forked from macvim-dev/macvim
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMMCoreTextView.m
More file actions
2651 lines (2304 loc) · 101 KB
/
MMCoreTextView.m
File metadata and controls
2651 lines (2304 loc) · 101 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
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
/* vi:set ts=8 sts=4 sw=4 ft=objc:
*
* VIM - Vi IMproved by Bram Moolenaar
* MacVim GUI port by Bjorn Winckler
*
* Do ":help uganda" in Vim to read copying and usage conditions.
* Do ":help credits" in Vim to see a list of people who contributed.
* See README.txt for an overview of the Vim source code.
*/
/*
* MMCoreTextView
*
* Dispatches keyboard and mouse input to the backend. Handles drag-n-drop of
* files onto window. The rendering is done using CoreText.
*
* The text view area consists of two parts:
* 1. The text area - this is where text is rendered; the size is governed by
* the current number of rows and columns.
* 2. The inset area - this is a border around the text area; the size is
* governed by the user defaults MMTextInset[Left|Right|Top|Bottom].
*
* The current size of the text view frame does not always match the desired
* area, i.e. the area determined by the number of rows, columns plus text
* inset. This distinction is particularly important when the view is being
* resized.
*/
#import "Miscellaneous.h"
#import "MMAppController.h"
#import "MMCoreTextView.h"
#import "MMTextViewHelper.h"
#import "MMVimController.h"
#import "MMWindowController.h"
// TODO: What does DRAW_TRANSP flag do? If the background isn't drawn when
// this flag is set, then sometimes the character after the cursor becomes
// blank. Everything seems to work fine by just ignoring this flag.
#define DRAW_TRANSP 0x01 // draw with transparent bg
#define DRAW_BOLD 0x02 // draw bold text
#define DRAW_UNDERL 0x04 // draw underline text
#define DRAW_UNDERC 0x08 // draw undercurl text
#define DRAW_ITALIC 0x10 // draw italic text
#define DRAW_CURSOR 0x20
#define DRAW_STRIKE 0x40 // draw strikethrough text
#define DRAW_UNDERDOUBLE 0x80 // draw double underline
#define DRAW_UNDERDOTTED 0x100 // draw dotted underline
#define DRAW_UNDERDASHED 0x200 // draw dashed underline
#define DRAW_WIDE 0x1000 // (MacVim only) draw wide text
#define DRAW_COMP 0x2000 // (MacVim only) drawing composing char
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_13
typedef NSString * NSAttributedStringKey;
#endif // MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_13
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_8
#define kCTFontOrientationDefault kCTFontDefaultOrientation
#endif // MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_8
extern void CGContextSetFontSmoothingStyle(CGContextRef, int);
extern int CGContextGetFontSmoothingStyle(CGContextRef);
#define fontSmoothingStyleLight (2 << 3)
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_7
static void
CTFontDrawGlyphs(CTFontRef fontRef, const CGGlyph glyphs[],
const CGPoint positions[], UniCharCount count,
CGContextRef context)
{
CGFontRef cgFontRef = CTFontCopyGraphicsFont(fontRef, NULL);
CGContextSetFont(context, cgFontRef);
CGContextShowGlyphsAtPositions(context, glyphs, positions, count);
CGFontRelease(cgFontRef);
}
#endif // MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_7
@interface MMCoreTextView (Private)
- (MMWindowController *)windowController;
- (MMVimController *)vimController;
- (NSFont *)fontVariantForTextFlags:(int)textFlags;
- (CTLineRef)lineForCharacterString:(NSString *)string
textFlags:(int)flags;
- (void)setCmdlineRow:(int)row;
@end
@interface MMCoreTextView (Drawing)
- (NSPoint)pointForRow:(int)row column:(int)column;
- (NSSize)textAreaSize;
- (void)batchDrawData:(NSData *)data;
- (void)setString:(NSString *)string
atRow:(int)row column:(int)col cells:(int)cells
withFlags:(int)flags foregroundColor:(int)fg
backgroundColor:(int)bg specialColor:(int)sp;
- (void)deleteLinesFromRow:(int)row lineCount:(int)count
scrollBottom:(int)bottom left:(int)left right:(int)right
color:(int)color;
- (void)insertLinesAtRow:(int)row lineCount:(int)count
scrollBottom:(int)bottom left:(int)left right:(int)right
color:(int)color;
- (void)clearBlockFromRow:(int)row1 column:(int)col1 toRow:(int)row2
column:(int)col2 color:(int)color;
- (void)clearAll;
- (void)setInsertionPointAtRow:(int)row column:(int)col shape:(int)shape
fraction:(int)percent color:(int)color;
- (void)invertBlockFromRow:(int)row column:(int)col numRows:(int)nrows
numColumns:(int)ncols;
@end
static float
defaultLineHeightForFont(NSFont *font)
{
// HACK: -[NSFont defaultLineHeightForFont] is deprecated but since the
// CoreText renderer does not use NSLayoutManager we create one
// temporarily.
NSLayoutManager *lm = [[NSLayoutManager alloc] init];
float height = [lm defaultLineHeightForFont:font];
[lm release];
return height;
}
static double
defaultAdvanceForFont(NSFont *font)
{
// NOTE: Previously we used CTFontGetAdvancesForGlyphs() to get the advance
// for 'm' but this sometimes returned advances that were too small making
// the font spacing look too tight.
// Instead use the same method to query the width of 'm' as MMTextStorage
// uses to make things consistent across renderers.
NSDictionary *a = [NSDictionary dictionaryWithObject:font
forKey:NSFontAttributeName];
return [@"m" sizeWithAttributes:a].width;
}
typedef struct {
unsigned color;
int shape;
int fraction;
} GridCellInsertionPoint;
/// A cell in the grid. Each cell represents a grapheme, which could consist of one or more
/// characters. If textFlags contains DRAW_WIDE, then it's a 'wide' cell, which means a grapheme
/// takes up two cell spaces to render (e.g. emoji or CJK characters). When this is the case, the
/// next cell in the grid should be ignored and skipped.
typedef struct {
// Note: All objects should be weak references.
// Fields are grouped by draw order.
BOOL inverted;
// 1. Background
unsigned bg;
// 2. Sign
NSImage* sign;
// 3. Insertion point
GridCellInsertionPoint insertionPoint;
// 4. Text
unsigned fg;
unsigned sp;
int textFlags;
NSString* string; ///< Owned by characterStrings. Length would be >1 if there are composing chars.
} GridCell;
typedef struct {
GridCell *cells;
int rows;
int cols;
} Grid;
static GridCell* grid_cell(Grid *grid, int row, int col) {
return grid->cells + row * grid->cols + col;
}
// Returns a static cell if row or col is out of bounds. Draw commands can point
// out of bounds if -setMaxRows:columns: is called while Vim is still drawing at
// a different size, which has been observed when exiting non-native fullscreen
// with `:set nofu`. If that gets fixed, then delete this workaround.
static GridCell* grid_cell_safe(Grid *grid, int row, int col) {
if (row >= grid->rows || col >= grid->cols) {
static GridCell scratch_cell = {};
return &scratch_cell;
}
return grid_cell(grid, row, col);
}
static void grid_resize(Grid *grid, int rows, int cols) {
if (rows == grid->rows && cols == grid->cols)
return;
if (cols == grid->cols && grid->cells != NULL) {
// If only the number of rows is changing, resize and zero out new rows.
size_t oldSize = grid->rows * grid->cols;
size_t newSize = rows * cols;
grid->cells = realloc(grid->cells, newSize * sizeof(GridCell));
if (newSize > oldSize)
bzero(grid->cells + oldSize, (newSize - oldSize) * sizeof(GridCell));
} else {
// Otherwise, allocate a new buffer.
GridCell *oldCells = grid->cells;
grid->cells = calloc(rows * cols, sizeof(GridCell));
if (oldCells) {
for (int r = 1; r < MIN(grid->rows, rows); r++)
memcpy(grid->cells + cols * r, oldCells + grid->cols * r, MIN(grid->cols, cols) * sizeof(GridCell));
free(oldCells);
}
}
grid->rows = rows;
grid->cols = cols;
}
static void grid_free(Grid *grid) {
if (grid->cells == NULL)
return;
free(grid->cells);
grid->cells = NULL;
}
@implementation MMCoreTextView {
Grid grid;
BOOL alignCmdLineToBottom; ///< Whether to pin the Vim command-line to the bottom of the window
int cmdlineRow; ///< Row number (0-indexed) where the cmdline starts. Used for pinning it to the bottom if desired.
/// Number of rows to expand when redrawing to make sure we don't clip tall
/// characters whose glyphs extend beyond the bottom/top of the cell.
///
/// Note: This is a short-term hacky solution as it permanently increases
/// the number of rows to expand every time we redraw. Eventually we should
/// calculate each line's glyphs' bounds before issuing a redraw and use
/// that to determine the accurate redraw bounds instead. Currently we
/// calculate the glyph run too late (inside the draw call itself).
unsigned int redrawExpandRows;
}
- (instancetype)initWithFrame:(NSRect)frame
{
if (!(self = [super initWithFrame:frame]))
return nil;
forceRefreshFont = NO;
self.wantsLayer = YES;
// NOTE: If the default changes to 'NO' then the intialization of
// p_antialias in option.c must change as well.
antialias = YES;
[self setFont:[NSFont userFixedPitchFontOfSize:0]];
fontVariants = [[NSMutableDictionary alloc] init];
characterStrings = [[NSMutableSet alloc] init];
characterLines = [[NSMutableDictionary alloc] init];
helper = [[MMTextViewHelper alloc] init];
[helper setTextView:self];
[self registerForDraggedTypes:@[getPasteboardFilenamesType(),
NSPasteboardTypeString]];
ligatures = NO;
alignCmdLineToBottom = NO; // this would be updated to the user preferences later
cmdlineRow = -1; // this would be updated by Vim
redrawExpandRows = 0; // start at 0, until we see a tall character. and then we expand it.
return self;
}
- (void)dealloc
{
[font release]; font = nil;
[fontWide release]; fontWide = nil;
[defaultBackgroundColor release]; defaultBackgroundColor = nil;
[defaultForegroundColor release]; defaultForegroundColor = nil;
[fontVariants release]; fontVariants = nil;
[characterStrings release]; characterStrings = nil;
[characterLines release]; characterLines = nil;
[helper setTextView:nil];
[helper release]; helper = nil;
grid_free(&grid);
[super dealloc];
}
- (int)maxRows
{
return maxRows;
}
- (int)maxColumns
{
return maxColumns;
}
- (void)getMaxRows:(int*)rows columns:(int*)cols
{
if (rows) *rows = maxRows;
if (cols) *cols = maxColumns;
}
- (void)setMaxRows:(int)rows columns:(int)cols
{
grid_resize(&grid, rows, cols);
maxRows = rows;
maxColumns = cols;
pendingMaxRows = rows;
pendingMaxColumns = cols;
}
- (int)pendingMaxRows
{
return pendingMaxRows;
}
- (int)pendingMaxColumns
{
return pendingMaxColumns;
}
- (void)setPendingMaxRows:(int)rows columns:(int)cols
{
pendingMaxRows = rows;
pendingMaxColumns = cols;
}
- (void)setDefaultColorsBackground:(NSColor *)bgColor
foreground:(NSColor *)fgColor
{
if (defaultBackgroundColor != bgColor) {
[defaultBackgroundColor release];
defaultBackgroundColor = bgColor ? [bgColor retain] : nil;
self.needsDisplay = YES;
}
// NOTE: The default foreground color isn't actually used for anything, but
// other class instances might want to be able to access it so it is stored
// here.
if (defaultForegroundColor != fgColor) {
[defaultForegroundColor release];
defaultForegroundColor = fgColor ? [fgColor retain] : nil;
}
[self setNeedsDisplay:YES];
}
- (NSColor *)defaultBackgroundColor
{
return defaultBackgroundColor;
}
- (NSColor *)defaultForegroundColor
{
return defaultForegroundColor;
}
- (void)setTextContainerInset:(NSSize)size
{
insetSize = size;
}
- (NSRect)rectForRowsInRange:(NSRange)range
{
// Compute rect whose vertical dimensions cover the rows in the given
// range.
// NOTE: The rect should be in _flipped_ coordinates and the first row must
// include the top inset as well. (This method is only used to place the
// scrollbars inside MMVimView.)
// Note: This doesn't really take alignCmdLineToBottom into account right now.
NSRect rect = { {0, 0}, {0, 0} };
NSUInteger start = range.location > maxRows ? maxRows : range.location;
NSUInteger length = range.length;
if (start + length > maxRows)
length = maxRows - start;
if (start > 0) {
rect.origin.y = cellSize.height * start + insetSize.height;
rect.size.height = cellSize.height * length;
} else {
// Include top inset
rect.origin.y = 0;
rect.size.height = cellSize.height * length + insetSize.height;
}
return rect;
}
- (NSRect)rectForColumnsInRange:(NSRange)range
{
// Compute rect whose horizontal dimensions cover the columns in the given
// range.
// NOTE: The first column must include the left inset. (This method is
// only used to place the scrollbars inside MMVimView.)
NSRect rect = { {0, 0}, {0, 0} };
NSUInteger start = range.location > maxColumns ? maxColumns : range.location;
NSUInteger length = range.length;
if (start+length > maxColumns)
length = maxColumns - start;
if (start > 0) {
rect.origin.x = cellSize.width * start + insetSize.width;
rect.size.width = cellSize.width * length;
} else {
// Include left inset
rect.origin.x = 0;
rect.size.width = cellSize.width * length + insetSize.width;
}
return rect;
}
- (void)setFont:(NSFont *)newFont
{
if (!newFont) {
ASLogInfo(@"Trying to set null font");
return;
}
if (!forceRefreshFont) {
if ([font isEqual:newFont])
return;
}
forceRefreshFont = NO;
const double em = round(defaultAdvanceForFont(newFont));
const float cellWidthMultiplier = [[NSUserDefaults standardUserDefaults]
floatForKey:MMCellWidthMultiplierKey];
// Some fonts have non-standard line heights, and historically MacVim has
// chosen to ignore it. Provide the option for the user to choose whether to
// use the font's line height. If not preserving, will create a new font
// from scratch with just name and pt size, which will disard the line
// height information.
//
// Defaults to the new behavior (preserveLineHeight==true) because it's
// simpler and respects the font's design more.
//
// Note: this behavior is somewhat inconsistent across editors and
// terminals. Xcode, for example, seems to be equivalent to
// (preserveLineHeight==true), but other editors/terminals behave
// differently. Xcode respecting the line height is partially the motivation
// for setting that as the default.
const BOOL preserveLineHeight = [[NSUserDefaults standardUserDefaults]
boolForKey:MMFontPreserveLineSpacingKey];
[font release];
if (!preserveLineHeight) {
double pt = round([newFont pointSize]);
CTFontDescriptorRef desc = CTFontDescriptorCreateWithNameAndSize((CFStringRef)[newFont fontName], pt);
CTFontRef fontRef = CTFontCreateWithFontDescriptor(desc, pt, NULL);
CFRelease(desc);
if (!fontRef) {
ASLogInfo(@"CTFontCreateWithFontDescriptor failed (preserveLineHeight == false, fontName: %@), pt: %f", [newFont fontName], pt);
}
font = (NSFont*)fontRef;
} else {
font = [newFont retain];
}
fontDescent = CTFontGetDescent((CTFontRef)font);
fontAscent = CTFontGetAscent((CTFontRef)font);
fontXHeight = CTFontGetXHeight((CTFontRef)font);
// NOTE! Even though NSFontFixedAdvanceAttribute is a float, it will
// only render at integer sizes. Hence, we restrict the cell width to
// an integer here, otherwise the window width and the actual text
// width will not match.
cellSize.width = columnspace + ceil(em * cellWidthMultiplier);
cellSize.height = linespace + defaultLineHeightForFont(font);
[self clearAll];
[fontVariants removeAllObjects];
[characterStrings removeAllObjects];
[characterLines removeAllObjects];
}
- (void)setWideFont:(NSFont *)newFont
{
if (!newFont) {
// Use the normal font as the wide font (note that the normal font may
// very well include wide characters.)
if (font) {
[self setWideFont:font];
return;
}
} else if (newFont != fontWide) {
[fontWide release];
fontWide = [newFont retain];
}
[self clearAll];
[fontVariants removeAllObjects];
[characterStrings removeAllObjects];
[characterLines removeAllObjects];
}
- (void)refreshFonts
{
// Mark force refresh, so that we won't try to use the cached font later.
forceRefreshFont = YES;
// Go through the standard path of updating fonts by passing the current
// font in. This lets Vim itself knows about the font change and initiates
// the resizing (depends on guioption-k) and redraws.
[self changeFont:NSFontManager.sharedFontManager];
}
- (NSFont *)font
{
return font;
}
- (NSFont *)fontWide
{
return fontWide;
}
- (NSSize)cellSize
{
return cellSize;
}
- (void)setLinespace:(float)newLinespace
{
linespace = newLinespace;
// NOTE: The linespace is added to the cell height in order for a multiline
// selection not to have white (background color) gaps between lines. Also
// this simplifies the code a lot because there is no need to check the
// linespace when calculating the size of the text view etc. When the
// linespace is non-zero the baseline will be adjusted as well; check
// MMTypesetter.
cellSize.height = linespace + defaultLineHeightForFont(font);
}
- (void)setColumnspace:(float)newColumnspace
{
columnspace = newColumnspace;
double em = round(defaultAdvanceForFont(font));
float cellWidthMultiplier = [[NSUserDefaults standardUserDefaults]
floatForKey:MMCellWidthMultiplierKey];
cellSize.width = columnspace + ceil(em * cellWidthMultiplier);
}
- (void)deleteSign:(NSString *)signName
{
[helper deleteImage:signName];
}
- (void)setShouldDrawInsertionPoint:(BOOL)on
{
}
- (void)setPreEditRow:(int)row column:(int)col
{
[helper setPreEditRow:row column:col];
}
- (void)setMouseShape:(int)shape
{
[helper setMouseShape:shape];
}
- (void)setAntialias:(BOOL)state
{
antialias = state;
}
- (void)setLigatures:(BOOL)state
{
ligatures = state;
[characterLines removeAllObjects];
}
- (void)setThinStrokes:(BOOL)state
{
thinStrokes = state;
}
/// Update the cmdline row number from Vim's state and cmdline alignment user settings.
- (void)updateCmdlineRow
{
[self setCmdlineRow: [[[self vimController] objectForVimStateKey:@"cmdline_row"] intValue]];
}
/// Shows the dictionary looup / definition of the provided text at row/col.
/// This is usually invoked from Vimscript via the showdefinition() function.
- (void)showDefinitionForCustomString:(NSString *)text row:(int)row col:(int)col
{
const NSRect cursorRect = [self rectForRow:row column:col numRows:1 numColumns:1];
NSPoint baselinePt = cursorRect.origin;
baselinePt.y += fontDescent;
NSAttributedString *attrText = [[[NSAttributedString alloc] initWithString:text
attributes:@{NSFontAttributeName: font}
] autorelease];
[self showDefinitionForAttributedString:attrText atPoint:baselinePt];
}
- (void)setImControl:(BOOL)enable
{
[helper setImControl:enable];
}
- (void)activateIm:(BOOL)enable
{
[helper activateIm:enable];
}
- (void)checkImState
{
[helper checkImState];
}
- (BOOL)_wantsKeyDownForEvent:(id)event
{
// HACK! This is an undocumented method which is called from within
// -[NSWindow sendEvent] (and perhaps in other places as well) when the
// user presses e.g. Ctrl-Tab or Ctrl-Esc . Returning YES here effectively
// disables the Cocoa "key view loop" (which is undesirable). It may have
// other side-effects, but we really _do_ want to process all key down
// events so it seems safe to always return YES.
return YES;
}
- (void)keyDown:(NSEvent *)event
{
[helper keyDown:event];
}
- (void)insertText:(id)string replacementRange:(NSRange)replacementRange
{
// We are not currently replacementRange right now.
[helper insertText:string];
}
- (void)doCommandBySelector:(SEL)selector
{
[helper doCommandBySelector:selector];
}
- (void)scrollWheel:(NSEvent *)event
{
[helper scrollWheel:event];
}
- (void)mouseDown:(NSEvent *)event
{
[helper mouseDown:event];
}
- (void)rightMouseDown:(NSEvent *)event
{
[helper mouseDown:event];
}
- (void)otherMouseDown:(NSEvent *)event
{
[helper mouseDown:event];
}
- (void)mouseUp:(NSEvent *)event
{
[helper mouseUp:event];
}
- (void)rightMouseUp:(NSEvent *)event
{
[helper mouseUp:event];
}
- (void)otherMouseUp:(NSEvent *)event
{
[helper mouseUp:event];
}
- (void)mouseDragged:(NSEvent *)event
{
[helper mouseDragged:event];
}
- (void)rightMouseDragged:(NSEvent *)event
{
[helper mouseDragged:event];
}
- (void)otherMouseDragged:(NSEvent *)event
{
[helper mouseDragged:event];
}
- (void)mouseMoved:(NSEvent *)event
{
[helper mouseMoved:event];
}
- (void)swipeWithEvent:(NSEvent *)event
{
[helper swipeWithEvent:event];
}
- (void)pressureChangeWithEvent:(NSEvent *)event
{
[helper pressureChangeWithEvent:event];
}
- (NSMenu*)menuForEvent:(NSEvent *)event
{
// HACK! Return nil to disable default popup menus (Vim provides its own).
// Called when user Ctrl-clicks in the view (this is already handled in
// rightMouseDown:).
return nil;
}
- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
{
return [helper performDragOperation:sender];
}
- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
{
return [helper draggingEntered:sender];
}
- (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
{
return [helper draggingUpdated:sender];
}
- (BOOL)mouseDownCanMoveWindow
{
return NO;
}
- (BOOL)isOpaque
{
return self.layer == nil || self.defaultBackgroundColor.alphaComponent == 1;
}
- (BOOL)acceptsFirstResponder
{
return YES;
}
- (BOOL)isFlipped
{
return NO;
}
- (void)setNeedsDisplayFromRow:(int)row column:(int)col toRow:(int)row2
column:(int)col2 {
row -= redrawExpandRows;
row2 += redrawExpandRows;
[self setNeedsDisplayInRect:[self rectForRow:row column:0 numRows:row2-row+1 numColumns:maxColumns]];
}
- (void)drawRect:(NSRect)rect
{
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
const BOOL clipTextToRow = [ud boolForKey:MMRendererClipToRowKey]; // Specify whether to clip tall characters by the row boundary.
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_VERSION_14_0
// On macOS 14+ by default views don't clip their content, which is good as it allows tall texts
// on first line to be drawn fully without getting clipped. However, in this case we should make
// sure the background color fill is clipped properly, as otherwise it will interfere with
// non-native fullscreen's background color setting.
const BOOL clipBackground = !self.clipsToBounds;
#else
const BOOL clipBackground = NO;
#endif
NSGraphicsContext *context = [NSGraphicsContext currentContext];
#if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_10
CGContextRef ctx = context.CGContext;
#else
CGContextRef ctx = [context graphicsPort];
#endif
[context setShouldAntialias:antialias];
{
CGColorSpaceRef colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
if (colorSpace) {
CGContextSetFillColorSpace(ctx, colorSpace);
CGColorSpaceRelease(colorSpace);
} else {
ASLogInfo(@"Could not create sRGB color space");
}
}
CGContextSetTextMatrix(ctx, CGAffineTransformIdentity);
CGContextSetTextDrawingMode(ctx, kCGTextFill);
CGContextSetFontSize(ctx, [font pointSize]);
CGContextSetShouldSmoothFonts(ctx, YES);
CGContextSetBlendMode(ctx, kCGBlendModeCopy);
int originalSmoothingStyle = 0;
if (thinStrokes) {
originalSmoothingStyle = CGContextGetFontSmoothingStyle(ctx);
CGContextSetFontSmoothingStyle(ctx, fontSmoothingStyleLight);
}
const unsigned defaultBg = defaultBackgroundColor.argbInt;
CGContextSetFillColor(ctx, COMPONENTS(defaultBg));
if (clipBackground) {
CGContextSaveGState(ctx);
CGContextClipToRect(ctx, self.bounds);
}
CGContextFillRect(ctx, rect);
if (clipBackground) {
CGContextRestoreGState(ctx);
}
// Function to draw all rows
void (^drawAllRows)(void (^)(CGContextRef,CGRect,int)) = ^(void (^drawFunc)(CGContextRef,CGRect,int)){
for (int r = 0; r < grid.rows; r++) {
const CGRect rowRect = [self rectForRow:(int)r
column:0
numRows:1
numColumns:grid.cols];
// Expand the clip rect to include some above/below rows in case we have tall characters.
const CGRect rowExpandedRect = [self rectForRow:(int)(r-redrawExpandRows)
column:0
numRows:(1+redrawExpandRows*2)
numColumns:grid.cols];
const CGRect rowClipRect = CGRectIntersection(rowExpandedRect, rect);
if (CGRectIsNull(rowClipRect))
continue;
CGContextSaveGState(ctx);
if (clipTextToRow)
CGContextClipToRect(ctx, rowClipRect);
drawFunc(ctx, rowRect, (int)r);
CGContextRestoreGState(ctx);
}
};
// Function to draw a row of background colors, signs, and cursor rect. These should go below
// any text.
void (^drawBackgroundAndCursorFunc)(CGContextRef,CGRect,int) = ^(CGContextRef ctx, CGRect rowRect, int r){
for (int c = 0; c < grid.cols; c++) {
GridCell cell = *grid_cell(&grid, r, c);
CGRect cellRect = {{rowRect.origin.x + cellSize.width * c, rowRect.origin.y}, cellSize};
if (cell.textFlags & DRAW_WIDE)
cellRect.size.width *= 2;
if (cell.inverted) {
cell.bg ^= 0xFFFFFF;
cell.fg ^= 0xFFFFFF;
cell.sp ^= 0xFFFFFF;
}
// Fill background
if (cell.bg != defaultBg && ALPHA(cell.bg) > 0) {
CGRect fillCellRect = cellRect;
if (c == grid.cols - 1 || (c == grid.cols - 2 && (cell.textFlags & DRAW_WIDE))) {
// Fill a little extra to the right if this is the last
// column, and the frame size isn't exactly the same size
// as the grid (due to smooth resizing, etc). This makes it
// look less ugly and more consisten. See rectForRow:'s
// implementation for extra comments.
CGFloat extraWidth = rowRect.origin.x + rowRect.size.width - (cellRect.size.width + cellRect.origin.x);
fillCellRect.size.width += extraWidth;
}
CGContextSetFillColor(ctx, COMPONENTS(cell.bg));
CGContextFillRect(ctx, fillCellRect);
}
// Handle signs
if (cell.sign) {
CGRect signRect = cellRect;
signRect.size.width *= 2;
[cell.sign drawInRect:signRect
fromRect:(NSRect){{0, 0}, cell.sign.size}
operation:(cell.inverted ? NSCompositingOperationDifference : NSCompositingOperationSourceOver)
fraction:1.0];
}
// Insertion point (cursor)
if (cell.insertionPoint.color && cell.insertionPoint.fraction) {
float frac = cell.insertionPoint.fraction / 100.0;
NSRect rect = cellRect;
if (MMInsertionPointHorizontal == cell.insertionPoint.shape) {
rect.size.height = cellSize.height * frac;
} else if (MMInsertionPointVertical == cell.insertionPoint.shape) {
rect.size.width = cellSize.width * frac;
} else if (MMInsertionPointVerticalRight == cell.insertionPoint.shape) {
rect.size.width = cellSize.width * frac;
rect.origin.x += cellRect.size.width - rect.size.width;
}
rect = [self backingAlignedRect:rect options:NSAlignAllEdgesInward];
[[NSColor colorWithArgbInt:cell.insertionPoint.color] set];
if (MMInsertionPointHollow == cell.insertionPoint.shape) {
[NSBezierPath strokeRect:NSInsetRect(rect, 0.5, 0.5)];
} else {
NSRectFill(rect);
}
}
}
};
// Function to draw a row of text with their corresponding text styles.
void (^drawTextFunc)(CGContextRef,CGRect,int) = ^(CGContextRef ctx, CGRect rowRect, int r){
__block NSMutableString *lineString = nil;
__block CGFloat lineStringStart = 0;
__block CFRange lineStringRange = {};
__block GridCell lastStringCell = {};
void (^flushLineString)() = ^{
// This function flushes the current pending line out to be rendered. When ligature is
// enabled it could be quite long. Otherwise, lineString would be just one cell/grapheme. Note
// that even one cell can have lineString.length > 1 and also multiple glyphs due to
// composing characters (limited by Vim's 'maxcombine').
if (!lineString.length)
return;
size_t cellOffsetByIndex[lineString.length];
for (int i = 0, stringIndex = 0; i < (int)lineStringRange.length; i++) {
GridCell cell = *grid_cell(&grid, r, (int)lineStringRange.location + i);
size_t cell_length = cell.string.length;
for (size_t j = 0; j < cell_length; j++) {
cellOffsetByIndex[stringIndex++] = i;
}
if (cell.textFlags & DRAW_WIDE)
i++;
}
CGContextSetFillColor(ctx, COMPONENTS(lastStringCell.fg));
CGContextSetTextPosition(ctx, lineStringStart, rowRect.origin.y + fontDescent);
CGContextSetBlendMode(ctx, kCGBlendModeNormal);
const NSUInteger lineStringLength = lineString.length;
CTLineRef line = [self lineForCharacterString:lineString textFlags:lastStringCell.textFlags];
NSArray* glyphRuns = (NSArray*)CTLineGetGlyphRuns(line);
if ([glyphRuns count] == 0) {
ASLogDebug(@"CTLineGetGlyphRuns no glyphs for: %@", lineString);
}
CGSize accumAdvance = CGSizeZero; // Accumulated advance for the currently cell's glyphs (we can get more than one glyph when we have composing chars)
CGPoint expectedGlyphPosition = CGPointZero; // The expected layout glyph position produced by CTLine
size_t curCell = -1; // The current cell offset within lineStrangeRange
for (id obj in glyphRuns) {
CTRunRef run = (CTRunRef)obj;
CFIndex glyphCount = CTRunGetGlyphCount(run);
CTFontRef runFont = CFDictionaryGetValue(CTRunGetAttributes(run), kCTFontAttributeName);
if (!runFont) {
ASLogDebug(@"Null font for rendering. glyphCount: %ld", (long)glyphCount);
}
CGPoint positions[glyphCount];
CFIndex indices_storage[glyphCount];
const CFIndex* indices = NULL;
if ((indices = CTRunGetStringIndicesPtr(run)) == NULL) {
CTRunGetStringIndices(run, CFRangeMake(0, 0), indices_storage);
indices = indices_storage;
}
const CGGlyph* glyphs = NULL;
CGGlyph glyphs_storage[glyphCount];
if ((glyphs = CTRunGetGlyphsPtr(run)) == NULL) {
CTRunGetGlyphs(run, CFRangeMake(0, 0), glyphs_storage);
glyphs = glyphs_storage;
}
const CGSize* advances = NULL;
CGSize advances_storage[glyphCount];
if ((advances = CTRunGetAdvancesPtr(run)) == NULL) {
CTRunGetAdvances(run, CFRangeMake(0, 0), advances_storage);
advances = advances_storage;
}
const CGPoint* layoutPositions = CTRunGetPositionsPtr(run);
CGPoint layoutPositions_storage[glyphCount];
if (layoutPositions == NULL) {
CTRunGetPositions(run, CFRangeMake(0, 0), layoutPositions_storage);
layoutPositions = layoutPositions_storage;
}