forked from macvim-dev/macvim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MMCoreTextView.m
2236 lines (1916 loc) · 73.1 KB
/
MMCoreTextView.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
/* 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_WIDE 0x80 /* draw wide text */
#define DRAW_COMP 0x100 /* drawing composing char */
#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;
@end
@interface MMCoreTextView (Drawing)
- (NSPoint)pointForRow:(int)row column:(int)column;
- (NSRect)rectFromRow:(int)row1 column:(int)col1
toRow:(int)row2 column:(int)col2;
- (NSSize)textAreaSize;
- (NSData *)optimizeBatchDrawData:(NSData *)data;
- (void)batchDrawData:(NSData *)data;
- (void)drawString:(const UniChar *)chars length:(UniCharCount)length
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)drawInsertionPointAtRow:(int)row column:(int)col shape:(int)shape
fraction:(int)percent color:(int)color;
- (void)drawInvertedRectAtRow:(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;
}
@implementation MMCoreTextView
- (id)initWithFrame:(NSRect)frame
{
if (!(self = [super initWithFrame:frame]))
return nil;
cgBufferDrawEnabled = [[NSUserDefaults standardUserDefaults]
boolForKey:MMBufferedDrawingKey];
cgBufferDrawNeedsUpdateContext = NO;
cgLayerEnabled = NO;
if (!cgBufferDrawEnabled) {
// Buffered draw supercedes the CGLayer renderer, which is deprecated
// and doesn't actually work in 10.14+.
cgLayerEnabled = [[NSUserDefaults standardUserDefaults]
boolForKey:MMUseCGLayerAlwaysKey];
}
cgLayerLock = [NSLock new];
// NOTE: If the default changes to 'NO' then the intialization of
// p_antialias in option.c must change as well.
antialias = YES;
drawData = [[NSMutableArray alloc] init];
fontCache = [[NSMutableArray alloc] init];
[self setFont:[NSFont userFixedPitchFontOfSize:0]];
helper = [[MMTextViewHelper alloc] init];
[helper setTextView:self];
[self registerForDraggedTypes:[NSArray arrayWithObjects:
NSFilenamesPboardType, NSStringPboardType, nil]];
ligatures = NO;
return self;
}
- (void)dealloc
{
[font release]; font = nil;
[fontWide release]; fontWide = nil;
[defaultBackgroundColor release]; defaultBackgroundColor = nil;
[defaultForegroundColor release]; defaultForegroundColor = nil;
[drawData release]; drawData = nil;
[fontCache release]; fontCache = nil;
CGContextRelease(cgContext); cgContext = nil;
[helper setTextView:nil];
[helper release]; helper = nil;
if (glyphs) { free(glyphs); glyphs = NULL; }
if (positions) { free(positions); positions = NULL; }
[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
{
// NOTE: Just remember the new values, the actual resizing is done lazily.
maxRows = rows;
maxColumns = cols;
}
- (void)setDefaultColorsBackground:(NSColor *)bgColor
foreground:(NSColor *)fgColor
{
if (defaultBackgroundColor != bgColor) {
[defaultBackgroundColor release];
defaultBackgroundColor = bgColor ? [bgColor retain] : nil;
}
// 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.)
NSRect rect = { {0, 0}, {0, 0} };
unsigned start = range.location > maxRows ? maxRows : range.location;
unsigned 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} };
unsigned start = range.location > maxColumns ? maxColumns : range.location;
unsigned 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 || [font isEqual:newFont])
return;
double em = round(defaultAdvanceForFont(newFont));
double pt = round([newFont pointSize]);
CTFontDescriptorRef desc = CTFontDescriptorCreateWithNameAndSize((CFStringRef)[newFont fontName], pt);
CTFontRef fontRef = CTFontCreateWithFontDescriptor(desc, pt, NULL);
CFRelease(desc);
[font release];
font = (NSFont*)fontRef;
float cellWidthMultiplier = [[NSUserDefaults standardUserDefaults]
floatForKey:MMCellWidthMultiplierKey];
// 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);
fontDescent = ceil(CTFontGetDescent(fontRef));
[fontCache 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];
} else if (newFont != fontWide) {
// NOTE: No need to set point size etc. since this is taken from the
// regular font when drawing.
[fontWide release];
// Use 'Apple Color Emoji' font for rendering emoji
CGFloat size = [newFont pointSize] > [font pointSize] ? [font pointSize] : [newFont pointSize];
NSFontDescriptor *emojiDesc = [NSFontDescriptor
fontDescriptorWithName:@"Apple Color Emoji" size:size];
NSFontDescriptor *newFontDesc = [newFont fontDescriptor];
NSDictionary *attrs = [NSDictionary
dictionaryWithObject:[NSArray arrayWithObject:newFontDesc]
forKey:NSFontCascadeListAttribute];
NSFontDescriptor *desc =
[emojiDesc fontDescriptorByAddingAttributes:attrs];
fontWide = [[NSFont fontWithDescriptor:desc size:size] retain];
}
}
- (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;
}
- (void)setThinStrokes:(BOOL)state
{
thinStrokes = state;
}
- (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)setFrameSize:(NSSize)newSize {
if (!NSEqualSizes(newSize, self.bounds.size)) {
if (!drawPending && !cgBufferDrawEnabled && drawData.count == 0) {
// When resizing a window, it will invalidate the buffer and cause
// MacVim to draw black until we get the draw commands from Vim and
// we draw them out in drawRect. Use beginGrouping to stop the
// window resize from happening until we get the draw calls.
//
// The updateLayer/cgBufferDrawEnabled path handles this differently
// and don't need this.
[NSAnimationContext beginGrouping];
drawPending = YES;
}
if (cgBufferDrawEnabled) {
cgBufferDrawNeedsUpdateContext = YES;
}
}
[super setFrameSize:newSize];
}
- (void)viewDidChangeBackingProperties {
if (cgBufferDrawEnabled) {
cgBufferDrawNeedsUpdateContext = YES;
}
[super viewDidChangeBackingProperties];
}
- (void)keyDown:(NSEvent *)event
{
[helper keyDown:event];
}
- (void)insertText:(id)string
{
[helper insertText:string];
}
- (void)doCommandBySelector:(SEL)selector
{
[helper doCommandBySelector:selector];
}
- (BOOL)hasMarkedText
{
return [helper hasMarkedText];
}
- (NSRange)markedRange
{
return [helper markedRange];
}
- (NSDictionary *)markedTextAttributes
{
return [helper markedTextAttributes];
}
- (void)setMarkedTextAttributes:(NSDictionary *)attr
{
[helper setMarkedTextAttributes:attr];
}
- (void)setMarkedText:(id)text selectedRange:(NSRange)range
{
[helper setMarkedText:text selectedRange:range];
}
- (void)unmarkText
{
[helper unmarkText];
}
- (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 YES;
}
- (BOOL)acceptsFirstResponder
{
return YES;
}
- (BOOL)isFlipped
{
return NO;
}
- (void)updateCGContext {
if (cgContext) {
CGContextRelease(cgContext);
cgContext = nil;
}
NSRect backingRect = [self convertRectToBacking:self.bounds];
cgContext = CGBitmapContextCreate(NULL, NSWidth(backingRect), NSHeight(backingRect), 8, 0, self.window.colorSpace.CGColorSpace, kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host);
CGContextScaleCTM(cgContext, self.window.backingScaleFactor, self.window.backingScaleFactor);
cgBufferDrawNeedsUpdateContext = NO;
}
- (BOOL)wantsUpdateLayer {
return cgBufferDrawEnabled;
}
- (void)updateLayer {
if (!cgContext) {
[self updateCGContext];
} else if (cgBufferDrawNeedsUpdateContext) {
if ([drawData count] != 0) {
[self updateCGContext];
} else {
// In this case, we don't have a single draw command, meaning that
// Vim hasn't caught up yet and hasn't issued draw commands. We
// don't want to use [NSAnimationContext beginGrouping] as it's
// fragile (we may miss the endGrouping call due to order of
// operation), and also it makes the animation jerky.
// Instead, copy the image to the new context and align it to the
// top left and make sure it doesn't stretch. This makes the
// resizing smooth while Vim tries to catch up in issuing draws.
CGImageRef oldImage = CGBitmapContextCreateImage(cgContext);
[self updateCGContext]; // This will make a new cgContext
CGContextSaveGState(cgContext);
CGContextSetBlendMode(cgContext, kCGBlendModeCopy);
// Filling the background so the edge won't be black.
NSRect newRect = [self bounds];
float r = [defaultBackgroundColor redComponent];
float g = [defaultBackgroundColor greenComponent];
float b = [defaultBackgroundColor blueComponent];
float a = [defaultBackgroundColor alphaComponent];
CGContextSetRGBFillColor(cgContext, r, g, b, a);
CGContextFillRect(cgContext, *(CGRect*)&newRect);
CGContextSetBlendMode(cgContext, kCGBlendModeNormal);
// Copy the old image over to the new image, and make sure to
// respect scaling and remember that CGImage's Y origin is
// bottom-left.
CGFloat scale = self.window.backingScaleFactor;
size_t oldWidth = CGImageGetWidth(oldImage) / scale;
size_t oldHeight = CGImageGetHeight(oldImage) / scale;
CGFloat newHeight = newRect.size.height;
NSRect imageRect = NSMakeRect(0, newHeight - oldHeight, (CGFloat)oldWidth, (CGFloat)oldHeight);
CGContextDrawImage(cgContext, imageRect, oldImage);
CGImageRelease(oldImage);
CGContextRestoreGState(cgContext);
}
}
// Now issue the batched draw commands
if ([drawData count] != 0) {
[NSGraphicsContext saveGraphicsState];
NSGraphicsContext.currentContext = [NSGraphicsContext graphicsContextWithCGContext:cgContext flipped:self.flipped];
id data;
NSEnumerator *e = [drawData objectEnumerator];
while ((data = [e nextObject]))
[self batchDrawData:data];
[drawData removeAllObjects];
[NSGraphicsContext restoreGraphicsState];
}
CGImageRef contentsImage = CGBitmapContextCreateImage(cgContext);
self.layer.contents = (id)contentsImage;
CGImageRelease(contentsImage);
}
- (void)drawRect:(NSRect)rect
{
NSGraphicsContext *context = [NSGraphicsContext currentContext];
[context setShouldAntialias:antialias];
if (cgLayerEnabled && drawData.count == 0) {
// during a live resize, we will have around a stale layer until the
// refresh messages travel back from the vim process. We push the old
// layer in at an offset to get rid of jitter due to lines changing
// position.
[cgLayerLock lock];
CGLayerRef l = [self getCGLayer];
CGSize cgLayerSize = CGLayerGetSize(l);
CGSize frameSize = [self frame].size;
NSRect drawRect = NSMakeRect(
0,
frameSize.height - cgLayerSize.height,
cgLayerSize.width,
cgLayerSize.height);
CGContextRef cgContext = [context graphicsPort];
const NSRect *rects;
long count;
[self getRectsBeingDrawn:&rects count:&count];
int i;
for (i = 0; i < count; i++) {
CGContextSaveGState(cgContext);
CGContextClipToRect(cgContext, rects[i]);
CGContextSetBlendMode(cgContext, kCGBlendModeCopy);
CGContextDrawLayerInRect(cgContext, drawRect, l);
CGContextRestoreGState(cgContext);
}
[cgLayerLock unlock];
} else {
id data;
NSEnumerator *e = [drawData objectEnumerator];
while ((data = [e nextObject]))
[self batchDrawData:data];
[drawData removeAllObjects];
}
}
- (void)performBatchDrawWithData:(NSData *)data
{
if (cgBufferDrawEnabled) {
// We batch up all the commands and actually perform the draw at
// updateLayer. The reason is that right now MacVim has a lot of
// different paths that could change the view size (zoom, user resizing
// from either dragging border or another program, Cmd-+/- to change
// font size, fullscreen, etc). Those different paths don't currently
// have a consistent order of operation of (Vim or MacVim go first), so
// sometimes Vim gets updated and issue a batch draw first, but
// sometimes MacVim gets notified first (e.g. when window is resized).
// If frame size has changed we need to call updateCGContext but we
// can't do it here because of the order of operation issue. That's why
// we wait till updateLayer to do it where everything has already been
// done and settled.
//
// Note: Should probably refactor the different ways window size could
// be changed and unify them instead of the status quo of spaghetti.
[drawData addObject:data];
[self setNeedsDisplay:YES];
} else if (cgLayerEnabled && drawData.count == 0 && [self getCGContext]) {
[cgLayerLock lock];
[self batchDrawData:data];
[cgLayerLock unlock];
} else {
[drawData addObject:data];
[self setNeedsDisplay:YES];
}
if (drawPending) {
[NSAnimationContext endGrouping];
drawPending = NO;
}
}
- (void)setCGLayerEnabled:(BOOL)enabled
{
if (cgContext || cgBufferDrawEnabled)
return;
cgLayerEnabled = enabled;
if (!cgLayerEnabled)
[self releaseCGLayer];
}
- (BOOL)getCGLayerEnabled
{
return cgLayerEnabled;
}
- (void)releaseCGLayer
{
if (cgLayer) {
CGLayerRelease(cgLayer);
cgLayer = nil;
cgLayerContext = nil;
}
}
- (CGLayerRef)getCGLayer
{
NSParameterAssert(cgLayerEnabled);
if (!cgLayer && [self lockFocusIfCanDraw]) {
NSGraphicsContext *context = [NSGraphicsContext currentContext];
NSRect frame = [self frame];
cgLayer = CGLayerCreateWithContext(
[context graphicsPort], frame.size, NULL);
[self unlockFocus];
}
return cgLayer;
}
- (CGContextRef)getCGContext
{
if (cgLayerEnabled) {
if (!cgLayerContext)
cgLayerContext = CGLayerGetContext([self getCGLayer]);
return cgLayerContext;
} else {
return [[NSGraphicsContext currentContext] graphicsPort];
}
}
- (void)setNeedsDisplayCGLayerInRect:(CGRect)rect
{
if (cgLayerEnabled)
[self setNeedsDisplayInRect:rect];
}
- (void)setNeedsDisplayCGLayer:(BOOL)flag
{
if (cgLayerEnabled)
[self setNeedsDisplay:flag];
}
- (NSSize)constrainRows:(int *)rows columns:(int *)cols toSize:(NSSize)size
{
// TODO:
// - Rounding errors may cause size change when there should be none
// - Desired rows/columns shold not be 'too small'
// Constrain the desired size to the given size. Values for the minimum
// rows and columns are taken from Vim.
NSSize desiredSize = [self desiredSize];
int desiredRows = maxRows;
int desiredCols = maxColumns;
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
int right = [ud integerForKey:MMTextInsetRightKey];
int bot = [ud integerForKey:MMTextInsetBottomKey];
if (size.height != desiredSize.height) {
float fh = cellSize.height;
float ih = insetSize.height + bot;
if (fh < 1.0f) fh = 1.0f;
desiredRows = floor((size.height - ih)/fh);
desiredSize.height = fh*desiredRows + ih;
}
if (size.width != desiredSize.width) {
float fw = cellSize.width;
float iw = insetSize.width + right;
if (fw < 1.0f) fw = 1.0f;
desiredCols = floor((size.width - iw)/fw);
desiredSize.width = fw*desiredCols + iw;
}
if (rows) *rows = desiredRows;
if (cols) *cols = desiredCols;
return desiredSize;
}
- (NSSize)desiredSize
{
// Compute the size the text view should be for the entire text area and
// inset area to be visible with the present number of rows and columns.
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
int right = [ud integerForKey:MMTextInsetRightKey];
int bot = [ud integerForKey:MMTextInsetBottomKey];
return NSMakeSize(maxColumns * cellSize.width + insetSize.width + right,
maxRows * cellSize.height + insetSize.height + bot);
}
- (NSSize)minSize
{
// Compute the smallest size the text view is allowed to be.
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
int right = [ud integerForKey:MMTextInsetRightKey];
int bot = [ud integerForKey:MMTextInsetBottomKey];
return NSMakeSize(MMMinColumns * cellSize.width + insetSize.width + right,
MMMinRows * cellSize.height + insetSize.height + bot);
}
- (void)changeFont:(id)sender
{
NSFont *newFont = [sender convertFont:font];
if (newFont) {
NSString *name = [newFont fontName];
unsigned len = [name lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
if (len > 0) {
NSMutableData *data = [NSMutableData data];
float pointSize = [newFont pointSize];
[data appendBytes:&pointSize length:sizeof(float)];
++len; // include NUL byte
[data appendBytes:&len length:sizeof(unsigned)];
[data appendBytes:[name UTF8String] length:len];
[[self vimController] sendMessage:SetFontMsgID data:data];
}
}
}
//
// NOTE: The menu items cut/copy/paste/undo/redo/select all/... must be bound
// to the same actions as in IB otherwise they will not work with dialogs. All
// we do here is forward these actions to the Vim process.
//
- (IBAction)cut:(id)sender
{
[[self windowController] vimMenuItemAction:sender];
}
- (IBAction)copy:(id)sender
{
[[self windowController] vimMenuItemAction:sender];
}
- (IBAction)paste:(id)sender
{
[[self windowController] vimMenuItemAction:sender];
}
- (IBAction)undo:(id)sender
{
[[self windowController] vimMenuItemAction:sender];
}
- (IBAction)redo:(id)sender
{
[[self windowController] vimMenuItemAction:sender];
}
- (IBAction)selectAll:(id)sender
{
[[self windowController] vimMenuItemAction:sender];
}
- (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column
{
point.y = [self bounds].size.height - point.y;
NSPoint origin = { insetSize.width, insetSize.height };
if (!(cellSize.width > 0 && cellSize.height > 0))
return NO;
if (row) *row = floor((point.y-origin.y-1) / cellSize.height);
if (column) *column = floor((point.x-origin.x-1) / cellSize.width);
//ASLogDebug(@"point=%@ row=%d col=%d",
// NSStringFromPoint(point), *row, *column);
return YES;
}
- (NSRect)rectForRow:(int)row column:(int)col numRows:(int)nr
numColumns:(int)nc
{