-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
iTermTextDrawingHelper.m
2881 lines (2547 loc) · 128 KB
/
iTermTextDrawingHelper.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
//
// iTermTextDrawingHelper.m
// iTerm2
//
// Created by George Nachman on 3/9/15.
//
//
#import "iTermTextDrawingHelper.h"
#import "charmaps.h"
#import "CVector.h"
#import "DebugLogging.h"
#import "iTermAdvancedSettingsModel.h"
#import "iTermBackgroundColorRun.h"
#import "iTermBoxDrawingBezierCurveFactory.h"
#import "iTermColorMap.h"
#import "iTermController.h"
#import "iTermFindCursorView.h"
#import "iTermImageInfo.h"
#import "iTermIndicatorsHelper.h"
#import "iTermMutableAttributedStringBuilder.h"
#import "iTermPreciseTimer.h"
#import "iTermSelection.h"
#import "iTermTextExtractor.h"
#import "iTermTimestampDrawHelper.h"
#import "MovingAverage.h"
#import "NSArray+iTerm.h"
#import "NSColor+iTerm.h"
#import "NSDictionary+iTerm.h"
#import "NSMutableAttributedString+iTerm.h"
#import "NSStringITerm.h"
#import "PTYFontInfo.h"
#import "RegexKitLite.h"
#import "VT100ScreenMark.h"
#import "VT100Terminal.h" // TODO: Remove this dependency
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
// I couldn't get masking to work with fastpath, so for now just use the slow path for underlined
// text (which should be rare, and hopefully renders just like the fastpath).
#define ENABLE_FASTPATH_UNDERLINES 0
static const int kBadgeMargin = 4;
extern void CGContextSetFontSmoothingStyle(CGContextRef, int);
extern int CGContextGetFontSmoothingStyle(CGContextRef);
BOOL CheckFindMatchAtIndex(NSData *findMatches, int index) {
int theIndex = index / 8;
int mask = 1 << (index & 7);
const char *matchBytes = findMatches.bytes;
return !!(theIndex < [findMatches length] && (matchBytes[theIndex] & mask));
}
@interface iTermTextDrawingHelper() <iTermCursorDelegate>
@end
// IMPORTANT: If you add a field here also update the comparison function
// shouldSegmentWithAttributes:imageAttributes:previousAttributes:previousImageAttributes:combinedAttributesChanged:
typedef struct {
BOOL initialized;
BOOL shouldAntiAlias;
NSColor *foregroundColor;
BOOL boxDrawing;
NSFont *font;
BOOL bold;
BOOL fakeBold;
BOOL fakeItalic;
BOOL underline;
BOOL isURL;
NSInteger ligatureLevel;
BOOL drawable;
} iTermCharacterAttributes;
enum {
TIMER_TOTAL_DRAW_RECT,
TIMER_CONSTRUCT_BACKGROUND_RUNS,
TIMER_DRAW_BACKGROUND,
TIMER_STAT_CONSTRUCTION,
TIMER_STAT_BUILD_MUTABLE_ATTRIBUTED_STRING,
TIMER_ATTRS_FOR_CHAR,
TIMER_SHOULD_SEGMENT,
TIMER_ADVANCES,
TIMER_COMBINE_ATTRIBUTES,
TIMER_UPDATE_BUILDER,
TIMER_STAT_DRAW,
TIMER_BETWEEN_CALLS_TO_DRAW_RECT,
TIMER_STAT_MAX
};
static NSString *const iTermAntiAliasAttribute = @"iTermAntiAliasAttribute";
static NSString *const iTermBoldAttribute = @"iTermBoldAttribute";
static NSString *const iTermFakeBoldAttribute = @"iTermFakeBoldAttribute";
static NSString *const iTermFakeItalicAttribute = @"iTermFakeItalicAttribute";
static NSString *const iTermImageCodeAttribute = @"iTermImageCodeAttribute";
static NSString *const iTermImageColumnAttribute = @"iTermImageColumnAttribute";
static NSString *const iTermImageLineAttribute = @"iTermImageLineAttribute";
static NSString *const iTermImageDisplayColumnAttribute = @"iTermImageDisplayColumnAttribute";
static NSString *const iTermIsBoxDrawingAttribute = @"iTermIsBoxDrawingAttribute";
static NSString *const iTermUnderlineLengthAttribute = @"iTermUnderlineLengthAttribute";
typedef struct iTermTextColorContext {
NSColor *lastUnprocessedColor;
CGFloat dimmingAmount;
CGFloat mutingAmount;
BOOL hasSelectedText;
iTermColorMap *colorMap;
NSView<iTermTextDrawingHelperDelegate> *delegate;
NSData *findMatches;
BOOL reverseVideo;
screen_char_t previousCharacterAttributes;
BOOL havePreviousCharacterAttributes;
NSColor *backgroundColor;
NSColor *previousBackgroundColor;
CGFloat minimumContrast;
NSColor *previousForegroundColor;
} iTermTextColorContext;
@implementation iTermTextDrawingHelper {
// Current font. Only valid for the duration of a single drawing context.
NSFont *_selectedFont;
// Last position of blinking cursor
VT100GridCoord _oldCursorPosition;
// Used by drawCursor: to remember the last time the cursor moved to avoid drawing a blinked-out
// cursor while it's moving.
NSTimeInterval _lastTimeCursorMoved;
BOOL _blinkingFound;
// Frame of the view we're drawing into.
NSRect _frame;
// The -visibleRect of the view we're drawing into.
NSRect _visibleRect;
NSSize _scrollViewContentSize;
NSRect _scrollViewDocumentVisibleRect;
// Pattern for background stripes
NSImage *_backgroundStripesImage;
NSMutableSet<NSString *> *_missingImages;
iTermPreciseTimerStats _stats[TIMER_STAT_MAX];
CGFloat _baselineOffset;
// The cache we're using now.
NSMutableDictionary<NSAttributedString *, id> *_lineRefCache;
// The cache we'll use next time.
NSMutableDictionary<NSAttributedString *, id> *_replacementLineRefCache;
}
- (instancetype)init {
self = [super init];
if (self) {
iTermPreciseTimerSetEnabled(YES);
iTermPreciseTimerStatsInit(&_stats[TIMER_TOTAL_DRAW_RECT], "Total drawRect");
iTermPreciseTimerStatsInit(&_stats[TIMER_CONSTRUCT_BACKGROUND_RUNS], "Construct BG runs");
iTermPreciseTimerStatsInit(&_stats[TIMER_DRAW_BACKGROUND], "Draw BG");
iTermPreciseTimerStatsInit(&_stats[TIMER_STAT_CONSTRUCTION], "Construction");
iTermPreciseTimerStatsInit(&_stats[TIMER_STAT_BUILD_MUTABLE_ATTRIBUTED_STRING], "Build attr strings");
iTermPreciseTimerStatsInit(&_stats[TIMER_STAT_DRAW], "Drawing");
iTermPreciseTimerStatsInit(&_stats[TIMER_ATTRS_FOR_CHAR], "Compute Attrs");
iTermPreciseTimerStatsInit(&_stats[TIMER_SHOULD_SEGMENT], "Segment");
iTermPreciseTimerStatsInit(&_stats[TIMER_UPDATE_BUILDER], "Update Builder");
iTermPreciseTimerStatsInit(&_stats[TIMER_COMBINE_ATTRIBUTES], "Combine Attrs");
iTermPreciseTimerStatsInit(&_stats[TIMER_ADVANCES], "Advances");
iTermPreciseTimerStatsInit(&_stats[TIMER_BETWEEN_CALLS_TO_DRAW_RECT], "Between calls");
_missingImages = [[NSMutableSet alloc] init];
_lineRefCache = [[NSMutableDictionary alloc] init];
_replacementLineRefCache = [[NSMutableDictionary alloc] init];
}
return self;
}
- (void)dealloc {
[_selection release];
[_cursorGuideColor release];
[_badgeImage release];
[_unfocusedSelectionColor release];
[_markedText release];
[_colorMap release];
[_selectedFont release];
[_missingImages release];
[_backgroundStripesImage release];
[_lineRefCache release];
[_replacementLineRefCache release];
[_timestampDrawHelper release];
[super dealloc];
}
#pragma mark - Drawing: General
- (void)drawTextViewContentInRect:(NSRect)rect
rectsPtr:(const NSRect *)rectArray
rectCount:(NSInteger)rectCount {
DLog(@"begin drawRect:%@ in view %@", [NSValue valueWithRect:rect], _delegate);
iTermPreciseTimerSetEnabled(YES);
if (_debug) {
[[NSColor redColor] set];
NSRectFill(rect);
}
[self updateCachedMetrics];
// If there are two or more rects that need display, the OS will pass in |rect| as the smallest
// bounding rect that contains them all. Luckily, we can get the list of the "real" dirty rects
// and they're guaranteed to be disjoint. So draw each of them individually.
[self startTiming];
const int haloWidth = 4;
NSInteger yLimit = _numberOfLines;
VT100GridCoordRange boundingCoordRange = [self coordRangeForRect:rect];
NSRange visibleLines = [self rangeOfVisibleRows];
// Start at 0 because ligatures can draw incorrectly otherwise. When a font has a ligature for
// -> and >-, then a line like ->->-> needs to start at the beginning since drawing only a
// suffix of it could draw a >- ligature at the start of the range being drawn. Issue 5030.
boundingCoordRange.start.x = 0;
boundingCoordRange.start.y = MAX(MAX(0, boundingCoordRange.start.y - 1), visibleLines.location);
boundingCoordRange.end.x = MIN(_gridSize.width, boundingCoordRange.end.x + haloWidth);
boundingCoordRange.end.y = MIN(yLimit, boundingCoordRange.end.y + 1);
int numRowsInRect = MAX(0, boundingCoordRange.end.y - boundingCoordRange.start.y);
if (numRowsInRect == 0) {
return;
}
NSMutableData *store = [NSMutableData dataWithLength:numRowsInRect * sizeof(NSRange)];
NSRange *ranges = (NSRange *)store.mutableBytes;
for (int i = 0; i < rectCount; i++) {
VT100GridCoordRange coordRange = [self coordRangeForRect:rectArray[i]];
// NSLog(@"Have to draw rect %@ (%@)", NSStringFromRect(rectArray[i]), VT100GridCoordRangeDescription(coordRange));
int coordRangeMinX = 0;
int coordRangeMaxX = MIN(_gridSize.width, coordRange.end.x + haloWidth);
for (int j = 0; j < numRowsInRect; j++) {
NSRange gridRange = ranges[j];
if (gridRange.location == 0 && gridRange.length == 0) {
ranges[j].location = coordRangeMinX;
ranges[j].length = coordRangeMaxX - coordRangeMinX;
} else {
const int min = MIN(gridRange.location, coordRangeMinX);
const int max = MAX(gridRange.location + gridRange.length, coordRangeMaxX);
ranges[j].location = min;
ranges[j].length = max - min;
}
// NSLog(@"Set range on line %d to %@", j + boundingCoordRange.start.y, NSStringFromRange(ranges[j]));
}
}
[self drawRanges:ranges count:numRowsInRect
origin:boundingCoordRange.start
boundingRect:[self rectForCoordRange:boundingCoordRange]
visibleLines:visibleLines];
if (_showDropTargets) {
[self drawDropTargets];
}
[self stopTiming];
iTermPreciseTimerPeriodicLog(@"drawRect", _stats, sizeof(_stats) / sizeof(*_stats), 5, [iTermAdvancedSettingsModel logDrawingPerformance], nil);
if (_debug) {
NSColor *c = [NSColor colorWithCalibratedRed:(rand() % 255) / 255.0
green:(rand() % 255) / 255.0
blue:(rand() % 255) / 255.0
alpha:1];
[c set];
NSFrameRect(rect);
}
[_selectedFont release];
_selectedFont = nil;
// Release cached CTLineRefs from the last set of drawings and update them with the new ones.
// This keeps us from having too many lines cached at once.
[_lineRefCache release];
_lineRefCache = _replacementLineRefCache;
_replacementLineRefCache = [[NSMutableDictionary alloc] init];
DLog(@"end drawRect:%@ in view %@", [NSValue valueWithRect:rect], _delegate);
}
- (NSImage *)imageForCoord:(VT100GridCoord)coord size:(CGSize)size {
NSData *rawMatches = [_delegate drawingHelperMatchesOnLine:coord.y];
screen_char_t *line = [_delegate drawingHelperLineAtIndex:coord.y];
iTermBackgroundColorRun backgroundRun = {
.range = { coord.x, 1 },
.bgColor = line[coord.x].backgroundColor,
.bgGreen = line[coord.x].bgGreen,
.bgBlue = line[coord.x].bgBlue,
.bgColorMode = line[coord.x].backgroundColorMode,
.selected = [[_selection selectedIndexesOnLine:coord.y] containsIndex:coord.x],
.isMatch = CheckFindMatchAtIndex(rawMatches, coord.x),
};
iTermBoxedBackgroundColorRun *boxedRun = [iTermBoxedBackgroundColorRun boxedBackgroundColorRunWithValue:backgroundRun];
NSColor *color = [self unprocessedColorForBackgroundRun:&backgroundRun];
// The unprocessed color is needed for minimum contrast computation for text color.
boxedRun.unprocessedBackgroundColor = color;
boxedRun.backgroundColor = [_colorMap processedBackgroundColorForBackgroundColor:color];
NSImage *image = [[NSImage alloc] initWithSize:size];
[image lockFocus];
[[NSColor redColor] set];
NSRectFill(NSMakeRect(0, 0, size.width, size.height));
[self drawForegroundForLineNumber:coord.y
y:0
backgroundRuns:@[ boxedRun ]
context:[[NSGraphicsContext currentContext] graphicsPort]];
[image unlockFocus];
return image;
}
- (NSInteger)numberOfEquivalentBackgroundColorLinesInRunArrays:(NSArray<iTermBackgroundColorRunsInLine *> *)backgroundRunArrays
fromIndex:(NSInteger)startIndex {
NSInteger count = 1;
iTermBackgroundColorRunsInLine *reference = backgroundRunArrays[startIndex];
for (NSInteger i = startIndex + 1; i < backgroundRunArrays.count; i++) {
if (![backgroundRunArrays[i].array isEqualToArray:reference.array]) {
break;
}
++count;
}
return count;
}
- (void)drawRanges:(NSRange *)ranges
count:(NSInteger)numRanges
origin:(VT100GridCoord)origin
boundingRect:(NSRect)boundingRect
visibleLines:(NSRange)visibleLines {
// Configure graphics
[[NSGraphicsContext currentContext] setCompositingOperation:NSCompositeCopy];
iTermTextExtractor *extractor = [self.delegate drawingHelperTextExtractor];
_blinkingFound = NO;
NSMutableArray<iTermBackgroundColorRunsInLine *> *backgroundRunArrays = [NSMutableArray array];
for (NSInteger i = 0; i < numRanges; i++) {
const int line = origin.y + i;
if (line >= NSMaxRange(visibleLines)) {
continue;
}
iTermPreciseTimerStatsStartTimer(&_stats[TIMER_CONSTRUCT_BACKGROUND_RUNS]);
NSRange charRange = ranges[i];
// We work hard to paint all the backgrounds first and then all the foregrounds. The reason this
// is necessary is because sometimes a glyph is larger than its cell. Some fonts draw narrow-
// width characters as full-width, some combining marks (e.g., combining enclosing circle) are
// necessarily larger than a cell, etc. For example, see issue 3446.
//
// By drawing characters after backgrounds and also drawing an extra "ring" of characters just
// outside the clipping region, we allow oversize characters to draw outside their bounds
// without getting painted-over by a background color. Of course if a glyph extends more than
// one full cell outside its bounds, it will still get overwritten by a background sometimes.
// First, find all the background runs. The outer array (backgroundRunArrays) will have one
// element per line. That element (a PTYTextViewBackgroundRunArray) contains the line number,
// y origin, and an array of PTYTextViewBackgroundRunBox objects.
const double y = line * _cellSize.height;
// An array of PTYTextViewBackgroundRunArray objects (one element per line).
// NSLog(@"Draw line %d at %f", line, y);
NSData *matches = [_delegate drawingHelperMatchesOnLine:line];
screen_char_t* theLine = [self.delegate drawingHelperLineAtIndex:line];
NSIndexSet *selectedIndexes =
[_selection selectedIndexesIncludingTabFillersInLine:line];
iTermBackgroundColorRunsInLine *runsInLine =
[iTermBackgroundColorRunsInLine backgroundRunsInLine:theLine
lineLength:_gridSize.width
row:line
selectedIndexes:selectedIndexes
withinRange:charRange
matches:matches
anyBlink:&_blinkingFound
textExtractor:extractor
y:y
line:line];
[backgroundRunArrays addObject:runsInLine];
iTermPreciseTimerStatsMeasureAndAccumulate(&_stats[TIMER_CONSTRUCT_BACKGROUND_RUNS]);
}
iTermPreciseTimerStatsStartTimer(&_stats[TIMER_DRAW_BACKGROUND]);
// If a background image is in use, draw the whole rect at once.
if (_hasBackgroundImage) {
[self.delegate drawingHelperDrawBackgroundImageInRect:boundingRect
blendDefaultBackground:NO];
}
// Now iterate over the lines and paint the backgrounds.
for (NSInteger i = 0; i < backgroundRunArrays.count; ) {
NSInteger rows = [self numberOfEquivalentBackgroundColorLinesInRunArrays:backgroundRunArrays fromIndex:i];
iTermBackgroundColorRunsInLine *runArray = backgroundRunArrays[i];
runArray.numberOfEquivalentRows = rows;
[self drawBackgroundForLine:runArray.line
atY:runArray.y
runs:runArray.array
equivalentRows:rows];
for (NSInteger j = i; j < i + rows; j++) {
[self drawMarginsAndMarkForLine:backgroundRunArrays[j].line y:backgroundRunArrays[j].y];
}
i += rows;
}
iTermPreciseTimerStatsMeasureAndAccumulate(&_stats[TIMER_DRAW_BACKGROUND]);
// Draw default background color over the line under the last drawn line so the tops of
// characters aren't visible there. If there is an IME, that could be many lines tall.
VT100GridCoordRange drawableCoordRange = [self drawableCoordRangeForRect:_visibleRect];
[self drawExcessAtLine:drawableCoordRange.end.y];
// Draw other background-like stuff that goes behind text.
[self drawAccessoriesInRect:boundingRect];
const BOOL drawCursorBeforeText = (_cursorType == CURSOR_UNDERLINE || _cursorType == CURSOR_VERTICAL);
if (drawCursorBeforeText) {
[self drawCursor:NO];
}
// Now iterate over the lines and paint the characters.
CGContextRef ctx = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
if ([self textAppearanceDependsOnBackgroundColor]) {
[self drawForegroundForBackgroundRunArrays:backgroundRunArrays
ctx:ctx];
} else {
[self drawUnprocessedForegroundForBackgroundRunArrays:backgroundRunArrays
ctx:ctx];
}
[self drawTopMargin];
// If the IME is in use, draw its contents over top of the "real" screen
// contents.
[self drawInputMethodEditorTextAt:_cursorCoord.x
y:_cursorCoord.y
width:_gridSize.width
height:_gridSize.height
cursorHeight:_cellSizeWithoutSpacing.height
ctx:ctx];
_blinkingFound |= self.cursorBlinking;
if (drawCursorBeforeText) {
if ([iTermAdvancedSettingsModel drawOutlineAroundCursor]) {
[self drawCursor:YES];
}
} else {
[self drawCursor:NO];
}
if (self.copyMode) {
[self drawCopyModeCursor];
}
}
- (BOOL)textAppearanceDependsOnBackgroundColor {
if (self.minimumContrast > 0) {
return YES;
}
if (self.colorMap.mutingAmount > 0) {
return YES;
}
if (self.colorMap.dimmingAmount > 0) {
return YES;
}
if (self.thinStrokes == iTermThinStrokesSettingDarkBackgroundsOnly) {
return YES;
}
if (self.thinStrokes == iTermThinStrokesSettingRetinaDarkBackgroundsOnly && _isRetina) {
return YES;
}
return NO;
}
#pragma mark - Drawing: Background
- (void)drawBackgroundForLine:(int)line
atY:(CGFloat)yOrigin
runs:(NSArray<iTermBoxedBackgroundColorRun *> *)runs
equivalentRows:(NSInteger)rows {
for (iTermBoxedBackgroundColorRun *box in runs) {
iTermBackgroundColorRun *run = box.valuePointer;
// NSLog(@"Paint background row %d range %@", line, NSStringFromRange(run->range));
NSRect rect = NSMakeRect(floor([iTermAdvancedSettingsModel terminalMargin] + run->range.location * _cellSize.width),
yOrigin,
ceil(run->range.length * _cellSize.width),
_cellSize.height * rows);
NSColor *color = [self unprocessedColorForBackgroundRun:run];
// The unprocessed color is needed for minimum contrast computation for text color.
box.unprocessedBackgroundColor = color;
color = [_colorMap processedBackgroundColorForBackgroundColor:color];
box.backgroundColor = color;
[box.backgroundColor set];
NSRectFillUsingOperation(rect,
_hasBackgroundImage ? NSCompositeSourceOver : NSCompositeCopy);
if (_debug) {
[[NSColor yellowColor] set];
NSBezierPath *path = [NSBezierPath bezierPath];
[path moveToPoint:rect.origin];
[path lineToPoint:NSMakePoint(NSMaxX(rect), NSMaxY(rect))];
[path stroke];
}
}
}
- (NSColor *)unprocessedColorForBackgroundRun:(iTermBackgroundColorRun *)run {
NSColor *color;
CGFloat alpha = _transparencyAlpha;
if (run->selected) {
color = [self selectionColorForCurrentFocus];
if (_transparencyAffectsOnlyDefaultBackgroundColor) {
alpha = 1;
}
} else if (run->isMatch) {
color = [NSColor colorWithCalibratedRed:1 green:1 blue:0 alpha:1];
} else {
const BOOL defaultBackground = (run->bgColor == ALTSEM_DEFAULT &&
run->bgColorMode == ColorModeAlternate);
// When set in preferences, applies alpha only to the defaultBackground
// color, useful for keeping Powerline segments opacity(background)
// consistent with their seperator glyphs opacity(foreground).
if (_transparencyAffectsOnlyDefaultBackgroundColor && !defaultBackground) {
alpha = 1;
}
if (_reverseVideo && defaultBackground) {
// Reverse video is only applied to default background-
// color chars.
color = [_delegate drawingHelperColorForCode:ALTSEM_DEFAULT
green:0
blue:0
colorMode:ColorModeAlternate
bold:NO
faint:NO
isBackground:NO];
} else {
// Use the regular background color.
color = [_delegate drawingHelperColorForCode:run->bgColor
green:run->bgGreen
blue:run->bgBlue
colorMode:run->bgColorMode
bold:NO
faint:NO
isBackground:YES];
}
if (defaultBackground && _hasBackgroundImage) {
alpha = 1 - _blend;
}
}
return [color colorWithAlphaComponent:alpha];
}
- (void)drawExcessAtLine:(int)line {
NSRect excessRect;
if (_numberOfIMELines) {
// Draw a default-color rectangle from below the last line of text to
// the bottom of the frame to make sure that IME offset lines are
// cleared when the screen is scrolled up.
excessRect.origin.x = 0;
excessRect.origin.y = line * _cellSize.height;
excessRect.size.width = _scrollViewContentSize.width;
excessRect.size.height = _frame.size.height - excessRect.origin.y;
} else {
// Draw the excess bar at the bottom of the visible rect the in case
// that some other tab has a larger font and these lines don't fit
// evenly in the available space.
NSRect visibleRect = _visibleRect;
excessRect.origin.x = 0;
excessRect.origin.y = NSMaxY(visibleRect) - _excess;
excessRect.size.width = _scrollViewContentSize.width;
excessRect.size.height = _excess;
}
[self.delegate drawingHelperDrawBackgroundImageInRect:excessRect
blendDefaultBackground:YES];
if (_debug) {
[[NSColor blueColor] set];
NSBezierPath *path = [NSBezierPath bezierPath];
[path moveToPoint:excessRect.origin];
[path lineToPoint:NSMakePoint(NSMaxX(excessRect), NSMaxY(excessRect))];
[path stroke];
NSFrameRect(excessRect);
}
if (_showStripes) {
[self drawStripesInRect:excessRect];
}
}
- (void)drawTopMargin {
// Draw a margin at the top of the visible area.
NSRect topMarginRect = _visibleRect;
topMarginRect.origin.y -=
MAX(0, [iTermAdvancedSettingsModel terminalVMargin] - NSMinY(_delegate.enclosingScrollView.documentVisibleRect));
topMarginRect.size.height = [iTermAdvancedSettingsModel terminalVMargin];
[self.delegate drawingHelperDrawBackgroundImageInRect:topMarginRect
blendDefaultBackground:YES];
if (_showStripes) {
[self drawStripesInRect:topMarginRect];
}
}
- (void)drawMarginsAndMarkForLine:(int)line y:(CGFloat)y {
NSRect leftMargin = NSMakeRect(0, y, [iTermAdvancedSettingsModel terminalMargin], _cellSize.height);
NSRect rightMargin;
NSRect visibleRect = _visibleRect;
rightMargin.origin.x = _cellSize.width * _gridSize.width + [iTermAdvancedSettingsModel terminalMargin];
rightMargin.origin.y = y;
rightMargin.size.width = visibleRect.size.width - rightMargin.origin.x;
rightMargin.size.height = _cellSize.height;
// Draw background in margins
[self.delegate drawingHelperDrawBackgroundImageInRect:leftMargin
blendDefaultBackground:YES];
[self.delegate drawingHelperDrawBackgroundImageInRect:rightMargin
blendDefaultBackground:YES];
[self drawMarkIfNeededOnLine:line leftMarginRect:leftMargin];
}
- (void)drawStripesInRect:(NSRect)rect {
if (!_backgroundStripesImage) {
_backgroundStripesImage = [[NSImage imageNamed:@"BackgroundStripes"] retain];
}
NSColor *color = [NSColor colorWithPatternImage:_backgroundStripesImage];
[color set];
[NSGraphicsContext saveGraphicsState];
[[NSGraphicsContext currentContext] setPatternPhase:NSMakePoint(0, 0)];
NSRectFillUsingOperation(rect, NSCompositeSourceOver);
[NSGraphicsContext restoreGraphicsState];
}
#pragma mark - Drawing: Accessories
- (void)drawAccessoriesInRect:(NSRect)bgRect {
VT100GridCoordRange coordRange = [self coordRangeForRect:bgRect];
[self drawBadgeInRect:bgRect];
// Draw red stripes in the background if sending input to all sessions
if (_showStripes) {
[self drawStripesInRect:bgRect];
}
// Highlight cursor line if the cursor is on this line and it's on.
int cursorLine = _cursorCoord.y + _numberOfScrollbackLines;
const BOOL drawCursorGuide = (self.highlightCursorLine &&
cursorLine >= coordRange.start.y &&
cursorLine < coordRange.end.y);
if (drawCursorGuide) {
CGFloat y = cursorLine * _cellSize.height;
[self drawCursorGuideForColumns:NSMakeRange(coordRange.start.x,
coordRange.end.x - coordRange.start.x)
y:y];
}
}
- (void)drawCursorGuideForColumns:(NSRange)range y:(CGFloat)yOrigin {
if (!_cursorVisible) {
return;
}
[_cursorGuideColor set];
NSPoint textOrigin = NSMakePoint([iTermAdvancedSettingsModel terminalMargin] + range.location * _cellSize.width, yOrigin);
NSRect rect = NSMakeRect(textOrigin.x,
textOrigin.y,
range.length * _cellSize.width,
_cellSize.height);
NSRectFillUsingOperation(rect, NSCompositeSourceOver);
rect.size.height = 1;
NSRectFillUsingOperation(rect, NSCompositeSourceOver);
rect.origin.y += _cellSize.height - 1;
NSRectFillUsingOperation(rect, NSCompositeSourceOver);
}
+ (NSRect)frameForMarkContainedInRect:(NSRect)container
cellSize:(CGSize)cellSize
cellSizeWithoutSpacing:(CGSize)cellSizeWithoutSpacing
scale:(CGFloat)scale {
const CGFloat verticalSpacing = MAX(0, scale * round((cellSize.height / scale - cellSizeWithoutSpacing.height / scale) / 2.0));
CGRect rect = NSMakeRect(container.origin.x,
container.origin.y + verticalSpacing,
container.size.width,
cellSizeWithoutSpacing.height);
const CGFloat kMaxHeight = 15 * scale;
const CGFloat kMinMargin = 3 * scale;
const CGFloat kMargin = MAX(kMinMargin, (cellSizeWithoutSpacing.height - kMaxHeight) / 2.0);
const CGFloat overage = rect.size.width - rect.size.height + 2 * kMargin;
if (overage > 0) {
rect.origin.x += overage * .7;
rect.size.width -= overage;
}
rect.origin.y += kMargin;
rect.size.height -= kMargin;
// Bump the bottom up by as much as 3 points.
rect.size.height -= MAX(3 * scale, (cellSizeWithoutSpacing.height - 15 * scale) / 2.0);
return rect;
}
+ (NSColor *)successMarkColor {
return [NSColor colorWithSRGBRed:0.53846
green:0.757301
blue:1
alpha:1];
}
+ (NSColor *)errorMarkColor {
return [NSColor colorWithSRGBRed:0.987265
green:0.447845
blue:0.426244
alpha:1];
}
+ (NSColor *)otherMarkColor {
return [NSColor colorWithSRGBRed:0.856645
green:0.847289
blue:0.425771
alpha:1];
}
- (void)drawMarkIfNeededOnLine:(int)line leftMarginRect:(NSRect)leftMargin {
VT100ScreenMark *mark = [self.delegate drawingHelperMarkOnLine:line];
if (mark.isVisible && self.drawMarkIndicators) {
NSRect insetLeftMargin = leftMargin;
insetLeftMargin.origin.x += 1;
insetLeftMargin.size.width -= 1;
NSRect rect = [iTermTextDrawingHelper frameForMarkContainedInRect:insetLeftMargin
cellSize:_cellSize
cellSizeWithoutSpacing:_cellSizeWithoutSpacing
scale:1];
const CGFloat minX = round(NSMinX(rect));
NSPoint top = NSMakePoint(minX, NSMinY(rect));
NSPoint right = NSMakePoint(minX + NSWidth(rect), NSMidY(rect) - 0.25);
NSPoint bottom = NSMakePoint(minX, NSMaxY(rect) - 0.5);
[[NSColor blackColor] set];
NSBezierPath *path = [NSBezierPath bezierPath];
[path moveToPoint:NSMakePoint(bottom.x, bottom.y)];
[path lineToPoint:NSMakePoint(right.x, right.y)];
[path setLineWidth:1.0];
[path stroke];
if (mark.code == 0) {
// Success
[[iTermTextDrawingHelper successMarkColor] set];
} else if ([iTermAdvancedSettingsModel showYellowMarkForJobStoppedBySignal] &&
mark.code >= 128 && mark.code <= 128 + 32) {
// Stopped by a signal (or an error, but we can't tell which)
[[iTermTextDrawingHelper otherMarkColor] set];
} else {
// Failure
[[iTermTextDrawingHelper errorMarkColor] set];
}
[path moveToPoint:top];
[path lineToPoint:right];
[path lineToPoint:bottom];
[path lineToPoint:top];
[path fill];
}
}
- (void)drawNoteRangesOnLine:(int)line {
NSArray *noteRanges = [self.delegate drawingHelperCharactersWithNotesOnLine:line];
if (noteRanges.count) {
for (NSValue *value in noteRanges) {
VT100GridRange range = [value gridRangeValue];
CGFloat x = range.location * _cellSize.width + [iTermAdvancedSettingsModel terminalMargin];
CGFloat y = line * _cellSize.height;
[[NSColor yellowColor] set];
CGFloat maxX = MIN(_frame.size.width - [iTermAdvancedSettingsModel terminalMargin], range.length * _cellSize.width + x);
CGFloat w = maxX - x;
NSRectFill(NSMakeRect(x, y + _cellSize.height - 1.5, w, 1));
[[NSColor orangeColor] set];
NSRectFill(NSMakeRect(x, y + _cellSize.height - 1, w, 1));
}
}
}
- (void)createTimestampDrawingHelper {
[_timestampDrawHelper autorelease];
_timestampDrawHelper =
[[iTermTimestampDrawHelper alloc] initWithBackgroundColor:[self defaultBackgroundColor]
textColor:[_colorMap colorForKey:kColorMapForeground]
now:self.now
useTestingTimezone:self.useTestingTimezone
rowHeight:_cellSize.height
retina:self.isRetina];
}
- (void)drawTimestamps {
if (!self.showTimestamps) {
return;
}
[self updateCachedMetrics];
CGContextRef ctx = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
if (!self.isRetina) {
CGContextSetShouldSmoothFonts(ctx, NO);
}
// Note: for the foreground color, we don't use the dimmed version because it looks bad on
// nonretina displays. That's why I go to the colormap instead of using -defaultForegroundColor.
for (int y = _scrollViewDocumentVisibleRect.origin.y / _cellSize.height;
y < NSMaxY(_scrollViewDocumentVisibleRect) / _cellSize.height && y < _numberOfLines;
y++) {
[_timestampDrawHelper setDate:[_delegate drawingHelperTimestampForLine:y] forLine:y];
}
[_timestampDrawHelper drawInContext:[NSGraphicsContext currentContext] frame:_frame];
if (!self.isRetina) {
CGContextSetShouldSmoothFonts(ctx, YES);
}
}
+ (NSRect)rectForBadgeImageOfSize:(NSSize)imageSize
destinationRect:(NSRect)rect
destinationFrameSize:(NSSize)textViewSize
visibleSize:(NSSize)visibleSize
sourceRectPtr:(NSRect *)sourceRectPtr {
if (NSEqualSizes(NSZeroSize, imageSize)) {
return NSZeroRect;
}
NSRect destination = NSMakeRect(textViewSize.width - imageSize.width - [iTermAdvancedSettingsModel badgeRightMargin],
textViewSize.height - visibleSize.height + kiTermIndicatorStandardHeight + [iTermAdvancedSettingsModel badgeTopMargin],
imageSize.width,
imageSize.height);
NSRect intersection = NSIntersectionRect(rect, destination);
if (intersection.size.width == 0 || intersection.size.height == 1) {
return NSZeroRect;
}
NSRect source = intersection;
source.origin.x -= destination.origin.x;
source.origin.y -= destination.origin.y;
source.origin.y = imageSize.height - (source.origin.y + source.size.height);
*sourceRectPtr = source;
return intersection;
}
- (NSSize)drawBadgeInRect:(NSRect)rect {
NSRect source;
NSRect intersection = [iTermTextDrawingHelper rectForBadgeImageOfSize:_badgeImage.size
destinationRect:rect
destinationFrameSize:_frame.size
visibleSize:_scrollViewDocumentVisibleRect.size
sourceRectPtr:&source];
if (NSEqualSizes(NSZeroSize, intersection.size)) {
return NSZeroSize;
}
[_badgeImage drawInRect:intersection
fromRect:source
operation:NSCompositeSourceOver
fraction:1
respectFlipped:YES
hints:nil];
NSSize imageSize = _badgeImage.size;
imageSize.width += kBadgeMargin + [iTermAdvancedSettingsModel badgeRightMargin];
return imageSize;
}
#pragma mark - Drawing: Drop targets
- (void)drawDropTargets {
NSColor *scrimColor;
NSColor *borderColor;
NSColor *labelColor;
NSColor *outlineColor;
if ([[self defaultBackgroundColor] isDark]) {
outlineColor = [NSColor whiteColor];
scrimColor = [NSColor whiteColor];
borderColor = [NSColor lightGrayColor];
labelColor = [NSColor blackColor];
} else {
outlineColor = [NSColor blackColor];
scrimColor = [NSColor blackColor];
borderColor = [NSColor darkGrayColor];
labelColor = [NSColor whiteColor];
}
scrimColor = [scrimColor colorWithAlphaComponent:0.6];
NSDictionary *attributes = @{ NSForegroundColorAttributeName: labelColor,
NSStrokeWidthAttributeName: @-4,
NSStrokeColorAttributeName: outlineColor };
[self enumerateDropTargets:^(NSString *label, NSRange range) {
NSRect rect = NSMakeRect(0,
range.location * _cellSize.height,
_scrollViewDocumentVisibleRect.size.width,
_cellSize.height * range.length);
if (NSLocationInRange(_dropLine, range)) {
[[[NSColor selectedControlColor] colorWithAlphaComponent:0.7] set];
} else {
[scrimColor set];
}
NSRectFillUsingOperation(rect, NSCompositeSourceOver);
[borderColor set];
NSFrameRect(rect);
[label drawInRect:rect withAttributes:[label attributesUsingFont:[NSFont boldSystemFontOfSize:8]
fittingSize:rect.size
attributes:attributes]];
}];
}
- (void)enumerateDropTargets:(void (^)(NSString *, NSRange))block {
NSRect rect = _scrollViewDocumentVisibleRect;
VT100GridCoordRange coordRange = [self drawableCoordRangeForRect:rect];
CGFloat y = coordRange.start.y * _cellSize.height;
NSMutableArray *labels = [NSMutableArray array];
NSMutableArray *lineRanges = [NSMutableArray array];
int firstLine = coordRange.start.y;
for (int line = coordRange.start.y; line <= coordRange.end.y; line++, y += _cellSize.height) {
NSString *label = [_delegate drawingHelperLabelForDropTargetOnLine:line];
if (!label) {
continue;
}
NSString *previousLabel = labels.lastObject;
if ([label isEqualToString:previousLabel]) {
[labels removeLastObject];
[lineRanges removeLastObject];
} else {
firstLine = line;
}
[labels addObject:label];
[lineRanges addObject:[NSValue valueWithRange:NSMakeRange(firstLine, line - firstLine + 1)]];
}
for (NSInteger i = 0; i < labels.count; i++) {
block(labels[i], [lineRanges[i] rangeValue]);
}
}
#pragma mark - Drawing: Foreground
// Draw assuming no foreground color processing. Keeps glyphs together in a single background color run across different background colors.
- (void)drawUnprocessedForegroundForBackgroundRunArrays:(NSArray<iTermBackgroundColorRunsInLine *> *)backgroundRunArrays
ctx:(CGContextRef)ctx {
// Combine runs on each line, except those with different values of
// `selected` or `match`. Those properties affect foreground color and must
// split ligatures up.
NSArray<iTermBackgroundColorRunsInLine *> *fakeRunArrays = [backgroundRunArrays mapWithBlock:^id(iTermBackgroundColorRunsInLine *runs) {
NSMutableArray<iTermBoxedBackgroundColorRun *> *combinedRuns = [NSMutableArray array];
iTermBackgroundColorRun previousRun = { {0} };
BOOL havePreviousRun = NO;
for (iTermBoxedBackgroundColorRun *run in runs.array) {
if (!havePreviousRun) {
havePreviousRun = YES;
previousRun = *run.valuePointer;
} else if (run.valuePointer->selected == previousRun.selected &&
run.valuePointer->isMatch == previousRun.isMatch) {
previousRun.range = NSUnionRange(previousRun.range, run.valuePointer->range);
} else {
[combinedRuns addObject:[iTermBoxedBackgroundColorRun boxedBackgroundColorRunWithValue:previousRun]];
previousRun = *run.valuePointer;
}
}
if (havePreviousRun) {
[combinedRuns addObject:[iTermBoxedBackgroundColorRun boxedBackgroundColorRunWithValue:previousRun]];
}
iTermBackgroundColorRunsInLine *fakeRuns = [[[iTermBackgroundColorRunsInLine alloc] init] autorelease];
fakeRuns.line = runs.line;
fakeRuns.y = runs.y;
fakeRuns.numberOfEquivalentRows = runs.numberOfEquivalentRows;
fakeRuns.array = combinedRuns;
return fakeRuns;