forked from scrod/nv
-
Notifications
You must be signed in to change notification settings - Fork 1
/
AppController.m
executable file
·1537 lines (1206 loc) · 56.5 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. */
#import "AppController.h"
#import "NoteObject.h"
#import "GlobalPrefs.h"
#import "AlienNoteImporter.h"
#import "NotationPrefs.h"
#import "PrefsWindowController.h"
#import "NoteAttributeColumn.h"
#import "NotationSyncServiceManager.h"
#import "NotationDirectoryManager.h"
#import "NSString_NV.h"
#import "NSCollection_utils.h"
#import "AttributedPlainText.h"
#import "EncodingsManager.h"
#import "ExporterManager.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 "DeletionManager.h"
#import "MultiplePageView.h"
#import "InvocationRecorder.h"
#import "URLGetter.h"
#import "LinearDividerShader.h"
#import <WebKit/WebArchive.h>
#include <Carbon/Carbon.h>
@implementation AppController
//an instance of this class is designated in the nib as the delegate of the window, nstextfield and two nstextviews
- (id)init {
if ([super init]) {
windowUndoManager = [[NSUndoManager alloc] init];
dividerShader = [[LinearDividerShader alloc] initWithStartColor:[NSColor colorWithCalibratedWhite:0.988 alpha:1.0]
endColor:[NSColor colorWithCalibratedWhite:0.875 alpha:1.0]];
isCreatingANote = isFilteringFromTyping = typedStringIsCached = NO;
typedString = @"";
}
return self;
}
- (void)awakeFromNib {
prefsController = [GlobalPrefs defaultPrefs];
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:@"Search or Create"];
toolbar = [[NSToolbar alloc] initWithIdentifier:@"NVToolbar"];
[toolbar setAllowsUserCustomization:NO];
[toolbar setAutosavesConfiguration:NO];
[toolbar setDisplayMode:NSToolbarDisplayModeIconOnly];
// [toolbar setSizeMode:NSToolbarSizeModeRegular];
[toolbar setShowsBaselineSeparator:YES];
[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];
[NSApp setDelegate:self];
[notesTableView setDelegate:self];
[window setDelegate:self];
[field setDelegate:self];
[textView setDelegate:self];
[splitView 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];
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!");
[splitView restoreState:YES];
[splitSubview addSubview:editorStatusView positioned:NSWindowAbove relativeTo:splitSubview];
[editorStatusView setFrame:[[textView enclosingScrollView] frame]];
[notesTableView restoreColumns];
[field setNextKeyView:textView];
[textView setNextKeyView:field];
[window setAutorecalculatesKeyViewLoop:NO];
//this is necessary on 10.3; keep just in case
[splitView display];
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] &&
[awokenOutlets containsObject:appDelegate->splitView]) {
[appDelegate setupViewsAfterAppAwakened];
}
}
- (void)runDelayedUIActionsAfterLaunch {
[[prefsController bookmarksController] setAppController:self];
[[prefsController bookmarksController] restoreWindowFromSave];
[[prefsController bookmarksController] updateBookmarksUI];
[self updateNoteMenus];
[prefsController registerAppActivationKeystrokeWithTarget:self selector:@selector(toggleNVActivation:)];
[notationController checkIfNotationIsTrashed];
//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:)];
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);
}
}
[NSApp setServicesProvider:self];
}
- (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 (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 ? [NSString 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 (notesToOpenOnLaunch) {
[notationController addNotes:notesToOpenOnLaunch];
[notesToOpenOnLaunch release];
notesToOpenOnLaunch = 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(setTableFontSize:sender:), //when to tell notationcontroller to regenerate the (now potentially too-short) note-body previews
@selector(setTableColumnsShowPreview:sender:), //when to tell notationcontroller to generate or disable note-body previews
@selector(setConfirmNoteDeletion:sender:),nil]; //whether "delete note" should have an ellipsis
[self performSelector:@selector(runDelayedUIActionsAfterLaunch) withObject:nil afterDelay:0.0];
return;
terminateApp:
[NSApp terminate:self];
}
- (void)setNotationController:(NotationController*)newNotation {
if (newNotation) {
if (notationController) {
[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]];
[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]];
[[DeletionManager sharedManager] setDelegate:notationController];
if ([notationController aliasNeedsUpdating]) {
[prefsController setAliasDataForDefaultDirectory:[notationController aliasDataForNoteDirectory] sender:self];
}
if ([[GlobalPrefs defaultPrefs] tableColumnsShowPreview]) {
[notationController regeneratePreviewsForColumn:[notesTableView noteAttributeColumnForIdentifier:NoteTitleColumnString]
visibleFilteredRows:[notesTableView rowsInRect:[notesTableView visibleRect]] forceUpdate:YES];
[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];
[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];
if (selector == @selector(printNote:) ||
selector == @selector(deleteNote:) ||
selector == @selector(exportNote:) ||
selector == @selector(tagNote:)) {
return (numberSelected > 0);
} else if (selector == @selector(renameNote:)) {
return (numberSelected == 1);
} else if (selector == @selector(fixFileEncoding:)) {
return (currentNote != nil && storageFormatOfNote(currentNote) == PlainTextFormat && ![currentNote contentsWere7Bit]);
}
return YES;
}
/*
- (void)menuNeedsUpdate:(NSMenu *)menu {
NSLog(@"mama needs update: %@", [menu title]);
NSArray *selectedNotes = [notationController notesAtIndexes:[notesTableView selectedRowIndexes]];
[selectedNotes setURLsInNotesForMenu:menu];
}*/
- (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]];
}
NSMenu *viewMenu = [[[NSApp mainMenu] itemWithTitle:@"View"] 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")];
}
}
- (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");
}
}
- (BOOL)addNotesFromPasteboard:(NSPasteboard*)pasteboard {
NSArray *types = [pasteboard types];
NSMutableAttributedString *newString = nil;
NoteObject *note = nil;
NSData *data = nil;
if ([types containsObject:NSFilenamesPboardType]) {
NSArray *files = [pasteboard propertyListForType:NSFilenamesPboardType];
if ([files isKindOfClass:[NSArray class]]) {
NSArray *notes = [[[[AlienNoteImporter alloc] initWithStoragePaths:files] autorelease] importedNotes];
if ([notes count] > 0) {
[notationController addNotes:notes];
return YES;
}
}
}
NSString *sourceIdentiferString = nil;
//webkit URL!
if ([types containsObject:WebArchivePboardType]) {
sourceIdentiferString = [[pasteboard dataForType:WebArchivePboardType] pathURLFromWebArchive];
//gecko URL!
} else if ([types containsObject:[NSString customPasteboardTypeOfCode:0x4D5A0003]]) {
//lazilly use syntheticTitle to get first line, even though that's not how our API is documented
sourceIdentiferString = [[pasteboard stringForType:[NSString customPasteboardTypeOfCode:0x4D5A0003]] syntheticTitle];
unichar nullChar = 0x0;
sourceIdentiferString = [sourceIdentiferString stringByReplacingOccurrencesOfString:
[NSString stringWithCharacters:&nullChar length:1] withString:@""];
}
if ([types containsObject:NSURLPboardType]) {
NSURL *url = [NSURL URLFromPasteboard:pasteboard];
NSString *potentialURLString = [types containsObject:NSStringPboardType] ? [pasteboard stringForType:NSStringPboardType] : nil;
if (potentialURLString && [[url absoluteString] isEqualToString:potentialURLString]) {
//only begin downloading if we know that there's no other useful string data
//because we've already checked NSFilenamesPboardType
if ([[url scheme] caseInsensitiveCompare:@"http"] == NSOrderedSame ||
[[url scheme] caseInsensitiveCompare:@"https"] == NSOrderedSame ||
[[url scheme] caseInsensitiveCompare:@"ftp"] == NSOrderedSame) {
NSString *linkTitleType = [NSString customPasteboardTypeOfCode:0x75726C6E];
NSString *linkTitle = [types containsObject:linkTitleType] ? [[pasteboard stringForType:linkTitleType] syntheticTitle] : nil;
if (!linkTitle) {
//try urld instead of urln
linkTitleType = [NSString customPasteboardTypeOfCode:0x75726C64];
linkTitle = [types containsObject:linkTitleType] ? [[pasteboard stringForType:linkTitleType] syntheticTitle] : nil;
}
[[[[AlienNoteImporter alloc] init] autorelease] importURLInBackground:url linkTitle:linkTitle receptionDelegate:self];
return YES;
}
}
}
//safari on 10.5 does not seem to provide a plain-text equivalent, so we must be able to dumb-down RTF data as well
//should fall-back to plain text if 1) user doesn't want styles and 2) plain text is actually available
BOOL shallUsePlainTextFallback = [types containsObject:NSStringPboardType] && ![prefsController pastePreservesStyle];
BOOL hasRTFData = NO;
if ([types containsObject:NVPTFPboardType]) {
if ((data = [pasteboard dataForType:NVPTFPboardType]))
newString = [[NSMutableAttributedString alloc] initWithRTF:data documentAttributes:NULL];
} else if ([types containsObject:NSRTFPboardType] && !shallUsePlainTextFallback) {
if ((data = [pasteboard dataForType:NSRTFPboardType]))
newString = [[NSMutableAttributedString alloc] initWithRTF:data documentAttributes:NULL];
hasRTFData = YES;
} else if ([types containsObject:NSRTFDPboardType] && !shallUsePlainTextFallback) {
if ((data = [pasteboard dataForType:NSRTFDPboardType]))
newString = [[NSMutableAttributedString alloc] initWithRTFD:data documentAttributes:NULL];
hasRTFData = YES;
} else if (([types containsObject:NSStringPboardType])) {
NSString *pboardString = [pasteboard stringForType:NSStringPboardType];
if (pboardString) newString = [[NSMutableAttributedString alloc] initWithString:pboardString];
}
[newString autorelease];
if ([newString length] > 0) {
[newString removeAttachments];
if (hasRTFData && ![prefsController pastePreservesStyle]) //fallback scenario
newString = [[[NSMutableAttributedString alloc] initWithString:[newString string]] autorelease];
NSString *noteTitle = [[newString string] syntheticTitle];
if ([sourceIdentiferString length] > 0) {
//add the URL or wherever it was that this piece of text came from
[newString prefixWithSourceString:sourceIdentiferString];
}
[newString santizeForeignStylesForImporting];
note = [notationController addNote:newString withTitle:noteTitle];
return note != nil;
}
return NO;
}
- (IBAction)renameNote:(id)sender {
//edit the first selected note
[notesTableView editRowAtColumnWithIdentifier:NoteTitleColumnString];
}
- (void)deleteSheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo {
id retainedDeleteObj = (id)contextInfo;
if (returnCode == NSAlertDefaultReturn) {
//delete! nil-msgsnd-checking
if ([retainedDeleteObj isKindOfClass:[NSArray class]]) {
[notationController removeNotes:retainedDeleteObj];
} else if ([retainedDeleteObj isKindOfClass:[NoteObject class]]) {
[notationController removeNote:retainedDeleteObj];
}
}
[retainedDeleteObj release];
}
- (IBAction)deleteNote:(id)sender {
[notesTableView abortEditing];
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]];
NSBeginAlertSheet(warnString, NSLocalizedString(@"Delete", @"name of delete button"), NSLocalizedString(@"Cancel", @"name of cancel button"),
nil, window, self, @selector(deleteSheetDidEnd:returnCode:contextInfo:), NULL, (void*)deleteObj,
NSLocalizedString(@"You can undo this action later.", @"informational delete-this-note? text"));
} else {
//just delete the notes outright
[notationController performSelector:[indexes count] > 1 ? @selector(removeNotes:) : @selector(removeNote:) withObject:deleteObj];
}
}
}
- (IBAction)exportNote:(id)sender {
NSIndexSet *indexes = [notesTableView selectedRowIndexes];
NSArray *notes = [notationController notesAtIndexes:indexes];
[notationController synchronizeNoteChanges:nil];
[[ExporterManager sharedManager] exportNotes:notes forWindow:window];
}
- (IBAction)printNote:(id)sender {
NSIndexSet *indexes = [notesTableView selectedRowIndexes];
[MultiplePageView printNotes:[notationController notesAtIndexes:indexes] forWindow:window];
}
- (IBAction)tagNote:(id)sender {
//if single note, add the tag column if necessary and then begin editing
NSIndexSet *indexes = [notesTableView selectedRowIndexes];
if ([indexes count] > 1) {
//show dialog for multiple notes, add or remove tags from them all using a dialog
//tags to remove is constituted by a union of all selected notes' tags
NSLog(@"multiple rows");
} else if ([indexes count] == 1) {
[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 = [[NSString pathCopiedFromAliasData:newData] stringByAbbreviatingWithTildeInPath];
NSString *oldLocation = [[NSString 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(setTableFontSize:sender:)] || [selectorString isEqualToString:SEL_STR(setTableColumnsShowPreview:sender:)]) {
[notesTableView updateTitleDereferencorState];
[notationController regeneratePreviewsForColumn:[notesTableView noteAttributeColumnForIdentifier:NoteTitleColumnString]
visibleFilteredRows:[notesTableView rowsInRect:[notesTableView visibleRect]] forceUpdate:YES];
if ([selectorString isEqualToString:SEL_STR(setTableColumnsShowPreview:sender:)]) [self updateNoteMenus];
[notesTableView performSelector:@selector(reloadData) withObject:nil afterDelay:0];
} else if ([selectorString isEqualToString:SEL_STR(setConfirmNoteDeletion:sender:)]) {
[self updateNoteMenus];
}
}
- (void)tableView:(NSTableView *)tableView didClickTableColumn:(NSTableColumn *)tableColumn {
if (tableView == notesTableView) {
//this sets global prefs options, which ultimately calls back to us
[notesTableView setStatusForSortedColumn:tableColumn];
}
}
- (BOOL)tableView:(NSTableView *)tableView shouldShowCellExpansionForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
return ![[tableColumn identifier] isEqualToString:NoteTitleColumnString];
}
- (IBAction)showHelpDocument:(id)sender {
NSString *path = nil;
switch ([sender tag]) {
case 1: //shortcuts
path = [[NSBundle mainBundle] pathForResource:NSLocalizedString(@"Excruciatingly Useful Shortcuts", nil) ofType:@"nvhelp" inDirectory:nil];
case 2: //acknowledgments
if (!path) path = [[NSBundle mainBundle] pathForResource:@"Acknowledgments" ofType:@"txt" inDirectory:nil];
[[NSWorkspace sharedWorkspace] openURLs:[NSArray arrayWithObject:[NSURL fileURLWithPath:path]] withAppBundleIdentifier:@"com.apple.TextEdit"
options:NSWorkspaceLaunchDefault additionalEventParamDescriptor:nil launchIdentifiers:NULL];
break;
case 3: //product site
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:NSLocalizedString(@"SiteURL", nil)]];
break;
case 4: //development site
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://notational.net/development"]];
break;
default:
NSBeep();
}
}
- (void)application:(NSApplication *)sender openFiles:(NSArray *)filenames {
//should check filenames here to see whether notationcontroller already owns these
NSArray *notes = [[[[AlienNoteImporter alloc] initWithStoragePaths:filenames] autorelease] importedNotes];
if (notes) {
if (notationController)
[notationController addNotes:notes];
else
notesToOpenOnLaunch = [notes mutableCopyWithZone:nil];
}
[NSApp replyToOpenOrPrint:notes ? NSApplicationDelegateReplySuccess : NSApplicationDelegateReplyFailure];
}
- (void)applicationDidBecomeActive:(NSNotification *)aNotification {
[notationController checkJournalExistence];
if ([notationController currentNoteStorageFormat] != SingleDatabaseFormat)
[notationController performSelector:@selector(synchronizeNotesFromDirectory) withObject:nil afterDelay:0.0];
if ([[prefsController notationPrefs] secureTextEntry]) {
EnableSecureEventInput();
}
[notationController updateDateStringsIfNecessary];
}
- (void)applicationWillResignActive:(NSNotification *)aNotification {
if ([[prefsController notationPrefs] secureTextEntry]) {
DisableSecureEventInput();
}
//sync note files when switching apps so user doesn't have to guess when they'll be updated
[notationController synchronizeNoteChanges:nil];
}
- (NSMenu *)applicationDockMenu:(NSApplication *)sender {
static NSMenu *dockMenu = nil;
if (!dockMenu) {
dockMenu = [[NSMenu alloc] initWithTitle:@"NV Dock Menu"];
[[dockMenu addItemWithTitle:NSLocalizedString(@"Add New Note from Clipboard", @"menu item title in dock menu")
action:@selector(paste:) keyEquivalent:@""] setTarget:notesTableView];
}
return dockMenu;
}
- (void)cancelOperation:(id)sender {
//simulate a search for nothing
[field setStringValue:@""];
typedStringIsCached = NO;
[notationController filterNotesFromString:@""];
[notesTableView deselectAll:sender];
[field selectText:sender];
[[field cell] setShowsClearButton:NO];
}
- (BOOL)control:(NSControl *)control textView:(NSTextView *)aTextView doCommandBySelector:(SEL)command {
if (control == (NSControl*)field) {
//backwards-searching is slow enough as it is, so why not just check this first?
if (command == @selector(deleteBackward:))
return NO;
if (command == @selector(moveDown:) || command == @selector(moveUp:) ||
//catch shift-up/down selection behavior
command == @selector(moveDownAndModifySelection:) ||
command == @selector(moveUpAndModifySelection:) ||
command == @selector(moveToBeginningOfDocumentAndModifySelection:) ||
command == @selector(moveToEndOfDocumentAndModifySelection:)) {
BOOL singleSelection = ([notesTableView numberOfRows] == 1 && [notesTableView numberOfSelectedRows] == 1);
[notesTableView keyDown:[window currentEvent]];
unsigned int strLen = [[aTextView string] length];
if (!singleSelection && [aTextView selectedRange].length != strLen) {
[aTextView setSelectedRange:NSMakeRange(0, strLen)];
}
return YES;
}
if ((command == @selector(insertTab:) || command == @selector(insertTabIgnoringFieldEditor:))) {
//[self setEmptyViewState:NO];
if (![[aTextView string] length] || [textView isHidden]) return YES;
[window makeFirstResponder:textView];
//don't eat the tab!
return NO;
}
if (command == @selector(moveToBeginningOfDocument:)) {
[notesTableView selectRowAndScroll:0];
return YES;
}
if (command == @selector(moveToEndOfDocument:)) {
[notesTableView selectRowAndScroll:[notesTableView numberOfRows]-1];
return YES;
}
if (command == @selector(moveToBeginningOfLine:) || command == @selector(moveToLeftEndOfLine:)) {
[aTextView moveToBeginningOfDocument:nil];
return YES;
}
if (command == @selector(moveToEndOfLine:) || command == @selector(moveToRightEndOfLine:)) {
[aTextView moveToEndOfDocument:nil];
return YES;
}
if (command == @selector(moveToBeginningOfLineAndModifySelection:) || command == @selector(moveToLeftEndOfLineAndModifySelection:)) {
if ([aTextView respondsToSelector:@selector(moveToBeginningOfDocumentAndModifySelection:)]) {
[(id)aTextView performSelector:@selector(moveToBeginningOfDocumentAndModifySelection:)];
return YES;
}
}
if (command == @selector(moveToEndOfLineAndModifySelection:) || command == @selector(moveToRightEndOfLineAndModifySelection:)) {
if ([aTextView respondsToSelector:@selector(moveToEndOfDocumentAndModifySelection:)]) {
[(id)aTextView performSelector:@selector(moveToEndOfDocumentAndModifySelection:)];
return YES;
}
}
//we should make these two commands work for linking editor as well
if (command == @selector(deleteToMark:)) {
[aTextView deleteWordBackward:nil];
return YES;
}
if (command == @selector(noop:)) {
//control-U is not set to anything by default, so we have to check the event itself for noops
NSEvent *event = [window currentEvent];
if ([event modifierFlags] & NSControlKeyMask) {
if ([event firstCharacterIgnoringModifiers] == 'u') {
//in 1.1.1 this deleted the entire line, like tcsh. this is more in-line with bash
[aTextView deleteToBeginningOfLine:nil];
return YES;
}
}
}
} else if (control == (NSControl*)notesTableView) {
if (command == @selector(insertNewline:)) {
//hit return in cell
[window makeFirstResponder:textView];
return YES;
}
} else
NSLog(@"%@/%@ got %@", [control description], [aTextView description], NSStringFromSelector(command));
return NO;
}
- (void)_setCurrentNote:(NoteObject*)aNote {
//save range of old current note
//we really only want to save the insertion point position if it's currently invisible
//how do we test that?
BOOL wasAutomatic = NO;
NSRange currentRange = [textView selectedRangeWasAutomatic:&wasAutomatic];
if (!wasAutomatic) [currentNote setSelectedRange:currentRange];
//regenerate content cache before switching to new note
[currentNote updateContentCacheCStringIfNecessary];
[currentNote release];
currentNote = [aNote retain];
}
- (NoteObject*)selectedNoteObject {
return currentNote;
}
- (NSString*)fieldSearchString {
NSString *typed = [self typedString];
if (typed) return typed;
if (!currentNote) return [field stringValue];
return nil;
}
- (NSString*)typedString {
if (typedStringIsCached)
return typedString;
return nil;
}
- (void)cacheTypedStringIfNecessary:(NSString*)aString {
if (!typedStringIsCached) {
[typedString release];
typedString = [(aString ? aString : [field stringValue]) copy];
typedStringIsCached = YES;
}
}
//from fieldeditor
- (void)controlTextDidChange:(NSNotification *)aNotification {
if ([aNotification object] == field) {
typedStringIsCached = NO;
isFilteringFromTyping = YES;
NSTextView *fieldEditor = [[aNotification userInfo] objectForKey:@"NSFieldEditor"];
NSString *fieldString = [fieldEditor string];
BOOL didFilter = [notationController filterNotesFromString:fieldString];
if ([fieldString length] > 0) {
[field setSnapbackString:nil];
NSUInteger preferredNoteIndex = [notationController preferredSelectedNoteIndex];
//lastLengthReplaced depends on textView:shouldChangeTextInRange:replacementString: being sent before controlTextDidChange: runs
if ([prefsController autoCompleteSearches] && preferredNoteIndex != NSNotFound &&
([field lastLengthReplaced] > 0 /*|| [notationController preferredSelectedNoteMatchesSearchString]*/)) {
[notesTableView selectRowAndScroll:preferredNoteIndex];
if (didFilter) {
//current selection may be at the same row, but note at that row may have changed
[self displayContentsForNoteAtIndex:preferredNoteIndex];
}
NSAssert(currentNote != nil, @"currentNote must not--cannot--be nil!");
NSRange typingRange = [fieldEditor selectedRange];
//fill in the remaining characters of the title and select
if ([field lastLengthReplaced] > 0 && typingRange.location < [titleOfNote(currentNote) length]) {
[self cacheTypedStringIfNecessary:fieldString];
NSAssert([fieldString isEqualToString:[fieldEditor string]], @"I don't think it makes sense for fieldString to change");
NSString *remainingTitle = [titleOfNote(currentNote) substringFromIndex:typingRange.location];
typingRange.length = [fieldString length] - typingRange.location;
typingRange.length = MAX(typingRange.length, 0U);
[fieldEditor replaceCharactersInRange:typingRange withString:remainingTitle];
typingRange.length = [remainingTitle length];
[fieldEditor setSelectedRange:typingRange];
}
} else {
//auto-complete is off, search string doesn't prefix any title, or part of the search string is being removed
goto selectNothing;
}
} else {
//selecting nothing; nothing typed
selectNothing:
isFilteringFromTyping = NO;
[notesTableView deselectAll:nil];
//reloadData could have already de-selected us, and hence this notification would not be sent from -deselectAll:
[self processChangedSelectionForTable:notesTableView];
}
isFilteringFromTyping = NO;
}
}
- (void)tableViewSelectionIsChanging:(NSNotification *)aNotification {
BOOL allowMultipleSelection = NO;
NSEvent *event = [window currentEvent];
NSEventType type = [event type];
//do not allow drag-selections unless a modifier is pressed
if (type == NSLeftMouseDragged || type == NSLeftMouseDown) {
unsigned flags = [event modifierFlags];
if ((flags & NSShiftKeyMask) || (flags & NSCommandKeyMask)) {
allowMultipleSelection = YES;
}
}
if (allowMultipleSelection != [notesTableView allowsMultipleSelection]) {
//we may need to hack some hidden NSTableView instance variables to improve mid-drag flags-changing
//NSLog(@"set allows mult: %d", allowMultipleSelection);
[notesTableView setAllowsMultipleSelection:allowMultipleSelection];
//we need this because dragging a selection back to the same note will nto trigger a selectionDidChange notification
[self performSelector:@selector(setTableAllowsMultipleSelection) withObject:nil afterDelay:0];
}
if ([window firstResponder] != notesTableView) {
//occasionally changing multiple selection ability in-between selecting multiple items causes total deselection
[window makeFirstResponder:notesTableView];
}
[self processChangedSelectionForTable:[aNotification object]];
}
- (void)setTableAllowsMultipleSelection {
[notesTableView setAllowsMultipleSelection:YES];
//NSLog(@"allow mult: %d", [notesTableView allowsMultipleSelection]);
//[textView setNeedsDisplay:YES];
}
- (void)tableViewSelectionDidChange:(NSNotification *)aNotification {
NSEventType type = [[window currentEvent] type];
if (type != NSKeyDown && type != NSKeyUp) {
[self performSelector:@selector(setTableAllowsMultipleSelection) withObject:nil afterDelay:0];
}
[self processChangedSelectionForTable:[aNotification object]];
}
- (void)processChangedSelectionForTable:(NSTableView*)table {
int selectedRow = [table selectedRow];
int numberSelected = [table numberOfSelectedRows];
NSTextView *fieldEditor = (NSTextView*)[field currentEditor];
if (table == (NSTableView*)notesTableView) {