-
Notifications
You must be signed in to change notification settings - Fork 28
/
SlideshowWindow.m
1421 lines (1301 loc) · 43.8 KB
/
SlideshowWindow.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
//Copyright 2005-2023 Dominic Yu. Some rights reserved.
//This work is licensed under the Creative Commons
//Attribution-NonCommercial-ShareAlike License. To view a copy of this
//license, visit http://creativecommons.org/licenses/by-nc-sa/2.0/ or send
//a letter to Creative Commons, 559 Nathan Abbott Way, Stanford,
//California 94305, USA.
#import "DYJpegtran.h"
#import "DYExiftags.h"
#import "SlideshowWindow.h"
#import "DYCarbonGoodies.h"
#import "CreeveyController.h"
#import "DYRandomizableArray.h"
#import "DYFileWatcher.h"
#import "NSMutableArray+DYMovable.h"
static BOOL UsingMagicMouse(NSEvent *e) {
return e.phase != NSEventPhaseNone || e.momentumPhase != NSEventPhaseNone;
}
@interface SlideshowWindow () <DYFileWatcherDelegate>
@property (nonatomic, copy) NSComparator comparator;
- (void)jump:(NSInteger)n;
- (void)jumpTo:(NSUInteger)n;
- (void)setTimer:(NSTimeInterval)s;
- (void)runTimer;
- (void)killTimer;
- (void)updateInfoFld;
- (void)updateExifFld;
- (void)saveZoomInfo;
// cat methods
- (void)displayCats;
- (void)assignCat:(short int)n toggle:(BOOL)toggle;
@end
@implementation SlideshowWindow
{
NSMutableSet * __strong *cats;
DYImageView *imgView;
NSTextField *infoFld, *catsFld; BOOL hideInfoFld, moreExif;
NSTextView *exifFld;
DYImageCache *imgCache;
BOOL timerPaused;
NSTimer *autoTimer;
NSMutableDictionary *rotations, *zooms, *flips;
NSString *basePath;
NSScreen *oldScreen;
NSUInteger currentIndex;
NSUInteger lastIndex; // for outside access to last slide shown
NSTextView *helpFld;
NSImageView *loopImageView;
BOOL loopMode, randomMode;
unsigned char keyIsRepeating;
BOOL mouseDragged;
DYRandomizableArray<NSString *> *filenames;
NSOperationQueue *_upcomingQueue;
DYFileWatcher *_fileWatcher;
_Atomic BOOL _stopLoading;
unsigned short int _sortType;
}
@synthesize autoRotate, autoadvanceTime = timerIntvl;
+ (void)initialize {
if (self != [SlideshowWindow class]) return;
[NSUserDefaults.standardUserDefaults registerDefaults:@{@"DYSlideshowWindowVisibleFields": @0}];
}
#define MAX_CACHED 15
// MAX_CACHED must be bigger than the number of items you plan to have cached!
#define MAX_REPEATING_CACHED 6
// when key is held down, max to cache before skipping over
- (instancetype)initWithContentRect:(NSRect)r styleMask:(NSWindowStyleMask)m backing:(NSBackingStoreType)b defer:(BOOL)d {
// full screen window, force it to be NSBorderlessWindowMask
if (self = [super initWithContentRect:r styleMask:NSWindowStyleMaskBorderless backing:b defer:d]) {
filenames = [[DYRandomizableArray alloc] init];
rotations = [[NSMutableDictionary alloc] init];
flips = [[NSMutableDictionary alloc] init];
zooms = [[NSMutableDictionary alloc] init];
imgCache = [[DYImageCache alloc] initWithCapacity:MAX_CACHED];
imgCache.rotatable = YES;
_upcomingQueue = [[NSOperationQueue alloc] init];
_fileWatcher = [[DYFileWatcher alloc] initWithDelegate:self];
self.backgroundColor = NSColor.blackColor;
self.opaque = NO;
_fullscreenMode = YES; // set this to prevent autosaving the frame from the nib
self.collectionBehavior = NSWindowCollectionBehaviorParticipatesInCycle|NSWindowCollectionBehaviorFullScreenNone|NSWindowCollectionBehaviorMoveToActiveSpace;
// *** Unfortunately the menubar doesn't seem to show up on the second screen... Eventually we'll want to switch to use NSView's enterFullScreenMode:withOptions:
currentIndex = NSNotFound;
}
return self;
}
- (void)awakeFromNib {
imgView = [[DYImageView alloc] initWithFrame:NSZeroRect];
[self.contentView addSubview:imgView];
imgView.frame = self.contentView.frame;
imgView.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
infoFld = [[NSTextField alloc] initWithFrame:NSMakeRect(0,0,360,20)];
[imgView addSubview:infoFld];
infoFld.autoresizingMask = NSViewMaxXMargin|NSViewMaxYMargin;
infoFld.backgroundColor = NSColor.grayColor;
infoFld.bezeled = NO;
infoFld.editable = NO;
catsFld = [[NSTextField alloc] initWithFrame:NSMakeRect(0,imgView.bounds.size.height-20,300,20)];
[imgView addSubview:catsFld];
catsFld.autoresizingMask = NSViewMaxXMargin|NSViewMinYMargin;
catsFld.backgroundColor = NSColor.grayColor;
catsFld.bezeled = NO;
catsFld.editable = NO; // **
catsFld.hidden = YES;
NSSize s = imgView.bounds.size;
NSScrollView *sv = [[NSScrollView alloc] initWithFrame:NSMakeRect(s.width-360,0,360,s.height-20)];
[imgView addSubview:sv];
sv.autoresizingMask = NSViewHeightSizable | NSViewMinXMargin;
exifFld = [[NSTextView alloc] initWithFrame:NSMakeRect(0,0,sv.contentSize.width,20)];
sv.documentView = exifFld;
exifFld.autoresizingMask = NSViewHeightSizable | NSViewWidthSizable | NSViewMinXMargin;
sv.drawsBackground = NO;
sv.hasVerticalScroller = YES;
sv.verticalScroller = [[NSScroller alloc] init];
sv.verticalScroller.controlSize = NSControlSizeSmall;
sv.autohidesScrollers = YES;
//[exifFld setEditable:NO];
exifFld.drawsBackground = NO;
exifFld.selectable = NO;
//[exifFld setVerticallyResizable:NO];
sv.hidden = YES;
switch ([NSUserDefaults.standardUserDefaults integerForKey:@"DYSlideshowWindowVisibleFields"]) {
case 0:
hideInfoFld = YES;
break;
case 2:
sv.hidden = NO;
break;
default:
break;
}
}
- (void)setFullscreenMode:(BOOL)b {
_fullscreenMode = b;
if (b) {
self.styleMask = NSWindowStyleMaskBorderless;
self.collectionBehavior = NSWindowCollectionBehaviorParticipatesInCycle|NSWindowCollectionBehaviorFullScreenNone|NSWindowCollectionBehaviorMoveToActiveSpace;
} else {
self.styleMask = NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable;
self.collectionBehavior = NSWindowCollectionBehaviorParticipatesInCycle|NSWindowCollectionBehaviorFullScreenNone|NSWindowCollectionBehaviorMoveToActiveSpace;
}
if (self.visible)
[self configureScreen];
}
- (void)setAutoRotate:(BOOL)b {
if (b == autoRotate) return;
autoRotate = b;
[rotations removeAllObjects];
[flips removeAllObjects];
if (currentIndex != NSNotFound) {
[self displayImage];
}
}
- (void)setCats:(NSMutableSet * __strong *)newCats {
cats = newCats;
}
// must override this for borderless windows
- (BOOL)canBecomeKeyWindow { return YES; }
- (BOOL)canBecomeMainWindow { return YES; }
#pragma mark start/end stuff
- (void)setFilenames:(NSArray *)files basePath:(NSString *)s wantsSubfolders:(BOOL)b comparator:(NSComparator)block sortOrder:(short int)sortOrder {
[self setFilenames:files basePath:s comparator:block sortOrder:sortOrder];
_fileWatcher.wantsSubfolders = b;
[_fileWatcher watchDirectory:s];
}
- (void)setFilenames:(NSArray *)files basePath:(NSString *)s comparator:(NSComparator)block sortOrder:(short int)sortOrder {
if (currentIndex != NSNotFound)
[self cleanUp];
if (s != basePath) {
if ([s characterAtIndex:s.length-1] != '/')
basePath = [s stringByAppendingString:@"/"];
else
basePath = [s copy];
}
[filenames setArray:files];
self.comparator = block;
_sortType = abs(sortOrder);
}
- (void)loadFilenamesFromPath:(NSString *)s fullScreen:(BOOL)fullScreen wantsSubfolders:(BOOL)b comparator:(NSComparator)block sortOrder:(short int)sortOrder {
static dispatch_queue_t _loadQueue;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_loadQueue = dispatch_queue_create("phoenixslides.slideshow.load", NULL);
});
self.fullscreenMode = fullScreen;
[self configureScreen];
currentIndex = NSNotFound;
imgView.image = nil;
self.title = NSProcessInfo.processInfo.processName;
infoFld.hidden = NO;
dispatch_async(dispatch_get_main_queue(), ^{
[self makeKeyAndOrderFront:nil];
});
self.comparator = block;
_sortType = abs(sortOrder);
_stopLoading = YES;
static _Atomic uint64_t blockTime;
uint64_t timeStamp = blockTime = mach_absolute_time();
dispatch_async(_loadQueue, ^{
if (timeStamp == blockTime)
[self loadImages:s subfolders:b];
});
}
- (NSString *)currentShortFilename {
NSString *s = filenames[currentIndex];
return s.length <= basePath.length ? s : [s substringFromIndex:basePath.length];
}
- (void)configureScreen // or rather, configure the window *for* the screen
{
NSScreen *myScreen = self.visible ? self.screen : NSScreen.mainScreen;
NSRect screenRect = myScreen.frame;
if (_fullscreenMode) {
NSRect boundingRect = screenRect;
if (@available(macOS 12.0, *))
if (![NSUserDefaults.standardUserDefaults boolForKey:@"pretendNotchIsntThere"])
boundingRect.size.height -= myScreen.safeAreaInsets.top;
[self setFrame:screenRect display:NO];
boundingRect.origin = imgView.frame.origin;
imgView.frame = boundingRect;
} else {
NSString *v = [NSUserDefaults.standardUserDefaults objectForKey:@"DYSlideshowWindowFrame"];
NSRect r;
if (v) {
r = NSRectFromString(v);
} else {
// if no saved frame, put it in the top left of the screen
r = screenRect;
r.size.width = r.size.width/2;
r.size.height = r.size.height/2;
r.origin.y = screenRect.size.height;
}
[self setFrame:r display:NO];
imgView.frame = self.contentLayoutRect;
}
}
- (void)configureBacking {
// this should only be called when the window is visible (when the backing scale factor has been updated)
NSScreen *screen = self.screen;
NSSize boundingSize = screen.frame.size;
if (@available(macOS 12.0, *))
boundingSize.height -= screen.safeAreaInsets.top;
NSSize backingSize = [imgView convertSizeToBacking:boundingSize];
NSSize oldSize = imgCache.boundingSize;
if (oldSize.width < backingSize.width || oldSize.height < backingSize.height)
[imgCache removeAllImages];
imgCache.boundingSize = backingSize;
oldScreen = screen;
}
- (void)resetScreen
{
if ([oldScreen.deviceDescription[@"NSScreenNumber"] isNotEqualTo:self.screen.deviceDescription[@"NSScreenNumber"]]) {
[self configureScreen];
[self displayImage];
}
}
- (void)cleanUp {
[_fileWatcher stop];
lastIndex = currentIndex;
if (currentIndex != NSNotFound) {
[self saveZoomInfo];
currentIndex = NSNotFound;
}
_stopLoading = YES;
[self killTimer];
[imgCache abortCaching];
[self.undoManager removeAllActions];
// this is a half-hearted attempt to clean up. Really we just rely on the countLimit on the cache
NSUInteger n = MIN(filenames.count, MAX_CACHED);
for (NSUInteger i=0; i<n; ++i) {
[imgCache endAccess:filenames[i]];
}
}
- (void)endSlideshow {
[self orderOut:nil];
}
- (void)orderOut:(id)sender {
[self cleanUp];
if (!_fullscreenMode)
[NSUserDefaults.standardUserDefaults setObject:NSStringFromRect(self.frame) forKey:@"DYSlideshowWindowFrame"];
[super orderOut:sender];
}
- (void)startSlideshow {
[self startSlideshowAtIndex:NSNotFound]; // to distinguish from 0, for random mode
}
- (void)startSlideshowAtIndex:(NSUInteger)startIndex {
if (filenames.count == 0) {
NSBeep();
return;
}
if (!self.visible) {
[self configureScreen];
}
if (randomMode) {
[filenames randomizeStartingWithObjectAtIndex:startIndex];
startIndex = 0;
} else {
if (startIndex == NSNotFound) startIndex = 0;
}
currentIndex = startIndex;
[self setTimer:timerIntvl]; // reset the timer, in case running
if (helpFld) helpFld.hidden = YES;
exifFld.string = @"";
[imgCache beginCaching];
imgView.image = nil;
self.title = NSProcessInfo.processInfo.processName;
[self makeKeyAndOrderFront:nil];
[self configureBacking];
[self displayImage];
NSUserDefaults *u = NSUserDefaults.standardUserDefaults;
BOOL seenIntro = [u boolForKey:@"seenSlideshowIntro"];
if (!seenIntro) {
NSAlert *alert = [[NSAlert alloc] init];
alert.messageText = NSLocalizedString(@"Welcome to Phoenix Slides!",@"");
alert.informativeText = NSLocalizedString(@"Hit the 'h' key to see a list of keyboard shortcuts you can use during the slideshow.",@"");
[alert addButtonWithTitle:NSLocalizedString(@"Got It!", @"welcome alert button 1")];
[alert addButtonWithTitle:NSLocalizedString(@"Show Me", @"welcome alert button 2")];
if ([alert runModal] == NSAlertSecondButtonReturn)
[self toggleHelp];
[u setBool:YES forKey:@"seenSlideshowIntro"];
}
// ordering front seems to reset the cursor, so force it again
[imgView setCursor];
}
- (void)becomeMainWindow { // need this when switching apps
if (_fullscreenMode)
NSApp.presentationOptions = NSApplicationPresentationHideDock|NSApplicationPresentationAutoHideMenuBar;
[super becomeMainWindow];
}
- (void)resignMainWindow {
if (_fullscreenMode)
NSApp.presentationOptions = NSApplicationPresentationDefault;
[super resignMainWindow];
}
- (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)screen
{
// As of 10.15.1(?) when the menubar hides, the window will get moved up by the height of the menubar.
// This should be the correct fix for that.
if (_fullscreenMode)
return [super constrainFrameRect:self.screen.frame toScreen:screen];
return [super constrainFrameRect:frameRect toScreen:screen];
}
- (void)watcherFiles:(NSArray *)files deleted:(NSArray *)deleted {
if (currentIndex == NSNotFound) return;
BOOL needUpdate = NO;
BOOL sortByModTime = _sortType == 2;
for (NSString *s in files) {
if (!sortByModTime && [self.currentFile isEqualToString:s]) {
[self redisplayImage];
continue;
}
if (sortByModTime) {
// modification time has changed, so it needs to be re-sorted
NSUInteger idx = [filenames indexOfObject:s];
if (idx != NSNotFound)
[self removeImageForFile:s atIndex:idx];
}
NSUInteger insertIdx;
if (NSNotFound == [filenames indexOfObject:s usingComparator:self.comparator insertIndex:&insertIdx]) {
[filenames insertObject:s usingOrderedIndex:insertIdx atIndex:filenames.count]; // appends to end if in random mode
if (!randomMode && insertIdx <= currentIndex) {
currentIndex++;
}
needUpdate = YES;
}
// if the file is already in the list, we can ignore it
// since any cached image will be auto-invalidated when the slideshow gets to it
}
for (NSString *s in deleted) {
NSUInteger idx = (_sortType == 1) ? [filenames indexOfObject:s usingComparator:self.comparator] : [filenames indexOfObject:s];
if (idx != NSNotFound)
[self removeImageForFile:s atIndex:idx];
}
if (needUpdate)
[self updateForAddedFiles];
}
- (void)watcherRootChanged:(NSURL *)fileRef {
NSString *s = _fileWatcher.path, *newPath = fileRef.path;
if (newPath == nil) {
// directory no longer exists!
dispatch_async(dispatch_get_main_queue(), ^{
[self endSlideshow];
});
return;
}
basePath = newPath.length == 1 ? newPath : [newPath stringByAppendingString:@"/"];
[filenames changeBase:s toPath:newPath];
}
#pragma mark timer stuff
// setTimer
// sets the interval between slide show advancing.
// set to 0 to stop.
- (void)setTimer:(NSTimeInterval)s {
timerIntvl = s;
[self updateTimer];
}
- (void)updateTimer {
if (timerIntvl > 0.0)
[self runTimer];
else
[self killTimer];
}
- (void)runTimer {
[self killTimer]; // always remove the old timer
if (loopMode || currentIndex+1 < filenames.count) {
//NSLog(@"scheduling timer from %d", currentIndex);
autoTimer = [NSTimer
scheduledTimerWithTimeInterval:timerIntvl
target:self
selector:@selector(nextTimer:)
userInfo:nil repeats:NO];
autoTimer.tolerance = 0.2;
}
}
- (void)killTimer {
[autoTimer invalidate]; autoTimer = nil;
}
- (void)pauseTimer {
[self killTimer];
timerPaused = YES;
if (hideInfoFld) infoFld.hidden = NO;
[self updateInfoFld];
}
- (void)nextTimer:(NSTimer *)t {
//NSLog(@"timer fired!");
autoTimer = nil; // so another thread won't send a message to a stale timer obj
[self jump:1]; // works with loop mode
}
#pragma mark display stuff
- (float)calcZoom:(NSSize)sourceSize {
// calc here b/c larger images have already been cached & shrunk!
NSRect boundsRect = imgView.bounds;
int rotation = imgView.rotation;
if (rotation == 90 || rotation == -90) {
CGFloat tmp = boundsRect.size.width;
boundsRect.size.width = boundsRect.size.height;
boundsRect.size.height = tmp;
}
if (!imgView.scalesUp
&& sourceSize.width <= boundsRect.size.width
&& sourceSize.height <= boundsRect.size.height)
{
return 1;
} else {
float w_ratio, h_ratio;
w_ratio = boundsRect.size.width/sourceSize.width;
h_ratio = boundsRect.size.height/sourceSize.height;
return w_ratio < h_ratio ? w_ratio : h_ratio;
}
}
- (void)updateExifFld {
if (currentIndex >= filenames.count) return;
NSMutableAttributedString *attStr;
attStr = Fileinfo2EXIFString(filenames[currentIndex],
imgCache,moreExif);
NSRange r = NSMakeRange(0,attStr.length);
NSShadow *shdw = [[NSShadow alloc] init];
shdw.shadowColor = NSColor.blackColor;
shdw.shadowBlurRadius = 7; // 7 or 8 is good
[attStr addAttribute:NSShadowAttributeName
value:shdw
range:r];
[exifFld replaceCharactersInRange:NSMakeRange(0,exifFld.string.length)
withRTF:[attStr RTFFromRange:NSMakeRange(0,attStr.length)
documentAttributes:@{}]];
exifFld.textColor = NSColor.whiteColor;
}
- (void)updateInfoFldWithRotation:(int)r {
DYImageInfo *info = [imgCache infoForKey:filenames[currentIndex]];
if (info == nil) {
// avoid crash if user tries to rotate before the image has loaded
return;
}
id dir;
switch (r) {
case 90: dir = NSLocalizedString(@" left", @""); break;
case -90: dir = NSLocalizedString(@" right", @""); break;
default: dir = @"";
}
if (r < 0) r = -r;
float zoom = imgView.zoomMode ? imgView.zoomF : [self calcZoom:info->pixelSize];
infoFld.stringValue = [NSString stringWithFormat:@"[%lu/%lu] %@%@ - %@%@%@%@ %@",
currentIndex+1, (unsigned long)filenames.count,
_fullscreenMode ? [[self currentShortFilename] stringByAppendingString:@" - "] : @"",
FileSize2String(info->fileSize),
info.pixelSizeAsString,
(zoom != 1.0 || imgView.zoomMode) ? [NSString stringWithFormat:
@" @ %.0f%%", zoom*100] : @"",
imgView.imageFlipped ? NSLocalizedString(@" flipped", @"") : @"",
r ? [NSString stringWithFormat:
NSLocalizedString(@" rotated%@ %i%C", @""), dir, r, 0xb0] : @"", //degrees
timerIntvl && timerPaused ? [NSString stringWithFormat:@" %@(%.1f%@) %@",
NSLocalizedString(@"Auto-advance", @""),
timerIntvl,
NSLocalizedString(@"seconds", @""),
NSLocalizedString(@"PAUSED", @"")]
: @""];
[infoFld sizeToFit];
}
- (void)updateInfoFld {
[self updateInfoFldWithRotation:imgView.rotation];
}
- (void)redisplayImage {
if (currentIndex == NSNotFound) return;
NSString *theFile = filenames[currentIndex];
[zooms removeObjectForKey:theFile]; // don't forget to reset the zoom/rotation!
[rotations removeObjectForKey:theFile];
[flips removeObjectForKey:theFile];
[self displayImage];
}
- (void)uncacheImage:(NSString *)s {
[imgCache removeImageForKey:s];
[zooms removeObjectForKey:s];
[rotations removeObjectForKey:s];
[flips removeObjectForKey:s];
if ((currentIndex != NSNotFound && currentIndex != filenames.count) && [s isEqualToString:filenames[currentIndex]])
[self displayImage];
}
- (void)displayImage {
if (currentIndex == NSNotFound) return; // in case called after slideshow ended
// not necessary if s/isActive/isKeyWindow/
if (currentIndex == filenames.count) { // if the last image was deleted, show a blank screen
catsFld.hidden = YES;
infoFld.hidden = NO;
infoFld.stringValue = NSLocalizedString(@"End of slideshow (last file was deleted)", @"");
[infoFld sizeToFit];
exifFld.string = @"";
imgView.image = nil;
self.title = NSProcessInfo.processInfo.processName;
return;
}
NSString *theFile = filenames[currentIndex];
[self setTitleWithRepresentedFilename:theFile];
NSImage *img = [self loadFromCache:theFile];
[self displayCats];
if (img) {
NSNumber *rot = rotations[theFile];
DYImageViewZoomInfo *zoomInfo = zooms[theFile];
int r = rot ? rot.intValue : 0;
BOOL imgFlipped = [flips[theFile] boolValue];
if (hideInfoFld) infoFld.hidden = YES; // this must happen before setImage, for redraw purposes
imgView.image = img;
if ([theFile.pathExtension.lowercaseString isEqualToString:@"webp"]) {
// check for animated webp
CGImageSourceRef src = CGImageSourceCreateWithURL((__bridge CFURLRef)[NSURL fileURLWithPath:theFile isDirectory:NO], NULL);
if (src) {
if (CGImageSourceGetCount(src) > 1)
imgView.webpImageSource = CFBridgingRelease(src);
else
CFRelease(src);
}
}
if (r) imgView.rotation = r;
if (imgFlipped) imgView.imageFlipped = YES;
// ** see keyDown for specifics
// if zoomed in, we need to set a different image
// here, copy-pasted from keyDown
DYImageInfo *info = [imgCache infoForKey:filenames[currentIndex]];
if (autoRotate && !rot && !imgFlipped && info->exifOrientation) {
// auto-rotate by exif orientation
exiforientation_to_components(info->exifOrientation, &r, &imgFlipped);
rotations[theFile] = @(r);
flips[theFile] = @(imgFlipped);
imgView.rotation = r;
imgView.imageFlipped = imgFlipped;
}
// if zoom has been manually set, or if the the image size is larger than the view size, we need to set the zoom to something other than fit-to-view
if (zoomInfo || (imgView.showActualSize && !(info->pixelSize.width <= imgView.bounds.size.width && info->pixelSize.height <= imgView.bounds.size.height))) {
if (!NSEqualSizes(info->pixelSize, info.image.size))
[info loadFullSizeImage];
[imgView setImage:info.image
zooming:zoomInfo ? DYImageViewZoomModeManual : DYImageViewZoomModeActualSize];
if (zoomInfo) imgView.zoomInfo = zoomInfo;
}
[self updateInfoFldWithRotation:r];
if (!exifFld.enclosingScrollView.hidden) [self updateExifFld];
if (timerIntvl) [self runTimer];
} else {
if (hideInfoFld) infoFld.hidden = NO;
infoFld.stringValue = [NSString stringWithFormat:NSLocalizedString(@"Loading [%i/%i] %@...", @""),
(unsigned int)currentIndex+1, (unsigned int)filenames.count, [self currentShortFilename]];
[infoFld sizeToFit];
return;
}
if (keyIsRepeating) return; // don't bother precaching if we're fast-forwarding anyway
if (self.isMainWindow && !imgView.dragMode)
[NSCursor setHiddenUntilMouseMoves:YES];
BOOL fullSize = imgView.showActualSize;
for (short i=1; i<=2; i++) {
if (currentIndex+i >= filenames.count)
break;
NSString *aPath = filenames[currentIndex+i];
[_upcomingQueue addOperationWithBlock:^{
[imgCache cacheFile:aPath fullSize:fullSize];
}];
}
}
- (void)showLoopAnimation {
if ([NSUserDefaults.standardUserDefaults boolForKey:@"SlideshowSuppressLoopIndicator"]) return;
if (!loopImageView) {
NSImage *loopImage = [NSImage imageNamed:@"loop_forward.tiff"];
loopImageView = [[NSImageView alloc] initWithFrame:(NSRect){NSZeroPoint, loopImage.size}];
[self.contentView addSubview:loopImageView];
loopImageView.image = loopImage;
}
NSRect r = loopImageView.frame;
NSSize s = self.frame.size;
r.origin.x = (int)(s.width-r.size.width)/2;
r.origin.y = (int)(s.height-r.size.height)/2;
loopImageView.frame = r;
loopImageView.hidden = NO;
NSDictionary *viewDict = @{ NSViewAnimationTargetKey: loopImageView, NSViewAnimationEffectKey: NSViewAnimationFadeOutEffect };
NSViewAnimation *theAnim = [[NSViewAnimation alloc] initWithViewAnimations:@[viewDict]];
theAnim.duration = 0.9;
theAnim.animationCurve = NSAnimationEaseIn;
[theAnim startAnimation];
}
- (void)jump:(NSInteger)n { // go forward n pics (negative numbers go backwards)
if (n > 0)
timerPaused = NO; // going forward unpauses auto-advance
if ((n > 0 && currentIndex+1 >= filenames.count) || (n < 0 && currentIndex == 0)){
if (loopMode) {
if (randomMode && n > 0 && [NSUserDefaults.standardUserDefaults boolForKey:@"Slideshow:RerandomizeOnLoop"]) {
// reshuffle whenever you loop through to the beginning
[filenames randomize];
}
[self jumpTo:n<0 ? filenames.count-1 : 0];
[self showLoopAnimation];
} else {
NSBeep();
}
} else {
if (n < 0 && labs(n) > currentIndex) {
n = -currentIndex;
} else if (n > 0 && n >= filenames.count - currentIndex) {
n = filenames.count - 1 - currentIndex;
}
[self jumpTo:currentIndex+n];
}
if (n < 0 && timerIntvl && autoTimer)
[self pauseTimer];
}
- (void)jump:(int)n ordered:(BOOL)ordered { // if ordered is YES, jump to the next/previous slide in the ordered sequence
if (ordered && randomMode) {
[self setTimer:0]; // always stop auto-advance here
if (currentIndex >= filenames.count) {
// stop if we just deleted the last file
NSBeep();
return;
}
NSUInteger newIndex = n < 0 ? [filenames orderedIndexOfObjectBeforeIndex:currentIndex] : [filenames orderedIndexOfObjectAfterIndex:currentIndex];
if (newIndex == NSNotFound) {
NSBeep();
return;
}
[self jumpTo:newIndex];
} else {
[self jump:n];
}
}
- (void)jumpTo:(NSUInteger)n {
//NSLog(@"jumping to %d", n);
[self killTimer];
// we rely on this only being called when changing pics, not at startup
[self saveZoomInfo];
// above code is repeated in endSlideshow, setBasePath
currentIndex = n >= filenames.count ? filenames.count - 1 : n;
[self displayImage];
}
- (void)saveZoomInfo {
if (currentIndex >= filenames.count) return;
if (imgView.zoomInfoNeedsSaving)
zooms[filenames[currentIndex]] = imgView.zoomInfo;
}
- (void)setRotation:(int)n {
n = [imgView addRotation:n];
rotations[filenames[currentIndex]] = @(n);
[self updateInfoFldWithRotation:n];
}
- (void)toggleFlip {
BOOL b = [imgView toggleFlip];
NSString *s = filenames[currentIndex];
flips[s] = @(b);
// also update the rotation to match, since flipping will reverse it
int r = [rotations[s] intValue];
if (r == 90 || r == -90)
rotations[s] = @(-r);
[self updateInfoFld];
}
- (void)toggleExif {
exifFld.enclosingScrollView.hidden = !exifFld.enclosingScrollView.hidden;
if (!exifFld.enclosingScrollView.hidden)
[self updateExifFld];
}
- (void)toggleHelp {
if (!helpFld) {
helpFld = [[NSTextView alloc] initWithFrame:NSZeroRect];
[self.contentView addSubview:helpFld];
if (![helpFld readRTFDFromFile:
[NSBundle.mainBundle pathForResource:@"creeveyhelp" ofType:@"rtf"]])
NSLog(@"couldn't load cheat sheet!");
helpFld.backgroundColor = NSColor.lightGrayColor;
helpFld.selectable = NO;
// NSLayoutManager *lm = [helpFld layoutManager];
// NSRange rnge = [lm glyphRangeForCharacterRange:NSMakeRange(0,[[helpFld textStorage] length])
// actualCharacterRange:NULL];
// NSSize s = [lm boundingRectForGlyphRange:rnge
// inTextContainer:[lm textContainerForGlyphAtIndex:0
// effectiveRange:NULL]].size;
// //[[helpFld textStorage] size];
// NSLog(NSStringFromRange(rnge));
NSSize s = [helpFld.textStorage size];
NSRect r = NSMakeRect(0,0,s.width+10,s.height);
// width must be bigger than text, or wrappage will occur
s = self.contentView.frame.size;
r.origin.x = s.width - r.size.width - 50;
r.origin.y = s.height - r.size.height - 55;
helpFld.frame = NSIntegralRect(r);
helpFld.autoresizingMask = NSViewMinXMargin|NSViewMinYMargin;
return;
}
helpFld.hidden = !helpFld.hidden;
}
#pragma mark event stuff
// Here's the bulk of our user interface, all keypresses
- (void)keyUp:(NSEvent *)e {
if (keyIsRepeating) {
keyIsRepeating = 0;
switch ([e.characters characterAtIndex:0]) {
case ' ':
case NSRightArrowFunctionKey:
case NSDownArrowFunctionKey:
case NSLeftArrowFunctionKey:
case NSUpArrowFunctionKey:
case NSPageUpFunctionKey:
case NSPageDownFunctionKey:
[self displayImage];
break;
default:
break;
}
}
}
- (void)keyDown:(NSEvent *)e {
if (e.characters.length == 0) return; // avoid exception on deadkeys
unichar c = [e.characters characterAtIndex:0];
if (currentIndex == NSNotFound) {
// loading filenames
switch(c) {
case 'q':
case '\x1b':
[self endSlideshow];
return;
default:
NSBeep();
return;
}
}
if (currentIndex == filenames.count) {
switch(c) {
case ' ': // only allow shift-space to go back
if ((e.modifierFlags & NSEventModifierFlagShift) == 0) return;
// fallthrough
case NSLeftArrowFunctionKey:
case NSUpArrowFunctionKey:
case NSHomeFunctionKey:
case NSEndFunctionKey:
case NSPageUpFunctionKey:
case 'q':
case '\x1b': // escape
case 'h':
case '?':
case '/':
break;
default:
NSBeep();
return;
}
}
if (c >= '1' && c <= '9') {
if ((e.modifierFlags & NSEventModifierFlagNumericPad) != 0 && imgView.zoomMode) {
if (c == '5') {
NSBeep();
} else {
char x,y;
c -= '0';
if (c<=3) y = 1; else if (c>=7) y = -1; else y = 0;
if (c%3 == 0) x = -1; else if (c%3 == 1) x = 1; else x=0;
[imgView fakeDragX:(imgView.bounds.size.width/2)*x
y:(imgView.bounds.size.height/2)*y];
}
} else {
if (timerIntvl == 0 || timerPaused) [self jump:1];
[self setTimer:c - '0'];
}
return;
}
if (c == '0') {
[self setTimer:0];
[self updateInfoFld];
return;
}
if (c >= NSF1FunctionKey && c <= NSF12FunctionKey) {
[self assignCat:c - NSF1FunctionKey + 1
toggle:(e.modifierFlags & NSEventModifierFlagCommand) != 0];
//NSLog(@"got cat %i", c - NSF1FunctionKey + 1);
return;
}
if (e.ARepeat && keyIsRepeating < MAX_REPEATING_CACHED) {
keyIsRepeating++;
}
if (c == ' ' && ((e.modifierFlags & NSEventModifierFlagShift) != 0)) {
c = NSLeftArrowFunctionKey;
}
DYImageInfo *obj;
switch (c) {
case '!':
[self setTimer:0.5];
break;
case '@':
[self setTimer:1.5];
break;
case ' ':
if (timerIntvl && autoTimer) {
//[self setTimer:0];
[self pauseTimer];
break; // pause slideshow only
}
// otherwise advance
case NSRightArrowFunctionKey:
case NSDownArrowFunctionKey:
// hold down option to go to the next non-randomized slide
[self jump:1 ordered:(e.modifierFlags & NSEventModifierFlagOption) != 0];
break;
case NSLeftArrowFunctionKey:
case NSUpArrowFunctionKey:
[self jump:-1 ordered:(e.modifierFlags & NSEventModifierFlagOption) != 0];
break;
case NSHomeFunctionKey:
[self jump:-currentIndex]; // <0 stops auto-advance
break;
case NSEndFunctionKey:
[self jumpTo:filenames.count-1];
break;
case NSPageUpFunctionKey:
[self jump:-10];
break;
case NSPageDownFunctionKey:
[self jump:10];
break;
case 'q':
case '\x1b': // escape
[self endSlideshow];
break;
case 'i':
// cycles three ways: info, info + exif, none
hideInfoFld = !infoFld.hidden && !exifFld.enclosingScrollView.hidden;
if (!infoFld.hidden)
[self toggleExif];
infoFld.hidden = hideInfoFld; // 10.3 or later!
{
unsigned short infoFldVisible = 0;
if (!exifFld.enclosingScrollView.hidden) {
infoFldVisible = 2;
} else if (!hideInfoFld) {
infoFldVisible = 1;
}
[NSUserDefaults.standardUserDefaults setInteger:infoFldVisible forKey:@"DYSlideshowWindowVisibleFields"];
}
break;
case 'h':
case '?':
case '/':
case NSHelpFunctionKey: // doesn't work, trapped at a higher level?
[self toggleHelp];
break;
case 'I':
if (exifFld.enclosingScrollView.hidden) {
moreExif = YES;
hideInfoFld = NO;
[self toggleExif];
infoFld.hidden = NO;
} else {
moreExif = !moreExif;
[self updateExifFld];
}
[NSUserDefaults.standardUserDefaults setInteger:2 forKey:@"DYSlideshowWindowVisibleFields"];
break;
case 'l':
[self setRotation:90];
break;
case 'r':
[self setRotation:-90];
break;
case 'f':
[self toggleFlip];
break;
case '=':
//if ([imgView showActualSize])
// [zooms removeObjectForKey:[filenames objectAtIndex:currentIndex]];
// actually, '=' doesn't center the pic, so this is wrong
// if you zoom or move a pic while in actualsize mode, you're basically stuck with a non-default zoom
// intentional fall-through to next cases
case '+':
case '-':
if ((obj = [imgCache infoForKey:filenames[currentIndex]])) {
if (obj.image == imgView.image
&& !NSEqualSizes(obj->pixelSize, obj.image.size)) { // cached image smaller than orig
[imgView setImage:[obj loadFullSizeImage]
zooming:c == '=' ? DYImageViewZoomModeActualSize : c == '+' ? DYImageViewZoomModeZoomIn : DYImageViewZoomModeZoomOut];
} else {
if (c == '+') [imgView zoomIn];
else if (c == '-') [imgView zoomOut];
else [imgView zoomActualSize];
}