/
NoteObject.m
executable file
·1382 lines (1087 loc) · 47.9 KB
/
NoteObject.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
//
// NoteObject.m
// Notation
//
// Created by Zachary Schneirov on 12/19/05.
// Copyright 2005 Zachary Schneirov. All rights reserved.
//
#import "NoteObject.h"
#import "GlobalPrefs.h"
#import "LabelObject.h"
#import "WALController.h"
#import "NotationController.h"
#import "NotationPrefs.h"
#import "AttributedPlainText.h"
#import "NSString_NV.h"
#include "BufferUtils.h"
#import "NotationFileManager.h"
#if __LP64__
// Needed for compatability with data created by 32bit app
typedef struct NSRange32 {
unsigned int location;
unsigned int length;
} NSRange32;
#else
typedef NSRange NSRange32;
#endif
@implementation NoteObject
static FSRef *noteFileRefInit(NoteObject* obj);
- (id)init {
if ([super init]) {
cTitle = cContents = cLabels = cTitleFoundPtr = cContentsFoundPtr = cLabelsFoundPtr = NULL;
bzero(&fileModifiedDate, sizeof(UTCDateTime));
modifiedDate = createdDate = 0.0;
currentFormatID = SingleDatabaseFormat;
nodeID = 0;
fileEncoding = NSUTF8StringEncoding;
contentsWere7Bit = NO;
serverModifiedTime = 0;
logSequenceNumber = 0;
selectedRange = NSMakeRange(NSNotFound, 0);
//these are created either when the object is initialized from disk or when it writes its files to disk
//bzero(¬eFileRef, sizeof(FSRef));
//labelSet = [[NSMutableSet alloc] init];
}
return self;
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[self invalidateFSRef];
[tableTitleString release];
[titleString release];
[labelString release];
[labelSet release];
[undoManager release];
[filename release];
[dateModifiedString release];
[dateCreatedString release];
if (cTitle)
free(cTitle);
if (cContents)
free(cContents);
if (cLabels)
free(cLabels);
[super dealloc];
}
- (id)delegate {
return delegate;
}
- (void)setDelegate:(id)theDelegate {
delegate = theDelegate;
//clean up anything else that couldn't be set due to the note being created without knowledge of its delegate
if (!filename) {
filename = [[delegate uniqueFilenameForTitle:titleString fromNote:self] retain];
}
}
static FSRef *noteFileRefInit(NoteObject* obj) {
if (!(obj->noteFileRef)) {
obj->noteFileRef = (FSRef*)calloc(1, sizeof(FSRef));
}
return obj->noteFileRef;
}
NSInteger compareFilename(id *one, id *two) {
return (NSInteger)CFStringCompare((CFStringRef)((*(NoteObject**)one)->filename),
(CFStringRef)((*(NoteObject**)two)->filename), kCFCompareCaseInsensitive);
}
NSInteger compareDateModified(id *a, id *b) {
return (*(NoteObject**)a)->modifiedDate - (*(NoteObject**)b)->modifiedDate;
}
NSInteger compareDateCreated(id *a, id *b) {
return (*(NoteObject**)a)->createdDate - (*(NoteObject**)b)->createdDate;
}
NSInteger compareLabelString(id *a, id *b) {
return (NSInteger)CFStringCompare((CFStringRef)(labelsOfNote(*(NoteObject **)a)),
(CFStringRef)(labelsOfNote(*(NoteObject **)b)), kCFCompareCaseInsensitive);
}
NSInteger compareTitleString(id *a, id *b) {
CFComparisonResult stringResult = CFStringCompare((CFStringRef)(titleOfNote(*(NoteObject**)a)),
(CFStringRef)(titleOfNote(*(NoteObject**)b)),
kCFCompareCaseInsensitive);
if (stringResult == kCFCompareEqualTo) {
NSInteger dateResult = compareDateCreated(a, b);
if (!dateResult)
return compareUniqueNoteIDBytes(a, b);
return dateResult;
}
return (NSInteger)stringResult;
}
NSInteger compareUniqueNoteIDBytes(id *a, id *b) {
return memcmp((&(*(NoteObject**)a)->uniqueNoteIDBytes), (&(*(NoteObject**)b)->uniqueNoteIDBytes), sizeof(CFUUIDBytes));
}
NSInteger compareDateModifiedReverse(id *a, id *b) {
return (*(NoteObject**)b)->modifiedDate - (*(NoteObject**)a)->modifiedDate;
}
NSInteger compareDateCreatedReverse(id *a, id *b) {
return (*(NoteObject**)b)->createdDate - (*(NoteObject**)a)->createdDate;
}
NSInteger compareLabelStringReverse(id *a, id *b) {
return (NSInteger)CFStringCompare((CFStringRef)(labelsOfNote(*(NoteObject **)b)),
(CFStringRef)(labelsOfNote(*(NoteObject **)a)), kCFCompareCaseInsensitive);
}
NSInteger compareTitleStringReverse(id *a, id *b) {
CFComparisonResult stringResult = CFStringCompare((CFStringRef)(titleOfNote(*(NoteObject **)b)),
(CFStringRef)(titleOfNote(*(NoteObject **)a)),
kCFCompareCaseInsensitive);
if (stringResult == kCFCompareEqualTo) {
NSInteger dateResult = compareDateCreatedReverse(a, b);
if (!dateResult)
return compareUniqueNoteIDBytes(b, a);
return dateResult;
}
return (NSInteger)stringResult;
}
NSInteger compareNodeID(id *a, id *b) {
return (*(NoteObject**)a)->nodeID - (*(NoteObject**)b)->nodeID;
}
//syncing w/ server and from journal; these should be objc methods so we can use polymorphism
- (CFUUIDBytes *)uniqueNoteIDBytes {
return &uniqueNoteIDBytes;
}
- (unsigned int)serverModifiedDate {
return serverModifiedTime;
}
- (unsigned int)logSequenceNumber {
return logSequenceNumber;
}
- (void)incrementLSN {
logSequenceNumber++;
}
- (BOOL)youngerThanLogObject:(id<SynchronizedNote>)obj {
return [self logSequenceNumber] < [obj logSequenceNumber];
}
//inlines won't make a difference in GCC, as these functions are called almost exclusively from other files
force_inline NSString* wordCountOfNote(NoteObject *note) {
return note->wordCountString;
}
force_inline NSString* filenameOfNote(NoteObject *note) {
return note->filename;
}
force_inline UInt32 fileNodeIDOfNote(NoteObject *note) {
return note->nodeID;
}
force_inline NSString* titleOfNote(NoteObject *note) {
return note->titleString;
}
force_inline NSString* labelsOfNote(NoteObject *note) {
return note->labelString;
}
force_inline NSAttributedString* tableTitleOfNote(NoteObject *note) {
return note->tableTitleString;
}
force_inline UTCDateTime fileModifiedDateOfNote(NoteObject *note) {
return note->fileModifiedDate;
}
force_inline CFAbsoluteTime modifiedDateOfNote(NoteObject *note) {
return note->modifiedDate;
}
force_inline int storageFormatOfNote(NoteObject *note) {
return note->currentFormatID;
}
force_inline NSStringEncoding fileEncodingOfNote(NoteObject *note) {
return note->fileEncoding;
}
force_inline NSString *dateCreatedStringOfNote(NoteObject *note) {
return note->dateCreatedString;
}
force_inline NSString *dateModifiedStringOfNote(NoteObject *note) {
return note->dateModifiedString;
}
//make notationcontroller should send setDelegate: and setLabelString: (if necessary) to each note when unarchiving this way
//there is no measurable difference in speed when using decodeValuesOfObjCTypes, oddly enough
//the overhead of the _decodeObject* C functions must be significantly greater than the objc_msgSend and argument passing overhead
#define DECODE_INDIVIDUALLY 1
- (id)initWithCoder:(NSCoder*)decoder {
if ([self init]) {
if ([decoder allowsKeyedCoding]) {
//(hopefully?) no versioning necessary here
modifiedDate = [decoder decodeDoubleForKey:VAR_STR(modifiedDate)];
createdDate = [decoder decodeDoubleForKey:VAR_STR(createdDate)];
selectedRange.location = [decoder decodeInt32ForKey:@"selectionRangeLocation"];
selectedRange.length = [decoder decodeInt32ForKey:@"selectionRangeLength"];
contentsWere7Bit = [decoder decodeBoolForKey:VAR_STR(contentsWere7Bit)];
logSequenceNumber = [decoder decodeInt32ForKey:VAR_STR(logSequenceNumber)];
currentFormatID = [decoder decodeInt32ForKey:VAR_STR(currentFormatID)];
nodeID = [decoder decodeInt32ForKey:VAR_STR(nodeID)];
fileModifiedDate.highSeconds = [decoder decodeInt32ForKey:@"fileModDateHigh"];
fileModifiedDate.lowSeconds = [decoder decodeInt32ForKey:@"fileModDateLow"];
fileModifiedDate.fraction = [decoder decodeInt32ForKey:@"fileModDateFrac"];
fileEncoding = [decoder decodeInt32ForKey:VAR_STR(fileEncoding)];
NSUInteger decodedByteCount;
const uint8_t *decodedBytes = [decoder decodeBytesForKey:VAR_STR(uniqueNoteIDBytes) returnedLength:&decodedByteCount];
if (decodedBytes) memcpy(&uniqueNoteIDBytes, decodedBytes, MIN(decodedByteCount, sizeof(CFUUIDBytes)));
serverModifiedTime = [decoder decodeInt32ForKey:VAR_STR(serverModifiedTime)];
titleString = [[decoder decodeObjectForKey:VAR_STR(titleString)] retain];
labelString = [[decoder decodeObjectForKey:VAR_STR(labelString)] retain];
contentString = [[decoder decodeObjectForKey:VAR_STR(contentString)] retain];
filename = [[decoder decodeObjectForKey:VAR_STR(filename)] retain];
} else {
NSRange32 range32;
float scrolledProportion = 0.0;
#if __LP64__
unsigned long longTemp;
#endif
#if DECODE_INDIVIDUALLY
[decoder decodeValueOfObjCType:@encode(CFAbsoluteTime) at:&modifiedDate];
[decoder decodeValueOfObjCType:@encode(CFAbsoluteTime) at:&createdDate];
#if __LP64__
[decoder decodeValueOfObjCType:"{_NSRange=II}" at:&range32];
#else
[decoder decodeValueOfObjCType:@encode(NSRange) at:&range32];
#endif
[decoder decodeValueOfObjCType:@encode(float) at:&scrolledProportion];
[decoder decodeValueOfObjCType:@encode(unsigned int) at:&logSequenceNumber];
[decoder decodeValueOfObjCType:@encode(int) at:¤tFormatID];
#if __LP64__
[decoder decodeValueOfObjCType:"L" at:&longTemp];
nodeID = (UInt32)longTemp;
#else
[decoder decodeValueOfObjCType:@encode(UInt32) at:&nodeID];
#endif
[decoder decodeValueOfObjCType:@encode(UInt16) at:&fileModifiedDate.highSeconds];
#if __LP64__
[decoder decodeValueOfObjCType:"L" at:&longTemp];
fileModifiedDate.lowSeconds = (UInt32)longTemp;
#else
[decoder decodeValueOfObjCType:@encode(UInt32) at:&fileModifiedDate.lowSeconds];
#endif
[decoder decodeValueOfObjCType:@encode(UInt16) at:&fileModifiedDate.fraction];
#if __LP64__
[decoder decodeValueOfObjCType:"I" at:&fileEncoding];
#else
[decoder decodeValueOfObjCType:@encode(NSStringEncoding) at:&fileEncoding];
#endif
[decoder decodeValueOfObjCType:@encode(CFUUIDBytes) at:&uniqueNoteIDBytes];
[decoder decodeValueOfObjCType:@encode(unsigned int) at:&serverModifiedTime];
titleString = [[decoder decodeObject] retain];
labelString = [[decoder decodeObject] retain];
contentString = [[decoder decodeObject] retain];
filename = [[decoder decodeObject] retain];
#else
[decoder decodeValuesOfObjCTypes: "dd{NSRange=ii}fIiI{UTCDateTime=SIS}I[16C]I@@@@", &modifiedDate, &createdDate, &range32,
&scrolledProportion, &logSequenceNumber, ¤tFormatID, &nodeID, &fileModifiedDate, &fileEncoding, &uniqueNoteIDBytes,
&serverModifiedTime, &titleString, &labelString, &contentString, &filename];
#endif
selectedRange.location = range32.location;
selectedRange.length = range32.length;
contentsWere7Bit = (*(unsigned int*)&scrolledProportion) != 0; //hacko wacko
}
//re-created at runtime to save space
[self initContentCacheCString];
cTitleFoundPtr = cTitle = titleString ? strdup([titleString lowercaseUTF8String]) : NULL;
cLabelsFoundPtr = cLabels = labelString ? strdup([labelString lowercaseUTF8String]) : NULL;
dateCreatedString = [[NSString relativeDateStringWithAbsoluteTime:createdDate] retain];
dateModifiedString = [[NSString relativeDateStringWithAbsoluteTime:modifiedDate] retain];
//[self updateTablePreviewString];
if (!titleString && !contentString && !labelString) return nil;
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder {
if ([coder allowsKeyedCoding]) {
[coder encodeDouble:modifiedDate forKey:VAR_STR(modifiedDate)];
[coder encodeDouble:createdDate forKey:VAR_STR(createdDate)];
[coder encodeInt32:(unsigned int)selectedRange.location forKey:@"selectionRangeLocation"];
[coder encodeInt32:(unsigned int)selectedRange.length forKey:@"selectionRangeLength"];
[coder encodeBool:contentsWere7Bit forKey:VAR_STR(contentsWere7Bit)];
[coder encodeInt32:logSequenceNumber forKey:VAR_STR(logSequenceNumber)];
[coder encodeInt32:currentFormatID forKey:VAR_STR(currentFormatID)];
[coder encodeInt32:nodeID forKey:VAR_STR(nodeID)];
[coder encodeInt32:fileModifiedDate.highSeconds forKey:@"fileModDateHigh"];
[coder encodeInt32:fileModifiedDate.lowSeconds forKey:@"fileModDateLow"];
[coder encodeInt32:fileModifiedDate.fraction forKey:@"fileModDateFrac"];
[coder encodeInt32:fileEncoding forKey:VAR_STR(fileEncoding)];
[coder encodeBytes:(const uint8_t *)&uniqueNoteIDBytes length:sizeof(CFUUIDBytes) forKey:VAR_STR(uniqueNoteIDBytes)];
[coder encodeInt32:serverModifiedTime forKey:VAR_STR(serverModifiedTime)];
[coder encodeObject:titleString forKey:VAR_STR(titleString)];
[coder encodeObject:labelString forKey:VAR_STR(labelString)];
[coder encodeObject:contentString forKey:VAR_STR(contentString)];
[coder encodeObject:filename forKey:VAR_STR(filename)];
} else {
// 64bit encoding would break 32bit reading - keyed archives should be used
#if !__LP64__
float scrolledProportion = 0.0;
*(unsigned int*)&scrolledProportion = (unsigned int)contentsWere7Bit;
#if DECODE_INDIVIDUALLY
[coder encodeValueOfObjCType:@encode(CFAbsoluteTime) at:&modifiedDate];
[coder encodeValueOfObjCType:@encode(CFAbsoluteTime) at:&createdDate];
[coder encodeValueOfObjCType:@encode(NSRange) at:&selectedRange];
[coder encodeValueOfObjCType:@encode(float) at:&scrolledProportion];
[coder encodeValueOfObjCType:@encode(unsigned int) at:&logSequenceNumber];
[coder encodeValueOfObjCType:@encode(int) at:¤tFormatID];
[coder encodeValueOfObjCType:@encode(UInt32) at:&nodeID];
[coder encodeValueOfObjCType:@encode(UInt16) at:&fileModifiedDate.highSeconds];
[coder encodeValueOfObjCType:@encode(UInt32) at:&fileModifiedDate.lowSeconds];
[coder encodeValueOfObjCType:@encode(UInt16) at:&fileModifiedDate.fraction];
[coder encodeValueOfObjCType:@encode(NSStringEncoding) at:&fileEncoding];
[coder encodeValueOfObjCType:@encode(CFUUIDBytes) at:&uniqueNoteIDBytes];
[coder encodeValueOfObjCType:@encode(unsigned int) at:&serverModifiedTime];
[coder encodeObject:titleString];
[coder encodeObject:labelString];
[coder encodeObject:contentString];
[coder encodeObject:filename];
#else
[coder encodeValuesOfObjCTypes: "dd{NSRange=ii}fIiI{UTCDateTime=SIS}I[16C]I@@@@", &modifiedDate, &createdDate, &range32,
&scrolledProportion, &logSequenceNumber, ¤tFormatID, &nodeID, &fileModifiedDate, &fileEncoding, &uniqueNoteIDBytes,
&serverModifiedTime, &titleString, &labelString, &contentString, &filename];
#endif
#endif // !__LP64__
}
}
- (id)initWithNoteBody:(NSAttributedString*)bodyText title:(NSString*)aNoteTitle uniqueFilename:(NSString*)aFilename format:(int)formatID {
if ([self init]) {
if (!bodyText || !aNoteTitle) {
return nil;
}
contentString = [[NSMutableAttributedString alloc] initWithAttributedString:bodyText];
[self initContentCacheCString];
if (!cContents) {
NSLog(@"couldn't get UTF8 string from contents?!?");
return nil;
}
if (![self _setTitleString:aNoteTitle])
titleString = NSLocalizedString(@"Untitled Note", @"Title of a nameless note");
//[self updateTablePreviewString];
labelString = @"";
cLabelsFoundPtr = cLabels = strdup("");
filename = [aFilename retain];
currentFormatID = formatID;
CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);
uniqueNoteIDBytes = CFUUIDGetUUIDBytes(uuidRef);
CFRelease(uuidRef);
createdDate = modifiedDate = CFAbsoluteTimeGetCurrent();
dateCreatedString = [dateModifiedString = [[NSString relativeDateStringWithAbsoluteTime:modifiedDate] retain] retain];
if (UCConvertCFAbsoluteTimeToUTCDateTime(modifiedDate, &fileModifiedDate) != noErr)
NSLog(@"Error initializing file modification date");
//delegate is not set yet, so we cannot dirty ourselves here
//[self makeNoteDirty];
}
return self;
}
//only get the fsrefs until we absolutely need them
- (id)initWithCatalogEntry:(NoteCatalogEntry*)entry delegate:(id)aDelegate {
if ([self init]) {
delegate = aDelegate;
filename = [(NSString*)entry->filename copy];
currentFormatID = [delegate currentNoteStorageFormat];
fileModifiedDate = entry->lastModified;
nodeID = entry->nodeID;
CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);
uniqueNoteIDBytes = CFUUIDGetUUIDBytes(uuidRef);
CFRelease(uuidRef);
if (![self _setTitleString:[filename stringByDeletingPathExtension]])
titleString = NSLocalizedString(@"Untitled Note", @"Title of a nameless note");
labelString = @""; //I'd like to get labels from getxattr
cLabelsFoundPtr = cLabels = strdup("");
contentString = [[NSMutableAttributedString alloc] initWithString:@""];
[self initContentCacheCString];
if (![self updateFromCatalogEntry:entry]) {
//just initialize a blank note for now; if the file becomes readable again we'll be updated
//but if we make modifications, well, the original is toast
//so warn the user here and offer to trash it?
//perhaps also offer to re-interpret using another text encoding?
//additionally, it is possible that the file was deleted before we could read it
}
if (!modifiedDate || !createdDate) {
modifiedDate = createdDate = CFAbsoluteTimeGetCurrent();
dateModifiedString = [dateCreatedString = [[NSString relativeDateStringWithAbsoluteTime:createdDate] retain] retain];
}
}
//[self updateTablePreviewString];
return self;
}
//assume any changes have been synchronized with undomanager
- (void)setContentString:(NSAttributedString*)attributedString {
if (attributedString) {
[contentString setAttributedString:attributedString];
//[self updateTablePreviewString];
contentCacheNeedsUpdate = YES;
//[self updateContentCacheCStringIfNecessary];
[self makeNoteDirtyUpdateTime:YES updateFile:YES];
}
}
- (NSAttributedString*)contentString {
return contentString;
}
- (void)updateContentCacheCStringIfNecessary {
if (contentCacheNeedsUpdate) {
//NSLog(@"updating ccache strs");
cContentsFoundPtr = cContents = replaceString(cContents, [[contentString string] lowercaseUTF8String]);
contentCacheNeedsUpdate = NO;
int len = strlen(cContents);
contentsWere7Bit = !(ContainsHighAscii(cContents, len));
//could cache dumbwordcount here for faster launch, but string creation takes more time, anyway
//if (wordCountString) CFRelease((CFStringRef*)wordCountString); //this is CFString, so bridge will just call back to CFRelease, anyway
//wordCountString = (NSString*)CFStringFromBase10Integer(DumbWordCount(cContents, len));
}
}
static int decoded7Bit = 0;
- (void)initContentCacheCString {
if (contentsWere7Bit) {
// NSLog(@"decoding %X as 7-bit", self);
decoded7Bit++;
if (!(cContentsFoundPtr = cContents = [[contentString string] copyLowercaseASCIIString]))
contentsWere7Bit = NO;
}
size_t len = -1;
if (!contentsWere7Bit) {
const char *cStringData = [[contentString string] lowercaseUTF8String];
cContentsFoundPtr = cContents = cStringData ? strdup(cStringData) : NULL;
contentsWere7Bit = cContents ? !(ContainsHighAscii(cContents, (len = strlen(cContents)))) : NO;
}
//if (len < 0) len = strlen(cContents);
//wordCountString = (NSString*)CFStringFromBase10Integer(DumbWordCount(cContents, len));
contentCacheNeedsUpdate = NO;
}
- (BOOL)contentsWere7Bit {
return contentsWere7Bit;
}
int decodedCount() {
return decoded7Bit;
}
- (NSAttributedString*)printableStringRelativeToBodyFont:(NSFont*)bodyFont {
NSFont *titleFont = [NSFont fontWithName:[bodyFont fontName] size:[bodyFont pointSize] + 6.0f];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:titleFont, NSFontAttributeName, nil];
NSMutableAttributedString *largeAttributedTitleString = [[[NSMutableAttributedString alloc] initWithString:titleString attributes:dict] autorelease];
NSAttributedString *noAttrBreak = [[NSAttributedString alloc] initWithString:@"\n\n\n" attributes:nil];
[largeAttributedTitleString appendAttributedString:noAttrBreak];
[noAttrBreak release];
//other header things here, too? like date created/mod/printed? tags?
[largeAttributedTitleString appendAttributedString:[self contentString]];
return largeAttributedTitleString;
}
- (void)updateTablePreviewString {
return;
[tableTitleString release];
tableTitleString = [[titleString attributedPreviewFromBodyText:contentString] retain];
}
- (void)setTitleString:(NSString*)aNewTitle {
NSString *oldTitle = [titleString retain];
if ([self _setTitleString:aNewTitle]) {
//do you really want to do this when the format is a single DB and the file on disk hasn't been removed?
//the filename could get out of sync if we lose the fsref and we could end up with a second file after note is rewritten
//solution: don't change the name in that case and allow its new name to be generated
//when the format is changed and the file rewritten?
//however, the filename is used for exporting and potentially other purposes, so we should also update
//it if we know that is has no currently existing (older) counterpart in the notes directory
//woe to the exporter who also left the note files in the notes directory after switching to a singledb format
//his note names might not be up-to-date
if ([delegate currentNoteStorageFormat] != SingleDatabaseFormat ||
![delegate notesDirectoryContainsFile:filename returningFSRef:noteFileRefInit(self)]) {
[self setFilenameFromTitle];
}
//yes, the given extension could be different from what we had before
//but makeNoteDirty will eventually cause it to be re-written in the current format
//and thus the format ID will be changed if that was the case
[self makeNoteDirtyUpdateTime:YES updateFile:YES];
//[self updateTablePreviewString];
/*NSUndoManager *undoMan = [delegate undoManager];
[undoMan registerUndoWithTarget:self selector:@selector(setTitleString:) object:oldTitle];
if (![undoMan isUndoing] && ![undoMan isRedoing])
[undoMan setActionName:[NSString stringWithFormat:@"Rename Note \"%@\"", titleString]];
*/
[oldTitle release];
[delegate note:self attributeChanged:NoteTitleColumnString];
}
}
- (BOOL)_setTitleString:(NSString*)aNewTitle {
if (!aNewTitle || ![aNewTitle length] || (titleString && [aNewTitle isEqualToString:titleString]))
return NO;
[titleString release];
titleString = [aNewTitle copy];
cTitleFoundPtr = cTitle = replaceString(cTitle, [titleString lowercaseUTF8String]);
return YES;
}
- (void)setFilenameFromTitle {
[self setFilename:[delegate uniqueFilenameForTitle:titleString fromNote:self] withExternalTrigger:NO];
}
- (void)setFilename:(NSString*)aString withExternalTrigger:(BOOL)externalTrigger {
if (!filename || ![aString isEqualToString:filename]) {
NSString *oldName = filename;
filename = [aString copy];
if (!externalTrigger) {
if ([delegate noteFileRenamed:noteFileRefInit(self) fromName:oldName toName:filename] != noErr) {
NSLog(@"Couldn't rename note %@", titleString);
//revert name
[filename release];
filename = [oldName retain];
return;
}
} else {
[self _setTitleString:[aString stringByDeletingPathExtension]];
[delegate note:self attributeChanged:NoteTitleColumnString];
}
[self makeNoteDirtyUpdateTime:YES updateFile:NO];
[delegate updateLinksToNote:self fromOldName:oldName];
//update all the notes that link to the old filename as well!!
[oldName release];
}
}
//how do we write a thousand RTF files at once, repeatedly?
- (void)updateUnstyledTextWithBaseFont:(NSFont*)baseFont {
if ([contentString restyleTextToFont:[[GlobalPrefs defaultPrefs] noteBodyFont] usingBaseFont:baseFont] > 0) {
[undoManager removeAllActions];
if ([delegate currentNoteStorageFormat] == RTFTextFormat)
[self makeNoteDirtyUpdateTime:NO updateFile:YES];
}
}
- (void)updateDateStrings {
[dateModifiedString release];
[dateCreatedString release];
dateCreatedString = [[NSString relativeDateStringWithAbsoluteTime:createdDate] retain];
dateModifiedString = [[NSString relativeDateStringWithAbsoluteTime:modifiedDate] retain];
}
- (void)setDateModified:(CFAbsoluteTime)newTime {
modifiedDate = newTime;
[dateModifiedString release];
dateModifiedString = [[NSString relativeDateStringWithAbsoluteTime:modifiedDate] retain];
}
- (void)setDateAdded:(CFAbsoluteTime)newTime {
createdDate = newTime;
[dateCreatedString release];
dateCreatedString = [[NSString relativeDateStringWithAbsoluteTime:createdDate] retain];
}
- (void)setSelectedRange:(NSRange)newRange {
//if (!newRange.length) newRange = NSMakeRange(0,0);
//don't save the range if it's invalid, it's equal to the current range, or the entire note is selected
if ((newRange.location != NSNotFound) && !NSEqualRanges(newRange, selectedRange) &&
!NSEqualRanges(newRange, NSMakeRange(0, [contentString length]))) {
// NSLog(@"saving: old range: %@, new range: %@", NSStringFromRange(selectedRange), NSStringFromRange(newRange));
selectedRange = newRange;
[self makeNoteDirtyUpdateTime:NO updateFile:NO];
}
}
- (NSRange)lastSelectedRange {
return selectedRange;
}
//these two methods let us get the actual label objects in use by other notes
//they assume that the label string already contains the title of the label object(s); that there is only replacement and not addition
- (void)replaceMatchingLabelSet:(NSSet*)aLabelSet {
[labelSet minusSet:aLabelSet];
[labelSet unionSet:aLabelSet];
}
- (void)replaceMatchingLabel:(LabelObject*)aLabel {
[aLabel retain]; // just in case this is actually the same label
//remove the old label and add the new one; if this is the same one, well, too bad
[labelSet removeObject:aLabel];
[labelSet addObject:aLabel];
[aLabel release];
}
- (void)updateLabelConnectionsAfterDecoding {
if ([labelString length] > 0) {
[self updateLabelConnections];
}
}
- (void)updateLabelConnections {
return;
//find differences between previous labels and new ones
NSMutableSet *oldLabelSet = labelSet;
NSMutableSet *newLabelSet = [labelString labelSetFromWordsAndContainingNote:self];
//what's left-over
NSMutableSet *oldLabels = [oldLabelSet mutableCopy];
[oldLabels minusSet:newLabelSet];
//what wasn't there last time
NSMutableSet *newLabels = newLabelSet;
[newLabels minusSet:oldLabelSet];
//update the currently known labels
[labelSet minusSet:oldLabels];
[labelSet unionSet:newLabels];
//update our status within the list of all labels, adding or removing from the list and updating the labels where appropriate
//these end up calling replaceMatchingLabel*
[delegate note:self didRemoveLabelSet:oldLabels];
[delegate note:self didAddLabelSet:newLabels];
}
- (void)setLabelString:(NSString*)newLabelString {
if (newLabelString && ![newLabelString isEqualToString:labelString]) {
[labelString release];
labelString = [newLabelString copy];
cLabelsFoundPtr = cLabels = replaceString(cLabels, [labelString lowercaseUTF8String]);
[self updateLabelConnections];
[self makeNoteDirtyUpdateTime:YES updateFile:NO];
[delegate note:self attributeChanged:NoteLabelsColumnString];
}
}
- (NSString*)noteFilePath {
if (IsZeros(noteFileRefInit(self), sizeof(FSRef))) {
if (![delegate notesDirectoryContainsFile:filename returningFSRef:noteFileRefInit(self)])
return nil;
}
return [NSString pathWithFSRef:noteFileRefInit(self)];
}
- (void)invalidateFSRef {
//bzero(¬eFileRef, sizeof(FSRef));
if (noteFileRef)
free(noteFileRef);
noteFileRef = NULL;
}
- (BOOL)writeUsingCurrentFileFormatIfNecessary {
//if note had been updated via makeNoteDirty and needed file to be rewritten
if (shouldWriteToFile) {
return [self writeUsingCurrentFileFormat];
}
return NO;
}
- (BOOL)writeUsingCurrentFileFormatIfNonExistingOrChanged {
BOOL fileWasCreated = NO;
BOOL fileIsOwned = NO;
if ([delegate createFileIfNotPresentInNotesDirectory:noteFileRefInit(self) forFilename:filename fileWasCreated:&fileWasCreated] != noErr)
return NO;
if (fileWasCreated) {
NSLog(@"writing note %@, because it didn't exist", titleString);
return [self writeUsingCurrentFileFormat];
}
FSCatalogInfo info;
if ([delegate fileInNotesDirectory:noteFileRefInit(self) isOwnedByUs:&fileIsOwned hasCatalogInfo:&info] != noErr)
return NO;
CFAbsoluteTime timeOnDisk, lastTime;
OSStatus err = noErr;
if ((err = (UCConvertUTCDateTimeToCFAbsoluteTime(&fileModifiedDate, &lastTime) == noErr)) &&
(err = (UCConvertUTCDateTimeToCFAbsoluteTime(&info.contentModDate, &timeOnDisk) == noErr))) {
if (lastTime > timeOnDisk) {
NSLog(@"writing note %@, because it was modified", titleString);
return [self writeUsingCurrentFileFormat];
}
} else {
NSLog(@"Could not convert dates: %d", err);
return NO;
}
return YES;
}
- (BOOL)writeUsingJournal:(WALStorageController*)wal {
BOOL wroteAllOfNote = [wal writeEstablishedNote:self];
if (wroteAllOfNote) {
//update formatID to absolutely ensure we don't reload an earlier note back from disk, from text encoding menu, for example
//currentFormatID = SingleDatabaseFormat;
} else {
[delegate noteDidNotWrite:self errorCode:kWriteJournalErr];
}
return wroteAllOfNote;
}
#if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_4
#define NSDocumentTypeDocumentAttribute @"DocumentType"
#endif
- (BOOL)writeUsingCurrentFileFormat {
NSData *formattedData = nil;
NSError *error = nil;
int formatID = [delegate currentNoteStorageFormat];
switch (formatID) {
case SingleDatabaseFormat:
//we probably shouldn't be here
NSAssert(NO, @"Warning! Tried to write data for an individual note in single-db format!");
return NO;
case PlainTextFormat:
if (!(formattedData = [[contentString string] dataUsingEncoding:fileEncoding allowLossyConversion:NO])) {
//just make the file unicode and ram it through
//unicode is probably better than UTF-8, as it's more easily auto-detected by other programs via the BOM
//but we can auto-detect UTF-8, so what the heck
[self _setFileEncoding:NSUTF8StringEncoding];
//maybe we could rename the file file.utf8.txt here
NSLog(@"promoting to unicode (UTF-8)");
formattedData = [[contentString string] dataUsingEncoding:fileEncoding allowLossyConversion:YES];
}
break;
case RTFTextFormat:
formattedData = [contentString RTFFromRange:NSMakeRange(0, [contentString length]) documentAttributes:nil];
break;
case HTMLFormat:
//10.4-only
if (RunningTigerAppKitOrHigher) {
//export to HTML document here using NSHTMLTextDocumentType;
formattedData = [contentString dataFromRange:NSMakeRange(0, [contentString length])
documentAttributes:[NSDictionary dictionaryWithObject:NSHTMLTextDocumentType
forKey:NSDocumentTypeDocumentAttribute] error:&error];
} else {
NSLog(@"Attempted to write a note as HTML on 10.3.9.");
}
//our links will always be to filenames, so hopefully we shouldn't have to change anything
break;
default:
NSLog(@"Attempted to write using unknown format ID: %d", formatID);
//return NO;
}
if (formattedData) {
BOOL resetFilename = NO;
if (!filename || currentFormatID != formatID) {
//file will (probably) be renamed
NSLog(@"resetting the file name due to format change: to %d from %d", formatID, currentFormatID);
[self setFilenameFromTitle];
resetFilename = YES;
}
currentFormatID = formatID;
OSStatus err = noErr;
if ((err = [delegate storeDataAtomicallyInNotesDirectory:formattedData withName:filename destinationRef:noteFileRefInit(self)]) != noErr) {
NSLog(@"Unable to save note file %@", filename);
[delegate noteDidNotWrite:self errorCode:err];
return NO;
}
//if writing plaintext set the file encoding with setxattr
if (PlainTextFormat == formatID) {
(void)[self writeCurrentFileEncodingToFSRef:noteFileRefInit(self)];
}
if (!resetFilename) {
//NSLog(@"resetting the file name just because.");
[self setFilenameFromTitle];
}
FSCatalogInfo info;
if ([delegate fileInNotesDirectory:noteFileRefInit(self) isOwnedByUs:NULL hasCatalogInfo:&info] != noErr) {
NSLog(@"Unable to get new modification date of file %@", filename);
return NO;
}
fileModifiedDate = info.contentModDate;
nodeID = info.nodeID;
//finished writing to file successfully
shouldWriteToFile = NO;
//tell any external editors that we've changed
} else {
[delegate noteDidNotWrite:self errorCode:kDataFormattingErr];
NSLog(@"Unable to convert note contents into format %d", formatID);
return NO;
}
return YES;
}
- (OSStatus)writeCurrentFileEncodingToFSRef:(FSRef*)fsRef {
NSAssert(fsRef, @"cannot write file encoding to a NULL FSRef");
//this is not the note's own fsRef; it could be anywhere
if (!RunningTigerAppKitOrHigher) return noErr;
NSMutableData *pathData = [NSMutableData dataWithLength:4 * 1024];
OSStatus err = noErr;
if ((err = FSRefMakePath(fsRef, [pathData mutableBytes], [pathData length])) == noErr) {
[NSString setTextEncodingAttribute:fileEncoding atFSPath:[pathData bytes]];
} else {
NSLog(@"%s: error getting path from FSRef: %d (IsZeros: %d)", _cmd, err, IsZeros(fsRef, sizeof(fsRef)));
}
return err;
}
- (BOOL)upgradeToUTF8IfUsingSystemEncoding {
if (CFStringConvertEncodingToNSStringEncoding(CFStringGetSystemEncoding()) == fileEncoding)
return [self upgradeEncodingToUTF8];
return NO;
}
- (BOOL)upgradeEncodingToUTF8 {
//"convert" the file to have a UTF-8 encoding
BOOL didUpgrade = YES;
if (NSUTF8StringEncoding != fileEncoding) {
[self _setFileEncoding:NSUTF8StringEncoding];
if (!contentsWere7Bit && PlainTextFormat == currentFormatID) {
//this note exists on disk as a plaintext file, and its encoding is incompatible with UTF-8
if ([delegate currentNoteStorageFormat] == PlainTextFormat) {
//actual conversion is expected because notes are presently being maintained as plain text files
NSLog(@"rewriting %@ as utf8 data", titleString);
didUpgrade = [self writeUsingCurrentFileFormat];
} else if ([delegate currentNoteStorageFormat] == SingleDatabaseFormat) {
//update last-written-filemod time to guarantee proper encoding at next DB storage format switch,
//in case this note isn't otherwise modified before that happens.
//a side effect is that if the user switches to an RTF or HTML format,
//this note will be written immediately instead of lazily upon the next modification
if (UCConvertCFAbsoluteTimeToUTCDateTime(CFAbsoluteTimeGetCurrent(), &fileModifiedDate) != noErr)
NSLog(@"%s: can't set file modification date from current date", _cmd);
}
}
//make note dirty to ensure these changes are saved
[self makeNoteDirtyUpdateTime:NO updateFile:NO];