-
Notifications
You must be signed in to change notification settings - Fork 30.1k
/
Copy pathterminalInstance.ts
1183 lines (1036 loc) · 46.8 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 lifecycle from 'vs/base/common/lifecycle';
import * as nls from 'vs/nls';
import * as platform from 'vs/base/common/platform';
import * as dom from 'vs/base/browser/dom';
import * as paths from 'vs/base/common/paths';
import * as os from 'os';
import { Event, Emitter } from 'vs/base/common/event';
import { WindowsShellHelper } from 'vs/workbench/parts/terminal/node/windowsShellHelper';
import { Terminal as XTermTerminal, ISearchOptions } from 'vscode-xterm';
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
import { ITerminalInstance, KEYBINDING_CONTEXT_TERMINAL_TEXT_SELECTED, TERMINAL_PANEL_ID, IShellLaunchConfig, ITerminalProcessManager, ProcessState, NEVER_MEASURE_RENDER_TIME_STORAGE_KEY, ITerminalDimensions } from 'vs/workbench/parts/terminal/common/terminal';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { TabFocus } from 'vs/editor/common/config/commonEditorConfig';
import { TerminalConfigHelper } from 'vs/workbench/parts/terminal/electron-browser/terminalConfigHelper';
import { TerminalLinkHandler } from 'vs/workbench/parts/terminal/electron-browser/terminalLinkHandler';
import { TerminalWidgetManager } from 'vs/workbench/parts/terminal/browser/terminalWidgetManager';
import { registerThemingParticipant, ITheme, ICssStyleCollector, IThemeService } from 'vs/platform/theme/common/themeService';
import { scrollbarSliderBackground, scrollbarSliderHoverBackground, scrollbarSliderActiveBackground, activeContrastBorder } from 'vs/platform/theme/common/colorRegistry';
import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService';
import { ansiColorIdentifiers, TERMINAL_BACKGROUND_COLOR, TERMINAL_FOREGROUND_COLOR, TERMINAL_CURSOR_FOREGROUND_COLOR, TERMINAL_CURSOR_BACKGROUND_COLOR, TERMINAL_SELECTION_BACKGROUND_COLOR } from 'vs/workbench/parts/terminal/common/terminalColorRegistry';
import { PANEL_BACKGROUND } from 'vs/workbench/common/theme';
import { IConfigurationService, ConfigurationTarget } from 'vs/platform/configuration/common/configuration';
import { IEditorOptions } from 'vs/editor/common/config/editorOptions';
import { INotificationService, Severity, IPromptChoice } from 'vs/platform/notification/common/notification';
import { ILogService } from 'vs/platform/log/common/log';
import { TerminalCommandTracker } from 'vs/workbench/parts/terminal/node/terminalCommandTracker';
import { TerminalProcessManager } from './terminalProcessManager';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import { execFile } from 'child_process';
// 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;
let Terminal: typeof XTermTerminal;
export class TerminalInstance implements ITerminalInstance {
private static readonly EOL_REGEX = /\r?\n/g;
private static _lastKnownDimensions: dom.Dimension = null;
private static _idCounter = 1;
private _processManager: ITerminalProcessManager | undefined;
private _id: number;
private _isExiting: boolean;
private _hadFocusOnExit: boolean;
private _isVisible: boolean;
private _isDisposed: boolean;
private _skipTerminalCommands: string[];
private _title: string;
private _wrapperElement: HTMLDivElement;
private _xterm: XTermTerminal;
private _xtermElement: HTMLDivElement;
private _terminalHasTextContextKey: IContextKey<boolean>;
private _cols: number;
private _rows: number;
private _dimensionsOverride: ITerminalDimensions;
private _windowsShellHelper: WindowsShellHelper;
private _xtermReadyPromise: Promise<void>;
private _titleReadyPromise: Promise<string>;
private _titleReadyComplete: (title: string) => any;
private _disposables: lifecycle.IDisposable[];
private _messageTitleDisposable: lifecycle.IDisposable;
private _widgetManager: TerminalWidgetManager;
private _linkHandler: TerminalLinkHandler;
private _commandTracker: TerminalCommandTracker;
public disableLayout: boolean;
public get id(): number { return this._id; }
public get cols(): number { return this._cols; }
public get rows(): number { return this._rows; }
// TODO: Ideally processId would be merged into processReady
public get processId(): number | undefined { return this._processManager ? this._processManager.shellProcessId : undefined; }
// 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 ? this._processManager.ptyProcessReady : Promise.resolve(void 0); }
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 commandTracker(): TerminalCommandTracker { return this._commandTracker; }
private readonly _onExit: Emitter<number> = new Emitter<number>();
public get onExit(): Event<number> { return this._onExit.event; }
private readonly _onDisposed: Emitter<ITerminalInstance> = new Emitter<ITerminalInstance>();
public get onDisposed(): Event<ITerminalInstance> { return this._onDisposed.event; }
private readonly _onFocused: Emitter<ITerminalInstance> = new Emitter<ITerminalInstance>();
public get onFocused(): Event<ITerminalInstance> { return this._onFocused.event; }
private readonly _onProcessIdReady: Emitter<ITerminalInstance> = new Emitter<ITerminalInstance>();
public get onProcessIdReady(): Event<ITerminalInstance> { return this._onProcessIdReady.event; }
private readonly _onTitleChanged: Emitter<ITerminalInstance> = new Emitter<ITerminalInstance>();
public get onTitleChanged(): Event<ITerminalInstance> { return this._onTitleChanged.event; }
private readonly _onProcessLaunching: Emitter<ITerminalInstance> = new Emitter<ITerminalInstance>();
public get onProcessLaunching(): Event<ITerminalInstance> { return this._onProcessLaunching.event; }
private readonly _onData: Emitter<string> = new Emitter<string>();
public get onData(): Event<string> { return this._onData.event; }
private readonly _onLineData: Emitter<string> = new Emitter<string>();
public get onLineData(): Event<string> { return this._onLineData.event; }
private readonly _onRendererInput: Emitter<string> = new Emitter<string>();
public get onRendererInput(): Event<string> { return this._onRendererInput.event; }
private readonly _onRequestExtHostProcess: Emitter<ITerminalInstance> = new Emitter<ITerminalInstance>();
public get onRequestExtHostProcess(): Event<ITerminalInstance> { return this._onRequestExtHostProcess.event; }
private readonly _onDimensionsChanged: Emitter<void> = new Emitter<void>();
public get onDimensionsChanged(): Event<void> { return this._onDimensionsChanged.event; }
private readonly _onFocus: Emitter<ITerminalInstance> = new Emitter<ITerminalInstance>();
public get onFocus(): Event<ITerminalInstance> { return this._onFocus.event; }
public constructor(
private readonly _terminalFocusContextKey: IContextKey<boolean>,
private readonly _configHelper: TerminalConfigHelper,
private _container: HTMLElement,
private _shellLaunchConfig: IShellLaunchConfig,
@IContextKeyService private readonly _contextKeyService: IContextKeyService,
@IKeybindingService private readonly _keybindingService: IKeybindingService,
@INotificationService private readonly _notificationService: INotificationService,
@IPanelService private readonly _panelService: IPanelService,
@IInstantiationService private readonly _instantiationService: IInstantiationService,
@IClipboardService private readonly _clipboardService: IClipboardService,
@IThemeService private readonly _themeService: IThemeService,
@IConfigurationService private readonly _configurationService: IConfigurationService,
@ILogService private _logService: ILogService,
@IStorageService private readonly _storageService: IStorageService
) {
this._disposables = [];
this._skipTerminalCommands = [];
this._isExiting = false;
this._hadFocusOnExit = false;
this._isVisible = false;
this._isDisposed = false;
this._id = TerminalInstance._idCounter++;
this._titleReadyPromise = new Promise<string>(c => {
this._titleReadyComplete = c;
});
this._terminalHasTextContextKey = KEYBINDING_CONTEXT_TERMINAL_TEXT_SELECTED.bindTo(this._contextKeyService);
this.disableLayout = false;
this._logService.trace(`terminalInstance#ctor (id: ${this.id})`, this._shellLaunchConfig);
this._initDimensions();
if (!this.shellLaunchConfig.isRendererOnly) {
this._createProcess();
} else {
this.setTitle(this._shellLaunchConfig.name, false);
}
this._xtermReadyPromise = this._createXterm();
this._xtermReadyPromise.then(() => {
// Only attach xterm.js to the DOM if the terminal panel has been opened before.
if (_container) {
this._attachToElement(_container);
}
});
this.addDisposable(this._configurationService.onDidChangeConfiguration(e => {
if (e.affectsConfiguration('terminal.integrated')) {
this.updateConfig();
}
if (e.affectsConfiguration('editor.accessibilitySupport')) {
this.updateAccessibilitySupport();
}
}));
}
public addDisposable(disposable: lifecycle.IDisposable): void {
this._disposables.push(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 {
// Ignore if dimensions are undefined or 0
if (!width || !height) {
return null;
}
const dimension = this._getDimension(width, height);
if (!dimension) {
return null;
}
const font = this._configHelper.getFont(this._xterm);
// 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;
let scaledCharWidth: number;
if (this._configHelper.config.rendererType === 'dom') {
scaledCharWidth = font.charWidth * window.devicePixelRatio;
} else {
scaledCharWidth = Math.floor(font.charWidth * window.devicePixelRatio) + font.letterSpacing;
}
this._cols = 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);
this._rows = Math.max(Math.floor(scaledHeightAvailable / scaledLineHeight), 1);
return dimension.width;
}
private _getDimension(width: number, height: number): dom.Dimension {
// The font needs to have been initialized
const font = this._configHelper.getFont(this._xterm);
if (!font || !font.charWidth || !font.charHeight) {
return null;
}
// The panel is minimized
if (!this._isVisible) {
return TerminalInstance._lastKnownDimensions;
} else {
// Trigger scroll event manually so that the viewport's scroll area is synced. This
// needs to happen otherwise its scrollTop value is invalid when the panel is toggled as
// it gets removed and then added back to the DOM (resetting scrollTop to 0).
// Upstream issue: https://github.com/sourcelair/xterm.js/issues/291
if (this._xterm) {
this._xterm.emit('scroll', this._xterm._core.buffer.ydisp);
}
}
if (!this._wrapperElement) {
return null;
}
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;
TerminalInstance._lastKnownDimensions = new dom.Dimension(innerWidth, innerHeight);
return TerminalInstance._lastKnownDimensions;
}
/**
* Create xterm.js instance and attach data listeners.
*/
protected async _createXterm(): Promise<void> {
if (!Terminal) {
Terminal = (await import('vscode-xterm')).Terminal;
// Enable xterm.js addons
Terminal.applyAddon(require.__$__nodeRequire('vscode-xterm/lib/addons/search/search'));
Terminal.applyAddon(require.__$__nodeRequire('vscode-xterm/lib/addons/webLinks/webLinks'));
Terminal.applyAddon(require.__$__nodeRequire('vscode-xterm/lib/addons/winptyCompat/winptyCompat'));
// Localize strings
Terminal.strings.blankLine = nls.localize('terminal.integrated.a11yBlankLine', 'Blank line');
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');
}
const accessibilitySupport = this._configurationService.getValue<IEditorOptions>('editor').accessibilitySupport;
const font = this._configHelper.getFont(undefined, true);
const config = this._configHelper.config;
this._xterm = new Terminal({
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,
bellStyle: config.enableBell ? 'sound' : 'none',
screenReaderMode: accessibilitySupport === 'on',
macOptionIsMeta: config.macOptionIsMeta,
macOptionClickForcesSelection: config.macOptionClickForcesSelection,
rightClickSelectsWord: config.rightClickBehavior === 'selectWord',
// TODO: Guess whether to use canvas or dom better
rendererType: config.rendererType === 'auto' ? 'canvas' : config.rendererType,
// TODO: Remove this once the setting is removed upstream
experimentalCharAtlas: 'dynamic'
});
if (this._shellLaunchConfig.initialText) {
this._xterm.writeln(this._shellLaunchConfig.initialText);
}
this._xterm.winptyCompatInit();
this._xterm.on('linefeed', () => this._onLineFeed());
if (this._processManager) {
this._processManager.onProcessData(data => this._onProcessData(data));
this._xterm.on('data', data => this._processManager.write(data));
// TODO: How does the cwd work on detached processes?
this._linkHandler = this._instantiationService.createInstance(TerminalLinkHandler, this._xterm, platform.platform);
this.processReady.then(() => {
this._linkHandler.initialCwd = this._processManager.initialCwd;
});
}
this._xterm.on('focus', () => this._onFocus.fire(this));
// Register listener to trigger the onInput ext API if the terminal is a renderer only
if (this._shellLaunchConfig.isRendererOnly) {
this._xterm.on('data', (data) => this._sendRendererInput(data));
}
this._commandTracker = new TerminalCommandTracker(this._xterm);
this._disposables.push(this._themeService.onThemeChange(theme => this._updateTheme(theme)));
}
public reattachToElement(container: HTMLElement): void {
if (!this._wrapperElement) {
throw new Error('The terminal instance has not been attached to a container yet');
}
if (this._wrapperElement.parentNode) {
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 _attachToElement(container: HTMLElement): void {
this._xtermReadyPromise.then(() => {
if (this._wrapperElement) {
throw new Error('The terminal instance has already been attached to a container');
}
this._container = container;
this._wrapperElement = document.createElement('div');
dom.addClass(this._wrapperElement, 'terminal-wrapper');
this._xtermElement = document.createElement('div');
// Attach the xterm object to the DOM, exposing it to the smoke tests
(<any>this._wrapperElement).xterm = this._xterm;
this._xterm.open(this._xtermElement);
this._xterm.attachCustomKeyEventHandler((event: KeyboardEvent) => {
// Disable all input if the terminal is exiting
if (this._isExiting) {
return false;
}
// Skip processing by xterm.js of keyboard events that resolve to commands described
// within commandsToSkipShell
const standardKeyboardEvent = new StandardKeyboardEvent(event);
const resolveResult = this._keybindingService.softDispatch(standardKeyboardEvent, standardKeyboardEvent.target);
if (resolveResult && this._skipTerminalCommands.some(k => k === resolveResult.commandId)) {
event.preventDefault();
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 (platform.isWindows && event.altKey && event.key === 'F4' && !event.ctrlKey) {
return false;
}
return undefined;
});
this._disposables.push(dom.addDisposableListener(this._xterm.element, 'mousedown', (event: KeyboardEvent) => {
// 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', (event: KeyboardEvent) => {
// 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._disposables.push(dom.addDisposableListener(this._xterm.element, 'keyup', (event: KeyboardEvent) => {
// Wait until keyup has propagated through the DOM before evaluating
// the new selection state.
setTimeout(() => this._refreshSelectionContextKey(), 0);
}));
const xtermHelper: HTMLElement = <HTMLElement>this._xterm.element.querySelector('.xterm-helpers');
const focusTrap: HTMLElement = document.createElement('div');
focusTrap.setAttribute('tabindex', '0');
dom.addClass(focusTrap, 'focus-trap');
this._disposables.push(dom.addDisposableListener(focusTrap, 'focus', (event: FocusEvent) => {
let currentElement = focusTrap;
while (!dom.hasClass(currentElement, 'part')) {
currentElement = currentElement.parentElement;
}
const hidePanelElement = <HTMLElement>currentElement.querySelector('.hide-panel-action');
hidePanelElement.focus();
}));
xtermHelper.insertBefore(focusTrap, this._xterm.textarea);
this._disposables.push(dom.addDisposableListener(this._xterm.textarea, 'focus', (event: KeyboardEvent) => {
this._terminalFocusContextKey.set(true);
this._onFocused.fire(this);
}));
this._disposables.push(dom.addDisposableListener(this._xterm.textarea, 'blur', (event: KeyboardEvent) => {
this._terminalFocusContextKey.reset();
this._refreshSelectionContextKey();
}));
this._disposables.push(dom.addDisposableListener(this._xterm.element, 'focus', (event: KeyboardEvent) => {
this._terminalFocusContextKey.set(true);
}));
this._disposables.push(dom.addDisposableListener(this._xterm.element, 'blur', (event: KeyboardEvent) => {
this._terminalFocusContextKey.reset();
this._refreshSelectionContextKey();
}));
this._wrapperElement.appendChild(this._xtermElement);
this._container.appendChild(this._wrapperElement);
if (this._processManager) {
this._widgetManager = new TerminalWidgetManager(this._wrapperElement);
this._linkHandler.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 (this._xterm.getOption('disableStdin')) {
this._attachPressAnyKeyToCloseListener();
}
const neverMeasureRenderTime = this._storageService.getBoolean(NEVER_MEASURE_RENDER_TIME_STORAGE_KEY, StorageScope.GLOBAL, false);
if (!neverMeasureRenderTime && this._configHelper.config.rendererType === 'auto') {
this._measureRenderTime();
}
});
}
private _measureRenderTime(): void {
const frameTimes: number[] = [];
const textRenderLayer = this._xterm._core.renderer._renderLayers[0];
const originalOnGridChanged = textRenderLayer.onGridChanged;
const evaluateCanvasRenderer = () => {
// Discard first frame time as it's normal to take longer
frameTimes.shift();
const averageTime = frameTimes.reduce((p, c) => p + c) / frameTimes.length;
if (averageTime > SLOW_CANVAS_RENDER_THRESHOLD) {
const promptChoices: IPromptChoice[] = [
{
label: nls.localize('yes', "Yes"),
run: () => {
this._configurationService.updateValue('terminal.integrated.rendererType', 'dom', ConfigurationTarget.USER).then(() => {
this._notificationService.info(nls.localize('terminal.rendererInAllNewTerminals', "The terminal is now using the fallback renderer."));
});
}
} 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)
} as IPromptChoice
];
this._notificationService.prompt(
Severity.Warning,
nls.localize('terminal.slowRendering', 'The standard renderer for the integrated terminal appears to be slow on your computer. Would you like to switch to the alternative DOM-based renderer 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 registerLinkMatcher(regex: RegExp, handler: (url: string) => void, matchIndex?: number, validationCallback?: (uri: string, callback: (isValid: boolean) => void) => void): number {
return this._linkHandler.registerCustomLinkHandler(regex, handler, matchIndex, validationCallback);
}
public deregisterLinkMatcher(linkMatcherId: number): void {
this._xterm.deregisterLinkMatcher(linkMatcherId);
}
public hasSelection(): boolean {
return this._xterm && this._xterm.hasSelection();
}
public copySelection(): void {
if (this.hasSelection()) {
this._clipboardService.writeText(this._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.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 {
return this._xterm.findNext(term, searchOptions);
}
public findPrevious(term: string, searchOptions: ISearchOptions): boolean {
return this._xterm.findPrevious(term, searchOptions);
}
public notifyFindWidgetFocusChanged(isFocused: boolean): void {
const terminalFocused = !isFocused && (document.activeElement === this._xterm.textarea || document.activeElement === this._xterm.element);
this._terminalFocusContextKey.set(terminalFocused);
}
public dispose(isShuttingDown?: boolean): void {
this._logService.trace(`terminalInstance#dispose (id: ${this.id})`);
this._windowsShellHelper = lifecycle.dispose(this._windowsShellHelper);
this._linkHandler = lifecycle.dispose(this._linkHandler);
this._commandTracker = lifecycle.dispose(this._commandTracker);
this._widgetManager = lifecycle.dispose(this._widgetManager);
if (this._xterm && this._xterm.element) {
this._hadFocusOnExit = dom.hasClass(this._xterm.element, 'focus');
}
if (this._wrapperElement) {
if ((<any>this._wrapperElement).xterm) {
(<any>this._wrapperElement).xterm = null;
}
this._container.removeChild(this._wrapperElement);
this._wrapperElement = null;
this._xtermElement = null;
}
if (this._xterm) {
const buffer = (<any>this._xterm._core.buffer);
this._sendLineData(buffer, buffer.ybase + buffer.y);
this._xterm.dispose();
this._xterm = null;
}
if (this._processManager) {
this._processManager.dispose(isShuttingDown);
}
if (!this._isDisposed) {
this._isDisposed = true;
this._onDisposed.fire(this);
}
this._disposables = lifecycle.dispose(this._disposables);
}
public focus(force?: boolean): void {
if (!this._xterm) {
return;
}
const text = window.getSelection().toString();
if (!text || force) {
this._xterm.focus();
}
}
public focusWhenReady(force?: boolean): Promise<void> {
return this._xtermReadyPromise.then(() => this.focus(force));
}
public paste(): void {
this.focus();
document.execCommand('paste');
}
public write(text: string): void {
this._xtermReadyPromise.then(() => {
if (!this._xterm) {
return;
}
this._xterm.write(text);
if (this._shellLaunchConfig.isRendererOnly) {
// Fire onData API in the extension host
this._onData.fire(text);
}
});
}
public sendText(text: string, addNewLine: boolean): void {
// Normalize line endings to 'enter' press.
text = text.replace(TerminalInstance.EOL_REGEX, '\r');
if (addNewLine && text.substr(text.length - 1) !== '\r') {
text += '\r';
}
if (this._shellLaunchConfig.isRendererOnly) {
// If the terminal is a renderer only, fire the onInput ext API
this._sendRendererInput(text);
} else {
// If the terminal has a process, send it to the process
if (this._processManager) {
this._processManager.ptyProcessReady.then(() => {
this._processManager.write(text);
});
}
}
}
public preparePathForTerminalAsync(path: string): Promise<string> {
return new Promise<string>(c => {
const hasSpace = path.indexOf(' ') !== -1;
if (platform.isWindows) {
const exe = this.shellLaunchConfig.executable;
// 17063 is the build number where wsl path was introduced.
// Update Windows uriPath to be executed in WSL.
if (((exe.indexOf('wsl') !== -1) || ((exe.indexOf('bash.exe') !== -1) && (exe.indexOf('git') === -1))) && (TerminalInstance.getWindowsBuildNumber() >= 17063)) {
execFile('bash.exe', ['-c', 'echo $(wslpath ' + this._escapeNonWindowsPath(path) + ')'], {}, (error, stdout, stderr) => {
c(this._escapeNonWindowsPath(stdout.trim()));
});
} else if (hasSpace) {
c('"' + path + '"');
}
} else if (!platform.isWindows) {
c(this._escapeNonWindowsPath(path));
}
});
}
private _escapeNonWindowsPath(path: string): string {
let newPath = path;
if (newPath.indexOf('\\') !== 0) {
newPath = newPath.replace(/\\/g, '\\\\');
}
if (!newPath && (newPath.indexOf('"') !== -1)) {
newPath = '\'' + newPath + '\'';
} else if (newPath.indexOf(' ') !== -1) {
newPath = newPath.replace(/ /g, '\\ ');
}
return newPath;
}
public static getWindowsBuildNumber(): number {
const osVersion = (/(\d+)\.(\d+)\.(\d+)/g).exec(os.release());
let buildNumber: number = 0;
if (osVersion && osVersion.length === 4) {
buildNumber = parseInt(osVersion[3]);
}
return buildNumber;
}
public setVisible(visible: boolean): void {
this._isVisible = visible;
if (this._wrapperElement) {
dom.toggleClass(this._wrapperElement, 'active', visible);
}
if (visible && this._xterm) {
// 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._xterm.emit('scroll', this._xterm._core.buffer.ydisp);
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.
setTimeout(() => this.layout(new dom.Dimension(width, height)), 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 activePanel = this._panelService.getActivePanel();
const isActive = activePanel && activePanel.getId() === TERMINAL_PANEL_ID;
this._terminalHasTextContextKey.set(isActive && this.hasSelection());
}
protected _createProcess(): void {
this._processManager = this._instantiationService.createInstance(TerminalProcessManager, this._id, this._configHelper);
this._processManager.onProcessReady(() => this._onProcessIdReady.fire(this));
this._processManager.onProcessExit(exitCode => this._onProcessExit(exitCode));
this._processManager.onProcessData(data => this._onData.fire(data));
this._onProcessLaunching.fire(this);
if (this._shellLaunchConfig.name) {
this.setTitle(this._shellLaunchConfig.name, false);
} else {
// Only listen for process title changes when a name is not provided
this.setTitle(this._shellLaunchConfig.executable, true);
this._messageTitleDisposable = this._processManager.onProcessTitle(title => this.setTitle(title ? title : '', true));
}
if (platform.isWindows) {
this._processManager.ptyProcessReady.then(() => {
this._xtermReadyPromise.then(() => {
if (!this._isDisposed) {
this._windowsShellHelper = new WindowsShellHelper(this._processManager.shellProcessId, this, this._xterm);
}
});
});
}
// Create the process asynchronously to allow the terminal's container
// to be created so dimensions are accurate
setTimeout(() => {
this._processManager.createProcess(this._shellLaunchConfig, this._cols, this._rows);
}, 0);
}
private _onProcessData(data: string): void {
if (this._widgetManager) {
this._widgetManager.closeMessage();
}
if (this._xterm) {
this._xterm.write(data);
}
}
private _onProcessExit(exitCode: number): void {
this._logService.debug(`Terminal process exit (id: ${this.id}) with code ${exitCode}`);
// Prevent dispose functions being triggered multiple times
if (this._isExiting) {
return;
}
this._isExiting = true;
let exitCodeMessage: string;
if (exitCode) {
exitCodeMessage = nls.localize('terminal.integrated.exitedWithCode', 'The terminal process terminated with exit code: {0}', exitCode);
}
this._logService.debug(`Terminal process exit (id: ${this.id}) state ${this._processManager.processState}`);
// Only trigger wait on exit when the exit was *not* triggered by the
// user (via the `workbench.action.terminal.kill` command).
if (this._shellLaunchConfig.waitOnExit && this._processManager.processState !== ProcessState.KILLED_BY_USER) {
if (exitCode) {
this._xterm.writeln(exitCodeMessage);
}
let message = typeof this._shellLaunchConfig.waitOnExit === 'string'
? this._shellLaunchConfig.waitOnExit
: nls.localize('terminal.integrated.waitOnExit', 'Press any key to close the terminal');
// Bold the message and add an extra new line to make it stand out from the rest of the output
message = `\n\x1b[1m${message}\x1b[0m`;
this._xterm.writeln(message);
// Disable all input if the terminal is exiting and listen for next keypress
this._xterm.setOption('disableStdin', true);
if (this._xterm.textarea) {
this._attachPressAnyKeyToCloseListener();
}
} else {
this.dispose();
if (exitCode) {
if (this._processManager.processState === ProcessState.KILLED_DURING_LAUNCH) {
let args = '';
if (typeof this._shellLaunchConfig.args === 'string') {
args = this._shellLaunchConfig.args;
} else if (this._shellLaunchConfig.args && this._shellLaunchConfig.args.length) {
args = ' ' + this._shellLaunchConfig.args.map(a => {
if (typeof a === 'string' && a.indexOf(' ') !== -1) {
return `'${a}'`;
}
return a;
}).join(' ');
}
if (this._shellLaunchConfig.executable) {
this._notificationService.error(nls.localize('terminal.integrated.launchFailed', 'The terminal process command \'{0}{1}\' failed to launch (exit code: {2})', this._shellLaunchConfig.executable, args, exitCode));
} else {
this._notificationService.error(nls.localize('terminal.integrated.launchFailedExtHost', 'The terminal process failed to launch (exit code: {0})', exitCode));
}
} else {
if (this._configHelper.config.showExitAlert) {
this._notificationService.error(exitCodeMessage);
} else {
console.warn(exitCodeMessage);
}
}
}
}
this._onExit.fire(exitCode);
}
private _attachPressAnyKeyToCloseListener() {
this._processManager.addDisposable(dom.addDisposableListener(this._xterm.textarea, 'keypress', (event: KeyboardEvent) => {
this.dispose();
event.preventDefault();
}));
}
public reuseTerminal(shell?: IShellLaunchConfig): void {
// Kill and clear up the process, making the process manager ready for a new process
this._processManager.dispose();
// Ensure new processes' output starts at start of new line
this._xterm.write('\n\x1b[G');
// Print initialText if specified
if (shell.initialText) {
this._xterm.writeln(shell.initialText);
}
// Initialize new process
const oldTitle = this._title;
this._shellLaunchConfig = shell;
this._createProcess();
if (oldTitle !== this._title) {
this.setTitle(this._title, true);
}
this._processManager.onProcessData(data => this._onProcessData(data));
// Clean up waitOnExit state
if (this._isExiting && this._shellLaunchConfig.waitOnExit) {
this._xterm.setOption('disableStdin', false);
this._isExiting = false;
}
// Set the new shell launch config
this._shellLaunchConfig = shell;
}
private _sendRendererInput(input: string): void {
if (this._processManager) {
throw new Error('onRendererInput attempted to be used on a regular terminal');
}
// For terminal renderers onData fires on keystrokes and when sendText is called.
this._onRendererInput.fire(input);
}
private _onLineFeed(): void {
const buffer = (<any>this._xterm._core.buffer);
const newLine = buffer.lines.get(buffer.ybase + buffer.y);
if (!newLine.isWrapped) {
this._sendLineData(buffer, buffer.ybase + buffer.y - 1);
}
}
private _sendLineData(buffer: any, lineIndex: number): void {
let lineData = buffer.translateBufferLineToString(lineIndex, true);
while (lineIndex >= 0 && buffer.lines.get(lineIndex--).isWrapped) {
lineData = buffer.translateBufferLineToString(lineIndex, false) + lineData;
}
this._onLineData.fire(lineData);
}
public updateConfig(): void {
const config = this._configHelper.config;
this._setCursorBlink(config.cursorBlinking);
this._setCursorStyle(config.cursorStyle);
this._setCommandsToSkipShell(config.commandsToSkipShell);
this._setEnableBell(config.enableBell);
this._safeSetOption('scrollback', config.scrollback);
this._safeSetOption('macOptionIsMeta', config.macOptionIsMeta);
this._safeSetOption('macOptionClickForcesSelection', config.macOptionClickForcesSelection);
this._safeSetOption('rightClickSelectsWord', config.rightClickBehavior === 'selectWord');
this._safeSetOption('rendererType', config.rendererType === 'auto' ? 'canvas' : config.rendererType);
}
public updateAccessibilitySupport(): void {
const value = this._configurationService.getValue('editor.accessibilitySupport');
this._xterm.setOption('screenReaderMode', value === 'on');
}
private _setCursorBlink(blink: boolean): void {
if (this._xterm && this._xterm.getOption('cursorBlink') !== blink) {
this._xterm.setOption('cursorBlink', blink);
this._xterm.refresh(0, this._xterm.rows - 1);
}
}
private _setCursorStyle(style: string): void {
if (this._xterm && this._xterm.getOption('cursorStyle') !== style) {
// 'line' is used instead of bar in VS Code to be consistent with editor.cursorStyle
const xtermOption = style === 'line' ? 'bar' : style;
this._xterm.setOption('cursorStyle', xtermOption);
}
}
private _setCommandsToSkipShell(commands: string[]): void {
this._skipTerminalCommands = commands;
}
private _setEnableBell(isEnabled: boolean): void {
if (this._xterm) {
if (this._xterm.getOption('bellStyle') === 'sound') {
if (!this._configHelper.config.enableBell) {
this._xterm.setOption('bellStyle', 'none');
}
} else {
if (this._configHelper.config.enableBell) {
this._xterm.setOption('bellStyle', 'sound');
}
}
}
}
private _safeSetOption(key: string, value: any): void {
if (!this._xterm) {
return;
}
if (this._xterm.getOption(key) !== value) {
this._xterm.setOption(key, value);