forked from ttscoff/nv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NoteObject.m
executable file
·1908 lines (1504 loc) · 70.3 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 (c) 2010, Zachary Schneirov. All rights reserved.
This file is part of Notational Velocity.
Notational Velocity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Notational Velocity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Notational Velocity. If not, see <http://www.gnu.org/licenses/>. */
#import "NoteObject.h"
#import "GlobalPrefs.h"
#import "LabelObject.h"
#import "WALController.h"
#import "NotationController.h"
#import "NotationPrefs.h"
#import "AttributedPlainText.h"
#import "NSString_CustomTruncation.h"
#import "NSFileManager_NV.h"
#include "BufferUtils.h"
#import "NotationFileManager.h"
#import "NotationSyncServiceManager.h"
#import "SyncServiceSessionProtocol.h"
#import "SyncSessionController.h"
#import "ExternalEditorListController.h"
#import "NSData_transformations.h"
#import "NSCollection_utils.h"
#import "NotesTableView.h"
#import "UnifiedCell.h"
#import "LabelColumnCell.h"
#import "ODBEditor.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);
static void setAttrModifiedDate(NoteObject *note, UTCDateTime *dateTime);
static void setCatalogNodeID(NoteObject *note, UInt32 cnid);
- (id)init {
if (self=[super init]) {
perDiskInfoGroups = calloc(1, sizeof(PerDiskInfo));
perDiskInfoGroups[0].diskIDIndex = -1;
perDiskInfoGroupCount = 1;
currentFormatID = SingleDatabaseFormat;
fileEncoding = NSUTF8StringEncoding;
selectedRange = NSMakeRange(NSNotFound, 0);
//other instance variables initialized on demand
return self;
}
return nil;
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[self invalidateFSRef];
[tableTitleString release];
[titleString release];
[labelString release];
[labelSet release];
[undoManager release];
[filename release];
[dateModifiedString release];
[dateCreatedString release];
[prefixParentNotes release];
if (perDiskInfoGroups)
free(perDiskInfoGroups);
if (cTitle)
free(cTitle);
if (cContents)
free(cContents);
if (cLabels)
free(cLabels);
[super dealloc];
}
- (id)delegate {
return delegate;
}
- (void)setDelegate:(id)theDelegate {
if (theDelegate) {
delegate = theDelegate;
//do things that ought to have been done during init, but were not possible due to lack of delegate information
if (!filename) filename = [[delegate uniqueFilenameForTitle:titleString fromNote:self] retain];
if (!tableTitleString && !didUnarchive) [self updateTablePreviewString];
if (!labelSet && !didUnarchive) [self updateLabelConnectionsAfterDecoding];
}
}
static FSRef *noteFileRefInit(NoteObject* obj) {
if (!(obj->noteFileRef)) {
obj->noteFileRef = (FSRef*)calloc(1, sizeof(FSRef));
}
return obj->noteFileRef;
}
static void setAttrModifiedDate(NoteObject *note, UTCDateTime *dateTime) {
unsigned int idx = SetPerDiskInfoWithTableIndex(dateTime, NULL, (UInt32)diskUUIDIndexForNotation(note->delegate),
&(note->perDiskInfoGroups), &(note->perDiskInfoGroupCount));
note->attrsModifiedDate = &(note->perDiskInfoGroups[idx].attrTime);
}
static void setCatalogNodeID(NoteObject *note, UInt32 cnid) {
SetPerDiskInfoWithTableIndex(NULL, &cnid, (UInt32)diskUUIDIndexForNotation(note->delegate),
&(note->perDiskInfoGroups), &(note->perDiskInfoGroupCount));
note->nodeID = cnid;
}
UTCDateTime *attrsModifiedDateOfNote(NoteObject *note) {
//once unarchived, the disk UUID index won't change, so this pointer will always reflect the current attr mod time
if (!note->attrsModifiedDate) {
//init from delegate based on disk table index
unsigned int i, tableIndex = (UInt32)diskUUIDIndexForNotation(note->delegate);
for (i=0; i<note->perDiskInfoGroupCount; i++) {
//check if this date has actually been initialized; this entry could be here only because setCatalogNodeID was called
if (note->perDiskInfoGroups[i].diskIDIndex == tableIndex && !UTCDateTimeIsEmpty(note->perDiskInfoGroups[i].attrTime)) {
note->attrsModifiedDate = &(note->perDiskInfoGroups[i].attrTime);
goto giveDate;
}
}
//this note doesn't have a file-modified date, so initialize a fairly reasonable one here
setAttrModifiedDate(note, &(note->fileModifiedDate));
}
giveDate:
return note->attrsModifiedDate;
}
UInt32 fileNodeIDOfNote(NoteObject *note) {
if (!note->nodeID) {
unsigned int i, tableIndex = (UInt32)diskUUIDIndexForNotation(note->delegate);
for (i=0; i<note->perDiskInfoGroupCount; i++) {
//check if this nodeID has actually been initialized; this entry could be here only because setAttrModifiedDate was called
if (note->perDiskInfoGroups[i].diskIDIndex == tableIndex && note->perDiskInfoGroups[i].nodeID != 0U) {
note->nodeID = note->perDiskInfoGroups[i].nodeID;
goto giveID;
}
}
//this note doesn't have a file-modified date, so initialize something that at least won't repeat this lookup
setCatalogNodeID(note, 1);
}
giveID:
return note->nodeID;
}
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) {
//add kCFCompareNumerically to options for natural order sort
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 fileNodeIDOfNote(*(NoteObject**)a) - fileNodeIDOfNote(*(NoteObject**)b);
}
NSInteger compareFileSize(id *a, id *b) {
return (*(NoteObject**)a)->logicalSize - (*(NoteObject**)b)->logicalSize;
}
#include "SynchronizedNoteMixIns.h"
//syncing w/ server and from journal;
DefModelAttrAccessor(filenameOfNote, filename)
DefModelAttrAccessor(fileSizeOfNote, logicalSize)
DefModelAttrAccessor(titleOfNote, titleString)
DefModelAttrAccessor(labelsOfNote, labelString)
DefModelAttrAccessor(fileModifiedDateOfNote, fileModifiedDate)
DefModelAttrAccessor(modifiedDateOfNote, modifiedDate)
DefModelAttrAccessor(createdDateOfNote, createdDate)
DefModelAttrAccessor(storageFormatOfNote, currentFormatID)
DefModelAttrAccessor(fileEncodingOfNote, fileEncoding)
DefModelAttrAccessor(prefixParentsOfNote, prefixParentNotes)
//DefColAttrAccessor(wordCountOfNote, wordCountString)
DefColAttrAccessor(titleOfNote2, titleString)
DefColAttrAccessor(dateCreatedStringOfNote, dateCreatedString)
DefColAttrAccessor(dateModifiedStringOfNote, dateModifiedString)
force_inline id tableTitleOfNote(NotesTableView *tv, NoteObject *note, NSInteger row) {
if (note->tableTitleString) return note->tableTitleString;
return titleOfNote(note);
}
force_inline id properlyHighlightingTableTitleOfNote(NotesTableView *tv, NoteObject *note, NSInteger row) {
if (note->tableTitleString) {
if ([tv isRowSelected:row]) {
return [note->tableTitleString string];
}
return note->tableTitleString;
}
return titleOfNote(note);
}
force_inline id labelColumnCellForNote(NotesTableView *tv, NoteObject *note, NSInteger row) {
LabelColumnCell *cell = [[tv tableColumnWithIdentifier:NoteLabelsColumnString] dataCellForRow:row];
[cell setNoteObject:note];
return labelsOfNote(note);
}
force_inline id unifiedCellSingleLineForNote(NotesTableView *tv, NoteObject *note, NSInteger row) {
id obj = note->tableTitleString ? (id)note->tableTitleString : (id)titleOfNote(note);
UnifiedCell *cell = [[[tv tableColumns] objectAtIndex:0] dataCellForRow:row];
[cell setNoteObject:note];
[cell setPreviewIsHidden:YES];
return obj;
}
force_inline id unifiedCellForNote(NotesTableView *tv, NoteObject *note, NSInteger row) {
//snow leopard is stricter about applying the default highlight-attributes (e.g., no shadow unless no paragraph formatting)
//so add the shadow here for snow leopard on selected rows
UnifiedCell *cell = [[[tv tableColumns] objectAtIndex:0] dataCellForRow:row];
[cell setNoteObject:note];
[cell setPreviewIsHidden:NO];
BOOL rowSelected = [tv isRowSelected:row];
BOOL drawShadow = IsSnowLeopardOrLater || (IsLeopardOrLater && rowSelected && [tv currentEditor]);
id obj = note->tableTitleString ? (rowSelected ? (id)AttributedStringForSelection(note->tableTitleString, drawShadow) :
(id)note->tableTitleString) : (id)titleOfNote(note);
return obj;
}
//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=[self init]) {
if ([decoder allowsKeyedCoding]) {
//(hopefully?) no versioning necessary here
//for knowing when to delay certain initializations during launch (e.g., preview generation)
didUnarchive = YES;
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)];
logicalSize = [decoder decodeInt32ForKey:VAR_STR(logicalSize)];
int64_t fileModifiedDate64 = [decoder decodeInt64ForKey:VAR_STR(fileModifiedDate)];
memcpy(&fileModifiedDate, &fileModifiedDate64, sizeof(int64_t));
NSUInteger decodedPerDiskByteCount = 0;
const uint8_t *decodedPerDiskBytes = [decoder decodeBytesForKey:VAR_STR(perDiskInfoGroups) returnedLength:&decodedPerDiskByteCount];
if (decodedPerDiskBytes && decodedPerDiskByteCount) {
CopyPerDiskInfoGroupsToOrder(&perDiskInfoGroups, &perDiskInfoGroupCount, (PerDiskInfo *)decodedPerDiskBytes, decodedPerDiskByteCount, 1);
}
fileEncoding = [decoder decodeInt32ForKey:VAR_STR(fileEncoding)];
NSUInteger decodedUUIDByteCount = 0;
const uint8_t *decodedUUIDBytes = [decoder decodeBytesForKey:VAR_STR(uniqueNoteIDBytes) returnedLength:&decodedUUIDByteCount];
if (decodedUUIDBytes) memcpy(&uniqueNoteIDBytes, decodedUUIDBytes, MIN(decodedUUIDByteCount, sizeof(CFUUIDBytes)));
syncServicesMD = [[decoder decodeObjectForKey:VAR_STR(syncServicesMD)] retain];
titleString = [[decoder decodeObjectForKey:VAR_STR(titleString)] retain];
labelString = [[decoder decodeObjectForKey:VAR_STR(labelString)] retain];
contentString = [[NSMutableAttributedString alloc] initWithAttributedString: [decoder decodeObjectForKey:VAR_STR(contentString)]];
filename = [[decoder decodeObjectForKey:VAR_STR(filename)] retain];
} else {
NSRange32 range32;
unsigned int serverModifiedTime = 0;
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] mutableCopy] 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];
if (!titleString && !contentString && !labelString) return nil;
return self;
}
return nil;
}
- (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 encodeInteger:currentFormatID forKey:VAR_STR(currentFormatID)];
[coder encodeInt32:logicalSize forKey:VAR_STR(logicalSize)];
uint8_t *flippedPerDiskInfoGroups = calloc(perDiskInfoGroupCount, sizeof(PerDiskInfo));
CopyPerDiskInfoGroupsToOrder((PerDiskInfo**)&flippedPerDiskInfoGroups, &perDiskInfoGroupCount, perDiskInfoGroups, perDiskInfoGroupCount * sizeof(PerDiskInfo), 0);
[coder encodeBytes:flippedPerDiskInfoGroups length:perDiskInfoGroupCount * sizeof(PerDiskInfo) forKey:VAR_STR(perDiskInfoGroups)];
free(flippedPerDiskInfoGroups);
[coder encodeInt64:*(int64_t*)&fileModifiedDate forKey:VAR_STR(fileModifiedDate)];
[coder encodeInt32:fileEncoding forKey:VAR_STR(fileEncoding)];
[coder encodeBytes:(const uint8_t *)&uniqueNoteIDBytes length:sizeof(CFUUIDBytes) forKey:VAR_STR(uniqueNoteIDBytes)];
[coder encodeObject:syncServicesMD forKey:VAR_STR(syncServicesMD)];
[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__
unsigned int serverModifiedTime = 0;
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 delegate:(id)aDelegate format:(NSInteger)formatID labels:(NSString*)aLabelString {
//delegate optional here
if (self=[self init]) {
if (!bodyText || !aNoteTitle) {
return nil;
}
delegate = aDelegate;
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");
if (![self _setLabelString:aLabelString]) {
labelString = @"";
cLabelsFoundPtr = cLabels = strdup("");
}
currentFormatID = formatID;
filename = [[delegate uniqueFilenameForTitle:titleString fromNote:nil] retain];
CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);
uniqueNoteIDBytes = CFUUIDGetUUIDBytes(uuidRef);
CFRelease(uuidRef);
createdDate = modifiedDate = CFAbsoluteTimeGetCurrent();
dateCreatedString = [dateModifiedString = [[NSString relativeDateStringWithAbsoluteTime:modifiedDate] retain] retain];
UCConvertCFAbsoluteTimeToUTCDateTime(modifiedDate, &fileModifiedDate);
if (delegate)
[self updateTablePreviewString];
return self;
}
return nil;
}
//only get the fsrefs until we absolutely need them
- (id)initWithCatalogEntry:(NoteCatalogEntry*)entry delegate:(id)aDelegate {
NSAssert(aDelegate != nil, @"must supply a delegate");
if (self=[self init]) {
delegate = aDelegate;
filename = [(NSString*)entry->filename copy];
currentFormatID = [delegate currentNoteStorageFormat];
fileModifiedDate = entry->lastModified;
setAttrModifiedDate(self, &(entry->lastAttrModified));
setCatalogNodeID(self, entry->nodeID);
logicalSize = entry->logicalSize;
CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);
uniqueNoteIDBytes = CFUUIDGetUUIDBytes(uuidRef);
CFRelease(uuidRef);
if (![self _setTitleString:[filename stringByDeletingPathExtension]])
titleString = NSLocalizedString(@"Untitled Note", @"Title of a nameless note");
labelString = @""; //set by updateFromCatalogEntry if there are openmeta extended attributes
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;
}
return nil;
}
//assume any changes have been synchronized with undomanager
- (void)setContentString:(NSAttributedString*)attributedString {
[self setContentString:attributedString updateTime:YES];
}
- (void)setContentString:(NSAttributedString*)attributedString updateTime:(BOOL)updateTime {
if (attributedString) {
[contentString setAttributedString:attributedString];
[self updateTablePreviewString];
contentCacheNeedsUpdate = YES;
//[self updateContentCacheCStringIfNecessary];
[delegate note:self attributeChanged:NotePreviewString];
[self makeNoteDirtyUpdateTime:updateTime updateFile:YES];
}
}
- (NSAttributedString*)contentString {
return contentString;
}
- (void)updateContentCacheCStringIfNecessary {
if (contentCacheNeedsUpdate) {
//NSLog(@"updating ccache strs");
cContentsFoundPtr = cContents = replaceString(cContents, [[contentString string] lowercaseUTF8String]);
contentCacheNeedsUpdate = NO;
unsigned long 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));
}
}
- (void)initContentCacheCString {
if (contentsWere7Bit) {
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;
}
- (NSString*)description {
return syncServicesMD ? [NSString stringWithFormat:@"%@ / %@", titleString, syncServicesMD] : titleString;
}
- (NSString*)combinedContentWithContextSeparator:(NSString*)sepWContext {
//combine title and body based on separator data usually generated by -syntheticTitleAndSeparatorWithContext:bodyLoc:
//if separator does not exist or chars do not match trailing and leading chars of title and body, respectively,
//then just delimit with a double-newline
NSString *content = [contentString string];
BOOL defaultJoin = NO;
if (![sepWContext length] || ![content length] || ![titleString length] ||
[titleString characterAtIndex:[titleString length] - 1] != [sepWContext characterAtIndex:0] ||
[content characterAtIndex:0] != [sepWContext characterAtIndex:[sepWContext length] - 1]) {
defaultJoin = YES;
}
NSString *separator = @"\n\n";
//if the separator lacks any actual separating characters, then concatenate with an empty string
if (!defaultJoin) {
separator = [sepWContext length] > 2 ? [sepWContext substringWithRange:NSMakeRange(1, [sepWContext length] - 2)] : @"";
}
NSMutableString *combined = [[NSMutableString alloc] initWithCapacity:[content length] + [titleString length] + [separator length]];
[combined appendString:titleString];
[combined appendString:separator];
[combined appendString:content];
return [combined autorelease];
}
- (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?
NSMutableAttributedString *contentMinusColor = [[self contentString] mutableCopy];
[contentMinusColor removeAttribute:NSForegroundColorAttributeName range:NSMakeRange(0, [contentMinusColor length])];
[largeAttributedTitleString appendAttributedString:contentMinusColor];
[contentMinusColor release];
return largeAttributedTitleString;
}
- (void)updateTablePreviewString {
//delegate required for this method
[tableTitleString release];
GlobalPrefs *prefs = [GlobalPrefs defaultPrefs];
if ([prefs tableColumnsShowPreview]) {
if ([prefs horizontalLayout]) {
//is called for visible notes at launch and resize only, generation of images for invisible notes is delayed until after launch
NSSize labelBlockSize = ColumnIsSet(NoteLabelsColumn, [prefs tableColumnsBitmap]) ? [self sizeOfLabelBlocks] : NSZeroSize;
tableTitleString = [[titleString attributedMultiLinePreviewFromBodyText:contentString upToWidth:[delegate titleColumnWidth]
intrusionWidth:labelBlockSize.width] retain];
} else {
tableTitleString = [[titleString attributedSingleLinePreviewFromBodyText:contentString upToWidth:[delegate titleColumnWidth]] retain];
}
} else {
if ([prefs horizontalLayout]) {
tableTitleString = [[titleString attributedSingleLineTitle] retain];
} else {
tableTitleString = nil;
}
}
}
- (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]];
[self updateTablePreviewString];
[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];
}
}
- (void)setForegroundTextColorOnly:(NSColor*)aColor {
//called when notationPrefs font doesn't match globalprefs font, or user changes the font
[contentString removeAttribute:NSForegroundColorAttributeName range:NSMakeRange(0, [contentString length])];
if (aColor) {
[contentString addAttribute:NSForegroundColorAttributeName value:aColor range:NSMakeRange(0, [contentString length])];
}
}
- (void)_resanitizeContent {
[contentString santizeForeignStylesForImporting];
//renormalize the title, in case it is still somehow derived from decomposed HFS+ filenames
CFMutableStringRef normalizedString = CFStringCreateMutableCopy(NULL, 0, (CFStringRef)titleString);
CFStringNormalize(normalizedString, kCFStringNormalizationFormC);
[self _setTitleString:(NSString*)normalizedString];
CFRelease(normalizedString);
if ([delegate currentNoteStorageFormat] == RTFTextFormat)
[self makeNoteDirtyUpdateTime:NO updateFile:YES];
}
//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 {
//find differences between previous labels and new ones
if (delegate) {
NSMutableSet *oldLabelSet = labelSet;
NSMutableSet *newLabelSet = [self labelSetFromCurrentString];
if (!oldLabelSet) {
oldLabelSet = labelSet = [[NSMutableSet alloc] initWithCapacity:[newLabelSet count]];
}
//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];
[oldLabels release];
[delegate note:self didAddLabelSet:newLabels];
}
}
- (void)disconnectLabels {
//when removing this note from NotationController, other LabelObjects as well as LabelsListController should know not to list it
if (delegate) {
[delegate note:self didRemoveLabelSet:labelSet];
[labelSet autorelease];
labelSet = nil;
} else {
NSLog(@"not disconnecting labels because no delegate exists");
}
}
- (BOOL)_setLabelString:(NSString*)newLabelString {
if (newLabelString && ![newLabelString isEqualToString:labelString]) {
[labelString release];
labelString = [newLabelString copy];
cLabelsFoundPtr = cLabels = replaceString(cLabels, [labelString lowercaseUTF8String]);
[self updateLabelConnections];
return YES;
}
return NO;
}
- (void)setLabelString:(NSString*)newLabelString {
if ([self _setLabelString:newLabelString]) {
if ([[GlobalPrefs defaultPrefs] horizontalLayout]) {
[self updateTablePreviewString];
}
[self makeNoteDirtyUpdateTime:YES updateFile:YES];
//[self registerModificationWithOwnedServices];
[delegate note:self attributeChanged:NoteLabelsColumnString];
}
}