/
terminalService.ts
1025 lines (915 loc) · 43.4 KB
/
terminalService.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 { timeout } from 'vs/base/common/async';
import { debounce, throttle } from 'vs/base/common/decorators';
import { Emitter, Event } from 'vs/base/common/event';
import { IDisposable } from 'vs/base/common/lifecycle';
import { basename } from 'vs/base/common/path';
import { isMacintosh, isWeb, isWindows, OperatingSystem } from 'vs/base/common/platform';
import { FindReplaceState } from 'vs/editor/contrib/find/findState';
import * as nls from 'vs/nls';
import { ConfigurationTarget, 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 { IInstantiationService, optional } from 'vs/platform/instantiation/common/instantiation';
import { IPickOptions, IQuickInputButton, IQuickInputService, IQuickPickItem, IQuickPickSeparator } from 'vs/platform/quickinput/common/quickInput';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { ILocalTerminalService, IShellLaunchConfig, ITerminalLaunchError, ITerminalsLayoutInfo, ITerminalsLayoutInfoById, TerminalShellType, WindowsShellType } from 'vs/platform/terminal/common/terminal';
import { ThemeIcon } from 'vs/platform/theme/common/themeService';
import { IViewDescriptorService, IViewsService, ViewContainerLocation } from 'vs/workbench/common/views';
import { IRemoteTerminalService, ITerminalExternalLinkProvider, ITerminalInstance, ITerminalService, ITerminalTab, TerminalConnectionState } from 'vs/workbench/contrib/terminal/browser/terminal';
import { TerminalConfigHelper } from 'vs/workbench/contrib/terminal/browser/terminalConfigHelper';
import { TerminalInstance } from 'vs/workbench/contrib/terminal/browser/terminalInstance';
import { TerminalTab } from 'vs/workbench/contrib/terminal/browser/terminalTab';
import { TerminalViewPane } from 'vs/workbench/contrib/terminal/browser/terminalView';
import { IAvailableProfilesRequest, IRemoteTerminalAttachTarget, ITerminalProfile, IStartExtensionTerminalRequest, ITerminalConfigHelper, ITerminalNativeWindowsDelegate, ITerminalProcessExtHostProxy, KEYBINDING_CONTEXT_TERMINAL_ALT_BUFFER_ACTIVE, KEYBINDING_CONTEXT_TERMINAL_FIND_VISIBLE, KEYBINDING_CONTEXT_TERMINAL_FOCUS, KEYBINDING_CONTEXT_TERMINAL_IS_OPEN, KEYBINDING_CONTEXT_TERMINAL_PROCESS_SUPPORTED, KEYBINDING_CONTEXT_TERMINAL_SHELL_TYPE, LinuxDistro, TERMINAL_VIEW_ID, ITerminalProfileObject, ITerminalExecutable, ITerminalProfileSource } from 'vs/workbench/contrib/terminal/common/terminal';
import { escapeNonWindowsPath } from 'vs/workbench/contrib/terminal/common/terminalEnvironment';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService';
import { ILifecycleService, ShutdownReason, WillShutdownEvent } from 'vs/workbench/services/lifecycle/common/lifecycle';
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
import { configureTerminalProfileIcon } from 'vs/workbench/contrib/terminal/browser/terminalIcons';
import { equals } from 'vs/base/common/objects';
interface IExtHostReadyEntry {
promise: Promise<void>;
resolve: () => void;
}
export class TerminalService implements ITerminalService {
public _serviceBrand: undefined;
private _isShuttingDown: boolean;
private _terminalFocusContextKey: IContextKey<boolean>;
private _terminalShellTypeContextKey: IContextKey<string>;
private _terminalAltBufferActiveContextKey: IContextKey<boolean>;
private _findWidgetVisible: IContextKey<boolean>;
private _terminalTabs: ITerminalTab[] = [];
private _backgroundedTerminalInstances: ITerminalInstance[] = [];
private get _terminalInstances(): ITerminalInstance[] {
return this._terminalTabs.reduce((p, c) => p.concat(c.terminalInstances), <ITerminalInstance[]>[]);
}
private _findState: FindReplaceState;
private _extHostsReady: { [authority: string]: IExtHostReadyEntry | undefined } = {};
private _activeTabIndex: number;
private _linkProviders: Set<ITerminalExternalLinkProvider> = new Set();
private _linkProviderDisposables: Map<ITerminalExternalLinkProvider, IDisposable[]> = new Map();
private _processSupportContextKey: IContextKey<boolean>;
public get activeTabIndex(): number { return this._activeTabIndex; }
public get terminalInstances(): ITerminalInstance[] { return this._terminalInstances; }
public get terminalTabs(): ITerminalTab[] { return this._terminalTabs; }
public get isProcessSupportRegistered(): boolean { return !!this._processSupportContextKey.get(); }
private _configHelper: TerminalConfigHelper;
private _terminalContainer: HTMLElement | undefined;
private _nativeWindowsDelegate: ITerminalNativeWindowsDelegate | undefined;
private _remoteTerminalsInitPromise: Promise<void> | undefined;
private _localTerminalsInitPromise: Promise<void> | undefined;
private _connectionState: TerminalConnectionState;
private _availableProfiles: ITerminalProfile[] | undefined;
public get configHelper(): ITerminalConfigHelper { return this._configHelper; }
private readonly _onActiveTabChanged = new Emitter<void>();
public get onActiveTabChanged(): Event<void> { return this._onActiveTabChanged.event; }
private readonly _onInstanceCreated = new Emitter<ITerminalInstance>();
public get onInstanceCreated(): Event<ITerminalInstance> { return this._onInstanceCreated.event; }
private readonly _onInstanceDisposed = new Emitter<ITerminalInstance>();
public get onInstanceDisposed(): Event<ITerminalInstance> { return this._onInstanceDisposed.event; }
private readonly _onInstanceProcessIdReady = new Emitter<ITerminalInstance>();
public get onInstanceProcessIdReady(): Event<ITerminalInstance> { return this._onInstanceProcessIdReady.event; }
private readonly _onInstanceLinksReady = new Emitter<ITerminalInstance>();
public get onInstanceLinksReady(): Event<ITerminalInstance> { return this._onInstanceLinksReady.event; }
private readonly _onInstanceRequestStartExtensionTerminal = new Emitter<IStartExtensionTerminalRequest>();
public get onInstanceRequestStartExtensionTerminal(): Event<IStartExtensionTerminalRequest> { return this._onInstanceRequestStartExtensionTerminal.event; }
private readonly _onInstanceDimensionsChanged = new Emitter<ITerminalInstance>();
public get onInstanceDimensionsChanged(): Event<ITerminalInstance> { return this._onInstanceDimensionsChanged.event; }
private readonly _onInstanceMaximumDimensionsChanged = new Emitter<ITerminalInstance>();
public get onInstanceMaximumDimensionsChanged(): Event<ITerminalInstance> { return this._onInstanceMaximumDimensionsChanged.event; }
private readonly _onInstancesChanged = new Emitter<void>();
public get onInstancesChanged(): Event<void> { return this._onInstancesChanged.event; }
private readonly _onInstanceTitleChanged = new Emitter<ITerminalInstance | undefined>();
public get onInstanceTitleChanged(): Event<ITerminalInstance | undefined> { return this._onInstanceTitleChanged.event; }
private readonly _onActiveInstanceChanged = new Emitter<ITerminalInstance | undefined>();
public get onActiveInstanceChanged(): Event<ITerminalInstance | undefined> { return this._onActiveInstanceChanged.event; }
private readonly _onTabDisposed = new Emitter<ITerminalTab>();
public get onTabDisposed(): Event<ITerminalTab> { return this._onTabDisposed.event; }
private readonly _onRequestAvailableProfiles = new Emitter<IAvailableProfilesRequest>();
public get onRequestAvailableProfiles(): Event<IAvailableProfilesRequest> { return this._onRequestAvailableProfiles.event; }
private readonly _onDidRegisterProcessSupport = new Emitter<void>();
public get onDidRegisterProcessSupport(): Event<void> { return this._onDidRegisterProcessSupport.event; }
private readonly _onDidChangeConnectionState = new Emitter<void>();
public get onDidChangeConnectionState(): Event<void> { return this._onDidChangeConnectionState.event; }
public get connectionState(): TerminalConnectionState { return this._connectionState; }
private readonly _onProfilesConfigChanged = new Emitter<void>();
public get onProfilesConfigChanged(): Event<void> { return this._onProfilesConfigChanged.event; }
private readonly _localTerminalService?: ILocalTerminalService;
constructor(
@IContextKeyService private _contextKeyService: IContextKeyService,
@IWorkbenchLayoutService private _layoutService: IWorkbenchLayoutService,
@ILifecycleService lifecycleService: ILifecycleService,
@IDialogService private _dialogService: IDialogService,
@IInstantiationService private _instantiationService: IInstantiationService,
@IRemoteAgentService private _remoteAgentService: IRemoteAgentService,
@IQuickInputService private _quickInputService: IQuickInputService,
@IConfigurationService private _configurationService: IConfigurationService,
@IViewsService private _viewsService: IViewsService,
@IViewDescriptorService private readonly _viewDescriptorService: IViewDescriptorService,
@IWorkbenchEnvironmentService private readonly _environmentService: IWorkbenchEnvironmentService,
@IRemoteTerminalService private readonly _remoteTerminalService: IRemoteTerminalService,
@ITelemetryService private readonly _telemetryService: ITelemetryService,
@IExtensionService private readonly _extensionService: IExtensionService,
@optional(ILocalTerminalService) localTerminalService: ILocalTerminalService
) {
this._localTerminalService = localTerminalService;
this._activeTabIndex = 0;
this._isShuttingDown = false;
this._findState = new FindReplaceState();
lifecycleService.onBeforeShutdown(async e => e.veto(this._onBeforeShutdown(e.reason), 'veto.terminal'));
lifecycleService.onWillShutdown(e => this._onWillShutdown(e));
this._terminalFocusContextKey = KEYBINDING_CONTEXT_TERMINAL_FOCUS.bindTo(this._contextKeyService);
this._terminalShellTypeContextKey = KEYBINDING_CONTEXT_TERMINAL_SHELL_TYPE.bindTo(this._contextKeyService);
this._terminalAltBufferActiveContextKey = KEYBINDING_CONTEXT_TERMINAL_ALT_BUFFER_ACTIVE.bindTo(this._contextKeyService);
this._findWidgetVisible = KEYBINDING_CONTEXT_TERMINAL_FIND_VISIBLE.bindTo(this._contextKeyService);
this._configHelper = this._instantiationService.createInstance(TerminalConfigHelper);
this.onTabDisposed(tab => this._removeTab(tab));
this.onActiveTabChanged(() => {
const instance = this.getActiveInstance();
this._onActiveInstanceChanged.fire(instance ? instance : undefined);
});
this.onInstanceLinksReady(instance => this._setInstanceLinkProviders(instance));
this._handleInstanceContextKeys();
this._processSupportContextKey = KEYBINDING_CONTEXT_TERMINAL_PROCESS_SUPPORTED.bindTo(this._contextKeyService);
this._processSupportContextKey.set(!isWeb || this._remoteAgentService.getConnection() !== null);
this._configurationService.onDidChangeConfiguration(async e => {
if (e.affectsConfiguration('terminal.integrated.profiles.windows') ||
e.affectsConfiguration('terminal.integrated.profiles.osx') ||
e.affectsConfiguration('terminal.integrated.profiles.linux') ||
e.affectsConfiguration('terminal.integrated.useWslProfiles')) {
this._updateAvailableProfilesNow();
}
});
const enableTerminalReconnection = this.configHelper.config.enablePersistentSessions;
const conn = this._remoteAgentService.getConnection();
const remoteAuthority = conn ? conn.remoteAuthority : 'null';
this._whenExtHostReady(remoteAuthority).then(() => {
this._updateAvailableProfiles();
});
// Connect to the extension host if it's there, set the connection state to connected when
// it's done. This should happen even when there is no extension host.
this._connectionState = TerminalConnectionState.Connecting;
let initPromise: Promise<any>;
if (!!this._environmentService.remoteAuthority && enableTerminalReconnection) {
initPromise = this._remoteTerminalsInitPromise = this._reconnectToRemoteTerminals();
} else if (enableTerminalReconnection) {
initPromise = this._localTerminalsInitPromise = this._reconnectToLocalTerminals();
} else {
initPromise = Promise.resolve();
}
initPromise.then(() => this._setConnected());
}
private _setConnected() {
this._connectionState = TerminalConnectionState.Connected;
this._onDidChangeConnectionState.fire();
}
private async _reconnectToRemoteTerminals(): Promise<void> {
// Reattach to all remote terminals
const layoutInfo = await this._remoteTerminalService.getTerminalLayoutInfo();
this._remoteTerminalService.reduceConnectionGraceTime();
const reconnectCounter = this._recreateTerminalTabs(layoutInfo);
/* __GDPR__
"terminalReconnection" : {
"count" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
}
*/
const data = {
count: reconnectCounter
};
this._telemetryService.publicLog('terminalReconnection', data);
// now that terminals have been restored,
// attach listeners to update remote when terminals are changed
this.attachProcessLayoutListeners(true);
}
private async _reconnectToLocalTerminals(): Promise<void> {
if (!this._localTerminalService) {
return;
}
// Reattach to all local terminals
const layoutInfo = await this._localTerminalService.getTerminalLayoutInfo();
if (layoutInfo && layoutInfo.tabs.length > 0) {
this._recreateTerminalTabs(layoutInfo);
}
// now that terminals have been restored,
// attach listeners to update local state when terminals are changed
this.attachProcessLayoutListeners(false);
}
private _recreateTerminalTabs(layoutInfo?: ITerminalsLayoutInfo): number {
let reconnectCounter = 0;
let activeTab: ITerminalTab | undefined;
if (layoutInfo) {
layoutInfo.tabs.forEach(tabLayout => {
const terminalLayouts = tabLayout.terminals.filter(t => t.terminal && t.terminal.isOrphan);
if (terminalLayouts.length) {
reconnectCounter += terminalLayouts.length;
let terminalInstance: ITerminalInstance | undefined;
let tab: ITerminalTab | undefined;
terminalLayouts.forEach((terminalLayout) => {
if (!terminalInstance) {
// create tab and terminal
terminalInstance = this.createTerminal({ attachPersistentProcess: terminalLayout.terminal! });
tab = this._getTabForInstance(terminalInstance);
if (tabLayout.isActive) {
activeTab = tab;
}
} else {
// add split terminals to this tab
this.splitInstance(terminalInstance, { attachPersistentProcess: terminalLayout.terminal! });
}
});
const activeInstance = this.terminalInstances.find(t => {
return t.shellLaunchConfig.attachPersistentProcess?.id === tabLayout.activePersistentProcessId;
});
if (activeInstance) {
this.setActiveInstance(activeInstance);
}
tab?.resizePanes(tabLayout.terminals.map(terminal => terminal.relativeSize));
}
});
if (layoutInfo.tabs.length) {
this.setActiveTabByIndex(activeTab ? this.terminalTabs.indexOf(activeTab) : 0);
}
}
return reconnectCounter;
}
private attachProcessLayoutListeners(isRemote: boolean): void {
this.onActiveTabChanged(() => isRemote ? this._updateRemoteState() : this._updateLocalState());
this.onActiveInstanceChanged(() => isRemote ? this._updateRemoteState() : this._updateLocalState());
this.onInstancesChanged(() => isRemote ? this._updateRemoteState() : this._updateLocalState());
// The state must be updated when the terminal is relaunched, otherwise the persistent
// terminal ID will be stale and the process will be leaked.
this.onInstanceProcessIdReady(() => isRemote ? this._updateRemoteState() : this._updateLocalState());
}
public setNativeWindowsDelegate(delegate: ITerminalNativeWindowsDelegate): void {
this._nativeWindowsDelegate = delegate;
}
public setLinuxDistro(linuxDistro: LinuxDistro): void {
this._configHelper.setLinuxDistro(linuxDistro);
}
private _handleInstanceContextKeys(): void {
const terminalIsOpenContext = KEYBINDING_CONTEXT_TERMINAL_IS_OPEN.bindTo(this._contextKeyService);
const updateTerminalContextKeys = () => {
terminalIsOpenContext.set(this.terminalInstances.length > 0);
};
this.onInstancesChanged(() => updateTerminalContextKeys());
}
public getActiveOrCreateInstance(): ITerminalInstance {
const activeInstance = this.getActiveInstance();
return activeInstance ? activeInstance : this.createTerminal(undefined);
}
public requestStartExtensionTerminal(proxy: ITerminalProcessExtHostProxy, cols: number, rows: number): Promise<ITerminalLaunchError | undefined> {
// The initial request came from the extension host, no need to wait for it
return new Promise<ITerminalLaunchError | undefined>(callback => {
this._onInstanceRequestStartExtensionTerminal.fire({ proxy, cols, rows, callback });
});
}
public async extHostReady(remoteAuthority: string): Promise<void> {
this._createExtHostReadyEntry(remoteAuthority);
this._extHostsReady[remoteAuthority]!.resolve();
}
public getAvailableProfiles(): ITerminalProfile[] {
this._updateAvailableProfiles();
return this._availableProfiles || [];
}
private async _getWorkspaceProfilePermissions(profile: ITerminalProfile): Promise<boolean> {
const platformKey = await this._getPlatformKey();
const profiles = this._configurationService.inspect<{ [key: string]: ITerminalProfileObject }>(`terminal.integrated.profiles.${platformKey}`);
if (!profiles || !profiles.workspaceValue || !profiles.defaultValue) {
return false;
}
const workspaceProfile = Object.entries(profiles.workspaceValue).find(p => p[0] === profile.profileName);
const defaultProfile = Object.entries(profiles.defaultValue).find(p => p[0] === profile.profileName);
if (workspaceProfile && defaultProfile && workspaceProfile[0] === defaultProfile[0]) {
let result = !this._terminalProfileObjectEqual(workspaceProfile[1], defaultProfile[1]);
return result;
} else if (!workspaceProfile && !defaultProfile) {
// user profile
return false;
} else {
// this key is missing from either default or the workspace config
return true;
}
}
private _terminalProfileObjectEqual(one?: ITerminalProfileObject, two?: ITerminalProfileObject): boolean {
if (one === null && two === null) {
return true;
} else if ((one as ITerminalExecutable).path && (two as ITerminalExecutable).path) {
const oneExec = (one as ITerminalExecutable);
const twoExec = (two as ITerminalExecutable);
return ((Array.isArray(oneExec.path) && Array.isArray(twoExec.path) && oneExec.path.length === twoExec.path.length && oneExec.path.every((p, index) => p === twoExec.path[index])) ||
(oneExec.path === twoExec.path)
) && ((Array.isArray(oneExec.args) && Array.isArray(twoExec.args) && oneExec.args?.every((a, index) => a === twoExec.args?.[index])) ||
(oneExec.args === twoExec.args)
);
} else if ((one as ITerminalProfileSource).source && (two as ITerminalProfileSource).source) {
const oneSource = (one as ITerminalProfileSource);
const twoSource = (two as ITerminalProfileSource);
return oneSource.source === twoSource.source
&& ((Array.isArray(oneSource.args) && Array.isArray(twoSource.args) && oneSource.args?.every((a, index) => a === twoSource.args?.[index])) ||
(oneSource.args === twoSource.args)
);
}
return false;
}
// when relevant config changes, update without debouncing
private async _updateAvailableProfilesNow(): Promise<void> {
const result = await this._detectProfiles(true);
for (const p of result) {
p.isWorkspaceProfile = await this._getWorkspaceProfilePermissions(p);
}
if (!equals(result, this._availableProfiles)) {
this._availableProfiles = result;
this._onProfilesConfigChanged.fire();
}
}
// avoid checking this very often, every ten seconds shoulds suffice
@throttle(10000)
private _updateAvailableProfiles(): Promise<void> {
return this._updateAvailableProfilesNow();
}
private async _detectProfiles(configuredProfilesOnly: boolean): Promise<ITerminalProfile[]> {
await this._extensionService.whenInstalledExtensionsRegistered();
// Wait for the remoteAuthority to be ready (and listening for events) before firing
// the event to spawn the ext host process
const conn = this._remoteAgentService.getConnection();
const remoteAuthority = conn ? conn.remoteAuthority : 'null';
await this._whenExtHostReady(remoteAuthority);
return new Promise(r => this._onRequestAvailableProfiles.fire({ callback: r, configuredProfilesOnly: configuredProfilesOnly }));
}
private async _whenExtHostReady(remoteAuthority: string): Promise<void> {
this._createExtHostReadyEntry(remoteAuthority);
return this._extHostsReady[remoteAuthority]!.promise;
}
private _createExtHostReadyEntry(remoteAuthority: string): void {
if (this._extHostsReady[remoteAuthority]) {
return;
}
let resolve!: () => void;
const promise = new Promise<void>(r => resolve = r);
this._extHostsReady[remoteAuthority] = { promise, resolve };
}
private _onBeforeShutdown(reason: ShutdownReason): boolean | Promise<boolean> {
if (this.terminalInstances.length === 0) {
// No terminal instances, don't veto
return false;
}
const shouldPersistTerminals = this._configHelper.config.enablePersistentSessions && reason === ShutdownReason.RELOAD;
if (this.configHelper.config.confirmOnExit && !shouldPersistTerminals) {
return this._onBeforeShutdownAsync();
}
this._isShuttingDown = true;
return false;
}
private async _onBeforeShutdownAsync(): Promise<boolean> {
// veto if configured to show confirmation and the user chose not to exit
const veto = await this._showTerminalCloseConfirmation();
if (!veto) {
this._isShuttingDown = true;
}
return veto;
}
private _onWillShutdown(e: WillShutdownEvent): void {
// Don't touch processes if the shutdown was a result of reload as they will be reattached
const shouldPersistTerminals = this._configHelper.config.enablePersistentSessions && e.reason === ShutdownReason.RELOAD;
if (shouldPersistTerminals) {
this.terminalInstances.forEach(instance => instance.detachFromProcess());
return;
}
// Force dispose of all terminal instances, don't force immediate disposal of the terminal
// processes on Windows as an additional mitigation for https://github.com/microsoft/vscode/issues/71966
// which causes the pty host to become unresponsive, disconnecting all terminals across all
// windows
this.terminalInstances.forEach(instance => instance.dispose(!isWindows));
this._localTerminalService!.setTerminalLayoutInfo(undefined);
}
public getTabLabels(): string[] {
return this._terminalTabs.filter(tab => tab.terminalInstances.length > 0).map((tab, index) => {
return `${index + 1}: ${tab.title ? tab.title : ''}`;
});
}
public getFindState(): FindReplaceState {
return this._findState;
}
@debounce(500)
private _updateRemoteState(): void {
if (!!this._environmentService.remoteAuthority) {
const state: ITerminalsLayoutInfoById = {
tabs: this.terminalTabs.map(t => t.getLayoutInfo(t === this.getActiveTab()))
};
this._remoteTerminalService.setTerminalLayoutInfo(state);
}
}
@debounce(500)
private _updateLocalState(): void {
const state: ITerminalsLayoutInfoById = {
tabs: this.terminalTabs.map(t => t.getLayoutInfo(t === this.getActiveTab()))
};
this._localTerminalService!.setTerminalLayoutInfo(state);
}
private _removeTab(tab: ITerminalTab): void {
// Get the index of the tab and remove it from the list
const index = this._terminalTabs.indexOf(tab);
const activeTab = this.getActiveTab();
const activeTabIndex = activeTab ? this._terminalTabs.indexOf(activeTab) : -1;
const wasActiveTab = tab === activeTab;
if (index !== -1) {
this._terminalTabs.splice(index, 1);
}
// Adjust focus if the tab was active
if (wasActiveTab && this._terminalTabs.length > 0) {
// TODO: Only focus the new tab if the removed tab had focus?
// const hasFocusOnExit = tab.activeInstance.hadFocusOnExit;
const newIndex = index < this._terminalTabs.length ? index : this._terminalTabs.length - 1;
this.setActiveTabByIndex(newIndex);
const activeInstance = this.getActiveInstance();
if (activeInstance) {
activeInstance.focus(true);
}
} else if (activeTabIndex >= this._terminalTabs.length) {
const newIndex = this._terminalTabs.length - 1;
this.setActiveTabByIndex(newIndex);
}
// Hide the panel if there are no more instances, provided that VS Code is not shutting
// down. When shutting down the panel is locked in place so that it is restored upon next
// launch.
if (this._terminalTabs.length === 0 && !this._isShuttingDown) {
this.hidePanel();
this._onActiveInstanceChanged.fire(undefined);
}
// Fire events
this._onInstancesChanged.fire();
if (wasActiveTab) {
this._onActiveTabChanged.fire();
}
}
public refreshActiveTab(): void {
// Fire active instances changed
this._onActiveTabChanged.fire();
}
public getActiveTab(): ITerminalTab | null {
if (this._activeTabIndex < 0 || this._activeTabIndex >= this._terminalTabs.length) {
return null;
}
return this._terminalTabs[this._activeTabIndex];
}
public getActiveInstance(): ITerminalInstance | null {
const tab = this.getActiveTab();
if (!tab) {
return null;
}
return tab.activeInstance;
}
public doWithActiveInstance<T>(callback: (terminal: ITerminalInstance) => T): T | void {
const instance = this.getActiveInstance();
if (instance) {
return callback(instance);
}
}
public getInstanceFromId(terminalId: number): ITerminalInstance | undefined {
let bgIndex = -1;
this._backgroundedTerminalInstances.forEach((terminalInstance, i) => {
if (terminalInstance.instanceId === terminalId) {
bgIndex = i;
}
});
if (bgIndex !== -1) {
return this._backgroundedTerminalInstances[bgIndex];
}
try {
return this.terminalInstances[this._getIndexFromId(terminalId)];
} catch {
return undefined;
}
}
public getInstanceFromIndex(terminalIndex: number): ITerminalInstance {
return this.terminalInstances[terminalIndex];
}
public setActiveInstance(terminalInstance: ITerminalInstance): void {
// If this was a hideFromUser terminal created by the API this was triggered by show,
// in which case we need to create the terminal tab
if (terminalInstance.shellLaunchConfig.hideFromUser) {
this._showBackgroundTerminal(terminalInstance);
}
this.setActiveInstanceByIndex(this._getIndexFromId(terminalInstance.instanceId));
}
public setActiveTabByIndex(tabIndex: number): void {
if (tabIndex >= this._terminalTabs.length) {
return;
}
const didTabChange = this._activeTabIndex !== tabIndex;
this._activeTabIndex = tabIndex;
this._terminalTabs.forEach((t, i) => t.setVisible(i === this._activeTabIndex));
if (didTabChange) {
this._onActiveTabChanged.fire();
}
}
public isAttachedToTerminal(remoteTerm: IRemoteTerminalAttachTarget): boolean {
return this.terminalInstances.some(term => term.processId === remoteTerm.pid);
}
public async initializeTerminals(): Promise<void> {
if (this._remoteTerminalsInitPromise) {
await this._remoteTerminalsInitPromise;
} else if (this._localTerminalsInitPromise) {
await this._localTerminalsInitPromise;
}
if (this.terminalTabs.length === 0 && this.isProcessSupportRegistered) {
this.createTerminal();
}
}
private _getInstanceFromGlobalInstanceIndex(index: number): { tab: ITerminalTab, tabIndex: number, instance: ITerminalInstance, localInstanceIndex: number } | null {
let currentTabIndex = 0;
while (index >= 0 && currentTabIndex < this._terminalTabs.length) {
const tab = this._terminalTabs[currentTabIndex];
const count = tab.terminalInstances.length;
if (index < count) {
return {
tab,
tabIndex: currentTabIndex,
instance: tab.terminalInstances[index],
localInstanceIndex: index
};
}
index -= count;
currentTabIndex++;
}
return null;
}
public setActiveInstanceByIndex(terminalIndex: number): void {
const query = this._getInstanceFromGlobalInstanceIndex(terminalIndex);
if (!query) {
return;
}
query.tab.setActiveInstanceByIndex(query.localInstanceIndex);
const didTabChange = this._activeTabIndex !== query.tabIndex;
this._activeTabIndex = query.tabIndex;
this._terminalTabs.forEach((t, i) => t.setVisible(i === query.tabIndex));
// Only fire the event if there was a change
if (didTabChange) {
this._onActiveTabChanged.fire();
}
}
public setActiveTabToNext(): void {
if (this._terminalTabs.length <= 1) {
return;
}
let newIndex = this._activeTabIndex + 1;
if (newIndex >= this._terminalTabs.length) {
newIndex = 0;
}
this.setActiveTabByIndex(newIndex);
}
public setActiveTabToPrevious(): void {
if (this._terminalTabs.length <= 1) {
return;
}
let newIndex = this._activeTabIndex - 1;
if (newIndex < 0) {
newIndex = this._terminalTabs.length - 1;
}
this.setActiveTabByIndex(newIndex);
}
public splitInstance(instanceToSplit: ITerminalInstance, shellLaunchConfig: IShellLaunchConfig = {}): ITerminalInstance | null {
const tab = this._getTabForInstance(instanceToSplit);
if (!tab) {
return null;
}
const instance = tab.split(shellLaunchConfig);
this._initInstanceListeners(instance);
this._onInstancesChanged.fire();
this._terminalTabs.forEach((t, i) => t.setVisible(i === this._activeTabIndex));
return instance;
}
protected _initInstanceListeners(instance: ITerminalInstance): void {
instance.addDisposable(instance.onDisposed(this._onInstanceDisposed.fire, this._onInstanceDisposed));
instance.addDisposable(instance.onTitleChanged(this._onInstanceTitleChanged.fire, this._onInstanceTitleChanged));
instance.addDisposable(instance.onProcessIdReady(this._onInstanceProcessIdReady.fire, this._onInstanceProcessIdReady));
instance.addDisposable(instance.onLinksReady(this._onInstanceLinksReady.fire, this._onInstanceLinksReady));
instance.addDisposable(instance.onDimensionsChanged(() => {
this._onInstanceDimensionsChanged.fire(instance);
if (this.configHelper.config.enablePersistentSessions && this.isProcessSupportRegistered) {
!!this._environmentService.remoteAuthority ? this._updateRemoteState() : this._updateLocalState();
}
}));
instance.addDisposable(instance.onMaximumDimensionsChanged(() => this._onInstanceMaximumDimensionsChanged.fire(instance)));
instance.addDisposable(instance.onFocus(this._onActiveInstanceChanged.fire, this._onActiveInstanceChanged));
}
public registerProcessSupport(isSupported: boolean): void {
if (!isSupported) {
return;
}
this._processSupportContextKey.set(isSupported);
this._onDidRegisterProcessSupport.fire();
}
public registerLinkProvider(linkProvider: ITerminalExternalLinkProvider): IDisposable {
const disposables: IDisposable[] = [];
this._linkProviders.add(linkProvider);
for (const instance of this.terminalInstances) {
if (instance.areLinksReady) {
disposables.push(instance.registerLinkProvider(linkProvider));
}
}
this._linkProviderDisposables.set(linkProvider, disposables);
return {
dispose: () => {
const disposables = this._linkProviderDisposables.get(linkProvider) || [];
for (const disposable of disposables) {
disposable.dispose();
}
this._linkProviders.delete(linkProvider);
}
};
}
private _setInstanceLinkProviders(instance: ITerminalInstance): void {
for (const linkProvider of this._linkProviders) {
const disposables = this._linkProviderDisposables.get(linkProvider);
const provider = instance.registerLinkProvider(linkProvider);
disposables?.push(provider);
}
}
private _getTabForInstance(instance: ITerminalInstance): ITerminalTab | undefined {
return this._terminalTabs.find(tab => tab.terminalInstances.indexOf(instance) !== -1);
}
public async showPanel(focus?: boolean): Promise<void> {
const pane = this._viewsService.getActiveViewWithId(TERMINAL_VIEW_ID) as TerminalViewPane;
if (!pane) {
await this._viewsService.openView(TERMINAL_VIEW_ID, focus);
}
if (focus) {
// Do the focus call asynchronously as going through the
// command palette will force editor focus
await timeout(0);
const instance = this.getActiveInstance();
if (instance) {
await instance.focusWhenReady(true);
}
}
}
private _getIndexFromId(terminalId: number): number {
let terminalIndex = -1;
this.terminalInstances.forEach((terminalInstance, i) => {
if (terminalInstance.instanceId === terminalId) {
terminalIndex = i;
}
});
if (terminalIndex === -1) {
throw new Error(`Terminal with ID ${terminalId} does not exist (has it already been disposed?)`);
}
return terminalIndex;
}
public async manageWorkspaceShellPermissions(): Promise<void> {
const allowItem: IQuickPickItem = { label: nls.localize('workbench.action.terminal.allowWorkspaceShell', "Allow Workspace Shell Configuration") };
const disallowItem: IQuickPickItem = { label: nls.localize('workbench.action.terminal.disallowWorkspaceShell', "Disallow Workspace Shell Configuration") };
const value = await this._quickInputService.pick([allowItem, disallowItem], { canPickMany: false });
if (!value) {
return;
}
this.configHelper.setWorkspaceShellAllowed(value === allowItem);
}
protected async _showTerminalCloseConfirmation(): Promise<boolean> {
let message: string;
if (this.terminalInstances.length === 1) {
message = nls.localize('terminalService.terminalCloseConfirmationSingular', "There is an active terminal session, do you want to kill it?");
} else {
message = nls.localize('terminalService.terminalCloseConfirmationPlural', "There are {0} active terminal sessions, do you want to kill them?", this.terminalInstances.length);
}
const res = await this._dialogService.confirm({
message,
type: 'warning',
});
return !res.confirmed;
}
public preparePathForTerminalAsync(originalPath: string, executable: string, title: string, shellType: TerminalShellType): Promise<string> {
return new Promise<string>(c => {
if (!executable) {
c(originalPath);
return;
}
const hasSpace = originalPath.indexOf(' ') !== -1;
const hasParens = originalPath.indexOf('(') !== -1 || originalPath.indexOf(')') !== -1;
const pathBasename = basename(executable, '.exe');
const isPowerShell = pathBasename === 'pwsh' ||
title === 'pwsh' ||
pathBasename === 'powershell' ||
title === 'powershell';
if (isPowerShell && (hasSpace || originalPath.indexOf('\'') !== -1)) {
c(`& '${originalPath.replace(/'/g, '\'\'')}'`);
return;
}
if (hasParens && isPowerShell) {
c(`& '${originalPath}'`);
return;
}
if (isWindows) {
// 17063 is the build number where wsl path was introduced.
// Update Windows uriPath to be executed in WSL.
if (shellType !== undefined) {
if (shellType === WindowsShellType.GitBash) {
c(originalPath.replace(/\\/g, '/'));
return;
}
else if (shellType === WindowsShellType.Wsl) {
if (this._nativeWindowsDelegate && this._nativeWindowsDelegate.getWindowsBuildNumber() >= 17063) {
c(this._nativeWindowsDelegate.getWslPath(originalPath));
} else {
c(originalPath.replace(/\\/g, '/'));
}
return;
}
if (hasSpace) {
c('"' + originalPath + '"');
} else {
c(originalPath);
}
} else {
const lowerExecutable = executable.toLowerCase();
if (this._nativeWindowsDelegate && this._nativeWindowsDelegate.getWindowsBuildNumber() >= 17063 &&
(lowerExecutable.indexOf('wsl') !== -1 || (lowerExecutable.indexOf('bash.exe') !== -1 && lowerExecutable.toLowerCase().indexOf('git') === -1))) {
c(this._nativeWindowsDelegate.getWslPath(originalPath));
return;
} else if (hasSpace) {
c('"' + originalPath + '"');
} else {
c(originalPath);
}
}
return;
}
c(escapeNonWindowsPath(originalPath));
});
}
private async _getPlatformKey(): Promise<string> {
const env = await this._remoteAgentService.getEnvironment();
if (env) {
return env.os === OperatingSystem.Windows ? 'windows' : (env.os === OperatingSystem.Macintosh ? 'osx' : 'linux');
}
return isWindows ? 'windows' : (isMacintosh ? 'osx' : 'linux');
}
public async selectDefaultProfile(): Promise<void> {
const profiles = await this._detectProfiles(false);
const platformKey = await this._getPlatformKey();
const options: IPickOptions<IProfileQuickPickItem> = {
placeHolder: nls.localize('terminal.integrated.chooseWindowsShell', "Select your default terminal profile"),
onDidTriggerItemButton: async (context) => {
const configKey = `terminal.integrated.profiles.${platformKey}`;
const configProfiles = this._configurationService.inspect<{ [key: string]: ITerminalProfileObject }>(configKey);
const existingProfiles = configProfiles.userValue ? Object.keys(configProfiles.userValue) : [];
const name = await this._quickInputService.input({
prompt: nls.localize('enterTerminalProfileName', "Enter terminal profile name"),
value: context.item.profile.profileName,
validateInput: async input => {
if (existingProfiles.includes(input)) {
return nls.localize('terminalProfileAlreadyExists', "A terminal profile already exists with that name");
}
return undefined;
}
});
if (!name) {
return;
}
const newConfigValue: { [key: string]: ITerminalProfileObject } = { ...configProfiles.userValue } ?? {};
newConfigValue[name] = {
path: context.item.profile.path,
args: context.item.profile.args
};
await this._configurationService.updateValue(configKey, newConfigValue, ConfigurationTarget.USER);
}
};
// Build quick pick items
const quickPickItems: (IProfileQuickPickItem | IQuickPickSeparator)[] = [];
const configProfiles = profiles.filter(e => !e.isAutoDetected);
const autoDetectedProfiles = profiles.filter(e => e.isAutoDetected);
if (configProfiles.length > 0) {
quickPickItems.push({ type: 'separator', label: nls.localize('terminalProfiles', "profiles") });
quickPickItems.push(...configProfiles.map(e => this._createProfileQuickPickItem(e)));
}
if (configProfiles.length > 0) {
quickPickItems.push({ type: 'separator', label: nls.localize('terminalProfiles.detected', "detected") });
quickPickItems.push(...autoDetectedProfiles.map(e => this._createProfileQuickPickItem(e)));
}
const value = await this._quickInputService.pick(quickPickItems, options);
if (!value) {
return;
}
await this._configurationService.updateValue(`terminal.integrated.shell.${platformKey}`, value.profile.path, ConfigurationTarget.USER);
await this._configurationService.updateValue(`terminal.integrated.shellArgs.${platformKey}`, value.profile.args, ConfigurationTarget.USER);
}
private _createProfileQuickPickItem(profile: ITerminalProfile): IProfileQuickPickItem {
const buttons: IQuickInputButton[] = [{
iconClass: ThemeIcon.asClassName(configureTerminalProfileIcon),
tooltip: nls.localize('createQuickLaunchProfile', "Configure Terminal Profile")
}];
if (profile.args) {
if (typeof profile.args === 'string') {
return { label: profile.profileName, description: `${profile.path} ${profile.args}`, profile, buttons };
}
const argsString = profile.args.map(e => {
if (e.includes(' ')) {
return `"${e.replace('/"/g', '\\"')}"`;
}
return e;
}).join(' ');
return { label: profile.profileName, description: `${profile.path} ${argsString}`, profile, buttons };
}
return { label: profile.profileName, description: profile.path, profile, buttons };
}
public createInstance(container: HTMLElement | undefined, shellLaunchConfig: IShellLaunchConfig): ITerminalInstance {
const instance = this._instantiationService.createInstance(TerminalInstance,
this._terminalFocusContextKey,
this._terminalShellTypeContextKey,
this._terminalAltBufferActiveContextKey,
this._configHelper,
container,
shellLaunchConfig
);
this._onInstanceCreated.fire(instance);
return instance;
}
public createTerminal(shell: IShellLaunchConfig = {}): ITerminalInstance {
if (!shell.isExtensionCustomPtyTerminal && !this.isProcessSupportRegistered) {
throw new Error('Could not create terminal when process support is not registered');
}
if (shell.hideFromUser) {
const instance = this.createInstance(undefined, shell);
this._backgroundedTerminalInstances.push(instance);
this._initInstanceListeners(instance);
return instance;
}
const terminalTab = this._instantiationService.createInstance(TerminalTab, this._terminalContainer, shell);
this._terminalTabs.push(terminalTab);
const instance = terminalTab.terminalInstances[0];
terminalTab.addDisposable(terminalTab.onDisposed(this._onTabDisposed.fire, this._onTabDisposed));
terminalTab.addDisposable(terminalTab.onInstancesChanged(this._onInstancesChanged.fire, this._onInstancesChanged));
this._initInstanceListeners(instance);
if (this.terminalInstances.length === 1) {
// It's the first instance so it should be made active automatically
this.setActiveInstanceByIndex(0);
}
this._onInstancesChanged.fire();
return instance;
}
protected _showBackgroundTerminal(instance: ITerminalInstance): void {
this._backgroundedTerminalInstances.splice(this._backgroundedTerminalInstances.indexOf(instance), 1);
instance.shellLaunchConfig.hideFromUser = false;
const terminalTab = this._instantiationService.createInstance(TerminalTab, this._terminalContainer, instance);
this._terminalTabs.push(terminalTab);
terminalTab.addDisposable(terminalTab.onDisposed(this._onTabDisposed.fire, this._onTabDisposed));
terminalTab.addDisposable(terminalTab.onInstancesChanged(this._onInstancesChanged.fire, this._onInstancesChanged));
if (this.terminalInstances.length === 1) {
// It's the first instance so it should be made active automatically
this.setActiveInstanceByIndex(0);
}
this._onInstancesChanged.fire();
}
public async focusFindWidget(): Promise<void> {
await this.showPanel(false);
const pane = this._viewsService.getActiveViewWithId(TERMINAL_VIEW_ID) as TerminalViewPane;
pane.focusFindWidget();
this._findWidgetVisible.set(true);
}
public hideFindWidget(): void {
const pane = this._viewsService.getActiveViewWithId(TERMINAL_VIEW_ID) as TerminalViewPane;
if (pane) {
pane.hideFindWidget();
this._findWidgetVisible.reset();
pane.focus();
}
}
public findNext(): void {
const pane = this._viewsService.getActiveViewWithId(TERMINAL_VIEW_ID) as TerminalViewPane;
if (pane) {
pane.showFindWidget();
pane.getFindWidget().find(false);
}
}
public findPrevious(): void {
const pane = this._viewsService.getActiveViewWithId(TERMINAL_VIEW_ID) as TerminalViewPane;
if (pane) {
pane.showFindWidget();