forked from scrod/nv
-
Notifications
You must be signed in to change notification settings - Fork 1
/
NotationController.m
executable file
·1396 lines (1060 loc) · 48.1 KB
/
NotationController.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
//
// NotationController.m
// Notation
//
// Created by Zachary Schneirov on 12/19/05.
/*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 "NotationController.h"
#import "NSCollection_utils.h"
#import "NoteObject.h"
#import "DeletedNoteObject.h"
#import "NSString_NV.h"
#import "BufferUtils.h"
#import "GlobalPrefs.h"
#import "NotationPrefs.h"
#import "NoteAttributeColumn.h"
#import "FrozenNotation.h"
#import "NotationFileManager.h"
#import "NotationSyncServiceManager.h"
#import "NotationDirectoryManager.h"
#import "SyncSessionController.h"
#import "BookmarksController.h"
@implementation NotationController
- (id)init {
if ([super init]) {
directoryChangesFound = notesChanged = aliasNeedsUpdating = NO;
allNotes = [[NSMutableArray alloc] init]; //<--the authoritative list of all memory-accessible notes
deletedNotes = [[NSMutableSet alloc] init];
labelsListController = [[LabelsListController alloc] init];
prefsController = [GlobalPrefs defaultPrefs];
notesListDataSource = [[FastListDataSource alloc] init];
allNotesBuffer = NULL;
allNotesBufferSize = 0;
manglingString = currentFilterStr = NULL;
lastWordInFilterStr = 0;
selectedNoteIndex = NSNotFound;
subscriptionCallback = NewFNSubscriptionUPP(NotesDirFNSubscriptionProc);
fsCatInfoArray = NULL;
HFSUniNameArray = NULL;
catalogEntries = NULL;
sortedCatalogEntries = NULL;
catEntriesCount = totalCatEntriesCount = 0;
bzero(¬eDirSubscription, sizeof(FNSubscriptionRef));
bzero(¬eDatabaseRef, sizeof(FSRef));
bzero(¬eDirectoryRef, sizeof(FSRef));
volumeSupportsExchangeObjects = -1;
lastCheckedDateInHours = hoursFromAbsoluteTime(CFAbsoluteTimeGetCurrent());
blockSize = 0;
lastWriteError = noErr;
unwrittenNotes = [[NSMutableSet alloc] init];
}
return self;
}
- (id)initWithAliasData:(NSData*)data error:(OSStatus*)err {
OSStatus anErr = noErr;
if (data && (anErr = PtrToHand([data bytes], (Handle*)&aliasHandle, [data length])) == noErr) {
FSRef targetRef;
Boolean changed;
if ((anErr = FSResolveAliasWithMountFlags(NULL, aliasHandle, &targetRef, &changed, 0)) == noErr) {
if ([self initWithDirectoryRef:&targetRef error:&anErr]) {
aliasNeedsUpdating = changed;
*err = noErr;
return self;
}
}
}
*err = anErr;
return nil;
}
- (id)initWithDefaultDirectoryReturningError:(OSStatus*)err {
FSRef targetRef;
OSStatus anErr = noErr;
if ((anErr = [NotationController getDefaultNotesDirectoryRef:&targetRef]) == noErr) {
if ([self initWithDirectoryRef:&targetRef error:&anErr]) {
*err = noErr;
return self;
}
}
*err = anErr;
return nil;
}
- (id)initWithDirectoryRef:(FSRef*)directoryRef error:(OSStatus*)err {
*err = noErr;
if ([self init]) {
aliasNeedsUpdating = YES; //we don't know if we have an alias yet
noteDirectoryRef = *directoryRef;
//check writable and readable perms, warning user if necessary
//first read cache file
OSStatus anErr = noErr;
if ((anErr = [self _readAndInitializeSerializedNotes]) != noErr) {
*err = anErr;
return nil;
}
//set up the directory subscription, if necessary
//and sync based on notes in directory and their mod. dates
[self databaseSettingsChangedFromOldFormat:[notationPrefs notesStorageFormat]];
if (!walWriter) {
*err = kJournalingError;
return nil;
}
[self upgradeDatabaseIfNecessary];
}
return self;
}
- (id)delegate {
return delegate;
}
- (void)setDelegate:(id)theDelegate {
delegate = theDelegate;
}
- (void)upgradeDatabaseIfNecessary {
if (![notationPrefs firstTimeUsed]) {
const UInt32 epochIteration = [notationPrefs epochIteration];
//upgrade note-text-encodings here if there might exist notes with the wrong encoding (check NotationPrefs values)
if (epochIteration < 2) {
//this would have to be a database from epoch 1, where the default file-encoding was system-default
NSLog(@"trying to upgrade note encodings");
[allNotes makeObjectsPerformSelector:@selector(upgradeToUTF8IfUsingSystemEncoding)];
//move aside the old database as the new format breaks compatibility
(void)[self renameAndForgetNoteDatabaseFile:@"Notes & Settings (old version from 2.0b)"];
}
if (epochIteration < 3) {
[allNotes makeObjectsPerformSelector:@selector(writeFileDatesAndUpdateTrackingInfo)];
}
if (epochIteration < 4) {
if ([self removeSpuriousDatabaseFileNotes]) {
NSLog(@"found and removed spurious DB notes");
[self refilterNotes];
}
}
if (epochIteration < EPOC_ITERATION) {
NSLog(@"epochIteration was upgraded from %u to %u", epochIteration, EPOC_ITERATION);
notesChanged = YES;
[self flushEverything];
} else if ([notationPrefs epochIteration] > EPOC_ITERATION) {
if (NSRunCriticalAlertPanel(NSLocalizedString(@"Warning: this database was created by a newer version of Notational Velocity. Continue anyway?", nil),
NSLocalizedString(@"If you make changes, some settings and metadata will be lost.", nil),
NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Continue", nil), nil) == NSAlertDefaultReturn);
exit(0);
}
}
}
//used to ensure a newly-written Notes & Settings file is valid before finalizing the save
//read the file back from disk, deserialize it, decrypt and decompress it, and compare the notes roughly to our current notes
- (NSNumber*)verifyDataAtTemporaryFSRef:(NSValue*)fsRefValue withFinalName:(NSString*)filename {
NSDate *date = [NSDate date];
NSAssert([filename isEqualToString:NotesDatabaseFileName], @"attempting to verify something other than the database");
FSRef *notesFileRef = [fsRefValue pointerValue];
UInt64 fileSize = 0;
char *notesData = NULL;
OSStatus err = noErr, result = noErr;
if ((err = FSRefReadData(notesFileRef, BlockSizeForNotation(self), &fileSize, (void**)¬esData, forceReadMask)) != noErr)
return [NSNumber numberWithInt:err];
FrozenNotation *frozenNotation = nil;
if (!fileSize) {
result = eofErr;
goto returnResult;
}
NSData *archivedNotation = [[[NSData alloc] initWithBytesNoCopy:notesData length:fileSize freeWhenDone:NO] autorelease];
@try {
frozenNotation = [NSKeyedUnarchiver unarchiveObjectWithData:archivedNotation];
} @catch (NSException *e) {
NSLog(@"(VERIFY) Error unarchiving notes and preferences from data (%@, %@)", [e name], [e reason]);
result = kCoderErr;
goto returnResult;
}
//unpack notes using the current NotationPrefs instance (not the just-unarchived one), with which we presumably just used to encrypt it
NSMutableArray *notesToVerify = [[frozenNotation unpackedNotesWithPrefs:notationPrefs returningError:&err] retain];
if (noErr != err) {
result = err;
goto returnResult;
}
//notes were unpacked--now roughly compare notesToVerify with allNotes, plus deletedNotes and notationPrefs
if (!notesToVerify || [notesToVerify count] != [allNotes count] || [[frozenNotation deletedNotes] count] != [deletedNotes count] ||
[[frozenNotation notationPrefs] notesStorageFormat] != [notationPrefs notesStorageFormat] ||
[[frozenNotation notationPrefs] hashIterationCount] != [notationPrefs hashIterationCount]) {
result = kItemVerifyErr;
goto returnResult;
}
unsigned int i;
for (i=0; i<[notesToVerify count]; i++) {
if ([[[notesToVerify objectAtIndex:i] contentString] length] != [[[allNotes objectAtIndex:i] contentString] length]) {
result = kItemVerifyErr;
goto returnResult;
}
}
NSLog(@"verified %u notes in %g s", [notesToVerify count], (float)[[NSDate date] timeIntervalSinceDate:date]);
returnResult:
if (notesData) free(notesData);
return [NSNumber numberWithInt:result];
}
- (OSStatus)_readAndInitializeSerializedNotes {
OSStatus err = noErr;
if ((err = [self createFileIfNotPresentInNotesDirectory:¬eDatabaseRef forFilename:NotesDatabaseFileName fileWasCreated:nil]) != noErr)
return err;
UInt64 fileSize = 0;
char *notesData = NULL;
if ((err = FSRefReadData(¬eDatabaseRef, BlockSizeForNotation(self), &fileSize, (void**)¬esData, noCacheMask)) != noErr)
return err;
FrozenNotation *frozenNotation = nil;
if (fileSize > 0) {
NSData *archivedNotation = [[NSData alloc] initWithBytesNoCopy:notesData length:fileSize freeWhenDone:NO];
@try {
frozenNotation = [NSKeyedUnarchiver unarchiveObjectWithData:archivedNotation];
} @catch (NSException *e) {
NSLog(@"Error unarchiving notes and preferences from data (%@, %@)", [e name], [e reason]);
if (notesData)
free(notesData);
//perhaps this shouldn't be an error, but the user should instead have the option of overwriting the DB with a new one?
return kCoderErr;
}
[archivedNotation autorelease];
}
[notationPrefs release];
if (!(notationPrefs = [[frozenNotation notationPrefs] retain]))
notationPrefs = [[NotationPrefs alloc] init];
[notationPrefs setDelegate:self];
[allNotes release];
syncSessionController = [[SyncSessionController alloc] initWithSyncDelegate:self notationPrefs:notationPrefs];
//frozennotation will work out passwords, keychains, decryption, etc...
if (!(allNotes = [[frozenNotation unpackedNotesReturningError:&err] retain])) {
//notes could be nil because the user cancelled password authentication
//or because they were corrupted, or for some other reason
if (err != noErr)
return err;
allNotes = [[NSMutableArray alloc] init];
} else {
[allNotes makeObjectsPerformSelector:@selector(setDelegate:) withObject:self];
//[allNotes makeObjectsPerformSelector:@selector(updateLabelConnectionsAfterDecoding)]; //not until we get an actual tag browser
}
[deletedNotes release];
if (!(deletedNotes = [[frozenNotation deletedNotes] retain]))
deletedNotes = [[NSMutableSet alloc] init];
[prefsController setNotationPrefs:notationPrefs sender:self];
if(notesData)
free(notesData);
return noErr;
}
- (BOOL)initializeJournaling {
const UInt32 maxPathSize = 8 * 1024;
UInt8 *convertedPath = (UInt8*)malloc(maxPathSize * sizeof(UInt8));
OSStatus err = noErr;
NSData *walSessionKey = [notationPrefs WALSessionKey];
if ((err = FSRefMakePath(¬eDirectoryRef, convertedPath, maxPathSize)) == noErr) {
//initialize the journal if necessary
if (!(walWriter = [[WALStorageController alloc] initWithParentFSRep:(char*)convertedPath encryptionKey:walSessionKey])) {
//journal file probably already exists, so try to recover it
WALRecoveryController *walReader = [[[WALRecoveryController alloc] initWithParentFSRep:(char*)convertedPath encryptionKey:walSessionKey] autorelease];
if (walReader) {
BOOL databaseCouldNotBeFlushed = NO;
NSDictionary *recoveredNotes = [walReader recoveredNotes];
if ([recoveredNotes count] > 0) {
[self processRecoveredNotes:recoveredNotes];
if (![self flushAllNoteChanges]) {
//we shouldn't continue because the journal is still the sole record of the unsaved notes, so we can't delete it
//BUT: what if the database can't be verified? We should be able to continue, and just keep adding to the WAL
//in this case the WAL should be destroyed, re-initialized, and the recovered (and de-duped) notes added back
NSLog(@"Unable to flush recovered notes back to database");
databaseCouldNotBeFlushed = YES;
//goto bail;
}
}
//is there a way that recoverNextObject could fail that would indicate a failure with the file as opposed to simple non-recovery?
//if so, it perhaps the recoveredNotes method should also return an error condition, to be checked here
//there could be other issues, too (1)
if (![walReader destroyLogFile]) {
//couldn't delete the log file, so we can't create a new one
NSLog(@"Unable to delete the old write-ahead-log file");
goto bail;
}
if (!(walWriter = [[WALStorageController alloc] initWithParentFSRep:(char*)convertedPath encryptionKey:walSessionKey])) {
//couldn't create a journal after recovering the old one
//if databaseCouldNotBeFlushed is true here, then we've potentially lost notes; perhaps exchangeobjects would be better here?
NSLog(@"Unable to create a new write-ahead-log after deleting the old one");
goto bail;
}
if ([recoveredNotes count] > 0) {
if (databaseCouldNotBeFlushed) {
//re-add the contents of recoveredNotes to walWriter; LSNs should take care of the order; no need to sort
//this allows for an ever-growing journal in the case of broken database serialization
//it should not be an acceptable condition for permanent use; hopefully an update would come soon
//warn the user, perhaps
[walWriter writeNoteObjects:[recoveredNotes allValues]];
}
[self refilterNotes];
}
} else {
NSLog(@"Unable to recover unsaved notes from write-ahead-log");
//1) should we let the user attempt to remove it without recovery?
goto bail;
}
}
[walWriter setDelegate:self];
return YES;
} else {
NSLog(@"FSRefMakePath error: %d", err);
goto bail;
}
bail:
free(convertedPath);
return NO;
}
//stick the newest unique recovered notes into allNotes
- (void)processRecoveredNotes:(NSDictionary*)dict {
const unsigned int vListBufCount = 16;
void* keysBuffer[vListBufCount], *valuesBuffer[vListBufCount];
unsigned int i, count = [dict count];
void **keys = (count <= vListBufCount) ? keysBuffer : (void **)malloc(sizeof(void*) * count);
void **values = (count <= vListBufCount) ? valuesBuffer : (void **)malloc(sizeof(void*) * count);
if (keys && values && dict) {
CFDictionaryGetKeysAndValues((CFDictionaryRef)dict, (const void **)keys, (const void **)values);
for (i=0; i<count; i++) {
CFUUIDBytes *objUUIDBytes = (CFUUIDBytes *)keys[i];
id<SynchronizedNote> obj = (id)values[i];
NSUInteger existingNoteIndex = [allNotes indexOfNoteWithUUIDBytes:objUUIDBytes];
if ([obj isKindOfClass:[DeletedNoteObject class]]) {
if (existingNoteIndex != NSNotFound) {
NoteObject *existingNote = [allNotes objectAtIndex:existingNoteIndex];
if ([existingNote youngerThanLogObject:obj]) {
NSLog(@"got a newer deleted note %@", obj);
//except that normally the undomanager doesn't exist by this point
[self _registerDeletionUndoForNote:existingNote];
[allNotes removeObjectAtIndex:existingNoteIndex];
//try to use use the deleted note object instead of allowing _addDeletedNote: to make a new one, to preserve any changes to the syncMD
[self _addDeletedNote:obj];
notesChanged = YES;
} else {
NSLog(@"got an older deleted note %@", obj);
}
} else {
NSLog(@"got a deleted note with a UUID that doesn't match anything in allNotes, adding to deletedNotes only");
//must remember that this was deleted; b/c it could've been added+synced and then deleted before syncing the deletion
//and it might not be in allNotes because the WALreader would have already coalesced by UUID, and so the next sync might re-add the note
[self _addDeletedNote:obj];
}
} else if (existingNoteIndex != NSNotFound) {
if ([[allNotes objectAtIndex:existingNoteIndex] youngerThanLogObject:obj]) {
// NSLog(@"replacing old note with new: %@", [[(NoteObject*)obj contentString] string]);
[(NoteObject*)obj setDelegate:self];
[(NoteObject*)obj updateLabelConnectionsAfterDecoding];
[allNotes replaceObjectAtIndex:existingNoteIndex withObject:obj];
notesChanged = YES;
} else {
// NSLog(@"note %@ is not being replaced because its LSN is %u, while the old note's LSN is %u",
// [[(NoteObject*)obj contentString] string], [(NoteObject*)obj logSequenceNumber], [[allNotes objectAtIndex:existingNoteIndex] logSequenceNumber]);
}
} else {
//NSLog(@"Found new note: %@", [(NoteObject*)obj contentString]);
[self _addNote:obj];
[(NoteObject*)obj updateLabelConnectionsAfterDecoding];
}
}
if (keys != keysBuffer)
free(keys);
if (values != valuesBuffer)
free(values);
} else {
NSLog(@"_makeChangesInDictionary: Could not get values or keys!");
}
}
- (void)closeJournal {
//remove journal file if we have one
if (walWriter) {
if (![walWriter destroyLogFile])
NSLog(@"couldn't remove wal file--is this an error for note flushing?");
[walWriter release];
walWriter = nil;
}
}
- (void)checkJournalExistence {
if (walWriter && ![walWriter logFileStillExists])
[self performSelector:@selector(handleJournalError) withObject:nil afterDelay:0.0];
}
- (void)flushEverything {
//if we could flush the database and there was a journal, then close it
if ([self flushAllNoteChanges] && walWriter) {
[self closeJournal];
//re-start the journal if we had one
if (![self initializeJournaling]) {
[self performSelector:@selector(handleJournalError) withObject:nil afterDelay:0.0];
}
}
}
- (BOOL)flushAllNoteChanges {
//write only if preferences or notes have been changed
if (notesChanged || [notationPrefs preferencesChanged]) {
//finish writing notes and/or db journal entries
[self synchronizeNoteChanges:changeWritingTimer];
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(synchronizeNoteChanges:) object:nil];
if (walWriter) {
if (![walWriter synchronize])
NSLog(@"Couldn't sync wal file--is this an error for note flushing?");
[NSObject cancelPreviousPerformRequestsWithTarget:walWriter selector:@selector(synchronize) object:nil];
}
NSData *serializedData = [FrozenNotation frozenDataWithExistingNotes:allNotes deletedNotes:deletedNotes prefs:notationPrefs];
if (!serializedData) {
NSLog(@"serialized data is nil!");
return NO;
}
//we should have all journal records on disk by now
if ([self storeDataAtomicallyInNotesDirectory:serializedData withName:NotesDatabaseFileName destinationRef:¬eDatabaseRef
verifyWithSelector:@selector(verifyDataAtTemporaryFSRef:withFinalName:) verificationDelegate:self] != noErr)
return NO;
[notationPrefs setPreferencesAreStored];
notesChanged = NO;
}
return YES;
}
- (void)handleJournalError {
//we can be static because the resulting action (exit) is global to the app
static BOOL displayedAlert = NO;
if (delegate && !displayedAlert) {
//we already have a delegate, so this must be a result of the format or file changing after initialization
displayedAlert = YES;
[self flushAllNoteChanges];
NSRunAlertPanel(NSLocalizedString(@"Unable to create or access the Interim Note-Changes file. Is another copy of Notational Velocity currently running?",nil),
NSLocalizedString(@"Open Console in /Applications/Utilities/ for more information.",nil), NSLocalizedString(@"Quit",nil), NULL, NULL);
exit(1);
}
}
//notation prefs delegate method
- (void)databaseEncryptionSettingsChanged {
//we _must_ re-init the journal (if fmt is single-db and jrnl exists) in addition to flushing DB
[self flushEverything];
}
//notation prefs delegate method
- (void)databaseSettingsChangedFromOldFormat:(int)oldFormat {
OSStatus err = noErr;
int currentStorageFormat = [notationPrefs notesStorageFormat];
if (!walWriter && ![self initializeJournaling]) {
[self performSelector:@selector(handleJournalError) withObject:nil afterDelay:0.0];
}
if (currentStorageFormat == SingleDatabaseFormat) {
[self stopFileNotifications];
/*if (![self initializeJournaling]) {
[self performSelector:@selector(handleJournalError) withObject:nil afterDelay:0.0];
}*/
} else {
//write to disk any unwritten notes; do this before flushing database to make sure that when it is flushed, it gets the new file mod. dates
//otherwise it would be necessary to set notesChanged = YES; after this method
//also make sure not to write new notes unless changing to a different format; don't rewrite deleted notes upon launch
if (currentStorageFormat != oldFormat)
[allNotes makeObjectsPerformSelector:@selector(writeUsingCurrentFileFormatIfNonExistingOrChanged)];
//flush and close the journal if necessary
/*if (walWriter) {
if ([self flushAllNoteChanges])
[self closeJournal];
}*/
//notationPrefs should call flushAllNoteChanges after this method, anyway
if (IsZeros(¬eDirSubscription, sizeof(FNSubscriptionRef))) {
err = FNSubscribe(¬eDirectoryRef, subscriptionCallback, self, kFNNoImplicitAllSubscription | kFNNotifyInBackground, ¬eDirSubscription);
if (err != noErr) {
NSLog(@"Could not subscribe to changes in notes directory!");
//just check modification time of directory?
}
}
[self synchronizeNotesFromDirectory];
}
}
- (int)currentNoteStorageFormat {
return [notationPrefs notesStorageFormat];
}
- (void)noteDidNotWrite:(NoteObject*)note errorCode:(OSStatus)error {
[unwrittenNotes addObject:note];
if (error != lastWriteError) {
NSRunAlertPanel([NSString stringWithFormat:NSLocalizedString(@"Changed notes could not be saved because %@.",
@"alert title appearing when notes couldn't be written"),
[NSString reasonStringFromCarbonFSError:error]], @"", NSLocalizedString(@"OK",nil), NULL, NULL);
lastWriteError = error;
}
}
- (void)synchronizeNoteChanges:(NSTimer*)timer {
if ([unwrittenNotes count] > 0) {
lastWriteError = noErr;
if ([notationPrefs notesStorageFormat] != SingleDatabaseFormat) {
[unwrittenNotes makeObjectsPerformSelector:@selector(writeUsingCurrentFileFormatIfNecessary)];
//this always seems to call ourselves
FNNotify(¬eDirectoryRef, kFNDirectoryModifiedMessage, kFNNoImplicitAllSubscription);
}
if (walWriter) {
//append unwrittenNotes to journal, if one exists
[unwrittenNotes makeObjectsPerformSelector:@selector(writeUsingJournal:) withObject:walWriter];
}
//NSLog(@"wrote %d unwritten notes", [unwrittenNotes count]);
[unwrittenNotes removeAllObjects];
[self scheduleUpdateListForAttribute:NoteDateModifiedColumnString];
}
if (changeWritingTimer) {
[changeWritingTimer invalidate];
[changeWritingTimer release];
changeWritingTimer = nil;
}
}
- (NSData*)aliasDataForNoteDirectory {
NSData* theData = nil;
FSRef userHomeFoundRef, *relativeRef = &userHomeFoundRef;
if (aliasNeedsUpdating) {
OSErr err = FSFindFolder(kUserDomain, kCurrentUserFolderType, kCreateFolder, &userHomeFoundRef);
if (err != noErr) {
relativeRef = NULL;
NSLog(@"FSFindFolder error: %d", err);
}
}
//re-fill handle from fsref if necessary, storing path relative to user directory
if (aliasNeedsUpdating && FSNewAlias(relativeRef, ¬eDirectoryRef, &aliasHandle ) != noErr)
return nil;
if (aliasHandle != NULL) {
aliasNeedsUpdating = NO;
HLock((Handle)aliasHandle);
theData = [NSData dataWithBytes:*aliasHandle length:GetHandleSize((Handle) aliasHandle)];
HUnlock((Handle)aliasHandle);
return theData;
}
return nil;
}
- (void)setAliasNeedsUpdating:(BOOL)needsUpdate {
aliasNeedsUpdating = needsUpdate;
}
- (BOOL)aliasNeedsUpdating {
return aliasNeedsUpdating;
}
- (void)checkIfNotationIsTrashed {
if ([self notesDirectoryIsTrashed]) {
NSString *trashLocation = [[NSString pathWithFSRef:¬eDirectoryRef] stringByAbbreviatingWithTildeInPath];
if (!trashLocation) trashLocation = @"unknown";
int result = NSRunCriticalAlertPanel([NSString stringWithFormat:NSLocalizedString(@"Your notes directory (%@) appears to be in the Trash.",nil), trashLocation],
NSLocalizedString(@"If you empty the Trash now, you could lose your notes. Relocate the notes to a less volatile folder?",nil),
NSLocalizedString(@"Relocate Notes",nil), NSLocalizedString(@"Quit",nil), NULL);
if (result == NSAlertDefaultReturn)
[self relocateNotesDirectory];
else [NSApp terminate:nil];
}
}
- (void)trashRemainingNoteFilesInDirectory {
NSAssert([notationPrefs notesStorageFormat] == SingleDatabaseFormat, @"We shouldn't be removing files if the storage is not single-database");
[allNotes makeObjectsPerformSelector:@selector(moveFileToTrash)];
[self notifyOfChangedTrash];
}
- (void)updateLinksToNote:(NoteObject*)aNoteObject fromOldName:(NSString*)oldname {
//O(n)
}
//for making notes that we don't already own
- (NoteObject*)addNote:(NSAttributedString*)attributedContents withTitle:(NSString*)title {
if (!title || ![title length])
title = NSLocalizedString(@"Untitled Note", @"Title of a nameless note");
if (!attributedContents)
attributedContents = [[[NSAttributedString alloc] initWithString:@"" attributes:[prefsController noteBodyAttributes]] autorelease];
NoteObject *note = [[NoteObject alloc] initWithNoteBody:attributedContents title:title
uniqueFilename:[self uniqueFilenameForTitle:title fromNote:nil]
format:[self currentNoteStorageFormat]];
[self addNewNote:note];
//we are the the owner of this note
[note release];
return note;
}
- (void)addNewNote:(NoteObject*)note {
[self _addNote:note];
//clear aNoteObject's syncServicesMD to facilitate sync recreation upon undoing of deletion
//new notes should not have any sync MD; if they do, they should be added using -addNotesFromSync:
//problem is that note could very likely still be in the process of syncing, in which case these dicts will be accessed
//for simplenote is is necessary only once the iPhone app has fully deleted the note off the server; otherwise a regular update will recreate it
//[note removeAllSyncServiceMD];
[note makeNoteDirtyUpdateTime:YES updateFile:YES];
//force immediate update
[self synchronizeNoteChanges:nil];
if ([[self undoManager] isUndoing]) {
//prohibit undoing of creation--only redoing of deletion
//NSLog(@"registering %s", _cmd);
[undoManager registerUndoWithTarget:self selector:@selector(removeNote:) object:note];
if (! [[self undoManager] isUndoing] && ! [[self undoManager] isRedoing])
[undoManager setActionName:[NSString stringWithFormat:NSLocalizedString(@"Create Note quotemark%@quotemark",@"undo action name for creating a single note"), titleOfNote(note)]];
}
[self resortAllNotes];
[self refilterNotes];
[delegate notation:self revealNote:note options:NVEditNoteToReveal | NVOrderFrontWindow];
}
//do not update the view here (why not?)
- (NoteObject*)addNoteFromCatalogEntry:(NoteCatalogEntry*)catEntry {
NoteObject *newNote = [[NoteObject alloc] initWithCatalogEntry:catEntry delegate:self];
[self _addNote:newNote];
[newNote release];
[self schedulePushToAllSyncServicesForNote:newNote];
directoryChangesFound = YES;
return newNote;
}
- (void)addNotesFromSync:(NSArray*)noteArray {
if (![noteArray count]) return;
unsigned int i;
if ([[self undoManager] isUndoing]) [undoManager beginUndoGrouping];
for (i=0; i<[noteArray count]; i++) {
NoteObject * note = [noteArray objectAtIndex:i];
[self _addNote:note];
[note makeNoteDirtyUpdateTime:NO updateFile:YES];
//absolutely ensure that this note is pushed to the rest of the services
[note registerModificationWithOwnedServices];
[self schedulePushToAllSyncServicesForNote:note];
}
if ([[self undoManager] isUndoing]) [undoManager endUndoGrouping];
//don't need to reverse-register undo because removeNote/s: will never use this method
[self synchronizeNoteChanges:nil];
[self resortAllNotes];
[self refilterNotes];
}
- (void)addNotes:(NSArray*)noteArray {
if (![noteArray count]) return;
unsigned int i;
if ([[self undoManager] isUndoing]) [undoManager beginUndoGrouping];
for (i=0; i<[noteArray count]; i++) {
NoteObject * note = [noteArray objectAtIndex:i];
[self _addNote:note];
[note makeNoteDirtyUpdateTime:YES updateFile:YES];
}
if ([[self undoManager] isUndoing]) [undoManager endUndoGrouping];
[self synchronizeNoteChanges:nil];
if ([[self undoManager] isUndoing]) {
//prohibit undoing of creation--only redoing of deletion
//NSLog(@"registering %s", _cmd);
[undoManager registerUndoWithTarget:self selector:@selector(removeNotes:) object:noteArray];
if (! [[self undoManager] isUndoing] && ! [[self undoManager] isRedoing])
[undoManager setActionName:[NSString stringWithFormat:NSLocalizedString(@"Add %d Notes", @"undo action name for creating multiple notes"), [noteArray count]]];
}
[self resortAllNotes];
[self refilterNotes];
if ([noteArray count] > 1)
[delegate notation:self revealNotes:noteArray];
else
[delegate notation:self revealNote:[noteArray lastObject] options:NVOrderFrontWindow];
}
- (void)note:(NoteObject*)note attributeChanged:(NSString*)attribute {
if ([attribute isEqualToString:NotePreviewString]) {
if ([prefsController tableColumnsShowPreview]) {
NSUInteger idx = [notesListDataSource indexOfObjectIdenticalTo:note];
if (NSNotFound != idx) {
[delegate rowShouldUpdate:idx];
}
}
//this attribute is not displayed as a column
return;
}
//[self scheduleUpdateListForAttribute:attribute];
[self performSelector:@selector(scheduleUpdateListForAttribute:) withObject:attribute afterDelay:0.0];
//special case for title requires this method, as app controller needs to know a few note-specific things
if ([attribute isEqualToString:NoteTitleColumnString])
[delegate titleUpdatedForNote:note];
}
- (void)scheduleUpdateListForAttribute:(NSString*)attribute {
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(scheduleUpdateListForAttribute:) object:attribute];
if ([[sortColumn identifier] isEqualToString:attribute]) {
if ([delegate notationListShouldChange:self]) {
[self sortAndRedisplayNotes];
} else {
[self performSelector:@selector(scheduleUpdateListForAttribute:) withObject:attribute afterDelay:1.5];
}
} else {
//catch col updates even if they aren't the sort key
NSEnumerator *enumerator = [[prefsController visibleTableColumns] objectEnumerator];
NSString *colIdentifier = nil;
//check to see if appropriate col is visible
while ((colIdentifier = [enumerator nextObject])) {
if ([colIdentifier isEqualToString:attribute]) {
if ([delegate notationListShouldChange:self]) {
[delegate notationListMightChange:self];
[delegate notationListDidChange:self];
} else {
[self performSelector:@selector(scheduleUpdateListForAttribute:) withObject:attribute afterDelay:1.5];
}
break;
}
}
}
}
- (void)scheduleWriteForNote:(NoteObject*)note {
BOOL immediately = NO;
notesChanged = YES;
[unwrittenNotes addObject:note];
//always synchronize absolutely no matter what 15 seconds after any change
if (!changeWritingTimer)
changeWritingTimer = [[NSTimer scheduledTimerWithTimeInterval:(immediately ? 0.0 : 15.0) target:self
selector:@selector(synchronizeNoteChanges:)
userInfo:nil repeats:NO] retain];
//next user change always invalidates queued write from performSelector, but not queued write from timer
//this avoids excessive writing and any potential and unnecessary disk access while user types
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(synchronizeNoteChanges:) object:nil];
if (walWriter) {
//perhaps a more general user interface activity timer would be better for this? update process syncs every 30 secs, anyway...
[NSObject cancelPreviousPerformRequestsWithTarget:walWriter selector:@selector(synchronize) object:nil];
//fsyncing WAL to disk can cause noticeable interruption when run from main thread
[walWriter performSelector:@selector(synchronize) withObject:nil afterDelay:15.0];
}
if (!immediately) {
//timer is already scheduled if immediately is true
//queue to write 2.7 seconds after last user change;
[self performSelector:@selector(synchronizeNoteChanges:) withObject:nil afterDelay:2.7];
}
}
//the gatekeepers!
- (void)_addNote:(NoteObject*)aNoteObject {
[aNoteObject setDelegate:self];
[allNotes addObject:aNoteObject];
[deletedNotes removeObject:aNoteObject];
notesChanged = YES;
}
//the gateway methods must always show warnings, or else flash overlay window if show-warnings-pref is off
- (void)removeNotes:(NSArray*)noteArray {
NSEnumerator *enumerator = [noteArray objectEnumerator];
NoteObject* note;
[undoManager beginUndoGrouping];
while ((note = [enumerator nextObject])) {
[self removeNote:note];
}
[undoManager endUndoGrouping];
if (! [[self undoManager] isUndoing] && ! [[self undoManager] isRedoing])
[undoManager setActionName:[NSString stringWithFormat:NSLocalizedString(@"Delete %d Notes",@"undo action name for deleting notes"), [noteArray count]]];
}
- (void)removeNote:(NoteObject*)aNoteObject {
//reset linking labels and their notes
[aNoteObject retain];
[allNotes removeObjectIdenticalTo:aNoteObject];
DeletedNoteObject *deletedNote = [self _addDeletedNote:aNoteObject];
notesChanged = YES;
//force-write any cached note changes to make sure that their LSNs are smaller than this deleted note's LSN
[self synchronizeNoteChanges:nil];
//we do this after removing it from the array to avoid re-discovering a removed file
if ([notationPrefs notesStorageFormat] != SingleDatabaseFormat) {
[aNoteObject removeFileFromDirectory];
}
//add journal removal event
if (walWriter && ![walWriter writeRemovalForNote:aNoteObject]) {
NSLog(@"Couldn't log note removal");
}
//a removal command will be sent to sync services if aNoteObject contains a matching syncServicesMD dict
//(e.g., already been synced at least once)
//make sure we use the same deleted note that was added to the list of deleted notes, to simplify record-keeping
//if the note didn't have metadata, try to sync it anyway so that the service knows this note shouldn't be created
[self schedulePushToAllSyncServicesForNote: deletedNote ? deletedNote : [DeletedNoteObject deletedNoteWithNote:aNoteObject]];
[self _registerDeletionUndoForNote:aNoteObject];
//delete note from bookmarks, too
[[prefsController bookmarksController] removeBookmarkForNote:aNoteObject];
[aNoteObject release];
[self refilterNotes];
}
- (void)_purgeAlreadyDistributedDeletedNotes {
//purge deletedNotes of objects without any more syncMD entries;
//once a note has been deleted from all services, there's no need to keep it around anymore
NSUInteger i = 0;
NSArray *dnArray = [deletedNotes allObjects];
for (i = 0; i<[dnArray count]; i++) {
DeletedNoteObject *dnObj = [dnArray objectAtIndex:i];
if (![[dnObj syncServicesMD] count]) {
[deletedNotes removeObject:dnObj];
notesChanged = YES;
}
}
//NSLog(@"%s: deleted notes left: %@", _cmd, deletedNotes);
}
- (DeletedNoteObject*)_addDeletedNote:(id<SynchronizedNote>)aNote {
//currently coupled to -[allNotes removeObjectIdenticalTo:]
//don't need to remember this deleted note unless it was already synced with some service
//furthermore, after that deleted note has been remotely-removed from all services with which it was previously synced,
//can it be purged from this database once and for all?
//e.g., each successful syncservice deletion would also remove that service's entry from syncServicesMD
//when syncServicesMD was empty, it would be removed from the set
//but what about synchronization systems without explicit delete APIs?
if ([[aNote syncServicesMD] count]) {
//it is important to use the actual deleted note if one is passed
DeletedNoteObject *deletedNote = [aNote isKindOfClass:[DeletedNoteObject class]] ? aNote : [DeletedNoteObject deletedNoteWithNote:aNote];