/
PTYTextView.m
7185 lines (6301 loc) · 280 KB
/
PTYTextView.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
#import "PTYTextView.h"
#import "AsyncHostLookupController.h"
#import "CharacterRun.h"
#import "CharacterRunInline.h"
#import "charmaps.h"
#import "FileTransferManager.h"
#import "FontSizeEstimator.h"
#import "FutureMethods.h"
#import "FutureMethods.h"
#import "ITAddressBookMgr.h"
#import "iTerm.h"
#import "iTermAdvancedSettingsModel.h"
#import "iTermApplicationDelegate.h"
#import "iTermAltScreenMouseScrollInferer.h"
#import "iTermBadgeLabel.h"
#import "iTermColorMap.h"
#import "iTermController.h"
#import "iTermCPS.h"
#import "iTermExpose.h"
#import "iTermFindCursorView.h"
#import "iTermFindOnPageHelper.h"
#import "iTermImageInfo.h"
#import "iTermLaunchServices.h"
#import "iTermMouseCursor.h"
#import "iTermNSKeyBindingEmulator.h"
#import "iTermPreferences.h"
#import "iTermPrintAccessoryViewController.h"
#import "iTermQuickLookController.h"
#import "iTermSelection.h"
#import "iTermSelectionScrollHelper.h"
#import "iTermShellHistoryController.h"
#import "iTermTextDrawingHelper.h"
#import "iTermTextExtractor.h"
#import "iTermTextViewAccessibilityHelper.h"
#import "iTermWebViewWrapperViewController.h"
#import "iTermWarning.h"
#import "MovePaneController.h"
#import "MovingAverage.h"
#import "NSColor+iTerm.h"
#import "NSData+iTerm.h"
#import "NSEvent+iTerm.h"
#import "NSFileManager+iTerm.h"
#import "NSImage+iTerm.h"
#import "NSMutableAttributedString+iTerm.h"
#import "NSPasteboard+iTerm.h"
#import "NSStringITerm.h"
#import "NSWindow+PSM.h"
#import "PasteboardHistory.h"
#import "PointerController.h"
#import "PointerPrefsController.h"
#import "PreferencePanel.h"
#import "PTYNoteView.h"
#import "PTYNoteViewController.h"
#import "PTYScrollView.h"
#import "PTYTab.h"
#import "PTYTask.h"
#import "RegexKitLite.h"
#import "SCPPath.h"
#import "SearchResult.h"
#import "SmartMatch.h"
#import "SmartSelectionController.h"
#import "SolidColorView.h"
#import "ThreeFingerTapGestureRecognizer.h"
#import "URLAction.h"
#import "VT100RemoteHost.h"
#import "VT100ScreenMark.h"
#import "WindowControllerInterface.h"
#import <CoreServices/CoreServices.h>
#import <QuartzCore/QuartzCore.h>
#include <math.h>
#include <sys/time.h>
#import <WebKit/WebKit.h>
static const int kMaxSelectedTextLengthForCustomActions = 400;
// This defines the fraction of a character's width on its right side that is used to
// select the NEXT character.
// | A rightward drag beginning left of the bar selects G.
// <-> kCharWidthFractionOffset * charWidth
// <-------> Character width
// .-----. . :
// ; : :
// : : :
// : ---- :------:
// ' : : :
// `-----' : :
static const double kCharWidthFractionOffset = 0.35;
static const NSUInteger kDragPaneModifiers = (NSAlternateKeyMask | NSCommandKeyMask | NSShiftKeyMask);
static const NSUInteger kRectangularSelectionModifiers = (NSCommandKeyMask | NSAlternateKeyMask);
static const NSUInteger kRectangularSelectionModifierMask = (kRectangularSelectionModifiers | NSControlKeyMask);
// Notifications posted when hostname lookups finish. Notifications are used to
// avoid dangling references.
static NSString *const kHostnameLookupFailed = @"kHostnameLookupFailed";
static NSString *const kHostnameLookupSucceeded = @"kHostnameLookupSucceeded";
static PTYTextView *gCurrentKeyEventTextView; // See comment in -keyDown:
// Minimum distance that the mouse must move before a cmd+drag will be
// recognized as a drag.
static const int kDragThreshold = 3;
@interface PTYTextView () <
iTermAltScreenMouseScrollInfererDelegate,
iTermTextViewAccessibilityHelperDelegate,
iTermTextDrawingHelperDelegate,
iTermFindCursorViewDelegate,
iTermFindOnPageHelperDelegate,
iTermIndicatorsHelperDelegate,
iTermSelectionDelegate,
iTermSelectionScrollHelperDelegate,
NSDraggingSource,
NSMenuDelegate>
// Set the hostname this view is currently waiting for AsyncHostLookupController to finish looking
// up.
@property(nonatomic, copy) NSString *currentUnderlineHostname;
@property(nonatomic, retain) iTermSelection *selection;
@property(nonatomic, retain) iTermSemanticHistoryController *semanticHistoryController;
@property(nonatomic, retain) iTermFindCursorView *findCursorView;
@property(nonatomic, retain) NSWindow *findCursorWindow; // For find-cursor animation
@property(nonatomic, retain) iTermQuickLookController *quickLookController;
// Set when a context menu opens, nilled when it closes. If the data source changes between when we
// ask the context menu to open and when the main thread enters a tracking runloop, the text under
// the selection can change. We want to respect what we show while the context menu is open.
// See issue 4048.
@property(nonatomic, copy) NSString *savedSelectedText;
@end
@implementation PTYTextView {
// -refresh does not want to be reentrant.
BOOL _inRefresh;
// geometry
double _lineHeight;
double _charWidth;
double _charWidthWithoutSpacing;
double _charHeightWithoutSpacing;
// NSTextInputClient support
// When an event is passed to -handleEvent, it may get dispatched to -insertText:replacementRange:
// or -doCommandBySelector:. If one of these methods processes the input by sending it to the
// delegate then this will be set to YES to prevent it from being handled twice.
BOOL _keyPressHandled;
// This is used by the experimental feature guarded by [iTermAdvancedSettingsModel experimentalKeyHandling].
// Indicates if marked text existed before invoking -handleEvent: for a keypress. If the
// input method handles the keypress and causes the IME to finish then the keypress must not
// be passed to the delegate. -insertText:replacementRange: and -doCommandBySelector: need to
// know if marked text existed prior to -handleEvent so they can avoid passing the event to the
// delegate in this case.
BOOL _hadMarkedTextBeforeHandlingKeypressEvent;
NSDictionary *_markedTextAttributes;
PTYFontInfo *_primaryFont;
PTYFontInfo *_secondaryFont; // non-ascii font, only used if self.useNonAsciiFont is set.
BOOL _mouseDown;
BOOL _mouseDragged;
BOOL _mouseDownOnSelection;
BOOL _mouseDownOnImage;
iTermImageInfo *_imageBeingClickedOn;
NSEvent *_mouseDownEvent;
// blinking cursor
NSTimeInterval _timeOfLastBlink;
// Was the last pressed key a "repeat" where the key is held down?
BOOL _keyIsARepeat;
// Previous tracking rect to avoid expensive calls to addTrackingRect.
NSRect _trackingRect;
// Helps with "selection scroll"
iTermSelectionScrollHelper *_selectionScrollHelper;
// Helps drawing text and background.
iTermTextDrawingHelper *_drawingHelper;
// Last position that accessibility was read up to.
int _lastAccessibilityCursorX;
int _lastAccessibiltyAbsoluteCursorY;
BOOL _changedSinceLastExpose;
// Works around an apparent OS bug where we get drag events without a mousedown.
BOOL dragOk_;
// Flag to make sure a Semantic History drag check is only one once per drag
BOOL _semanticHistoryDragged;
// Saves the monotonically increasing event number of a first-mouse click, which disallows
// selection.
NSInteger _firstMouseEventNumber;
// Number of fingers currently down (only valid if three finger click
// emulates middle button)
int _numTouches;
// If true, ignore the next mouse up because it's due to a three finger
// mouseDown.
BOOL _mouseDownIsThreeFingerClick;
PointerController *pointer_;
NSCursor *cursor_;
// True while the context menu is being opened.
BOOL openingContextMenu_;
// Detects three finger taps (as opposed to clicks).
ThreeFingerTapGestureRecognizer *threeFingerTapGestureRecognizer_;
// Position of cursor last time we looked. Since the cursor might move around a lot between
// calls to -updateDirtyRects without making any changes, we only redraw the old and new cursor
// positions.
VT100GridAbsCoord _previousCursorCoord;
// Point clicked, valid only during -validateMenuItem and calls made from
// the context menu and if x and y are nonnegative.
VT100GridCoord _validationClickPoint;
iTermSelection *_oldSelection;
// The most recent mouse-down was a "first mouse" (activated the window).
BOOL _mouseDownWasFirstMouse;
// Size of the documentVisibleRect when the badge was set.
NSSize _badgeDocumentVisibleRectSize;
iTermIndicatorsHelper *_indicatorsHelper;
// Show a background indicator when in broadcast input mode
BOOL _showStripesWhenBroadcastingInput;
iTermFindOnPageHelper *_findOnPageHelper;
iTermTextViewAccessibilityHelper *_accessibilityHelper;
iTermBadgeLabel *_badgeLabel;
NSPoint _mouseLocationToRefuseFirstResponderAt;
// Number of times -setalKeyFocus has been called since the last time it
// was released with releaseKeyFocus.
int _keyFocusStolenCount;
iTermNSKeyBindingEmulator *_keyBindingEmulator;
// Detects when the user is trying to scroll in alt screen with the scroll wheel.
iTermAltScreenMouseScrollInferer *_altScreenMouseScrollInferer;
}
- (instancetype)initWithFrame:(NSRect)frameRect {
// Must call initWithFrame:colorMap:.
assert(false);
}
- (instancetype)initWithFrame:(NSRect)aRect colorMap:(iTermColorMap *)colorMap {
self = [super initWithFrame:aRect];
if (self) {
[self resetMouseLocationToRefuseFirstResponderAt];
_drawingHelper = [[iTermTextDrawingHelper alloc] init];
_drawingHelper.delegate = self;
_colorMap = [colorMap retain];
_colorMap.delegate = self;
_drawingHelper.colorMap = colorMap;
_firstMouseEventNumber = -1;
[self updateMarkedTextAttributes];
_drawingHelper.cursorVisible = YES;
_selection = [[iTermSelection alloc] init];
_selection.delegate = self;
_oldSelection = [_selection copy];
_drawingHelper.underlineRange =
VT100GridWindowedRangeMake(VT100GridCoordRangeMake(-1, -1, -1, -1), 0, 0);
_timeOfLastBlink = [NSDate timeIntervalSinceReferenceDate];
[[self window] useOptimizedDrawing:YES];
// register for drag and drop
[self registerForDraggedTypes: [NSArray arrayWithObjects:
NSFilenamesPboardType,
NSStringPboardType,
nil]];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(useBackgroundIndicatorChanged:)
name:kUseBackgroundPatternIndicatorChangedNotification
object:nil];
[self useBackgroundIndicatorChanged:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(_settingsChanged:)
name:kRefreshTerminalNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(_pointerSettingsChanged:)
name:kPointerPrefsChangedNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(flagsChangedNotification:)
name:@"iTermFlagsChanged"
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(hostnameLookupFailed:)
name:kHostnameLookupFailed
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(hostnameLookupSucceeded:)
name:kHostnameLookupSucceeded
object:nil];
_semanticHistoryController = [[iTermSemanticHistoryController alloc] init];
_semanticHistoryController.delegate = self;
_semanticHistoryDragged = NO;
pointer_ = [[PointerController alloc] init];
pointer_.delegate = self;
_primaryFont = [[PTYFontInfo alloc] init];
_secondaryFont = [[PTYFontInfo alloc] init];
if ([pointer_ viewShouldTrackTouches]) {
DLog(@"Begin tracking touches in view %@", self);
[self setAcceptsTouchEvents:YES];
[self setWantsRestingTouches:YES];
if ([self useThreeFingerTapGestureRecognizer]) {
threeFingerTapGestureRecognizer_ =
[[ThreeFingerTapGestureRecognizer alloc] initWithTarget:self
selector:@selector(threeFingerTap:)];
}
}
[self viewDidChangeBackingProperties];
_indicatorsHelper = [[iTermIndicatorsHelper alloc] init];
_indicatorsHelper.delegate = self;
_selectionScrollHelper = [[iTermSelectionScrollHelper alloc] init];
_selectionScrollHelper.delegate = self;
_findOnPageHelper = [[iTermFindOnPageHelper alloc] init];
_findOnPageHelper.delegate = self;
_accessibilityHelper = [[iTermTextViewAccessibilityHelper alloc] init];
_accessibilityHelper.delegate = self;
_badgeLabel = [[iTermBadgeLabel alloc] init];
_keyBindingEmulator = [[iTermNSKeyBindingEmulator alloc] init];
_altScreenMouseScrollInferer = [[iTermAltScreenMouseScrollInferer alloc] init];
_altScreenMouseScrollInferer.delegate = self;
}
return self;
}
- (void)removeAllTrackingAreas {
while (self.trackingAreas.count) {
[self removeTrackingArea:self.trackingAreas[0]];
}
}
- (void)dealloc {
[_selection release];
[_oldSelection release];
[_smartSelectionRules release];
[_mouseDownEvent release];
_mouseDownEvent = nil;
[self removeAllTrackingAreas];
if ([self isFindingCursor]) {
[self.findCursorWindow close];
}
[_findCursorWindow release];
[[NSNotificationCenter defaultCenter] removeObserver:self];
_colorMap.delegate = nil;
[_colorMap release];
[_primaryFont release];
[_secondaryFont release];
[_markedTextAttributes release];
[_semanticHistoryController release];
[pointer_ release];
[cursor_ release];
[threeFingerTapGestureRecognizer_ disconnectTarget];
[threeFingerTapGestureRecognizer_ release];
if (self.currentUnderlineHostname) {
[[AsyncHostLookupController sharedInstance] cancelRequestForHostname:self.currentUnderlineHostname];
}
[_currentUnderlineHostname release];
_indicatorsHelper.delegate = nil;
[_indicatorsHelper release];
_selectionScrollHelper.delegate = nil;
[_selectionScrollHelper release];
_findOnPageHelper.delegate = nil;
[_findOnPageHelper release];
[_drawingHook release];
_drawingHelper.delegate = nil;
[_drawingHelper release];
[_accessibilityHelper release];
[_badgeLabel release];
[_quickLookController close];
[_quickLookController release];
[_savedSelectedText release];
[_keyBindingEmulator release];
[_altScreenMouseScrollInferer release];
[super dealloc];
}
- (NSString *)description {
return [NSString stringWithFormat:@"<PTYTextView: %p frame=%@ visibleRect=%@ dataSource=%@ delegate=%@ window=%@>",
self,
[NSValue valueWithRect:self.frame],
[NSValue valueWithRect:[self visibleRect]],
_dataSource,
_delegate,
self.window];
}
- (BOOL)useThreeFingerTapGestureRecognizer {
// This used to be guarded by [[NSUserDefaults standardUserDefaults] boolForKey:@"ThreeFingerTapEmulatesThreeFingerClick"];
// but I'm going to turn it on by default and see if anyone complains. 12/16/13
return YES;
}
- (void)viewDidChangeBackingProperties {
CGFloat scale = [[[self window] screen] backingScaleFactor];
BOOL isRetina = scale > 1;
_drawingHelper.antiAliasedShift = isRetina ? 0.5 : 0;
_drawingHelper.isRetina = isRetina;
}
- (NSColor *)defaultBackgroundColor {
CGFloat alpha = [self useTransparency] ? 1 - _transparency : 1;
return [[_colorMap processedBackgroundColorForBackgroundColor:[_colorMap colorForKey:kColorMapBackground]] colorWithAlphaComponent:alpha];
}
- (NSColor *)defaultTextColor {
return [_colorMap processedTextColorForTextColor:[_colorMap colorForKey:kColorMapForeground]
overBackgroundColor:[self defaultBackgroundColor]];
}
- (NSColor *)selectionBackgroundColor {
CGFloat alpha = [self useTransparency] ? 1 - _transparency : 1;
return [[_colorMap processedBackgroundColorForBackgroundColor:[_colorMap colorForKey:kColorMapSelection]] colorWithAlphaComponent:alpha];
}
- (NSColor *)selectedTextColor {
return [_colorMap processedTextColorForTextColor:[_colorMap colorForKey:kColorMapSelectedText]
overBackgroundColor:[self selectionBackgroundColor]];
}
- (void)updateMarkedTextAttributes {
// During initialization, this may be called before the non-ascii font is set so we use a system
// font as a placeholder.
NSDictionary *theAttributes =
@{ NSBackgroundColorAttributeName: [self defaultBackgroundColor],
NSForegroundColorAttributeName: [self defaultTextColor],
NSFontAttributeName: self.nonAsciiFont ?: [NSFont systemFontOfSize:12],
NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle | NSUnderlineByWordMask) };
[self setMarkedTextAttributes:theAttributes];
}
- (void)sendFakeThreeFingerClickDown:(BOOL)isDown basedOnEvent:(NSEvent *)event {
NSEvent *fakeEvent = isDown ? [event mouseDownEventFromGesture] : [event mouseUpEventFromGesture];
int saved = _numTouches;
_numTouches = 3;
if (isDown) {
DLog(@"Emulate three finger click down");
[self mouseDown:fakeEvent];
DLog(@"Returned from mouseDown");
} else {
DLog(@"Emulate three finger click up");
[self mouseUp:fakeEvent];
DLog(@"Returned from mouseDown");
}
DLog(@"Restore numTouches to saved value of %d", saved);
_numTouches = saved;
}
- (void)threeFingerTap:(NSEvent *)ev {
[self sendFakeThreeFingerClickDown:YES basedOnEvent:ev];
[self sendFakeThreeFingerClickDown:NO basedOnEvent:ev];
}
- (void)touchesBeganWithEvent:(NSEvent *)ev {
_numTouches = [[ev touchesMatchingPhase:NSTouchPhaseBegan | NSTouchPhaseStationary
inView:self] count];
[threeFingerTapGestureRecognizer_ touchesBeganWithEvent:ev];
DLog(@"%@ Begin touch. numTouches_ -> %d", self, _numTouches);
}
- (void)touchesEndedWithEvent:(NSEvent *)ev {
_numTouches = [[ev touchesMatchingPhase:NSTouchPhaseStationary
inView:self] count];
[threeFingerTapGestureRecognizer_ touchesEndedWithEvent:ev];
DLog(@"%@ End touch. numTouches_ -> %d", self, _numTouches);
}
- (void)touchesCancelledWithEvent:(NSEvent *)event {
_numTouches = 0;
[threeFingerTapGestureRecognizer_ touchesCancelledWithEvent:event];
DLog(@"%@ Cancel touch. numTouches_ -> %d", self, _numTouches);
}
- (void)refuseFirstResponderAtCurrentMouseLocation {
_mouseLocationToRefuseFirstResponderAt = [NSEvent mouseLocation];
}
- (void)resetMouseLocationToRefuseFirstResponderAt {
_mouseLocationToRefuseFirstResponderAt = NSMakePoint(DBL_MAX, DBL_MAX);
}
- (BOOL)resignFirstResponder {
[_altScreenMouseScrollInferer firstResponderDidChange];
[self removeUnderline];
return YES;
}
- (BOOL)becomeFirstResponder {
[_altScreenMouseScrollInferer firstResponderDidChange];
[_delegate textViewDidBecomeFirstResponder];
return YES;
}
- (void)viewWillMoveToWindow:(NSWindow *)win {
if (!win && [self window]) {
[self removeAllTrackingAreas];
}
[super viewWillMoveToWindow:win];
}
// TODO: Not sure if this is used.
- (BOOL)shouldDrawInsertionPoint
{
return NO;
}
- (BOOL)isFlipped
{
return YES;
}
- (BOOL)isOpaque
{
return YES;
}
- (void)setHighlightCursorLine:(BOOL)highlightCursorLine {
_drawingHelper.highlightCursorLine = highlightCursorLine;
}
- (BOOL)highlightCursorLine {
return _drawingHelper.highlightCursorLine;
}
- (void)setUseNonAsciiFont:(BOOL)useNonAsciiFont {
_drawingHelper.useNonAsciiFont = useNonAsciiFont;
_useNonAsciiFont = useNonAsciiFont;
[self setNeedsDisplay:YES];
[self updateMarkedTextAttributes];
}
- (void)setAntiAlias:(BOOL)asciiAntiAlias nonAscii:(BOOL)nonAsciiAntiAlias {
_drawingHelper.asciiAntiAlias = asciiAntiAlias;
_drawingHelper.nonAsciiAntiAlias = nonAsciiAntiAlias;
[self setNeedsDisplay:YES];
}
- (void)setUseBoldFont:(BOOL)boldFlag {
_useBoldFont = boldFlag;
[self setNeedsDisplay:YES];
}
- (void)setThinStrokes:(iTermThinStrokesSetting)thinStrokes {
_thinStrokes = thinStrokes;
[self setNeedsDisplay:YES];
}
- (void)setUseItalicFont:(BOOL)italicFlag
{
_useItalicFont = italicFlag;
[self setNeedsDisplay:YES];
}
- (void)setUseBrightBold:(BOOL)flag
{
_useBrightBold = flag;
_drawingHelper.useBrightBold = flag;
[self setNeedsDisplay:YES];
}
- (void)setBlinkAllowed:(BOOL)value {
_drawingHelper.blinkAllowed = value;
_blinkAllowed = value;
[self setNeedsDisplay:YES];
}
- (void)setCursorNeedsDisplay {
[self setNeedsDisplayInRect:[self rectWithHalo:[self cursorFrame]]];
}
- (void)setCursorType:(ITermCursorType)value {
_drawingHelper.cursorType = value;
[self setCursorNeedsDisplay];
[self refresh];
}
- (NSDictionary*)markedTextAttributes {
return _markedTextAttributes;
}
- (void)setMarkedTextAttributes:(NSDictionary *)attr
{
[_markedTextAttributes autorelease];
_markedTextAttributes = [attr retain];
}
- (void)updateScrollerForBackgroundColor
{
PTYScroller *scroller = [_delegate textViewVerticalScroller];
NSColor *backgroundColor = [_colorMap colorForKey:kColorMapBackground];
scroller.knobStyle =
[backgroundColor isDark] ? NSScrollerKnobStyleLight : NSScrollerKnobStyleDefault;
}
- (NSFont *)font {
return _primaryFont.font;
}
- (NSFont *)nonAsciiFont {
return _useNonAsciiFont ? _secondaryFont.font : _primaryFont.font;
}
- (NSFont *)nonAsciiFontEvenIfNotUsed {
return _secondaryFont.font;
}
+ (NSSize)charSizeForFont:(NSFont*)aFont horizontalSpacing:(double)hspace verticalSpacing:(double)vspace baseline:(double*)baseline
{
FontSizeEstimator* fse = [FontSizeEstimator fontSizeEstimatorForFont:aFont];
NSSize size = [fse size];
size.width = ceil(size.width * hspace);
size.height = ceil(vspace * ceil(size.height + [aFont leading]));
if (baseline) {
*baseline = [fse baseline];
}
return size;
}
+ (NSSize)charSizeForFont:(NSFont*)aFont horizontalSpacing:(double)hspace verticalSpacing:(double)vspace
{
return [PTYTextView charSizeForFont:aFont horizontalSpacing:hspace verticalSpacing:vspace baseline:nil];
}
- (void)setFont:(NSFont*)aFont
nonAsciiFont:(NSFont *)nonAsciiFont
horizontalSpacing:(double)horizontalSpacing
verticalSpacing:(double)verticalSpacing
{
double baseline;
NSSize sz = [PTYTextView charSizeForFont:aFont
horizontalSpacing:1.0
verticalSpacing:1.0
baseline:&baseline];
_charWidthWithoutSpacing = sz.width;
_charHeightWithoutSpacing = sz.height;
_horizontalSpacing = horizontalSpacing;
_verticalSpacing = verticalSpacing;
self.charWidth = ceil(_charWidthWithoutSpacing * horizontalSpacing);
self.lineHeight = ceil(_charHeightWithoutSpacing * verticalSpacing);
_primaryFont.font = aFont;
_primaryFont.baselineOffset = baseline;
_primaryFont.boldVersion = [_primaryFont computedBoldVersion];
_primaryFont.italicVersion = [_primaryFont computedItalicVersion];
_primaryFont.boldItalicVersion = [_primaryFont computedBoldItalicVersion];
_secondaryFont.font = nonAsciiFont;
_secondaryFont.baselineOffset = baseline;
_secondaryFont.boldVersion = [_secondaryFont computedBoldVersion];
_secondaryFont.italicVersion = [_secondaryFont computedItalicVersion];
_secondaryFont.boldItalicVersion = [_secondaryFont computedBoldItalicVersion];
// Force the secondary font to use the same baseline as the primary font.
_secondaryFont.baselineOffset = _primaryFont.baselineOffset;
if (_secondaryFont.boldVersion) {
if (_primaryFont.boldVersion) {
_secondaryFont.boldVersion.baselineOffset = _primaryFont.boldVersion.baselineOffset;
} else {
_secondaryFont.boldVersion.baselineOffset = _secondaryFont.baselineOffset;
}
}
if (_secondaryFont.italicVersion) {
if (_primaryFont.italicVersion) {
_secondaryFont.italicVersion.baselineOffset = _primaryFont.italicVersion.baselineOffset;
} else {
_secondaryFont.italicVersion.baselineOffset = _secondaryFont.baselineOffset;
}
}
[self updateMarkedTextAttributes];
[self setNeedsDisplay:YES];
NSScrollView* scrollview = [self enclosingScrollView];
[scrollview setLineScroll:[self lineHeight]];
[scrollview setPageScroll:2 * [self lineHeight]];
[self updateNoteViewFrames];
[_delegate textViewFontDidChange];
}
- (void)changeFont:(id)fontManager
{
if ([[[PreferencePanel sharedInstance] window] isVisible]) {
[[PreferencePanel sharedInstance] changeFont:fontManager];
} else if ([[[PreferencePanel sessionsInstance] window] isVisible]) {
[[PreferencePanel sessionsInstance] changeFont:fontManager];
}
}
- (void)setLineHeight:(double)aLineHeight {
_lineHeight = ceil(aLineHeight);
_drawingHelper.cellSize = NSMakeSize(_charWidth, _lineHeight);
_drawingHelper.cellSizeWithoutSpacing = NSMakeSize(_charWidthWithoutSpacing, _charHeightWithoutSpacing);
}
- (void)setCharWidth:(double)width {
_charWidth = ceil(width);
_drawingHelper.cellSize = NSMakeSize(_charWidth, _lineHeight);
_drawingHelper.cellSizeWithoutSpacing = NSMakeSize(_charWidthWithoutSpacing, _charHeightWithoutSpacing);
}
- (void)toggleShowTimestamps:(id)sender {
_drawingHelper.showTimestamps = !_drawingHelper.showTimestamps;
[self setNeedsDisplay:YES];
}
- (NSRect)scrollViewContentSize {
NSRect r = NSMakeRect(0, 0, 0, 0);
r.size = [[self enclosingScrollView] contentSize];
return r;
}
// Number of extra lines below the last line of text that are always the background color.
// This is 2 except for just after the frame has changed and things are resizing.
- (double)excess {
NSRect visible = [self scrollViewContentSize];
visible.size.height -= VMARGIN * 2; // Height without top and bottom margins.
int rows = visible.size.height / _lineHeight;
double usablePixels = rows * _lineHeight;
return MAX(visible.size.height - usablePixels + VMARGIN, VMARGIN); // Never have less than VMARGIN excess, but it can be more (if another tab has a bigger font)
}
- (CGFloat)desiredHeight {
// Force the height to always be correct
return ([_dataSource numberOfLines] * _lineHeight +
[self excess] +
_drawingHelper.numberOfIMELines * _lineHeight);
}
- (void)setFrameSize:(NSSize)newSize {
[super setFrameSize:newSize];
[self recomputeBadgeLabel];
}
// This exists to work around an apparent OS bug described in issue 2690. Under some circumstances
// (which I cannot reproduce) the key window will be an NSToolbarFullScreenWindow and the PTYWindow
// will be one of the main windows. NSToolbarFullScreenWindow doesn't appear to handle keystrokes,
// so they fall through to the main window. We'd like the cursor to blink and have other key-
// window behaviors in this case.
- (BOOL)isInKeyWindow
{
if ([[self window] isKeyWindow]) {
DLog(@"%@ is key window", self);
return YES;
}
NSWindow *theKeyWindow = [[NSApplication sharedApplication] keyWindow];
if (!theKeyWindow) {
DLog(@"There is no key window");
return NO;
}
if (!strcmp("NSToolbarFullScreenWindow", object_getClassName(theKeyWindow))) {
DLog(@"key window is a NSToolbarFullScreenWindow, using my main window status of %d as key status",
(int)self.window.isMainWindow);
return [[self window] isMainWindow];
}
return NO;
}
- (BOOL)isCursorBlinking {
if (_blinkingCursor &&
[self isInKeyWindow] &&
[_delegate textViewIsActiveSession]) {
return YES;
} else {
return NO;
}
}
- (BOOL)_isTextBlinking
{
int width = [_dataSource width];
int lineStart = ([self visibleRect].origin.y + VMARGIN) / _lineHeight; // add VMARGIN because stuff under top margin isn't visible.
int lineEnd = ceil(([self visibleRect].origin.y + [self visibleRect].size.height - [self excess]) / _lineHeight);
if (lineStart < 0) {
lineStart = 0;
}
if (lineEnd > [_dataSource numberOfLines]) {
lineEnd = [_dataSource numberOfLines];
}
for (int y = lineStart; y < lineEnd; y++) {
screen_char_t* theLine = [_dataSource getLineAtIndex:y];
for (int x = 0; x < width; x++) {
if (theLine[x].blink) {
return YES;
}
}
}
return NO;
}
- (BOOL)_isAnythingBlinking {
return [self isCursorBlinking] || (_blinkAllowed && [self _isTextBlinking]);
}
- (void)handleScrollbackOverflow:(int)scrollbackOverflow userScroll:(BOOL)userScroll {
// Keep correct selection highlighted
[_selection moveUpByLines:scrollbackOverflow];
[_oldSelection moveUpByLines:scrollbackOverflow];
// Keep the user's current scroll position.
NSScrollView *scrollView = [self enclosingScrollView];
BOOL canSkipRedraw = NO;
if (userScroll) {
NSRect scrollRect = [self visibleRect];
double amount = [scrollView verticalLineScroll] * scrollbackOverflow;
scrollRect.origin.y -= amount;
if (scrollRect.origin.y < 0) {
scrollRect.origin.y = 0;
} else {
// No need to redraw the whole screen because nothing is
// changing because of the scroll.
canSkipRedraw = YES;
}
[self scrollRectToVisible:scrollRect];
}
// NOTE: I used to use scrollRect:by: here, and it is faster, but it is
// absolutely a lost cause as far as correctness goes. When drawRect
// gets called it needs to take that scrolling (which would happen
// immediately when scrollRect:by: gets called) into account. Good luck
// getting that right. I don't *think* it's a meaningful performance issue.
// Because of a bug, we were always drawing the whole screen anyway. And if
// the screen has scrolled by less than its height, input is coming in
// slowly anyway.
if (!canSkipRedraw) {
[self setNeedsDisplay:YES];
}
// Move subviews up
[self updateNoteViewFrames];
NSAccessibilityPostNotification(self, NSAccessibilityRowCountChangedNotification);
}
// Update accessibility, to be called periodically.
- (void)refreshAccessibility {
NSAccessibilityPostNotification(self, NSAccessibilityValueChangedNotification);
long long absCursorY = ([_dataSource cursorY] + [_dataSource numberOfLines] +
[_dataSource totalScrollbackOverflow] - [_dataSource height]);
if ([_dataSource cursorX] != _lastAccessibilityCursorX ||
absCursorY != _lastAccessibiltyAbsoluteCursorY) {
NSAccessibilityPostNotification(self, NSAccessibilitySelectedTextChangedNotification);
NSAccessibilityPostNotification(self, NSAccessibilitySelectedRowsChangedNotification);
NSAccessibilityPostNotification(self, NSAccessibilitySelectedColumnsChangedNotification);
_lastAccessibilityCursorX = [_dataSource cursorX];
_lastAccessibiltyAbsoluteCursorY = absCursorY;
if (UAZoomEnabled()) {
CGRect viewRect = NSRectToCGRect(
[self.window convertRectToScreen:[self convertRect:[self visibleRect] toView:nil]]);
CGRect selectedRect = NSRectToCGRect(
[self.window convertRectToScreen:[self convertRect:[self cursorFrame] toView:nil]]);
viewRect.origin.y = ([[NSScreen mainScreen] frame].size.height -
(viewRect.origin.y + viewRect.size.height));
selectedRect.origin.y = ([[NSScreen mainScreen] frame].size.height -
(selectedRect.origin.y + selectedRect.size.height));
UAZoomChangeFocus(&viewRect, &selectedRect, kUAZoomFocusTypeInsertionPoint);
}
}
}
// This is called periodically. It updates the frame size, scrolls if needed, ensures selections
// and subviews are positioned correctly in case things scrolled
//
// Returns YES if blinking text or cursor was found.
- (BOOL)refresh {
DLog(@"PTYTextView refresh called with delegate %@", _delegate);
if (_dataSource == nil || _inRefresh) {
return YES;
}
// Get the number of lines that have disappeared if scrollback buffer is full.
int scrollbackOverflow = [_dataSource scrollbackOverflow];
[_dataSource resetScrollbackOverflow];
[_delegate textViewResizeFrameIfNeeded];
// Perform adjustments if lines were lost from the head of the buffer.
BOOL userScroll = [(PTYScroller*)([[self enclosingScrollView] verticalScroller]) userScroll];
if (scrollbackOverflow > 0) {
// -selectionDidChange might get called here, which calls -refresh.
// Keeping this function safely reentrant is just too difficult.
_inRefresh = YES;
[self handleScrollbackOverflow:scrollbackOverflow userScroll:userScroll];
_inRefresh = NO;
}
// Scroll to the bottom if needed.
if (!userScroll) {
[self scrollEnd];
}
// Update accessibility.
[self refreshAccessibility];
if ([[self subviews] count]) {
// TODO: Why update notes not in this textview?
[[NSNotificationCenter defaultCenter] postNotificationName:PTYNoteViewControllerShouldUpdatePosition
object:nil];
// Not sure why this is needed, but for some reason this view draws over its subviews.
for (NSView *subview in [self subviews]) {
[subview setNeedsDisplay:YES];
}
}
// See if any characters are dirty and mark them as needing to be redrawn.
// Return if anything was found to be blinking.
return [self updateDirtyRects] || [self isCursorBlinking];
}
- (void)setNeedsDisplayOnLine:(int)line
{
[self setNeedsDisplayOnLine:line inRange:VT100GridRangeMake(0, _dataSource.width)];
}
// Overrides an NSView method.
- (NSRect)adjustScroll:(NSRect)proposedVisibleRect {
proposedVisibleRect.origin.y = (int)(proposedVisibleRect.origin.y / _lineHeight + 0.5) * _lineHeight;
return proposedVisibleRect;
}
- (void)scrollLineUp:(id)sender {
[self scrollBy:-[self.enclosingScrollView verticalLineScroll]];
}
- (void)scrollLineDown:(id)sender {
[self scrollBy:[self.enclosingScrollView verticalLineScroll]];
}
- (void)scrollBy:(CGFloat)deltaY {
NSScrollView *scrollView = self.enclosingScrollView;
NSRect rect = scrollView.documentVisibleRect;
NSPoint point;
point = rect.origin;
point.y += deltaY;
[scrollView.documentView scrollPoint:point];
}
- (CGFloat)pageScrollHeight {
NSRect scrollRect = [self visibleRect];
return scrollRect.size.height - [[self enclosingScrollView] verticalPageScroll];
}
- (void)scrollPageUp:(id)sender {
[self scrollBy:-self.pageScrollHeight];
}
- (void)scrollPageDown:(id)sender {
[self scrollBy:self.pageScrollHeight];
}
- (void)scrollHome {
NSRect scrollRect;
scrollRect = [self visibleRect];