-
Notifications
You must be signed in to change notification settings - Fork 29.7k
/
terminalInstance.ts
1811 lines (1603 loc) · 72.7 KB
/
terminalInstance.ts
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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as path from 'vs/base/common/path';
import * as dom from 'vs/base/browser/dom';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { debounce } from 'vs/base/common/decorators';
import { Emitter, Event } from 'vs/base/common/event';
import { KeyCode } from 'vs/base/common/keyCodes';
import { IDisposable, dispose, Disposable } from 'vs/base/common/lifecycle';
import { TabFocus } from 'vs/editor/common/config/commonEditorConfig';
import * as nls from 'vs/nls';
import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService';
import { ConfigurationTarget, IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { ILogService } from 'vs/platform/log/common/log';
import { INotificationService, IPromptChoice, Severity } from 'vs/platform/notification/common/notification';
import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { activeContrastBorder, scrollbarSliderActiveBackground, scrollbarSliderBackground, scrollbarSliderHoverBackground } from 'vs/platform/theme/common/colorRegistry';
import { ICssStyleCollector, IColorTheme, IThemeService, registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { PANEL_BACKGROUND, SIDE_BAR_BACKGROUND } from 'vs/workbench/common/theme';
import { TerminalWidgetManager } from 'vs/workbench/contrib/terminal/browser/widgets/widgetManager';
import { ITerminalProcessManager, KEYBINDING_CONTEXT_TERMINAL_TEXT_SELECTED, NEVER_MEASURE_RENDER_TIME_STORAGE_KEY, ProcessState, TERMINAL_VIEW_ID, KEYBINDING_CONTEXT_TERMINAL_A11Y_TREE_FOCUS, INavigationMode, TitleEventSource, DEFAULT_COMMANDS_TO_SKIP_SHELL, TERMINAL_CREATION_COMMANDS, KEYBINDING_CONTEXT_TERMINAL_ALT_BUFFER_ACTIVE, SUGGESTED_RENDERER_TYPE, ITerminalProfileResolverService } from 'vs/workbench/contrib/terminal/common/terminal';
import { ansiColorIdentifiers, TERMINAL_BACKGROUND_COLOR, TERMINAL_CURSOR_BACKGROUND_COLOR, TERMINAL_CURSOR_FOREGROUND_COLOR, TERMINAL_FOREGROUND_COLOR, TERMINAL_SELECTION_BACKGROUND_COLOR } from 'vs/workbench/contrib/terminal/common/terminalColorRegistry';
import { TerminalConfigHelper } from 'vs/workbench/contrib/terminal/browser/terminalConfigHelper';
import { TerminalLinkManager } from 'vs/workbench/contrib/terminal/browser/links/terminalLinkManager';
import { IAccessibilityService } from 'vs/platform/accessibility/common/accessibility';
import { ITerminalInstanceService, ITerminalInstance, ITerminalExternalLinkProvider } from 'vs/workbench/contrib/terminal/browser/terminal';
import { TerminalProcessManager } from 'vs/workbench/contrib/terminal/browser/terminalProcessManager';
import type { Terminal as XTermTerminal, IBuffer, ITerminalAddon, RendererType } from 'xterm';
import type { SearchAddon, ISearchOptions } from 'xterm-addon-search';
import type { Unicode11Addon } from 'xterm-addon-unicode11';
import type { WebglAddon } from 'xterm-addon-webgl';
import { CommandTrackerAddon } from 'vs/workbench/contrib/terminal/browser/addons/commandTrackerAddon';
import { NavigationModeAddon } from 'vs/workbench/contrib/terminal/browser/addons/navigationModeAddon';
import { XTermCore } from 'vs/workbench/contrib/terminal/browser/xterm-private';
import { IEditorOptions } from 'vs/editor/common/config/editorOptions';
import { IViewsService, IViewDescriptorService, ViewContainerLocation } from 'vs/workbench/common/views';
import { EnvironmentVariableInfoWidget } from 'vs/workbench/contrib/terminal/browser/widgets/environmentVariableInfoWidget';
import { TerminalLaunchHelpAction } from 'vs/workbench/contrib/terminal/browser/terminalActions';
import { TypeAheadAddon } from 'vs/workbench/contrib/terminal/browser/terminalTypeAheadAddon';
import { BrowserFeatures } from 'vs/base/browser/canIUse';
import { IPreferencesService } from 'vs/workbench/services/preferences/common/preferences';
import { IEnvironmentVariableInfo } from 'vs/workbench/contrib/terminal/common/environmentVariable';
import { IProcessDataEvent, IShellLaunchConfig, ITerminalDimensionsOverride, ITerminalLaunchError, TerminalShellType } from 'vs/platform/terminal/common/terminal';
import { IProductService } from 'vs/platform/product/common/productService';
import { formatMessageForTerminal } from 'vs/workbench/contrib/terminal/common/terminalStrings';
import { AutoOpenBarrier } from 'vs/base/common/async';
import { Codicon, iconRegistry } from 'vs/base/common/codicons';
import { ITerminalStatusList, TerminalStatus, TerminalStatusList } from 'vs/workbench/contrib/terminal/browser/terminalStatusList';
import { IQuickInputService, IQuickPickItem } from 'vs/platform/quickinput/common/quickInput';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { isMacintosh, isWindows, OperatingSystem, OS } from 'vs/base/common/platform';
// How long in milliseconds should an average frame take to render for a notification to appear
// which suggests the fallback DOM-based renderer
const SLOW_CANVAS_RENDER_THRESHOLD = 50;
const NUMBER_OF_FRAMES_TO_MEASURE = 20;
const enum Constants {
/**
* The maximum amount of milliseconds to wait for a container before starting to create the
* terminal process. This period helps ensure the terminal has good initial dimensions to work
* with if it's going to be a foreground terminal.
*/
WaitForContainerThreshold = 100
}
let xtermConstructor: Promise<typeof XTermTerminal> | undefined;
interface ICanvasDimensions {
width: number;
height: number;
}
interface IGridDimensions {
cols: number;
rows: number;
}
export class TerminalInstance extends Disposable implements ITerminalInstance {
private static readonly EOL_REGEX = /\r?\n/g;
private static _lastKnownCanvasDimensions: ICanvasDimensions | undefined;
private static _lastKnownGridDimensions: IGridDimensions | undefined;
private static _instanceIdCounter = 1;
private _processManager!: ITerminalProcessManager;
private _pressAnyKeyToCloseListener: IDisposable | undefined;
private _instanceId: number;
private _latestXtermWriteData: number = 0;
private _latestXtermParseData: number = 0;
private _isExiting: boolean;
private _hadFocusOnExit: boolean;
private _isVisible: boolean;
private _isDisposed: boolean;
private _exitCode: number | undefined;
private _skipTerminalCommands: string[];
private _shellType: TerminalShellType;
private _title: string = '';
private _wrapperElement: (HTMLElement & { xterm?: XTermTerminal }) | undefined;
private _xterm: XTermTerminal | undefined;
private _xtermCore: XTermCore | undefined;
private _xtermTypeAhead: TypeAheadAddon | undefined;
private _xtermSearch: SearchAddon | undefined;
private _xtermUnicode11: Unicode11Addon | undefined;
private _xtermElement: HTMLDivElement | undefined;
private _terminalHasTextContextKey: IContextKey<boolean>;
private _terminalA11yTreeFocusContextKey: IContextKey<boolean>;
private _cols: number = 0;
private _rows: number = 0;
private _dimensionsOverride: ITerminalDimensionsOverride | undefined;
private _xtermReadyPromise: Promise<XTermTerminal>;
private _titleReadyPromise: Promise<string>;
private _titleReadyComplete: ((title: string) => any) | undefined;
private _areLinksReady: boolean = false;
private _initialDataEvents: string[] | undefined = [];
private _containerReadyBarrier: AutoOpenBarrier;
private _messageTitleDisposable: IDisposable | undefined;
private _widgetManager: TerminalWidgetManager = this._instantiationService.createInstance(TerminalWidgetManager);
private _linkManager: TerminalLinkManager | undefined;
private _environmentInfo: { widget: EnvironmentVariableInfoWidget, disposable: IDisposable } | undefined;
private _webglAddon: WebglAddon | undefined;
private _commandTrackerAddon: CommandTrackerAddon | undefined;
private _navigationModeAddon: INavigationMode & ITerminalAddon | undefined;
private _timeoutDimension: dom.Dimension | undefined;
private hasHadInput: boolean;
public readonly statusList: ITerminalStatusList = new TerminalStatusList();
public disableLayout: boolean;
public get instanceId(): number { return this._instanceId; }
public get cols(): number {
if (this._dimensionsOverride && this._dimensionsOverride.cols) {
if (this._dimensionsOverride.forceExactSize) {
return this._dimensionsOverride.cols;
}
return Math.min(Math.max(this._dimensionsOverride.cols, 2), this._cols);
}
return this._cols;
}
public get rows(): number {
if (this._dimensionsOverride && this._dimensionsOverride.rows) {
if (this._dimensionsOverride.forceExactSize) {
return this._dimensionsOverride.rows;
}
return Math.min(Math.max(this._dimensionsOverride.rows, 2), this._rows);
}
return this._rows;
}
public get maxCols(): number { return this._cols; }
public get maxRows(): number { return this._rows; }
// TODO: Ideally processId would be merged into processReady
public get processId(): number | undefined { return this._processManager.shellProcessId; }
// TODO: How does this work with detached processes?
// TODO: Should this be an event as it can fire twice?
public get processReady(): Promise<void> { return this._processManager.ptyProcessReady; }
public get areLinksReady(): boolean { return this._areLinksReady; }
public get initialDataEvents(): string[] | undefined { return this._initialDataEvents; }
public get exitCode(): number | undefined { return this._exitCode; }
public get title(): string { return this._title; }
public get hadFocusOnExit(): boolean { return this._hadFocusOnExit; }
public get isTitleSetByProcess(): boolean { return !!this._messageTitleDisposable; }
public get shellLaunchConfig(): IShellLaunchConfig { return this._shellLaunchConfig; }
public get shellType(): TerminalShellType { return this._shellType; }
public get commandTracker(): CommandTrackerAddon | undefined { return this._commandTrackerAddon; }
public get navigationMode(): INavigationMode | undefined { return this._navigationModeAddon; }
public get isDisconnected(): boolean { return this._processManager.isDisconnected; }
public get icon(): Codicon { return this._getIcon(); }
private readonly _onExit = new Emitter<number | undefined>();
public get onExit(): Event<number | undefined> { return this._onExit.event; }
private readonly _onDisposed = new Emitter<ITerminalInstance>();
public get onDisposed(): Event<ITerminalInstance> { return this._onDisposed.event; }
private readonly _onFocused = new Emitter<ITerminalInstance>();
public get onFocused(): Event<ITerminalInstance> { return this._onFocused.event; }
private readonly _onProcessIdReady = new Emitter<ITerminalInstance>();
public get onProcessIdReady(): Event<ITerminalInstance> { return this._onProcessIdReady.event; }
private readonly _onLinksReady = new Emitter<ITerminalInstance>();
public get onLinksReady(): Event<ITerminalInstance> { return this._onLinksReady.event; }
private readonly _onTitleChanged = new Emitter<ITerminalInstance>();
public get onTitleChanged(): Event<ITerminalInstance> { return this._onTitleChanged.event; }
private readonly _onData = new Emitter<string>();
public get onData(): Event<string> { return this._onData.event; }
private readonly _onBinary = new Emitter<string>();
public get onBinary(): Event<string> { return this._onBinary.event; }
private readonly _onLineData = new Emitter<string>();
public get onLineData(): Event<string> { return this._onLineData.event; }
private readonly _onRequestExtHostProcess = new Emitter<ITerminalInstance>();
public get onRequestExtHostProcess(): Event<ITerminalInstance> { return this._onRequestExtHostProcess.event; }
private readonly _onDimensionsChanged = new Emitter<void>();
public get onDimensionsChanged(): Event<void> { return this._onDimensionsChanged.event; }
private readonly _onMaximumDimensionsChanged = new Emitter<void>();
public get onMaximumDimensionsChanged(): Event<void> { return this._onMaximumDimensionsChanged.event; }
private readonly _onFocus = new Emitter<ITerminalInstance>();
public get onFocus(): Event<ITerminalInstance> { return this._onFocus.event; }
public constructor(
private readonly _terminalFocusContextKey: IContextKey<boolean>,
private readonly _terminalShellTypeContextKey: IContextKey<string>,
private readonly _terminalAltBufferActiveContextKey: IContextKey<boolean>,
private readonly _configHelper: TerminalConfigHelper,
private _container: HTMLElement | undefined,
private _shellLaunchConfig: IShellLaunchConfig,
@ITerminalInstanceService private readonly _terminalInstanceService: ITerminalInstanceService,
@ITerminalProfileResolverService private readonly _terminalProfileResolverService: ITerminalProfileResolverService,
@IContextKeyService private readonly _contextKeyService: IContextKeyService,
@IKeybindingService private readonly _keybindingService: IKeybindingService,
@INotificationService private readonly _notificationService: INotificationService,
@IPreferencesService private readonly _preferencesService: IPreferencesService,
@IViewsService private readonly _viewsService: IViewsService,
@IInstantiationService private readonly _instantiationService: IInstantiationService,
@IClipboardService private readonly _clipboardService: IClipboardService,
@IThemeService private readonly _themeService: IThemeService,
@IConfigurationService private readonly _configurationService: IConfigurationService,
@ILogService private readonly _logService: ILogService,
@IStorageService private readonly _storageService: IStorageService,
@IAccessibilityService private readonly _accessibilityService: IAccessibilityService,
@IViewDescriptorService private readonly _viewDescriptorService: IViewDescriptorService,
@IProductService private readonly _productService: IProductService,
@IQuickInputService private readonly _quickInputService: IQuickInputService,
@IWorkbenchEnvironmentService workbenchEnvironmentService: IWorkbenchEnvironmentService
) {
super();
this._skipTerminalCommands = [];
this._isExiting = false;
this._hadFocusOnExit = false;
this._isVisible = false;
this._isDisposed = false;
this._instanceId = TerminalInstance._instanceIdCounter++;
this.hasHadInput = false;
this._titleReadyPromise = new Promise<string>(c => {
this._titleReadyComplete = c;
});
this._terminalHasTextContextKey = KEYBINDING_CONTEXT_TERMINAL_TEXT_SELECTED.bindTo(this._contextKeyService);
this._terminalA11yTreeFocusContextKey = KEYBINDING_CONTEXT_TERMINAL_A11Y_TREE_FOCUS.bindTo(this._contextKeyService);
this._terminalAltBufferActiveContextKey = KEYBINDING_CONTEXT_TERMINAL_ALT_BUFFER_ACTIVE.bindTo(this._contextKeyService);
this.disableLayout = false;
this._logService.trace(`terminalInstance#ctor (instanceId: ${this.instanceId})`, this._shellLaunchConfig);
// Resolve just the icon ahead of time so that it shows up immediately in the tabs. This is
// disabled in remote because this needs to be sync and the OS may differ on the remote
// which would result in the wrong profile being selected and the wrong icon being
// permanently attached to the terminal.
if (!this.shellLaunchConfig.executable && !workbenchEnvironmentService.remoteAuthority) {
this._terminalProfileResolverService.resolveIcon(this._shellLaunchConfig, OS);
}
this._initDimensions();
this._createProcessManager();
this._containerReadyBarrier = new AutoOpenBarrier(Constants.WaitForContainerThreshold);
this._xtermReadyPromise = this._createXterm();
this._xtermReadyPromise.then(async () => {
// Wait for a period to allow a container to be ready
await this._containerReadyBarrier.wait();
// Only attach xterm.js to the DOM if the terminal panel has been opened before.
if (_container) {
this._attachToElement(_container);
}
this._createProcess();
});
this.addDisposable(this._configurationService.onDidChangeConfiguration(e => {
if (e.affectsConfiguration('terminal.integrated') || e.affectsConfiguration('editor.fastScrollSensitivity') || e.affectsConfiguration('editor.mouseWheelScrollSensitivity') || e.affectsConfiguration('editor.multiCursorModifier')) {
this.updateConfig();
// HACK: Trigger another async layout to ensure xterm's CharMeasure is ready to use,
// this hack can be removed when https://github.com/xtermjs/xterm.js/issues/702 is
// supported.
this.setVisible(this._isVisible);
}
if (e.affectsConfiguration('terminal.integrated.unicodeVersion')) {
this._updateUnicodeVersion();
}
if (e.affectsConfiguration('editor.accessibilitySupport')) {
this.updateAccessibilitySupport();
}
if (e.affectsConfiguration('terminal.integrated.gpuAcceleration')) {
this._storageService.remove(SUGGESTED_RENDERER_TYPE, StorageScope.GLOBAL);
}
}));
// Clear out initial data events after 10 seconds, hopefully extension hosts are up and
// running at that point.
let initialDataEventsTimeout: number | undefined = window.setTimeout(() => {
initialDataEventsTimeout = undefined;
this._initialDataEvents = undefined;
}, 10000);
this._register({
dispose: () => {
if (initialDataEventsTimeout) {
window.clearTimeout(initialDataEventsTimeout);
}
}
});
}
private _getIcon(): Codicon {
if (this.shellLaunchConfig.icon) {
return iconRegistry.get(this.shellLaunchConfig.icon) || Codicon.terminal;
} else if (this.shellLaunchConfig?.attachPersistentProcess?.icon) {
return iconRegistry.get(this.shellLaunchConfig.attachPersistentProcess.icon) || Codicon.terminal;
}
return Codicon.terminal;
}
public addDisposable(disposable: IDisposable): void {
this._register(disposable);
}
private _initDimensions(): void {
// The terminal panel needs to have been created
if (!this._container) {
return;
}
const computedStyle = window.getComputedStyle(this._container.parentElement!);
const width = parseInt(computedStyle.getPropertyValue('width').replace('px', ''), 10);
const height = parseInt(computedStyle.getPropertyValue('height').replace('px', ''), 10);
this._evaluateColsAndRows(width, height);
}
/**
* Evaluates and sets the cols and rows of the terminal if possible.
* @param width The width of the container.
* @param height The height of the container.
* @return The terminal's width if it requires a layout.
*/
private _evaluateColsAndRows(width: number, height: number): number | null {
// Ignore if dimensions are undefined or 0
if (!width || !height) {
this._setLastKnownColsAndRows();
return null;
}
const dimension = this._getDimension(width, height);
if (!dimension) {
this._setLastKnownColsAndRows();
return null;
}
const font = this._configHelper.getFont(this._xtermCore);
if (!font.charWidth || !font.charHeight) {
this._setLastKnownColsAndRows();
return null;
}
// Because xterm.js converts from CSS pixels to actual pixels through
// the use of canvas, window.devicePixelRatio needs to be used here in
// order to be precise. font.charWidth/charHeight alone as insufficient
// when window.devicePixelRatio changes.
const scaledWidthAvailable = dimension.width * window.devicePixelRatio;
const scaledCharWidth = font.charWidth * window.devicePixelRatio + font.letterSpacing;
const newCols = Math.max(Math.floor(scaledWidthAvailable / scaledCharWidth), 1);
const scaledHeightAvailable = dimension.height * window.devicePixelRatio;
const scaledCharHeight = Math.ceil(font.charHeight * window.devicePixelRatio);
const scaledLineHeight = Math.floor(scaledCharHeight * font.lineHeight);
const newRows = Math.max(Math.floor(scaledHeightAvailable / scaledLineHeight), 1);
if (this._cols !== newCols || this._rows !== newRows) {
this._cols = newCols;
this._rows = newRows;
this._fireMaximumDimensionsChanged();
}
return dimension.width;
}
private _setLastKnownColsAndRows(): void {
if (TerminalInstance._lastKnownGridDimensions) {
this._cols = TerminalInstance._lastKnownGridDimensions.cols;
this._rows = TerminalInstance._lastKnownGridDimensions.rows;
}
}
@debounce(50)
private _fireMaximumDimensionsChanged(): void {
this._onMaximumDimensionsChanged.fire();
}
private _getDimension(width: number, height: number): ICanvasDimensions | undefined {
// The font needs to have been initialized
const font = this._configHelper.getFont(this._xtermCore);
if (!font || !font.charWidth || !font.charHeight) {
return undefined;
}
// The panel is minimized
if (!this._isVisible) {
return TerminalInstance._lastKnownCanvasDimensions;
}
if (!this._wrapperElement) {
return undefined;
}
const wrapperElementStyle = getComputedStyle(this._wrapperElement);
const marginLeft = parseInt(wrapperElementStyle.marginLeft!.split('px')[0], 10);
const marginRight = parseInt(wrapperElementStyle.marginRight!.split('px')[0], 10);
const bottom = parseInt(wrapperElementStyle.bottom!.split('px')[0], 10);
const innerWidth = width - marginLeft - marginRight;
const innerHeight = height - bottom - 1;
TerminalInstance._lastKnownCanvasDimensions = new dom.Dimension(innerWidth, innerHeight);
return TerminalInstance._lastKnownCanvasDimensions;
}
public get persistentProcessId(): number | undefined { return this._processManager.persistentProcessId; }
public get shouldPersist(): boolean { return this._processManager.shouldPersist; }
private async _getXtermConstructor(): Promise<typeof XTermTerminal> {
if (xtermConstructor) {
return xtermConstructor;
}
xtermConstructor = new Promise<typeof XTermTerminal>(async (resolve) => {
const Terminal = await this._terminalInstanceService.getXtermConstructor();
// Localize strings
Terminal.strings.promptLabel = nls.localize('terminal.integrated.a11yPromptLabel', 'Terminal input');
Terminal.strings.tooMuchOutput = nls.localize('terminal.integrated.a11yTooMuchOutput', 'Too much output to announce, navigate to rows manually to read');
resolve(Terminal);
});
return xtermConstructor;
}
/**
* Create xterm.js instance and attach data listeners.
*/
protected async _createXterm(): Promise<XTermTerminal> {
const Terminal = await this._getXtermConstructor();
const font = this._configHelper.getFont(undefined, true);
const config = this._configHelper.config;
const editorOptions = this._configurationService.getValue<IEditorOptions>('editor');
let xtermRendererType: RendererType;
if (config.gpuAcceleration === 'auto') {
// Set the builtin renderer to canvas, even when webgl is being used since it's an addon
const suggestedRendererType = this._storageService.get(SUGGESTED_RENDERER_TYPE, StorageScope.GLOBAL);
xtermRendererType = suggestedRendererType === 'dom' ? 'dom' : 'canvas';
} else {
xtermRendererType = config.gpuAcceleration === 'on' ? 'canvas' : 'dom';
}
const xterm = new Terminal({
altClickMovesCursor: config.altClickMovesCursor && editorOptions.multiCursorModifier === 'alt',
scrollback: config.scrollback,
theme: this._getXtermTheme(),
drawBoldTextInBrightColors: config.drawBoldTextInBrightColors,
fontFamily: font.fontFamily,
fontWeight: config.fontWeight,
fontWeightBold: config.fontWeightBold,
fontSize: font.fontSize,
letterSpacing: font.letterSpacing,
lineHeight: font.lineHeight,
minimumContrastRatio: config.minimumContrastRatio,
bellStyle: config.enableBell ? 'sound' : 'none',
macOptionIsMeta: config.macOptionIsMeta,
macOptionClickForcesSelection: config.macOptionClickForcesSelection,
rightClickSelectsWord: config.rightClickBehavior === 'selectWord',
fastScrollModifier: 'alt',
fastScrollSensitivity: editorOptions.fastScrollSensitivity,
scrollSensitivity: editorOptions.mouseWheelScrollSensitivity,
rendererType: xtermRendererType,
wordSeparator: config.wordSeparators
});
this._xterm = xterm;
this._xtermCore = (xterm as any)._core as XTermCore;
this._updateUnicodeVersion();
this.updateAccessibilitySupport();
this._terminalInstanceService.getXtermSearchConstructor().then(Addon => {
this._xtermSearch = new Addon();
xterm.loadAddon(this._xtermSearch);
});
if (this._shellLaunchConfig.initialText) {
this._xterm.writeln(this._shellLaunchConfig.initialText);
}
this._xterm.onBell(() => this.statusList.add({ id: TerminalStatus.Bell, severity: Severity.Warning, icon: Codicon.bell }, 3000));
this._xterm.onLineFeed(() => this._onLineFeed());
this._xterm.onKey(e => this._onKey(e.key, e.domEvent));
this._xterm.onSelectionChange(async () => this._onSelectionChange());
this._xterm.buffer.onBufferChange(() => this._refreshAltBufferContextKey());
this._processManager.onProcessData(e => this._onProcessData(e));
this._xterm.onData(data => this._processManager.write(data));
this._xterm.onBinary(data => this._processManager.processBinary(data));
this.processReady.then(async () => {
if (this._linkManager) {
this._linkManager.processCwd = await this._processManager.getInitialCwd();
}
});
// Init winpty compat and link handler after process creation as they rely on the
// underlying process OS
this._processManager.onProcessReady(() => {
if (this._processManager.os === OperatingSystem.Windows) {
xterm.setOption('windowsMode', true);
// Force line data to be sent when the cursor is moved, the main purpose for
// this is because ConPTY will often not do a line feed but instead move the
// cursor, in which case we still want to send the current line's data to tasks.
xterm.parser.registerCsiHandler({ final: 'H' }, () => {
this._onCursorMove();
return false;
});
}
this._linkManager = this._instantiationService.createInstance(TerminalLinkManager, xterm, this._processManager!);
this._areLinksReady = true;
this._onLinksReady.fire(this);
});
this._commandTrackerAddon = new CommandTrackerAddon();
this._xterm.loadAddon(this._commandTrackerAddon);
this._register(this._themeService.onDidColorThemeChange(theme => this._updateTheme(xterm, theme)));
this._register(this._viewDescriptorService.onDidChangeLocation(({ views }) => {
if (views.some(v => v.id === TERMINAL_VIEW_ID)) {
this._updateTheme(xterm);
}
}));
this._xtermTypeAhead = this._register(this._instantiationService.createInstance(TypeAheadAddon, this._processManager, this._configHelper));
this._xterm.loadAddon(this._xtermTypeAhead);
return xterm;
}
public reattachToElement(container: HTMLElement): void {
if (!this._wrapperElement) {
throw new Error('The terminal instance has not been attached to a container yet');
}
this._wrapperElement.parentNode?.removeChild(this._wrapperElement);
this._container = container;
this._container.appendChild(this._wrapperElement);
}
public attachToElement(container: HTMLElement): void {
// The container did not change, do nothing
if (this._container === container) {
return;
}
// Attach has not occured yet
if (!this._wrapperElement) {
this._attachToElement(container);
return;
}
// The container changed, reattach
this._container?.removeChild(this._wrapperElement);
this._container = container;
this._container.appendChild(this._wrapperElement);
}
public async _attachToElement(container: HTMLElement): Promise<void> {
const xterm = await this._xtermReadyPromise;
if (this._wrapperElement) {
throw new Error('The terminal instance has already been attached to a container');
}
this._container = container;
this._wrapperElement = document.createElement('div');
this._wrapperElement.classList.add('terminal-wrapper');
this._xtermElement = document.createElement('div');
// Attach the xterm object to the DOM, exposing it to the smoke tests
this._wrapperElement.xterm = this._xterm;
this._wrapperElement.appendChild(this._xtermElement);
this._container.appendChild(this._wrapperElement);
xterm.open(this._xtermElement);
const suggestedRendererType = this._storageService.get(SUGGESTED_RENDERER_TYPE, StorageScope.GLOBAL);
if (this._configHelper.config.gpuAcceleration === 'auto' && (suggestedRendererType === 'auto' || suggestedRendererType === undefined)
|| this._configHelper.config.gpuAcceleration === 'on') {
this._enableWebglRenderer();
}
if (!xterm.element || !xterm.textarea) {
throw new Error('xterm elements not set after open');
}
this._setAriaLabel(xterm, this._instanceId, this._title);
xterm.textarea.addEventListener('focus', () => this._onFocus.fire(this));
xterm.attachCustomKeyEventHandler((event: KeyboardEvent): boolean => {
// Disable all input if the terminal is exiting
if (this._isExiting) {
return false;
}
const standardKeyboardEvent = new StandardKeyboardEvent(event);
const resolveResult = this._keybindingService.softDispatch(standardKeyboardEvent, standardKeyboardEvent.target);
// Respect chords if the allowChords setting is set and it's not Escape. Escape is
// handled specially for Zen Mode's Escape, Escape chord, plus it's important in
// terminals generally
const isValidChord = resolveResult?.enterChord && this._configHelper.config.allowChords && event.key !== 'Escape';
if (this._keybindingService.inChordMode || isValidChord) {
event.preventDefault();
return false;
}
const SHOW_TERMINAL_CONFIG_PROMPT = 'terminal.integrated.showTerminalConfigPrompt';
const EXCLUDED_KEYS = ['RightArrow', 'LeftArrow', 'UpArrow', 'DownArrow', 'Space', 'Meta', 'Control', 'Shift', 'Alt', '', 'Delete', 'Backspace', 'Tab'];
// only keep track of input if prompt hasn't already been shown
if (this._storageService.getBoolean(SHOW_TERMINAL_CONFIG_PROMPT, StorageScope.GLOBAL, true) &&
!EXCLUDED_KEYS.includes(event.key) &&
!event.ctrlKey &&
!event.shiftKey &&
!event.altKey) {
this.hasHadInput = true;
}
// for keyboard events that resolve to commands described
// within commandsToSkipShell, either alert or skip processing by xterm.js
if (resolveResult && resolveResult.commandId && this._skipTerminalCommands.some(k => k === resolveResult.commandId) && !this._configHelper.config.sendKeybindingsToShell) {
// don't alert when terminal is opened or closed
if (this._storageService.getBoolean(SHOW_TERMINAL_CONFIG_PROMPT, StorageScope.GLOBAL, true) &&
this.hasHadInput &&
!TERMINAL_CREATION_COMMANDS.includes(resolveResult.commandId)) {
this._notificationService.prompt(
Severity.Info,
nls.localize('keybindingHandling', "Some keybindings don't go to the terminal by default and are handled by {0} instead.", this._productService.nameLong),
[
{
label: nls.localize('configureTerminalSettings', "Configure Terminal Settings"),
run: () => {
this._preferencesService.openSettings(false, '@id:terminal.integrated.commandsToSkipShell,terminal.integrated.sendKeybindingsToShell,terminal.integrated.allowChords');
}
} as IPromptChoice
]
);
this._storageService.store(SHOW_TERMINAL_CONFIG_PROMPT, false, StorageScope.GLOBAL, StorageTarget.USER);
}
event.preventDefault();
return false;
}
// Skip processing by xterm.js of keyboard events that match menu bar mnemonics
if (this._configHelper.config.allowMnemonics && !isMacintosh && event.altKey) {
return false;
}
// If tab focus mode is on, tab is not passed to the terminal
if (TabFocus.getTabFocusMode() && event.keyCode === 9) {
return false;
}
// Always have alt+F4 skip the terminal on Windows and allow it to be handled by the
// system
if (isWindows && event.altKey && event.key === 'F4' && !event.ctrlKey) {
return false;
}
// Fallback to force ctrl+v to paste on browsers that do not support
// navigator.clipboard.readText
if (!BrowserFeatures.clipboard.readText && event.key === 'v' && event.ctrlKey) {
return false;
}
return true;
});
this._register(dom.addDisposableListener(xterm.element, 'mousedown', () => {
// We need to listen to the mouseup event on the document since the user may release
// the mouse button anywhere outside of _xterm.element.
const listener = dom.addDisposableListener(document, 'mouseup', () => {
// Delay with a setTimeout to allow the mouseup to propagate through the DOM
// before evaluating the new selection state.
setTimeout(() => this._refreshSelectionContextKey(), 0);
listener.dispose();
});
}));
// xterm.js currently drops selection on keyup as we need to handle this case.
this._register(dom.addDisposableListener(xterm.element, 'keyup', () => {
// Wait until keyup has propagated through the DOM before evaluating
// the new selection state.
setTimeout(() => this._refreshSelectionContextKey(), 0);
}));
this._register(dom.addDisposableListener(xterm.textarea, 'focus', () => {
this._terminalFocusContextKey.set(true);
if (this.shellType) {
this._terminalShellTypeContextKey.set(this.shellType.toString());
} else {
this._terminalShellTypeContextKey.reset();
}
this._onFocused.fire(this);
}));
this._register(dom.addDisposableListener(xterm.textarea, 'blur', () => {
this._terminalFocusContextKey.reset();
this._refreshSelectionContextKey();
}));
this._widgetManager.attachToElement(xterm.element);
this._processManager.onProcessReady(() => this._linkManager?.setWidgetManager(this._widgetManager));
const computedStyle = window.getComputedStyle(this._container);
const width = parseInt(computedStyle.getPropertyValue('width').replace('px', ''), 10);
const height = parseInt(computedStyle.getPropertyValue('height').replace('px', ''), 10);
this.layout(new dom.Dimension(width, height));
this.setVisible(this._isVisible);
this.updateConfig();
// If IShellLaunchConfig.waitOnExit was true and the process finished before the terminal
// panel was initialized.
if (xterm.getOption('disableStdin')) {
this._attachPressAnyKeyToCloseListener(xterm);
}
}
private async _measureRenderTime(): Promise<void> {
await this._xtermReadyPromise;
const frameTimes: number[] = [];
const textRenderLayer = this._xtermCore!._renderService._renderer._renderLayers[0];
const originalOnGridChanged = textRenderLayer.onGridChanged;
const evaluateCanvasRenderer = () => {
// Discard first frame time as it's normal to take longer
frameTimes.shift();
const medianTime = frameTimes.sort((a, b) => a - b)[Math.floor(frameTimes.length / 2)];
if (medianTime > SLOW_CANVAS_RENDER_THRESHOLD) {
if (this._configHelper.config.gpuAcceleration === 'auto') {
this._storageService.store(SUGGESTED_RENDERER_TYPE, 'dom', StorageScope.GLOBAL, StorageTarget.MACHINE);
this.updateConfig();
} else {
const promptChoices: IPromptChoice[] = [
{
label: nls.localize('yes', "Yes"),
run: () => this._configurationService.updateValue('terminal.integrated.gpuAcceleration', 'off', ConfigurationTarget.USER)
} as IPromptChoice,
{
label: nls.localize('no', "No"),
run: () => { }
} as IPromptChoice,
{
label: nls.localize('dontShowAgain', "Don't Show Again"),
isSecondary: true,
run: () => this._storageService.store(NEVER_MEASURE_RENDER_TIME_STORAGE_KEY, true, StorageScope.GLOBAL, StorageTarget.MACHINE)
} as IPromptChoice
];
this._notificationService.prompt(
Severity.Warning,
nls.localize('terminal.slowRendering', 'Terminal GPU acceleration appears to be slow on your computer. Would you like to switch to disable it which may improve performance? [Read more about terminal settings](https://code.visualstudio.com/docs/editor/integrated-terminal#_changing-how-the-terminal-is-rendered).'),
promptChoices
);
}
}
};
textRenderLayer.onGridChanged = (terminal: XTermTerminal, firstRow: number, lastRow: number) => {
const startTime = performance.now();
originalOnGridChanged.call(textRenderLayer, terminal, firstRow, lastRow);
frameTimes.push(performance.now() - startTime);
if (frameTimes.length === NUMBER_OF_FRAMES_TO_MEASURE) {
evaluateCanvasRenderer();
// Restore original function
textRenderLayer.onGridChanged = originalOnGridChanged;
}
};
}
public hasSelection(): boolean {
return this._xterm ? this._xterm.hasSelection() : false;
}
public async copySelection(): Promise<void> {
const xterm = await this._xtermReadyPromise;
if (this.hasSelection()) {
await this._clipboardService.writeText(xterm.getSelection());
} else {
this._notificationService.warn(nls.localize('terminal.integrated.copySelection.noSelection', 'The terminal has no selection to copy'));
}
}
public get selection(): string | undefined {
return this._xterm && this.hasSelection() ? this._xterm.getSelection() : undefined;
}
public clearSelection(): void {
this._xterm?.clearSelection();
}
public selectAll(): void {
// Focus here to ensure the terminal context key is set
this._xterm?.focus();
this._xterm?.selectAll();
}
public findNext(term: string, searchOptions: ISearchOptions): boolean {
if (!this._xtermSearch) {
return false;
}
return this._xtermSearch.findNext(term, searchOptions);
}
public findPrevious(term: string, searchOptions: ISearchOptions): boolean {
if (!this._xtermSearch) {
return false;
}
return this._xtermSearch.findPrevious(term, searchOptions);
}
public notifyFindWidgetFocusChanged(isFocused: boolean): void {
if (!this._xterm) {
return;
}
const terminalFocused = !isFocused && (document.activeElement === this._xterm.textarea || document.activeElement === this._xterm.element);
this._terminalFocusContextKey.set(terminalFocused);
}
public refreshFocusState() {
this.notifyFindWidgetFocusChanged(false);
}
private _refreshAltBufferContextKey() {
this._terminalAltBufferActiveContextKey.set(!!(this._xterm && this._xterm.buffer.active === this._xterm.buffer.alternate));
}
public override dispose(immediate?: boolean): void {
this._logService.trace(`terminalInstance#dispose (instanceId: ${this.instanceId})`);
dispose(this._linkManager);
this._linkManager = undefined;
dispose(this._commandTrackerAddon);
this._commandTrackerAddon = undefined;
dispose(this._widgetManager);
if (this._xterm && this._xterm.element) {
this._hadFocusOnExit = this._xterm.element.classList.contains('focus');
}
if (this._wrapperElement) {
if (this._wrapperElement.xterm) {
this._wrapperElement.xterm = undefined;
}
if (this._wrapperElement.parentElement && this._container) {
this._container.removeChild(this._wrapperElement);
}
}
if (this._xterm) {
const buffer = this._xterm.buffer;
this._sendLineData(buffer.active, buffer.active.baseY + buffer.active.cursorY);
this._xterm.dispose();
}
if (this._pressAnyKeyToCloseListener) {
this._pressAnyKeyToCloseListener.dispose();
this._pressAnyKeyToCloseListener = undefined;
}
this._processManager.dispose(immediate);
// Process manager dispose/shutdown doesn't fire process exit, trigger with undefined if it
// hasn't happened yet
this._onProcessExit(undefined);
if (!this._isDisposed) {
this._isDisposed = true;
this._onDisposed.fire(this);
}
super.dispose();
}
public detachFromProcess(): void {
this._processManager.detachFromProcess();
}
public forceRedraw(): void {
if (!this._xterm) {
return;
}
this._webglAddon?.clearTextureAtlas();
// TODO: Do canvas renderer too?
}
public focus(force?: boolean): void {
this._refreshAltBufferContextKey();
if (!this._xterm) {
return;
}
const selection = window.getSelection();
if (!selection) {
return;
}
const text = selection.toString();
if (!text || force) {
this._xterm.focus();
}
}
public async focusWhenReady(force?: boolean): Promise<void> {
await this._xtermReadyPromise;
this.focus(force);
}
public async paste(): Promise<void> {
if (!this._xterm) {
return;
}
this.focus();
this._xterm.paste(await this._clipboardService.readText());
}
public async pasteSelection(): Promise<void> {
if (!this._xterm) {
return;
}
this.focus();
this._xterm.paste(await this._clipboardService.readText('selection'));
}
public async sendText(text: string, addNewLine: boolean): Promise<void> {
// Normalize line endings to 'enter' press.
text = text.replace(TerminalInstance.EOL_REGEX, '\r');
if (addNewLine && text.substr(text.length - 1) !== '\r') {
text += '\r';
}
// Send it to the process
return this._processManager.write(text);
}
public setVisible(visible: boolean): void {
this._isVisible = visible;
if (this._wrapperElement) {
this._wrapperElement.classList.toggle('active', visible);
}
if (visible && this._xterm && this._xtermCore) {
// Trigger a manual scroll event which will sync the viewport and scroll bar. This is
// necessary if the number of rows in the terminal has decreased while it was in the
// background since scrollTop changes take no effect but the terminal's position does
// change since the number of visible rows decreases.
// This can likely be removed after https://github.com/xtermjs/xterm.js/issues/291 is
// fixed upstream.
this._xtermCore._onScroll.fire(this._xterm.buffer.active.viewportY);
if (this._container && this._container.parentElement) {
// Force a layout when the instance becomes invisible. This is particularly important
// for ensuring that terminals that are created in the background by an extension will
// correctly get correct character measurements in order to render to the screen (see
// #34554).
const computedStyle = window.getComputedStyle(this._container.parentElement);
const width = parseInt(computedStyle.getPropertyValue('width').replace('px', ''), 10);
const height = parseInt(computedStyle.getPropertyValue('height').replace('px', ''), 10);
this.layout(new dom.Dimension(width, height));
// HACK: Trigger another async layout to ensure xterm's CharMeasure is ready to use,
// this hack can be removed when https://github.com/xtermjs/xterm.js/issues/702 is
// supported.
this._timeoutDimension = new dom.Dimension(width, height);
setTimeout(() => this.layout(this._timeoutDimension!), 0);
}
}
}
public scrollDownLine(): void {
this._xterm?.scrollLines(1);
}
public scrollDownPage(): void {
this._xterm?.scrollPages(1);
}
public scrollToBottom(): void {
this._xterm?.scrollToBottom();
}
public scrollUpLine(): void {
this._xterm?.scrollLines(-1);
}
public scrollUpPage(): void {
this._xterm?.scrollPages(-1);
}
public scrollToTop(): void {
this._xterm?.scrollToTop();
}
public clear(): void {
this._xterm?.clear();
}
private _refreshSelectionContextKey() {
const isActive = !!this._viewsService.getActiveViewWithId(TERMINAL_VIEW_ID);
this._terminalHasTextContextKey.set(isActive && this.hasSelection());
}
protected _createProcessManager(): void {
this._processManager = this._instantiationService.createInstance(TerminalProcessManager, this._instanceId, this._configHelper);