forked from eclipse-theia/theia
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathterminal-ext.ts
551 lines (471 loc) · 22.1 KB
/
terminal-ext.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
// *****************************************************************************
// Copyright (C) 2018 Red Hat, Inc. and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0.
//
// This Source Code may also be made available under the following Secondary
// Licenses when the conditions for such availability set forth in the Eclipse
// Public License v. 2.0 are satisfied: GNU General Public License, version 2
// with the GNU Classpath Exception which is available at
// https://www.gnu.org/software/classpath/license.html.
//
// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0
// *****************************************************************************
import { UUID } from '@theia/core/shared/@phosphor/coreutils';
import { Terminal, TerminalOptions, PseudoTerminalOptions, ExtensionTerminalOptions, TerminalState } from '@theia/plugin';
import { TerminalServiceExt, TerminalServiceMain, PLUGIN_RPC_CONTEXT } from '../common/plugin-api-rpc';
import { RPCProtocol } from '../common/rpc-protocol';
import { Event, Emitter } from '@theia/core/lib/common/event';
import { MultiKeyMap } from '@theia/core/lib/common/collections';
import { Deferred } from '@theia/core/lib/common/promise-util';
import * as theia from '@theia/plugin';
import * as Converter from './type-converters';
import { Disposable, EnvironmentVariableMutatorType, TerminalExitReason, ThemeIcon } from './types-impl';
import { NO_ROOT_URI, SerializableEnvironmentVariableCollection } from '@theia/terminal/lib/common/shell-terminal-protocol';
import { ProvidedTerminalLink } from '../common/plugin-api-rpc-model';
import { ThemeIcon as MonacoThemeIcon } from '@theia/monaco-editor-core/esm/vs/platform/theme/common/themeService';
export function getIconUris(iconPath: theia.TerminalOptions['iconPath']): { id: string } | undefined {
if (ThemeIcon.is(iconPath)) {
return { id: iconPath.id };
}
return undefined;
}
export function getIconClass(options: theia.TerminalOptions | theia.ExtensionTerminalOptions): string | undefined {
const iconClass = getIconUris(options.iconPath);
if (iconClass) {
return MonacoThemeIcon.asClassName(iconClass);
}
return undefined;
}
/**
* Provides high level terminal plugin api to use in the Theia plugins.
* This service allow(with help proxy) create and use terminal emulator.
*/
export class TerminalServiceExtImpl implements TerminalServiceExt {
private readonly proxy: TerminalServiceMain;
private readonly _terminals = new Map<string, TerminalExtImpl>();
private readonly _pseudoTerminals = new Map<string, PseudoTerminal>();
private static nextProviderId = 0;
private readonly terminalLinkProviders = new Map<string, theia.TerminalLinkProvider>();
private readonly terminalProfileProviders = new Map<string, theia.TerminalProfileProvider>();
private readonly onDidCloseTerminalEmitter = new Emitter<Terminal>();
readonly onDidCloseTerminal: theia.Event<Terminal> = this.onDidCloseTerminalEmitter.event;
private readonly onDidOpenTerminalEmitter = new Emitter<Terminal>();
readonly onDidOpenTerminal: theia.Event<Terminal> = this.onDidOpenTerminalEmitter.event;
private readonly onDidChangeActiveTerminalEmitter = new Emitter<Terminal | undefined>();
readonly onDidChangeActiveTerminal: theia.Event<Terminal | undefined> = this.onDidChangeActiveTerminalEmitter.event;
private readonly onDidChangeTerminalStateEmitter = new Emitter<Terminal>();
readonly onDidChangeTerminalState: theia.Event<Terminal> = this.onDidChangeTerminalStateEmitter.event;
protected environmentVariableCollections: MultiKeyMap<string, EnvironmentVariableCollectionImpl> = new MultiKeyMap(2);
private shell: string;
private readonly onDidChangeShellEmitter = new Emitter<string>();
readonly onDidChangeShell: theia.Event<string> = this.onDidChangeShellEmitter.event;
constructor(rpc: RPCProtocol) {
this.proxy = rpc.getProxy(PLUGIN_RPC_CONTEXT.TERMINAL_MAIN);
}
get terminals(): TerminalExtImpl[] {
return [...this._terminals.values()];
}
get defaultShell(): string {
return this.shell || '';
}
async $setShell(shell: string): Promise<void> {
if (this.shell !== shell) {
this.shell = shell;
this.onDidChangeShellEmitter.fire(shell);
}
}
createTerminal(
nameOrOptions: TerminalOptions | PseudoTerminalOptions | ExtensionTerminalOptions | (string | undefined),
shellPath?: string, shellArgs?: string[] | string
): Terminal {
const id = `plugin-terminal-${UUID.uuid4()}`;
let options: TerminalOptions;
let pseudoTerminal: theia.Pseudoterminal | undefined = undefined;
if (typeof nameOrOptions === 'object') {
if ('pty' in nameOrOptions) {
pseudoTerminal = nameOrOptions.pty;
options = {
name: nameOrOptions.name,
};
this._pseudoTerminals.set(id, new PseudoTerminal(id, this.proxy, pseudoTerminal));
} else {
options = nameOrOptions;
}
} else {
options = {
name: nameOrOptions,
shellPath: shellPath,
shellArgs: shellArgs
};
}
let parentId;
if (options.location && typeof options.location === 'object' && 'parentTerminal' in options.location) {
const parentTerminal = options.location.parentTerminal;
if (parentTerminal instanceof TerminalExtImpl) {
for (const [k, v] of this._terminals) {
if (v === parentTerminal) {
parentId = k;
break;
}
}
}
}
this.proxy.$createTerminal(id, options, parentId, !!pseudoTerminal);
let creationOptions: theia.TerminalOptions | theia.ExtensionTerminalOptions = options;
// make sure to pass ExtensionTerminalOptions as creation options
if (typeof nameOrOptions === 'object' && 'pty' in nameOrOptions) {
creationOptions = nameOrOptions;
}
return this.obtainTerminal(id, options.name || 'Terminal', creationOptions);
}
attachPtyToTerminal(terminalId: number, pty: theia.Pseudoterminal): void {
this._pseudoTerminals.set(terminalId.toString(), new PseudoTerminal(terminalId, this.proxy, pty, true));
}
protected obtainTerminal(id: string, name: string, options?: theia.TerminalOptions | theia.ExtensionTerminalOptions): TerminalExtImpl {
let terminal = this._terminals.get(id);
if (!terminal) {
terminal = new TerminalExtImpl(this.proxy, options ?? {});
this._terminals.set(id, terminal);
}
terminal.name = name;
return terminal;
}
$terminalOnInput(id: string, data: string): void {
const terminal = this._pseudoTerminals.get(id);
if (!terminal) {
return;
}
terminal.emitOnInput(data);
}
$terminalStateChanged(id: string): void {
const terminal = this._terminals.get(id);
if (!terminal) {
return;
}
if (!terminal.state.isInteractedWith) {
terminal.state = { isInteractedWith: true };
this.onDidChangeTerminalStateEmitter.fire(terminal);
}
}
$terminalSizeChanged(id: string, clos: number, rows: number): void {
const terminal = this._pseudoTerminals.get(id);
if (!terminal) {
return;
}
terminal.emitOnResize(clos, rows);
}
$terminalCreated(id: string, name: string): void {
const terminal = this.obtainTerminal(id, name);
terminal.id.resolve(id);
this.onDidOpenTerminalEmitter.fire(terminal);
}
$terminalNameChanged(id: string, name: string): void {
const terminal = this._terminals.get(id);
if (terminal) {
terminal.name = name;
}
}
$terminalOpened(id: string, processId: number, terminalId: number, cols: number, rows: number): void {
const terminal = this._terminals.get(id);
if (terminal) {
// resolve for existing clients
terminal.deferredProcessId.resolve(processId);
// install new if terminal is reconnected
terminal.deferredProcessId = new Deferred<number>();
terminal.deferredProcessId.resolve(processId);
}
// Switch the pseudoterminal keyed by terminalId to be keyed by terminal ID
const tId = terminalId.toString();
if (this._pseudoTerminals.has(tId)) {
const pseudo = this._pseudoTerminals.get(tId);
if (pseudo) {
this._pseudoTerminals.set(id, pseudo);
}
this._pseudoTerminals.delete(tId);
}
const pseudoTerminal = this._pseudoTerminals.get(id);
if (pseudoTerminal) {
pseudoTerminal.emitOnOpen(cols, rows);
}
}
$terminalClosed(id: string, exitStatus: theia.TerminalExitStatus | undefined): void {
const terminal = this._terminals.get(id);
if (terminal) {
terminal.exitStatus = exitStatus ?? { code: undefined, reason: TerminalExitReason.Unknown };
this.onDidCloseTerminalEmitter.fire(terminal);
this._terminals.delete(id);
}
const pseudoTerminal = this._pseudoTerminals.get(id);
if (pseudoTerminal) {
pseudoTerminal.emitOnClose();
this._pseudoTerminals.delete(id);
}
}
private activeTerminalId: string | undefined;
get activeTerminal(): TerminalExtImpl | undefined {
return this.activeTerminalId && this._terminals.get(this.activeTerminalId) || undefined;
}
$currentTerminalChanged(id: string | undefined): void {
this.activeTerminalId = id;
this.onDidChangeActiveTerminalEmitter.fire(this.activeTerminal);
}
registerTerminalLinkProvider(provider: theia.TerminalLinkProvider): theia.Disposable {
const providerId = (TerminalServiceExtImpl.nextProviderId++).toString();
this.terminalLinkProviders.set(providerId, provider);
this.proxy.$registerTerminalLinkProvider(providerId);
return Disposable.create(() => {
this.proxy.$unregisterTerminalLinkProvider(providerId);
this.terminalLinkProviders.delete(providerId);
});
}
registerTerminalProfileProvider(id: string, provider: theia.TerminalProfileProvider): theia.Disposable {
this.terminalProfileProviders.set(id, provider);
return Disposable.create(() => {
this.terminalProfileProviders.delete(id);
});
}
/** @stubbed */
registerTerminalQuickFixProvider(id: string, provider: theia.TerminalQuickFixProvider): theia.Disposable {
return Disposable.NULL;
}
protected isExtensionTerminalOptions(options: theia.TerminalOptions | theia.ExtensionTerminalOptions): options is theia.ExtensionTerminalOptions {
return 'pty' in options;
}
async $startProfile(profileId: string, cancellationToken: theia.CancellationToken): Promise<string> {
const provider = this.terminalProfileProviders.get(profileId);
if (!provider) {
throw new Error(`No terminal profile provider with id '${profileId}'`);
}
const profile = await provider.provideTerminalProfile(cancellationToken);
if (!profile) {
throw new Error(`Profile with id ${profileId} could not be created`);
}
const id = `plugin-terminal-${UUID.uuid4()}`;
const options = profile.options;
if (this.isExtensionTerminalOptions(options)) {
this._pseudoTerminals.set(id, new PseudoTerminal(id, this.proxy, options.pty));
return this.proxy.$createTerminal(id, { name: options.name }, undefined, true);
} else {
return this.proxy.$createTerminal(id, profile.options);
}
}
async $provideTerminalLinks(line: string, terminalId: string, token: theia.CancellationToken): Promise<ProvidedTerminalLink[]> {
const links: ProvidedTerminalLink[] = [];
const terminal = this._terminals.get(terminalId);
if (terminal) {
for (const [providerId, provider] of this.terminalLinkProviders) {
const providedLinks = await provider.provideTerminalLinks({ line, terminal }, token);
if (providedLinks) {
links.push(...providedLinks.map(link => ({ ...link, providerId })));
}
}
}
return links;
}
async $handleTerminalLink(link: ProvidedTerminalLink): Promise<void> {
const provider = this.terminalLinkProviders.get(link.providerId);
if (!provider) {
throw Error('Terminal link provider not found');
}
await provider.handleTerminalLink(link);
}
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// some code copied and modified from https://github.com/microsoft/vscode/blob/1.49.0/src/vs/workbench/api/common/extHostTerminalService.ts
getEnvironmentVariableCollection(extensionIdentifier: string, rootUri: string = NO_ROOT_URI): theia.GlobalEnvironmentVariableCollection {
const that = this;
let collection = this.environmentVariableCollections.get([extensionIdentifier, rootUri]);
if (!collection) {
collection = new class extends EnvironmentVariableCollectionImpl {
override getScoped(scope: theia.EnvironmentVariableScope): theia.EnvironmentVariableCollection {
return that.getEnvironmentVariableCollection(extensionIdentifier, scope.workspaceFolder?.uri.toString());
}
}(true);
this.setEnvironmentVariableCollection(extensionIdentifier, rootUri, collection);
}
return collection;
}
private syncEnvironmentVariableCollection(extensionIdentifier: string, rootUri: string, collection: EnvironmentVariableCollectionImpl): void {
const serialized = [...collection.map.entries()];
this.proxy.$setEnvironmentVariableCollection(collection.persistent, extensionIdentifier,
rootUri,
{
mutators: serialized,
description: Converter.fromMarkdownOrString(collection.description)
});
}
private setEnvironmentVariableCollection(pluginIdentifier: string, rootUri: string, collection: EnvironmentVariableCollectionImpl): void {
this.environmentVariableCollections.set([pluginIdentifier, rootUri], collection);
collection.onDidChangeCollection(() => {
// When any collection value changes send this immediately, this is done to ensure
// following calls to createTerminal will be created with the new environment. It will
// result in more noise by sending multiple updates when called but collections are
// expected to be small.
this.syncEnvironmentVariableCollection(pluginIdentifier, rootUri, collection);
});
}
$initEnvironmentVariableCollections(collections: [string, string, boolean, SerializableEnvironmentVariableCollection][]): void {
collections.forEach(entry => {
const extensionIdentifier = entry[0];
const rootUri = entry[1];
const collection = new EnvironmentVariableCollectionImpl(entry[2], entry[3]);
this.setEnvironmentVariableCollection(extensionIdentifier, rootUri, collection);
});
}
}
export class EnvironmentVariableCollectionImpl implements theia.GlobalEnvironmentVariableCollection {
readonly map: Map<string, theia.EnvironmentVariableMutator> = new Map();
private _description?: string | theia.MarkdownString;
private _persistent: boolean = true;
public get description(): string | theia.MarkdownString | undefined { return this._description; }
public set description(value: string | theia.MarkdownString | undefined) {
this._description = value;
this.onDidChangeCollectionEmitter.fire();
}
public get persistent(): boolean { return this._persistent; }
public set persistent(value: boolean) {
this._persistent = value;
this.onDidChangeCollectionEmitter.fire();
}
protected readonly onDidChangeCollectionEmitter: Emitter<void> = new Emitter<void>();
onDidChangeCollection: Event<void> = this.onDidChangeCollectionEmitter.event;
constructor(
persistent: boolean,
serialized?: SerializableEnvironmentVariableCollection
) {
this._persistent = persistent;
this.map = new Map(serialized?.mutators);
}
getScoped(scope: theia.EnvironmentVariableScope): theia.EnvironmentVariableCollection {
throw new Error('Cannot get scoped from a regular env var collection');
}
get size(): number {
return this.map.size;
}
replace(variable: string, value: string, options?: theia.EnvironmentVariableMutatorOptions): void {
this._setIfDiffers(variable, { value, type: EnvironmentVariableMutatorType.Replace, options: options ?? { applyAtProcessCreation: true } });
}
append(variable: string, value: string, options?: theia.EnvironmentVariableMutatorOptions): void {
this._setIfDiffers(variable, { value, type: EnvironmentVariableMutatorType.Append, options: options ?? { applyAtProcessCreation: true } });
}
prepend(variable: string, value: string, options?: theia.EnvironmentVariableMutatorOptions): void {
this._setIfDiffers(variable, { value, type: EnvironmentVariableMutatorType.Prepend, options: options ?? { applyAtProcessCreation: true } });
}
private _setIfDiffers(variable: string, mutator: theia.EnvironmentVariableMutator): void {
const current = this.map.get(variable);
if (!current || current.value !== mutator.value || current.type !== mutator.type) {
this.map.set(variable, mutator);
this.onDidChangeCollectionEmitter.fire();
}
}
get(variable: string): theia.EnvironmentVariableMutator | undefined {
return this.map.get(variable);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
forEach(callback: (variable: string, mutator: theia.EnvironmentVariableMutator, collection: theia.EnvironmentVariableCollection) => any, thisArg?: any): void {
this.map.forEach((value, key) => callback.call(thisArg, key, value, this));
}
delete(variable: string): void {
this.map.delete(variable);
this.onDidChangeCollectionEmitter.fire();
}
clear(): void {
this.map.clear();
this.onDidChangeCollectionEmitter.fire();
}
}
export class TerminalExtImpl implements Terminal {
name: string;
readonly id = new Deferred<string>();
exitStatus: theia.TerminalExitStatus | undefined;
deferredProcessId = new Deferred<number>();
get processId(): Thenable<number> {
return this.deferredProcessId.promise;
}
readonly creationOptions: Readonly<TerminalOptions | ExtensionTerminalOptions>;
state: TerminalState = { isInteractedWith: false };
constructor(private readonly proxy: TerminalServiceMain, private readonly options: theia.TerminalOptions | theia.ExtensionTerminalOptions) {
this.creationOptions = this.options;
}
sendText(text: string, addNewLine: boolean = true): void {
this.id.promise.then(id => this.proxy.$sendText(id, text, addNewLine));
}
show(preserveFocus?: boolean): void {
this.id.promise.then(id => this.proxy.$show(id, preserveFocus));
}
hide(): void {
this.id.promise.then(id => this.proxy.$hide(id));
}
dispose(): void {
this.id.promise.then(id => this.proxy.$dispose(id));
}
}
export class PseudoTerminal {
constructor(
id: string | number,
private readonly proxy: TerminalServiceMain,
private readonly pseudoTerminal: theia.Pseudoterminal,
waitOnExit?: boolean | string
) {
pseudoTerminal.onDidWrite(data => {
if (typeof id === 'string') {
this.proxy.$write(id, data);
} else {
this.proxy.$writeByTerminalId(id, data);
}
});
if (pseudoTerminal.onDidClose) {
pseudoTerminal.onDidClose((e: number | void = undefined) => {
if (typeof id === 'string') {
this.proxy.$dispose(id);
} else {
this.proxy.$disposeByTerminalId(id, waitOnExit);
}
});
}
if (pseudoTerminal.onDidOverrideDimensions) {
pseudoTerminal.onDidOverrideDimensions(e => {
if (e) {
if (typeof id === 'string') {
this.proxy.$resize(id, e.columns, e.rows);
} else {
this.proxy.$resizeByTerminalId(id, e.columns, e.rows);
}
}
});
}
if (pseudoTerminal.onDidChangeName) {
pseudoTerminal.onDidChangeName(name => {
if (typeof id === 'string') {
this.proxy.$setName(id, name);
} else {
this.proxy.$setNameByTerminalId(id, name);
}
});
}
}
emitOnClose(): void {
this.pseudoTerminal.close();
}
emitOnInput(data: string): void {
if (this.pseudoTerminal.handleInput) {
this.pseudoTerminal.handleInput(data);
}
}
emitOnOpen(cols: number, rows: number): void {
this.pseudoTerminal.open({
rows,
columns: cols,
});
}
emitOnResize(cols: number, rows: number): void {
if (this.pseudoTerminal.setDimensions) {
this.pseudoTerminal.setDimensions({ columns: cols, rows });
}
}
}