forked from DonJayamanne/pythonVSCode
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathservice.ts
More file actions
280 lines (255 loc) · 10.8 KB
/
service.ts
File metadata and controls
280 lines (255 loc) · 10.8 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
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import { inject, injectable } from 'inversify';
import { CancellationToken, Disposable, Event, EventEmitter, Terminal, TerminalShellExecution } 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 { IApplicationShell, 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 { sleep } from '../utils/async';
import { useEnvExtension } from '../../envExt/api.internal';
import { ensureTerminalLegacy } from '../../envExt/api.legacy';
@injectable()
export class TerminalService implements ITerminalService, Disposable {
private terminal?: Terminal;
private terminalShellType!: TerminalShellType;
private terminalClosed = new EventEmitter<void>();
private terminalManager: ITerminalManager;
private terminalHelper: ITerminalHelper;
private terminalActivator: ITerminalActivator;
private terminalAutoActivator: ITerminalAutoActivation;
private applicationShell: IApplicationShell;
private readonly executeCommandListeners: Set<Disposable> = new Set();
private _terminalFirstLaunched: boolean = true;
private pythonReplCommandQueue: string[] = [];
private isReplReady: boolean = false;
private replPromptListener?: Disposable;
private replShellTypeListener?: Disposable;
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.applicationShell = this.serviceContainer.get<IApplicationShell>(IApplicationShell);
this.terminalManager.onDidCloseTerminal(this.terminalCloseHandler, this, disposableRegistry);
this.terminalActivator = this.serviceContainer.get<ITerminalActivator>(ITerminalActivator);
}
public dispose() {
this.terminal?.dispose();
this.disposeReplListener();
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);
}
public async executeCommand(
commandLine: string,
isPythonShell: boolean,
): Promise<TerminalShellExecution | undefined> {
if (isPythonShell) {
if (this.isReplReady) {
this.terminal?.sendText(commandLine);
traceVerbose(`Python REPL sendText: ${commandLine}`);
} else {
// Queue command to run once REPL is ready.
this.pythonReplCommandQueue.push(commandLine);
traceVerbose(`Python REPL queued command: ${commandLine}`);
this.startReplListener();
}
return undefined;
}
// Non-REPL code execution
return this.executeCommandInternal(commandLine);
}
private startReplListener(): void {
if (this.replPromptListener || this.replShellTypeListener) {
return;
}
this.replShellTypeListener = this.terminalManager.onDidChangeTerminalState((terminal) => {
if (this.terminal && terminal === this.terminal) {
if (terminal.state.shell == 'python') {
traceVerbose('Python REPL ready from terminal shell api');
this.onReplReady();
}
}
});
let terminalData = '';
this.replPromptListener = this.applicationShell.onDidWriteTerminalData((e) => {
if (this.terminal && e.terminal === this.terminal) {
terminalData += e.data;
if (/>>>\s*$/.test(terminalData)) {
traceVerbose('Python REPL ready, from >>> prompt detection');
this.onReplReady();
}
}
});
}
private onReplReady(): void {
if (this.isReplReady) {
return;
}
this.isReplReady = true;
this.flushReplQueue();
this.disposeReplListener();
}
private disposeReplListener(): void {
if (this.replPromptListener) {
this.replPromptListener.dispose();
this.replPromptListener = undefined;
}
if (this.replShellTypeListener) {
this.replShellTypeListener.dispose();
this.replShellTypeListener = undefined;
}
}
private flushReplQueue(): void {
while (this.pythonReplCommandQueue.length > 0) {
const commandLine = this.pythonReplCommandQueue.shift();
if (commandLine) {
traceVerbose(`Executing queued REPL command: ${commandLine}`);
this.terminal?.sendText(commandLine);
}
}
}
private async executeCommandInternal(commandLine: string): Promise<TerminalShellExecution | undefined> {
const terminal = this.terminal;
if (!terminal) {
traceVerbose('Terminal not available, cannot execute command');
return undefined;
}
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;
}
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}`);
}
return undefined;
}
public async show(preserveFocus: boolean = true): Promise<void> {
await this.ensureTerminal(preserveFocus);
if (!this.options?.hideFromUser) {
this.terminal!.show(preserveFocus);
}
}
// TODO: Debt switch to Promise<Terminal> ---> breaks 20 tests
public async ensureTerminal(preserveFocus: boolean = true): Promise<void> {
if (this.terminal) {
return;
}
if (useEnvExtension()) {
this.terminal = await ensureTerminalLegacy(this.options?.resource, {
name: this.options?.title || 'Python',
hideFromUser: this.options?.hideFromUser,
});
return;
} else {
this.terminalShellType = this.terminalHelper.identifyTerminalShell(this.terminal);
this.terminal = this.terminalManager.createTerminal({
name: this.options?.title || 'Python',
hideFromUser: this.options?.hideFromUser,
});
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.isReplReady = false;
this.disposeReplListener();
this.pythonReplCommandQueue = [];
}
}
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 !!this.terminal;
}
}