-
Notifications
You must be signed in to change notification settings - Fork 30.5k
/
Copy pathterminalInstance.ts
2727 lines (2450 loc) · 111 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 '../../../../base/browser/browser.js';
import { BrowserFeatures } from '../../../../base/browser/canIUse.js';
import { DataTransfers } from '../../../../base/browser/dnd.js';
import * as dom from '../../../../base/browser/dom.js';
import { StandardKeyboardEvent } from '../../../../base/browser/keyboardEvent.js';
import { Orientation } from '../../../../base/browser/ui/sash/sash.js';
import { DomScrollableElement } from '../../../../base/browser/ui/scrollbar/scrollableElement.js';
import { AutoOpenBarrier, Barrier, Promises, disposableTimeout, timeout } from '../../../../base/common/async.js';
import { Codicon } from '../../../../base/common/codicons.js';
import { debounce } from '../../../../base/common/decorators.js';
import { onUnexpectedError } from '../../../../base/common/errors.js';
import { Emitter, Event } from '../../../../base/common/event.js';
import { KeyCode } from '../../../../base/common/keyCodes.js';
import { ISeparator, template } from '../../../../base/common/labels.js';
import { Disposable, DisposableMap, DisposableStore, IDisposable, ImmortalReference, MutableDisposable, dispose, toDisposable, type IReference } from '../../../../base/common/lifecycle.js';
import { Schemas } from '../../../../base/common/network.js';
import * as path from '../../../../base/common/path.js';
import { OS, OperatingSystem, isMacintosh, isWindows } from '../../../../base/common/platform.js';
import { ScrollbarVisibility } from '../../../../base/common/scrollable.js';
import { URI } from '../../../../base/common/uri.js';
import { TabFocus } from '../../../../editor/browser/config/tabFocus.js';
import * as nls from '../../../../nls.js';
import { IAccessibilityService } from '../../../../platform/accessibility/common/accessibility.js';
import { AccessibilitySignal, IAccessibilitySignalService } from '../../../../platform/accessibilitySignal/browser/accessibilitySignalService.js';
import { ICommandService } from '../../../../platform/commands/common/commands.js';
import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js';
import { IContextKey, IContextKeyService } from '../../../../platform/contextkey/common/contextkey.js';
import { CodeDataTransfers, containsDragType, getPathForFile } from '../../../../platform/dnd/browser/dnd.js';
import { FileSystemProviderCapabilities, IFileService } from '../../../../platform/files/common/files.js';
import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js';
import { ServiceCollection } from '../../../../platform/instantiation/common/serviceCollection.js';
import { IKeybindingService } from '../../../../platform/keybinding/common/keybinding.js';
import { ResultKind } from '../../../../platform/keybinding/common/keybindingResolver.js';
import { INotificationService, IPromptChoice, Severity } from '../../../../platform/notification/common/notification.js';
import { IOpenerService } from '../../../../platform/opener/common/opener.js';
import { IProductService } from '../../../../platform/product/common/productService.js';
import { IQuickInputService, IQuickPickItem, QuickPickItem } from '../../../../platform/quickinput/common/quickInput.js';
import { IStorageService, StorageScope, StorageTarget } from '../../../../platform/storage/common/storage.js';
import { ITelemetryService } from '../../../../platform/telemetry/common/telemetry.js';
import { IMarkProperties, TerminalCapability } from '../../../../platform/terminal/common/capabilities/capabilities.js';
import { TerminalCapabilityStoreMultiplexer } from '../../../../platform/terminal/common/capabilities/terminalCapabilityStore.js';
import { IEnvironmentVariableCollection, IMergedEnvironmentVariableCollection } from '../../../../platform/terminal/common/environmentVariable.js';
import { deserializeEnvironmentVariableCollections } from '../../../../platform/terminal/common/environmentVariableShared.js';
import { GeneralShellType, IProcessDataEvent, IProcessPropertyMap, IReconnectionProperties, IShellLaunchConfig, ITerminalDimensionsOverride, ITerminalLaunchError, ITerminalLogService, PosixShellType, ProcessPropertyType, ShellIntegrationStatus, TerminalExitReason, TerminalIcon, TerminalLocation, TerminalSettingId, TerminalShellType, TitleEventSource, WindowsShellType } from '../../../../platform/terminal/common/terminal.js';
import { formatMessageForTerminal } from '../../../../platform/terminal/common/terminalStrings.js';
import { editorBackground } from '../../../../platform/theme/common/colorRegistry.js';
import { getIconRegistry } from '../../../../platform/theme/common/iconRegistry.js';
import { IColorTheme, IThemeService } from '../../../../platform/theme/common/themeService.js';
import { IWorkspaceContextService, IWorkspaceFolder } from '../../../../platform/workspace/common/workspace.js';
import { IWorkspaceTrustRequestService } from '../../../../platform/workspace/common/workspaceTrust.js';
import { PANEL_BACKGROUND, SIDE_BAR_BACKGROUND } from '../../../common/theme.js';
import { IViewDescriptorService, ViewContainerLocation } from '../../../common/views.js';
import { IViewsService } from '../../../services/views/common/viewsService.js';
import { AccessibilityVerbositySettingId } from '../../accessibility/browser/accessibilityConfiguration.js';
import { IRequestAddInstanceToGroupEvent, ITerminalConfigurationService, ITerminalContribution, ITerminalInstance, IXtermColorProvider, TerminalDataTransfers } from './terminal.js';
import { TerminalLaunchHelpAction } from './terminalActions.js';
import { TerminalEditorInput } from './terminalEditorInput.js';
import { TerminalExtensionsRegistry } from './terminalExtensions.js';
import { getColorClass, createColorStyleElement, getStandardColors } from './terminalIcon.js';
import { TerminalProcessManager } from './terminalProcessManager.js';
import { ITerminalStatusList, TerminalStatus, TerminalStatusList } from './terminalStatusList.js';
import { getTerminalResourcesFromDragEvent, getTerminalUri } from './terminalUri.js';
import { TerminalWidgetManager } from './widgets/widgetManager.js';
import { LineDataEventAddon } from './xterm/lineDataEventAddon.js';
import { XtermTerminal, getXtermScaledDimensions } from './xterm/xtermTerminal.js';
import { IEnvironmentVariableInfo } from '../common/environmentVariable.js';
import { DEFAULT_COMMANDS_TO_SKIP_SHELL, ITerminalProcessManager, ITerminalProfileResolverService, ProcessState, TERMINAL_CREATION_COMMANDS, TERMINAL_VIEW_ID, TerminalCommandId } from '../common/terminal.js';
import { TERMINAL_BACKGROUND_COLOR } from '../common/terminalColorRegistry.js';
import { TerminalContextKeys } from '../common/terminalContextKey.js';
import { getWorkspaceForTerminal, preparePathForShell } from '../common/terminalEnvironment.js';
import { IEditorService } from '../../../services/editor/common/editorService.js';
import { IWorkbenchEnvironmentService } from '../../../services/environment/common/environmentService.js';
import { IHistoryService } from '../../../services/history/common/history.js';
import { isHorizontal, IWorkbenchLayoutService } from '../../../services/layout/browser/layoutService.js';
import { IPathService } from '../../../services/path/common/pathService.js';
import { IPreferencesService } from '../../../services/preferences/common/preferences.js';
import { importAMDNodeModule } from '../../../../amdX.js';
import type { IMarker, Terminal as XTermTerminal } from '@xterm/xterm';
import { AccessibilityCommandId } from '../../accessibility/common/accessibilityCommands.js';
import { terminalStrings } from '../common/terminalStrings.js';
import { TerminalIconPicker } from './terminalIconPicker.js';
import { TerminalResizeDebouncer } from './terminalResizeDebouncer.js';
import { openContextMenu } from './terminalContextMenu.js';
import type { IMenu } from '../../../../platform/actions/common/actions.js';
import { IContextMenuService } from '../../../../platform/contextview/browser/contextView.js';
import { TerminalContribCommandId } from '../terminalContribExports.js';
import type { IProgressState } from '@xterm/addon-progress';
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,
MaxCanvasWidth = 4096
}
let xtermConstructor: Promise<typeof XTermTerminal> | undefined;
interface ICanvasDimensions {
width: number;
height: number;
}
interface IGridDimensions {
cols: number;
rows: number;
}
const shellIntegrationSupportedShellTypes: (PosixShellType | GeneralShellType | WindowsShellType)[] = [
PosixShellType.Bash,
PosixShellType.Zsh,
GeneralShellType.PowerShell,
GeneralShellType.Python,
];
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 _contributions: Map<string, ITerminalContribution> = new Map();
private readonly _resource: URI;
/**
* Resolves when xterm.js is ready, this will be undefined if the terminal instance is disposed
* before xterm.js could be created.
*/
private _xtermReadyPromise: Promise<XtermTerminal | 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 _exitCode: number | undefined;
private _exitReason: TerminalExitReason | undefined;
private _skipTerminalCommands: string[];
private _shellType: TerminalShellType | undefined;
private _title: string = '';
private _titleSource: TitleEventSource = TitleEventSource.Process;
private _container: HTMLElement | undefined;
private _wrapperElement: (HTMLElement & { xterm?: XTermTerminal });
get domElement(): HTMLElement { return this._wrapperElement; }
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 _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 _injectedArgs: string[] | undefined = undefined;
private _layoutSettingsChanged: boolean = true;
private _dimensionsOverride: ITerminalDimensionsOverride | undefined;
private _areLinksReady: boolean = false;
private readonly _initialDataEventsListener: MutableDisposable<IDisposable> = this._register(new MutableDisposable());
private _initialDataEvents: string[] | undefined = [];
private _containerReadyBarrier: AutoOpenBarrier;
private _attachBarrier: AutoOpenBarrier;
private _icon: TerminalIcon | undefined;
private readonly _messageTitleDisposable: MutableDisposable<IDisposable> = this._register(new MutableDisposable());
private _widgetManager: TerminalWidgetManager;
private readonly _dndObserver: MutableDisposable<IDisposable> = this._register(new MutableDisposable());
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 _usedShellIntegrationInjection: boolean = false;
get usedShellIntegrationInjection(): boolean { return this._usedShellIntegrationInjection; }
private _lineDataEventAddon: LineDataEventAddon | undefined;
private readonly _scopedContextKeyService: IContextKeyService;
private _resizeDebouncer?: TerminalResizeDebouncer;
private _pauseInputEventBarrier: Barrier | undefined;
pauseInputEvents(barrier: Barrier): void {
this._pauseInputEventBarrier = barrier;
}
readonly capabilities = this._register(new TerminalCapabilityStoreMultiplexer());
readonly statusList: ITerminalStatusList;
get store(): DisposableStore {
return this._store;
}
get extEnvironmentVariableCollection(): IMergedEnvironmentVariableCollection | undefined { return this._processManager.extEnvironmentVariableCollection; }
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;
}
private _targetRef: ImmortalReference<TerminalLocation | undefined> = new ImmortalReference(undefined);
get targetRef(): IReference<TerminalLocation | undefined> { return this._targetRef; }
get target(): TerminalLocation | undefined { return this._targetRef.object; }
set target(value: TerminalLocation | undefined) {
this._targetRef.object = value;
this._onDidChangeTarget.fire(value);
}
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._store.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.value; }
get shellLaunchConfig(): IShellLaunchConfig { return this._shellLaunchConfig; }
get shellType(): TerminalShellType | undefined { return this._shellType; }
get os(): OperatingSystem | undefined { return this._processManager.os; }
get isRemote(): boolean { return this._processManager.remoteAuthority !== undefined; }
get remoteAuthority(): string | undefined { return this._processManager.remoteAuthority; }
get hasFocus(): boolean { return dom.isAncestorOfActiveElement(this._wrapperElement); }
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 progressState(): IProgressState | undefined { return this.xterm?.progressState; }
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;
switch (type) {
case 'Task': return terminalStrings.typeTask;
case 'Local': return terminalStrings.typeLocal;
default: return undefined;
}
}
get userHome(): string | undefined { return this._userHome; }
get shellIntegrationNonce(): string { return this._processManager.shellIntegrationNonce; }
get injectedArgs(): string[] | undefined { return this._injectedArgs; }
// 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 _onProcessReplayComplete = this._register(new Emitter<void>());
readonly onProcessReplayComplete = this._onProcessReplayComplete.event;
private readonly _onTitleChanged = this._register(new Emitter<ITerminalInstance>());
readonly onTitleChanged = this._onTitleChanged.event;
private readonly _onIconChanged = this._register(new Emitter<{ instance: ITerminalInstance; userInitiated: boolean }>());
readonly onIconChanged = this._onIconChanged.event;
private readonly _onWillData = this._register(new Emitter<string>());
readonly onWillData = this._onWillData.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 _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 _onDidRequestFocus = this._register(new Emitter<void>());
readonly onDidRequestFocus = this._onDidRequestFocus.event;
private readonly _onDidBlur = this._register(new Emitter<ITerminalInstance>());
readonly onDidBlur = this._onDidBlur.event;
private readonly _onDidInputData = this._register(new Emitter<string>());
readonly onDidInputData = this._onDidInputData.event;
private readonly _onDidChangeSelection = this._register(new Emitter<ITerminalInstance>());
readonly onDidChangeSelection = this._onDidChangeSelection.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 _onDidExecuteText = this._register(new Emitter<void>());
readonly onDidExecuteText = this._onDidExecuteText.event;
private readonly _onDidChangeTarget = this._register(new Emitter<TerminalLocation | undefined>());
readonly onDidChangeTarget = this._onDidChangeTarget.event;
private readonly _onDidSendText = this._register(new Emitter<string>());
readonly onDidSendText = this._onDidSendText.event;
private readonly _onDidChangeShellType = this._register(new Emitter<TerminalShellType>());
readonly onDidChangeShellType = this._onDidChangeShellType.event;
private readonly _onDidChangeVisibility = this._register(new Emitter<boolean>());
readonly onDidChangeVisibility = this._onDidChangeVisibility.event;
private readonly _onLineData = this._register(new Emitter<string>({
onDidAddFirstListener: async () => (this.xterm ?? await this._xtermReadyPromise)?.raw.loadAddon(this._lineDataEventAddon!)
}));
readonly onLineData = this._onLineData.event;
constructor(
private readonly _terminalShellTypeContextKey: IContextKey<string>,
private _shellLaunchConfig: IShellLaunchConfig,
@IContextKeyService private readonly _contextKeyService: IContextKeyService,
@IContextMenuService private readonly _contextMenuService: IContextMenuService,
@IInstantiationService instantiationService: IInstantiationService,
@ITerminalConfigurationService private readonly _terminalConfigurationService: ITerminalConfigurationService,
@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,
@IThemeService private readonly _themeService: IThemeService,
@IConfigurationService private readonly _configurationService: IConfigurationService,
@ITerminalLogService private readonly _logService: ITerminalLogService,
@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,
@IAccessibilitySignalService private readonly _accessibilitySignalService: IAccessibilitySignalService,
@IViewDescriptorService private readonly _viewDescriptorService: IViewDescriptorService,
) {
super();
this._wrapperElement = document.createElement('div');
this._wrapperElement.classList.add('terminal-wrapper');
this._widgetManager = this._register(instantiationService.createInstance(TerminalWidgetManager));
this._skipTerminalCommands = [];
this._isExiting = false;
this._hadFocusOnExit = false;
this._isVisible = false;
this._instanceId = TerminalInstance._instanceIdCounter++;
this._hasHadInput = false;
this._fixedRows = _shellLaunchConfig.attachPersistentProcess?.fixedDimensions?.rows;
this._fixedCols = _shellLaunchConfig.attachPersistentProcess?.fixedDimensions?.cols;
this._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 = this._workspaceContextService.getWorkspaceFolder(cwdUri) ?? undefined;
}
}
if (!this._workspaceFolder) {
const activeWorkspaceRootUri = this._historyService.getLastActiveWorkspaceRoot();
this._workspaceFolder = activeWorkspaceRootUri ? this._workspaceContextService.getWorkspaceFolder(activeWorkspaceRootUri) ?? undefined : undefined;
}
const scopedContextKeyService = this._register(_contextKeyService.createScoped(this._wrapperElement));
this._scopedContextKeyService = scopedContextKeyService;
this._scopedInstantiationService = this._register(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._terminalAltBufferActiveContextKey = TerminalContextKeys.altBufferActive.bindTo(scopedContextKeyService);
this._terminalShellIntegrationEnabledContextKey = TerminalContextKeys.terminalShellIntegrationEnabled.bindTo(scopedContextKeyService);
this._logService.trace(`terminalInstance#ctor (instanceId: ${this.instanceId})`, this._shellLaunchConfig);
this._register(this.capabilities.onDidAddCapabilityType(e => this._logService.debug('terminalInstance added capability', e)));
this._register(this.capabilities.onDidRemoveCapabilityType(e => this._logService.debug('terminalInstance removed capability', e)));
const capabilityListeners = this._register(new DisposableMap<TerminalCapability, IDisposable>());
this._register(this.capabilities.onDidAddCapabilityType(capability => {
capabilityListeners.get(capability)?.dispose();
if (capability === TerminalCapability.CwdDetection) {
const cwdDetection = this.capabilities.get(capability);
if (cwdDetection) {
capabilityListeners.set(capability, cwdDetection.onDidChangeCwd(e => {
this._cwd = e;
this._setTitle(this.title, TitleEventSource.Config);
}));
}
}
if (capability === TerminalCapability.CommandDetection) {
const commandDetection = this.capabilities.get(capability);
if (commandDetection) {
capabilityListeners.set(capability, Event.any(
commandDetection.promptInputModel.onDidStartInput,
commandDetection.promptInputModel.onDidChangeInput,
commandDetection.promptInputModel.onDidFinishInput
)(() => this._labelComputer?.refreshLabel(this)));
}
}
}));
this._register(this.capabilities.onDidRemoveCapabilityType(capability => {
capabilityListeners.get(capability)?.dispose();
}));
// 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._register(this._scopedInstantiationService.createInstance(TerminalStatusList));
this._initDimensions();
this._processManager = this._createProcessManager();
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
let os: OperatingSystem | undefined;
if (!this.shellLaunchConfig.customPtyImplementation && this._terminalConfigurationService.config.shellIntegration?.enabled && !this.shellLaunchConfig.executable) {
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;
if (this.shellLaunchConfig.isExtensionOwnedTerminal) {
// Only use default icon and color and env if they are undefined in the SLC
this.shellLaunchConfig.icon ??= defaultProfile.icon;
this.shellLaunchConfig.color ??= defaultProfile.color;
this.shellLaunchConfig.env ??= defaultProfile.env;
} else {
this.shellLaunchConfig.icon = defaultProfile.icon;
this.shellLaunchConfig.color = defaultProfile.color;
this.shellLaunchConfig.env = defaultProfile.env;
}
}
// Resolve the shell type ahead of time to allow features that depend upon it to work
// before the process is actually created (like terminal suggest manual request)
if (os && this.shellLaunchConfig.executable) {
this.setShellType(guessShellTypeFromExecutable(os, this.shellLaunchConfig.executable));
}
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(AccessibilityVerbositySettingId.Terminal)) {
this._setAriaLabel(this.xterm?.raw, this._instanceId, this.title);
}
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);
}
}));
this._register(this._workspaceContextService.onDidChangeWorkspaceFolders(() => this._labelComputer?.refreshLabel(this)));
// Clear out initial data events after 10 seconds, hopefully extension hosts are up and
// running at that point.
let initialDataEventsTimeout: number | undefined = dom.getWindow(this._container).setTimeout(() => {
initialDataEventsTimeout = undefined;
this._initialDataEvents = undefined;
this._initialDataEventsListener.clear();
}, 10000);
this._register(toDisposable(() => {
if (initialDataEventsTimeout) {
dom.getWindow(this._container).clearTimeout(initialDataEventsTimeout);
}
}));
// Initialize contributions
const contributionDescs = TerminalExtensionsRegistry.getTerminalContributions();
for (const desc of contributionDescs) {
if (this._contributions.has(desc.id)) {
onUnexpectedError(new Error(`Cannot have two terminal contributions with the same id ${desc.id}`));
continue;
}
let contribution: ITerminalContribution;
try {
contribution = this._register(this._scopedInstantiationService.createInstance(desc.ctor, {
instance: this,
processManager: this._processManager,
widgetManager: this._widgetManager
}));
this._contributions.set(desc.id, contribution);
} catch (err) {
onUnexpectedError(err);
}
this._xtermReadyPromise.then(xterm => {
if (xterm) {
contribution.xtermReady?.(xterm);
}
});
this._register(this.onDisposed(() => {
contribution.dispose();
this._contributions.delete(desc.id);
// Just in case to prevent potential future memory leaks due to cyclic dependency.
if ('instance' in contribution) {
delete contribution.instance;
}
if ('_instance' in contribution) {
delete contribution._instance;
}
}));
}
}
public getContribution<T extends ITerminalContribution>(id: string): T | null {
return this._contributions.get(id) as T | null;
}
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 = dom.getWindow(this._container).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._terminalConfigurationService.getFont(dom.getWindow(this.domElement));
const newRC = getXtermScaledDimensions(dom.getWindow(this.domElement), font, dimension.width, dimension.height);
if (!newRC) {
this._setLastKnownColsAndRows();
return null;
}
if (this._cols !== newRC.cols || this._rows !== newRC.rows) {
this._cols = newRC.cols;
this._rows = newRC.rows;
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._terminalConfigurationService.getFont(dom.getWindow(this.domElement));
if (!font || !font.charWidth || !font.charHeight) {
return undefined;
}
if (!this.xterm?.raw.element) {
return undefined;
}
const computedStyle = dom.getWindow(this.xterm.raw.element).getComputedStyle(this.xterm.raw.element);
const horizontalPadding = parseInt(computedStyle.paddingLeft) + parseInt(computedStyle.paddingRight) + 14/*scroll bar padding*/;
const verticalPadding = parseInt(computedStyle.paddingTop) + parseInt(computedStyle.paddingBottom);
TerminalInstance._lastKnownCanvasDimensions = new dom.Dimension(
Math.min(Constants.MaxCanvasWidth, width - horizontalPadding),
height - verticalPadding + (this._hasScrollBar && this._horizontalScrollbar ? -5/* scroll bar height */ : 0));
return TerminalInstance._lastKnownCanvasDimensions;
}
get persistentProcessId(): number | undefined { return this._processManager.persistentProcessId; }
get shouldPersist(): boolean { return this._processManager.shouldPersist && !this.shellLaunchConfig.isTransient && (!this.reconnectionProperties || this._configurationService.getValue('task.reconnection') === true); }
public static getXtermConstructor(keybindingService: IKeybindingService, contextKeyService: IContextKeyService) {
const keybinding = keybindingService.lookupKeybinding(TerminalContribCommandId.A11yFocusAccessibleBuffer, contextKeyService);
if (xtermConstructor) {
return xtermConstructor;
}
xtermConstructor = Promises.withAsyncBody<typeof XTermTerminal>(async (resolve) => {
const Terminal = (await importAMDNodeModule<typeof import('@xterm/xterm')>('@xterm/xterm', 'lib/xterm.js')).Terminal;
// Localize strings
Terminal.strings.promptLabel = nls.localize('terminal.integrated.a11yPromptLabel', 'Terminal input');
Terminal.strings.tooMuchOutput = keybinding ? nls.localize('terminal.integrated.useAccessibleBuffer', 'Use the accessible buffer {0} to manually review output', keybinding.getLabel()) : nls.localize('terminal.integrated.useAccessibleBufferNoKb', 'Use the Terminal: Focus Accessible Buffer command to manually review output');
resolve(Terminal);
});
return xtermConstructor;
}
/**
* Create xterm.js instance and attach data listeners.
*/
protected async _createXterm(): Promise<XtermTerminal | undefined> {
const Terminal = await TerminalInstance.getXtermConstructor(this._keybindingService, this._contextKeyService);
if (this.isDisposed) {
return undefined;
}
const disableShellIntegrationReporting = (this.shellLaunchConfig.executable === undefined || this.shellType === undefined) || !shellIntegrationSupportedShellTypes.includes(this.shellType);
const xterm = this._scopedInstantiationService.createInstance(XtermTerminal, Terminal, {
cols: this._cols,
rows: this._rows,
xtermColorProvider: this._scopedInstantiationService.createInstance(TerminalInstanceColorProvider, this._targetRef),
capabilities: this.capabilities,
shellIntegrationNonce: this._processManager.shellIntegrationNonce,
disableShellIntegrationReporting,
});
this.xterm = xterm;
this._resizeDebouncer = this._register(new TerminalResizeDebouncer(
() => this._isVisible,
() => xterm,
async (cols, rows) => {
xterm.raw.resize(cols, rows);
await this._updatePtyDimensions(xterm.raw);
},
async (cols) => {
xterm.raw.resize(cols, xterm.raw.rows);
await this._updatePtyDimensions(xterm.raw);
},
async (rows) => {
xterm.raw.resize(xterm.raw.cols, rows);
await this._updatePtyDimensions(xterm.raw);
}
));
this._register(toDisposable(() => this._resizeDebouncer = undefined));
this.updateAccessibilitySupport();
this._register(this.xterm.onDidRequestRunCommand(e => {
this.sendText(e.command.command, e.noNewLine ? false : true);
}));
this._register(this.xterm.onDidRequestRefreshDimensions(() => {
if (this._lastLayoutDimensions) {
this.layout(this._lastLayoutDimensions);
}
}));
// Write initial text, deferring onLineFeed listener when applicable to avoid firing
// onLineData events containing initialText
const initialTextWrittenPromise = this._shellLaunchConfig.initialText ? new Promise<void>(r => this._writeInitialText(xterm, r)) : undefined;
const lineDataEventAddon = this._register(new LineDataEventAddon(initialTextWrittenPromise));
this._register(lineDataEventAddon.onLineData(e => this._onLineData.fire(e)));
this._lineDataEventAddon = lineDataEventAddon;
// Delay the creation of the bell listener to avoid showing the bell when the terminal
// starts up or reconnects
disposableTimeout(() => {
this._register(xterm.raw.onBell(() => {
if (this._configurationService.getValue(TerminalSettingId.EnableBell) || this._configurationService.getValue(TerminalSettingId.EnableVisualBell)) {
this.statusList.add({
id: TerminalStatus.Bell,
severity: Severity.Warning,
icon: Codicon.bell,
tooltip: nls.localize('bellStatus', "Bell")
}, this._terminalConfigurationService.config.bellDuration);
}
this._accessibilitySignalService.playSignal(AccessibilitySignal.terminalBell);
}));
}, 1000, this._store);
this._register(xterm.raw.onSelectionChange(() => this._onDidChangeSelection.fire(this)));
this._register(xterm.raw.buffer.onBufferChange(() => this._refreshAltBufferContextKey()));
this._register(this._processManager.onProcessData(e => this._onProcessData(e)));
this._register(xterm.raw.onData(async data => {
await this._pauseInputEventBarrier?.wait();
await this._processManager.write(data);
this._onDidInputData.fire(data);
}));
this._register(xterm.raw.onBinary(data => this._processManager.processBinary(data)));
// Init winpty compat and link handler after process creation as they rely on the
// underlying process OS
this._register(this._processManager.onProcessReady(async (processTraits) => {
if (this._processManager.os) {
lineDataEventAddon.setOperatingSystem(this._processManager.os);
}
xterm.raw.options.windowsPty = processTraits.windowsPty;
}));
this._register(this._processManager.onRestoreCommands(e => this.xterm?.shellIntegration.deserialize(e)));
this._register(this._viewDescriptorService.onDidChangeLocation(({ views }) => {
if (views.some(v => v.id === TERMINAL_VIEW_ID)) {
xterm.refresh();
}
}));
this._register(xterm.onDidChangeProgress(() => this._labelComputer?.refreshLabel(this)));
// Set up updating of the process cwd on key press, this is only needed when the cwd
// detection capability has not been registered
if (!this.capabilities.has(TerminalCapability.CwdDetection)) {
let onKeyListener: IDisposable | undefined = xterm.raw.onKey(e => {
const event = new StandardKeyboardEvent(e.domEvent);
if (event.equals(KeyCode.Enter)) {
this._updateProcessCwd();
}
});
this._register(this.capabilities.onDidAddCapabilityType(e => {
if (e === TerminalCapability.CwdDetection) {
onKeyListener?.dispose();
onKeyListener = undefined;
}
}));
}
this._pathService.userHome().then(userHome => {
this._userHome = userHome.fsPath;
});
if (this._isVisible) {
this._open();
}
return xterm;
}
async runCommand(commandLine: string, shouldExecute: boolean): Promise<void> {
let commandDetection = this.capabilities.get(TerminalCapability.CommandDetection);
// Await command detection if the terminal is starting up
if (!commandDetection && (this._processManager.processState === ProcessState.Uninitialized || this._processManager.processState === ProcessState.Launching)) {
const store = new DisposableStore();
await Promise.race([
new Promise<void>(r => {
store.add(this.capabilities.onDidAddCapabilityType(e => {
if (e === TerminalCapability.CommandDetection) {
commandDetection = this.capabilities.get(TerminalCapability.CommandDetection);
r();
}
}));
}),
timeout(2000),
]);
store.dispose();
}
// Determine whether to send ETX (ctrl+c) before running the command. This should always
// happen unless command detection can reliably say that a command is being entered and
// there is no content in the prompt
if (!commandDetection || commandDetection.promptInputModel.value.length > 0) {
await this.sendText('\x03', false);
// Wait a little before running the command to avoid the sequences being echoed while the ^C
// is being evaluated
await timeout(100);
}
// Use bracketed paste mode only when not running the command
await this.sendText(commandLine, shouldExecute, !shouldExecute);
}
detachFromElement(): void {
this._wrapperElement.remove();
this._container = undefined;
}
attachToElement(container: HTMLElement): void {
// The container did not change, do nothing
if (this._container === container) {
return;
}
if (!this._attachBarrier.isOpen()) {
this._attachBarrier.open();
}
// The container changed, reattach
this._container = container;
this._container.appendChild(this._wrapperElement);
// If xterm is already attached, call open again to pick up any changes to the window.
if (this.xterm?.raw.element) {
this.xterm.raw.open(this.xterm.raw.element);
}
this.xterm?.refresh();
setTimeout(() => {
if (this._store.isDisposed) {
return;
}
this._initDragAndDrop(container);
}, 0);
}
/**
* 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);
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);
// Fire xtermOpen on all contributions
for (const contribution of this._contributions.values()) {
if (!this.xterm) {
this._xtermReadyPromise.then(xterm => {
if (xterm) {
contribution.xtermOpen?.(xterm);
}
});
} else {
contribution.xtermOpen?.(this.xterm);
}
}
this._register(xterm.shellIntegration.onDidChangeStatus(() => {
if (this.hasFocus) {
this._setShellIntegrationContextKey();
} else {
this._terminalShellIntegrationEnabledContextKey.reset();
}
}));
if (!xterm.raw.element || !xterm.raw.textarea) {