forked from DonJayamanne/pythonVSCode
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathexternalTerminalService.ts
More file actions
252 lines (228 loc) · 10.1 KB
/
externalTerminalService.ts
File metadata and controls
252 lines (228 loc) · 10.1 KB
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import { inject, injectable } from 'inversify';
import { CancellationToken, Disposable, Event, EventEmitter, Terminal, TerminalShellExecution, window } from 'vscode';
import '../../common/extensions';
import { IInterpreterService } from '../../interpreter/contracts';
import { IServiceContainer } from '../../ioc/types';
import { captureTelemetry } from '../../telemetry';
import { EventName } from '../../telemetry/constants';
import { ITerminalAutoActivation } from '../../terminals/types';
import { ITerminalManager } from '../application/types';
import { _SCRIPTS_DIR } from '../process/internal/scripts/constants';
import { IConfigurationService, IDisposableRegistry } from '../types';
import {
ITerminalActivator,
ITerminalHelper,
ITerminalService,
TerminalCreationOptions,
TerminalShellType,
} from './types';
import { traceVerbose } from '../../logging';
import { getConfiguration } from '../vscodeApis/workspaceApis';
import { useEnvExtension } from '../../envExt/api.internal';
import { ensureTerminalLegacy } from '../../envExt/api.legacy';
import { sleep } from '../utils/async';
import { isWindows } from '../utils/platform';
import { getPythonMinorVersion } from '../../repl/replUtils';
import { PythonEnvironment } from '../../pythonEnvironments/info';
@injectable()
export class ExternalTerminalService implements ITerminalService, Disposable {
private terminal?: Terminal;
private ownsTerminal: boolean = false;
private terminalShellType!: TerminalShellType;
private terminalClosed = new EventEmitter<void>();
private terminalManager: ITerminalManager;
private terminalHelper: ITerminalHelper;
private terminalActivator: ITerminalActivator;
private terminalAutoActivator: ITerminalAutoActivation;
private readonly executeCommandListeners: Set<Disposable> = new Set();
private _terminalFirstLaunched: boolean = true;
public get onDidCloseTerminal(): Event<void> {
return this.terminalClosed.event.bind(this.terminalClosed);
}
constructor(
@inject(IServiceContainer) private serviceContainer: IServiceContainer,
private readonly options?: TerminalCreationOptions,
) {
const disposableRegistry = this.serviceContainer.get<Disposable[]>(IDisposableRegistry);
disposableRegistry.push(this);
this.terminalHelper = this.serviceContainer.get<ITerminalHelper>(ITerminalHelper);
this.terminalManager = this.serviceContainer.get<ITerminalManager>(ITerminalManager);
this.terminalAutoActivator = this.serviceContainer.get<ITerminalAutoActivation>(ITerminalAutoActivation);
this.terminalManager.onDidCloseTerminal(this.terminalCloseHandler, this, disposableRegistry);
this.terminalActivator = this.serviceContainer.get<ITerminalActivator>(ITerminalActivator);
}
public dispose() {
if (this.ownsTerminal) {
this.terminal?.dispose();
}
if (this.executeCommandListeners && this.executeCommandListeners.size > 0) {
this.executeCommandListeners.forEach((d) => {
d?.dispose();
});
}
}
public async sendCommand(command: string, args: string[], _?: CancellationToken): Promise<void> {
await this.ensureTerminal();
const text = this.terminalHelper.buildCommandForTerminal(this.terminalShellType, command, args);
if (!this.options?.hideFromUser) {
this.terminal!.show(true);
}
await this.executeCommand(text, false);
}
/** @deprecated */
public async sendText(text: string): Promise<void> {
await this.ensureTerminal();
if (!this.options?.hideFromUser) {
this.terminal!.show(true);
}
this.terminal!.sendText(text);
this.terminal = undefined;
}
public async executeCommand(
commandLine: string,
isPythonShell: boolean,
): Promise<TerminalShellExecution | undefined> {
const terminal = window.activeTerminal!;
if (!this.options?.hideFromUser) {
terminal.show(true);
}
// If terminal was just launched, wait some time for shell integration to onDidChangeShellIntegration.
if (!terminal.shellIntegration && this._terminalFirstLaunched) {
this._terminalFirstLaunched = false;
const promise = new Promise<boolean>((resolve) => {
const disposable = this.terminalManager.onDidChangeTerminalShellIntegration(() => {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
clearTimeout(timer);
disposable.dispose();
resolve(true);
});
const TIMEOUT_DURATION = 500;
const timer = setTimeout(() => {
disposable.dispose();
resolve(true);
}, TIMEOUT_DURATION);
});
await promise;
}
const config = getConfiguration('python');
const pythonrcSetting = config.get<boolean>('terminal.shellIntegration.enabled');
const minorVersion = this.options?.resource
? await getPythonMinorVersion(
this.options.resource,
this.serviceContainer.get<IInterpreterService>(IInterpreterService),
)
: undefined;
if ((isPythonShell && !pythonrcSetting) || (isPythonShell && isWindows()) || (minorVersion ?? 0) >= 13) {
// If user has explicitly disabled SI for Python, use sendText for inside Terminal REPL.
terminal.sendText(commandLine);
return undefined;
} else if (terminal.shellIntegration) {
const execution = terminal.shellIntegration.executeCommand(commandLine);
traceVerbose(`Shell Integration is enabled, executeCommand: ${commandLine}`);
return execution;
} else {
terminal.sendText(commandLine);
traceVerbose(`Shell Integration is disabled, sendText: ${commandLine}`);
}
this.terminal = undefined;
return undefined;
}
public async show(preserveFocus: boolean = true): Promise<void> {
await this.ensureTerminal(preserveFocus);
if (!this.options?.hideFromUser) {
this.terminal!.show(preserveFocus);
}
this.terminal = undefined;
}
private resolveInterpreterPath(
interpreter: PythonEnvironment | undefined,
settingsPythonPath: string | undefined,
): string {
if (interpreter) {
if ('path' in interpreter && interpreter.path) {
return interpreter.path;
}
const uriFsPath = (interpreter as any).uri?.fsPath as string | undefined;
if (uriFsPath) {
return uriFsPath;
}
}
return settingsPythonPath ?? 'python';
}
private runPythonReplInActiveTerminal() {
const settings = this.serviceContainer
.get<IConfigurationService>(IConfigurationService)
.getSettings(this.options?.resource);
const interpreterPath = this.resolveInterpreterPath(this.options?.interpreter, settings.pythonPath);
this.terminalShellType = this.terminalHelper.identifyTerminalShell(this.terminal);
const launchCmd = this.terminalHelper.buildCommandForTerminal(this.terminalShellType, interpreterPath, []);
this.terminal!.sendText(launchCmd);
}
// TODO: Debt switch to Promise<Terminal> ---> breaks 20 tests
public async ensureTerminal(preserveFocus: boolean = true): Promise<void> {
this.terminal = window.activeTerminal;
if (this.terminal) {
this.ownsTerminal = false;
if (this.terminal.state.shell !== 'python') {
this.runPythonReplInActiveTerminal();
}
return;
}
if (useEnvExtension()) {
this.terminal = await ensureTerminalLegacy(this.options?.resource, {
name: this.options?.title || 'Python',
hideFromUser: this.options?.hideFromUser,
});
this.ownsTerminal = true;
} else {
this.terminalShellType = this.terminalHelper.identifyTerminalShell(this.terminal);
this.terminal = this.terminalManager.createTerminal({
name: this.options?.title || 'Python',
hideFromUser: this.options?.hideFromUser,
});
this.ownsTerminal = true;
this.terminalAutoActivator.disableAutoActivation(this.terminal);
await sleep(100);
await this.terminalActivator.activateEnvironmentInTerminal(this.terminal, {
resource: this.options?.resource,
preserveFocus,
interpreter: this.options?.interpreter,
hideFromUser: this.options?.hideFromUser,
});
}
if (!this.options?.hideFromUser) {
this.terminal.show(preserveFocus);
}
this.sendTelemetry().ignoreErrors();
return;
}
private terminalCloseHandler(terminal: Terminal) {
if (terminal === this.terminal) {
this.terminalClosed.fire();
this.terminal = undefined;
this.ownsTerminal = false;
}
}
private async sendTelemetry() {
const pythonPath = this.serviceContainer
.get<IConfigurationService>(IConfigurationService)
.getSettings(this.options?.resource).pythonPath;
const interpreterInfo =
this.options?.interpreter ||
(await this.serviceContainer
.get<IInterpreterService>(IInterpreterService)
.getInterpreterDetails(pythonPath));
const pythonVersion = interpreterInfo && interpreterInfo.version ? interpreterInfo.version.raw : undefined;
const interpreterType = interpreterInfo ? interpreterInfo.envType : undefined;
captureTelemetry(EventName.TERMINAL_CREATE, {
terminal: this.terminalShellType,
pythonVersion,
interpreterType,
});
}
public hasActiveTerminal(): boolean {
return !!window.activeTerminal;
}
}