-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMUPhotoView.m
2168 lines (1783 loc) · 70.1 KB
/
MUPhotoView.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// MUPhotoView
//
// Copyright (c) 2006 Blake Seely
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
// OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// * You include a link to http://www.blakeseely.com in your final product.
//
// Version History:
//
// Version 1.0 - April 17, 2006 - Initial Release
// Version 1.1 - April 29, 2006 - Photo removal support, Added support for reduced-size drawing during live resize
// Version 1.2 - September 24, 2006 - Updated selection behavior, Changed to MIT license, Fixed issue where no images would show, fixed autoscroll
// Modified for the iMedia project http://imedia.karelia.com/
#import "MUPhotoView.h"
NSString *ShowCaptionChangedNotification = @"ShowCaptionChangedNotification";
@implementation MUPhotoView
#pragma mark -
// Initializers and Dealloc
#pragma mark Initializers and Dealloc
+ (void)initialize
{
if ( self == [MUPhotoView class] )
{
// Only do some work when not called because one of our subclasses does not implement +initialize
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDictionary *defaultsBase = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat:75.0], @"MUPhotoSize", nil];
[defaults registerDefaults:defaultsBase];
[self exposeBinding:@"photosArray"];
[self exposeBinding:@"selectedPhotoIndexes"];
[self exposeBinding:@"backgroundColor"];
[self exposeBinding:@"photoSize"];
[self exposeBinding:@"useShadowBorder"];
[self exposeBinding:@"useOutlineBorder"];
[self exposeBinding:@"useShadowSelection"];
[self exposeBinding:@"useOutlineSelection"];
[self setKeys:[NSArray arrayWithObject:@"backgroundColor"] triggerChangeNotificationsForDependentKey:@"shadowBoxColor"];
[pool release];
}
}
- (id)initWithFrame:(NSRect)frameRect
{
if ((self = [super initWithFrame:frameRect]) != nil) {
delegate = nil;
sendsLiveSelectionUpdates = NO;
useHighQualityResize = NO;
photosArray = nil;
photosFastArray = nil;
selectedPhotoIndexes = nil;
dragSelectedPhotoIndexes = [[NSMutableIndexSet alloc] init];
[self setBackgroundColor:[NSColor grayColor]];
useShadowBorder = YES;
useOutlineBorder = YES;
borderShadow = [[NSShadow alloc] init];
[borderShadow setShadowColor:[NSColor colorWithCalibratedWhite:0. alpha:.5]];
[borderShadow setShadowOffset:NSMakeSize(0.0, -2.0)];
[borderShadow setShadowBlurRadius:4.0];
noShadow = [[NSShadow alloc] init];
[noShadow setShadowOffset:NSMakeSize(0,0)];
[noShadow setShadowBlurRadius:0.0];
[self setBorderOutlineColor:[NSColor colorWithCalibratedWhite:0.5 alpha:1.0]];
useShadowSelection = NO;
useBorderSelection = YES;
[self setSelectionBorderColor:[NSColor selectedControlColor]];
selectionBorderWidth = 3.0;
[self setShadowBoxColor:[NSColor colorWithCalibratedWhite:0.0 alpha:0.5]];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
photoSize = [defaults floatForKey:@"MUPhotoSize"];
photoVerticalSpacing = 25.0;
photoHorizontalSpacing = 25.0;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(resetCaptionShowing:)
name:ShowCaptionChangedNotification
object:nil];
photoResizeTimer = nil;
photoResizeTime = [[NSDate date] retain];
isDonePhotoResizing = YES;
}
return self;
}
- (void)dealloc
{
[dragSelectedPhotoIndexes release], dragSelectedPhotoIndexes = nil;
[photoResizeTime release], photoResizeTime = nil;
[borderShadow release], borderShadow = nil;
[noShadow release], noShadow = nil;
[self setBorderOutlineColor:nil];
[self setSelectionBorderColor:nil];
[self setShadowBoxColor:nil];
[self setBackgroundColor:nil];
[self setPhotosArray:nil];
[self setSelectedPhotoIndexes:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
#pragma mark -
// Drawing Methods
#pragma mark Drawing Methods
- (BOOL)isOpaque
{
return YES;
}
- (BOOL)isFlipped
{
return YES;
}
static NSDictionary *sTitleAttributes = nil;
- (void)drawRect:(NSRect)rect
{
[self removeAllToolTips];
// draw the background color
[[self backgroundColor] set];
[NSBezierPath fillRect:rect];
// get the number of photos
unsigned photoCount = [self photoCount];
if (0 == photoCount)
return;
// update internal grid size, adjust height based on the new grid size
// because I may not find out that the photos array has changed until I draw and read the photos from the delegate, this call has to stay here
[self updateGridAndFrame];
// any other setup
if (useHighQualityResize) {
[[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
}
/**** BEGIN Drawing Photos ****/
NSRange rangeToDraw = [self photoIndexRangeForRect:rect]; // adjusts for photoCount if the rect goes outside my range
unsigned thisPhotoIndex;
unsigned lastIndex = rangeToDraw.location + rangeToDraw.length;
// Our version of photoIndexRangeForRect: returns one item more in the range than the MUPhotoView 1.2 version. Hence we also
// must do one less iteration so here we do < instead of <=
for (thisPhotoIndex = rangeToDraw.location; thisPhotoIndex < lastIndex; thisPhotoIndex++) {
// Get the image at the current index - a gray bezier anywhere in the view means it asked for an image, but got nil for that index
BOOL allowShadows = YES;
NSImage* photo = [self currentDisplayImageAtIndex:thisPhotoIndex allowsShadows:&allowShadows];
// set it to draw correctly in a flipped view (will restore it after drawing)
BOOL isFlipped = [photo isFlipped];
[photo setFlipped:YES];
NSString* title = [self titleAtIndex:thisPhotoIndex];
NSRect gridRect = NSZeroRect;
NSRect photoRect = NSZeroRect;
NSRect titleRect = NSZeroRect;
// Note this will automatically cause the photo to scale as necessary
[self getDrawingRectsAtIndex:thisPhotoIndex withPhoto:photo withTitle:title outGridRect:&gridRect outPhotoRect:&photoRect outTitleRect:&titleRect];
//**** BEGIN Background Drawing - any drawing that technically goes under the image ****/
#if 0 // Debugging Aid - Enable this to fill each gridRect with a different gray
[[NSColor colorWithCalibratedWhite:(float)(thisPhotoIndex % 5) / 4.0 alpha:0.8] set];
[NSBezierPath fillRect:gridRect];
#endif
// kSelectionStyleShadowBox draws a semi-transparent rounded rect behind/around the image
if ([self isPhotoSelectedAtIndex:thisPhotoIndex] && [self useShadowSelection]) {
NSBezierPath *shadowBoxPath = [self shadowBoxPathForRect:gridRect];
[shadowBoxColor set];
[shadowBoxPath fill];
}
//**** END Background Drawing ****/
// kBorderStyleShadow - set the appropriate shadow
// Don't draw the shadow if we have a border and the item is selected, or if shadows are disabled for this image
if ([self useShadowBorder] && (allowShadows == YES) &&
([self useBorderSelection] == NO || [[self selectionIndexes] containsIndex:thisPhotoIndex] == NO)) {
[borderShadow set];
}
// draw the current photo
NSRect imageRect = NSMakeRect(0, 0, [photo size].width, [photo size].height);
[photo drawInRect:photoRect fromRect:imageRect operation:NSCompositeSourceOver fraction:1.0];
// register the tooltip area
[self addToolTipRect:photoRect owner:self userData:nil];
// restore the photo's flipped status
[photo setFlipped:isFlipped];
// kBorderStyleShadow - remove the shadow after drawing the image
[noShadow set];
//**** BEGIN Foreground Drawing - includes outline borders, selection rectangles ****/
if ([self isPhotoSelectedAtIndex:thisPhotoIndex] && [self useBorderSelection]) {
NSBezierPath *selectionBorder = [NSBezierPath bezierPathWithRect:NSInsetRect(photoRect,-3.0,-3.0)];
[selectionBorder setLineWidth:[self selectionBorderWidth]];
[[self selectionBorderColor] set];
[selectionBorder stroke];
} else if ([self useOutlineBorder]) {
photoRect = NSInsetRect(photoRect,0.5,0.5); // line up the 1px border so it completely fills a single row of pixels
NSBezierPath *outlinePath = [NSBezierPath bezierPathWithRect:photoRect];
[outlinePath setLineWidth:1.0];
[borderOutlineColor set];
[outlinePath stroke];
}
//**** END Foreground Drawing ****//
// draw title
if (title)
{
// center rect
NSMutableString *s1 = [NSMutableString stringWithString:[title substringToIndex:[title length] / 2]];
NSMutableString *s2 = [NSMutableString stringWithString:[title substringFromIndex:[title length] / 2]];
NSSize titleSize = [self sizeOfTitleWithCurrentAttributes:title];
while (titleSize.width > NSWidth(titleRect))
{
[s1 deleteCharactersInRange:NSMakeRange([s1 length] - 1, 1)];
[s2 deleteCharactersInRange:NSMakeRange(0, 1)];
title = [NSString stringWithFormat:@"%@...%@", s1, s2];
titleSize = [title sizeWithAttributes:sTitleAttributes];
}
titleRect.origin.x = NSMidX(titleRect) - (titleSize.width / 2);
titleRect.size.width = titleSize.width;
[title drawInRect:titleRect withAttributes:sTitleAttributes];
}
}
//**** END Drawing Photos ****//
//**** BEGIN Selection Rectangle ****//
if (mouseDown) {
[noShadow set];
[[NSColor whiteColor] set];
float minX = (mouseDownPoint.x < mouseCurrentPoint.x) ? mouseDownPoint.x : mouseCurrentPoint.x;
float minY = (mouseDownPoint.y < mouseCurrentPoint.y) ? mouseDownPoint.y : mouseCurrentPoint.y;
float maxX = (mouseDownPoint.x > mouseCurrentPoint.x) ? mouseDownPoint.x : mouseCurrentPoint.x;
float maxY = (mouseDownPoint.y > mouseCurrentPoint.y) ? mouseDownPoint.y : mouseCurrentPoint.y;
NSRect selectionRectangle = NSMakeRect(minX,minY,maxX-minX,maxY-minY);
[NSBezierPath strokeRect:selectionRectangle];
[[NSColor colorWithDeviceRed:0.8 green:0.8 blue:0.8 alpha:0.5] set];
[NSBezierPath fillRect:selectionRectangle];
}
//**** END Selection Rectangle ****//
}
- (void)forceRedisplay
{
[self setNeedsDisplay:YES];
}
- (void)setNeedsDisplayInRect:(NSRect)invalidatedRect
{
// Make the view redraw some more pixels, to avoid the "disappearing shadows on scroll" problem
if ([[borderShadow shadowColor] alphaComponent]!=0.0) {
NSRect shadowRect = invalidatedRect;
shadowRect.origin.x += [borderShadow shadowOffset].width;
shadowRect.origin.y -= [borderShadow shadowOffset].height;
shadowRect = NSInsetRect(shadowRect, -[borderShadow shadowBlurRadius], -[borderShadow shadowBlurRadius]);
invalidatedRect = NSUnionRect(invalidatedRect, shadowRect);
}
[super setNeedsDisplayInRect:invalidatedRect];
}
- (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)userData
{
unsigned idx = [self photoIndexForPoint:point];
if (idx < [self photoCount])
{
return [delegate photoView:self tooltipForPhotoAtIndex:[self photoIndexForPoint:point]];
}
return nil;
}
#pragma mark -
// Delegate Accessors
#pragma mark Delegate Accessors
- (id)delegate
{
return delegate;
}
- (void)setDelegate:(id)del
{
[self willChangeValueForKey:@"delegate"];
delegate = del;
[self didChangeValueForKey:@"delegate"];
}
#pragma mark -
// Photos Methods
#pragma mark Photo Methods
- (NSArray *)photosArray
{
//NSLog(@"in -photosArray, returned photosArray = %@", photosArray);
return photosArray;
}
- (void)setPhotosArray:(NSArray *)aPhotosArray
{
//NSLog(@"in -setPhotosArray:, old value of photosArray: %@, changed to: %@", photosArray, aPhotosArray);
if (photosArray != aPhotosArray) {
[photosArray release];
[self willChangeValueForKey:@"photosArray"];
photosArray = [aPhotosArray mutableCopy];
[self didChangeValueForKey:@"photosArray"];
// update live resize array
if (nil != photosFastArray) {
[photosFastArray release];
}
photosFastArray = [[NSMutableArray alloc] initWithCapacity:[aPhotosArray count]];
unsigned i;
for (i = 0; i < [photosArray count]; i++)
{
[photosFastArray addObject:[NSNull null]];
}
// update internal grid size, adjust height based on the new grid size
[self scrollPoint:([self frame].origin)];
[self setNeedsDisplayInRect:[self visibleRect]];
}
}
#pragma mark -
// Selection Management
#pragma mark Selection Management
- (NSIndexSet *)selectedPhotoIndexes
{
//NSLog(@"in -selectedPhotoIndexes, returned selectedPhotoIndexes = %@", selectedPhotoIndexes);
return selectedPhotoIndexes;
}
- (void)setSelectedPhotoIndexes:(NSIndexSet *)aSelectedPhotoIndexes
{
//NSLog(@"in -setSelectedPhotoIndexes:, old value of selectedPhotoIndexes: %@, changed to: %@", selectedPhotoIndexes, aSelectedPhotoIndexes);
if ((selectedPhotoIndexes != aSelectedPhotoIndexes) && (![selectedPhotoIndexes isEqualToIndexSet:aSelectedPhotoIndexes])) {
// Set the selection and send KVO
[selectedPhotoIndexes release];
[self willChangeValueForKey:@"selectedPhotoIndexes"];
selectedPhotoIndexes = [aSelectedPhotoIndexes copy];
[self didChangeValueForKey:@"selectedPhotoIndexes"];
}
}
#pragma mark -
// Selection Style
#pragma mark Selection Style
- (BOOL)useBorderSelection
{
//NSLog(@"in -useBorderSelection, returned useBorderSelection = %@", useBorderSelection ? @"YES": @"NO");
return useBorderSelection;
}
- (void)setUseBorderSelection:(BOOL)flag
{
//NSLog(@"in -setUseBorderSelection, old value of useBorderSelection: %@, changed to: %@", (useBorderSelection ? @"YES": @"NO"), (flag ? @"YES": @"NO"));
[self willChangeValueForKey:@"useBorderSelection"];
useBorderSelection = flag;
[self didChangeValueForKey:@"useBorderSelection"];
[self setNeedsDisplayInRect:[self visibleRect]];
}
- (NSColor *)selectionBorderColor
{
//NSLog(@"in -selectionBorderColor, returned selectionBorderColor = %@", selectionBorderColor);
return selectionBorderColor;
}
- (void)setSelectionBorderColor:(NSColor *)aSelectionBorderColor
{
//NSLog(@"in -setSelectionBorderColor:, old value of selectionBorderColor: %@, changed to: %@", selectionBorderColor, aSelectionBorderColor);
if (selectionBorderColor != aSelectionBorderColor) {
[selectionBorderColor release];
[self willChangeValueForKey:@"selectionBorderColor"];
selectionBorderColor = [aSelectionBorderColor copy];
[self didChangeValueForKey:@"selectionBorderColor"];
}
}
- (BOOL)useShadowSelection
{
//NSLog(@"in -useShadowSelection, returned useShadowSelection = %@", useShadowSelection ? @"YES": @"NO");
return useShadowSelection;
}
- (void)setUseShadowSelection:(BOOL)flag
{
//NSLog(@"in -setUseShadowSelection, old value of useShadowSelection: %@, changed to: %@", (useShadowSelection ? @"YES": @"NO"), (flag ? @"YES": @"NO"));
[self willChangeValueForKey:@"useShadowSelection"];
useShadowSelection = flag;
[self willChangeValueForKey:@"useShadowSelection"];
[self setNeedsDisplayInRect:[self visibleRect]];
}
#pragma mark -
// Appearance
#pragma mark Appearance
- (BOOL)useShadowBorder
{
//NSLog(@"in -useShadowBorder, returned useShadowBorder = %@", useShadowBorder ? @"YES": @"NO");
return useShadowBorder;
}
- (void)setUseShadowBorder:(BOOL)flag
{
//NSLog(@"in -setUseShadowBorder, old value of useShadowBorder: %@, changed to: %@", (useShadowBorder ? @"YES": @"NO"), (flag ? @"YES": @"NO"));
[self willChangeValueForKey:@"useShadowBorder"];
useShadowBorder = flag;
[self didChangeValueForKey:@"useShadowBorder"];
[self setNeedsDisplayInRect:[self visibleRect]];
}
- (BOOL)useOutlineBorder
{
//NSLog(@"in -useOutlineBorder, returned useOutlineBorder = %@", useOutlineBorder ? @"YES": @"NO");
return useOutlineBorder;
}
- (void)setUseOutlineBorder:(BOOL)flag
{
//NSLog(@"in -setUseOutlineBorder, old value of useOutlineBorder: %@, changed to: %@", (useOutlineBorder ? @"YES": @"NO"), (flag ? @"YES": @"NO"));
[self willChangeValueForKey:@"useOutlineBorder"];
useOutlineBorder = flag;
[self didChangeValueForKey:@"useOutlineBorder"];
[self setNeedsDisplayInRect:[self visibleRect]];
}
- (NSColor *)backgroundColor
{
//NSLog(@"in -backgroundColor, returned backgroundColor = %@", backgroundColor);
return [[backgroundColor retain] autorelease];
}
- (void)setBackgroundColor:(NSColor *)aBackgroundColor
{
//NSLog(@"in -setBackgroundColor:, old value of backgroundColor: %@, changed to: %@", backgroundColor, aBackgroundColor);
if (backgroundColor != aBackgroundColor) {
[backgroundColor release];
[self willChangeValueForKey:@"backgroundColor"];
backgroundColor = [aBackgroundColor copy];
[self didChangeValueForKey:@"backgroundColor"];
// adjust the shadow box selection color based on the background color. values closer to white use black and vice versa
NSColor *newShadowBoxColor;
CGFloat whiteValue = 0.0;
if ([backgroundColor numberOfComponents] >= 3) {
CGFloat red, green, blue;
[backgroundColor getRed:&red green:&green blue:&blue alpha:NULL];
whiteValue = (red + green + blue) / 3;
} else if ([backgroundColor numberOfComponents] >= 1) {
[backgroundColor getWhite:&whiteValue alpha:NULL];
}
if (0.5 > whiteValue)
newShadowBoxColor = [NSColor colorWithDeviceWhite:1.0 alpha:0.5];
else
newShadowBoxColor = [NSColor colorWithDeviceWhite:0.0 alpha:0.5];
[self setShadowBoxColor:newShadowBoxColor];
}
}
- (BOOL)useHighQualityResize
{
return useHighQualityResize;
}
- (void)setUseHighQualityResize:(BOOL)flag
{
useHighQualityResize = flag;
}
- (BOOL)showCaptions
{
return showCaptions;
}
- (void)setShowCaptions:(BOOL)flag
{
showCaptions = flag;
}
- (void) resetCaptionShowing:(NSNotification *)notification
{
NSDictionary *ui = [notification userInfo];
BOOL flag = [[ui objectForKey:@"flag"] boolValue];
[self setShowCaptions:flag];
}
- (float)photoSize
{
//NSLog(@"in -photoSize, returned photoSize = %f", photoSize);
return photoSize;
}
- (void)setPhotoSize:(float)aPhotoSize
{
//NSLog(@"in -setPhotoSize, old value of photoSize: %f, changed to: %f", photoSize, aPhotoSize);
[self willChangeValueForKey:@"photoSize"];
photoSize = aPhotoSize;
[self didChangeValueForKey:@"photoSize"];
// update internal grid size, adjust height based on the new grid size
// to make sure the same photos stay in view, get a visible photos' index, then scroll to that photo after the update
NSRect visibleRect = [self visibleRect];
float heightRatio = visibleRect.origin.y / [self frame].size.height;
visibleRect.origin.y = heightRatio * [self frame].size.height;
[self scrollRectToVisible:visibleRect];
[self viewWillStartLiveResize];
[self setNeedsDisplayInRect:[self visibleRect]];
// update time for live resizing
if (nil != photoResizeTime) {
[photoResizeTime release];
photoResizeTime = nil;
}
isDonePhotoResizing = NO;
photoResizeTime = [[NSDate date] retain];
if (photoResizeTimer) {
[photoResizeTimer invalidate];
photoResizeTimer = nil;
}
// note that the timer retains the target
photoResizeTimer = [NSTimer scheduledTimerWithTimeInterval:0.5
target:self
selector:@selector(updatePhotoResizing)
userInfo:nil
repeats:YES];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setFloat:aPhotoSize forKey:@"MUPhotoSize"];
}
- (IBAction)takePhotoSizeFrom:(id)sender // allow hooking up to a slider
{
if ([sender respondsToSelector:@selector(doubleValue)])
{
mouseCurrentPoint = mouseDownPoint = NSZeroPoint;
[self setPhotoSize:[sender doubleValue]];
//fake a bounds resize notification
[[NSNotificationCenter defaultCenter] postNotificationName:NSViewFrameDidChangeNotification
object:self];
if ([[self selectionIndexes] count] > 0)
{
unsigned lastSelectedIndex = [[self selectionIndexes] lastIndex];
NSRect r = [self photoRectForIndex:lastSelectedIndex];
r.origin.y -= photoVerticalSpacing;
r.size.height += photoVerticalSpacing;
[self scrollRectToVisible:r];
}
}
}
#pragma mark -
// Don't Mess With Texas
#pragma mark Don't Mess With Texas
// haven't tested changing these behaviors yet - there's no reason they shouldn't work... but use at your own risk.
- (float)photoVerticalSpacing
{
//NSLog(@"in -photoVerticalSpacing, returned photoVerticalSpacing = %f", photoVerticalSpacing);
return photoVerticalSpacing;
}
- (void)setPhotoVerticalSpacing:(float)aPhotoVerticalSpacing
{
//NSLog(@"in -setPhotoVerticalSpacing, old value of photoVerticalSpacing: %f, changed to: %f", photoVerticalSpacing, aPhotoVerticalSpacing);
[self willChangeValueForKey:@"photoVerticalSpacing"];
photoVerticalSpacing = aPhotoVerticalSpacing;
[self didChangeValueForKey:@"photoVertificalSpacing"];
// update internal grid size, adjust height based on the new grid size
NSRect visibleRect = [self visibleRect];
float heightRatio = visibleRect.origin.y / [self frame].size.height;
visibleRect.origin.y = heightRatio * [self frame].size.height;
[self scrollRectToVisible:visibleRect];
[self setNeedsDisplayInRect:[self visibleRect]];
// update time for live resizing
if (nil != photoResizeTime) {
[photoResizeTime release];
photoResizeTime = nil;
}
isDonePhotoResizing = NO;
photoResizeTime = [[NSDate date] retain];
if (nil == photoResizeTimer) {
// the timer retains the target
photoResizeTimer = [NSTimer scheduledTimerWithTimeInterval:2.0
target:self
selector:@selector(updatePhotoResizing)
userInfo:nil
repeats:YES];
}
}
- (float)photoHorizontalSpacing
{
//NSLog(@"in -photoHorizontalSpacing, returned photoHorizontalSpacing = %f", photoHorizontalSpacing);
return photoHorizontalSpacing;
}
- (void)setPhotoHorizontalSpacing:(float)aPhotoHorizontalSpacing
{
//NSLog(@"in -setPhotoHorizontalSpacing, old value of photoHorizontalSpacing: %f, changed to: %f", photoHorizontalSpacing, aPhotoHorizontalSpacing);
[self willChangeValueForKey:@"photoHorizontalSpacing"];
photoHorizontalSpacing = aPhotoHorizontalSpacing;
[self didChangeValueForKey:@"photoHorizontalSpacing"];
// update internal grid size, adjust height based on the new grid size
NSRect visibleRect = [self visibleRect];
float heightRatio = visibleRect.origin.y / [self frame].size.height;
visibleRect.origin.y = heightRatio * [self frame].size.height;
[self scrollRectToVisible:visibleRect];
[self setNeedsDisplayInRect:[self visibleRect]];
// update time for live resizing
if (nil != photoResizeTime) {
[photoResizeTime release];
photoResizeTime = nil;
}
isDonePhotoResizing = NO;
photoResizeTime = [[NSDate date] retain];
if (nil == photoResizeTimer) {
// the timer retains the target
photoResizeTimer = [NSTimer scheduledTimerWithTimeInterval:2.0
target:self
selector:@selector(updatePhotoResizing)
userInfo:nil
repeats:YES];
}
}
- (NSColor *)borderOutlineColor
{
//NSLog(@"in -borderOutlineColor, returned borderOutlineColor = %@", borderOutlineColor);
return borderOutlineColor;
}
- (void)setBorderOutlineColor:(NSColor *)aBorderOutlineColor
{
//NSLog(@"in -setBorderOutlineColor:, old value of borderOutlineColor: %@, changed to: %@", borderOutlineColor, aBorderOutlineColor);
if (borderOutlineColor != aBorderOutlineColor) {
[borderOutlineColor release];
[self willChangeValueForKey:@"borderOutlineColor"];
borderOutlineColor = [aBorderOutlineColor copy];
[self didChangeValueForKey:@"borderOutlineColor"];
[self setNeedsDisplayInRect:[self visibleRect]];
}
}
- (NSColor *)shadowBoxColor
{
//NSLog(@"in -shadowBoxColor, returned shadowBoxColor = %@", shadowBoxColor);
return shadowBoxColor;
}
- (void)setShadowBoxColor:(NSColor *)aShadowBoxColor
{
//NSLog(@"in -setShadowBoxColor:, old value of shadowBoxColor: %@, changed to: %@", shadowBoxColor, aShadowBoxColor);
if (shadowBoxColor != aShadowBoxColor) {
[shadowBoxColor release];
shadowBoxColor = [aShadowBoxColor copy];
[self setNeedsDisplayInRect:[self visibleRect]];
}
}
- (float)selectionBorderWidth
{
//NSLog(@"in -selectionBorderWidth, returned selectionBorderWidth = %f", selectionBorderWidth);
return selectionBorderWidth;
}
- (void)setSelectionBorderWidth:(float)aSelectionBorderWidth
{
//NSLog(@"in -setSelectionBorderWidth, old value of selectionBorderWidth: %f, changed to: %f", selectionBorderWidth, aSelectionBorderWidth);
selectionBorderWidth = aSelectionBorderWidth;
}
#pragma mark -
// Mouse Event Methods
#pragma mark Mouse Event Methods
- (void) mouseDown:(NSEvent *) event
{
mouseDown = YES;
mouseDownPoint = [self convertPoint:[event locationInWindow] fromView:nil];
mouseCurrentPoint = mouseDownPoint;
unsigned clickedIndex = [self photoIndexForPoint:mouseDownPoint];
NSRect photoRect = [self photoRectForIndex:clickedIndex];
unsigned int flags = [event modifierFlags];
NSMutableIndexSet* indexes = [[self selectionIndexes] mutableCopy];
BOOL imageHit = NSPointInRect(mouseDownPoint, photoRect);
if (imageHit) {
if (flags & NSCommandKeyMask) {
// Flip current image selection state.
if ([indexes containsIndex:clickedIndex]) {
[indexes removeIndex:clickedIndex];
} else {
[indexes addIndex:clickedIndex];
}
} else {
if (flags & NSShiftKeyMask) {
// Add range to selection.
if ([indexes count] == 0) {
[indexes addIndex:clickedIndex];
} else {
unsigned int origin = (clickedIndex < [indexes lastIndex]) ? clickedIndex :[indexes lastIndex];
unsigned int length = (clickedIndex < [indexes lastIndex]) ? [indexes lastIndex] - clickedIndex : clickedIndex - [indexes lastIndex];
length++;
[indexes addIndexesInRange:NSMakeRange(origin, length)];
}
} else {
if (![self isPhotoSelectedAtIndex:clickedIndex]) {
// Photo selection without modifiers.
[indexes removeAllIndexes];
[indexes addIndex:clickedIndex];
}
}
}
potentialDragDrop = YES;
} else {
if ((flags & NSShiftKeyMask) == 0) {
[indexes removeAllIndexes];
}
potentialDragDrop = NO;
}
[self setSelectionIndexes:indexes];
[indexes release];
}
- (void)mouseDragged:(NSEvent *)event
{
if (0 == columns) return;
mouseCurrentPoint = [self convertPoint:[event locationInWindow] fromView:nil];
// if the mouse has moved less than 5px in either direction, don't register the drag yet
float xFromStart = fabs((mouseDownPoint.x - mouseCurrentPoint.x));
float yFromStart = fabs((mouseDownPoint.y - mouseCurrentPoint.y));
if ((xFromStart < 5) && (yFromStart < 5)) {
return;
} else if (potentialDragDrop && (nil != delegate)) {
// create a drag image
unsigned clickedIndex = [self photoIndexForPoint:mouseDownPoint];
NSImage *clickedImage = [self photoAtIndex:clickedIndex];
BOOL flipped = [clickedImage isFlipped];
[clickedImage setFlipped:YES];
NSSize scaledSize = [self scaledPhotoSizeForSize:[clickedImage size]];
if (nil == clickedImage) { // creates a red image, which should let the user/developer know something is wrong
clickedImage = [[[NSImage alloc] initWithSize:NSMakeSize(photoSize,photoSize)] autorelease];
[clickedImage lockFocus];
[[NSColor redColor] set];
[NSBezierPath fillRect:NSMakeRect(0,0,photoSize,photoSize)];
[clickedImage unlockFocus];
}
NSImage *dragImage = [[NSImage alloc] initWithSize:scaledSize];
// draw the drag image as a semi-transparent copy of the image the user dragged, and optionally a red badge indicating the number of photos
[dragImage lockFocus];
[clickedImage drawInRect:NSMakeRect(0,0,scaledSize.width,scaledSize.height) fromRect:NSMakeRect(0,0,[clickedImage size].width,[clickedImage size].height) operation:NSCompositeCopy fraction:0.7];
[dragImage unlockFocus];
[clickedImage setFlipped:flipped];
// if there's more than one image, put a badge on the photo
if ([[self selectionIndexes] count] > 1) {
NSMutableDictionary *attributes = [[NSMutableDictionary alloc] init];
[attributes setObject:[NSColor whiteColor] forKey:NSForegroundColorAttributeName];
[attributes setObject:[NSFont fontWithName:@"Helvetica" size:14] forKey:NSFontAttributeName];
NSAttributedString *badgeString = [[NSAttributedString alloc] initWithString:[[NSNumber numberWithInt:[[self selectionIndexes] count]] stringValue] attributes:attributes];
NSSize stringSize = [badgeString size];
int diameter = stringSize.width;
if (stringSize.height > diameter) diameter = stringSize.height;
diameter += 5;
// calculate the badge circle
int maxY = [dragImage size].height - 5;
int maxX = [dragImage size].width - 5;
int minY = maxY - diameter;
int minX = maxX - diameter;
NSBezierPath *circle = [NSBezierPath bezierPathWithOvalInRect:NSMakeRect(minX,minY,maxX-minX,maxY-minY)];
// draw the string
NSPoint point;
point.x = maxX - ((maxX - minX) / 2) - 1 - (stringSize.width / 2);
point.y = maxY - diameter + (stringSize.height / 2) - 6;
NSAffineTransform *t = [NSAffineTransform transform];
[t translateXBy:0 yBy:maxY];
[t scaleXBy:1 yBy:-1];
[dragImage lockFocus];
[t concat];
[[NSColor colorWithDeviceRed:1 green:0.1 blue:0.1 alpha:0.7] set];
[circle fill];
[badgeString drawAtPoint:point];
[t invert];
[t concat];
[dragImage unlockFocus];
[badgeString release];
[attributes release];
}
[dragImage setFlipped:YES];
// get the pasteboard and register the returned types with delegate as the owner
NSPasteboard *pb = [NSPasteboard pasteboardWithName:NSDragPboard];
[pb declareTypes:[NSArray array] owner:nil]; // clear the pasteboard
[delegate photoView:self fillPasteboardForDrag:pb];
// place the cursor in the center of the drag image
NSPoint p = [self convertPoint:[event locationInWindow] fromView:nil];
NSSize imageSize = [dragImage size];
p.x = p.x - imageSize.width / 2;
p.y = p.y + imageSize.height / 2;
[self dragImage:dragImage at:p offset:NSZeroSize event:event pasteboard:pb source:self slideBack:YES];
[dragImage release];
} else {
// adjust the mouse current point so that it's not outside the frame
NSRect frameRect = [self frame];
if (mouseCurrentPoint.x < NSMinX(frameRect))
mouseCurrentPoint.x = NSMinX(frameRect);
if (mouseCurrentPoint.x > NSMaxX(frameRect))
mouseCurrentPoint.x = NSMaxX(frameRect);
if (mouseCurrentPoint.y < NSMinY(frameRect))
mouseCurrentPoint.y = NSMinY(frameRect);
if (mouseCurrentPoint.y > NSMaxY(frameRect))
mouseCurrentPoint.y = NSMaxY(frameRect);
// determine the rect for the current drag area
float minX, maxX, minY, maxY;
minX = (mouseCurrentPoint.x < mouseDownPoint.x) ? mouseCurrentPoint.x : mouseDownPoint.x;
minY = (mouseCurrentPoint.y < mouseDownPoint.y) ? mouseCurrentPoint.y : mouseDownPoint.y;
maxX = (mouseCurrentPoint.x > mouseDownPoint.x) ? mouseCurrentPoint.x : mouseDownPoint.x;
maxY = (mouseCurrentPoint.y > mouseDownPoint.y) ? mouseCurrentPoint.y : mouseDownPoint.y;
if (maxY > NSMaxY(frameRect))
maxY = NSMaxY(frameRect);
if (maxX > NSMaxX(frameRect))
maxX = NSMaxX(frameRect);
NSRect selectionRect = NSMakeRect(minX,minY,maxX-minX,maxY-minY);
unsigned minIndex = [self photoIndexForPoint:NSMakePoint(minX, minY)];
unsigned xRun = [self photoIndexForPoint:NSMakePoint(maxX, minY)] - minIndex + 1;
unsigned yRun = [self photoIndexForPoint:NSMakePoint(minX, maxY)] - minIndex + 1;
unsigned selectedRows = (yRun / columns);
// Save the current selection (if any), then populate the drag indexes
// this allows us to shift band select to add to the current selection.
[dragSelectedPhotoIndexes removeAllIndexes];
[dragSelectedPhotoIndexes addIndexes:[self selectionIndexes]];
// add indexes in the drag rectangle
unsigned i;
for (i = 0; i <= selectedRows; i++) {
unsigned rowStartIndex = (i * columns) + minIndex;
unsigned j;
for (j = rowStartIndex; j < (rowStartIndex + xRun); j++) {
if (NSIntersectsRect([self photoRectForIndex:j],selectionRect))
[dragSelectedPhotoIndexes addIndex:j];
}
}
// if requested, set the selection. this could cause a rapid series of KVO notifications, so if this is false, the view tracks
// the selection internally, but doesn't pass it to the bindings or the delegates until the drag is over.
// This will cause an appropriate redraw.
if (sendsLiveSelectionUpdates)
{
[self setSelectionIndexes:dragSelectedPhotoIndexes];
}
// autoscrolling
if (autoscrollTimer == nil) {
// the timer retains the target: must invalidate or dealloc wont be called on the photo view!
autoscrollTimer = [NSTimer scheduledTimerWithTimeInterval:0.2
target:self
selector:@selector(autoscroll)
userInfo:nil
repeats:YES];
}
[[self superview] autoscroll:event];
[self setNeedsDisplayInRect:[self visibleRect]];
}
}
- (void)mouseUp:(NSEvent *)event
{
// Double-click Handling
if ([event clickCount] == 2) {
// There could be more than one selected photo. In that case, call the delegates doubleClickOnPhotoAtIndex routine for
// each selected photo.
NSUInteger selectedIndex = [[self selectionIndexes] firstIndex];
while (selectedIndex != NSNotFound) {
[delegate photoView:self doubleClickOnPhotoAtIndex:selectedIndex withFrame:[self photoRectForIndex:selectedIndex]];
selectedIndex = [[self selectionIndexes] indexGreaterThanIndex:selectedIndex];
}
}
else if (0 < [dragSelectedPhotoIndexes count]) { // finishing a drag selection
// move the drag indexes into the main selection indexes - firing off KVO messages or delegate messages
[self setSelectionIndexes:dragSelectedPhotoIndexes];
[dragSelectedPhotoIndexes removeAllIndexes];
}
if (autoscrollTimer != nil) {
[autoscrollTimer invalidate];
autoscrollTimer = nil;
}
mouseDown = NO;
mouseCurrentPoint = mouseDownPoint = NSZeroPoint;
[self setNeedsDisplayInRect:[self visibleRect]];
}
- (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal
{
if (nil != delegate)
return [delegate photoView:self draggingSourceOperationMaskForLocal:isLocal];
else