-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkingEditor.m
executable file
·1535 lines (1202 loc) · 62.1 KB
/
LinkingEditor.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*Copyright (c) 2010, Zachary Schneirov. All rights reserved.
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 "LinkingEditor.h"
#import "GlobalPrefs.h"
#import "AppController.h"
#import "AppController_Importing.h"
#import "NotesTableView.h"
#import "NSTextFinder.h"
#import "LinkingEditor_Indentation.h"
#import "NSCollection_utils.h"
#import "AttributedPlainText.h"
#import "NSString_NV.h"
#import "NVPasswordGenerator.h"
#include <CoreServices/CoreServices.h>
#if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
#include <Carbon/Carbon.h>
#endif
#define PASSWORD_SUGGESTIONS 0
#ifdef notyet
static long (*GetGetScriptManagerVariablePointer())(short);
#endif
@interface NSCursor (WhiteIBeamCursor)
+ (NSCursor*)whiteIBeamCursor;
@end
@implementation NSCursor (WhiteIBeamCursor)
+ (NSCursor*)whiteIBeamCursor {
static NSCursor *invertedIBeamCursor = nil;
if (!invertedIBeamCursor) {
invertedIBeamCursor = [[NSCursor alloc] initWithImage:[NSImage imageNamed:@"IBeamInverted"] hotSpot:NSMakePoint(4,5)];
}
return invertedIBeamCursor;
}
@end
@implementation LinkingEditor
CGFloat _perceptualDarkness(NSColor*a);
- (void)awakeFromNib {
prefsController = [GlobalPrefs defaultPrefs];
[self setContinuousSpellCheckingEnabled:[prefsController checkSpellingAsYouType]];
if (IsSnowLeopardOrLater) {
[self setAutomaticTextReplacementEnabled:[prefsController useTextReplacement]];
}
[prefsController registerWithTarget:self forChangesInSettings:
@selector(setCheckSpellingAsYouType:sender:),
@selector(setUseTextReplacement:sender:),
@selector(setNoteBodyFont:sender:),
@selector(setMakeURLsClickable:sender:),
@selector(setSearchTermHighlightColor:sender:),
@selector(setShouldHighlightSearchTerms:sender:),
@selector(setBackgroundTextColor:sender:),
@selector(setForegroundTextColor:sender:), nil];
[self setTextContainerInset:NSMakeSize(3, 8)];
[self setSmartInsertDeleteEnabled:NO];
[self setUsesRuler:NO];
[self setUsesFontPanel:NO];
[self setDrawsBackground:YES];
[self setBackgroundColor:[prefsController backgroundTextColor]];
[self updateTextColors];
[[self window] setAcceptsMouseMovedEvents:YES];
if (IsLeopardOrLater) {
defaultIBeamCursorIMP = method_getImplementation(class_getClassMethod([NSCursor class], @selector(IBeamCursor)));
whiteIBeamCursorIMP = method_getImplementation(class_getClassMethod([NSCursor class], @selector(whiteIBeamCursor)));
}
didRenderFully = NO;
[[self layoutManager] setDelegate:self];
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(windowBecameOrResignedMain:) name:NSWindowDidBecomeMainNotification object:[self window]];
[center addObserver:self selector:@selector(windowBecameOrResignedMain:) name:NSWindowDidResignMainNotification object:[self window]];
[center addObserver:self selector:@selector(updateTextColors) name:NSSystemColorsDidChangeNotification object:nil]; // recreate gradient if needed
outletObjectAwoke(self);
}
- (void)settingChangedForSelectorString:(NSString*)selectorString {
if ([selectorString isEqualToString:SEL_STR(setCheckSpellingAsYouType:sender:)]) {
[self setContinuousSpellCheckingEnabled:[prefsController checkSpellingAsYouType]];
} else if ([selectorString isEqualToString:SEL_STR(setUseTextReplacement:sender:)]) {
if (IsSnowLeopardOrLater) {
[self setAutomaticTextReplacementEnabled:[prefsController useTextReplacement]];
}
} else if ([selectorString isEqualToString:SEL_STR(setNoteBodyFont:sender:)]) {
[self setTypingAttributes:[prefsController noteBodyAttributes]];
//[textView setFont:[prefsController noteBodyFont]];
} else if ([selectorString isEqualToString:SEL_STR(setMakeURLsClickable:sender:)]) {
[self setLinkTextAttributes:[self preferredLinkAttributes]];
} else if ([selectorString isEqualToString:SEL_STR(setBackgroundTextColor:sender:)]) {
//link-color is derived both from foreground and background colors
[self setBackgroundColor:[prefsController backgroundTextColor]];
[self updateTextColors];
} else if ([selectorString isEqualToString:SEL_STR(setForegroundTextColor:sender:)]) {
[self updateTextColors];
[self setTypingAttributes:[prefsController noteBodyAttributes]];
} else if ([selectorString isEqualToString:SEL_STR(setSearchTermHighlightColor:sender:)] ||
[selectorString isEqualToString:SEL_STR(setShouldHighlightSearchTerms:sender:)]) {
if (![prefsController highlightSearchTerms]) {
[self removeHighlightedTerms];
} else {
NSString *typedString = [[NSApp delegate] typedString];
if (typedString)
[self highlightTermsTemporarilyReturningFirstRange:typedString avoidHighlight:NO];
}
}
}
- (BOOL)becomeFirstResponder {
[notesTableView setShouldUseSecondaryHighlightColor:YES];
if ([[[self window] currentEvent] type] == NSKeyDown && [[[self window] currentEvent] firstCharacter] == '\t') {
//"indicate" the current cursor/selection when moving focus to this field, but only if the user did not click here
NSRange range = [self selectedRange];
if (range.length) {
range = NSMakeRange(MIN([[self string] length] - 1, range.location), range.length);
[self performSelector:@selector(indicateRange:) withObject:[NSValue valueWithRange:range] afterDelay:0];
}
}
[self setTypingAttributes:[prefsController noteBodyAttributes]];
[self performSelector:@selector(_fixCursorForBackgroundUpdatingMouseInside:) withObject:[NSNumber numberWithBool:YES] afterDelay:0.0];
return [super becomeFirstResponder];
}
- (void)indicateRange:(NSValue*)rangeValue {
if (IsLeopardOrLater) {
[self showFindIndicatorForRange:[rangeValue rangeValue]];
}
}
- (BOOL)resignFirstResponder {
[notesTableView setShouldUseSecondaryHighlightColor:NO];
[self performSelector:@selector(_fixCursorForBackgroundUpdatingMouseInside:) withObject:[NSNumber numberWithBool:YES] afterDelay:0.0];
return [super resignFirstResponder];
}
- (void)changeColor:(id)sender {
//NSLog(@"You do not change the color.");
return;
}
- (void)setBackgroundColor:(NSColor*)aColor {
backgroundIsDark = (_perceptualDarkness([aColor colorUsingColorSpaceName:NSCalibratedRGBColorSpace]) > 0.5);
[super setBackgroundColor:aColor];
}
- (void)updateTextColors {
NSColor *fgColor = [prefsController foregroundTextColor];
NSColor *bgColor = [prefsController backgroundTextColor];
[self setInsertionPointColor:[self _insertionPointColorForForegroundColor:fgColor backgroundColor:bgColor]];
[self setLinkTextAttributes:[self preferredLinkAttributes]];
[self setSelectedTextAttributes:[NSDictionary dictionaryWithObject:[self _selectionColorForForegroundColor:fgColor backgroundColor:bgColor]
forKey:NSBackgroundColorAttributeName]];
}
#define _CM(__ch) ((__ch) * 255.0)
CGFloat _perceptualDarkness(NSColor*a) {
//0 to 1; the higher the darker
CGFloat aRed, aGreen, aBlue;
[a getRed:&aRed green:&aGreen blue:&aBlue alpha:NULL];
return 1 - (0.299 * _CM(aRed) + 0.587 * _CM(aGreen) + 0.114 * _CM(aBlue))/255;
}
CGFloat _perceptualColorDifference(NSColor*a, NSColor*b) {
//acceptable: 500
CGFloat aRed, aGreen, aBlue, bRed, bGreen, bBlue;
[a getRed:&aRed green:&aGreen blue:&aBlue alpha:NULL];
[b getRed:&bRed green:&bGreen blue:&bBlue alpha:NULL];
return (MAX(_CM(aRed), _CM(bRed)) - MIN(_CM(aRed), _CM(bRed))) + (MAX(_CM(aGreen), _CM(bGreen)) - MIN(_CM(aGreen), _CM(bGreen))) +
(MAX(_CM(aBlue), _CM(bBlue)) - MIN(_CM(aBlue), _CM(bBlue)));
}
- (NSColor*)_linkColorForForegroundColor:(NSColor*)fgColor backgroundColor:(NSColor*)bgColor {
//if fgColor is black, choose blue; otherwise, rotate hue (keeping the same sat.) until color is different enough
fgColor = [fgColor colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
bgColor = [bgColor colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
CGFloat hue, brightness, saturation, alpha, diffInc = 0.5;
NSUInteger rotationsLeft = 25;
[fgColor getHue:&hue saturation:&saturation brightness:&brightness alpha:&alpha];
//if foreground color is too dark for hue changes to matter, then just use blue
if (brightness <= 0.24)
return [NSColor blueColor];
brightness = _perceptualDarkness(bgColor) > 0.5 ? MAX(0.75, brightness) : MIN(0.35, brightness);
saturation = MAX(0.5, saturation);
//adjust hue until the perceptual differences between the proposed link
//and current foreground and background colors are great enough
NSColor *proposedLinkColor = nil;
do {
hue -= diffInc;
if (hue < 0.0)
hue += 1.0;
proposedLinkColor = [NSColor colorWithCalibratedHue:hue saturation:saturation brightness:brightness alpha:alpha];
diffInc = rotationsLeft > 15 ? 0.125 : 0.0625;
} while ((_perceptualColorDifference(proposedLinkColor, bgColor) < 360.0 ||
_perceptualColorDifference(proposedLinkColor, fgColor) < 170.0) && --rotationsLeft > 0);
return proposedLinkColor;
}
- (NSColor*)_selectionColorForForegroundColor:(NSColor*)fgColor backgroundColor:(NSColor*)bgColor {
fgColor = [fgColor colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
bgColor = [bgColor colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
NSColor *proposedBlend = [fgColor blendedColorWithFraction:0.5 ofColor:bgColor];
NSColor *defaultColor = [[NSColor selectedTextBackgroundColor] colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
float fgDiff = _perceptualColorDifference(proposedBlend, fgColor);
float fgSelDiff = _perceptualColorDifference(defaultColor, fgColor);
//selection color should be between foreground and background in terms of brightness
//but the selection-color-difference from the foreground text needs to be great enough as well,
//and the proposed-color-difference from the foreground can't be too poor
//this heuristic chooses all the system-highlight colors in default fg/bg combinations and fg/bg blends in all others
// NSLog(@"fg diff of proposed: %g fg diff of sel: %g", fgDiff, fgSelDiff);
if ((_perceptualDarkness(fgColor) > _perceptualDarkness(defaultColor) &&
_perceptualDarkness(defaultColor) > _perceptualDarkness(bgColor) && fgSelDiff > 300.0) || fgDiff < 170.0)
return defaultColor;
//amplify the background balance after testing
return [fgColor blendedColorWithFraction:0.69 ofColor:bgColor];
}
- (NSColor*)_insertionPointColorForForegroundColor:(NSColor*)fgColor backgroundColor:(NSColor*)bgColor {
fgColor = [fgColor colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
bgColor = [bgColor colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
CGFloat hue, brightness, saturation;
[fgColor getHue:&hue saturation:&saturation brightness:&brightness alpha:NULL];
//make the insertion point lighter than the foreground color if the background is dark and vise versa
NSColor *brighter = [fgColor blendedColorWithFraction:0.4 ofColor:[NSColor whiteColor]];
NSColor *darker = [fgColor blendedColorWithFraction:0.4 ofColor:[NSColor blackColor]];
return _perceptualColorDifference(brighter, bgColor) > _perceptualColorDifference(darker, bgColor) ? brighter : darker;
}
- (NSDictionary*)preferredLinkAttributes {
if (![prefsController URLsAreClickable])
return [NSDictionary dictionary];
return [NSDictionary dictionaryWithObjectsAndKeys:
[NSCursor pointingHandCursor], NSCursorAttributeName,
[NSNumber numberWithInt:NSUnderlineStyleSingle], NSUnderlineStyleAttributeName,
[self _linkColorForForegroundColor:[prefsController foregroundTextColor] backgroundColor:[prefsController backgroundTextColor]],
NSForegroundColorAttributeName, nil];
}
/*
- (BOOL)acceptsFirstResponder {
return ([[controlField stringValue] length] > 0);
}*/
- (void)toggleAutomaticTextReplacement:(id)sender {
[super toggleAutomaticTextReplacement:sender];
[prefsController setUseTextReplacement:[self isAutomaticTextReplacementEnabled] sender:self];
}
- (void)toggleContinuousSpellChecking:(id)sender {
[super toggleContinuousSpellChecking:sender];
[prefsController setCheckSpellingAsYouType:[self isContinuousSpellCheckingEnabled] sender:self];
}
- (BOOL)isContinuousSpellCheckingEnabled {
//optimization so that we don't spell-check while scrolling through notes that don't have focus
NSView *responder = (NSView*)[[self window] firstResponder];
return (responder == self && [super isContinuousSpellCheckingEnabled]);
}
- (BOOL)didRenderFully {
return didRenderFully;
}
- (void)layoutManager:(NSLayoutManager *)aLayoutManager didCompleteLayoutForTextContainer:(NSTextContainer *)aTextContainer atEnd:(BOOL)flag {
didRenderFully = YES;
}
- (void)layoutManagerDidInvalidateLayout:(NSLayoutManager *)aLayoutManager {
didRenderFully = NO;
}
- (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pboard type:(NSString *)type {
//NSLog(@"readSelectionFromPasteboard: %@ (total %@)", type, [[pboard types] description]);
if ([type isEqualToString:NSFilenamesPboardType]) {
//paste as a file:// URL, so that it can be linked
NSString *allURLsString = [[NSApp delegate] stringWithNoteURLsOnPasteboard:pboard];
if ([allURLsString length]) {
NSRange selectedRange = [self rangeForUserTextChange];
if ([self shouldChangeTextInRange:selectedRange replacementString:allURLsString]) {
[self replaceCharactersInRange:selectedRange withString:allURLsString];
[self didChangeText];
return YES;
}
}
}
if ([type isEqualToString:NSRTFPboardType] || [type isEqualToString:NVPTFPboardType] || [type isEqualToString:NSHTMLPboardType]) {
//strip formatting if RTF and stick it into a new pboard
NSMutableAttributedString *newString = [[[NSMutableAttributedString alloc] performSelector:[type isEqualToString:NSHTMLPboardType] ?
@selector(initWithHTML:documentAttributes:) : @selector(initWithRTF:documentAttributes:)
withObject:[pboard dataForType:type] withObject:nil] autorelease];
if ([newString length]) {
if (![type isEqualToString:NVPTFPboardType]) {
//remove the link attribute, because it will be re-added after we paste, and restyleText would preserve it otherwise
//and we only want real URLs to be linked
[newString removeAttribute:NSLinkAttributeName range:NSMakeRange(0, [newString length])];
[newString indentTextLists];
[newString restyleTextToFont:[prefsController noteBodyFont] usingBaseFont:nil];
}
NSRange selectedRange = [self rangeForUserTextChange];
if ([self shouldChangeTextInRange:selectedRange replacementString:[newString string]]) {
[self replaceCharactersInRange:selectedRange withRTF:[newString RTFFromRange:
NSMakeRange(0, [newString length]) documentAttributes:nil]];
//paragraph styles will ALWAYS be added _after_ replaceCharactersInRange, it seems
//[[self textStorage] removeAttribute:NSParagraphStyleAttributeName range:NSMakeRange(0, [[self string] length])];
[self didChangeText];
return YES;
}
}
}
return [super readSelectionFromPasteboard:pboard type:type];
}
- (NSArray *)acceptableDragTypes {
return [self readablePasteboardTypes];
}
- (NSArray *)readablePasteboardTypes {
NSMutableArray *types = [NSMutableArray arrayWithObjects:NSFilenamesPboardType, NVPTFPboardType, NSStringPboardType, nil];
if ([prefsController pastePreservesStyle]) {
[types insertObject:NSRTFPboardType atIndex:2];
[types insertObject:NSHTMLPboardType atIndex:3];
}
return types;
}
- (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pboard type:(NSString *)type {
if ([type isEqualToString:NVPTFPboardType] || [type isEqualToString:NSRTFPboardType]) {
//always preserve RTF to allow pasting into ourselves; prejudice against external sources
NSMutableAttributedString *newString = [[[self textStorage] attributedSubstringFromRange:[self selectedRange]] mutableCopy];
if (![type isEqualToString:NVPTFPboardType])
[newString removeAttribute:NSForegroundColorAttributeName range:NSMakeRange(0, [newString length])];
NSData *rtfData = [newString RTFFromRange:NSMakeRange(0, [newString length]) documentAttributes:nil];;
if (rtfData) [pboard setData:rtfData forType:type];
[newString release];
return YES;
}
return [super writeSelectionToPasteboard:pboard type:type];
}
#define COPY_PASTE_DEBUG 0
- (NSArray *)writablePasteboardTypes {
NSMutableArray *types = [NSMutableArray arrayWithObjects:NVPTFPboardType, NSStringPboardType, nil];
NSRange selectedRange = [self selectedRange];
if (selectedRange.length) {
NSRange firstAttributeRange;
[[self textStorage] attributesAtIndex:selectedRange.location effectiveRange:&firstAttributeRange];
if (firstAttributeRange.length < selectedRange.length) {
//there are multiple styles across the selected text
NSAttributedString *newString = [[self textStorage] attributedSubstringFromRange:selectedRange];
NSRange effectiveRange = NSMakeRange(0,0);
unsigned int stringLength = [newString length];
//iterate over all styles; if any are acceptable, copy as RTF
while (NSMaxRange(effectiveRange) < stringLength) {
// Get the attributes for the current range
NSDictionary *attributes = [newString attributesAtIndex:NSMaxRange(effectiveRange) effectiveRange:&effectiveRange];
if ([attributes attributesHaveFontTrait:NSBoldFontMask orAttribute:NSStrokeWidthAttributeName])
goto copyRTFType;
if ([attributes attributesHaveFontTrait:NSItalicFontMask orAttribute:NSObliquenessAttributeName])
goto copyRTFType;
if ([attributes attributesHaveFontTrait:0 orAttribute:NSStrikethroughStyleAttributeName])
goto copyRTFType;
}
#if COPY_PASTE_DEBUG
NSLog(@"false alarm: no real styles");
#endif
} else {
#if COPY_PASTE_DEBUG
NSLog(@"homogeneous style");
#endif
}
if (0) {
copyRTFType:
//we have more than a single styling segment within the selection--grudgingly allow regular RTF copying
#if COPY_PASTE_DEBUG
NSLog(@"copying RTF due to multiple attributes");
[[self layoutManager] addTemporaryAttributes:[prefsController searchTermHighlightAttributes] forCharacterRange:effectiveRange];
#endif
[types insertObject:NSRTFPboardType atIndex:1];
}
}
return types;
}
//font panel is disabled for the note-body, so styles must be applied manually:
- (void)strikethroughNV:(id)sender {
[self applyStyleOfTrait:0 alternateAttributeName:NSStrikethroughStyleAttributeName
alternateAttributeValue:[NSNumber numberWithInt:NSUnderlineStyleSingle]];
[[self undoManager] setActionName:NSLocalizedString(@"Strikethrough",nil)];
}
#define STROKE_WIDTH_FOR_BOLD (-3.50)
#define OBLIQUENESS_FOR_ITALIC (0.20)
- (void)bold:(id)sender {
[self applyStyleOfTrait:NSBoldFontMask alternateAttributeName:NSStrokeWidthAttributeName
alternateAttributeValue:[NSNumber numberWithFloat:STROKE_WIDTH_FOR_BOLD]];
[[self undoManager] setActionName:NSLocalizedString(@"Bold",nil)];
}
- (void)italic:(id)sender {
[self applyStyleOfTrait:NSItalicFontMask alternateAttributeName:NSObliquenessAttributeName
alternateAttributeValue:[NSNumber numberWithFloat:OBLIQUENESS_FOR_ITALIC]];
[[self undoManager] setActionName:NSLocalizedString(@"Italic",nil)];
}
- (void)applyStyleOfTrait:(NSFontTraitMask)trait alternateAttributeName:(NSString*)attrName alternateAttributeValue:(id)value {
NSFont *font = nil;
NSMutableDictionary *attributes = nil;
BOOL hasTrait = NO;
if ([self selectedRange].length) {
NSRange limitRange, effectiveRange;
NSTextStorage *text = [self textStorage];
limitRange = [self selectedRange];
if ([self shouldChangeTextInRange:limitRange replacementString:nil]) {
NSDictionary *firstAttrs = [text attributesAtIndex:limitRange.location longestEffectiveRange:NULL inRange:limitRange];
hasTrait = [firstAttrs attributesHaveFontTrait:trait orAttribute:attrName];
[text beginEditing];
while (limitRange.length > 0) {
attributes = [[text attributesAtIndex:limitRange.location longestEffectiveRange:&effectiveRange
inRange:limitRange] mutableCopyWithZone:nil];
if (!attributes) attributes = [[prefsController noteBodyAttributes] mutableCopyWithZone:nil];
font = [attributes objectForKey:NSFontAttributeName];
[attributes applyStyleInverted:hasTrait trait:trait forFont:font alternateAttributeName:attrName alternateAttributeValue:value];
[text setAttributes:attributes range:effectiveRange];
[attributes release];
limitRange = NSMakeRange( NSMaxRange( effectiveRange ), NSMaxRange( limitRange ) - NSMaxRange( effectiveRange ) );
}
[text endEditing];
[self didChangeText];
}
} else {
attributes = [[self typingAttributes] mutableCopyWithZone:nil];
if (!attributes) attributes = [[prefsController noteBodyAttributes] mutableCopyWithZone:nil];
font = [attributes objectForKey:NSFontAttributeName];
hasTrait = [attributes attributesHaveFontTrait:trait orAttribute:attrName];
[attributes applyStyleInverted:hasTrait trait:trait forFont:font alternateAttributeName:attrName alternateAttributeValue:value];
[self setTypingAttributes:attributes];
[attributes release];
}
}
- (void)removeHighlightedTerms {
[[self layoutManager] removeTemporaryAttribute:NSBackgroundColorAttributeName forCharacterRange:NSMakeRange(0, [[self string] length])];
}
//use with rangesOfWordsInString:(NSString*)findString earliestRange:(NSRange*)aRange inRange:
- (void)highlightRangesTemporarily:(CFArrayRef)ranges {
CFIndex rangeIndex;
int bodyLength = [[self string] length];
NSDictionary *highlightDict = [prefsController searchTermHighlightAttributes];
for (rangeIndex = 0; rangeIndex < CFArrayGetCount(ranges); rangeIndex++) {
CFRange *range = (CFRange *)CFArrayGetValueAtIndex(ranges, rangeIndex);
if (range && range->length > 0 && range->location + range->length <= bodyLength) {
[[self layoutManager] addTemporaryAttributes:highlightDict forCharacterRange:*(NSRange*)range];
} else {
NSLog(@"highlightRangesTemporarily: Invalid range (%@)", range ? NSStringFromRange(*(NSRange*)range) : @"null");
}
}
}
- (NSRange)highlightTermsTemporarilyReturningFirstRange:(NSString*)typedString avoidHighlight:(BOOL)noHighlight {
//if lengths of respective UTF8-string equivalents for contentString are the same, we should revert to cstring-based algorithm
CFStringRef quoteStr = CFSTR("\"");
NSRange firstRange = NSMakeRange(NSNotFound,0);
CFRange quoteRange = CFStringFind((CFStringRef)typedString, quoteStr, 0);
CFArrayRef terms = CFStringCreateArrayBySeparatingStrings(NULL, (CFStringRef)typedString,
quoteRange.location == kCFNotFound ? CFSTR(" ") : quoteStr);
if (terms) {
CFIndex termIndex, rangeIndex;
CFStringRef bodyString = (CFStringRef)[self string];
NSDictionary *highlightDict = [prefsController searchTermHighlightAttributes];
for (termIndex = 0; termIndex < CFArrayGetCount(terms); termIndex++) {
CFStringRef term = CFArrayGetValueAtIndex(terms, termIndex);
if (CFStringGetLength(term) > 0) {
CFArrayRef ranges = CFStringCreateArrayWithFindResults(NULL, bodyString, term, CFRangeMake(0, CFStringGetLength(bodyString)),
kCFCompareCaseInsensitive);
if (!ranges)
continue;
for (rangeIndex = 0; rangeIndex < CFArrayGetCount(ranges); rangeIndex++) {
CFRange *range = (CFRange *)CFArrayGetValueAtIndex(ranges, rangeIndex);
if (range && range->length > 0 && range->location + range->length <= CFStringGetLength(bodyString)) {
if (firstRange.location > (NSUInteger)range->location) {
firstRange = *(NSRange*)range;
if (noHighlight) {
CFRelease(ranges);
goto returnEarly;
}
}
[[self layoutManager] addTemporaryAttributes:highlightDict forCharacterRange:*(NSRange*)range];
} else {
NSLog(@"highlightTermsTemporarily: Invalid range (%@)", range ? NSStringFromRange(*(NSRange*)range) : @"?");
}
}
CFRelease(ranges);
}
}
returnEarly:
CFRelease(terms);
}
return (firstRange);
}
- (NSRange)selectionRangeForProposedRange:(NSRange)proposedSelRange granularity:(NSSelectionGranularity)granularity {
if (granularity != NSSelectByWord || [[self string] length] == proposedSelRange.location) {
// If it's not a double-click return unchanged
return [super selectionRangeForProposedRange:proposedSelRange granularity:granularity];
}
unsigned int location = [super selectionRangeForProposedRange:proposedSelRange granularity:NSSelectByCharacter].location;
int originalLocation = location;
NSString *completeString = [self string];
unichar characterToCheck = [completeString characterAtIndex:location];
unsigned short skipMatchingBrace = 0;
unsigned int lengthOfString = [completeString length];
if (lengthOfString == proposedSelRange.location) { // To avoid crash if a double-click occurs after any text
return [super selectionRangeForProposedRange:proposedSelRange granularity:granularity];
}
BOOL triedToMatchBrace = NO;
char *rightGroupings = ")}]>";
char *leftGroupings = "({[<";
int groupingIndex = 0;
char *rightChar = strchr(rightGroupings, (char)characterToCheck);
if (rightChar) {
groupingIndex = rightChar - rightGroupings;
triedToMatchBrace = YES;
while (location--) {
characterToCheck = [completeString characterAtIndex:location];
if (characterToCheck == leftGroupings[groupingIndex]) {
if (!skipMatchingBrace) {
return NSMakeRange(location, originalLocation - location + 1);
} else {
skipMatchingBrace--;
}
} else if (characterToCheck == *rightChar) {
skipMatchingBrace++;
}
}
//NSBeep();
}
char *leftChar = strchr(leftGroupings, (char)characterToCheck);
if (leftChar) {
groupingIndex = leftChar - leftGroupings;
triedToMatchBrace = YES;
while (++location < lengthOfString) {
characterToCheck = [completeString characterAtIndex:location];
if (characterToCheck == rightGroupings[groupingIndex]) {
if (!skipMatchingBrace) {
return NSMakeRange(originalLocation, location - originalLocation + 1);
} else {
skipMatchingBrace--;
}
} else if (characterToCheck == *leftChar) {
skipMatchingBrace++;
}
}
//NSBeep();
}
// If it has a found a "starting" brace but not found a match, a double-click should only select the "starting" brace and not what it usually would select at a double-click
if (triedToMatchBrace) {
return [super selectionRangeForProposedRange:NSMakeRange(proposedSelRange.location, 1) granularity:NSSelectByCharacter];
} else {
return [super selectionRangeForProposedRange:proposedSelRange granularity:granularity];
}
}
- (NSRange)selectedRangeWasAutomatic:(BOOL*)automatic {
NSRange myRange = [self selectedRange];
if (automatic) {
*automatic = !didRenderFully || NSEqualRanges(lastAutomaticallySelectedRange, myRange);
}
return myRange;
}
- (void)setAutomaticallySelectedRange:(NSRange)newRange {
lastAutomaticallySelectedRange = newRange;
didChangeIntoAutomaticRange = NO;
[self setSelectedRange:newRange];
}
- (IBAction)performFindPanelAction:(id)sender {
id controller = [NSApp delegate];
NSString *typedString = [controller typedString];
NSString *currentFindString = nil;
if (!typedString) typedString = [controlField stringValue];
typedString = [typedString stringByReplacingOccurrencesOfString:@"\"" withString:@""];
NSTextFinder *textFinder = [NSTextFinder sharedTextFinder];
if ([typedString length] > 0 && ![lastImportedFindString isEqualToString:typedString]) {
NSPasteboard *pasteboard = [NSPasteboard pasteboardWithName:NSFindPboard];
[pasteboard declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
[pasteboard setString:typedString forType:NSStringPboardType];
if ([textFinder respondsToSelector:@selector(loadFindStringFromPasteboard)])
[textFinder loadFindStringFromPasteboard];
else
NSLog(@"Apple changed NSTextFinder (loadFindStringFromPasteboard)");
[lastImportedFindString release];
lastImportedFindString = [typedString retain];
}
[currentFindString release];
if ([textFinder respondsToSelector:@selector(findString)])
currentFindString = [[textFinder findString] retain];
else
NSLog(@"Apple changed NSTextFinder (findString)");
int rowNumber = -1;
int totalNotes = [notesTableView numberOfRows];
int tag = [sender tag];
if (![controller selectedNoteObject]) {
rowNumber = (tag == NSFindPanelActionPrevious ? totalNotes - 1 : 0);
} else if (textFinder && [textFinder nv_lastFindWasSuccessful] == LAST_FIND_NO && //if the last find op. didn't work
selectedRangeDuringFind.location == [self selectedRange].location && //and user didn't change the selection
noteDuringFind == [controller selectedNoteObject] && //or select a different note
[stringDuringFind isEqualToString:currentFindString]) { //or type a new search string
//then go to next/previous note in the list
int selectedRow = [notesTableView selectedRow];
rowNumber = (tag == NSFindPanelActionPrevious ? (selectedRow < 1 ? totalNotes - 1 : selectedRow - 1) :
(selectedRow >= totalNotes - 1 ? 0 : selectedRow + 1));
}
if (rowNumber > -1 && tag != NSFindPanelActionShowFindPanel) {
//when skipping notes, also set the selection depending on find direction
[notesTableView selectRowAndScroll:rowNumber];
[self setSelectedRange:NSMakeRange((tag == NSFindPanelActionPrevious ? [[self string] length] : 0),0)];
}
if ([controller selectedNoteObject])
[[self window] makeFirstResponder:self];
[super performFindPanelAction:sender];
[stringDuringFind release];
stringDuringFind = [currentFindString retain];
noteDuringFind = [controller selectedNoteObject];
selectedRangeDuringFind = [self selectedRange];
lastAutomaticallySelectedRange = selectedRangeDuringFind;
}
- (BOOL)performKeyEquivalent:(NSEvent *)anEvent {
if ([anEvent modifierFlags] & NSCommandKeyMask) {
unichar keyChar = [anEvent firstCharacterIgnoringModifiers];
if (keyChar == NSCarriageReturnCharacter || keyChar == NSNewlineCharacter || keyChar == NSEnterCharacter) {
unsigned charIndex = [self selectedRange].location;
id aLink = [self highlightLinkAtIndex:charIndex];
if ([aLink isKindOfClass:[NSURL class]]) {
[self clickedOnLink:aLink atIndex:charIndex];
return YES;
}
} else if ((keyChar == NSBackspaceCharacter || keyChar == NSDeleteCharacter) && [[self window] firstResponder] == self) {
if ([[self string] length]) {
[self doCommandBySelector:@selector(deleteToBeginningOfLine:)];
return YES;
}
}
}
return [super performKeyEquivalent:anEvent];
}
- (void)keyDown:(NSEvent*)anEvent {
unichar keyChar = [anEvent firstCharacterIgnoringModifiers];
if (keyChar == NSBackTabCharacter) {
//apparently interpretKeyEvents: on 10.3 does not call insertBacktab
//maybe it works on someone else's 10.3 Mac
[self doCommandBySelector:@selector(insertBacktab:)];
return;
}
[super keyDown:anEvent];
}
- (BOOL)jumpToRenaming {
NSEvent *event = [[self window] currentEvent];
if ([event type] == NSKeyDown && ![event isARepeat] && NSEqualRanges([self selectedRange], NSMakeRange(0, 0))) {
//command-left at the beginning of the note--jump to editing the title!
[[NSApp delegate] renameNote:nil];
NSText *editor = [notesTableView currentEditor];
NSRange endRange = NSMakeRange([[editor string] length], 0);
[editor setSelectedRange:endRange];
[editor scrollRangeToVisible:endRange];
return YES;
}
return NO;
}
- (void)moveToLeftEndOfLine:(id)sender {
if (![self jumpToRenaming])
[super moveToLeftEndOfLine:sender];
}
- (void)moveToBeginningOfLine:(id)sender {
if (![self jumpToRenaming])
[super moveToBeginningOfLine:sender];
}
- (void)insertTab:(id)sender {
//check prefs for tab behavior
BOOL wasAutomatic = NSEqualRanges(lastAutomaticallySelectedRange, [self selectedRange]);
if ([prefsController tabKeyIndents] && (!wasAutomatic || ![[self string] length] || didChangeIntoAutomaticRange)) {
[self insertTabIgnoringFieldEditor:sender];
} else {
[[self window] selectNextKeyView:self];
}
}
- (void)insertBacktab:(id)sender {
//check temporary NVHiddenBulletIndentAttributeName here first
if ([prefsController autoFormatsListBullets] && [self _selectionAbutsBulletIndentRange]) {
[self shiftLeftAction:nil];
} else {
[[self window] selectPreviousKeyView:self];
}
}
- (void)insertTabIgnoringFieldEditor:(id)sender {
NSRange range = [self selectedRange];
if ((range.length > 0 && [[self string] rangeOfCharacterFromSet:[NSCharacterSet newlineCharacterSet]
options:NSLiteralSearch range:range].location != NSNotFound) ||
([prefsController autoFormatsListBullets] && [self _selectionAbutsBulletIndentRange])) {
//tab shifts text only if there is more than one line selected (i.e., the selection contains at least one line break), or an indented bullet is near
[self shiftRightAction:nil];
} else if ([prefsController softTabs]) {
int numberOfSpacesPerTab = [prefsController numberOfSpacesInTab];
int locationOnLine = range.location - [[self string] lineRangeForRange:range].location;
if (numberOfSpacesPerTab != 0) {
int numberOfSpacesLess = locationOnLine % numberOfSpacesPerTab;
numberOfSpacesPerTab = numberOfSpacesPerTab - numberOfSpacesLess;
}
NSMutableString *spacesString = [[NSMutableString alloc] initWithCapacity:numberOfSpacesPerTab];
while (numberOfSpacesPerTab--) {
[spacesString appendString:@" "];
}
[self insertText:spacesString];
[spacesString release];
} else {
[self insertText:@"\t"];
}
}
- (void)deleteBackward:(id)sender {
NSRange charRange = [self rangeForUserTextChange];
if (charRange.location != NSNotFound) {
if (charRange.length > 0) {
// Non-zero selection. Delete normally.
[super deleteBackward:sender];
} else {
if (charRange.location == 0) {
// At beginning of text. Delete normally.
[super deleteBackward:sender];
} else {
NSString *string = [self string];
NSRange paraRange = [string lineRangeForRange:NSMakeRange(charRange.location - 1, 1)];
if (paraRange.location == charRange.location) {
// At beginning of line. Delete normally.
[super deleteBackward:sender];
} else {
unsigned tabWidth = [prefsController numberOfSpacesInTab];
unsigned indentWidth = 4;
BOOL usesTabs = ![prefsController softTabs];
NSRange leadingSpaceRange = paraRange;
unsigned leadingSpaces = [string numberOfLeadingSpacesFromRange:&leadingSpaceRange tabWidth:tabWidth];
if (charRange.location > NSMaxRange(leadingSpaceRange)) {
// Not in leading whitespace. Delete normally.
[super deleteBackward:sender];
} else {
if ([string rangeOfString:@"\t" options:NSLiteralSearch range:leadingSpaceRange].location == NSNotFound) {
//if this line was indented only with spaces, then keep the soft-tabbed-indentation
usesTabs = NO;
} else if ([string rangeOfString:@" " options:NSLiteralSearch range:leadingSpaceRange].location != NSNotFound && ![prefsController _bodyFontIsMonospace]) {
//mixed tabs and spaces, and we have a proportional font -- what a mess! just revert to normal backward-deletes
[super deleteBackward:sender];
return;
}
NSTextStorage *text = [self textStorage];
unsigned leadingIndents = leadingSpaces / indentWidth;
NSString *replaceString;
// If we were indented to an fractional level just go back to the last even multiple of indentWidth, if we were exactly on, go back a full level.
if (leadingSpaces % indentWidth == 0) {
leadingIndents--;
}
leadingSpaces = leadingIndents * indentWidth;
replaceString = ((leadingSpaces > 0) ? [NSString tabbifiedStringWithNumberOfSpaces:leadingSpaces tabWidth:tabWidth usesTabs:usesTabs] : @"");
if ([self shouldChangeTextInRange:leadingSpaceRange replacementString:replaceString]) {
NSDictionary *newTypingAttributes;
if (charRange.location < [string length]) {
newTypingAttributes = [[text attributesAtIndex:charRange.location effectiveRange:NULL] retain];
} else {
newTypingAttributes = [[text attributesAtIndex:(charRange.location - 1) effectiveRange:NULL] retain];
}
[text replaceCharactersInRange:leadingSpaceRange withString:replaceString];
[self setTypingAttributes:newTypingAttributes];
[newTypingAttributes release];
[self didChangeText];
}
}
}
}
}
}
}
//maybe if we knew we would always have a mono-spaced font
/*- (void)insertNewline:(id)sender {
NSString *lineEnding = @"\n";
NSRange charRange = [self rangeForUserTextChange];
if (charRange.location != NSNotFound) {
NSString *insertString = (lineEnding ? lineEnding : @"");
NSString *string = [self string];
if (charRange.location > 0) {
if (!lineEnding) {
// the newline has already been inserted. Back up by one char.
charRange.location--;
}
if ((charRange.location > 0) && !IsHardLineBreakUnichar([string characterAtIndex:(charRange.location - 1)], string, charRange.location - 1)) {
unsigned tabWidth = [prefsController numberOfSpacesInTab];
NSRange paraRange = [string lineRangeForRange:NSMakeRange(charRange.location - 1, 1)];
unsigned leadingSpaces = [string numberOfLeadingSpacesFromRange:¶Range tabWidth:tabWidth];
insertString = [insertString stringByAppendingString:[NSString tabbifiedStringWithNumberOfSpaces:leadingSpaces tabWidth:tabWidth
usesTabs:![prefsController softTabs]]];
}
}
[self insertText:insertString];
}
}*/
- (void)mouseEntered:(NSEvent*)anEvent {
mouseInside = YES;
[self fixCursorForBackgroundUpdatingMouseInside:NO];
}
- (void)mouseExited:(NSEvent*)anEvent {
mouseInside = NO;
[self fixCursorForBackgroundUpdatingMouseInside:NO];
}
- (void)_fixCursorForBackgroundUpdatingMouseInside:(NSNumber*)num {
[self fixCursorForBackgroundUpdatingMouseInside:[num boolValue]];
}
- (void)fixCursorForBackgroundUpdatingMouseInside:(BOOL)setMouseInside {