-
-
Notifications
You must be signed in to change notification settings - Fork 197
/
AppController.m
executable file
·3432 lines (2838 loc) · 129 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 "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 "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 "ETContentView.h"
#import "PreviewController.h"
#import "ETClipView.h"
//#import "ETScrollView.h"
#import "NSFileManager+DirectoryLocations.h"
#import "nvaDevConfig.h"
#import <Sparkle/SUUpdater.h>
#define NSApplicationPresentationAutoHideMenuBar (1 << 2)
#define NSApplicationPresentationHideMenuBar (1 << 3)
//#define NSApplicationPresentationAutoHideDock (1 << 0)
#define NSApplicationPresentationHideDock (1 << 1)
//#define NSApplicationActivationPolicyAccessory
#define kSparkleUpdateFeedForLions @"https://updates.designheresy.com/nvalt/updates.xml"
#define kSparkleUpdateFeedForSnowLeopard @"http://abyss.designheresy.com/nvalt2/nvalt2snowleopardfeed.xml"
//http://abyss.designheresy.com/nvalt/betaupdates.xml
#define kSplitViewExpandedDividerThickness 8.0f
#define kSplitViewCollapsedDividerThickness 5.0f
//#define NSTextViewChangedNotification @"TextViewHasChangedContents"
//#define kDefaultMarkupPreviewMode @"markupPreviewMode"
#define kDualFieldHeight 35.0
#define k_FinderTaggingReset 0
NSWindow *normalWindow;
NSInteger ModFlagger;
NSInteger popped;
BOOL splitViewAwoke;
@implementation AppController
@synthesize isEditing;
//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 {
self = [super init];
if (self) {
if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_11) {
[NSWindow setAllowsAutomaticWindowTabbing:NO];
}
#if k_FinderTaggingReset
[[NSUserDefaults standardUserDefaults]removeObjectForKey:@"UseFinderTags"];
#endif
hasLaunched=NO;
if (![[NSUserDefaults standardUserDefaults] boolForKey:@"ShowDockIcon"]){
if (IsLionOrLater) {
ProcessSerialNumber psn = { 0, kCurrentProcess };
OSStatus returnCode = TransformProcessType(&psn, kProcessTransformToUIElementApplication);
if( returnCode != 0) {
NSLog(@"Could not bring the application to front. Error %d", returnCode);
}
}
if (![[NSUserDefaults standardUserDefaults] boolForKey:@"StatusBarItem"]) {
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"StatusBarItem"];
}
}else{
if (!IsLionOrLater) {
enum {NSApplicationActivationPolicyRegular};
[[NSApplication sharedApplication] setActivationPolicy:NSApplicationActivationPolicyRegular];
}
}
splitViewAwoke = NO;
windowUndoManager = [[NSUndoManager alloc] init];
previewController = [[PreviewController alloc] init];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *folder = [fileManager applicationSupportDirectory];
if ([fileManager fileExistsAtPath: folder] == NO)
{
[fileManager createFolderAtPath:folder];
// [fileManager createDirectoryAtPath: folder attributes: nil];
}
NSNotificationCenter *nc=[NSNotificationCenter defaultCenter];
[nc addObserver:previewController selector:@selector(requestPreviewUpdate:) name:@"TextViewHasChangedContents" object:self];
[nc addObserver:self selector:@selector(togDockIcon:) name:@"AppShouldToggleDockIcon" object:nil];
[nc addObserver:self selector:@selector(toggleStatusItem:) name:@"AppShouldToggleStatusItem" object:nil];
[nc addObserver:self selector:@selector(resetModTimers:) name:@"ModTimersShouldReset" object:nil];
[nc addObserver:self selector:@selector(releaseTagEditor:) name:@"TagEditorShouldRelease" object:nil];
// 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 = @"";
self.isEditing=NO;
}
return self;
}
- (void)awakeFromNib {
splitViewIsChangingLayout=NO;
theFieldEditor = [[[NSTextView alloc]initWithFrame:[window frame]] retain];
[theFieldEditor setFieldEditor:YES];
// [theFieldEditor setDelegate:self];
[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];
//here
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:kSplitViewExpandedDividerThickness];
[splitView setAutoresizesSubviews:YES];
[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];
id docView = [[textScrollView documentView] retain];
ETClipView *newClipView = [[ETClipView alloc] initWithFrame:[[textScrollView contentView] frame]];
[newClipView setDrawsBackground:NO];
// [newClipView setBackgroundColor:[self backgrndColor]];
[textScrollView setContentView:(ETClipView *)newClipView];
[newClipView release];
[textScrollView setDocumentView:textView];
[docView release];
[textScrollView setFrame:[splitSubview frame]];
// [textScrollView setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)];
[splitView adjustSubviews];
[splitView needsDisplay];
[mainView setNeedsDisplay:YES];
splitViewAwoke = YES;
[notesScrollView setBorderType:NSNoBorder];
[textScrollView setBorderType:NSNoBorder];
prefsController = [GlobalPrefs defaultPrefs];
[NSColor setIgnoresAlpha:NO];
//For ElasticThreads' fullscreen implementation.
[self setDualFieldInToolbar];
[notesTableView setDelegate:self];
[field setDelegate:self];
[textView setDelegate:self];
//set up temporary FastListDataSource containing false visible notes
//this will not make a difference
//[window makeKeyAndOrderFront:self];
//[self setEmptyViewState:YES];
if (!IsYosemiteOrLater) {
[window useOptimizedDrawing:YES];
}
// Create elasticthreads' NSStatusItem.
if ( [[NSUserDefaults standardUserDefaults] boolForKey:@"StatusBarItem"]) {
[self setUpStatusBarItem];
}
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];
}
outletObjectAwoke(self);
}
//really need make AppController a subclass of NSWindowController and stick this junk in windowDidLoad
- (void)setupViewsAfterAppAwakened {
static BOOL awakenedViews = 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 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]) { probably a mistake to have put this in the begin with
// [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")) {
// NSLog(@"su:%@ SEL:%@",sparkleUpdateItem.target,sparkleUpdateItem.action);
// }else{
NSString *frameworkPath = [[[NSBundle bundleForClass:[self class]] privateFrameworksPath] stringByAppendingPathComponent:@"Sparkle.framework"];
if ([[NSBundle bundleWithPath:frameworkPath] load]) {
SUUpdater *updater =[SUUpdater sharedUpdater];
if (IsLionOrLater) {
[updater setFeedURL:[NSURL URLWithString:kSparkleUpdateFeedForLions]];
}else{
[updater setFeedURL:[NSURL URLWithString:kSparkleUpdateFeedForSnowLeopard]];
}
[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 setAutomaticallyChecksForUpdates:YES];
// [updater methodForSelector:checksSEL](updater, checksSEL, YES);
}
} else {
NSLog(@"Could not load %@!", frameworkPath);
}
// }
// add elasticthreads' menuitems
if(IsLeopardOrLater){
[fsMenuItem setEnabled:YES];
[fsMenuItem setHidden:NO];
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
if (IsLionOrLater) {
// [window setCollectionBehavior:NSWindowCollectionBehaviorTransient|NSWindowCollectionBehaviorMoveToActiveSpace];
//
[window setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
// [window setCollectionBehavior:NSWindowCollectionBehaviorFullScreenAuxiliary];
// [NSApp setPresentationOptions:[NSApp currentSystemPresentationOptions]|NSApplicationPresentationFullScreen];
}else{
#endif
[fsMenuItem setTarget:self];
[fsMenuItem setAction:@selector(switchFullScreen:)];
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
}
#endif
NSMenuItem *theMenuItem = [fsMenuItem copy];
[statBarMenu insertItem:theMenuItem atIndex:14];
[theMenuItem release];
}
[wordCounter setHidden:[prefsController showWordCount]];
//
[NSApp setServicesProvider:self];
if (!hasLaunched) {
hasLaunched=YES;
[self focusControlField:self activate:NO];
}
// self.isEditing=NO;
// [NSApp activateIgnoringOtherApps:NO];
// [window makeKeyAndOrderFront:self];
}
//
//- (void)applicationWillFinishLaunching:(NSNotification *)aNotification{
//
//}
- (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] autorelease];
subMessage = NSLocalizedString(@"Please choose a different folder in which to store your notes.",nil);
} else {
newNotation = [[[NotationController alloc] initWithDefaultDirectoryReturningError:&err] autorelease];
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
// [newNotation release];
goto terminateApp;
} else if ((newNotation = [[[NotationController alloc] initWithDirectoryRef:¬esDirectoryRef error:&err] autorelease])) {
//have to make sure alias data is saved from setNotationController
[newNotation setAliasNeedsUpdating:YES];
break;
}
} else {
goto terminateApp;
}
}
[self setNotationController:newNotation];
NSLog(@"load time: %g, ",[[NSDate date] timeIntervalSinceDate:before]);
// NSLog(@"version: %s", PRODUCT_NAME);
//import old database(s) here if necessary
[AlienNoteImporter importBlorOrHelpFilesIfNecessaryIntoNotation:newNotation];
// [newNotation release];
if (pathsToOpenOnLaunch) {
[notationController openFiles:[pathsToOpenOnLaunch autorelease]];//autorelease
pathsToOpenOnLaunch = nil;
}
if (URLToInterpretOnLaunch) {
[self interpretNVURL:[NSURL URLWithString:URLToInterpretOnLaunch]];
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(setUseFinderTags:), //whether nvalt should use findertags
@selector(setAutoCompleteSearches:sender:),@selector(setUseETScrollbarsOnLion: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 path]retain];
}
}
- (void)setNotationController:(NotationController*)newNotation {
if (newNotation) {
if (notationController) {
[notationController closeAllResources];
[[NSNotificationCenter defaultCenter] removeObserver:self name:SyncSessionsChangedVisibleStatusNotification
object:[notationController syncSessionController]];
}
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])&&(hasLaunched)) {
[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];
NSInteger 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:NSLocalizedString(@"Expand Notes List",@"menu item title for expanding notes list")];
}else{
[menuItem setTitle:NSLocalizedString(@"Collapse Notes List",@"menu item title for collapsing notes list")];
if (!currentNote){
return NO;
}
}
} else if ((selector == @selector(toggleFullScreen:))||(selector == @selector(switchFullScreen:))) {
if (IsLeopardOrLater) {
if([NSApp presentationOptions]>0){
[menuItem setTitle:NSLocalizedString(@"Exit Full Screen",@"menu item title for exiting fullscreen")];
}else{
[menuItem setTitle:NSLocalizedString(@"Enter Full Screen",@"menu item title for entering fullscreen")];
}
}
} 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]]];
}else if (selector == @selector(previewNoteWithMarked:)){
BOOL gotMarked=[[[NSWorkspace sharedWorkspace]URLForApplicationWithBundleIdentifier:@"com.brettterpstra.marky"] isFileURL] || [[[NSWorkspace sharedWorkspace]URLForApplicationWithBundleIdentifier:@"com.brettterpstra.marked2"] isFileURL]
|| [[[NSWorkspace sharedWorkspace]URLForApplicationWithBundleIdentifier:@"com.brettterpstra.marked2.beta"] isFileURL]
|| [[[NSWorkspace sharedWorkspace]URLForApplicationWithBundleIdentifier:@"com.brettterpstra.marked-setapp"] isFileURL];
if ([menuItem isHidden]==gotMarked) {
[menuItem setHidden:!gotMarked];
}
return gotMarked&&([[notesTableView selectedRowIndexes]count]>0);
}else if (selector==@selector(togglePreview:)){
return (currentNote != nil);
}
return YES;
}
- (void)updateNoteMenus {
NSMenu *notesMenu = [[[NSApp mainMenu] itemWithTag:NOTES_MENU_ID] submenu];
NSInteger 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 {
splitViewIsChangingLayout=YES;
self.isEditing = NO;
BOOL horiz = [prefsController horizontalLayout];
if ([notesSubview isCollapsed]) {
[notesSubview expand];
[splitView setVertical:horiz];
[splitView setDividerThickness:kSplitViewCollapsedDividerThickness];
[notesSubview collapse];
}else {
[splitView setVertical:horiz];
// if (!verticalDividerImg && [splitView divider]) verticalDividerImg = [[splitView divider] retain];
// [splitView setDivider: verticalDividerImg];
[splitView setDividerThickness:kSplitViewExpandedDividerThickness];
if (![self dualFieldIsVisible]) {
[self setDualFieldIsVisible:YES];
}
}
splitViewIsChangingLayout=NO;
if (horiz) {
[splitSubview setMinDimension:100.0 andMaxDimension:0.0];
}
}
- (IBAction)switchViewLayout:(id)sender {
if ([self isInFullScreen]) {
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];
[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
self.isEditing = YES;
[notesTableView editRowAtColumnWithIdentifier:NoteTitleColumnString];
}
//
- (void)deleteAlertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(NSIndexSet *)contextInfo {
if ((returnCode == NSAlertFirstButtonReturn)&&(contextInfo!=nil)&&([contextInfo count]>0)) {
// NSLog(@"gonna delete:%@",contextInfo);
// NSIndexSet *indexes=(NSIndexSet *)contextInfo;
[notationController removeNotesAtIndexes:contextInfo];
}
[contextInfo release];
[alert release];
}
//
// 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) {
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 new];
alert.messageText=warnString;
alert.informativeText=NSLocalizedString(@"Press Command-Z to undo this action later.", @"informational delete-this-note? text");
[alert addButtonWithTitle:NSLocalizedString(@"Delete", @"name of delete button")];
[alert addButtonWithTitle:NSLocalizedString(@"Cancel", @"name of cancel button")];
[alert setShowsSuppressionButton:YES];
if (IsMavericksOrLater) {
[alert beginSheetModalForWindow:window completionHandler:^(NSModalResponse returnCode) {
if (returnCode == NSAlertFirstButtonReturn) {
[notationController removeNotesAtIndexes:indexes];
}
}];
[alert release];
}else{
[indexes retain];
[alert beginSheetModalForWindow:window modalDelegate:self didEndSelector:@selector(deleteAlertDidEnd:returnCode:contextInfo:) contextInfo:indexes];
}
} else {
//just delete the notes outright
[notationController removeNotesAtIndexes:indexes];
}
}
}
- (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)previewNoteWithMarked:(id)sender {
if (![[[NSWorkspace sharedWorkspace]URLForApplicationWithBundleIdentifier:@"com.brettterpstra.marked2"] isFileURL] && ![[[NSWorkspace sharedWorkspace]URLForApplicationWithBundleIdentifier:@"com.brettterpstra.marky"] isFileURL] && ![[[NSWorkspace sharedWorkspace]URLForApplicationWithBundleIdentifier:@"com.brettterpstra.marked-setapp"] isFileURL] && ![[[NSWorkspace sharedWorkspace]URLForApplicationWithBundleIdentifier:@"com.brettterpstra.marked2.beta"] isFileURL])
{
NSBeep();
NSLog(@"Marked not found");
} else {
NSIndexSet *indexes = [notesTableView selectedRowIndexes];
//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(previewUsingMarked)];
}
}
- (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 *selIndexes = [notesTableView selectedRowIndexes];
if ([selIndexes count] > 1) {
NSRect linkingFrame=[textScrollView convertRect:[textScrollView frame] toView:nil];
if (IsLionOrLater) {
linkingFrame=[window convertRectToScreen:linkingFrame];
}else{
linkingFrame.origin=[window convertBaseToScreen:linkingFrame.origin];
}
NSPoint cPoint=NSMakePoint(NSMidX(linkingFrame), NSMaxY(linkingFrame));
//Multiple Notes selected, use ElasticThreads' multitagging implementation
tagEditor = [[[TagEditingManager alloc] initWithDelegate:self commonTags:[self commonLabelsForNotesAtIndexes:selIndexes] atPoint:cPoint] retain];
//Multiple Notes selected, use ElasticThreads' multitagging implementation
} else if ([selIndexes count] == 1) {
self.isEditing = YES;
[notesTableView editRowAtColumnWithIdentifier:NoteLabelsColumnString];
}
}
- (void)noteImporter:(AlienNoteImporter*)importer importedNotes:(NSArray*)notes {