/
OakTextView.mm
2644 lines (2261 loc) · 89 KB
/
OakTextView.mm
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
#import "OakTextView.h"
#import "OakPasteboardWrapper.h"
#import "OakChoiceMenu.h"
#import "OakDocumentView.h" // addAuxiliaryView:atEdge: signature
#import <OakAppKit/OakAppKit.h>
#import <OakAppKit/NSEvent Additions.h>
#import <OakAppKit/NSColor Additions.h>
#import <OakAppKit/NSImage Additions.h>
#import <OakAppKit/NSMenuItem Additions.h>
#import <OakAppKit/OakPasteboard.h>
#import <OakAppKit/OakPopOutAnimation.h>
#import <OakAppKit/OakToolTip.h>
#import <OakFoundation/NSString Additions.h>
#import <OakFoundation/OakFoundation.h>
#import <OakFoundation/OakTimer.h>
#import <OakSystem/application.h>
#import <bundles/bundles.h>
#import <cf/cf.h>
#import <command/runner.h>
#import <document/collection.h>
#import <file/type.h>
#import <layout/layout.h>
#import <ns/ns.h>
#import <ns/spellcheck.h>
#import <text/classification.h>
#import <text/format.h>
#import <text/utf16.h>
#import <text/utf8.h>
#import <oak/CocoaSTL.h>
#import <oak/debug.h>
OAK_DEBUG_VAR(OakTextView_TextInput);
OAK_DEBUG_VAR(OakTextView_Spelling);
OAK_DEBUG_VAR(OakTextView_ViewRect);
OAK_DEBUG_VAR(OakTextView_NSView);
OAK_DEBUG_VAR(OakTextView_DragNDrop);
OAK_DEBUG_VAR(OakTextView_MouseEvents);
OAK_DEBUG_VAR(OakTextView_Macros);
int32_t const NSWrapColumnWindowWidth = 0;
int32_t const NSWrapColumnAskUser = -1;
NSString* const kUserDefaultsDisableAntiAliasKey = @"disableAntiAlias";
@interface OakTextView ()
+ (NSArray*)dropTypes;
- (void)ensureSelectionIsInVisibleArea:(id)sender;
- (NSPoint)positionForWindowUnderCaret;
- (void)toggleColumnSelection:(id)sender;
- (void)delete:(id)sender;
- (void)updateChoiceMenu:(id)sender;
- (void)resetBlinkCaretTimer;
- (void)reflectDocumentSize;
- (void)updateSelection;
- (void)updateMarkedRanges;
- (void)redisplayFrom:(size_t)from to:(size_t)to;
- (void)recordSelector:(SEL)aSelector withArgument:(id)anArgument;
- (NSImage*)imageForRanges:(ng::ranges_t const&)ranges imageRect:(NSRect*)outRect;
- (void)highlightRanges:(ng::ranges_t const&)ranges;
@property (nonatomic, assign) ng::ranges_t const& markedRanges;
@property (nonatomic, retain) NSDate* optionDownDate;
@property (nonatomic, retain) OakTimer* initiateDragTimer;
@property (nonatomic, retain) OakTimer* dragScrollTimer;
@property (nonatomic, assign) BOOL showDragCursor;
@property (nonatomic, assign) BOOL showColumnSelectionCursor;
@property (nonatomic, readonly) BOOL hasSelection;
@property (nonatomic, retain) OakChoiceMenu* choiceMenu;
@property (nonatomic, assign) NSUInteger refreshNestCount;
@property (nonatomic, retain) NSViewController* liveSearchViewController;
@property (nonatomic, copy) NSString* liveSearchString;
@property (nonatomic, assign) ng::ranges_t const& liveSearchRanges;
@end
static std::vector<bundles::item_ptr> items_for_tab_expansion (ng::buffer_t const& buffer, ng::ranges_t const& ranges, std::string const& scopeAttributes, ng::range_t* range)
{
size_t caret = ranges.last().min().index;
size_t line = buffer.convert(caret).line;
size_t bol = buffer.begin(line);
bool lastWasWordChar = false;
std::string lastCharacterClass = ng::kCharacterClassUnknown;
for(size_t i = bol; i < caret; i += buffer[i].size())
{
// we don’t use text::is_word_char because that function treats underscores as word characters, which is undesired, see <issue://157>.
bool isWordChar = CFCharacterSetIsLongCharacterMember(CFCharacterSetGetPredefined(kCFCharacterSetAlphaNumeric), utf8::to_ch(buffer[i]));
std::string characterClass = character_class(buffer, i);
if(i == bol || lastWasWordChar != isWordChar || lastCharacterClass != characterClass)
{
std::vector<bundles::item_ptr> const& items = bundles::query(bundles::kFieldTabTrigger, buffer.substr(i, caret), ng::scope(buffer, ng::ranges_t(i), scopeAttributes));
if(!items.empty())
{
if(range)
*range = ng::range_t(i, caret);
return items;
}
}
lastWasWordChar = isWordChar;
lastCharacterClass = characterClass;
}
return std::vector<bundles::item_ptr>();
}
static ng::ranges_t merge (ng::ranges_t lhs, ng::ranges_t const& rhs)
{
iterate(range, rhs)
lhs.push_back(*range);
return lhs;
}
struct refresh_helper_t
{
typedef std::shared_ptr<ng::layout_t> layout_ptr;
refresh_helper_t (OakTextView* self, document::document_ptr document, ng::editor_ptr editor, layout_ptr theLayout) : _self(self), _document(document), _editor(editor), _layout(theLayout)
{
if(++_self.refreshNestCount == 1)
{
_revision = document->buffer().revision();
_selection = editor->ranges();
_document->undo_manager().begin_undo_group(_editor->ranges());
if(layout_ptr layout = _layout.lock())
layout->begin_refresh_cycle(merge(_editor->ranges(), [_self markedRanges]), [_self liveSearchRanges]);
}
}
static NSView* find_gutter_view (NSView* view)
{
for(NSView* candidate in [view subviews])
{
if([candidate isKindOfClass:NSClassFromString(@"GutterView")])
return candidate;
else if(NSView* res = find_gutter_view(candidate))
return res;
}
return nil;
}
~refresh_helper_t ()
{
if(--_self.refreshNestCount == 0)
{
_document->undo_manager().end_undo_group(_editor->ranges());
if(layout_ptr layout = _layout.lock())
{
if(_revision == _document->buffer().revision())
{
citerate(range, ng::highlight_ranges_for_movement(_document->buffer(), _selection, _editor->ranges()))
{
NSRect imageRect;
NSImage* image = [_self imageForRanges:*range imageRect:&imageRect];
imageRect = [_self convertRect:imageRect toView:nil];
imageRect.origin = [[_self window] convertBaseToScreen:imageRect.origin];
OakShowPopOutAnimation(imageRect, image);
}
}
if(_revision != _document->buffer().revision() || _selection != _editor->ranges())
[_self updateMarkedRanges];
auto damagedRects = layout->end_refresh_cycle(merge(_editor->ranges(), [_self markedRanges]), [_self visibleRect], [_self liveSearchRanges]);
NSRect r = [[_self enclosingScrollView] documentVisibleRect];
NSSize newSize = NSMakeSize(std::max(NSWidth(r), layout->width()), std::max(NSHeight(r), layout->height()));
if(!NSEqualSizes([_self frame].size, newSize))
[_self setFrameSize:newSize];
NSView* gutterView = find_gutter_view([[_self enclosingScrollView] superview]);
iterate(rect, damagedRects)
{
[_self setNeedsDisplayInRect:*rect];
if(gutterView)
{
NSRect r = *rect;
r.origin.x = 0;
r.size.width = NSWidth([gutterView frame]);
[gutterView setNeedsDisplayInRect:r];
}
}
if(_revision != _document->buffer().revision() || _selection != _editor->ranges())
{
if(_revision != _document->buffer().revision()) // FIXME document_t needs to skip work in set_revision if nothing changed.
_document->set_revision(_document->buffer().revision());
[_self updateSelection];
[_self ensureSelectionIsInVisibleArea:nil];
[_self resetBlinkCaretTimer];
[_self updateChoiceMenu:nil];
}
}
}
}
private:
OakTextView* _self;
document::document_ptr _document;
size_t _revision;
ng::editor_ptr _editor;
ng::ranges_t _selection;
std::weak_ptr<ng::layout_t> _layout;
};
#define AUTO_REFRESH refresh_helper_t _dummy(self, document, editor, layout)
struct buffer_refresh_callback_t : ng::callback_t
{
buffer_refresh_callback_t (OakTextView* textView) : textView(textView) { }
void did_parse (size_t from, size_t to);
private:
OakTextView* textView;
};
void buffer_refresh_callback_t::did_parse (size_t from, size_t to)
{
[textView redisplayFrom:from to:to];
}
static std::string shell_quote (std::vector<std::string> paths)
{
iterate(it, paths)
*it = format_string::replace(*it, ".*", "'${0/'/'\\''/g}'");
return text::join(paths, " ");
}
// =============================
// = OakTextView’s Find Server =
// =============================
@interface OakTextViewFindServer : NSObject <OakFindServerProtocol>
{
OakTextView* textView;
find_operation_t findOperation;
find::options_t findOptions;
}
@property (nonatomic, retain) OakTextView* textView;
@property (nonatomic, readonly) find_operation_t findOperation;
@property (nonatomic, readonly) find::options_t findOptions;
@end
@implementation OakTextViewFindServer
@synthesize textView, findOperation, findOptions;
- (id)initWithTextView:(OakTextView*)aTextView operation:(find_operation_t)anOperation options:(find::options_t)someOptions
{
if((self = [super init]))
{
self.textView = aTextView;
findOperation = anOperation;
findOptions = someOptions;
}
return self;
}
- (void)dealloc
{
[textView release];
[super dealloc];
}
+ (id)findServerWithTextView:(OakTextView*)aTextView operation:(find_operation_t)anOperation options:(find::options_t)someOptions
{
return [[[self alloc] initWithTextView:aTextView operation:anOperation options:someOptions] autorelease];
}
- (NSString*)findString { return [[OakPasteboard pasteboardWithName:NSFindPboard] current].string; }
- (NSString*)replaceString { return [[OakPasteboard pasteboardWithName:NSReplacePboard] current].string; }
- (void)didFind:(NSUInteger)aNumber occurrencesOf:(NSString*)aFindString atPosition:(text::pos_t const&)aPosition
{
static NSString* const formatStrings[2][3] = {
{ @"No more occurrences of “%@”.", nil, @"%2$ld occurrences of “%@”." },
{ @"No more matches for “%@”.", nil, @"%2$ld matches for “%@”." },
};
if(NSString* format = formatStrings[(findOptions & find::regular_expression) ? 1 : 0][aNumber > 2 ? 2 : aNumber])
OakShowToolTip([NSString stringWithFormat:format, aFindString, aNumber], [textView positionForWindowUnderCaret]);
}
- (void)didReplace:(NSUInteger)aNumber occurrencesOf:(NSString*)aFindString with:(NSString*)aReplacementString
{
static NSString* const formatStrings[2][3] = {
{ @"Nothing replaced (no occurrences of “%@”).", @"Replaced one occurrence of “%@”.", @"Replaced %2$ld occurrences of “%@”." },
{ @"Nothing replaced (no matches for “%@”).", @"Replaced one match of “%@”.", @"Replaced %2$ld matches of “%@”." }
};
NSString* format = formatStrings[(findOptions & find::regular_expression) ? 1 : 0][aNumber > 2 ? 2 : aNumber];
OakShowToolTip([NSString stringWithFormat:format, aFindString, aNumber], [textView positionForWindowUnderCaret]);
}
@end
@implementation OakTextView
@synthesize antiAlias;
@synthesize initiateDragTimer, dragScrollTimer, optionDownDate, showColumnSelectionCursor, showDragCursor, choiceMenu;
@synthesize markedRanges;
@synthesize document;
@synthesize refreshNestCount;
@synthesize liveSearchViewController, liveSearchString, liveSearchRanges;
- (NSImage*)imageForRanges:(ng::ranges_t const&)ranges imageRect:(NSRect*)outRect
{
NSRect srcRect = NSZeroRect, visibleRect = [self visibleRect];
citerate(range, ranges)
srcRect = NSUnionRect(srcRect, NSIntersectionRect(visibleRect, layout->rect_for_range(range->min().index, range->max().index)));
NSBezierPath* clip = [NSBezierPath bezierPath];
citerate(rect, layout->rects_for_ranges(ranges))
[clip appendBezierPath:[NSBezierPath bezierPathWithRect:NSOffsetRect(*rect, -NSMinX(srcRect), -NSMinY(srcRect))]];
NSImage* image = [[[NSImage alloc] initWithSize:NSMakeSize(std::max<CGFloat>(NSWidth(srcRect), 1), std::max<CGFloat>(NSHeight(srcRect), 1))] autorelease];
[image setFlipped:[self isFlipped]];
[image lockFocus];
[clip addClip];
CGContextRef context = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
CGContextTranslateCTM(context, -NSMinX(srcRect), -NSMinY(srcRect));
NSRectClip(srcRect);
layout->draw(context, srcRect, [self isFlipped], false, ng::ranges_t(), ng::ranges_t(), false, cf::color_t("#000000"));
[image unlockFocus];
[image setFlipped:NO];
if(outRect)
*outRect = srcRect;
return image;
}
- (void)highlightRanges:(ng::ranges_t const&)ranges
{
iterate(range, ranges)
layout->remove_enclosing_folds(range->min().index, range->max().index);
[self ensureSelectionIsInVisibleArea:self];
citerate(range, ranges)
{
NSRect imageRect;
NSImage* image = [self imageForRanges:*range imageRect:&imageRect];
imageRect = [self convertRect:imageRect toView:nil];
imageRect.origin = [[self window] convertBaseToScreen:imageRect.origin];
OakShowPopOutAnimation(imageRect, image);
}
}
- (void)setDocument:(document::document_ptr const&)aDocument
{
if(document && aDocument && *document == *aDocument)
{
if(document->selection() != NULL_STR)
{
ng::ranges_t ranges = convert(document->buffer(), document->selection());
editor->set_selections(ranges);
iterate(range, ranges)
layout->remove_enclosing_folds(range->min().index, range->max().index);
[self ensureSelectionIsInVisibleArea:self];
[self updateSelection];
}
[self resetBlinkCaretTimer];
return;
}
if(editor)
{
document->buffer().remove_callback(callback);
document->set_folded(layout->folded_as_string());
delete callback;
callback = NULL;
editor.reset();
layout.reset();
self.choiceMenu = nil;
choiceVector.clear();
}
if(document = aDocument)
{
settings_t const& settings = document->settings();
editor = ng::editor_for_document(document);
wrapColumn = settings.get(kSettingsWrapColumnKey, wrapColumn);
layout.reset(new ng::layout_t(document->buffer(), theme, fontName, fontSize, settings.get(kSettingsSoftWrapKey, false), wrapColumn, document->folded()));
if(settings.get(kSettingsShowWrapColumnKey, false))
layout->set_draw_wrap_column(true);
BOOL hasFocus = (self.keyState & (OakViewViewIsFirstResponderMask|OakViewWindowIsKeyMask|OakViewApplicationIsActiveMask)) == (OakViewViewIsFirstResponderMask|OakViewWindowIsKeyMask|OakViewApplicationIsActiveMask);
layout->set_is_key(hasFocus);
callback = new buffer_refresh_callback_t(self);
editor->set_clipboard(get_clipboard(NSGeneralPboard));
editor->set_find_clipboard(get_clipboard(NSFindPboard));
editor->set_replace_clipboard(get_clipboard(NSReplacePboard));
std::string const visibleRect = document->visible_rect();
if(document->selection() != NULL_STR)
{
ng::ranges_t ranges = convert(document->buffer(), document->selection());
editor->set_selections(ranges);
iterate(range, ranges)
layout->remove_enclosing_folds(range->min().index, range->max().index);
}
auto bgColor = theme->styles_for_scope(document->buffer().scope(0).left, fontName, fontSize).background();
[[self enclosingScrollView] setBackgroundColor:[NSColor colorWithCGColor:bgColor]];
SetLionScrollerKnobStyle([self enclosingScrollView], cf::color_is_dark(bgColor) ? NSScrollerKnobStyleLight : NSScrollerKnobStyleDark);
[[self window] setOpaque:CGColorGetAlpha(bgColor) == 1];
[self reflectDocumentSize];
[self updateSelection];
if(visibleRect != NULL_STR)
[self scrollRectToVisible:NSRectFromString([NSString stringWithCxxString:visibleRect])];
else [self ensureSelectionIsInVisibleArea:self];
document->buffer().add_callback(callback);
[self resetBlinkCaretTimer];
[self setNeedsDisplay:YES];
}
}
- (id)initWithFrame:(NSRect)aRect
{
if(self = [super initWithFrame:aRect])
{
settings_t const& settings = settings_for_path();
theme = parse_theme(bundles::lookup(settings.get(kSettingsThemeKey, NULL_STR)));
fontName = settings.get(kSettingsFontNameKey, NULL_STR);
fontSize = settings.get(kSettingsFontSizeKey, 11);
showInvisibles = settings.get(kSettingsShowInvisiblesKey, false);
antiAlias = ![[NSUserDefaults standardUserDefaults] boolForKey:kUserDefaultsDisableAntiAliasKey];
[self registerForDraggedTypes:[[self class] dropTypes]];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(documentWillSave:) name:@"OakDocumentNotificationWillSave" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userDefaultsDidChange:) name:NSUserDefaultsDidChangeNotification object:[NSUserDefaults standardUserDefaults]];
}
return self;
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
[liveSearchString release];
[self setDocument:document::document_ptr()];
[super dealloc];
}
- (void)documentWillSave:(NSNotification*)aNotification
{
if(document && layout)
document->set_folded(layout->folded_as_string());
}
- (void)reflectDocumentSize
{
if(document && layout && [self enclosingScrollView])
{
NSRect r = [[self enclosingScrollView] documentVisibleRect];
layout->set_viewport_size(r.size);
NSSize newSize = NSMakeSize(std::max(NSWidth(r), layout->width()), std::max(NSHeight(r), layout->height()));
if(!NSEqualSizes([self frame].size, newSize))
[self setFrameSize:newSize];
}
}
- (void)resizeWithOldSuperviewSize:(NSSize)oldBoundsSize
{
if(document && layout)
[self reflectDocumentSize];
else [super resizeWithOldSuperviewSize:oldBoundsSize];
}
- (void)centerSelectionInVisibleArea:(id)sender
{
[self recordSelector:_cmd withArgument:nil];
CGRect r = layout->rect_at_index(editor->ranges().last().last);
CGFloat w = NSWidth([self visibleRect]), h = NSHeight([self visibleRect]);
CGFloat x = r.origin.x < w ? 0 : r.origin.x - w/2;
CGFloat y = oak::cap(NSMinY([self frame]), r.origin.y - (h-r.size.height)/2, NSHeight([self frame]) - h);
[self scrollRectToVisible:CGRectMake(round(x), round(y), w, h)];
}
- (void)ensureSelectionIsInVisibleArea:(id)sender
{
CGRect r = layout->rect_at_index(editor->ranges().last().last);
CGRect s = [self visibleRect];
CGFloat x = NSMinX(s), w = NSWidth(s);
CGFloat y = NSMinY(s), h = NSHeight(s);
if(x + w - 2*r.size.width < r.origin.x)
{
D(DBF_OakTextView_ViewRect, bug("scroll right\n"););
x = r.origin.x + 5*r.size.width - w;
}
else if(r.origin.x < x + 2*r.size.width)
{
D(DBF_OakTextView_ViewRect, bug("scroll left\n"););
x = r.origin.x < w/2 ? 0 : r.origin.x - 5*r.size.width;
}
if(oak::cap<CGFloat>(y + h - 1.5*r.size.height, r.origin.y, y + h + 1.5*r.size.height) == r.origin.y) // scroll down
{
D(DBF_OakTextView_ViewRect, bug("scroll down\n"););
y = r.origin.y + 1.5*r.size.height - h;
}
else if(oak::cap<CGFloat>(y - 3*r.size.height, r.origin.y, y + 0.5*r.size.height) == r.origin.y) // scroll up
{
D(DBF_OakTextView_ViewRect, bug("scroll up\n"););
y = r.origin.y - 0.5*r.size.height;
}
else if(oak::cap(y, r.origin.y, y + h) != r.origin.y) // center y
{
y = r.origin.y - (h-r.size.height)/2;
}
CGRect b = [self bounds];
x = oak::cap(NSMinX(b), x, NSMaxX(b) - w);
y = oak::cap(NSMinY(b), y, NSMaxY(b) - h);
NSClipView* contentView = [[self enclosingScrollView] contentView];
if([contentView respondsToSelector:@selector(_extendNextScrollRelativeToCurrentPosition)])
[contentView performSelector:@selector(_extendNextScrollRelativeToCurrentPosition)];
[self scrollRectToVisible:CGRectMake(round(x), round(y), w, h)];
}
- (void)updateChoiceMenu:(id)sender
{
if(choiceVector == editor->choices())
return;
self.choiceMenu = nil;
choiceVector = editor->choices();
if(!choiceVector.empty())
{
choiceMenu = [OakChoiceMenu new];
choiceMenu.choices = (NSArray*)((CFArrayRef)cf::wrap(choiceVector));
std::string const& currentChoice = editor->placeholder_content();
for(size_t i = choiceVector.size(); i-- > 0; )
{
if(choiceVector[i] == currentChoice)
choiceMenu.choiceIndex = i;
}
[choiceMenu showAtTopLeftPoint:[self positionForWindowUnderCaret] forView:self];
}
}
// ======================
// = Generic view stuff =
// ======================
- (BOOL)acceptsFirstResponder { return YES; }
- (BOOL)isFlipped { return YES; }
- (BOOL)isOpaque { return YES; }
- (void)redisplayFrom:(size_t)from to:(size_t)to
{
AUTO_REFRESH;
layout->did_update_scopes(from, to);
}
- (void)drawRect:(NSRect)aRect
{
[[NSColor clearColor] set];
NSRectFill(aRect); // Only necessary when theme uses a transparent background.
CGContextRef context = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
if(!antiAlias)
CGContextSetShouldAntialias(context, false);
layout->draw(context, aRect, [self isFlipped], showInvisibles, merge(editor->ranges(), [self markedRanges]), liveSearchRanges);
}
// ===============
// = NSTextInput =
// ===============
- (NSInteger)conversationIdentifier
{
return (NSInteger)self;
}
// ==================
// = Accented input =
// ==================
- (void)setMarkedText:(id)aString selectedRange:(NSRange)aRange
{
D(DBF_OakTextView_TextInput, bug("‘%s’ %s\n", to_s([aString description]).c_str(), [NSStringFromRange(aRange) UTF8String]););
if(![aString isKindOfClass:[NSString class]])
{
if([aString respondsToSelector:@selector(string)])
aString = [aString string];
else if([aString respondsToSelector:@selector(description)])
aString = [aString description];
else
aString = @"<ERROR>";
}
AUTO_REFRESH;
if(!markedRanges.empty())
editor->set_selections(markedRanges);
markedRanges = ng::ranges_t();
editor->insert(to_s([aString description]), true);
if([aString length] != 0)
markedRanges = editor->ranges();
pendingMarkedRanges = markedRanges;
ng::ranges_t sel;
citerate(range, editor->ranges())
{
std::string const str = document->buffer().substr(range->min().index, range->max().index);
char const* base = str.data();
size_t from = utf16::advance(base, aRange.location) - base;
size_t to = utf16::advance(base, aRange.location + aRange.length) - base;
sel.push_back(ng::range_t(range->min() + from, range->min() + to));
}
editor->set_selections(sel);
}
- (NSRange)selectedRange
{
std::string const text = editor->as_string();
ng::range_t const r = editor->ranges().last();
NSRange res = NSMakeRange(utf16::distance(text.data(), text.data() + r.min().index), utf16::distance(text.data() + r.min().index, text.data() + r.max().index));
D(DBF_OakTextView_TextInput, bug("%s\n", [NSStringFromRange(res) UTF8String]););
return res;
}
- (NSRange)markedRange
{
D(DBF_OakTextView_TextInput, bug("%s\n", to_s(markedRanges).c_str()););
if(markedRanges.empty())
return NSMakeRange(NSNotFound, 0);
ng::range_t const r = markedRanges.last();
std::string const text = document->buffer().substr(0, r.max().index);
return NSMakeRange(utf16::distance(text.data(), text.data() + r.min().index), utf16::distance(text.data() + r.min().index, text.data() + r.max().index));
}
- (void)unmarkText
{
D(DBF_OakTextView_TextInput, bug("\n"););
AUTO_REFRESH;
markedRanges = ng::ranges_t();
}
- (BOOL)hasMarkedText
{
D(DBF_OakTextView_TextInput, bug("%s\n", BSTR(!markedRanges.empty())););
return !markedRanges.empty();
}
- (NSArray*)validAttributesForMarkedText
{
D(DBF_OakTextView_TextInput, bug("\n"););
return [NSArray array];
}
- (void)updateMarkedRanges
{
if(!markedRanges.empty() && pendingMarkedRanges.empty())
[[NSInputManager currentInputManager] markedTextAbandoned:self];
markedRanges = pendingMarkedRanges;
pendingMarkedRanges = ng::ranges_t();
}
// =====================
// = Dictionary pop-up =
// =====================
- (NSString*)string
{
D(DBF_OakTextView_TextInput, bug("\n"););
return [NSString stringWithCxxString:editor->as_string()]; // While undocumented (<rdar://4178606>), this is required in Lion to work with the dictionary implementation (⌃⌘D)
}
- (NSUInteger)characterIndexForPoint:(NSPoint)thePoint
{
NSPoint p = [self convertPoint:[[self window] convertScreenToBase:thePoint] fromView:nil];
std::string const text = editor->as_string();
size_t index = layout->index_at_point(p).index;
D(DBF_OakTextView_TextInput, bug("%s → %zu\n", [NSStringFromPoint(thePoint) UTF8String], index););
return utf16::distance(text.data(), text.data() + index);
}
- (NSAttributedString*)attributedSubstringFromRange:(NSRange)theRange
{
std::string const text = editor->as_string();
char const* const base = text.data();
size_t from = utf16::advance(base, theRange.location, base + text.size()) - base;
size_t to = utf16::advance(base + from, theRange.length, base + text.size()) - base;
CFMutableAttributedStringRef res = CFAttributedStringCreateMutable(kCFAllocatorDefault, 0);
std::map<size_t, scope::scope_t> scopes = document->buffer().scopes(from, to);
for(auto pair = scopes.begin(); pair != scopes.end(); )
{
styles_t const& styles = theme->styles_for_scope(pair->second, fontName, fontSize);
size_t i = from + pair->first;
size_t j = ++pair != scopes.end() ? from + pair->first : to;
CFMutableAttributedStringRef str = CFAttributedStringCreateMutable(kCFAllocatorDefault, 0);
CFAttributedStringReplaceString(str, CFRangeMake(0, 0), cf::wrap(text.substr(i, j - i)));
CFAttributedStringSetAttribute(str, CFRangeMake(0, CFAttributedStringGetLength(str)), kCTFontAttributeName, styles.font());
CFAttributedStringSetAttribute(str, CFRangeMake(0, CFAttributedStringGetLength(str)), kCTForegroundColorAttributeName, styles.foreground());
if(styles.underlined())
CFAttributedStringSetAttribute(str, CFRangeMake(0, CFAttributedStringGetLength(str)), kCTUnderlineStyleAttributeName, cf::wrap(0x1|kCTUnderlinePatternSolid));
CFAttributedStringReplaceAttributedString(res, CFRangeMake(CFAttributedStringGetLength(res), 0), str);
CFRelease(str);
}
return [(NSAttributedString*)res autorelease];
}
- (NSRect)firstRectForCharacterRange:(NSRange)theRange
{
std::string const text = editor->as_string();
size_t index = utf16::advance(text.data(), theRange.location) - text.data();
NSRect rect = [self convertRect:layout->rect_at_index(index) toView:nil];
rect.origin = [[self window] convertBaseToScreen:rect.origin];
D(DBF_OakTextView_TextInput, bug("%s → %s\n", [NSStringFromRange(theRange) UTF8String], [NSStringFromRect(rect) UTF8String]););
return rect;
}
- (void)doCommandBySelector:(SEL)aSelector
{
D(DBF_OakTextView_TextInput, bug("%s\n", sel_getName(aSelector)););
AUTO_REFRESH;
[self tryToPerform:aSelector with:self];
}
// ================
// = Bundle Items =
// ================
- (void)performBundleItem:(bundles::item_ptr const&)item
{
// D(DBF_OakTextView_BundleItems, bug("%s\n", anItem->full_name().c_str()););
AUTO_REFRESH;
switch(item->kind())
{
case bundles::kItemTypeSnippet:
{
[self recordSelector:@selector(insertSnippetWithOptions:) withArgument:ns::to_dictionary(item->plist())];
editor->snippet_dispatch(item->plist(), editor->variables(item->environment()));
}
break;
case bundles::kItemTypeCommand:
{
[self recordSelector:@selector(executeCommandWithOptions:) withArgument:ns::to_dictionary(item->plist())];
document::run(parse_command(item), document->buffer(), editor->ranges(), document);
}
break;
case bundles::kItemTypeMacro:
{
[self recordSelector:@selector(playMacroWithOptions:) withArgument:ns::to_dictionary(item->plist())];
editor->macro_dispatch(item->plist(), editor->variables(item->environment()));
}
break;
case bundles::kItemTypeGrammar:
{
document->set_file_type(item->value_for_field(bundles::kFieldGrammarScope));
file::set_type(document->virtual_path(), item->value_for_field(bundles::kFieldGrammarScope));
}
break;
case bundles::kItemTypeTheme:
{
OakDocumentView* documentView = (OakDocumentView*)[[self enclosingScrollView] superview];
[documentView setThemeWithUUID:[NSString stringWithCxxString:item->uuid()]];
}
break;
}
}
- (void)applicationDidBecomeActiveNotification:(NSNotification*)aNotification
{
citerate(item, bundles::query(bundles::kFieldSemanticClass, "callback.application.did-activate", editor->scope()))
[self performBundleItem:*item];
}
- (void)applicationDidResignActiveNotification:(NSNotification*)aNotification
{
citerate(item, bundles::query(bundles::kFieldSemanticClass, "callback.application.did-deactivate", editor->scope()))
[self performBundleItem:*item];
}
// ============
// = Key Down =
// ============
static plist::dictionary_t KeyBindings;
static plist::dictionary_t const* KeyEventContext = &KeyBindings;
static plist::any_t normalize_potential_dictionary (plist::any_t const& action)
{
if(plist::dictionary_t const* dict = boost::get<plist::dictionary_t>(&action))
{
plist::dictionary_t res;
citerate(pair, *dict)
res.insert(std::make_pair(ns::normalize_event_string(pair->first), normalize_potential_dictionary(pair->second)));
return res;
}
return action;
}
typedef std::multimap<std::string, std::string> action_to_key_t;
static void update_menu_key_equivalents (NSMenu* menu, action_to_key_t const& actionToKey)
{
for(NSMenuItem* item in [menu itemArray])
{
SEL action = [item action];
action_to_key_t::const_iterator it = actionToKey.find(sel_getName(action));
if(it != actionToKey.end() && [[item keyEquivalent] isEqualToString:@""])
[item setKeyEquivalentCxxString:it->second];
update_menu_key_equivalents([item submenu], actionToKey);
}
}
+ (void)initialize
{
static bool didLoad = false;
if(!didLoad)
{
didLoad = true;
static std::string const localKeyBindings = oak::application_t::support("KeyBindings.dict");
static std::string const defaultKeyBindings = oak::application_t::path("Contents/Resources/KeyBindings.dict");
static std::string const KeyBindingLocations[] =
{
path::exists(localKeyBindings) ? localKeyBindings : defaultKeyBindings,
path::join(path::home(), "Library/KeyBindings/DefaultKeyBinding.dict"),
"/Library/KeyBindings/DefaultKeyBinding.dict",
"/System/Library/Frameworks/AppKit.framework/Resources/StandardKeyBinding.dict",
};
iterate(path, KeyBindingLocations)
{
citerate(pair, plist::load(*path))
KeyBindings.insert(std::make_pair(ns::normalize_event_string(pair->first), normalize_potential_dictionary(pair->second)));
}
action_to_key_t actionToKey;
iterate(pair, KeyBindings)
{
if(std::string const* selector = boost::get<std::string>(&pair->second))
actionToKey.insert(std::make_pair(*selector, pair->first));
}
update_menu_key_equivalents([NSApp mainMenu], actionToKey);
}
[NSApp registerServicesMenuSendTypes:@[ NSStringPboardType ] returnTypes:@[ NSStringPboardType ]];
}
// ======================
// = NSServicesRequests =
// ======================
- (id)validRequestorForSendType:(NSString*)sendType returnType:(NSString*)returnType
{
if([sendType isEqual:NSStringPboardType] && [self hasSelection] && !macroRecordingArray)
return self;
if(!sendType && [returnType isEqual:NSStringPboardType] && !macroRecordingArray)
return self;
return [super validRequestorForSendType:sendType returnType:returnType];
}
- (BOOL)writeSelectionToPasteboard:(NSPasteboard*)pboard types:(NSArray*)types
{
BOOL res = NO;
if([self hasSelection] && [types containsObject:NSStringPboardType])
{
std::vector<std::string> v;
ng::ranges_t const ranges = ng::dissect_columnar(document->buffer(), editor->ranges());
iterate(range, ranges)
v.push_back(document->buffer().substr(range->min().index, range->max().index));
[pboard declareTypes:@[ NSStringPboardType ] owner:nil];
res = [pboard setString:[NSString stringWithCxxString:text::join(v, "\n")] forType:NSStringPboardType];
}
return res;
}
- (BOOL)readSelectionFromPasteboard:(NSPasteboard*)pboard
{
if(NSString* str = [pboard stringForType:[pboard availableTypeFromArray:@[ @"public.plain-text" ]]])
{
AUTO_REFRESH;
editor->insert(to_s(str));
return YES;
}
return NO;
}
// ======================
- (void)handleKeyBindingAction:(plist::any_t const&)anAction
{
AUTO_REFRESH;
if(std::string const* selector = boost::get<std::string>(&anAction))
{
KeyEventContext = &KeyBindings;
[self doCommandBySelector:NSSelectorFromString([NSString stringWithCxxString:*selector])];
}
else if(plist::array_t const* actions = boost::get<plist::array_t>(&anAction))
{
KeyEventContext = &KeyBindings;
std::vector<std::string> selectors;
iterate(it, *actions)
{
if(std::string const* selector = boost::get<std::string>(&*it))
selectors.push_back(*selector);
}
for(size_t i = 0; i < selectors.size(); ++i)
{
if(selectors[i] == "insertText:" && i+1 < selectors.size())
[self insertText:[NSString stringWithCxxString:selectors[++i]]];
else [self doCommandBySelector:NSSelectorFromString([NSString stringWithCxxString:selectors[i]])];
}
}
else if(plist::dictionary_t const* nested = boost::get<plist::dictionary_t>(&anAction))
{
KeyEventContext = nested;
}
}
- (BOOL)performKeyEquivalent:(NSEvent*)anEvent
{
BOOL hasFocus = (self.keyState & (OakViewViewIsFirstResponderMask|OakViewWindowIsKeyMask|OakViewApplicationIsActiveMask)) == (OakViewViewIsFirstResponderMask|OakViewWindowIsKeyMask|OakViewApplicationIsActiveMask);
if(!hasFocus && ([[[self window] firstResponder] isKindOfClass:[self class]] || [[[self window] firstResponder] isKindOfClass:NSClassFromString(@"OakKeyEquivalentView")]))
return NO;
D(DBF_OakTextView_TextInput, bug("%s\n", [[anEvent description] UTF8String]););
AUTO_REFRESH;
std::string const eventString = to_s(anEvent);
if(KeyEventContext != &KeyBindings)
{
plist::dictionary_t::const_iterator pair = KeyEventContext->find(eventString);
if(pair != KeyEventContext->end())
return [self handleKeyBindingAction:pair->second], YES;
}
std::vector<bundles::item_ptr> const& items = bundles::query(bundles::kFieldKeyEquivalent, eventString, editor->scope());
if(!items.empty())
{
if(bundles::item_ptr item = bundles::show_menu_for_items(items, [self positionForWindowUnderCaret]))
[self performBundleItem:item];
return YES;
}
static std::string const kBackwardDelete = "\x7F";
static std::string const kForwardDelete = "\uF728";
static std::string const kUpArrow = "\uF700";
static std::string const kDownArrow = "\uF701";
static std::string const kLeftArrow = "\uF702";
static std::string const kRightArrow = "\uF703";
// these never reach ‘keyDown:’ (tested on 10.5.8)
static std::string const SpecialKeys[] =
{
"^" + kBackwardDelete, "^" + kForwardDelete,
"^" + kUpArrow, "^" + kDownArrow, "^" + kLeftArrow, "^" + kRightArrow,
"^$" + kUpArrow, "^$" + kDownArrow, "^$" + kLeftArrow, "^$" + kRightArrow,
"^~" + kUpArrow, "^~" + kDownArrow, "^~" + kLeftArrow, "^~" + kRightArrow,
"^~$" + kUpArrow, "^~$" + kDownArrow, "^~$" + kLeftArrow, "^~$" + kRightArrow,
};
if(oak::contains(beginof(SpecialKeys), endof(SpecialKeys), eventString))
{
plist::dictionary_t::const_iterator pair = KeyEventContext->find(eventString);
if(pair != KeyEventContext->end())
return [self handleKeyBindingAction:pair->second], YES;
}
return NO;
}