Repository navigation
Expand file tree
/
Copy pathGlobalPrefs.m
More file actions
executable file
·924 lines (726 loc) · 30.9 KB
/
Copy pathGlobalPrefs.m
File metadata and controls
executable file
·924 lines (726 loc) · 30.9 KB
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
//
// GlobalPrefs.m
// Notation
//
// Created by Zachary Schneirov on 1/31/06.
/*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 "GlobalPrefs.h"
#import "NSData_transformations.h"
#import "NotationPrefs.h"
#import "BookmarksController.h"
#import "AttributedPlainText.h"
#import "FastListDataSource.h"
#import "NotesTableView.h"
#import "PTHotKey.h"
#import "PTKeyCombo.h"
#import "PTHotKeyCenter.h"
#import "NSString_NV.h"
#import "NSFileManager_NV.h"
#define SEND_CALLBACKS() sendCallbacksForGlobalPrefs(self, _cmd, sender)
static NSString *TriedToImportBlorKey = @"TriedToImportBlor";
static NSString *DirectoryAliasKey = @"DirectoryAlias";
static NSString *DirectoryBookmarkKey = @"DirectoryBookmark";
static NSString *AutoCompleteSearchesKey = @"AutoCompleteSearches";
static NSString *NoteAttributesVisibleKey = @"NoteAttributesVisible";
static NSString *TableFontSizeKey = @"TableFontPointSize";
static NSString *TableSortColumnKey = @"TableSortColumn";
static NSString *TableIsReverseSortedKey = @"TableIsReverseSorted";
static NSString *TableColumnsHaveBodyPreviewKey = @"TableColumnsHaveBodyPreview";
static NSString *NoteBodyFontKey = @"NoteBodyFont";
static NSString *NoteBodyFontKeyedArchiveKey = @"NoteBodyFontKeyedArchive";
static NSString *ConfirmNoteDeletionKey = @"ConfirmNoteDeletion";
static NSString *CheckSpellingInNoteBodyKey = @"CheckSpellingInNoteBody";
static NSString *TextReplacementInNoteBodyKey = @"TextReplacementInNoteBody";
static NSString *QuitWhenClosingMainWindowKey = @"QuitWhenClosingMainWindow";
static NSString *TabKeyIndentsKey = @"TabKeyIndents";
static NSString *PastePreservesStyleKey = @"PastePreservesStyle";
static NSString *AutoFormatsDoneTagKey = @"AutoFormatsDoneTag";
static NSString *AutoFormatsMarkdownHeadingsKey = @"AutoFormatsMarkdownHeadings";
static NSString *AutoFormatsListBulletsKey = @"AutoFormatsListBullets";
static NSString *AutoSuggestLinksKey = @"AutoSuggestLinks";
static NSString *AutoIndentsNewLinesKey = @"AutoIndentsNewLines";
static NSString *HighlightSearchTermsKey = @"HighlightSearchTerms";
static NSString *SearchTermHighlightColorKey = @"SearchTermHighlightColor";
static NSString *ForegroundTextColorKey = @"ForegroundTextColor";
static NSString *BackgroundTextColorKey = @"BackgroundTextColor";
static NSString *SearchTermHighlightColorKeyedArchiveKey = @"SearchTermHighlightColorKeyedArchive";
static NSString *ForegroundTextColorKeyedArchiveKey = @"ForegroundTextColorKeyedArchive";
static NSString *BackgroundTextColorKeyedArchiveKey = @"BackgroundTextColorKeyedArchive";
static NSString *UseSoftTabsKey = @"UseSoftTabs";
static NSString *NumberOfSpacesInTabKey = @"NumberOfSpacesInTab";
static NSString *MakeURLsClickableKey = @"MakeURLsClickable";
static NSString *AppActivationKeyCodeKey = @"AppActivationKeyCode";
static NSString *AppActivationModifiersKey = @"AppActivationModifiers";
static NSString *HorizontalLayoutKey = @"HorizontalLayout";
static NSString *BookmarksKey = @"Bookmarks";
static NSString *LastScrollOffsetKey = @"LastScrollOffset";
static NSString *LastSearchStringKey = @"LastSearchString";
static NSString *LastSelectedNoteUUIDBytesKey = @"LastSelectedNoteUUIDBytes";
static NSString *LastSelectedPreferencesPaneKey = @"LastSelectedPrefsPane";
//static NSString *PasteClipboardOnNewNoteKey = @"PasteClipboardOnNewNote";
//these 4 strings manually localized
NSString *NoteTitleColumnString = @"Title";
NSString *NoteLabelsColumnString = @"Tags";
NSString *NoteDateModifiedColumnString = @"Date Modified";
NSString *NoteDateCreatedColumnString = @"Date Added";
//virtual column
NSString *NotePreviewString = @"Note Preview";
NSString *NVPTFPboardType = @"Notational Velocity Poor Text Format";
NSString *HotKeyAppToFrontName = @"bring Notational Velocity to the foreground";
static NSData *ArchivePreference(id object) {
NSError *error = nil;
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:object requiringSecureCoding:YES error:&error];
if (!data) NSLog(@"Error archiving preference: %@", error);
return data;
}
// Legacy keys remain read-only so older app versions retain their last settings.
static id UnarchiveLegacyPreference(NSData *data, Class expectedClass) {
if (!data) return nil;
id object = nil;
@try {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
object = [NSUnarchiver unarchiveObjectWithData:data];
#pragma clang diagnostic pop
} @catch (NSException *exception) {
return nil;
}
return [object isKindOfClass:expectedClass] ? object : nil;
}
// Legacy or invalid values repair the keyed archive; wholly absent values use defaults without writing.
static id ArchivedPreference(NSUserDefaults *defaults, NSString *keyedArchiveKey, NSString *legacyKey, Class expectedClass, id defaultObject) {
id storedValue = [defaults objectForKey:keyedArchiveKey];
BOOL shouldArchive = storedValue != nil;
NSData *data = [storedValue isKindOfClass:[NSData class]] ? storedValue : nil;
id object = data ? [NSKeyedUnarchiver unarchivedObjectOfClass:expectedClass fromData:data error:nil] : nil;
if (object) return object;
storedValue = [defaults objectForKey:legacyKey];
if (storedValue) shouldArchive = YES;
data = [storedValue isKindOfClass:[NSData class]] ? storedValue : nil;
object = UnarchiveLegacyPreference(data, expectedClass);
if (!object) object = defaultObject;
if (object && shouldArchive) {
data = ArchivePreference(object);
if (data) [defaults setObject:data forKey:keyedArchiveKey];
}
return object;
}
static void SetArchivedPreference(NSUserDefaults *defaults, NSString *key, id object) {
NSData *data = ArchivePreference(object);
if (data) [defaults setObject:data forKey:key];
}
@interface GlobalPrefs ()
@property (nonatomic, retain, readwrite) NSDictionary *noteBodyAttributes;
@property (nonatomic, retain, readwrite) NSDictionary *searchTermHighlightAttributes;
@end
@implementation GlobalPrefs
@synthesize noteBodyAttributes;
static void sendCallbacksForGlobalPrefs(GlobalPrefs* self, SEL selector, id originalSender) {
if (originalSender != self) {
self->runCallbacksIMP(self, @selector(notifyCallbacksForSelector:excludingSender:),
selector, originalSender);
}
}
- (id)init {
self = [super init];
if (self) {
runCallbacksIMP = (id (*)(GlobalPrefs*, SEL, SEL, id))[self methodForSelector:@selector(notifyCallbacksForSelector:excludingSender:)];
selectorObservers = [[NSMutableDictionary alloc] init];
defaults = [NSUserDefaults standardUserDefaults];
tableColumns = nil;
[defaults registerDefaults:@{
AutoSuggestLinksKey: @YES,
AutoFormatsDoneTagKey: @YES,
AutoFormatsMarkdownHeadingsKey: @YES,
AutoIndentsNewLinesKey: @YES,
AutoFormatsListBulletsKey: @YES,
UseSoftTabsKey: @NO,
NumberOfSpacesInTabKey: @4,
PastePreservesStyleKey: @YES,
TabKeyIndentsKey: @YES,
ConfirmNoteDeletionKey: @YES,
CheckSpellingInNoteBodyKey: @YES,
TextReplacementInNoteBodyKey: @NO,
AutoCompleteSearchesKey: @YES,
QuitWhenClosingMainWindowKey: @YES,
TriedToImportBlorKey: @NO,
HorizontalLayoutKey: @NO,
MakeURLsClickableKey: @YES,
HighlightSearchTermsKey: @YES,
TableColumnsHaveBodyPreviewKey: @YES,
LastScrollOffsetKey: @0.0,
LastSelectedPreferencesPaneKey: @"General",
TableFontSizeKey: @((float)[NSFont smallSystemFontSize]),
NoteAttributesVisibleKey: @[ NoteTitleColumnString, NoteDateModifiedColumnString ],
TableSortColumnKey: NoteDateModifiedColumnString,
TableIsReverseSortedKey: @YES }];
autoCompleteSearches = [defaults boolForKey:AutoCompleteSearchesKey];
}
return self;
}
+ (GlobalPrefs *)defaultPrefs {
static GlobalPrefs *prefs = nil;
if (!prefs)
prefs = [[GlobalPrefs alloc] init];
return prefs;
}
- (void)dealloc {
[noteBodyAttributes release];
[tableColumns release];
[super dealloc];
}
- (void)registerWithTarget:(id)sender forChangesInSettings:(SEL)firstSEL, ... {
NSAssert(firstSEL != NULL, @"need at least one selector");
if ([sender respondsToSelector:(@selector(settingChangedForSelectorString:))]) {
va_list argList;
va_start(argList, firstSEL);
SEL aSEL = firstSEL;
do {
NSString *selectorKey = NSStringFromSelector(aSEL);
NSMutableArray *senders = [selectorObservers objectForKey:selectorKey];
if (!senders) {
senders = [[NSMutableArray alloc] initWithCapacity:1];
[selectorObservers setObject:senders forKey:selectorKey];
}
[senders addObject:sender];
} while (( aSEL = va_arg( argList, SEL) ) != nil);
va_end(argList);
} else {
NSLog(@"%@: target %@ does not respond to callback selector!", NSStringFromSelector(_cmd), [sender description]);
}
}
- (void)registerForSettingChange:(SEL)selector withTarget:(id)sender {
[self registerWithTarget:sender forChangesInSettings:selector, nil];
}
- (void)unregisterForNotificationsFromSelector:(SEL)selector sender:(id)sender {
NSString *selectorKey = NSStringFromSelector(selector);
NSMutableArray *senders = [selectorObservers objectForKey:selectorKey];
if (senders) {
[senders removeObjectIdenticalTo:sender];
if (![senders count])
[selectorObservers removeObjectForKey:selectorKey];
} else {
NSLog(@"Selector %@ has no observers?", NSStringFromSelector(selector));
}
}
- (void)notifyCallbacksForSelector:(SEL)selector excludingSender:(id)sender {
NSArray *observers = nil;
id observer = nil;
NSString *selectorKey = NSStringFromSelector(selector);
if ((observers = [selectorObservers objectForKey:selectorKey])) {
unsigned int i;
for (i=0; i<[observers count]; i++) {
if ((observer = [observers objectAtIndex:i]) != sender && observer)
[observer performSelector:@selector(settingChangedForSelectorString:) withObject:selectorKey];
}
}
}
- (void)setNotationPrefs:(NotationPrefs*)newNotationPrefs sender:(id)sender {
[notationPrefs autorelease];
notationPrefs = [newNotationPrefs retain];
[self resolveNoteBodyFontFromNotationPrefsFromSender:sender];
SEND_CALLBACKS();
}
- (NotationPrefs*)notationPrefs {
return notationPrefs;
}
- (BOOL)autoCompleteSearches {
return autoCompleteSearches;
}
- (void)setAutoCompleteSearches:(BOOL)value sender:(id)sender {
autoCompleteSearches = value;
[defaults setBool:value forKey:AutoCompleteSearchesKey];
SEND_CALLBACKS();
}
- (void)setTabIndenting:(BOOL)value sender:(id)sender {
[defaults setBool:value forKey:TabKeyIndentsKey];
SEND_CALLBACKS();
}
- (BOOL)tabKeyIndents {
return [defaults boolForKey:TabKeyIndentsKey];
}
- (void)setUseTextReplacement:(BOOL)value sender:(id)sender {
[defaults setBool:value forKey:TextReplacementInNoteBodyKey];
SEND_CALLBACKS();
}
- (BOOL)useTextReplacement {
return [defaults boolForKey:TextReplacementInNoteBodyKey];
}
- (void)setCheckSpellingAsYouType:(BOOL)value sender:(id)sender {
[defaults setBool:value forKey:CheckSpellingInNoteBodyKey];
SEND_CALLBACKS();
}
- (BOOL)checkSpellingAsYouType {
return [defaults boolForKey:CheckSpellingInNoteBodyKey];
}
- (void)setConfirmNoteDeletion:(BOOL)value sender:(id)sender {
[defaults setBool:value forKey:ConfirmNoteDeletionKey];
SEND_CALLBACKS();
}
- (BOOL)confirmNoteDeletion {
return [defaults boolForKey:ConfirmNoteDeletionKey];
}
- (void)setQuitWhenClosingWindow:(BOOL)value sender:(id)sender {
[defaults setBool:value forKey:QuitWhenClosingMainWindowKey];
SEND_CALLBACKS();
}
- (BOOL)quitWhenClosingWindow {
return [defaults boolForKey:QuitWhenClosingMainWindowKey];
}
- (void)setAppActivationKeyCombo:(PTKeyCombo*)aCombo sender:(id)sender {
if (aCombo) {
[appActivationKeyCombo release];
appActivationKeyCombo = [aCombo retain];
[[self appActivationHotKey] setKeyCombo:appActivationKeyCombo];
[defaults setInteger:[aCombo keyCode] forKey:AppActivationKeyCodeKey];
[defaults setInteger:[aCombo modifiers] forKey:AppActivationModifiersKey];
SEND_CALLBACKS();
}
}
- (PTHotKey*)appActivationHotKey {
if (!appActivationHotKey) {
appActivationHotKey = [[PTHotKey alloc] init];
[appActivationHotKey setName:HotKeyAppToFrontName];
[appActivationHotKey setKeyCombo:[self appActivationKeyCombo]];
}
return appActivationHotKey;
}
- (PTKeyCombo*)appActivationKeyCombo {
if (!appActivationKeyCombo) {
appActivationKeyCombo = [[PTKeyCombo alloc] initWithKeyCode:[[defaults objectForKey:AppActivationKeyCodeKey] intValue]
modifiers:[[defaults objectForKey:AppActivationModifiersKey] intValue]];
}
return appActivationKeyCombo;
}
- (BOOL)registerAppActivationKeystrokeWithTarget:(id)target selector:(SEL)selector {
PTHotKey *hotKey = [self appActivationHotKey];
[hotKey setTarget:target];
[hotKey setAction:selector];
[[PTHotKeyCenter sharedCenter] unregisterHotKeyForName:HotKeyAppToFrontName];
return [[PTHotKeyCenter sharedCenter] registerHotKey:hotKey];
}
- (void)setPastePreservesStyle:(BOOL)value sender:(id)sender {
[defaults setBool:value forKey:PastePreservesStyleKey];
SEND_CALLBACKS();
}
- (BOOL)pastePreservesStyle {
return [defaults boolForKey:PastePreservesStyleKey];
}
- (void)setAutoFormatsDoneTag:(BOOL)value sender:(id)sender {
[defaults setBool:value forKey:AutoFormatsDoneTagKey];
SEND_CALLBACKS();
}
- (BOOL)autoFormatsDoneTag {
return [defaults boolForKey:AutoFormatsDoneTagKey];
}
- (BOOL)autoFormatsMarkdownHeadings {
return [defaults boolForKey:AutoFormatsMarkdownHeadingsKey];
}
- (BOOL)autoFormatsListBullets {
return [defaults boolForKey:AutoFormatsListBulletsKey];
}
- (void)setAutoFormatsListBullets:(BOOL)value sender:(id)sender {
[defaults setBool:value forKey:AutoFormatsListBulletsKey];
SEND_CALLBACKS();
}
- (BOOL)autoIndentsNewLines {
return [defaults boolForKey:AutoIndentsNewLinesKey];
}
- (void)setAutoIndentsNewLines:(BOOL)value sender:(id)sender {
[defaults setBool:value forKey:AutoIndentsNewLinesKey];
SEND_CALLBACKS();
}
- (void)setLinksAutoSuggested:(BOOL)value sender:(id)sender {
[defaults setBool:value forKey:AutoSuggestLinksKey];
SEND_CALLBACKS();
}
- (BOOL)linksAutoSuggested {
return [defaults boolForKey:AutoSuggestLinksKey];
}
- (void)setMakeURLsClickable:(BOOL)value sender:(id)sender {
[defaults setBool:value forKey:MakeURLsClickableKey];
SEND_CALLBACKS();
}
- (BOOL)URLsAreClickable {
return [defaults boolForKey:MakeURLsClickableKey];
}
- (void)setShouldHighlightSearchTerms:(BOOL)shouldHighlight sender:(id)sender {
[defaults setBool:shouldHighlight forKey:HighlightSearchTermsKey];
SEND_CALLBACKS();
}
- (BOOL)highlightSearchTerms {
return [defaults boolForKey:HighlightSearchTermsKey];
}
- (void)setSearchTermHighlightColor:(NSColor*)color sender:(id)sender {
if (color) {
self.searchTermHighlightAttributes = nil;
SetArchivedPreference(defaults, SearchTermHighlightColorKeyedArchiveKey, color);
SEND_CALLBACKS();
}
}
- (NSColor*)searchTermHighlightColorRaw:(BOOL)isRaw {
NSColor *defaultColor = [NSColor colorWithCalibratedRed:0.945 green:0.702 blue:0.702 alpha:1.0f];
NSColor *color = ArchivedPreference(defaults, SearchTermHighlightColorKeyedArchiveKey, SearchTermHighlightColorKey, [NSColor class], defaultColor);
if (isRaw) return color;
//nslayoutmanager temporary attributes don't seem to like alpha components, so synthesize translucency using the bg color
NSColor *fauxAlphaSTHC = [[color colorUsingColorSpace:[NSColorSpace genericRGBColorSpace]] colorWithAlphaComponent:1.0];
return [fauxAlphaSTHC blendedColorWithFraction:(1.0 - [color alphaComponent]) ofColor:[self backgroundTextColor]];
}
- (NSDictionary*)searchTermHighlightAttributes {
NSColor *highlightColor = nil;
if (!searchTermHighlightAttributes && (highlightColor = [self searchTermHighlightColorRaw:NO])) {
self.searchTermHighlightAttributes = @{ NSBackgroundColorAttributeName: highlightColor };
}
return searchTermHighlightAttributes;
}
- (void)setSearchTermHighlightAttributes:(NSDictionary *)attributes {
[searchTermHighlightAttributes release];
searchTermHighlightAttributes = [attributes retain];
}
- (void)setSoftTabs:(BOOL)value sender:(id)sender {
[defaults setBool:value forKey:UseSoftTabsKey];
SEND_CALLBACKS();
}
- (BOOL)softTabs {
return [defaults boolForKey:UseSoftTabsKey];
}
- (int)numberOfSpacesInTab {
return (int)[defaults integerForKey:NumberOfSpacesInTabKey];
}
BOOL ColorsEqualWith8BitChannels(NSColor *c1, NSColor *c2) {
//sometimes floating point numbers really don't like to be compared to each other
CGFloat pRed, pGreen, pBlue, gRed, gGreen, gBlue, pAlpha, gAlpha;
[[c1 colorUsingColorSpace:[NSColorSpace genericRGBColorSpace]] getRed:&pRed green:&pGreen blue:&pBlue alpha:&pAlpha];
[[c2 colorUsingColorSpace:[NSColorSpace genericRGBColorSpace]] getRed:&gRed green:&gGreen blue:&gBlue alpha:&gAlpha];
#define SCR(__ch) ((int)roundf(((__ch) * 255.0)))
return (SCR(pRed) == SCR(gRed) && SCR(pBlue) == SCR(gBlue) && SCR(pGreen) == SCR(gGreen) && SCR(pAlpha) == SCR(gAlpha));
}
- (void)resolveNoteBodyFontFromNotationPrefsFromSender:(id)sender {
NSFont *prefsFont = [notationPrefs baseBodyFont];
if (prefsFont) {
NSFont *noteFont = [self noteBodyFont];
if (![[prefsFont fontName] isEqualToString:[noteFont fontName]] ||
[prefsFont pointSize] != [noteFont pointSize]) {
NSLog(@"archived notationPrefs base font does not match current global default font!");
[self _setNoteBodyFont:prefsFont];
SEND_CALLBACKS();
}
}
}
- (void)_setNoteBodyFont:(NSFont*)aFont {
NSFont *oldFont = noteBodyFont;
noteBodyFont = [aFont retain];
[noteBodyParagraphStyle release];
noteBodyParagraphStyle = nil;
self.noteBodyAttributes = nil; //cause method to re-update
SetArchivedPreference(defaults, NoteBodyFontKeyedArchiveKey, noteBodyFont);
//restyle any PTF data on the clipboard to the new font
NSData *ptfData = [[NSPasteboard generalPasteboard] dataForType:NVPTFPboardType];
if (ptfData) {
NSMutableAttributedString *newString = [[[NSMutableAttributedString alloc] initWithRTF:ptfData documentAttributes:nil] autorelease];
[newString restyleTextToFont:noteBodyFont usingBaseFont:oldFont];
NSData *rtf = [newString RTFFromRange:NSMakeRange(0, [newString length]) documentAttributes:@{}];
if (rtf) {
[[NSPasteboard generalPasteboard] setData:rtf forType:NVPTFPboardType];
}
}
[oldFont release];
}
- (void)setNoteBodyFont:(NSFont*)aFont sender:(id)sender {
if (aFont) {
[self _setNoteBodyFont:aFont];
SEND_CALLBACKS();
}
}
- (NSFont*)noteBodyFont {
if (!noteBodyFont) {
NSFont *defaultFont = [NSFont fontWithName:@"Helvetica" size:12.0f];
noteBodyFont = [ArchivedPreference(defaults, NoteBodyFontKeyedArchiveKey, NoteBodyFontKey, [NSFont class], defaultFont) retain];
}
return noteBodyFont;
}
- (NSDictionary*)noteBodyAttributes {
NSFont *bodyFont = [self noteBodyFont];
if (!noteBodyAttributes && bodyFont) {
NSMutableDictionary *attrs = [@{ NSFontAttributeName: bodyFont } mutableCopy];
//not storing the foreground color in each note will make the database smaller, and black is assumed when drawing text
NSColor *fgColor = [self foregroundTextColor];
if (!ColorsEqualWith8BitChannels([NSColor blackColor], fgColor)) {
[attrs setObject:fgColor forKey:NSForegroundColorAttributeName];
}
// background text color is handled directly by the NSTextView subclass and so does not need to be stored here
if ([self _bodyFontIsMonospace]) {
NSParagraphStyle *pStyle = [self noteBodyParagraphStyle];
if (pStyle)
[attrs setObject:pStyle forKey:NSParagraphStyleAttributeName];
}
/*NSTextWritingDirectionEmbedding*/
//[NSArray arrayWithObjects:[NSNumber numberWithInt:0], [NSNumber numberWithInt:0], nil], @"NSWritingDirection", //for auto-LTR-RTL text
self.noteBodyAttributes = [attrs autorelease];
}
return noteBodyAttributes;
}
- (BOOL)_bodyFontIsMonospace {
NSString *name = [noteBodyFont fontName];
return (([noteBodyFont isFixedPitch] || [name caseInsensitiveCompare:@"Osaka-Mono"] == NSOrderedSame) &&
[name caseInsensitiveCompare:@"MS-PGothic"] != NSOrderedSame);
}
- (NSParagraphStyle*)noteBodyParagraphStyle {
NSFont *bodyFont = [self noteBodyFont];
if (!noteBodyParagraphStyle && bodyFont) {
int numberOfSpaces = [self numberOfSpacesInTab];
NSMutableString *sizeString = [[NSMutableString alloc] initWithCapacity:numberOfSpaces];
while (numberOfSpaces--) {
[sizeString appendString:@" "];
}
NSDictionary *sizeAttribute = [[NSDictionary alloc] initWithObjectsAndKeys:bodyFont, NSFontAttributeName, nil];
float sizeOfTab = [sizeString sizeWithAttributes:sizeAttribute].width;
[sizeAttribute release];
[sizeString release];
noteBodyParagraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
NSTextTab *textTabToBeRemoved;
NSEnumerator *enumerator = [[noteBodyParagraphStyle tabStops] objectEnumerator];
while ((textTabToBeRemoved = [enumerator nextObject])) {
[noteBodyParagraphStyle removeTabStop:textTabToBeRemoved];
}
//[paragraphStyle setHeadIndent:sizeOfTab]; //for soft-indents, this would probably have to be applied contextually, and heaven help us for soft tabs
[noteBodyParagraphStyle setDefaultTabInterval:sizeOfTab];
}
return noteBodyParagraphStyle;
}
- (void)setForegroundTextColor:(NSColor*)aColor sender:(id)sender {
if (aColor) {
self.noteBodyAttributes = nil;
SetArchivedPreference(defaults, ForegroundTextColorKeyedArchiveKey, aColor);
SEND_CALLBACKS();
}
}
- (NSColor*)foregroundTextColor {
return ArchivedPreference(defaults, ForegroundTextColorKeyedArchiveKey, ForegroundTextColorKey, [NSColor class], [NSColor textColor]);
}
- (void)setBackgroundTextColor:(NSColor*)aColor sender:(id)sender {
if (aColor) {
//highlight color is based on blended-alpha version of background color
//(because nslayoutmanager temporary attributes don't seem to like alpha components)
//so it's necessary to invalidate the effective cache of that computed highlight color
self.searchTermHighlightAttributes = nil;
SetArchivedPreference(defaults, BackgroundTextColorKeyedArchiveKey, aColor);
SEND_CALLBACKS();
}
}
- (NSColor*)backgroundTextColor {
//don't need to cache the unarchived color, as it's not used in a random-access pattern
return ArchivedPreference(defaults, BackgroundTextColorKeyedArchiveKey, BackgroundTextColorKey, [NSColor class], [NSColor textBackgroundColor]);
}
- (BOOL)tableColumnsShowPreview {
return [defaults boolForKey:TableColumnsHaveBodyPreviewKey];
}
- (void)setTableColumnsShowPreview:(BOOL)showPreview sender:(id)sender {
[defaults setBool:showPreview forKey:TableColumnsHaveBodyPreviewKey];
SEND_CALLBACKS();
}
- (float)tableFontSize {
return [defaults floatForKey:TableFontSizeKey];
}
- (void)setTableFontSize:(float)fontSize sender:(id)sender {
[defaults setFloat:fontSize forKey:TableFontSizeKey];
SEND_CALLBACKS();
}
- (void)removeTableColumn:(NSString*)columnKey sender:(id)sender {
[tableColumns removeObject:columnKey];
tableColsBitmap = 0U;
[defaults setObject:tableColumns forKey:NoteAttributesVisibleKey];
SEND_CALLBACKS();
}
- (void)addTableColumn:(NSString*)columnKey sender:(id)sender {
if (![tableColumns containsObject:columnKey]) {
[tableColumns addObject:columnKey];
tableColsBitmap = 0U;
[defaults setObject:tableColumns forKey:NoteAttributesVisibleKey];
SEND_CALLBACKS();
}
}
- (NSArray*)visibleTableColumns {
if (!tableColumns) {
tableColumns = [[NSMutableArray arrayWithArray:[defaults arrayForKey:NoteAttributesVisibleKey]] retain];
tableColsBitmap = 0U;
}
if (![tableColumns count])
[self addTableColumn:NoteTitleColumnString sender:self];
return tableColumns;
}
- (unsigned int)tableColumnsBitmap {
if (tableColsBitmap == 0U) {
if ([tableColumns containsObject:NoteTitleColumnString])
tableColsBitmap = (tableColsBitmap | (1 << NoteTitleColumn));
if ([tableColumns containsObject:NoteLabelsColumnString])
tableColsBitmap = (tableColsBitmap | (1 << NoteLabelsColumn));
if ([tableColumns containsObject:NoteDateModifiedColumnString])
tableColsBitmap = (tableColsBitmap | (1 << NoteDateModifiedColumn));
if ([tableColumns containsObject:NoteDateCreatedColumnString])
tableColsBitmap = (tableColsBitmap | (1 << NoteDateCreatedColumn));
}
return tableColsBitmap;
}
- (void)setSortedTableColumnKey:(NSString*)sortedKey reversed:(BOOL)reversed sender:(id)sender {
[defaults setBool:reversed forKey:TableIsReverseSortedKey];
[defaults setObject:sortedKey forKey:TableSortColumnKey];
SEND_CALLBACKS();
}
- (NSString*)sortedTableColumnKey {
return [defaults objectForKey:TableSortColumnKey];
}
- (BOOL)tableIsReverseSorted {
return [defaults boolForKey:TableIsReverseSortedKey];
}
- (void)setHorizontalLayout:(BOOL)value sender:(id)sender {
if ([self horizontalLayout] != value) {
[defaults setBool:value forKey:HorizontalLayoutKey];
SEND_CALLBACKS();
}
}
- (BOOL)horizontalLayout {
return [defaults boolForKey:HorizontalLayoutKey];
}
- (NSString*)lastSelectedPreferencesPane {
return [defaults stringForKey:LastSelectedPreferencesPaneKey];
}
- (void)setLastSelectedPreferencesPane:(NSString*)pane sender:(id)sender {
[defaults setObject:pane forKey:LastSelectedPreferencesPaneKey];
SEND_CALLBACKS();
}
- (void)setLastSearchString:(NSString*)string selectedNote:(id<SynchronizedNote>)aNote scrollOffsetForTableView:(NotesTableView*)tv sender:(id)sender {
NSMutableString *stringMinusBreak = [[string mutableCopy] autorelease];
[stringMinusBreak replaceOccurrencesOfString:@"\n" withString:@" " options:NSLiteralSearch range:NSMakeRange(0, [stringMinusBreak length])];
[defaults setObject:stringMinusBreak forKey:LastSearchStringKey];
CFUUIDBytes *bytes = [aNote uniqueNoteIDBytes];
NSString *uuidString = nil;
if (bytes) uuidString = [NSString uuidStringWithBytes:*bytes];
[defaults setObject:uuidString forKey:LastSelectedNoteUUIDBytesKey];
double offset = [tv distanceFromRow:[(FastListDataSource*)[tv dataSource] indexOfObjectIdenticalTo:aNote] forVisibleArea:[tv visibleRect]];
[defaults setDouble:offset forKey:LastScrollOffsetKey];
SEND_CALLBACKS();
}
- (NSString*)lastSearchString {
return [defaults objectForKey:LastSearchStringKey];
}
- (CFUUIDBytes)UUIDBytesOfLastSelectedNote {
CFUUIDBytes bytes = {0};
NSString *uuidString = [defaults objectForKey:LastSelectedNoteUUIDBytesKey];
if (uuidString) bytes = [uuidString uuidBytes];
return bytes;
}
- (double)scrollOffsetOfLastSelectedNote {
return [defaults doubleForKey:LastScrollOffsetKey];
}
- (void)saveCurrentBookmarksFromSender:(id)sender {
//run this during quit and when saved searches change?
NSArray *bookmarks = [bookmarksController dictionaryReps];
if (bookmarks) {
[defaults setObject:bookmarks forKey:BookmarksKey];
[defaults setBool:[bookmarksController isVisible] forKey:@"BookmarksVisible"];
}
SEND_CALLBACKS();
}
- (BookmarksController*)bookmarksController {
if (!bookmarksController) {
bookmarksController = [[BookmarksController alloc] initWithBookmarks:[defaults arrayForKey:BookmarksKey]];
}
return bookmarksController;
}
- (void)setAliasDataForDefaultDirectory:(NSData*)alias sender:(id)sender {
[defaults setObject:alias forKey:DirectoryAliasKey];
SEND_CALLBACKS();
}
- (NSData*)aliasDataForDefaultDirectory {
return [defaults dataForKey:DirectoryAliasKey];
}
- (NSData*)bookmarkDataForDefaultDirectory {
return [defaults dataForKey:DirectoryBookmarkKey];
}
- (BOOL)setDefaultDirectoryURL:(NSURL*)url sender:(id)sender error:(NSError**)error {
NSFileManager *manager = [NSFileManager defaultManager];
NSURL *referenceURL = [manager fileReferenceURLForURL:url error:error];
if (!referenceURL) return NO;
NSData *bookmarkData = [manager bookmarkDataForFileReferenceURL:referenceURL error:error];
NSData *aliasData = [NSData legacyAliasDataForFileReferenceURL:referenceURL];
if (!bookmarkData || !aliasData) {
if (error && !*error)
*error = [NSError errorWithDomain:@"NVFileReferenceErrorDomain" code:EIO
userInfo:@{ NSLocalizedDescriptionKey: @"Unable to create compatible directory identity data." }];
return NO;
}
[defaults setObject:bookmarkData forKey:DirectoryBookmarkKey];
[defaults setObject:aliasData forKey:DirectoryAliasKey];
SEND_CALLBACKS();
return YES;
}
- (NSURL*)defaultDirectoryURLResolvingBookmark:(BOOL*)stale error:(NSError**)error {
NSFileManager *manager = [NSFileManager defaultManager];
NSData *bookmarkData = [self bookmarkDataForDefaultDirectory];
NSData *aliasData = [self aliasDataForDefaultDirectory];
BOOL bookmarkStale = NO;
NSURL *bookmarkURL = bookmarkData ? [manager fileReferenceURLFromBookmarkData:bookmarkData
stale:&bookmarkStale error:NULL] : nil;
NSData *convertedAliasBookmark = [aliasData bookmarkDataFromLegacyAliasRecord];
NSURL *aliasURL = convertedAliasBookmark ? [manager fileReferenceURLFromBookmarkData:convertedAliasBookmark
stale:NULL error:NULL] : nil;
NSURL *chosenURL = nil;
if (bookmarkURL && aliasURL)
chosenURL = NVURLsReferToSameItem(bookmarkURL, aliasURL) ? bookmarkURL : aliasURL;
else
chosenURL = bookmarkURL ? bookmarkURL : aliasURL;
if (!chosenURL) {
if (error) *error = [NSError errorWithDomain:@"NVFileReferenceErrorDomain" code:ENOENT
userInfo:@{ NSLocalizedDescriptionKey: @"The saved notes directory could not be located." }];
return nil;
}
BOOL needsRepair = bookmarkStale || !bookmarkURL || !aliasURL ||
(bookmarkURL && aliasURL && !NVURLsReferToSameItem(bookmarkURL, aliasURL));
if (needsRepair) {
NSData *freshBookmark = [manager bookmarkDataForFileReferenceURL:chosenURL error:error];
NSData *freshAlias = [NSData legacyAliasDataForFileReferenceURL:chosenURL];
if (!freshBookmark || !freshAlias) return nil;
[defaults setObject:freshBookmark forKey:DirectoryBookmarkKey];
[defaults setObject:freshAlias forKey:DirectoryAliasKey];
}
if (stale) *stale = needsRepair;
return chosenURL;
}
- (NSString*)displayNameForDefaultDirectoryURL:(NSURL*)url {
if (!url) url = [self defaultDirectoryURLResolvingBookmark:NULL error:NULL];
NSString *displayName = nil;
[url getResourceValue:&displayName forKey:NSURLLocalizedNameKey error:NULL];
return displayName;
}
- (NSString*)humanViewablePathForDefaultDirectory {
NSURL *url = [self defaultDirectoryURLResolvingBookmark:NULL error:NULL];
if (url) {
NSURL *displayURL = [NSURL URLByResolvingBookmarkData:[self bookmarkDataForDefaultDirectory]
options:NSURLBookmarkResolutionWithoutUI relativeToURL:nil
bookmarkDataIsStale:NULL error:NULL];
return [[displayURL path] stringByAbbreviatingWithTildeInPath];
}
return nil;
}
- (void)setBlorImportAttempted:(BOOL)value {
[defaults setBool:value forKey:TriedToImportBlorKey];
}
- (BOOL)triedToImportBlor {
return [defaults boolForKey:TriedToImportBlorKey];
}
- (void)synchronize {
[defaults synchronize];
}
@end