-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
iTermTextDrawingHelper.m
2157 lines (1897 loc) · 93.8 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 "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)
static const int kBadgeMargin = 4;
extern void CGContextSetFontSmoothingStyle(CGContextRef, int);
extern int CGContextGetFontSmoothingStyle(CGContextRef);
@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;
NSInteger ligatureLevel;
} iTermCharacterAttributes;
enum {
TIMER_STAT_CONSTRUCTION,
TIMER_STAT_BUILD_MUTABLE_ATTRIBUTED_STRING,
TIMER_STAT_DRAW,
TIMER_ATTRS_FOR_CHAR,
TIMER_SHOULD_SEGMENT,
TIMER_ADVANCES,
TIMER_UPDATE_BUILDER,
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 iTermIsBoxDrawingAttribute = @"iTermIsBoxDrawingAttribute";
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;
BOOL haveUnderlinedHostname;
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;
MovingAverage *_drawRectDuration;
MovingAverage *_drawRectInterval;
// 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;
iTermPreciseTimerStats _stats[TIMER_STAT_MAX];
CGFloat _baselineOffset;
}
- (instancetype)init {
self = [super init];
if (self) {
if ([iTermAdvancedSettingsModel logDrawingPerformance]) {
NSLog(@"** Drawing performance timing enabled **");
_drawRectDuration = [[MovingAverage alloc] init];
_drawRectInterval = [[MovingAverage alloc] init];
_drawRectDuration.alpha = 0.95;
_drawRectInterval.alpha = 0.95;
iTermPreciseTimerStatsInit(&_stats[TIMER_STAT_CONSTRUCTION], "Construction");
iTermPreciseTimerStatsInit(&_stats[TIMER_STAT_BUILD_MUTABLE_ATTRIBUTED_STRING], "Builder");
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_ADVANCES], "Advances");
}
}
return self;
}
- (void)dealloc {
[_selection release];
[_cursorGuideColor release];
[_badgeImage release];
[_unfocusedSelectionColor release];
[_markedText release];
[_colorMap release];
[_selectedFont release];
[_drawRectDuration release];
[_drawRectInterval release];
[_backgroundStripesImage release];
[super dealloc];
}
#pragma mark - Drawing: General
- (void)drawTextViewContentInRect:(NSRect)rect
rectsPtr:(const NSRect *)rectArray
rectCount:(NSInteger)rectCount {
// NSLog(@"drawRect:%@ in view %@", [NSValue valueWithRect:rect], _delegate);
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.
if (_drawRectDuration) {
[self startTiming];
}
const int haloWidth = 4;
NSInteger yLimit = _numberOfLines;
VT100GridCoordRange boundingCoordRange = [self coordRangeForRect:rect];
boundingCoordRange.start.x = MAX(0, boundingCoordRange.start.x - haloWidth);
boundingCoordRange.start.y = MAX(0, boundingCoordRange.start.y - 1);
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 = MAX(0, coordRange.start.x - haloWidth);
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]];
// The OS may ask us to draw an area outside the visible area, but that looks awful so cover it
// up by drawing some background over it.
[self drawExcessAtLine:[self coordRangeForRect:rect].end.y];
[self drawCursor];
if (_showDropTargets) {
[self drawDropTargets];
}
if (_drawRectDuration) {
[self stopTiming];
}
if ([iTermAdvancedSettingsModel logDrawingPerformance]) {
iTermPreciseTimerPeriodicLog(_stats, sizeof(_stats) / sizeof(*_stats), 0);
}
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);
}
}
- (void)drawRanges:(NSRange *)ranges count:(NSInteger)numRanges origin:(VT100GridCoord)origin boundingRect:(NSRect)boundingRect {
// Configure graphics
[[NSGraphicsContext currentContext] setCompositingOperation:NSCompositeCopy];
iTermTextExtractor *extractor = [self.delegate drawingHelperTextExtractor];
_blinkingFound = NO;
NSMutableArray *backgroundRunArrays = [NSMutableArray array];
for (NSInteger i = 0; i < numRanges; i++) {
const int line = origin.y + i;
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", line);
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];
}
// 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 (iTermBackgroundColorRunsInLine *runArray in backgroundRunArrays) {
[self drawBackgroundForLine:runArray.line
atY:runArray.y
runs:runArray.array];
[self drawMarginsAndMarkForLine:runArray.line y:runArray.y];
}
// Draw other background-like stuff that goes behind text.
[self drawAccessoriesInRect:boundingRect];
// Now iterate over the lines and paint the characters.
CGContextRef ctx = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
for (iTermBackgroundColorRunsInLine *runArray in backgroundRunArrays) {
[self drawCharactersForLine:runArray.line
atY:runArray.y
backgroundRuns:runArray.array
context:ctx];
[self drawNoteRangesOnLine:runArray.line];
if (_debug) {
NSString *s = [NSString stringWithFormat:@"%d", runArray.line];
[s drawAtPoint:NSMakePoint(0, runArray.y)
withAttributes:@{ NSForegroundColorAttributeName: [NSColor blackColor],
NSBackgroundColorAttributeName: [NSColor whiteColor],
NSFontAttributeName: [NSFont systemFontOfSize:8] }];
}
}
[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;
[_selectedFont release];
_selectedFont = nil;
}
#pragma mark - Drawing: Background
- (void)drawBackgroundForLine:(int)line
atY:(CGFloat)yOrigin
runs:(NSArray<iTermBoxedBackgroundColorRun *> *)runs {
for (iTermBoxedBackgroundColorRun *box in runs) {
iTermBackgroundColorRun *run = box.valuePointer;
// NSLog(@"Paint background row %d range %@", line, NSStringFromRange(run->range));
NSRect rect = NSMakeRect(floor(MARGIN + run->range.location * _cellSize.width),
yOrigin,
ceil(run->range.length * _cellSize.width),
_cellSize.height);
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, VMARGIN - NSMinY(_delegate.enclosingScrollView.documentVisibleRect));
topMarginRect.size.height = VMARGIN;
[self.delegate drawingHelperDrawBackgroundImageInRect:topMarginRect
blendDefaultBackground:YES];
if (_showStripes) {
[self drawStripesInRect:topMarginRect];
}
}
- (void)drawMarginsAndMarkForLine:(int)line y:(CGFloat)y {
NSRect leftMargin = NSMakeRect(0, y, MARGIN, _cellSize.height);
NSRect rightMargin;
NSRect visibleRect = _visibleRect;
rightMargin.origin.x = _cellSize.width * _gridSize.width + MARGIN;
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];
NSRectFillUsingOperation(rect, NSCompositeSourceOver);
}
#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(MARGIN + 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);
}
- (void)drawMarkIfNeededOnLine:(int)line leftMarginRect:(NSRect)leftMargin {
VT100ScreenMark *mark = [self.delegate drawingHelperMarkOnLine:line];
if (mark.isVisible && self.drawMarkIndicators) {
const CGFloat verticalSpacing = MAX(0, round((_cellSize.height - _cellSizeWithoutSpacing.height) / 2.0));
CGRect rect = NSMakeRect(leftMargin.origin.x,
leftMargin.origin.y + verticalSpacing,
MARGIN,
_cellSizeWithoutSpacing.height);
const CGFloat kMaxHeight = 15;
const CGFloat kMinMargin = 3;
const CGFloat kMargin = MAX(kMinMargin, (_cellSizeWithoutSpacing.height - kMaxHeight) / 2.0);
NSPoint top = NSMakePoint(NSMinX(rect), rect.origin.y + kMargin);
NSPoint right = NSMakePoint(NSMaxX(rect), NSMidY(rect));
NSPoint bottom = NSMakePoint(NSMinX(rect), NSMaxY(rect) - kMargin);
[[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
[[NSColor colorWithCalibratedRed:120.0 / 255.0 green:178.0 / 255.0 blue:255.0 / 255.0 alpha:1] 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)
[[NSColor colorWithCalibratedRed:210.0 / 255.0 green:210.0 / 255.0 blue:90.0 / 255.0 alpha:1] set];
} else {
// Failure
[[NSColor colorWithCalibratedRed:248.0 / 255.0 green:90.0 / 255.0 blue:90.0 / 255.0 alpha:1] 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 + MARGIN;
CGFloat y = line * _cellSize.height;
[[NSColor yellowColor] set];
CGFloat maxX = MIN(_frame.size.width - MARGIN, 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));
}
}
}
- (CGFloat)drawTimestamps {
[self updateCachedMetrics];
CGContextRef ctx = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
if (!self.isRetina) {
CGContextSetShouldSmoothFonts(ctx, NO);
}
NSString *previous = nil;
CGFloat width = 0;
for (int y = _scrollViewDocumentVisibleRect.origin.y / _cellSize.height;
y < NSMaxY(_scrollViewDocumentVisibleRect) / _cellSize.height && y < _numberOfLines;
y++) {
CGFloat thisWidth = 0;
previous = [self drawTimestampForLine:y previousTimestamp:previous width:&thisWidth];
width = MAX(thisWidth, width);
}
if (!self.isRetina) {
CGContextSetShouldSmoothFonts(ctx, YES);
}
return width;
}
- (NSString *)drawTimestampForLine:(int)line
previousTimestamp:(NSString *)previousTimestamp
width:(CGFloat *)widthPtr {
NSDate *timestamp = [_delegate drawingHelperTimestampForLine:line];
NSDateFormatter *fmt = [[[NSDateFormatter alloc] init] autorelease];
const NSTimeInterval day = -86400;
const NSTimeInterval timeDelta = timestamp.timeIntervalSinceReferenceDate - self.now;
if (timeDelta < day * 180) {
// More than 180 days ago: include year
// I tried using 365 but it was pretty confusing to see tomorrow's date.
[fmt setDateFormat:[NSDateFormatter dateFormatFromTemplate:@"yyyyMMMd jj:mm:ss"
options:0
locale:[NSLocale currentLocale]]];
} else if (timeDelta < day * 6) {
// 6 days to 180 days ago: include date without year
[fmt setDateFormat:[NSDateFormatter dateFormatFromTemplate:@"MMMd jj:mm:ss"
options:0
locale:[NSLocale currentLocale]]];
} else if (timeDelta < day) {
// 1 day to 6 days ago: include day of week
[fmt setDateFormat:[NSDateFormatter dateFormatFromTemplate:@"EEE jj:mm:ss"
options:0
locale:[NSLocale currentLocale]]];
} else {
// In last 24 hours, just show time
[fmt setDateFormat:[NSDateFormatter dateFormatFromTemplate:@"jj:mm:ss"
options:0
locale:[NSLocale currentLocale]]];
}
if (self.useTestingTimezone) {
fmt.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
}
NSString *theTimestamp = [fmt stringFromDate:timestamp];
if (!timestamp || ![timestamp timeIntervalSinceReferenceDate]) {
theTimestamp = @"";
}
NSString *s = theTimestamp;
BOOL repeat = [theTimestamp isEqualToString:previousTimestamp];
NSString *widest = [s stringByReplacingOccurrencesOfRegex:@"[\\d\\p{Alphabetic}]" withString:@"M"];
NSSize size = [widest sizeWithAttributes:@{ NSFontAttributeName: [NSFont systemFontOfSize:[iTermAdvancedSettingsModel pointSizeOfTimeStamp]] }];
int w = size.width + MARGIN;
int x = MAX(0, _frame.size.width - w);
CGFloat y = line * _cellSize.height;
NSColor *bgColor = [self defaultBackgroundColor];
// I don't want to use the dimmed color for this because it's really ugly (esp on nonretina)
// so I can't use -defaultForegroundColor here.
NSColor *fgColor = [_colorMap colorForKey:kColorMapForeground];
NSColor *shadowColor;
if ([fgColor isDark]) {
shadowColor = [NSColor whiteColor];
} else {
shadowColor = [NSColor blackColor];
}
const CGFloat alpha = 0.9;
NSGradient *gradient =
[[[NSGradient alloc] initWithStartingColor:[bgColor colorWithAlphaComponent:0]
endingColor:[bgColor colorWithAlphaComponent:alpha]] autorelease];
[[NSGraphicsContext currentContext] setCompositingOperation:NSCompositeSourceOver];
[gradient drawInRect:NSMakeRect(x - 20, y, 20, _cellSize.height) angle:0];
[[bgColor colorWithAlphaComponent:alpha] set];
[[NSGraphicsContext currentContext] setCompositingOperation:NSCompositeSourceOver];
NSRectFillUsingOperation(NSMakeRect(x, y, w, _cellSize.height), NSCompositeSourceOver);
NSShadow *shadow = [[[NSShadow alloc] init] autorelease];
shadow.shadowColor = shadowColor;
shadow.shadowBlurRadius = 0.2f;
shadow.shadowOffset = CGSizeMake(0.5, -0.5);
NSDictionary *attributes;
if (self.isRetina) {
attributes = @{ NSFontAttributeName: [NSFont userFixedPitchFontOfSize:[iTermAdvancedSettingsModel pointSizeOfTimeStamp]],
NSForegroundColorAttributeName: fgColor,
NSShadowAttributeName: shadow };
} else {
NSFont *font = [NSFont userFixedPitchFontOfSize:[iTermAdvancedSettingsModel pointSizeOfTimeStamp]];
attributes = @{ NSFontAttributeName: [[NSFontManager sharedFontManager] fontWithFamily:font.familyName
traits:NSBoldFontMask
weight:0
size:font.pointSize],
NSForegroundColorAttributeName: fgColor };
}
CGFloat offset = (_cellSize.height - size.height) / 2;
if (s.length && repeat) {
[fgColor set];
CGFloat center = x + 10;
NSRectFill(NSMakeRect(center - 1, y, 1, _cellSize.height));
NSRectFill(NSMakeRect(center + 1, y, 1, _cellSize.height));
} else {
[s drawAtPoint:NSMakePoint(x, y + offset) withAttributes:attributes];
}
*widthPtr = w;
return theTimestamp;
}
- (NSSize)drawBadgeInRect:(NSRect)rect {
NSImage *image = _badgeImage;
if (!image) {
return NSZeroSize;
}
NSSize textViewSize = _frame.size;
NSSize visibleSize = _scrollViewDocumentVisibleRect.size;
NSSize imageSize = image.size;
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 NSZeroSize;
}
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);
[image drawInRect:intersection
fromRect:source
operation:NSCompositeSourceOver
fraction:1
respectFlipped:YES
hints:nil];
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: Text
- (void)drawCharactersForLine:(int)line
atY:(CGFloat)y
backgroundRuns:(NSArray<iTermBoxedBackgroundColorRun *> *)backgroundRuns
context:(CGContextRef)ctx {
screen_char_t* theLine = [self.delegate drawingHelperLineAtIndex:line];
NSData *matches = [_delegate drawingHelperMatchesOnLine:line];
for (iTermBoxedBackgroundColorRun *box in backgroundRuns) {
iTermBackgroundColorRun *run = box.valuePointer;
NSPoint textOrigin = NSMakePoint(MARGIN + run->range.location * _cellSize.width,
y);
[self constructAndDrawRunsForLine:theLine
row:line
inRange:run->range
startingAtPoint:textOrigin
bgselected:run->selected
bgColor:box.unprocessedBackgroundColor
processedBackgroundColor:box.backgroundColor
matches:matches
forceTextColor:nil
context:ctx];
}
}
- (void)constructAndDrawRunsForLine:(screen_char_t *)theLine
row:(int)row
inRange:(NSRange)indexRange
startingAtPoint:(NSPoint)initialPoint
bgselected:(BOOL)bgselected
bgColor:(NSColor *)bgColor
processedBackgroundColor:(NSColor *)processedBackgroundColor
matches:(NSData *)matches
forceTextColor:(NSColor *)forceTextColor // optional
context:(CGContextRef)ctx {
CTVector(CGFloat) positions;
CTVectorCreate(&positions, _gridSize.width);
if (indexRange.location > 0) {
screen_char_t firstCharacter = theLine[indexRange.location];
if (firstCharacter.code == DWC_RIGHT && !firstCharacter.complexChar) {
// Don't try to start drawing in the middle of a double-width character.
indexRange.location -= 1;
indexRange.length += 1;
initialPoint.x -= _cellSize.width;
}
}
// NSLog(@"Draw text on line %d range %@", row, NSStringFromRange(indexRange));
iTermPreciseTimerStatsStartTimer(&_stats[TIMER_STAT_CONSTRUCTION]);
NSArray<NSAttributedString *> *attributedStrings = [self attributedStringsForLine:theLine
range:indexRange
hasSelectedText:bgselected
backgroundColor:bgColor
forceTextColor:forceTextColor
findMatches:matches
underlinedRange:[self underlinedRangeOnLine:row + _totalScrollbackOverflow]
positions:&positions];
iTermPreciseTimerStatsMeasureAndRecordTimer(&_stats[TIMER_STAT_CONSTRUCTION]);
iTermPreciseTimerStatsStartTimer(&_stats[TIMER_STAT_DRAW]);
[self drawMultipartAttributedString:attributedStrings
atPoint:initialPoint
origin:VT100GridCoordMake(indexRange.location, row)
positions:&positions
inContext:ctx
backgroundColor:processedBackgroundColor];
CTVectorDestroy(&positions);
iTermPreciseTimerStatsMeasureAndRecordTimer(&_stats[TIMER_STAT_DRAW]);
}
- (void)drawMultipartAttributedString:(NSArray<NSAttributedString *> *)attributedStrings
atPoint:(NSPoint)initialPoint
origin:(VT100GridCoord)initialOrigin
positions:(CTVector(CGFloat) *)positions
inContext:(CGContextRef)ctx
backgroundColor:(NSColor *)backgroundColor {
NSPoint point = initialPoint;
VT100GridCoord origin = initialOrigin;
NSInteger start = 0;
for (NSAttributedString *singlePartAttributedString in attributedStrings) {
CGFloat *subpositions = CTVectorElementsFromIndex(positions, start);
start += singlePartAttributedString.length;
CGFloat width =
[self drawSinglePartAttributedString:singlePartAttributedString
atPoint:point
origin:origin
positions:subpositions
inContext:ctx
backgroundColor:backgroundColor];
// [[NSColor colorWithRed:arc4random_uniform(255) / 255.0
// green:arc4random_uniform(255) / 255.0
// blue:arc4random_uniform(255) / 255.0
// alpha:1] set];
// NSFrameRect(NSMakeRect(point.x + [subpositions.firstObject doubleValue], point.y, width, _cellSize.height));
origin.x += round(width / _cellSize.width);
}
}
- (void)drawBoxDrawingCharacter:(unichar)theCharacter withAttributes:(NSDictionary *)attributes at:(NSPoint)pos {
NSGraphicsContext *ctx = [NSGraphicsContext currentContext];
[ctx saveGraphicsState];
NSAffineTransform *transform = [NSAffineTransform transform];
[transform translateXBy:pos.x yBy:pos.y];
[transform concat];
for (NSBezierPath *path in [iTermBoxDrawingBezierCurveFactory bezierPathsForBoxDrawingCode:theCharacter
cellSize:_cellSize]) {
NSColor *color = attributes[NSForegroundColorAttributeName];
[color set];
[path stroke];
}
[ctx restoreGraphicsState];
}
#warning This should return a number of cells, not a number of points.
- (CGFloat)drawSinglePartAttributedString:(NSAttributedString *)attributedString
atPoint:(NSPoint)point
origin:(VT100GridCoord)origin
positions:(CGFloat *)positions
inContext:(CGContextRef)ctx
backgroundColor:(NSColor *)backgroundColor {
NSDictionary *attributes = [attributedString attributesAtIndex:0 effectiveRange:nil];
if (attributes[iTermImageCodeAttribute]) {
// Handle cells that are part of an image.
VT100GridCoord originInImage = VT100GridCoordMake([attributes[iTermImageColumnAttribute] intValue],
[attributes[iTermImageLineAttribute] intValue]);
[self drawImageWithCode:[attributes[iTermImageCodeAttribute] shortValue]
origin:origin
length:attributedString.length
atPoint:point
originInImage:originInImage];
return _cellSize.width * attributedString.length;
} else if ([attributes[iTermIsBoxDrawingAttribute] boolValue]) {
// Special box-drawing cells don't use the font so they look prettier.
[attributedString.string enumerateComposedCharacters:^(NSRange range, unichar simple, NSString *complexString, BOOL *stop) {
NSPoint p = NSMakePoint(point.x + positions[range.location], point.y);
[self drawBoxDrawingCharacter:simple
withAttributes:[attributedString attributesAtIndex:range.location
effectiveRange:nil]
at:p];
}];
return _cellSize.width * attributedString.length;