terminalInstance.ts 14.8 KB
Newer Older
1 2 3 4 5 6
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

import DOM = require('vs/base/browser/dom');
J
Johannes Rieken 已提交
7
import Event, { Emitter } from 'vs/base/common/event';
8 9
import URI from 'vs/base/common/uri';
import cp = require('child_process');
10
import lifecycle = require('vs/base/common/lifecycle');
C
Christof Marti 已提交
11
import nls = require('vs/nls');
C
Christof Marti 已提交
12
import os = require('os');
13 14
import path = require('path');
import platform = require('vs/base/common/platform');
15
import xterm = require('xterm');
16
import { Dimension } from 'vs/base/browser/builder';
17
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
18 19 20
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IMessageService, Severity } from 'vs/platform/message/common/message';
import { IStringDictionary } from 'vs/base/common/collections';
21
import { ITerminalInstance, KEYBINDING_CONTEXT_TERMINAL_TEXT_SELECTED, IShell } from 'vs/workbench/parts/terminal/common/terminal';
22 23 24
import { IWorkspace } from 'vs/platform/workspace/common/workspace';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { TabFocus } from 'vs/editor/common/config/commonEditorConfig';
25
import { TerminalConfigHelper } from 'vs/workbench/parts/terminal/electron-browser/terminalConfigHelper';
26

27
export class TerminalInstance implements ITerminalInstance {
28 29
	/** The amount of time to consider terminal errors to be related to the launch */
	private static readonly LAUNCHING_DURATION = 500;
30
	private static readonly EOL_REGEX = /\r?\n/g;
C
Christof Marti 已提交
31

D
Daniel Imms 已提交
32 33
	private static _idCounter = 1;

34
	private _id: number;
D
Daniel Imms 已提交
35
	private _isExiting: boolean;
K
Kai Wood 已提交
36
	private _hadFocusOnExit: boolean;
37
	private _isLaunching: boolean;
D
Daniel Imms 已提交
38
	private _isVisible: boolean;
39
	private _onDisposed: Emitter<TerminalInstance>;
40
	private _onProcessIdReady: Emitter<TerminalInstance>;
D
Daniel Imms 已提交
41
	private _onTitleChanged: Emitter<string>;
D
Daniel Imms 已提交
42
	private _process: cp.ChildProcess;
43
	private _processId: number;
D
Daniel Imms 已提交
44
	private _skipTerminalCommands: string[];
D
Daniel Imms 已提交
45 46 47 48 49
	private _title: string;
	private _toDispose: lifecycle.IDisposable[];
	private _wrapperElement: HTMLDivElement;
	private _xterm: any;
	private _xtermElement: HTMLDivElement;
50
	private _terminalHasTextContextKey: IContextKey<boolean>;
D
Daniel Imms 已提交
51

52
	public get id(): number { return this._id; }
53
	public get processId(): number { return this._processId; }
54
	public get onClosed(): Event<TerminalInstance> { return this._onDisposed.event; }
55
	public get onProcessIdReady(): Event<TerminalInstance> { return this._onProcessIdReady.event; }
D
Daniel Imms 已提交
56
	public get onTitleChanged(): Event<string> { return this._onTitleChanged.event; }
D
Daniel Imms 已提交
57
	public get title(): string { return this._title; }
K
Kai Wood 已提交
58
	public get hadFocusOnExit(): boolean { return this._hadFocusOnExit; }
59 60

	public constructor(
D
Daniel Imms 已提交
61 62 63
		private _terminalFocusContextKey: IContextKey<boolean>,
		private _configHelper: TerminalConfigHelper,
		private _container: HTMLElement,
D
Daniel Imms 已提交
64
		workspace: IWorkspace,
65
		name: string,
P
Pine Wu 已提交
66
		shell: IShell,
67
		@IContextKeyService private _contextKeyService: IContextKeyService,
D
Daniel Imms 已提交
68 69
		@IKeybindingService private _keybindingService: IKeybindingService,
		@IMessageService private _messageService: IMessageService
70
	) {
D
Daniel Imms 已提交
71
		this._toDispose = [];
D
Daniel Imms 已提交
72
		this._skipTerminalCommands = [];
D
Daniel Imms 已提交
73
		this._isExiting = false;
K
Kai Wood 已提交
74
		this._hadFocusOnExit = false;
75
		this._isLaunching = true;
D
Daniel Imms 已提交
76 77
		this._isVisible = false;
		this._id = TerminalInstance._idCounter++;
78
		this._terminalHasTextContextKey = KEYBINDING_CONTEXT_TERMINAL_TEXT_SELECTED.bindTo(this._contextKeyService);
D
Daniel Imms 已提交
79

80
		this._onDisposed = new Emitter<TerminalInstance>();
81 82
		this._onProcessIdReady = new Emitter<TerminalInstance>();
		this._onTitleChanged = new Emitter<string>();
83

D
Daniel Imms 已提交
84
		this._createProcess(workspace, name, shell);
D
Daniel Imms 已提交
85 86 87

		if (_container) {
			this.attachToElement(_container);
88 89 90
		}
	}

D
Daniel Imms 已提交
91
	public addDisposable(disposable: lifecycle.IDisposable): void {
D
Daniel Imms 已提交
92
		this._toDispose.push(disposable);
D
Daniel Imms 已提交
93 94
	}

95
	public attachToElement(container: HTMLElement): void {
D
Daniel Imms 已提交
96
		if (this._wrapperElement) {
97 98 99
			throw new Error('The terminal instance has already been attached to a container');
		}

D
Daniel Imms 已提交
100 101 102 103
		this._container = container;
		this._wrapperElement = document.createElement('div');
		DOM.addClass(this._wrapperElement, 'terminal-wrapper');
		this._xtermElement = document.createElement('div');
104

D
Daniel Imms 已提交
105 106
		this._xterm = xterm();
		this._xterm.open(this._xtermElement);
107

D
Daniel Imms 已提交
108
		this._process.on('message', (message) => {
D
Daniel Imms 已提交
109 110 111
			if (!this._xterm) {
				return;
			}
D
Daniel Imms 已提交
112
			if (message.type === 'data') {
D
Daniel Imms 已提交
113
				this._xterm.write(message.content);
D
Daniel Imms 已提交
114 115
			}
		});
D
Daniel Imms 已提交
116 117
		this._xterm.on('data', (data) => {
			this._process.send({
D
Daniel Imms 已提交
118
				event: 'input',
D
Daniel Imms 已提交
119
				data: this._sanitizeInput(data)
D
Daniel Imms 已提交
120 121 122
			});
			return false;
		});
D
Daniel Imms 已提交
123
		this._xterm.attachCustomKeydownHandler((event: KeyboardEvent) => {
124 125
			// Skip processing by xterm.js of keyboard events that resolve to commands described
			// within commandsToSkipShell
D
Daniel Imms 已提交
126
			const standardKeyboardEvent = new StandardKeyboardEvent(event);
127
			const keybinding = standardKeyboardEvent.toKeybinding();
D
Daniel Imms 已提交
128 129
			const resolveResult = this._keybindingService.resolve(keybinding, standardKeyboardEvent.target);
			if (resolveResult && this._skipTerminalCommands.some(k => k === resolveResult.commandId)) {
D
Daniel Imms 已提交
130 131 132 133 134 135 136 137 138
				event.preventDefault();
				return false;
			}

			// If tab focus mode is on, tab is not passed to the terminal
			if (TabFocus.getTabFocusMode() && event.keyCode === 9) {
				return false;
			}
		});
139 140 141 142
		(<HTMLElement>this._xterm.element).addEventListener('mouseup', event => {
			// Wait until mouseup has propogated through the DOM before evaluating the new selection
			// state.
			setTimeout(() => {
143 144 145 146 147 148 149 150 151 152
				this._refreshSelectionContextKey();
			}, 0);
		});

		// xterm.js currently drops selection on keyup as we need to handle this case.
		(<HTMLElement>this._xterm.element).addEventListener('keyup', event => {
			// Wait until keyup has propogated through the DOM before evaluating the new selection
			// state.
			setTimeout(() => {
				this._refreshSelectionContextKey();
153 154
			}, 0);
		});
D
Daniel Imms 已提交
155

D
Daniel Imms 已提交
156
		let xtermHelper: HTMLElement = this._xterm.element.querySelector('.xterm-helpers');
157 158 159 160 161 162 163 164 165 166 167
		let focusTrap: HTMLElement = document.createElement('div');
		focusTrap.setAttribute('tabindex', '0');
		DOM.addClass(focusTrap, 'focus-trap');
		focusTrap.addEventListener('focus', function (event: FocusEvent) {
			let currentElement = focusTrap;
			while (!DOM.hasClass(currentElement, 'part')) {
				currentElement = currentElement.parentElement;
			}
			let hidePanelElement = <HTMLElement>currentElement.querySelector('.hide-panel-action');
			hidePanelElement.focus();
		});
D
Daniel Imms 已提交
168
		xtermHelper.insertBefore(focusTrap, this._xterm.textarea);
169

D
Daniel Imms 已提交
170 171
		this._toDispose.push(DOM.addDisposableListener(this._xterm.textarea, 'focus', (event: KeyboardEvent) => {
			this._terminalFocusContextKey.set(true);
172
		}));
D
Daniel Imms 已提交
173 174
		this._toDispose.push(DOM.addDisposableListener(this._xterm.textarea, 'blur', (event: KeyboardEvent) => {
			this._terminalFocusContextKey.reset();
175
		}));
D
Daniel Imms 已提交
176 177
		this._toDispose.push(DOM.addDisposableListener(this._xterm.element, 'focus', (event: KeyboardEvent) => {
			this._terminalFocusContextKey.set(true);
178
		}));
D
Daniel Imms 已提交
179 180
		this._toDispose.push(DOM.addDisposableListener(this._xterm.element, 'blur', (event: KeyboardEvent) => {
			this._terminalFocusContextKey.reset();
181 182
		}));

D
Daniel Imms 已提交
183 184
		this._wrapperElement.appendChild(this._xtermElement);
		this._container.appendChild(this._wrapperElement);
185

186 187 188 189
		const computedStyle = window.getComputedStyle(this._container);
		const width = parseInt(computedStyle.getPropertyValue('width').replace('px', ''), 10);
		const height = parseInt(computedStyle.getPropertyValue('height').replace('px', ''), 10);
		this.layout(new Dimension(width, height));
D
Daniel Imms 已提交
190
		this.setVisible(this._isVisible);
K
Kai Wood 已提交
191 192 193
		this.setCursorBlink(this._configHelper.getCursorBlink());
		this.setCommandsToSkipShell(this._configHelper.getCommandsToSkipShell());
		this.setScrollback(this._configHelper.getScrollback());
194 195
	}

D
Daniel Imms 已提交
196
	public copySelection(): void {
D
Daniel Imms 已提交
197 198 199
		if (document.activeElement.classList.contains('xterm')) {
			document.execCommand('copy');
		} else {
D
Daniel Imms 已提交
200
			this._messageService.show(Severity.Warning, nls.localize('terminal.integrated.copySelection.noSelection', 'Cannot copy terminal selection when terminal does not have focus'));
D
Daniel Imms 已提交
201
		}
D
Daniel Imms 已提交
202 203 204
	}

	public dispose(): void {
205
		this._isExiting = true;
K
Kai Wood 已提交
206 207 208 209

		if (this._xterm && this._xterm.element) {
			this._hadFocusOnExit = DOM.hasClass(this._xterm.element, 'focus');
		}
D
Daniel Imms 已提交
210 211 212
		if (this._wrapperElement) {
			this._container.removeChild(this._wrapperElement);
			this._wrapperElement = null;
D
Daniel Imms 已提交
213
		}
D
Daniel Imms 已提交
214 215 216
		if (this._xterm) {
			this._xterm.destroy();
			this._xterm = null;
D
Daniel Imms 已提交
217
		}
D
Daniel Imms 已提交
218 219 220
		if (this._process) {
			if (this._process.connected) {
				this._process.kill();
D
Daniel Imms 已提交
221
			}
D
Daniel Imms 已提交
222
			this._process = null;
D
Daniel Imms 已提交
223
		}
224
		this._onDisposed.fire(this);
D
Daniel Imms 已提交
225
		this._toDispose = lifecycle.dispose(this._toDispose);
D
Daniel Imms 已提交
226 227
	}

D
Daniel Imms 已提交
228
	public focus(force?: boolean): void {
D
Daniel Imms 已提交
229
		if (!this._xterm) {
D
Daniel Imms 已提交
230 231 232 233
			return;
		}
		let text = window.getSelection().toString();
		if (!text || force) {
D
Daniel Imms 已提交
234
			this._xterm.focus();
D
Daniel Imms 已提交
235
		}
D
Daniel Imms 已提交
236 237 238
	}

	public paste(): void {
D
Daniel Imms 已提交
239 240
		this.focus();
		document.execCommand('paste');
D
Daniel Imms 已提交
241 242 243
	}

	public sendText(text: string, addNewLine: boolean): void {
D
Daniel Imms 已提交
244 245 246
		if (addNewLine && text.substr(text.length - os.EOL.length) !== os.EOL) {
			text += os.EOL;
		}
D
Daniel Imms 已提交
247
		this._process.send({
D
Daniel Imms 已提交
248 249 250
			event: 'input',
			data: text
		});
D
Daniel Imms 已提交
251
	}
252 253

	public setVisible(visible: boolean): void {
D
Daniel Imms 已提交
254 255 256
		this._isVisible = visible;
		if (this._wrapperElement) {
			DOM.toggleClass(this._wrapperElement, 'active', visible);
257
		}
258 259
	}

260
	public scrollDownLine(): void {
D
Daniel Imms 已提交
261
		this._xterm.scrollDisp(1);
D
Daniel Imms 已提交
262 263
	}

264
	public scrollDownPage(): void {
265
		this._xterm.scrollPages(1);
266 267
	}

268 269 270 271
	public scrollToBottom(): void {
		this._xterm.scrollToBottom();
	}

272
	public scrollUpLine(): void {
D
Daniel Imms 已提交
273
		this._xterm.scrollDisp(-1);
D
Daniel Imms 已提交
274
	}
275

276
	public scrollUpPage(): void {
277
		this._xterm.scrollPages(-1);
278 279
	}

280 281 282 283
	public scrollToTop(): void {
		this._xterm.scrollToTop();
	}

D
Daniel Imms 已提交
284 285 286 287
	public clear(): void {
		this._xterm.clear();
	}

288 289 290 291
	private _refreshSelectionContextKey() {
		this._terminalHasTextContextKey.set(!window.getSelection().isCollapsed);
	}

D
Daniel Imms 已提交
292
	private _sanitizeInput(data: any) {
293
		return typeof data === 'string' ? data.replace(TerminalInstance.EOL_REGEX, os.EOL) : data;
C
Christof Marti 已提交
294 295
	}

D
Daniel Imms 已提交
296 297
	private _createProcess(workspace: IWorkspace, name: string, shell: IShell) {
		let locale = this._configHelper.isSetLocaleVariables() ? platform.locale : undefined;
D
Daniel Imms 已提交
298
		if (!shell.executable) {
D
Daniel Imms 已提交
299
			shell = this._configHelper.getShell();
P
Pine Wu 已提交
300
		}
D
Daniel Imms 已提交
301
		let env = TerminalInstance.createTerminalEnv(process.env, shell, workspace, locale);
302
		this._title = name ? name : '';
D
Daniel Imms 已提交
303
		this._process = cp.fork('./terminalProcess', [], {
304 305 306 307 308
			env: env,
			cwd: URI.parse(path.dirname(require.toUrl('./terminalProcess'))).fsPath
		});
		if (!name) {
			// Only listen for process title changes when a name is not provided
D
Daniel Imms 已提交
309
			this._process.on('message', (message) => {
310
				if (message.type === 'title') {
D
Daniel Imms 已提交
311
					this._title = message.content ? message.content : '';
312
					this._onTitleChanged.fire(this._title);
313
				}
314 315
			});
		}
316 317 318 319 320 321
		this._process.on('message', (message) => {
			if (message.type === 'pid') {
				this._processId = message.content;
				this._onProcessIdReady.fire(this);
			}
		});
D
Daniel Imms 已提交
322
		this._process.on('exit', (exitCode) => {
323
			// Prevent dispose functions being triggered multiple times
D
Daniel Imms 已提交
324
			if (!this._isExiting) {
325 326
				this.dispose();
				if (exitCode) {
327 328 329 330 331 332
					if (this._isLaunching) {
						const args = shell.args && shell.args.length ? ' ' + shell.args.map(a => a.indexOf(' ') !== -1 ? `'${a}'` : a).join(' ') : '';
						this._messageService.show(Severity.Error, nls.localize('terminal.integrated.launchFailed', 'The terminal process command `{0}{1}` failed to launch (exit code: {2})', shell.executable, args, exitCode));
					} else {
						this._messageService.show(Severity.Error, nls.localize('terminal.integrated.exitedWithCode', 'The terminal process terminated with exit code: {0}', exitCode));
					}
333 334 335
				}
			}
		});
336 337 338
		setTimeout(() => {
			this._isLaunching = false;
		}, TerminalInstance.LAUNCHING_DURATION);
339 340
	}

D
Daniel Imms 已提交
341
	public static createTerminalEnv(parentEnv: IStringDictionary<string>, shell: IShell, workspace: IWorkspace, locale?: string): IStringDictionary<string> {
D
Daniel Imms 已提交
342
		let env = TerminalInstance._cloneEnv(parentEnv);
343 344
		env['PTYPID'] = process.pid.toString();
		env['PTYSHELL'] = shell.executable;
D
Daniel Imms 已提交
345 346 347 348 349
		if (shell.args) {
			shell.args.forEach((arg, i) => {
				env[`PTYSHELLARG${i}`] = arg;
			});
		}
D
Daniel Imms 已提交
350
		env['PTYCWD'] = TerminalInstance._sanitizeCwd(workspace ? workspace.resource.fsPath : os.homedir());
351
		if (locale) {
D
Daniel Imms 已提交
352
			env['LANG'] = TerminalInstance._getLangEnvVariable(locale);
353 354
		}
		return env;
355 356
	}

D
Daniel Imms 已提交
357
	private static _sanitizeCwd(cwd: string) {
358 359 360
		// Make the drive letter uppercase on Windows (see #9448)
		if (platform.platform === platform.Platform.Windows && cwd && cwd[1] === ':') {
			return cwd[0].toUpperCase() + cwd.substr(1);
D
Daniel Imms 已提交
361
		}
362
		return cwd;
D
Daniel Imms 已提交
363 364
	}

D
Daniel Imms 已提交
365
	private static _cloneEnv(env: IStringDictionary<string>): IStringDictionary<string> {
366 367 368
		let newEnv: IStringDictionary<string> = Object.create(null);
		Object.keys(env).forEach((key) => {
			newEnv[key] = env[key];
369
		});
370
		return newEnv;
371 372
	}

D
Daniel Imms 已提交
373
	private static _getLangEnvVariable(locale: string) {
374 375 376 377
		const parts = locale.split('-');
		const n = parts.length;
		if (n > 1) {
			parts[n - 1] = parts[n - 1].toUpperCase();
D
Daniel Imms 已提交
378
		}
379
		return parts.join('_') + '.UTF-8';
D
Daniel Imms 已提交
380
	}
D
Daniel Imms 已提交
381 382

	public setCursorBlink(blink: boolean): void {
D
Daniel Imms 已提交
383
		if (this._xterm && this._xterm.getOption('cursorBlink') !== blink) {
D
Daniel Imms 已提交
384
			this._xterm.setOption('cursorBlink', blink);
D
Daniel Imms 已提交
385
			this._xterm.refresh(0, this._xterm.rows - 1);
D
Daniel Imms 已提交
386 387 388 389
		}
	}

	public setCommandsToSkipShell(commands: string[]): void {
D
Daniel Imms 已提交
390
		this._skipTerminalCommands = commands;
D
Daniel Imms 已提交
391 392
	}

D
Daniel Imms 已提交
393 394 395 396 397 398
	public setScrollback(lineCount: number): void {
		if (this._xterm && this._xterm.getOption('scrollback') !== lineCount) {
			this._xterm.setOption('scrollback', lineCount);
		}
	}

399
	public layout(dimension: { width: number, height: number }): void {
D
Daniel Imms 已提交
400
		let font = this._configHelper.getFont();
401
		if (!font || !font.charWidth || !font.charHeight) {
D
Daniel Imms 已提交
402 403 404 405
			return;
		}
		if (!dimension.height) { // Minimized
			return;
406 407 408 409 410 411
		} else {
			// Trigger scroll event manually so that the viewport's scroll area is synced. This
			// needs to happen otherwise its scrollTop value is invalid when the panel is toggled as
			// it gets removed and then added back to the DOM (resetting scrollTop to 0).
			// Upstream issue: https://github.com/sourcelair/xterm.js/issues/291
			this._xterm.emit('scroll', this._xterm.ydisp);
D
Daniel Imms 已提交
412 413 414
		}
		let leftPadding = parseInt(getComputedStyle(document.querySelector('.terminal-outer-container')).paddingLeft.split('px')[0], 10);
		let innerWidth = dimension.width - leftPadding;
415 416
		let cols = Math.floor(innerWidth / font.charWidth);
		let rows = Math.floor(dimension.height / font.charHeight);
D
Daniel Imms 已提交
417 418 419
		if (this._xterm) {
			this._xterm.resize(cols, rows);
			this._xterm.element.style.width = innerWidth + 'px';
D
Daniel Imms 已提交
420
		}
D
Daniel Imms 已提交
421 422
		if (this._process.connected) {
			this._process.send({
D
Daniel Imms 已提交
423 424 425 426 427 428
				event: 'resize',
				cols: cols,
				rows: rows
			});
		}
	}
429
}