forked from btrask/Sequential
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PGDisplayController.m
1345 lines (1246 loc) · 57.2 KB
/
PGDisplayController.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 © 2007-2009, The Sequential Project
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the the Sequential Project nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE SEQUENTIAL PROJECT ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE SEQUENTIAL PROJECT BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
#import "PGDisplayController.h"
#import <unistd.h>
#import <tgmath.h>
// Models
#import "PGDocument.h"
#import "PGNode.h"
#import "PGContainerAdapter.h"
#import "PGGenericImageAdapter.h"
#import "PGResourceIdentifier.h"
#import "PGBookmark.h"
// Views
#import "PGDocumentWindow.h"
#import "PGClipView.h"
#import "PGImageView.h"
#import "PGBezelPanel.h"
#import "PGAlertView.h"
#import "PGInfoView.h"
#import "PGFindView.h"
// Controllers
#import "PGDocumentController.h"
#import "PGPreferenceWindowController.h"
#import "PGBookmarkController.h"
#import "PGThumbnailController.h"
#import "PGImageSaveAlert.h"
// Other Sources
#import "PGAppKitAdditions.h"
#import "PGDebug.h"
#import "PGDelayedPerforming.h"
#import "PGFoundationAdditions.h"
#import "PGGeometry.h"
#import "PGKeyboardLayout.h"
NSString *const PGDisplayControllerActiveNodeDidChangeNotification = @"PGDisplayControllerActiveNodeDidChange";
NSString *const PGDisplayControllerActiveNodeWasReadNotification = @"PGDisplayControllerActiveNodeWasRead";
NSString *const PGDisplayControllerTimerDidChangeNotification = @"PGDisplayControllerTimerDidChange";
#define PGWindowMinSize ((NSSize){350.0f, 200.0f})
enum {
PGZoomNone = 0,
PGZoomIn = 1 << 0,
PGZoomOut = 1 << 1
};
typedef NSUInteger PGZoomDirection;
static inline NSSize PGConstrainSize(NSSize min, NSSize size, NSSize max)
{
return NSMakeSize(MIN(MAX(min.width, size.width), max.width), MIN(MAX(min.height, size.height), max.height));
}
@interface PGDisplayController(Private)
- (void)_setImageView:(PGImageView *)aView;
- (BOOL)_setActiveNode:(PGNode *)aNode;
- (void)_readActiveNode;
- (void)_readFinished;
- (NSSize)_sizeForImageRep:(NSImageRep *)rep orientation:(PGOrientation)orientation;
- (NSSize)_sizeForImageRep:(NSImageRep *)rep orientation:(PGOrientation)orientation scaleMode:(PGImageScaleMode)scaleMode factor:(float)factor;
- (void)_updateImageViewSizeAllowAnimation:(BOOL)flag;
- (void)_updateNodeIndex;
- (void)_updateInfoPanelText;
- (void)_setCopyAsDesktopPicturePanelDidEnd:(NSSavePanel *)savePanel returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo;
- (void)_offerToOpenBookmarkAlertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode bookmark:(PGBookmark *)bookmark;
@end
@implementation PGDisplayController
#pragma mark +PGDisplayController
+ (NSArray *)pasteboardTypes
{
return [NSArray PG_arrayWithContentsOfArrays:[PGNode pasteboardTypes], [PGImageView pasteboardTypes], nil];
}
#pragma mark +NSObject
+ (void)initialize
{
[NSApp registerServicesMenuSendTypes:[self pasteboardTypes] returnTypes:[NSArray array]];
}
- (NSUserDefaultsController *)userDefaults
{
return [NSUserDefaultsController sharedUserDefaultsController];
}
#pragma mark -PGDisplayController
- (IBAction)reveal:(id)sender
{
if([[self activeDocument] isOnline]) {
if([[NSWorkspace sharedWorkspace] openURL:[[[self activeDocument] rootIdentifier] URLByFollowingAliases:NO]]) return;
} else {
NSString *const path = [[[[self activeNode] identifier] URLByFollowingAliases:NO] path];
if([[PGDocumentController sharedDocumentController] pathFinderRunning]) {
if([[[[NSAppleScript alloc] initWithSource:[NSString stringWithFormat:@"tell application \"Path Finder\"\nactivate\nreveal \"%@\"\nend tell", path]] autorelease] executeAndReturnError:NULL]) return;
} else {
if([[NSWorkspace sharedWorkspace] selectFile:path inFileViewerRootedAtPath:nil]) return;
}
}
NSBeep();
}
- (IBAction)saveImagesTo:(id)sender
{
[[[[PGImageSaveAlert alloc] initWithRoot:[[self activeDocument] node] initialSelection:[self selectedNodes]] autorelease] beginSheetForWindow:[self windowForSheet]];
}
- (IBAction)setAsDesktopPicture:(id)sender
{
PGResourceIdentifier *const ident = [[self activeNode] identifier];
if(![ident isFileIdentifier] || ![[NSScreen PG_mainScreen] PG_setDesktopImageURL:[ident URLByFollowingAliases:YES]]) NSBeep();
}
- (IBAction)setCopyAsDesktopPicture:(id)sender
{
NSSavePanel *const savePanel = [NSSavePanel savePanel];
[savePanel setTitle:NSLocalizedString(@"Save Copy as Desktop Picture", @"Title of save dialog when setting a copy as the desktop picture.")];
PGDisplayableIdentifier *const ident = [[self activeNode] identifier];
[savePanel setRequiredFileType:[[ident naturalDisplayName] pathExtension]];
[savePanel setCanSelectHiddenExtension:YES];
NSWindow *const window = [self windowForSheet];
NSString *const file = [[ident naturalDisplayName] stringByDeletingPathExtension];
if(window) [savePanel beginSheetForDirectory:nil file:file modalForWindow:window modalDelegate:self didEndSelector:@selector(_setCopyAsDesktopPicturePanelDidEnd:returnCode:contextInfo:) contextInfo:NULL];
else [self _setCopyAsDesktopPicturePanelDidEnd:savePanel returnCode:[savePanel runModalForDirectory:nil file:file] contextInfo:NULL];
}
- (IBAction)moveToTrash:(id)sender
{
BOOL movedAnything = NO;
for(PGNode *const node in [self selectedNodes]) {
NSString *const path = [[[node identifier] URL] path];
if([[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:[path stringByDeletingLastPathComponent] destination:@"" files:[NSArray arrayWithObject:[path lastPathComponent]] tag:NULL]) movedAnything = YES;
}
if(!movedAnything) NSBeep();
}
#pragma mark -
- (IBAction)copy:(id)sender
{
if(![self writeSelectionToPasteboard:[NSPasteboard generalPasteboard] types:[[self class] pasteboardTypes]]) NSBeep();
}
- (IBAction)performFindPanelAction:(id)sender
{
switch([sender tag]) {
case NSFindPanelActionShowFindPanel:
[self setFindPanelShown:!([self findPanelShown] && [_findPanel isKeyWindow])];
break;
case NSFindPanelActionNext:
case NSFindPanelActionPrevious:
{
NSArray *const terms = [[searchField stringValue] PG_searchTerms];
if(terms && [terms count] && ![self tryToSetActiveNode:[[[self activeNode] resourceAdapter] sortedViewableNodeNext:[sender tag] == NSFindPanelActionNext matchSearchTerms:terms] forward:YES]) NSBeep();
break;
}
default:
NSBeep();
}
if([_findPanel isKeyWindow]) [_findPanel makeFirstResponder:searchField];
}
- (IBAction)hideFindPanel:(id)sender
{
[self setFindPanelShown:NO];
}
#pragma mark -
- (IBAction)toggleFullscreen:(id)sender
{
[[PGDocumentController sharedDocumentController] setFullscreen:![PGDocumentController sharedDocumentController].fullscreen];
}
- (IBAction)toggleInfo:(id)sender
{
[[self activeDocument] setShowsInfo:![[self activeDocument] showsInfo]];
}
- (IBAction)toggleThumbnails:(id)sender
{
[[self activeDocument] setShowsThumbnails:![[self activeDocument] showsThumbnails]];
}
- (IBAction)changeReadingDirection:(id)sender
{
[[self activeDocument] setReadingDirection:[sender tag]];
}
- (IBAction)changeSortOrder:(id)sender
{
[[self activeDocument] setSortOrder:([sender tag] & PGSortOrderMask) | ([[self activeDocument] sortOrder] & PGSortOptionsMask)];
}
- (IBAction)changeSortDirection:(id)sender
{
[[self activeDocument] setSortOrder:([[self activeDocument] sortOrder] & ~PGSortDescendingMask) | [sender tag]];
}
- (IBAction)changeSortRepeat:(id)sender
{
[[self activeDocument] setSortOrder:([[self activeDocument] sortOrder] & ~PGSortRepeatMask) | [sender tag]];
}
- (IBAction)revertOrientation:(id)sender
{
[[self activeDocument] setBaseOrientation:PGUpright];
}
- (IBAction)changeOrientation:(id)sender
{
[[self activeDocument] setBaseOrientation:PGAddOrientation([[self activeDocument] baseOrientation], [sender tag])];
}
- (IBAction)toggleAnimation:(id)sender
{
NSParameterAssert([_imageView canAnimateRep]);
BOOL const nowPlaying = ![[self activeDocument] animatesImages];
[[_graphicPanel content] pushGraphic:[PGBezierPathIconGraphic graphicWithIconType:nowPlaying ? AEPlayIcon : AEPauseIcon] window:[self window]];
[[self activeDocument] setAnimatesImages:nowPlaying];
}
#pragma mark -
- (IBAction)changeImageScaleMode:(id)sender
{
[[self activeDocument] setImageScaleMode:[sender tag]];
}
- (IBAction)zoomIn:(id)sender
{
if(![self zoomKeyDown:[[self window] currentEvent]]) [self zoomBy:2.0f animate:YES];
}
- (IBAction)zoomOut:(id)sender
{
if(![self zoomKeyDown:[[self window] currentEvent]]) [self zoomBy:0.5f animate:YES];
}
- (IBAction)changeImageScaleFactor:(id)sender
{
[[self activeDocument] setImageScaleFactor:pow(2.0f, (CGFloat)[sender doubleValue]) animate:NO];
[[[PGDocumentController sharedDocumentController] scaleMenu] update];
}
- (IBAction)minImageScaleFactor:(id)sender
{
[[self activeDocument] setImageScaleFactor:PGScaleMin];
[[[PGDocumentController sharedDocumentController] scaleMenu] update];
}
- (IBAction)maxImageScaleFactor:(id)sender
{
[[self activeDocument] setImageScaleFactor:PGScaleMax];
[[[PGDocumentController sharedDocumentController] scaleMenu] update];
}
#pragma mark -
- (IBAction)previousPage:(id)sender
{
[self tryToGoForward:NO allowAlerts:YES];
}
- (IBAction)nextPage:(id)sender
{
[self tryToGoForward:YES allowAlerts:YES];
}
- (IBAction)firstPage:(id)sender
{
[self setActiveNode:[[[[self activeDocument] node] resourceAdapter] sortedViewableNodeFirst:YES] forward:YES];
}
- (IBAction)lastPage:(id)sender
{
[self setActiveNode:[[[[self activeDocument] node] resourceAdapter] sortedViewableNodeFirst:NO] forward:NO];
}
#pragma mark -
- (IBAction)firstOfPreviousFolder:(id)sender
{
if([self tryToSetActiveNode:[[[self activeNode] resourceAdapter] sortedFirstViewableNodeInFolderNext:NO inclusive:NO] forward:YES]) return;
[self prepareToLoop]; // -firstOfPreviousFolder: is an exception to our usual looping mechanic, so we can't use -loopForward:.
PGNode *const last = [[[[self activeDocument] node] resourceAdapter] sortedViewableNodeFirst:NO];
[self tryToLoopForward:NO toNode:[[last resourceAdapter] isSortedFirstViewableNodeOfFolder] ? last : [[last resourceAdapter] sortedFirstViewableNodeInFolderNext:NO inclusive:YES] pageForward:YES allowAlerts:YES];
}
- (IBAction)firstOfNextFolder:(id)sender
{
if([self tryToSetActiveNode:[[[self activeNode] resourceAdapter] sortedFirstViewableNodeInFolderNext:YES inclusive:NO] forward:YES]) return;
[self loopForward:YES];
}
- (IBAction)skipBeforeFolder:(id)sender
{
if([self tryToSetActiveNode:[[[[self activeNode] resourceAdapter] containerAdapter] sortedViewableNodeNext:NO includeChildren:NO] forward:NO]) return;
[self loopForward:NO];
}
- (IBAction)skipPastFolder:(id)sender
{
if([self tryToSetActiveNode:[[[[self activeNode] resourceAdapter] containerAdapter] sortedViewableNodeNext:YES includeChildren:NO] forward:YES]) return;
[self loopForward:YES];
}
- (IBAction)firstOfFolder:(id)sender
{
[self setActiveNode:[[[self activeNode] resourceAdapter] sortedViewableNodeInFolderFirst:YES] forward:YES];
}
- (IBAction)lastOfFolder:(id)sender
{
[self setActiveNode:[[[self activeNode] resourceAdapter] sortedViewableNodeInFolderFirst:NO] forward:NO];
}
#pragma mark -
- (IBAction)jumpToPage:(id)sender
{
PGNode *node = [[(NSMenuItem *)sender representedObject] nonretainedObjectValue];
if(![node isViewable]) node = [[node resourceAdapter] sortedViewableNodeFirst:YES];
if([self activeNode] == node || !node) return;
[self setActiveNode:node forward:YES];
}
#pragma mark -
- (IBAction)pauseDocument:(id)sender
{
[[PGBookmarkController sharedBookmarkController] addBookmark:[[self activeNode] bookmark]];
}
- (IBAction)pauseAndCloseDocument:(id)sender
{
[self pauseDocument:sender];
[[self activeDocument] close];
}
#pragma mark -
- (IBAction)reload:(id)sender
{
[reloadButton setEnabled:NO];
[[self activeNode] reload];
[self _readActiveNode];
}
- (IBAction)decrypt:(id)sender
{
PGNode *const activeNode = [self activeNode];
[activeNode PG_addObserver:self selector:@selector(nodeLoadingDidProgress:) name:PGNodeLoadingDidProgressNotification];
[activeNode PG_addObserver:self selector:@selector(nodeReadyForViewing:) name:PGNodeReadyForViewingNotification];
// TODO: Figure this out.
// [[[activeNode resourceAdapter] info] setObject:[passwordField stringValue] forKey:PGPasswordKey];
[activeNode becomeViewed];
}
#pragma mark -
@synthesize activeDocument = _activeDocument;
@synthesize activeNode = _activeNode;
- (NSWindow *)windowForSheet
{
return [self window];
}
- (NSSet *)selectedNodes
{
NSSet *const thumbnailSelection = [_thumbnailController selectedNodes];
if([thumbnailSelection count]) return thumbnailSelection;
return [self activeNode] ? [NSSet setWithObject:[self activeNode]] : [NSSet set];
}
- (PGNode *)selectedNode
{
NSSet *const selectedNodes = [self selectedNodes];
return [selectedNodes count] == 1 ? [selectedNodes anyObject] : nil;
}
@synthesize clipView;
@synthesize initialLocation = _initialLocation;
@synthesize reading = _reading;
- (BOOL)isDisplayingImage
{
return [clipView documentView] == _imageView;
}
- (BOOL)canShowInfo
{
return YES;
}
- (BOOL)shouldShowInfo
{
return [[self activeDocument] showsInfo] && [self canShowInfo];
}
- (BOOL)loadingIndicatorShown
{
return _loadingGraphic != nil;
}
- (BOOL)findPanelShown
{
return [_findPanel isVisible] && ![_findPanel isFadingOut];
}
- (void)setFindPanelShown:(BOOL)flag
{
if(flag) {
NSDisableScreenUpdates();
[[self window] orderFront:self];
if(![self findPanelShown]) [_findPanel displayOverWindow:[self window]];
[_findPanel makeKeyWindow];
[self documentReadingDirectionDidChange:nil];
NSEnableScreenUpdates();
} else {
[_findPanel fadeOut];
[self documentReadingDirectionDidChange:nil];
[[self window] makeKeyWindow];
}
}
- (NSDate *)nextTimerFireDate
{
return [[_nextTimerFireDate retain] autorelease];
}
- (BOOL)timerRunning
{
return !!_timer;
}
- (void)setTimerRunning:(BOOL)run
{
[_nextTimerFireDate release];
[_timer invalidate];
[_timer release];
if(run) {
_nextTimerFireDate = [[NSDate alloc] initWithTimeIntervalSinceNow:[[self activeDocument] timerInterval]];
_timer = [[self PG_performSelector:@selector(advanceOnTimer) withObject:nil fireDate:_nextTimerFireDate interval:0.0f options:kNilOptions mode:NSDefaultRunLoopMode] retain];
} else {
_nextTimerFireDate = nil;
_timer = nil;
}
[self PG_postNotificationName:PGDisplayControllerTimerDidChangeNotification];
}
#pragma mark -
- (BOOL)setActiveDocument:(PGDocument *)document closeIfAppropriate:(BOOL)flag
{
if(document == _activeDocument) return NO;
if(_activeDocument) {
if(_reading) [_imageView setImageRep:nil orientation:PGUpright size:NSZeroSize];
[_activeDocument storeNode:[self activeNode] imageView:_imageView offset:[clipView pinLocationOffset] query:[searchField stringValue]];
[self _setImageView:nil];
[_activeDocument PG_removeObserver:self name:PGDocumentWillRemoveNodesNotification];
[_activeDocument PG_removeObserver:self name:PGDocumentSortedNodesDidChangeNotification];
[_activeDocument PG_removeObserver:self name:PGDocumentNodeDisplayNameDidChangeNotification];
[_activeDocument PG_removeObserver:self name:PGDocumentNodeIsViewableDidChangeNotification];
[_activeDocument PG_removeObserver:self name:PGPrefObjectBaseOrientationDidChangeNotification];
[_activeDocument PG_removeObserver:self name:PGPrefObjectShowsInfoDidChangeNotification];
[_activeDocument PG_removeObserver:self name:PGPrefObjectShowsThumbnailsDidChangeNotification];
[_activeDocument PG_removeObserver:self name:PGPrefObjectReadingDirectionDidChangeNotification];
[_activeDocument PG_removeObserver:self name:PGPrefObjectImageScaleDidChangeNotification];
[_activeDocument PG_removeObserver:self name:PGPrefObjectAnimatesImagesDidChangeNotification];
[_activeDocument PG_removeObserver:self name:PGPrefObjectTimerIntervalDidChangeNotification];
}
if(flag && !document && _activeDocument) {
_activeDocument = nil;
[[self retain] autorelease]; // Necessary if the find panel is open.
[[self window] close];
return YES;
}
_activeDocument = document;
if([[self window] isMainWindow]) [[PGDocumentController sharedDocumentController] setCurrentDocument:_activeDocument];
[_activeDocument PG_addObserver:self selector:@selector(documentWillRemoveNodes:) name:PGDocumentWillRemoveNodesNotification];
[_activeDocument PG_addObserver:self selector:@selector(documentSortedNodesDidChange:) name:PGDocumentSortedNodesDidChangeNotification];
[_activeDocument PG_addObserver:self selector:@selector(documentNodeDisplayNameDidChange:) name:PGDocumentNodeDisplayNameDidChangeNotification];
[_activeDocument PG_addObserver:self selector:@selector(documentNodeIsViewableDidChange:) name:PGDocumentNodeIsViewableDidChangeNotification];
[_activeDocument PG_addObserver:self selector:@selector(documentBaseOrientationDidChange:) name:PGPrefObjectBaseOrientationDidChangeNotification];
[_activeDocument PG_addObserver:self selector:@selector(documentShowsInfoDidChange:) name:PGPrefObjectShowsInfoDidChangeNotification];
[_activeDocument PG_addObserver:self selector:@selector(documentShowsThumbnailsDidChange:) name:PGPrefObjectShowsThumbnailsDidChangeNotification];
[_activeDocument PG_addObserver:self selector:@selector(documentReadingDirectionDidChange:) name:PGPrefObjectReadingDirectionDidChangeNotification];
[_activeDocument PG_addObserver:self selector:@selector(documentImageScaleDidChange:) name:PGPrefObjectImageScaleDidChangeNotification];
[_activeDocument PG_addObserver:self selector:@selector(documentAnimatesImagesDidChange:) name:PGPrefObjectAnimatesImagesDidChangeNotification];
[_activeDocument PG_addObserver:self selector:@selector(documentTimerIntervalDidChange:) name:PGPrefObjectTimerIntervalDidChangeNotification];
[self setTimerRunning:NO];
if(_activeDocument) {
NSDisableScreenUpdates();
PGNode *node;
PGImageView *view;
NSSize offset;
NSString *query;
[_activeDocument getStoredNode:&node imageView:&view offset:&offset query:&query];
[self _setImageView:view];
if([view rep]) {
[self _setActiveNode:node];
[clipView setDocumentView:view];
[view setImageRep:[view rep] orientation:[view orientation] size:[self _sizeForImageRep:[view rep] orientation:[view orientation]]];
[clipView scrollPinLocationToOffset:offset animation:PGNoAnimation];
[self _readFinished];
} else {
[clipView setDocumentView:view];
[self setActiveNode:node forward:YES];
}
[self documentNodeIsViewableDidChange:nil]; // In case the node has become unviewable in the meantime.
[searchField setStringValue:query];
[self documentReadingDirectionDidChange:nil];
[self documentShowsInfoDidChange:nil];
[self documentShowsThumbnailsDidChange:nil];
[_thumbnailController setDocument:_activeDocument];
NSEnableScreenUpdates();
}
return NO;
}
- (void)activateDocument:(PGDocument *)document
{
[self setActiveDocument:document closeIfAppropriate:NO];
[[self window] makeKeyAndOrderFront:self];
}
#pragma mark -
- (void)setActiveNode:(PGNode *)aNode forward:(BOOL)flag
{
if(![self _setActiveNode:aNode]) return;
if([[[self window] currentEvent] modifierFlags] & NSControlKeyMask) _initialLocation = PGPreserveLocation;
else _initialLocation = flag ? PGHomeLocation : [[[NSUserDefaults standardUserDefaults] objectForKey:PGBackwardsInitialLocationKey] integerValue];
[self _readActiveNode];
}
- (BOOL)tryToSetActiveNode:(PGNode *)aNode forward:(BOOL)flag
{
if(!aNode) return NO;
[self setActiveNode:aNode forward:flag];
return YES;
}
- (BOOL)tryToGoForward:(BOOL)forward allowAlerts:(BOOL)flag
{
if([self tryToSetActiveNode:[[[self activeNode] resourceAdapter] sortedViewableNodeNext:forward] forward:forward]) return YES;
[self prepareToLoop];
return [self tryToLoopForward:forward toNode:[[[[self activeDocument] node] resourceAdapter] sortedViewableNodeFirst:forward] pageForward:forward allowAlerts:flag];
}
- (void)loopForward:(BOOL)flag
{
[self prepareToLoop];
[self tryToLoopForward:flag toNode:[[[[self activeDocument] node] resourceAdapter] sortedViewableNodeFirst:flag] pageForward:flag allowAlerts:YES];
}
- (void)prepareToLoop
{
PGSortOrder const o = [[self activeDocument] sortOrder];
if(!(PGSortRepeatMask & o) || (PGSortOrderMask & o) != PGSortShuffle) return;
PGDocument *const doc = [self activeDocument];
[[doc node] noteSortOrderDidChange]; // Reshuffle.
[doc noteSortedChildrenDidChange];
}
- (BOOL)tryToLoopForward:(BOOL)loopForward toNode:(PGNode *)node pageForward:(BOOL)pageForward allowAlerts:(BOOL)flag
{
PGDocument *const doc = [self activeDocument];
BOOL const left = ([doc readingDirection] == PGReadingDirectionLeftToRight) == !loopForward;
PGSortOrder const o = [[self activeDocument] sortOrder];
if(PGSortRepeatMask & o && [self tryToSetActiveNode:node forward:pageForward]) {
if(flag) [[_graphicPanel content] pushGraphic:left ? [PGAlertGraphic loopedLeftGraphic] : [PGAlertGraphic loopedRightGraphic] window:[self window]];
return YES;
}
if(flag) [[_graphicPanel content] pushGraphic:left ? [PGAlertGraphic cannotGoLeftGraphic] : [PGAlertGraphic cannotGoRightGraphic] window:[self window]];
return NO;
}
- (void)activateNode:(PGNode *)node
{
[self setActiveDocument:[node document] closeIfAppropriate:NO];
[self setActiveNode:node forward:YES];
}
#pragma mark -
- (void)showLoadingIndicator
{
if(_loadingGraphic) return;
_loadingGraphic = [[PGLoadingGraphic loadingGraphic] retain];
[_loadingGraphic setProgress:[[[[self activeNode] resourceAdapter] activity] progress]];
[[_graphicPanel content] pushGraphic:_loadingGraphic window:[self window]];
}
- (void)offerToOpenBookmark:(PGBookmark *)bookmark
{
NSAlert *const alert = [[NSAlert alloc] init];
[alert setMessageText:[NSString stringWithFormat:NSLocalizedString(@"This document has a bookmark for the page %@.", @"Offer to resume from bookmark alert message text. %@ is replaced with the page name."), [[bookmark fileIdentifier] displayName]]];
[alert setInformativeText:NSLocalizedString(@"If you don't resume from this page, the bookmark will be kept and you will start from the first page as usual.", @"Offer to resume from bookmark alert informative text.")];
[[alert addButtonWithTitle:NSLocalizedString(@"Resume", @"Do resume from bookmark button.")] setKeyEquivalent:@"\r"];
[[alert addButtonWithTitle:NSLocalizedString(@"Don't Resume", @"Don't resume from bookmark button.")] setKeyEquivalent:@"\e"];
NSWindow *const window = [self windowForSheet];
[bookmark retain];
if(window) [alert beginSheetModalForWindow:window modalDelegate:self didEndSelector:@selector(_offerToOpenBookmarkAlertDidEnd:returnCode:bookmark:) contextInfo:bookmark];
else [self _offerToOpenBookmarkAlertDidEnd:alert returnCode:[alert runModal] bookmark:bookmark];
}
- (void)advanceOnTimer
{
[self setTimerRunning:[self tryToGoForward:YES allowAlerts:YES]];
}
#pragma mark -
- (void)zoomBy:(CGFloat)factor animate:(BOOL)flag
{
[[self activeDocument] setImageScaleFactor:MAX(PGScaleMin, MIN([_imageView averageScaleFactor] * factor, PGScaleMax)) animate:flag];
}
- (BOOL)zoomKeyDown:(NSEvent *)firstEvent
{
[NSCursor setHiddenUntilMouseMoves:YES];
[_imageView setUsesCaching:NO];
[NSEvent startPeriodicEventsAfterDelay:0.0f withPeriod:PGAnimationFramerate];
NSEvent *latestEvent = firstEvent;
PGZoomDirection dir = PGZoomNone;
BOOL stop = NO, didAnything = NO;
do {
NSEventType const type = [latestEvent type];
if(NSKeyDown == type || NSKeyUp == type) {
PGZoomDirection newDir = PGZoomNone;
switch([latestEvent keyCode]) {
case PGKeyEquals:
case PGKeyPadPlus:
newDir = PGZoomIn; break;
case PGKeyMinus:
case PGKeyPadMinus:
newDir = PGZoomOut; break;
}
switch(type) {
case NSKeyDown: dir |= newDir; break;
case NSKeyUp: dir &= ~newDir; break;
}
} else {
switch(dir) {
case PGZoomNone: stop = YES; break;
case PGZoomIn: [self zoomBy:1.1f animate:NO]; break;
case PGZoomOut: [self zoomBy:1.0f / 1.1f animate:NO]; break;
}
if(!stop) didAnything = YES;
}
} while(!stop && (latestEvent = [[self window] nextEventMatchingMask:NSKeyDownMask | NSKeyUpMask | NSPeriodicMask untilDate:[NSDate distantFuture] inMode:NSEventTrackingRunLoopMode dequeue:YES]));
[NSEvent stopPeriodicEvents];
[[self window] discardEventsMatchingMask:NSAnyEventMask beforeEvent:latestEvent];
[_imageView setUsesCaching:YES];
return didAnything;
}
#pragma mark -
- (void)clipViewFrameDidChange:(NSNotification *)aNotif
{
[self _updateImageViewSizeAllowAnimation:NO];
}
#pragma mark -
- (void)nodeLoadingDidProgress:(NSNotification *)aNotif
{
NSParameterAssert([aNotif object] == [self activeNode]);
[_loadingGraphic setProgress:[[[[self activeNode] resourceAdapter] activity] progress]];
}
- (void)nodeReadyForViewing:(NSNotification *)aNotif
{
NSParameterAssert([aNotif object] == [self activeNode]);
NSError *const error = [[[self activeNode] resourceAdapter] error];
if(!error) {
NSPoint const relativeCenter = [clipView relativeCenter];
NSImageRep *const rep = [[aNotif userInfo] objectForKey:PGImageRepKey];
PGOrientation const orientation = [[[self activeNode] resourceAdapter] orientationWithBase:YES];
[_imageView setImageRep:rep orientation:orientation size:[self _sizeForImageRep:rep orientation:orientation]];
[clipView setDocumentView:_imageView];
if(PGPreserveLocation == _initialLocation) [clipView scrollRelativeCenterTo:relativeCenter animation:PGNoAnimation];
else [clipView scrollToLocation:_initialLocation animation:PGNoAnimation];
[[self window] makeFirstResponder:clipView];
} else if(PGEqualObjects([error domain], PGNodeErrorDomain)) switch([error code]) {
case PGGenericError:
[errorLabel PG_setAttributedStringValue:[[[_activeNode resourceAdapter] dataProvider] attributedString]];
[errorMessage setStringValue:[error localizedDescription]];
[errorView setFrameSize:NSMakeSize(NSWidth([errorView frame]), NSHeight([errorView frame]) - NSHeight([errorMessage frame]) + [[errorMessage cell] cellSizeForBounds:NSMakeRect(0.0f, 0.0f, NSWidth([errorMessage frame]), CGFLOAT_MAX)].height)];
[reloadButton setEnabled:YES];
[clipView setDocumentView:errorView];
break;
case PGPasswordError:
[passwordLabel PG_setAttributedStringValue:[[[_activeNode resourceAdapter] dataProvider] attributedString]];
[passwordField setStringValue:@""];
[clipView setDocumentView:passwordView];
break;
}
if(![_imageView superview]) [_imageView setImageRep:nil orientation:PGUpright size:NSZeroSize];
[self _readFinished];
[_thumbnailController clipViewBoundsDidChange:nil];
}
#pragma mark -
- (void)documentWillRemoveNodes:(NSNotification *)aNotif
{
PGNode *const changedNode = [[aNotif userInfo] objectForKey:PGDocumentNodeKey];
NSArray *const removedChildren = [[aNotif userInfo] objectForKey:PGDocumentRemovedChildrenKey];
PGNode *node = [[[self activeNode] resourceAdapter] sortedViewableNodeNext:YES afterRemovalOfChildren:removedChildren fromNode:changedNode];
if(!node) node = [[[self activeNode] resourceAdapter] sortedViewableNodeNext:NO afterRemovalOfChildren:removedChildren fromNode:changedNode];
[self setActiveNode:node forward:YES];
}
- (void)documentSortedNodesDidChange:(NSNotification *)aNotif
{
[self documentShowsInfoDidChange:nil];
[self documentShowsThumbnailsDidChange:nil];
if(![self activeNode]) [self setActiveNode:[[[[self activeDocument] node] resourceAdapter] sortedViewableNodeFirst:YES] forward:YES];
else [self _updateNodeIndex];
}
- (void)documentNodeDisplayNameDidChange:(NSNotification *)aNotif
{
NSParameterAssert(aNotif);
PGNode *const node = [[aNotif userInfo] objectForKey:PGDocumentNodeKey];
if([self activeNode] == node || [[self activeNode] parentNode] == node) [self _updateInfoPanelText]; // The parent may be displayed too, depending.
}
- (void)documentNodeIsViewableDidChange:(NSNotification *)aNotif
{
PGNode *const node = aNotif ? [[aNotif userInfo] objectForKey:PGDocumentNodeKey] : [self activeNode];
if(![self activeNode]) {
if([node isViewable]) [self setActiveNode:node forward:YES];
} else if([self activeNode] == node) {
if(![node isViewable] && ![self tryToGoForward:YES allowAlerts:NO] && ![self tryToGoForward:NO allowAlerts:NO]) [self setActiveNode:[[[[self activeDocument] node] resourceAdapter] sortedViewableNodeFirst:YES] forward:YES];
}
if(aNotif) {
[self documentShowsInfoDidChange:nil];
[self documentShowsThumbnailsDidChange:nil];
[self _updateNodeIndex];
}
}
- (void)documentBaseOrientationDidChange:(NSNotification *)aNotif
{
PGOrientation const o = [[[self activeNode] resourceAdapter] orientationWithBase:YES];
[_imageView setImageRep:[_imageView rep] orientation:o size:[self _sizeForImageRep:[_imageView rep] orientation:o]];
}
#pragma mark -
- (void)documentShowsInfoDidChange:(NSNotification *)aNotif
{
if([self shouldShowInfo]) {
[[_infoPanel content] setCount:[[[[self activeDocument] node] resourceAdapter] viewableNodeCount]];
[_infoPanel displayOverWindow:[self window]];
} else [_infoPanel fadeOut];
}
- (void)documentShowsThumbnailsDidChange:(NSNotification *)aNotif
{
if([PGThumbnailController shouldShowThumbnailsForDocument:[self activeDocument]]) {
if(_thumbnailController) return;
_thumbnailController = [[PGThumbnailController alloc] init];
NSDisableScreenUpdates();
[_thumbnailController setDisplayController:self];
[self thumbnailControllerContentInsetDidChange:nil];
NSEnableScreenUpdates();
[_thumbnailController PG_addObserver:self selector:@selector(thumbnailControllerContentInsetDidChange:) name:PGThumbnailControllerContentInsetDidChangeNotification];
} else {
[_thumbnailController PG_removeObserver:self name:PGThumbnailControllerContentInsetDidChangeNotification];
[_thumbnailController fadeOut];
[_thumbnailController release];
_thumbnailController = nil;
[self thumbnailControllerContentInsetDidChange:nil];
}
}
- (void)documentReadingDirectionDidChange:(NSNotification *)aNotif
{
if(![self activeDocument]) return;
BOOL const ltr = [[self activeDocument] readingDirection] == PGReadingDirectionLeftToRight;
PGRectCorner const corner = ltr ? PGMinXMinYCorner : PGMaxXMinYCorner;
PGInset inset = PGZeroInset;
switch(corner) {
case PGMinXMinYCorner: inset.minY = [self findPanelShown] ? NSHeight([_findPanel frame]) : 0.0f; break;
case PGMaxXMinYCorner: inset.minX = [self findPanelShown] ? NSWidth([_findPanel frame]) : 0.0f; break;
}
if(_thumbnailController) inset = PGAddInsets(inset, [_thumbnailController contentInset]);
[_infoPanel setFrameInset:inset];
[[_infoPanel content] setOriginCorner:corner];
[_infoPanel updateFrameDisplay:YES];
[[[self activeDocument] pageMenu] update];
}
- (void)documentImageScaleDidChange:(NSNotification *)aNotif
{
[self _updateImageViewSizeAllowAnimation:[[[aNotif userInfo] objectForKey:PGPrefObjectAnimateKey] boolValue]];
}
- (void)documentAnimatesImagesDidChange:(NSNotification *)aNotif
{
[_imageView setAnimates:[[self activeDocument] animatesImages]];
}
- (void)documentTimerIntervalDidChange:(NSNotification *)aNotif
{
[self setTimerRunning:[self timerRunning]];
}
#pragma mark -
- (void)thumbnailControllerContentInsetDidChange:(NSNotification *)aNotif
{
NSDisableScreenUpdates();
PGInset inset = PGZeroInset;
NSSize minSize = PGWindowMinSize;
if(_thumbnailController) {
PGInset const thumbnailInset = [_thumbnailController contentInset];
inset = PGAddInsets(inset, thumbnailInset);
minSize.width += thumbnailInset.minX + thumbnailInset.maxX;
}
[clipView setBoundsInset:inset];
[clipView displayIfNeeded];
[_findPanel setFrameInset:inset];
[_graphicPanel setFrameInset:inset];
[self _updateImageViewSizeAllowAnimation:NO];
[self documentReadingDirectionDidChange:nil];
[_findPanel updateFrameDisplay:YES];
[_graphicPanel updateFrameDisplay:YES];
NSWindow *const w = [self window];
NSRect currentFrame = [w frame];
if(NSWidth(currentFrame) < minSize.width) {
currentFrame.size.width = minSize.width;
[w setFrame:currentFrame display:YES];
}
[w setMinSize:minSize];
NSEnableScreenUpdates();
}
- (void)prefControllerBackgroundPatternColorDidChange:(NSNotification *)aNotif;
{
[clipView setBackgroundColor:[[PGPreferenceWindowController sharedPrefController] backgroundPatternColor]];
}
#pragma mark -PGDisplayController(Private)
- (void)_setImageView:(PGImageView *)aView
{
if(aView == _imageView) return;
[_imageView unbind:@"antialiasWhenUpscaling"];
[_imageView unbind:@"usesRoundedCorners"];
[_imageView release];
_imageView = [aView retain];
[_imageView bind:@"antialiasWhenUpscaling" toObject:[NSUserDefaults standardUserDefaults] withKeyPath:PGAntialiasWhenUpscalingKey options:nil];
[self documentAnimatesImagesDidChange:nil];
}
- (BOOL)_setActiveNode:(PGNode *)aNode
{
if(aNode == _activeNode) return NO;
[_activeNode PG_removeObserver:self name:PGNodeLoadingDidProgressNotification];
[_activeNode PG_removeObserver:self name:PGNodeReadyForViewingNotification];
[_activeNode release];
_activeNode = [aNode retain];
[self _updateNodeIndex];
[self _updateInfoPanelText];
[self PG_postNotificationName:PGDisplayControllerActiveNodeDidChangeNotification];
return YES;
}
- (void)_readActiveNode
{
[self PG_cancelPreviousPerformRequestsWithSelector:@selector(showLoadingIndicator) object:nil];
if(!_activeNode) return [self nodeReadyForViewing:nil];
_reading = YES;
[self PG_performSelector:@selector(showLoadingIndicator) withObject:nil fireDate:nil interval:0.5f options:kNilOptions];
[_activeNode PG_addObserver:self selector:@selector(nodeLoadingDidProgress:) name:PGNodeLoadingDidProgressNotification];
[_activeNode PG_addObserver:self selector:@selector(nodeReadyForViewing:) name:PGNodeReadyForViewingNotification];
[_activeNode becomeViewed];
[self setTimerRunning:[self timerRunning]];
}
- (void)_readFinished
{
_reading = NO;
[self PG_cancelPreviousPerformRequestsWithSelector:@selector(showLoadingIndicator) object:nil];
[[_graphicPanel content] popGraphicsOfType:PGSingleImageGraphic]; // Hide most alerts.
[_loadingGraphic release];
_loadingGraphic = nil;
[self PG_postNotificationName:PGDisplayControllerActiveNodeWasReadNotification];
}
- (NSSize)_sizeForImageRep:(NSImageRep *)rep orientation:(PGOrientation)orientation
{
return [self _sizeForImageRep:rep orientation:orientation scaleMode:[[self activeDocument] imageScaleMode] factor:[[self activeDocument] imageScaleFactor]];
}
- (NSSize)_sizeForImageRep:(NSImageRep *)rep orientation:(PGOrientation)orientation scaleMode:(PGImageScaleMode)scaleMode factor:(float)factor
{
if(!rep) return NSZeroSize;
NSSize originalSize = NSMakeSize([rep pixelsWide], [rep pixelsHigh]);
if(orientation & PGRotated90CCW) {
CGFloat const w = originalSize.width;
originalSize.width = originalSize.height;
originalSize.height = w;
}
NSSize newSize = originalSize;
if(PGConstantFactorScale == scaleMode) {
newSize.width *= factor;
newSize.height *= factor;
} else {
PGImageScaleConstraint const constraint = [[[NSUserDefaults standardUserDefaults] objectForKey:PGImageScaleConstraintKey] unsignedIntegerValue];
BOOL const resIndependent = [[[self activeNode] resourceAdapter] isResolutionIndependent];
NSSize const minSize = constraint != PGUpscaleOnly || resIndependent ? NSZeroSize : newSize;
NSSize const maxSize = constraint != PGDownscaleOnly || resIndependent ? NSMakeSize(CGFLOAT_MAX, CGFLOAT_MAX) : newSize;
NSRect const bounds = [clipView insetBounds];
CGFloat scaleX = NSWidth(bounds) / round(newSize.width);
CGFloat scaleY = NSHeight(bounds) / round(newSize.height);
if(PGAutomaticScale == scaleMode) {
NSSize const scrollMax = [clipView maximumDistanceForScrollType:PGScrollByPage];
if(scaleX > scaleY) scaleX = scaleY = MAX(scaleY, MIN(scaleX, (floor(newSize.height * scaleX / scrollMax.height + 0.3f) * scrollMax.height) / newSize.height));
else if(scaleX < scaleY) scaleX = scaleY = MAX(scaleX, MIN(scaleY, (floor(newSize.width * scaleY / scrollMax.width + 0.3f) * scrollMax.width) / newSize.width));
} else if(PGViewFitScale == scaleMode) scaleX = scaleY = MIN(scaleX, scaleY);
newSize = PGConstrainSize(minSize, PGScaleSizeByXY(newSize, scaleX, scaleY), maxSize);
}
return PGIntegralSize(newSize);
}
- (void)_updateImageViewSizeAllowAnimation:(BOOL)flag
{
[_imageView setSize:[self _sizeForImageRep:[_imageView rep] orientation:[_imageView orientation]] allowAnimation:flag];
}
- (void)_updateNodeIndex
{
_displayImageIndex = [[[self activeNode] resourceAdapter] viewableNodeIndex];
[(PGInfoView *)[_infoPanel content] setIndex:_displayImageIndex];
[self synchronizeWindowTitleWithDocumentName];
}
- (void)_updateInfoPanelText
{
NSString *text = nil;
PGNode *const node = [self activeNode];
if(node) {
text = [[node identifier] displayName];
PGNode *const parent = [node parentNode];
if([parent parentNode]) text = [NSString stringWithFormat:@"%@ %C %@", [[parent identifier] displayName], 0x25B8, text];
} else text = NSLocalizedString(@"No image", @"Label for when no image is being displayed in the window.");
[[_infoPanel content] setStringValue:text];
}
- (void)_setCopyAsDesktopPicturePanelDidEnd:(NSSavePanel *)savePanel returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo
{
if(NSFileHandlingPanelOKButton != returnCode) return;
NSURL *const URL = [[savePanel filename] PG_fileURL];
[[[[self activeNode] resourceAdapter] data] writeToURL:URL atomically:NO];
if(![[NSScreen PG_mainScreen] PG_setDesktopImageURL:URL]) NSBeep();
}
- (void)_offerToOpenBookmarkAlertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode bookmark:(PGBookmark *)bookmark
{
[bookmark autorelease];
if(NSAlertFirstButtonReturn == returnCode) [[self activeDocument] openBookmark:bookmark];
}
#pragma mark -NSWindowController
- (IBAction)showWindow:(id)sender
{
[super showWindow:sender];
[self documentReadingDirectionDidChange:nil];
if([self shouldShowInfo]) [_infoPanel displayOverWindow:[self window]];
[_thumbnailController display];
}
#pragma mark -
- (void)windowDidLoad
{
[super windowDidLoad];
[passwordView retain];
[[self window] useOptimizedDrawing:YES];
[[self window] setMinSize:PGWindowMinSize];
NSImage *const cursorImage = [NSImage imageNamed:@"Cursor-Hand-Pointing"];
[clipView setAcceptsFirstResponder:YES];
[clipView setCursor:cursorImage ? [[[NSCursor alloc] initWithImage:cursorImage hotSpot:NSMakePoint(5.0f, 0.0f)] autorelease] : [NSCursor pointingHandCursor]];
[clipView setPostsFrameChangedNotifications:YES];
[clipView PG_addObserver:self selector:@selector(clipViewFrameDidChange:) name:NSViewFrameDidChangeNotification];
_findPanel = [[PGBezelPanel alloc] initWithContentView:findView];
[_findPanel setInitialFirstResponder:searchField];
[_findPanel setDelegate:self];
[_findPanel setAcceptsEvents:YES];
[_findPanel setCanBecomeKey:YES];
[self prefControllerBackgroundPatternColorDidChange:nil];
}
- (void)synchronizeWindowTitleWithDocumentName
{
PGDisplayableIdentifier *const identifier = [[[self activeDocument] node] identifier];
NSURL *const URL = [identifier URL];
if([identifier isFileIdentifier]) {
NSString *const path = [identifier isFileIdentifier] ? [URL path] : nil;
[[self window] setRepresentedFilename:path ? path : @""];
} else {
[[self window] setRepresentedURL:URL];
NSButton *const docButton = [[self window] standardWindowButton:NSWindowDocumentIconButton];
NSImage *const image = [[[identifier icon] copy] autorelease];
[image setSize:[docButton bounds].size];
[image recache];
[docButton setImage:image];
}
NSUInteger const count = [[[[self activeDocument] node] resourceAdapter] viewableNodeCount];
NSString *const title = [identifier displayName];
NSString *const titleDetails = count > 1 ? [NSString stringWithFormat:@" (%lu/%lu)", (unsigned long)_displayImageIndex + 1, (unsigned long)count] : @"";
[[self window] setTitle:title ? [title stringByAppendingString:titleDetails] : @""];
NSMutableAttributedString *const menuLabel = [[[identifier attributedStringWithAncestory:NO] mutableCopy] autorelease];
[[menuLabel mutableString] appendString:titleDetails];
[[[PGDocumentController sharedDocumentController] windowsMenuItemForDocument:[self activeDocument]] setAttributedTitle:menuLabel];
}
- (void)close
{
[[self activeDocument] close];
}
#pragma mark -NSResponder
- (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType
{
return ![returnType length] && [self writeSelectionToPasteboard:nil types:[NSArray arrayWithObject:sendType]] ? self : [super validRequestorForSendType:sendType returnType:returnType];
}