-
Notifications
You must be signed in to change notification settings - Fork 30.1k
/
Copy pathterminalInstance.ts
2668 lines (2377 loc) · 107 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 { isFirefox } from 'vs/base/browser/browser';
import { BrowserFeatures } from 'vs/base/browser/canIUse';
import { DataTransfers } from 'vs/base/browser/dnd';
import * as dom from 'vs/base/browser/dom';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { Orientation } from 'vs/base/browser/ui/sash/sash';
import { DomScrollableElement } from 'vs/base/browser/ui/scrollbar/scrollableElement';
import { AutoOpenBarrier, Promises } from 'vs/base/common/async';
import { Codicon } from 'vs/base/common/codicons';
import { debounce } from 'vs/base/common/decorators';
import { ErrorNoTelemetry } from 'vs/base/common/errors';
import { Emitter, Event } from 'vs/base/common/event';
import { KeyCode } from 'vs/base/common/keyCodes';
import { ISeparator, template } from 'vs/base/common/labels';
import { Disposable, dispose, IDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { Schemas } from 'vs/base/common/network';
import * as path from 'vs/base/common/path';
import { isMacintosh, isWindows, OperatingSystem, OS } from 'vs/base/common/platform';
import { ScrollbarVisibility } from 'vs/base/common/scrollable';
import { withNullAsUndefined } from 'vs/base/common/types';
import { URI } from 'vs/base/common/uri';
import { TabFocus } from 'vs/editor/browser/config/tabFocus';
import { FindReplaceState } from 'vs/editor/contrib/find/browser/findState';
import * as nls from 'vs/nls';
import { IAccessibilityService } from 'vs/platform/accessibility/common/accessibility';
import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
import { CodeDataTransfers, containsDragType } from 'vs/platform/dnd/browser/dnd';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
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 { IOpenerService } from 'vs/platform/opener/common/opener';
import { IProductService } from 'vs/platform/product/common/productService';
import { IQuickInputService, IQuickPickItem, QuickPickItem } from 'vs/platform/quickinput/common/quickInput';
import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IMarkProperties, ITerminalCommand, TerminalCapability } from 'vs/platform/terminal/common/capabilities/capabilities';
import { TerminalCapabilityStoreMultiplexer } from 'vs/platform/terminal/common/capabilities/terminalCapabilityStore';
import { IProcessDataEvent, IProcessPropertyMap, IReconnectionProperties, IShellLaunchConfig, ITerminalDimensionsOverride, ITerminalLaunchError, PosixShellType, ProcessPropertyType, ShellIntegrationStatus, TerminalExitReason, TerminalIcon, TerminalLocation, TerminalSettingId, TerminalShellType, TitleEventSource, WindowsShellType } from 'vs/platform/terminal/common/terminal';
import { escapeNonWindowsPath } from 'vs/platform/terminal/common/terminalEnvironment';
import { formatMessageForTerminal } from 'vs/platform/terminal/common/terminalStrings';
import { activeContrastBorder, scrollbarSliderActiveBackground, scrollbarSliderBackground, scrollbarSliderHoverBackground } from 'vs/platform/theme/common/colorRegistry';
import { getIconRegistry } from 'vs/platform/theme/common/iconRegistry';
import { IColorTheme, ICssStyleCollector, IThemeService, registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { IWorkspaceContextService, IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import { IWorkspaceTrustRequestService } from 'vs/platform/workspace/common/workspaceTrust';
import { IViewDescriptorService, IViewsService, ViewContainerLocation } from 'vs/workbench/common/views';
import { TaskSettingId } from 'vs/workbench/contrib/tasks/common/tasks';
import { IDetectedLinks, TerminalLinkManager } from 'vs/workbench/contrib/terminal/browser/links/terminalLinkManager';
import { TerminalLinkQuickpick } from 'vs/workbench/contrib/terminal/browser/links/terminalLinkQuickpick';
import { IRequestAddInstanceToGroupEvent, ITerminalExternalLinkProvider, ITerminalInstance, TerminalDataTransfers } from 'vs/workbench/contrib/terminal/browser/terminal';
import { TerminalLaunchHelpAction } from 'vs/workbench/contrib/terminal/browser/terminalActions';
import { TerminalConfigHelper } from 'vs/workbench/contrib/terminal/browser/terminalConfigHelper';
import { TerminalEditorInput } from 'vs/workbench/contrib/terminal/browser/terminalEditorInput';
import { TerminalFindWidget } from 'vs/workbench/contrib/terminal/browser/terminalFindWidget';
import { getColorClass, getColorStyleElement, getStandardColors } from 'vs/workbench/contrib/terminal/browser/terminalIcon';
import { TerminalProcessManager } from 'vs/workbench/contrib/terminal/browser/terminalProcessManager';
import { showRunRecentQuickPick } from 'vs/workbench/contrib/terminal/browser/terminalRunRecentQuickPick';
import { ITerminalStatusList, TerminalStatus, TerminalStatusList } from 'vs/workbench/contrib/terminal/browser/terminalStatusList';
import { TypeAheadAddon } from 'vs/workbench/contrib/terminal/browser/terminalTypeAheadAddon';
import { getTerminalResourcesFromDragEvent, getTerminalUri } from 'vs/workbench/contrib/terminal/browser/terminalUri';
import { EnvironmentVariableInfoWidget } from 'vs/workbench/contrib/terminal/browser/widgets/environmentVariableInfoWidget';
import { TerminalWidgetManager } from 'vs/workbench/contrib/terminal/browser/widgets/widgetManager';
import { LineDataEventAddon } from 'vs/workbench/contrib/terminal/browser/xterm/lineDataEventAddon';
import { NavigationModeAddon } from 'vs/workbench/contrib/terminal/browser/xterm/navigationModeAddon';
import { XtermTerminal } from 'vs/workbench/contrib/terminal/browser/xterm/xtermTerminal';
import { IEnvironmentVariableCollection, IEnvironmentVariableInfo } from 'vs/workbench/contrib/terminal/common/environmentVariable';
import { deserializeEnvironmentVariableCollections } from 'vs/workbench/contrib/terminal/common/environmentVariableShared';
import { getCommandHistory, getDirectoryHistory } from 'vs/workbench/contrib/terminal/common/history';
import { DEFAULT_COMMANDS_TO_SKIP_SHELL, INavigationMode, ITerminalBackend, ITerminalProcessManager, ITerminalProfileResolverService, ProcessState, TerminalCommandId, TERMINAL_CREATION_COMMANDS, TERMINAL_VIEW_ID } from 'vs/workbench/contrib/terminal/common/terminal';
import { TerminalContextKeys } from 'vs/workbench/contrib/terminal/common/terminalContextKey';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { IHistoryService } from 'vs/workbench/services/history/common/history';
import { IWorkbenchLayoutService, Position } from 'vs/workbench/services/layout/browser/layoutService';
import { IPathService } from 'vs/workbench/services/path/common/pathService';
import { IPreferencesService } from 'vs/workbench/services/preferences/common/preferences';
import type { IMarker, ITerminalAddon, Terminal as XTermTerminal } from 'xterm';
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,
DefaultCols = 80,
DefaultRows = 30,
MaxSupportedCols = 5000,
MaxCanvasWidth = 8000
}
let xtermConstructor: Promise<typeof XTermTerminal> | undefined;
function getXtermConstructor(): Promise<typeof XTermTerminal> {
if (xtermConstructor) {
return xtermConstructor;
}
xtermConstructor = Promises.withAsyncBody<typeof XTermTerminal>(async (resolve) => {
const Terminal = (await import('xterm')).Terminal;
// 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;
}
interface ICanvasDimensions {
width: number;
height: number;
}
interface IGridDimensions {
cols: number;
rows: number;
}
const shellIntegrationSupportedShellTypes = [PosixShellType.Bash, PosixShellType.Zsh, PosixShellType.PowerShell, WindowsShellType.PowerShell];
const scrollbarHeight = 5;
export class TerminalInstance extends Disposable implements ITerminalInstance {
private static _lastKnownCanvasDimensions: ICanvasDimensions | undefined;
private static _lastKnownGridDimensions: IGridDimensions | undefined;
private static _instanceIdCounter = 1;
private readonly _scopedInstantiationService: IInstantiationService;
private readonly _processManager: ITerminalProcessManager;
private readonly _resource: URI;
private _shutdownPersistentProcessId: number | undefined;
// Enables disposal of the xterm onKey
// event when the CwdDetection capability
// is added
private _xtermOnKey: IDisposable | undefined;
private _xtermReadyPromise: Promise<XtermTerminal>;
private _xtermTypeAheadAddon: TypeAheadAddon | undefined;
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 _exitReason: TerminalExitReason | undefined;
private _skipTerminalCommands: string[];
private _shellType: TerminalShellType;
private _title: string = '';
private _titleSource: TitleEventSource = TitleEventSource.Process;
private _container: HTMLElement | undefined;
private _wrapperElement: (HTMLElement & { xterm?: XTermTerminal });
private _horizontalScrollbar: DomScrollableElement | undefined;
private _terminalFocusContextKey: IContextKey<boolean>;
private _terminalHasFixedWidth: IContextKey<boolean>;
private _terminalHasTextContextKey: IContextKey<boolean>;
private _terminalAltBufferActiveContextKey: IContextKey<boolean>;
private _terminalShellIntegrationEnabledContextKey: IContextKey<boolean>;
private _terminalA11yTreeFocusContextKey: IContextKey<boolean>;
private _navigationModeActiveContextKey: IContextKey<boolean>;
private _cols: number = 0;
private _rows: number = 0;
private _fixedCols: number | undefined;
private _fixedRows: number | undefined;
private _cwd: string | undefined = undefined;
private _initialCwd: string | undefined = undefined;
private _layoutSettingsChanged: boolean = true;
private _dimensionsOverride: ITerminalDimensionsOverride | undefined;
private _areLinksReady: boolean = false;
private _initialDataEvents: string[] | undefined = [];
private _containerReadyBarrier: AutoOpenBarrier;
private _attachBarrier: AutoOpenBarrier;
private _icon: TerminalIcon | undefined;
private _messageTitleDisposable: IDisposable | undefined;
private _widgetManager: TerminalWidgetManager = new TerminalWidgetManager();
private _linkManager: TerminalLinkManager | undefined;
private _environmentInfo: { widget: EnvironmentVariableInfoWidget; disposable: IDisposable } | undefined;
private _navigationModeAddon: INavigationMode & ITerminalAddon | undefined;
private _dndObserver: IDisposable | undefined;
private _terminalLinkQuickpick: TerminalLinkQuickpick | undefined;
private _lastLayoutDimensions: dom.Dimension | undefined;
private _hasHadInput: boolean;
private _description?: string;
private _processName: string = '';
private _sequence?: string;
private _staticTitle?: string;
private _workspaceFolder?: IWorkspaceFolder;
private _labelComputer?: TerminalLabelComputer;
private _userHome?: string;
private _hasScrollBar?: boolean;
private _target?: TerminalLocation | undefined;
private _disableShellIntegrationReporting: boolean | undefined;
private _usedShellIntegrationInjection: boolean = false;
readonly capabilities = new TerminalCapabilityStoreMultiplexer();
readonly statusList: ITerminalStatusList;
readonly findWidget: TerminalFindWidget;
xterm?: XtermTerminal;
disableLayout: boolean = false;
get waitOnExit(): ITerminalInstance['waitOnExit'] { return this._shellLaunchConfig.attachPersistentProcess?.waitOnExit || this._shellLaunchConfig.waitOnExit; }
set waitOnExit(value: ITerminalInstance['waitOnExit']) {
this._shellLaunchConfig.waitOnExit = value;
}
get target(): TerminalLocation | undefined { return this._target; }
set target(value: TerminalLocation | undefined) {
if (this.xterm) {
this.xterm.target = value;
}
this._target = value;
}
get disableShellIntegrationReporting(): boolean {
if (this._disableShellIntegrationReporting === undefined) {
this._disableShellIntegrationReporting = (this.shellLaunchConfig.hideFromUser || this.shellLaunchConfig.executable === undefined || this.shellType === undefined) || !shellIntegrationSupportedShellTypes.includes(this.shellType);
}
return this._disableShellIntegrationReporting;
}
get instanceId(): number { return this._instanceId; }
get resource(): URI { return this._resource; }
get cols(): number {
if (this._fixedCols !== undefined) {
return this._fixedCols;
}
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;
}
get rows(): number {
if (this._fixedRows !== undefined) {
return this._fixedRows;
}
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;
}
get isDisposed(): boolean { return this._isDisposed; }
get fixedCols(): number | undefined { return this._fixedCols; }
get fixedRows(): number | undefined { return this._fixedRows; }
get maxCols(): number { return this._cols; }
get maxRows(): number { return this._rows; }
// TODO: Ideally processId would be merged into processReady
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?
get processReady(): Promise<void> { return this._processManager.ptyProcessReady; }
get hasChildProcesses(): boolean { return this.shellLaunchConfig.attachPersistentProcess?.hasChildProcesses || this._processManager.hasChildProcesses; }
get reconnectionProperties(): IReconnectionProperties | undefined { return this.shellLaunchConfig.attachPersistentProcess?.reconnectionProperties || this.shellLaunchConfig.reconnectionProperties; }
get areLinksReady(): boolean { return this._areLinksReady; }
get initialDataEvents(): string[] | undefined { return this._initialDataEvents; }
get exitCode(): number | undefined { return this._exitCode; }
get exitReason(): TerminalExitReason | undefined { return this._exitReason; }
get hadFocusOnExit(): boolean { return this._hadFocusOnExit; }
get isTitleSetByProcess(): boolean { return !!this._messageTitleDisposable; }
get shellLaunchConfig(): IShellLaunchConfig { return this._shellLaunchConfig; }
get shellType(): TerminalShellType { return this._shellType; }
get os(): OperatingSystem | undefined { return this._processManager.os; }
get navigationMode(): INavigationMode | undefined { return this._navigationModeAddon; }
get isRemote(): boolean { return this._processManager.remoteAuthority !== undefined; }
get remoteAuthority(): string | undefined { return this._processManager.remoteAuthority; }
get hasFocus(): boolean { return this._wrapperElement.contains(document.activeElement) ?? false; }
get title(): string { return this._title; }
get titleSource(): TitleEventSource { return this._titleSource; }
get icon(): TerminalIcon | undefined { return this._getIcon(); }
get color(): string | undefined { return this._getColor(); }
get processName(): string { return this._processName; }
get sequence(): string | undefined { return this._sequence; }
get staticTitle(): string | undefined { return this._staticTitle; }
get workspaceFolder(): IWorkspaceFolder | undefined { return this._workspaceFolder; }
get cwd(): string | undefined { return this._cwd; }
get initialCwd(): string | undefined { return this._initialCwd; }
get description(): string | undefined {
if (this._description) {
return this._description;
}
const type = this.shellLaunchConfig.attachPersistentProcess?.type || this.shellLaunchConfig.type;
if (type) {
if (type === 'Task') {
return nls.localize('terminalTypeTask', "Task");
}
return nls.localize('terminalTypeLocal', "Local");
}
return undefined;
}
get userHome(): string | undefined { return this._userHome; }
// The onExit event is special in that it fires and is disposed after the terminal instance
// itself is disposed
private readonly _onExit = new Emitter<number | ITerminalLaunchError | undefined>();
readonly onExit = this._onExit.event;
private readonly _onDisposed = this._register(new Emitter<ITerminalInstance>());
readonly onDisposed = this._onDisposed.event;
private readonly _onProcessIdReady = this._register(new Emitter<ITerminalInstance>());
readonly onProcessIdReady = this._onProcessIdReady.event;
private readonly _onLinksReady = this._register(new Emitter<ITerminalInstance>());
readonly onLinksReady = this._onLinksReady.event;
private readonly _onTitleChanged = this._register(new Emitter<ITerminalInstance>());
readonly onTitleChanged = this._onTitleChanged.event;
private readonly _onIconChanged = this._register(new Emitter<ITerminalInstance>());
readonly onIconChanged = this._onIconChanged.event;
private readonly _onData = this._register(new Emitter<string>());
readonly onData = this._onData.event;
private readonly _onBinary = this._register(new Emitter<string>());
readonly onBinary = this._onBinary.event;
private readonly _onLineData = this._register(new Emitter<string>());
readonly onLineData = this._onLineData.event;
private readonly _onRequestExtHostProcess = this._register(new Emitter<ITerminalInstance>());
readonly onRequestExtHostProcess = this._onRequestExtHostProcess.event;
private readonly _onDimensionsChanged = this._register(new Emitter<void>());
readonly onDimensionsChanged = this._onDimensionsChanged.event;
private readonly _onMaximumDimensionsChanged = this._register(new Emitter<void>());
readonly onMaximumDimensionsChanged = this._onMaximumDimensionsChanged.event;
private readonly _onDidFocus = this._register(new Emitter<ITerminalInstance>());
readonly onDidFocus = this._onDidFocus.event;
private readonly _onDidBlur = this._register(new Emitter<ITerminalInstance>());
readonly onDidBlur = this._onDidBlur.event;
private readonly _onDidInputData = this._register(new Emitter<ITerminalInstance>());
readonly onDidInputData = this._onDidInputData.event;
private readonly _onRequestAddInstanceToGroup = this._register(new Emitter<IRequestAddInstanceToGroupEvent>());
readonly onRequestAddInstanceToGroup = this._onRequestAddInstanceToGroup.event;
private readonly _onDidChangeHasChildProcesses = this._register(new Emitter<boolean>());
readonly onDidChangeHasChildProcesses = this._onDidChangeHasChildProcesses.event;
private readonly _onDidChangeFindResults = new Emitter<{ resultIndex: number; resultCount: number } | undefined>();
readonly onDidChangeFindResults = this._onDidChangeFindResults.event;
constructor(
private readonly _terminalShellTypeContextKey: IContextKey<string>,
private readonly _terminalInRunCommandPicker: IContextKey<boolean>,
private readonly _configHelper: TerminalConfigHelper,
private _shellLaunchConfig: IShellLaunchConfig,
resource: URI | undefined,
@IContextKeyService readonly contextKeyService: IContextKeyService,
@IInstantiationService readonly instantiationService: IInstantiationService,
@ITerminalProfileResolverService private readonly _terminalProfileResolverService: ITerminalProfileResolverService,
@IPathService private readonly _pathService: IPathService,
@IKeybindingService private readonly _keybindingService: IKeybindingService,
@INotificationService private readonly _notificationService: INotificationService,
@IPreferencesService private readonly _preferencesService: IPreferencesService,
@IViewsService private readonly _viewsService: IViewsService,
@IClipboardService private readonly _clipboardService: IClipboardService,
@IThemeService private readonly _themeService: IThemeService,
@IConfigurationService private readonly _configurationService: IConfigurationService,
@ILogService private readonly _logService: ILogService,
@IDialogService private readonly _dialogService: IDialogService,
@IStorageService private readonly _storageService: IStorageService,
@IAccessibilityService private readonly _accessibilityService: IAccessibilityService,
@IProductService private readonly _productService: IProductService,
@IQuickInputService private readonly _quickInputService: IQuickInputService,
@IWorkbenchEnvironmentService workbenchEnvironmentService: IWorkbenchEnvironmentService,
@IWorkspaceContextService private readonly _workspaceContextService: IWorkspaceContextService,
@IEditorService private readonly _editorService: IEditorService,
@IWorkspaceTrustRequestService private readonly _workspaceTrustRequestService: IWorkspaceTrustRequestService,
@IHistoryService private readonly _historyService: IHistoryService,
@ITelemetryService private readonly _telemetryService: ITelemetryService,
@IOpenerService private readonly _openerService: IOpenerService,
@ICommandService private readonly _commandService: ICommandService
) {
super();
this._wrapperElement = document.createElement('div');
this._wrapperElement.classList.add('terminal-wrapper');
this._skipTerminalCommands = [];
this._isExiting = false;
this._hadFocusOnExit = false;
this._isVisible = false;
this._isDisposed = false;
this._instanceId = TerminalInstance._instanceIdCounter++;
this._hasHadInput = false;
this._fixedRows = _shellLaunchConfig.attachPersistentProcess?.fixedDimensions?.rows;
this._fixedCols = _shellLaunchConfig.attachPersistentProcess?.fixedDimensions?.cols;
// the resource is already set when it's been moved from another window
this._resource = resource || getTerminalUri(this._workspaceContextService.getWorkspace().id, this.instanceId, this.title);
if (this._shellLaunchConfig.attachPersistentProcess?.hideFromUser) {
this._shellLaunchConfig.hideFromUser = this._shellLaunchConfig.attachPersistentProcess.hideFromUser;
}
if (this._shellLaunchConfig.attachPersistentProcess?.isFeatureTerminal) {
this._shellLaunchConfig.isFeatureTerminal = this._shellLaunchConfig.attachPersistentProcess.isFeatureTerminal;
}
if (this._shellLaunchConfig.attachPersistentProcess?.type) {
this._shellLaunchConfig.type = this._shellLaunchConfig.attachPersistentProcess.type;
}
if (this.shellLaunchConfig.cwd) {
const cwdUri = typeof this._shellLaunchConfig.cwd === 'string' ? URI.from({
scheme: Schemas.file,
path: this._shellLaunchConfig.cwd
}) : this._shellLaunchConfig.cwd;
if (cwdUri) {
this._workspaceFolder = withNullAsUndefined(this._workspaceContextService.getWorkspaceFolder(cwdUri));
}
}
if (!this._workspaceFolder) {
const activeWorkspaceRootUri = this._historyService.getLastActiveWorkspaceRoot();
this._workspaceFolder = activeWorkspaceRootUri ? withNullAsUndefined(this._workspaceContextService.getWorkspaceFolder(activeWorkspaceRootUri)) : undefined;
}
const scopedContextKeyService = this._register(contextKeyService.createScoped(this._wrapperElement));
this._scopedInstantiationService = this.instantiationService.createChild(new ServiceCollection(
[IContextKeyService, scopedContextKeyService]
));
this._terminalFocusContextKey = TerminalContextKeys.focus.bindTo(scopedContextKeyService);
this._terminalHasFixedWidth = TerminalContextKeys.terminalHasFixedWidth.bindTo(scopedContextKeyService);
this._terminalHasTextContextKey = TerminalContextKeys.textSelected.bindTo(scopedContextKeyService);
this._terminalA11yTreeFocusContextKey = TerminalContextKeys.a11yTreeFocus.bindTo(scopedContextKeyService);
this._navigationModeActiveContextKey = TerminalContextKeys.navigationModeActive.bindTo(scopedContextKeyService);
this._terminalAltBufferActiveContextKey = TerminalContextKeys.altBufferActive.bindTo(scopedContextKeyService);
this._terminalShellIntegrationEnabledContextKey = TerminalContextKeys.terminalShellIntegrationEnabled.bindTo(scopedContextKeyService);
this.findWidget = this._scopedInstantiationService.createInstance(TerminalFindWidget, new FindReplaceState(), this);
this._logService.trace(`terminalInstance#ctor (instanceId: ${this.instanceId})`, this._shellLaunchConfig);
this._register(this.capabilities.onDidAddCapability(e => {
this._logService.debug('terminalInstance added capability', e);
if (e === TerminalCapability.CwdDetection) {
this.capabilities.get(TerminalCapability.CwdDetection)?.onDidChangeCwd(e => {
this._cwd = e;
this._xtermOnKey?.dispose();
this._setTitle(this.title, TitleEventSource.Config);
this._scopedInstantiationService.invokeFunction(getDirectoryHistory)?.add(e, { remoteAuthority: this.remoteAuthority });
});
} else if (e === TerminalCapability.CommandDetection) {
this.capabilities.get(TerminalCapability.CommandDetection)?.onCommandFinished(e => {
if (e.command.trim().length > 0) {
this._scopedInstantiationService.invokeFunction(getCommandHistory)?.add(e.command, { shellType: this._shellType });
}
});
}
}));
this._register(this.capabilities.onDidRemoveCapability(e => this._logService.debug('terminalInstance removed capability', e)));
// 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. This also doesn't work when the default profile
// setting is set to null, that's handled after the process is created.
if (!this.shellLaunchConfig.executable && !workbenchEnvironmentService.remoteAuthority) {
this._terminalProfileResolverService.resolveIcon(this._shellLaunchConfig, OS);
}
this._icon = _shellLaunchConfig.attachPersistentProcess?.icon || _shellLaunchConfig.icon;
// When a custom pty is used set the name immediately so it gets passed over to the exthost
// and is available when Pseudoterminal.open fires.
if (this.shellLaunchConfig.customPtyImplementation) {
this._setTitle(this._shellLaunchConfig.name, TitleEventSource.Api);
}
this.statusList = this._scopedInstantiationService.createInstance(TerminalStatusList);
this._initDimensions();
this._processManager = this._createProcessManager();
this._register(toDisposable(() => this._dndObserver?.dispose()));
this._containerReadyBarrier = new AutoOpenBarrier(Constants.WaitForContainerThreshold);
this._attachBarrier = new AutoOpenBarrier(1000);
this._xtermReadyPromise = this._createXterm();
this._xtermReadyPromise.then(async () => {
// Wait for a period to allow a container to be ready
await this._containerReadyBarrier.wait();
// Resolve the executable ahead of time if shell integration is enabled, this should not
// be done for custom PTYs as that would cause extension Pseudoterminal-based terminals
// to hang in resolver extensions
if (!this.shellLaunchConfig.customPtyImplementation && this._configHelper.config.shellIntegration?.enabled && !this.shellLaunchConfig.executable) {
const os = await this._processManager.getBackendOS();
const defaultProfile = (await this._terminalProfileResolverService.getDefaultProfile({ remoteAuthority: this.remoteAuthority, os }));
this.shellLaunchConfig.executable = defaultProfile.path;
this.shellLaunchConfig.args = defaultProfile.args;
this.shellLaunchConfig.icon = defaultProfile.icon;
this.shellLaunchConfig.color = defaultProfile.color;
}
await this._createProcess();
// Re-establish the title after reconnect
if (this.shellLaunchConfig.attachPersistentProcess) {
this._cwd = this.shellLaunchConfig.attachPersistentProcess.cwd;
this._setTitle(this.shellLaunchConfig.attachPersistentProcess.title, this.shellLaunchConfig.attachPersistentProcess.titleSource);
this.setShellType(this.shellType);
}
if (this._fixedCols) {
await this._addScrollbar();
}
}).catch((err) => {
// Ignore exceptions if the terminal is already disposed
if (!this._isDisposed) {
throw err;
}
});
this._register(this._configurationService.onDidChangeConfiguration(async e => {
if (e.affectsConfiguration('terminal.integrated')) {
this.updateConfig();
this.setVisible(this._isVisible);
}
const layoutSettings: string[] = [
TerminalSettingId.FontSize,
TerminalSettingId.FontFamily,
TerminalSettingId.FontWeight,
TerminalSettingId.FontWeightBold,
TerminalSettingId.LetterSpacing,
TerminalSettingId.LineHeight,
'editor.fontFamily'
];
if (layoutSettings.some(id => e.affectsConfiguration(id))) {
this._layoutSettingsChanged = true;
await this._resize();
}
if (e.affectsConfiguration(TerminalSettingId.UnicodeVersion)) {
this._updateUnicodeVersion();
}
if (e.affectsConfiguration('editor.accessibilitySupport')) {
this.updateAccessibilitySupport();
}
if (
e.affectsConfiguration(TerminalSettingId.TerminalTitle) ||
e.affectsConfiguration(TerminalSettingId.TerminalTitleSeparator) ||
e.affectsConfiguration(TerminalSettingId.TerminalDescription)) {
this._labelComputer?.refreshLabel();
}
}));
this._register(this._workspaceContextService.onDidChangeWorkspaceFolders(() => this._labelComputer?.refreshLabel()));
// 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(toDisposable(() => {
if (initialDataEventsTimeout) {
window.clearTimeout(initialDataEventsTimeout);
}
}));
this._register(this.findWidget.focusTracker.onDidFocus(() => this._container?.classList.toggle('find-focused', true)));
this._register(this.findWidget.focusTracker.onDidBlur(() => this._container?.classList.toggle('find-focused', false)));
}
private _getIcon(): TerminalIcon | undefined {
if (!this._icon) {
this._icon = this._processManager.processState >= ProcessState.Launching
? getIconRegistry().getIcon(this._configurationService.getValue(TerminalSettingId.TabsDefaultIcon))
: undefined;
}
return this._icon;
}
private _getColor(): string | undefined {
if (this.shellLaunchConfig.color) {
return this.shellLaunchConfig.color;
}
if (this.shellLaunchConfig?.attachPersistentProcess?.color) {
return this.shellLaunchConfig.attachPersistentProcess.color;
}
if (this._processManager.processState >= ProcessState.Launching) {
return undefined;
}
return undefined;
}
private _initDimensions(): void {
// The terminal panel needs to have been created to get the real view dimensions
if (!this._container) {
// Set the fallback dimensions if not
this._cols = Constants.DefaultCols;
this._rows = Constants.DefaultRows;
return;
}
const computedStyle = window.getComputedStyle(this._container);
const width = parseInt(computedStyle.width);
const height = parseInt(computedStyle.height);
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.xterm ? this.xterm.getFont() : this._configHelper.getFont();
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.xterm ? this.xterm.getFont() : this._configHelper.getFont();
if (!font || !font.charWidth || !font.charHeight) {
return undefined;
}
if (!this.xterm?.raw.element) {
return undefined;
}
const computedStyle = window.getComputedStyle(this.xterm.raw.element);
const horizontalPadding = parseInt(computedStyle.paddingLeft) + parseInt(computedStyle.paddingRight);
const verticalPadding = parseInt(computedStyle.paddingTop) + parseInt(computedStyle.paddingBottom);
TerminalInstance._lastKnownCanvasDimensions = new dom.Dimension(
Math.min(Constants.MaxCanvasWidth, width - horizontalPadding),
height + (this._hasScrollBar && !this._horizontalScrollbar ? -scrollbarHeight : 0) - 2/* bottom padding */ - verticalPadding);
return TerminalInstance._lastKnownCanvasDimensions;
}
set shutdownPersistentProcessId(shutdownPersistentProcessId: number | undefined) {
this._shutdownPersistentProcessId = shutdownPersistentProcessId;
}
get persistentProcessId(): number | undefined { return this._processManager.persistentProcessId ?? this._shutdownPersistentProcessId; }
get shouldPersist(): boolean { return (this._processManager.shouldPersist || this._shutdownPersistentProcessId !== undefined) && !this.shellLaunchConfig.isTransient && (!this.reconnectionProperties || this._configurationService.getValue(TaskSettingId.Reconnection) === true); }
/**
* Create xterm.js instance and attach data listeners.
*/
protected async _createXterm(): Promise<XtermTerminal> {
const Terminal = await getXtermConstructor();
if (this._isDisposed) {
throw new ErrorNoTelemetry('Terminal disposed of during xterm.js creation');
}
const xterm = this._scopedInstantiationService.createInstance(XtermTerminal, Terminal, this._configHelper, this._cols, this._rows, this.target || TerminalLocation.Panel, this.capabilities, this.disableShellIntegrationReporting);
this.xterm = xterm;
const lineDataEventAddon = new LineDataEventAddon();
this.xterm.raw.loadAddon(lineDataEventAddon);
this.updateAccessibilitySupport();
this.xterm.onDidRequestRunCommand(e => {
if (e.copyAsHtml) {
this.copySelection(true, e.command);
} else {
this.sendText(e.command.command, true);
}
});
// Write initial text, deferring onLineFeed listener when applicable to avoid firing
// onLineData events containing initialText
if (this._shellLaunchConfig.initialText) {
this._writeInitialText(this.xterm, () => {
lineDataEventAddon.onLineData(e => this._onLineData.fire(e));
});
} else {
lineDataEventAddon.onLineData(e => this._onLineData.fire(e));
}
// Delay the creation of the bell listener to avoid showing the bell when the terminal
// starts up or reconnects
setTimeout(() => {
xterm.raw.onBell(() => {
if (this._configHelper.config.enableBell) {
this.statusList.add({
id: TerminalStatus.Bell,
severity: Severity.Warning,
icon: Codicon.bell,
tooltip: nls.localize('bellStatus', "Bell")
}, this._configHelper.config.bellDuration);
}
});
}, 1000);
this._xtermOnKey = xterm.raw.onKey(e => this._onKey(e.key, e.domEvent));
xterm.raw.onSelectionChange(async () => this._onSelectionChange());
xterm.raw.buffer.onBufferChange(() => this._refreshAltBufferContextKey());
this._processManager.onProcessData(e => this._onProcessData(e));
xterm.raw.onData(async data => {
await this._processManager.write(data);
this._onDidInputData.fire(this);
});
xterm.raw.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(async (processTraits) => {
// If links are ready, do not re-create the manager.
if (this._areLinksReady) {
return;
}
if (this._processManager.os) {
lineDataEventAddon.setOperatingSystem(this._processManager.os);
}
if (this._processManager.os === OperatingSystem.Windows) {
xterm.raw.options.windowsMode = processTraits.requiresWindowsMode || false;
}
this._linkManager = this._scopedInstantiationService.createInstance(TerminalLinkManager, xterm.raw, this._processManager!, this.capabilities);
this._areLinksReady = true;
this._onLinksReady.fire(this);
});
this._processManager.onRestoreCommands(e => this.xterm?.shellIntegration.deserialize(e));
this._loadTypeAheadAddon(xterm);
this._register(this._configurationService.onDidChangeConfiguration(e => {
if (e.affectsConfiguration(TerminalSettingId.LocalEchoEnabled)) {
this._loadTypeAheadAddon(xterm);
}
}));
this._pathService.userHome().then(userHome => {
this._userHome = userHome.fsPath;
});
if (this._isVisible) {
this._open();
}
return xterm;
}
private _loadTypeAheadAddon(xterm: XtermTerminal): void {
const enabled = this._configHelper.config.localEchoEnabled;
const isRemote = !!this.remoteAuthority;
if (enabled === 'off' || enabled === 'auto' && !isRemote) {
return this._xtermTypeAheadAddon?.dispose();
}
if (this._xtermTypeAheadAddon) {
return;
}
if (enabled === 'on' || (enabled === 'auto' && isRemote)) {
this._xtermTypeAheadAddon = this._register(this._scopedInstantiationService.createInstance(TypeAheadAddon, this._processManager, this._configHelper));
xterm.raw.loadAddon(this._xtermTypeAheadAddon);
}
}
async showLinkQuickpick(extended?: boolean): Promise<void> {
if (!this._terminalLinkQuickpick) {
this._terminalLinkQuickpick = this._scopedInstantiationService.createInstance(TerminalLinkQuickpick);
this._terminalLinkQuickpick.onDidRequestMoreLinks(() => {
this.showLinkQuickpick(true);
});
}
const links = await this._getLinks(extended);
if (!links) {
return;
}
return await this._terminalLinkQuickpick.show(links);
}
private async _getLinks(extended?: boolean): Promise<IDetectedLinks | undefined> {
if (!this.areLinksReady || !this._linkManager) {
throw new Error('terminal links are not ready, cannot generate link quick pick');
}
if (!this.xterm) {
throw new Error('no xterm');
}
return this._linkManager.getLinks(extended);
}
async openRecentLink(type: 'localFile' | 'url'): Promise<void> {
if (!this.areLinksReady || !this._linkManager) {
throw new Error('terminal links are not ready, cannot open a link');
}
if (!this.xterm) {
throw new Error('no xterm');
}
this._linkManager.openRecentLink(type);
}
async runRecent(type: 'command' | 'cwd', filterMode?: 'fuzzy' | 'contiguous', value?: string): Promise<void> {
return this._scopedInstantiationService.invokeFunction(
showRunRecentQuickPick, this, this._terminalInRunCommandPicker, type, filterMode, value
);
}
detachFromElement(): void {
this._wrapperElement.remove();
this._container = undefined;
}
attachToElement(container: HTMLElement): void {
// The container did not change, do nothing
if (this._container === container) {
return;
}
this._attachBarrier.open();
// The container changed, reattach
this._container = container;
this._container.appendChild(this._wrapperElement);
this._container.appendChild(this.findWidget.getDomNode());
setTimeout(() => this._initDragAndDrop(container));
}
/**
* Opens the the terminal instance inside the parent DOM element previously set with
* `attachToElement`, you must ensure the parent DOM element is explicitly visible before
* invoking this function as it performs some DOM calculations internally
*/
private _open(): void {
if (!this.xterm || this.xterm.raw.element) {
return;
}
if (!this._container || !this._container.isConnected) {
throw new Error('A container element needs to be set with `attachToElement` and be part of the DOM before calling `_open`');
}
const xtermElement = document.createElement('div');
this._wrapperElement.appendChild(xtermElement);
this._container.appendChild(this._wrapperElement);
this._container.appendChild(this.findWidget.getDomNode());
const xterm = this.xterm;
// Attach the xterm object to the DOM, exposing it to the smoke tests
this._wrapperElement.xterm = xterm.raw;
const screenElement = xterm.attachToElement(xtermElement);
this._register(xterm.onDidChangeFindResults(() => this.findWidget.updateResultCount()));
this._register(xterm.shellIntegration.onDidChangeStatus(() => {
if (this.hasFocus) {
this._setShellIntegrationContextKey();
} else {
this._terminalShellIntegrationEnabledContextKey.reset();
}
}));
if (!xterm.raw.element || !xterm.raw.textarea) {
throw new Error('xterm elements not set after open');
}
this._setAriaLabel(xterm.raw, this._instanceId, this._title);
xterm.raw.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_KEY = '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_KEY, StorageScope.APPLICATION, 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_KEY, StorageScope.APPLICATION, 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({ jsonEditor: false, query: `@id:${TerminalSettingId.CommandsToSkipShell},${TerminalSettingId.SendKeybindingsToShell},${TerminalSettingId.AllowChords}` });
}
} as IPromptChoice
]
);
this._storageService.store(SHOW_TERMINAL_CONFIG_PROMPT_KEY, false, StorageScope.APPLICATION, 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.raw.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();
});
}));
this._register(dom.addDisposableListener(xterm.raw.element, 'touchstart', () => {
xterm.raw.focus();
}));
// xterm.js currently drops selection on keyup as we need to handle this case.