forked from ttscoff/nv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AppController.m
executable file
·3184 lines (2658 loc) · 115 KB
/
AppController.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 (c) 2010, Zachary Schneirov. 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 Notational Velocity nor the names of its contributors may be used to endorse
or promote products derived from this software without specific prior written permission. */
//ET NV4
//#import "NVTransparentScroller.h"
#import "NSTextFinder.h"
#import "AppController.h"
#import "NoteObject.h"
#import "GlobalPrefs.h"
#import "AlienNoteImporter.h"
#import "AppController_Importing.h"
#import "NotationPrefs.h"
#import "PrefsWindowController.h"
#import "NoteAttributeColumn.h"
#import "NotationSyncServiceManager.h"
#import "NotationDirectoryManager.h"
#import "NotationFileManager.h"
#import "NSString_NV.h"
#import "NSFileManager_NV.h"
#import "EncodingsManager.h"
#import "ExporterManager.h"
#import "ExternalEditorListController.h"
#import "NSData_transformations.h"
#import "BufferUtils.h"
#import "LinkingEditor.h"
#import "EmptyView.h"
#import "DualField.h"
#import "TitlebarButton.h"
#import "RBSplitView/RBSplitView.h"
#import "AugmentedScrollView.h"
#import "BookmarksController.h"
#import "SyncSessionController.h"
#import "MultiplePageView.h"
#import "InvocationRecorder.h"
#import "LinearDividerShader.h"
#import "SecureTextEntryManager.h"
#import "TagEditingManager.h"
#import "NotesTableHeaderCell.h"
#import "DFView.h"
#import "StatusItemView.h"
#import "ETContentView.h"
#import "PreviewController.h"
#define NSApplicationPresentationAutoHideMenuBar (1 << 2)
#define NSApplicationPresentationHideMenuBar (1 << 3)
//#define NSApplicationPresentationAutoHideDock (1 << 0)
#define NSApplicationPresentationHideDock (1 << 1)
//#define NSApplicationActivationPolicyAccessory
//#define NSTextViewChangedNotification @"TextView has changed contents"
//#define kDefaultMarkupPreviewMode @"markupPreviewMode"
NSWindow *normalWindow;
int ModFlagger;
int popped;
BOOL splitViewAwoke;
BOOL isEd;
@implementation AppController
//an instance of this class is designated in the nib as the delegate of the window, nstextfield and two nstextviews
/*
+ (void)initialize
{
NSDictionary *appDefaults = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:MultiMarkdownPreview] forKey:kDefaultMarkupPreviewMode];
[[NSUserDefaults standardUserDefaults] registerDefaults:appDefaults];
} // initialize*/
- (id)init {
if ([super init]) {
splitViewAwoke = NO;
windowUndoManager = [[NSUndoManager alloc] init];
previewController = [[PreviewController alloc] init];
[[NSNotificationCenter defaultCenter] addObserver:previewController selector:@selector(requestPreviewUpdate:) name:@"TextView has changed contents" object:self];
// Setup URL Handling
NSAppleEventManager *appleEventManager = [NSAppleEventManager sharedAppleEventManager];
[appleEventManager setEventHandler:self andSelector:@selector(handleGetURLEvent:withReplyEvent:) forEventClass:kInternetEventClass andEventID:kAEGetURL];
// dividerShader = [[LinearDividerShader alloc] initWithStartColor:[NSColor colorWithCalibratedWhite:0.988 alpha:1.0]
// endColor:[NSColor colorWithCalibratedWhite:0.875 alpha:1.0]];
dividerShader = [[[LinearDividerShader alloc] initWithBaseColors:self] retain];
isCreatingANote = isFilteringFromTyping = typedStringIsCached = NO;
typedString = @"";
}
return self;
}
- (void)awakeFromNib {
if (![[[NSUserDefaults standardUserDefaults] stringForKey:@"HideDockIcon"] isEqualToString:@"Show Dock Icon"]){
if((IsSnowLeopardOrLater)&&([[NSApplication sharedApplication] respondsToSelector: @selector(setActivationPolicy:)])) {
enum {NSApplicationActivationPolicyRegular};
[[NSApplication sharedApplication] setActivationPolicy:NSApplicationActivationPolicyRegular];
}else {
ProcessSerialNumber psn = { 0, kCurrentProcess };
OSStatus returnCode = TransformProcessType(&psn, kProcessTransformToForegroundApplication);
if( returnCode != 0) {
NSLog(@"Could not bring the application to front. Error %d", returnCode);
}
}
}
theFieldEditor = [[[NSTextView alloc]initWithFrame:[window frame]] retain];
[theFieldEditor setFieldEditor:YES];
[self updateFieldAttributes];
[NSApp setDelegate:self];
[window setDelegate:self];
//ElasticThreads>> set up the rbsplitview programatically to remove dependency on IBPlugin
splitView = [[[RBSplitView alloc] initWithFrame:[mainView frame] andSubviews:2] retain];
[splitView setAutosaveName:@"centralSplitView" recursively:NO];
[splitView setDelegate:self];
NSImage *image = [[[NSImage alloc] initWithSize:NSMakeSize(1.0,1.0)] autorelease];
[image lockFocus];
[[NSColor clearColor] set];
NSRectFill(NSMakeRect(0.0,0.0,1.0,1.0));
[image unlockFocus];
[image setFlipped:YES];
[splitView setDivider:image];
[splitView setDividerThickness:8.75f];
[splitView setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)];
[mainView addSubview:splitView];
//[mainView setNextResponder:field];//<<--
[splitView setNextKeyView:notesTableView];
notesSubview = [[splitView subviewAtPosition:0] retain];
[notesSubview setMinDimension: 80.0
andMaxDimension:600.0];
[notesSubview setCanCollapse:YES];
[notesSubview setAutoresizesSubviews:YES];
[notesSubview addSubview:notesScrollView];
splitSubview = [[splitView subviewAtPosition:1] retain];
[notesScrollView setFrame:[notesSubview frame]];
[notesScrollView setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)];
[splitSubview setMinDimension:1 andMaxDimension:0];
[splitSubview setCanCollapse:NO];
[splitSubview setAutoresizesSubviews:YES];
[splitSubview addSubview:textScrollView];
[textScrollView setFrame:[splitSubview frame]];
[textScrollView setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)];
[mainView setNeedsDisplay:YES];
[splitView adjustSubviews];
[splitView needsDisplay];
splitViewAwoke = YES;
[notesScrollView setBorderType:NSNoBorder];
[textScrollView setBorderType:NSNoBorder];
prefsController = [GlobalPrefs defaultPrefs];
[NSColor setIgnoresAlpha:NO];
//For ElasticThreads' fullscreen implementation. delete the next line of code and uncomment the following the block to undo
[self setDualFieldInToolbar];
/*
NSView *dualSV = [field superview];
dualFieldItem = [[NSToolbarItem alloc] initWithItemIdentifier:@"DualField"];
//[[dualSV superview] setFrameSize:NSMakeSize([[dualSV superview] frame].size.width, [[dualSV superview] frame].size.height -1)];
[dualFieldItem setView:dualSV];
[dualFieldItem setMaxSize:NSMakeSize(FLT_MAX, [dualSV frame].size.height)];
[dualFieldItem setMinSize:NSMakeSize(50.0f, [dualSV frame].size.height)];
[dualFieldItem setLabel:NSLocalizedString(@"Search or Create", @"placeholder text in search/create field")];
toolbar = [[NSToolbar alloc] initWithIdentifier:@"NVToolbar"];
[toolbar setAllowsUserCustomization:NO];
[toolbar setAutosavesConfiguration:NO];
[toolbar setDisplayMode:NSToolbarDisplayModeIconOnly];
// [toolbar setSizeMode:NSToolbarSizeModeRegular];
[toolbar setShowsBaselineSeparator:YES];
[toolbar setVisible:![[NSUserDefaults standardUserDefaults] boolForKey:@"ToolbarHidden"]];
[toolbar setDelegate:self];
[window setToolbar:toolbar];
[window setShowsToolbarButton:NO];
titleBarButton = [[TitlebarButton alloc] initWithFrame:NSMakeRect(0, 0, 17.0, 17.0) pullsDown:YES];
[titleBarButton addToWindow:window];
*/
[notesTableView setDelegate:self];
[field setDelegate:self];
[textView setDelegate:self];
//set up temporary FastListDataSource containing false visible notes
//this will not make a difference
[window useOptimizedDrawing:YES];
//[window makeKeyAndOrderFront:self];
//[self setEmptyViewState:YES];
// Create elasticthreads' NSStatusItem.
if ( [[NSUserDefaults standardUserDefaults] boolForKey:@"StatusBarItem"]) {
float width = 25.0f;
CGFloat height = [[NSStatusBar systemStatusBar] thickness];
NSRect viewFrame = NSMakeRect(0.0f, 0.0f, width, height);
statusItem = [[[NSStatusBar systemStatusBar] statusItemWithLength:width] retain];
cView = [[[StatusItemView alloc] initWithFrame:viewFrame controller:self] autorelease];
[statusItem setView:cView];
}
currentPreviewMode = [[NSUserDefaults standardUserDefaults] integerForKey:@"markupPreviewMode"];
if (currentPreviewMode == MarkdownPreview) {
[multiMarkdownPreview setState:NSOnState];
} else if (currentPreviewMode == MultiMarkdownPreview) {
[multiMarkdownPreview setState:NSOnState];
} else if (currentPreviewMode == TextilePreview) {
[textilePreview setState:NSOnState];
}
[NSApp setServicesProvider:self];
outletObjectAwoke(self);
}
//really need make AppController a subclass of NSWindowController and stick this junk in windowDidLoad
- (void)setupViewsAfterAppAwakened {
static BOOL awakenedViews = NO;
isEd = NO;
if (!awakenedViews) {
//NSLog(@"all (hopefully relevant) views awakend!");
[self _configureDividerForCurrentLayout];
[splitView restoreState:YES];
if ([notesSubview dimension]<200.0) {
if ([splitView isVertical]) { ///vertical means "Horiz layout"/notes list is to the left of the note body
if (([splitView frame].size.width < 600.0) && ([splitView frame].size.width - 400 > [notesSubview dimension])) {
[notesSubview setDimension:[splitView frame].size.width-400.0];
}else if ([splitView frame].size.width >= 600.0) {
[notesSubview setDimension:200.0];
}
}else{
if (([splitView frame].size.height < 600.0) && ([splitView frame].size.height - 400 > [notesSubview dimension])) {
[notesSubview setDimension:[splitView frame].size.height-450.0];
}else if ([splitView frame].size.height >= 600.0){
[notesSubview setDimension:150.0];
}
}
}
[splitView adjustSubviews];
[splitSubview addSubview:editorStatusView positioned:NSWindowAbove relativeTo:splitSubview];
[editorStatusView setFrame:[textScrollView frame]];
[notesTableView restoreColumns];
[field setNextKeyView:textView];
[textView setNextKeyView:field];
[window setAutorecalculatesKeyViewLoop:NO];
[self updateRTL];
[self setMaxNoteBodyWidth];
[self setEmptyViewState:YES];
ModFlagger = 0;
popped = 0;
userScheme = [[NSUserDefaults standardUserDefaults] integerForKey:@"ColorScheme"];
if (userScheme==0) {
[self setBWColorScheme:self];
}else if (userScheme==1) {
[self setLCColorScheme:self];
}else if (userScheme==2) {
[self setUserColorScheme:self];
}
//this is necessary on 10.3; keep just in case
[splitView display];
if (![NSApp isActive]) {
[NSApp activateIgnoringOtherApps:YES];
}
awakenedViews = YES;
}
}
//what a hack
void outletObjectAwoke(id sender) {
static NSMutableSet *awokenOutlets = nil;
if (!awokenOutlets) awokenOutlets = [[NSMutableSet alloc] initWithCapacity:5];
[awokenOutlets addObject:sender];
AppController* appDelegate = (AppController*)[NSApp delegate];
if ((appDelegate) && ([awokenOutlets containsObject:appDelegate] &&
[awokenOutlets containsObject:appDelegate->notesTableView] &&
[awokenOutlets containsObject:appDelegate->textView] &&
[awokenOutlets containsObject:appDelegate->editorStatusView]) &&(splitViewAwoke)) {
// && [awokenOutlets containsObject:appDelegate->splitView])
[appDelegate setupViewsAfterAppAwakened];
}
}
- (void)runDelayedUIActionsAfterLaunch {
[[prefsController bookmarksController] setAppController:self];
[[prefsController bookmarksController] restoreWindowFromSave];
[[prefsController bookmarksController] updateBookmarksUI];
[self updateNoteMenus];
[textView setupFontMenu];
[prefsController registerAppActivationKeystrokeWithTarget:self selector:@selector(toggleNVActivation:)];
[notationController updateLabelConnectionsAfterDecoding];
[notationController checkIfNotationIsTrashed];
[[SecureTextEntryManager sharedInstance] checkForIncompatibleApps];
//connect sparkle programmatically to avoid loading its framework at nib awake;
if (!NSClassFromString(@"SUUpdater")) {
NSString *frameworkPath = [[[NSBundle bundleForClass:[self class]] privateFrameworksPath] stringByAppendingPathComponent:@"Sparkle.framework"];
if ([[NSBundle bundleWithPath:frameworkPath] load]) {
id updater = [NSClassFromString(@"SUUpdater") performSelector:@selector(sharedUpdater)];
[sparkleUpdateItem setTarget:updater];
[sparkleUpdateItem setAction:@selector(checkForUpdates:)];
NSMenuItem *siSparkle = [statBarMenu itemWithTag:902];
[siSparkle setTarget:updater];
[siSparkle setAction:@selector(checkForUpdates:)];
if (![[prefsController notationPrefs] firstTimeUsed]) {
//don't do anything automatically on the first launch; afterwards, check every 4 days, as specified in Info.plist
SEL checksSEL = @selector(setAutomaticallyChecksForUpdates:);
[updater methodForSelector:checksSEL](updater, checksSEL, YES);
}
} else {
NSLog(@"Could not load %@!", frameworkPath);
}
}
// add elasticthreads' menuitems
NSMenuItem *theMenuItem = [[[NSMenuItem alloc] init] autorelease];
[theMenuItem setTarget:self];
NSMenu *notesMenu = [[[NSApp mainMenu] itemWithTag:NOTES_MENU_ID] submenu];
theMenuItem = [theMenuItem copy];
// [statBarMenu insertItem:theMenuItem atIndex:4];
[theMenuItem release];
//theMenuItem = [[viewMenu itemWithTag:801] copy];
//[statBarMenu insertItem:theMenuItem atIndex:11];
//[theMenuItem release];
if(IsLeopardOrLater){
NSMenu *viewMenu = [[[NSApp mainMenu] itemWithTag:VIEW_MENU_ID] submenu];
theMenuItem = [[[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"Toggle Fullscreen Mode",@"menu item title for toggling fs")
action:@selector(toggleFullscreen:) keyEquivalent:@"F"] autorelease];
[theMenuItem setTarget:self];
[viewMenu insertItem:theMenuItem atIndex:1];
theMenuItem = [theMenuItem copy];
[statBarMenu insertItem:theMenuItem atIndex:11];
[theMenuItem release];
}
if (![prefsController showWordCount]) {
[wordCounter setHidden:NO];
}else {
[wordCounter setHidden:YES];
}
//
}
- (void)applicationDidFinishLaunching:(NSNotification*)aNote {
//on tiger dualfield is often not ready to add tracking tracks until this point:
[field setTrackingRect];
NSDate *before = [NSDate date];
prefsWindowController = [[PrefsWindowController alloc] init];
OSStatus err = noErr;
NotationController *newNotation = nil;
NSData *aliasData = [prefsController aliasDataForDefaultDirectory];
NSString *subMessage = @"";
//if the option key is depressed, go straight to picking a new notes folder location
if (kCGEventFlagMaskAlternate == (CGEventSourceFlagsState(kCGEventSourceStateCombinedSessionState) & NSDeviceIndependentModifierFlagsMask)) {
goto showOpenPanel;
}
if (aliasData) {
newNotation = [[NotationController alloc] initWithAliasData:aliasData error:&err];
subMessage = NSLocalizedString(@"Please choose a different folder in which to store your notes.",nil);
} else {
newNotation = [[NotationController alloc] initWithDefaultDirectoryReturningError:&err];
subMessage = NSLocalizedString(@"Please choose a folder in which your notes will be stored.",nil);
}
//no need to display an alert if the error wasn't real
if (err == kPassCanceledErr)
goto showOpenPanel;
NSString *location = (aliasData ? [[NSFileManager defaultManager] pathCopiedFromAliasData:aliasData] : NSLocalizedString(@"your Application Support directory",nil));
if (!location) { //fscopyaliasinfo sucks
FSRef locationRef;
if ([aliasData fsRefAsAlias:&locationRef] && LSCopyDisplayNameForRef(&locationRef, (CFStringRef*)&location) == noErr) {
[location autorelease];
} else {
location = NSLocalizedString(@"its current location",nil);
}
}
while (!newNotation) {
location = [location stringByAbbreviatingWithTildeInPath];
NSString *reason = [NSString reasonStringFromCarbonFSError:err];
if (NSRunAlertPanel([NSString stringWithFormat:NSLocalizedString(@"Unable to initialize notes database in \n%@ because %@.",nil), location, reason],
subMessage, NSLocalizedString(@"Choose another folder",nil),NSLocalizedString(@"Quit",nil),NULL) == NSAlertDefaultReturn) {
//show nsopenpanel, defaulting to current default notes dir
FSRef notesDirectoryRef;
showOpenPanel:
if (![prefsWindowController getNewNotesRefFromOpenPanel:¬esDirectoryRef returnedPath:&location]) {
//they cancelled the open panel, or it was unable to get the path/FSRef of the file
goto terminateApp;
} else if ((newNotation = [[NotationController alloc] initWithDirectoryRef:¬esDirectoryRef error:&err])) {
//have to make sure alias data is saved from setNotationController
[newNotation setAliasNeedsUpdating:YES];
break;
}
} else {
goto terminateApp;
}
}
[self setNotationController:newNotation];
[newNotation release];
NSLog(@"load time: %g, ",[[NSDate date] timeIntervalSinceDate:before]);
// NSLog(@"version: %s", PRODUCT_NAME);
//import old database(s) here if necessary
[AlienNoteImporter importBlorOrHelpFilesIfNecessaryIntoNotation:newNotation];
if (pathsToOpenOnLaunch) {
[notationController openFiles:[pathsToOpenOnLaunch autorelease]];
pathsToOpenOnLaunch = nil;
}
if (URLToInterpretOnLaunch) {
[self interpretNVURL:[URLToInterpretOnLaunch autorelease]];
URLToInterpretOnLaunch = nil;
}
//tell us..
[prefsController registerWithTarget:self forChangesInSettings:
@selector(setAliasDataForDefaultDirectory:sender:), //when someone wants to load a new database
@selector(setSortedTableColumnKey:reversed:sender:), //when sorting prefs changed
@selector(setNoteBodyFont:sender:), //when to tell notationcontroller to restyle its notes
@selector(setForegroundTextColor:sender:), //ditto
@selector(setBackgroundTextColor:sender:), //ditto
@selector(setTableFontSize:sender:), //when to tell notationcontroller to regenerate the (now potentially too-short) note-body previews
@selector(addTableColumn:sender:), //ditto
@selector(removeTableColumn:sender:), //ditto
@selector(setTableColumnsShowPreview:sender:), //when to tell notationcontroller to generate or disable note-body previews
@selector(setConfirmNoteDeletion:sender:), //whether "delete note" should have an ellipsis
@selector(setAutoCompleteSearches:sender:), nil]; //when to tell notationcontroller to build its title-prefix connections
[self performSelector:@selector(runDelayedUIActionsAfterLaunch) withObject:nil afterDelay:0.0];
return;
terminateApp:
[NSApp terminate:self];
}
- (void)handleGetURLEvent:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent {
NSURL *fullURL = [NSURL URLWithString:[[event paramDescriptorForKeyword:keyDirectObject] stringValue]];
if (notationController) {
if (![self interpretNVURL:fullURL])
NSBeep();
} else {
URLToInterpretOnLaunch = [fullURL retain];
}
}
- (void)setNotationController:(NotationController*)newNotation {
if (newNotation) {
if (notationController) {
[notationController endDeletionManagerIfNecessary];
[notationController stopSyncServices];
[[NSNotificationCenter defaultCenter] removeObserver:self name:SyncSessionsChangedVisibleStatusNotification
object:[notationController syncSessionController]];
[notationController stopFileNotifications];
if ([notationController flushAllNoteChanges])
[notationController closeJournal];
}
NotationController *oldNotation = notationController;
notationController = [newNotation retain];
if (oldNotation) {
[notesTableView abortEditing];
[prefsController setLastSearchString:[self fieldSearchString] selectedNote:currentNote
scrollOffsetForTableView:notesTableView sender:self];
//if we already had a notation, appController should already be bookmarksController's delegate
[[prefsController bookmarksController] performSelector:@selector(updateBookmarksUI) withObject:nil afterDelay:0.0];
}
[notationController setSortColumn:[notesTableView noteAttributeColumnForIdentifier:[prefsController sortedTableColumnKey]]];
[notesTableView setDataSource:[notationController notesListDataSource]];
[notesTableView setLabelsListSource:[notationController labelsListDataSource]];
[notationController setDelegate:self];
//allow resolution of UUIDs to NoteObjects from saved searches
[[prefsController bookmarksController] setDataSource:notationController];
//update the list using the new notation and saved settings
[self restoreListStateUsingPreferences];
//window's undomanager could be referencing actions from the old notation object
[[window undoManager] removeAllActions];
[notationController setUndoManager:[window undoManager]];
if ([notationController aliasNeedsUpdating]) {
[prefsController setAliasDataForDefaultDirectory:[notationController aliasDataForNoteDirectory] sender:self];
}
if ([prefsController tableColumnsShowPreview] || [prefsController horizontalLayout]) {
[self _forceRegeneratePreviewsForTitleColumn];
[notesTableView setNeedsDisplay:YES];
}
[titleBarButton setMenu:[[notationController syncSessionController] syncStatusMenu]];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(syncSessionsChangedVisibleStatus:)
name:SyncSessionsChangedVisibleStatusNotification
object:[notationController syncSessionController]];
[notationController performSelector:@selector(startSyncServices) withObject:nil afterDelay:0.0];
if ([[notationController notationPrefs] secureTextEntry]) {
[[SecureTextEntryManager sharedInstance] enableSecureTextEntry];
} else {
[[SecureTextEntryManager sharedInstance] disableSecureTextEntry];
}
[field selectText:nil];
[oldNotation autorelease];
}
}
- (BOOL)applicationOpenUntitledFile:(NSApplication *)sender {
if (![prefsController quitWhenClosingWindow]) {
[self bringFocusToControlField:nil];
return YES;
}
return NO;
}
- (NSToolbarItem *)toolbar:(NSToolbar *)toolbar itemForItemIdentifier:(NSString *)itemIdentifier willBeInsertedIntoToolbar:(BOOL)flag {
return [itemIdentifier isEqualToString:@"DualField"] ? dualFieldItem : nil;
}
- (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar*)theToolbar {
return [self toolbarDefaultItemIdentifiers:theToolbar];
}
- (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar*)theToolbar {
return [NSArray arrayWithObject:@"DualField"];
}
- (BOOL)validateMenuItem:(NSMenuItem*)menuItem {
SEL selector = [menuItem action];
int numberSelected = [notesTableView numberOfSelectedRows];
NSInteger tag = [menuItem tag];
if ((tag == TextilePreview) || (tag == MarkdownPreview) || (tag == MultiMarkdownPreview)) {
// Allow only one Preview mode to be selected at every one time
[menuItem setState:((tag == currentPreviewMode) ? NSOnState : NSOffState)];
return YES;
} else if (selector == @selector(printNote:) ||
selector == @selector(deleteNote:) ||
selector == @selector(exportNote:) ||
selector == @selector(tagNote:)) {
return (numberSelected > 0);
} else if (selector == @selector(renameNote:) ||
selector == @selector(copyNoteLink:)) {
return (numberSelected == 1);
} else if (selector == @selector(revealNote:)) {
return (numberSelected == 1) && [notationController currentNoteStorageFormat] != SingleDatabaseFormat;
} else if (selector == @selector(openFileInEditor:)) {
NSString *defApp = [prefsController textEditor];
if (![[self getTxtAppList] containsObject:defApp]) {
defApp = @"Default";
[prefsController setTextEditor:@"Default"];
}
if (([defApp isEqualToString:@"Default"])||(![[NSFileManager defaultManager] fileExistsAtPath:[[NSWorkspace sharedWorkspace] fullPathForApplication:defApp]])) {
if (![defApp isEqualToString:@"Default"]) {
[prefsController setTextEditor:@"Default"];
}
CFStringRef cfFormat = (CFStringRef)noteFormat;
defApp = [(NSString *)LSCopyDefaultRoleHandlerForContentType(cfFormat,kLSRolesEditor) autorelease];
defApp = [[NSWorkspace sharedWorkspace] absolutePathForAppBundleWithIdentifier: defApp];
defApp = [[NSFileManager defaultManager] displayNameAtPath: defApp];
}
if ((!defApp)||([defApp isEqualToString:@"Safari"])) {
defApp = @"TextEdit";
}
[menuItem setTitle:[@"Open Note in " stringByAppendingString:defApp]];
return (numberSelected == 1) && [notationController currentNoteStorageFormat] != SingleDatabaseFormat;
} else if (selector == @selector(toggleCollapse:)) {
if ([notesSubview isCollapsed]) {
[menuItem setTitle:@"Expand Notes List"];
}else{
[menuItem setTitle:@"Collapse Notes List"];
if (!currentNote){
return NO;
}
}
} else if (selector == @selector(fixFileEncoding:)) {
return (currentNote != nil && storageFormatOfNote(currentNote) == PlainTextFormat && ![currentNote contentsWere7Bit]);
} else if (selector == @selector(editNoteExternally:)) {
return (numberSelected > 0) && [[menuItem representedObject] canEditAllNotes:[notationController notesAtIndexes:[notesTableView selectedRowIndexes]]];
}
return YES;
}
- (void)updateNoteMenus {
NSMenu *notesMenu = [[[NSApp mainMenu] itemWithTag:NOTES_MENU_ID] submenu];
int menuIndex = [notesMenu indexOfItemWithTarget:self andAction:@selector(deleteNote:)];
NSMenuItem *deleteItem = nil;
if (menuIndex > -1 && (deleteItem = [notesMenu itemAtIndex:menuIndex])) {
NSString *trailingQualifier = [prefsController confirmNoteDeletion] ? NSLocalizedString(@"...", @"ellipsis character") : @"";
[deleteItem setTitle:[NSString stringWithFormat:@"%@%@",
NSLocalizedString(@"Delete", nil), trailingQualifier]];
}
[notesMenu setSubmenu:[[ExternalEditorListController sharedInstance] addEditNotesMenu] forItem:[notesMenu itemWithTag:88]];
NSMenu *viewMenu = [[[NSApp mainMenu] itemWithTag:VIEW_MENU_ID] submenu];
menuIndex = [viewMenu indexOfItemWithTarget:notesTableView andAction:@selector(toggleNoteBodyPreviews:)];
NSMenuItem *bodyPreviewItem = nil;
if (menuIndex > -1 && (bodyPreviewItem = [viewMenu itemAtIndex:menuIndex])) {
[bodyPreviewItem setTitle: [prefsController tableColumnsShowPreview] ?
NSLocalizedString(@"Hide Note Previews in Title", @"menu item in the View menu to turn off note-body previews in the Title column") :
NSLocalizedString(@"Show Note Previews in Title", @"menu item in the View menu to turn on note-body previews in the Title column")];
}
menuIndex = [viewMenu indexOfItemWithTarget:self andAction:@selector(switchViewLayout:)];
NSMenuItem *switchLayoutItem = nil;
NSString *switchStr = [prefsController horizontalLayout] ?
NSLocalizedString(@"Switch to Vertical Layout", @"title of alternate view layout menu item") :
NSLocalizedString(@"Switch to Horizontal Layout", @"title of view layout menu item");
if (menuIndex > -1 && (switchLayoutItem = [viewMenu itemAtIndex:menuIndex])) {
[switchLayoutItem setTitle:switchStr];
}
// add to elasticthreads' statusbar menu
menuIndex = [statBarMenu indexOfItemWithTarget:self andAction:@selector(switchViewLayout:)];
if (menuIndex>-1) {
NSMenuItem *anxItem = [statBarMenu itemAtIndex:menuIndex];
[anxItem setTitle:switchStr];
}
}
- (void)_forceRegeneratePreviewsForTitleColumn {
[notationController regeneratePreviewsForColumn:[notesTableView noteAttributeColumnForIdentifier:NoteTitleColumnString]
visibleFilteredRows:[notesTableView rowsInRect:[notesTableView visibleRect]] forceUpdate:YES];
}
- (void)_configureDividerForCurrentLayout {
isEd = NO;
BOOL horiz = [prefsController horizontalLayout];
if ([notesSubview isCollapsed]) {
[notesSubview expand];
[splitView setVertical:horiz];
[splitView setDividerThickness:7.0f];
NSSize size = [notesSubview frame].size;
[notesScrollView setFrame: NSMakeRect(0, 0, size.width, size.height + 1)];
[notesSubview collapse];
}else {
[splitView setVertical:horiz];
if (!verticalDividerImg && [splitView divider]) verticalDividerImg = [[splitView divider] retain];
[splitView setDivider: verticalDividerImg];
[splitView setDividerThickness:8.75f];
NSSize size = [notesSubview frame].size;
[notesScrollView setFrame: horiz? NSMakeRect(0, 0, size.width, size.height) : NSMakeRect(0, 0, size.width, size.height + 1)];
if (![self dualFieldIsVisible]) {
[self setDualFieldIsVisible:YES];
}
}
if (horiz) {
[splitSubview setMinDimension:100.0 andMaxDimension:0.0];
}
}
- (IBAction)switchViewLayout:(id)sender {
if ([mainView isInFullScreenMode]) {
wasVert = YES;
}
ViewLocationContext ctx = [notesTableView viewingLocation];
ctx.pivotRowWasEdge = NO;
CGFloat colW = [notesSubview dimension];
if (![splitView isVertical]) {
colW += 30.0f;
}else{
colW -= 30.0f;
}
[prefsController setHorizontalLayout:![prefsController horizontalLayout] sender:self];
[notationController updateDateStringsIfNecessary];
[self _configureDividerForCurrentLayout];
// [notesTableView noteFirstVisibleRow];
[notesSubview setDimension:colW];
[notationController regenerateAllPreviews];
[splitView adjustSubviews];
[notesTableView setViewingLocation:ctx];
[notesTableView makeFirstPreviouslyVisibleRowVisibleIfNecessary];
[self updateNoteMenus];
[self setMaxNoteBodyWidth];
[notesTableView setBackgroundColor:backgrndColor];
[notesTableView setNeedsDisplay];
}
- (void)createFromSelection:(NSPasteboard *)pboard userData:(NSString *)userData error:(NSString **)error {
if (!notationController || ![self addNotesFromPasteboard:pboard]) {
*error = NSLocalizedString(@"Error: Couldn't create a note from the selection.", @"error message to set during a Service call when adding a note failed");
}
}
- (IBAction)renameNote:(id)sender {
if ([notesSubview isCollapsed]) {
[self toggleCollapse:sender];
}
//edit the first selected note
isEd = YES;
/* NSTextView *fieldEditor = (NSTextView *)[window fieldEditor:YES forObject:notesTableView];
NSColor *selCol = [NSColor colorWithCalibratedHue: 0.6
saturation: 0.25
brightness: 0.9
alpha: 0.27];
NSDictionary *colDict = [NSDictionary dictionaryWithObjectsAndKeys:[NSColor redColor], NSForegroundColorAttributeName, [NSColor blueColor], NSBackgroundColorAttributeName, nil];
[fieldEditor setSelectedTextAttributes:colDict];
[fieldEditor setTextColor:[NSColor greenColor]];
[fieldEditor setDrawsBackground:YES];
[fieldEditor setBackgroundColor:[NSColor blackColor]];
[fieldEditor setNeedsDisplay:YES];
*/
[notesTableView editRowAtColumnWithIdentifier:NoteTitleColumnString];
}
- (void)deleteAlertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo {
id retainedDeleteObj = (id)contextInfo;
if (returnCode == NSAlertDefaultReturn) {
//delete! nil-msgsnd-checking
//ensure that there are no pending edits in the tableview,
//lest editing end with the same field editor and a different selected note
//resulting in the renaming of notes in adjacent rows
[notesTableView abortEditing];
if ([retainedDeleteObj isKindOfClass:[NSArray class]]) {
[notationController removeNotes:retainedDeleteObj];
} else if ([retainedDeleteObj isKindOfClass:[NoteObject class]]) {
[notationController removeNote:retainedDeleteObj];
}
if (IsLeopardOrLater && [[alert suppressionButton] state] == NSOnState) {
[prefsController setConfirmNoteDeletion:NO sender:self];
}
}
[retainedDeleteObj release];
}
- (IBAction)deleteNote:(id)sender {
NSIndexSet *indexes = [notesTableView selectedRowIndexes];
if ([indexes count] > 0) {
id deleteObj = [indexes count] > 1 ? (id)([notationController notesAtIndexes:indexes]) : (id)([notationController noteObjectAtFilteredIndex:[indexes firstIndex]]);
if ([prefsController confirmNoteDeletion]) {
[deleteObj retain];
NSString *warningSingleFormatString = NSLocalizedString(@"Delete the note titled quotemark%@quotemark?", @"alert title when asked to delete a note");
NSString *warningMultipleFormatString = NSLocalizedString(@"Delete %d notes?", @"alert title when asked to delete multiple notes");
NSString *warnString = currentNote ? [NSString stringWithFormat:warningSingleFormatString, titleOfNote(currentNote)] :
[NSString stringWithFormat:warningMultipleFormatString, [indexes count]];
NSAlert *alert = [NSAlert alertWithMessageText:warnString defaultButton:NSLocalizedString(@"Delete", @"name of delete button")
alternateButton:NSLocalizedString(@"Cancel", @"name of cancel button") otherButton:nil
informativeTextWithFormat:NSLocalizedString(@"Press Command-Z to undo this action later.", @"informational delete-this-note? text")];
if (IsLeopardOrLater) [alert setShowsSuppressionButton:YES];
[alert beginSheetModalForWindow:window modalDelegate:self didEndSelector:@selector(deleteAlertDidEnd:returnCode:contextInfo:) contextInfo:(void*)deleteObj];
} else {
//just delete the notes outright
[notationController performSelector:[indexes count] > 1 ? @selector(removeNotes:) : @selector(removeNote:) withObject:deleteObj];
}
}
}
- (IBAction)copyNoteLink:(id)sender {
NSIndexSet *indexes = [notesTableView selectedRowIndexes];
if ([indexes count] == 1) {
[[[[[notationController notesAtIndexes:indexes] lastObject]
uniqueNoteLink] absoluteString] copyItemToPasteboard:nil];
}
}
- (IBAction)exportNote:(id)sender {
NSIndexSet *indexes = [notesTableView selectedRowIndexes];
NSArray *notes = [notationController notesAtIndexes:indexes];
[notationController synchronizeNoteChanges:nil];
[[ExporterManager sharedManager] exportNotes:notes forWindow:window];
}
- (IBAction)revealNote:(id)sender {
NSIndexSet *indexes = [notesTableView selectedRowIndexes];
NSString *path = nil;
if ([indexes count] != 1 || !(path = [[notationController noteObjectAtFilteredIndex:[indexes lastIndex]] noteFilePath])) {
NSBeep();
return;
}
[[NSWorkspace sharedWorkspace] selectFile:path inFileViewerRootedAtPath:@""];
}
- (IBAction)editNoteExternally:(id)sender {
ExternalEditor *ed = [sender representedObject];
if ([ed isKindOfClass:[ExternalEditor class]]) {
NSIndexSet *indexes = [notesTableView selectedRowIndexes];
if (kCGEventFlagMaskAlternate == (CGEventSourceFlagsState(kCGEventSourceStateCombinedSessionState) & NSDeviceIndependentModifierFlagsMask)) {
//allow changing the default editor directly from Notes menu
[[ExternalEditorListController sharedInstance] setDefaultEditor:ed];
}
//force-write any queued changes to disk in case notes are being stored as separate files which might be opened directly by the method below
[notationController synchronizeNoteChanges:nil];
[[notationController notesAtIndexes:indexes] makeObjectsPerformSelector:@selector(editExternallyUsingEditor:) withObject:ed];
} else {
NSBeep();
}
}
- (IBAction)printNote:(id)sender {
NSIndexSet *indexes = [notesTableView selectedRowIndexes];
[MultiplePageView printNotes:[notationController notesAtIndexes:indexes] forWindow:window];
}
- (IBAction)tagNote:(id)sender {
if ([notesSubview isCollapsed]) {
[self toggleCollapse:sender];
}
//if single note, add the tag column if necessary and then begin editing
NSIndexSet *indexes = [notesTableView selectedRowIndexes];
if ([indexes count] > 1) {
//Multiple Notes selected, use ElasticThreads' multitagging implementation
TagEditer = [[[TagEditingManager alloc] init] retain];
[TagEditer setDel:self];
@try {
cTags = [[[NSArray alloc] initWithArray:[self commonLabels]] retain];
if ([cTags count]>0) {
[TagEditer setTF:[cTags componentsJoinedByString:@","]];
}else {
[TagEditer setTF:@""];
}
[TagEditer popTP:self];
}
@catch (NSException * e) {
NSLog(@"multitag excep this: %@",[e name]);
}
} else if ([indexes count] == 1) {
isEd = YES;
[notesTableView editRowAtColumnWithIdentifier:NoteLabelsColumnString];
}
}
- (void)noteImporter:(AlienNoteImporter*)importer importedNotes:(NSArray*)notes {
[notationController addNotes:notes];
}
- (IBAction)importNotes:(id)sender {
AlienNoteImporter *importer = [[AlienNoteImporter alloc] init];
[importer importNotesFromDialogAroundWindow:window receptionDelegate:self];
[importer autorelease];
}
- (void)settingChangedForSelectorString:(NSString*)selectorString {
if ([selectorString isEqualToString:SEL_STR(setAliasDataForDefaultDirectory:sender:)]) {
//defaults changed for the database location -- load the new one!
OSStatus err = noErr;
NotationController *newNotation = nil;
NSData *newData = [prefsController aliasDataForDefaultDirectory];
if (newData) {
if ((newNotation = [[NotationController alloc] initWithAliasData:newData error:&err])) {
[self setNotationController:newNotation];
[newNotation release];
} else {
//set alias data back
NSData *oldData = [notationController aliasDataForNoteDirectory];
[prefsController setAliasDataForDefaultDirectory:oldData sender:self];
//display alert with err--could not set notation directory
NSString *location = [[[NSFileManager defaultManager] pathCopiedFromAliasData:newData] stringByAbbreviatingWithTildeInPath];
NSString *oldLocation = [[[NSFileManager defaultManager] pathCopiedFromAliasData:oldData] stringByAbbreviatingWithTildeInPath];
NSString *reason = [NSString reasonStringFromCarbonFSError:err];
NSRunAlertPanel([NSString stringWithFormat:NSLocalizedString(@"Unable to initialize notes database in \n%@ because %@.",nil), location, reason],
[NSString stringWithFormat:NSLocalizedString(@"Reverting to current location of %@.",nil), oldLocation],
NSLocalizedString(@"OK",nil), NULL, NULL);
}
}
} else if ([selectorString isEqualToString:SEL_STR(setSortedTableColumnKey:reversed:sender:)]) {
NoteAttributeColumn *oldSortCol = [notationController sortColumn];
NoteAttributeColumn *newSortCol = [notesTableView noteAttributeColumnForIdentifier:[prefsController sortedTableColumnKey]];
BOOL changedColumns = oldSortCol != newSortCol;
ViewLocationContext ctx;
if (changedColumns) {
ctx = [notesTableView viewingLocation];
ctx.pivotRowWasEdge = NO;
}
[notationController setSortColumn:newSortCol];
if (changedColumns) [notesTableView setViewingLocation:ctx];
} else if ([selectorString isEqualToString:SEL_STR(setNoteBodyFont:sender:)]) {
[notationController restyleAllNotes];
if (currentNote) {
[self contentsUpdatedForNote:currentNote];
}
} else if ([selectorString isEqualToString:SEL_STR(setForegroundTextColor:sender:)]) {
if (userScheme!=2) {
[self setUserColorScheme:self];
}else {
[self setForegrndColor:[prefsController foregroundTextColor]];
[self updateColorScheme];
}
} else if ([selectorString isEqualToString:SEL_STR(setBackgroundTextColor:sender:)]) {
if (userScheme!=2) {
[self setUserColorScheme:self];
}else {
[self setBackgrndColor:[prefsController backgroundTextColor]];
[self updateColorScheme];
}
} else if ([selectorString isEqualToString:SEL_STR(setTableFontSize:sender:)] || [selectorString isEqualToString:SEL_STR(setTableColumnsShowPreview:sender:)]) {
ResetFontRelatedTableAttributes();
[notesTableView updateTitleDereferencorState];
[notationController invalidateAllLabelPreviewImages];
[self _forceRegeneratePreviewsForTitleColumn];
if ([selectorString isEqualToString:SEL_STR(setTableColumnsShowPreview:sender:)]) [self updateNoteMenus];
[notesTableView performSelector:@selector(reloadData) withObject:nil afterDelay:0];
} else if ([selectorString isEqualToString:SEL_STR(addTableColumn:sender:)] || [selectorString isEqualToString:SEL_STR(removeTableColumn:sender:)]) {
ResetFontRelatedTableAttributes();
[self _forceRegeneratePreviewsForTitleColumn];
[notesTableView performSelector:@selector(reloadDataIfNotEditing) withObject:nil afterDelay:0];
} else if ([selectorString isEqualToString:SEL_STR(setConfirmNoteDeletion:sender:)]) {
[self updateNoteMenus];
} else if ([selectorString isEqualToString:SEL_STR(setAutoCompleteSearches:sender:)]) {
if ([prefsController autoCompleteSearches])
[notationController updateTitlePrefixConnections];