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

6
import * as path from 'path';
7
import DOM = require('vs/base/browser/dom');
J
Johannes Rieken 已提交
8
import Event, { Emitter } from 'vs/base/common/event';
9 10
import URI from 'vs/base/common/uri';
import cp = require('child_process');
11
import lifecycle = require('vs/base/common/lifecycle');
C
Christof Marti 已提交
12
import nls = require('vs/nls');
C
Christof Marti 已提交
13
import os = require('os');
14
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
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IMessageService, Severity } from 'vs/platform/message/common/message';
20
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
21
import { IStringDictionary } from 'vs/base/common/collections';
22
import { ITerminalInstance, KEYBINDING_CONTEXT_TERMINAL_TEXT_SELECTED, TERMINAL_PANEL_ID, IShellLaunchConfig } from 'vs/workbench/parts/terminal/common/terminal';
23
import { ITerminalProcessFactory } from 'vs/workbench/parts/terminal/electron-browser/terminal';
24
import { IWorkspace, IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
25
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
26
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
27 28
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { TabFocus } from 'vs/editor/common/config/commonEditorConfig';
29
import { TerminalConfigHelper } from 'vs/workbench/parts/terminal/electron-browser/terminalConfigHelper';
30
import { TerminalLinkHandler } from 'vs/workbench/parts/terminal/electron-browser/terminalLinkHandler';
31
import { TerminalWidgetManager } from 'vs/workbench/parts/terminal/browser/terminalWidgetManager';
32

D
Daniel Imms 已提交
33 34 35
/** The amount of time to consider terminal errors to be related to the launch */
const LAUNCHING_DURATION = 500;

36 37 38 39 40 41 42 43 44
class StandardTerminalProcessFactory implements ITerminalProcessFactory {
	public create(env: { [key: string]: string }): cp.ChildProcess {
		return cp.fork('./terminalProcess', [], {
			env,
			cwd: URI.parse(path.dirname(require.toUrl('./terminalProcess'))).fsPath
		});
	}
}

45
export class TerminalInstance implements ITerminalInstance {
46
	private static readonly WINDOWS_EOL_REGEX = /\r?\n/g;
C
Christof Marti 已提交
47

48
	private static _terminalProcessFactory: ITerminalProcessFactory = new StandardTerminalProcessFactory();
49
	private static _lastKnownDimensions: Dimension = null;
D
Daniel Imms 已提交
50 51
	private static _idCounter = 1;

52
	private _id: number;
D
Daniel Imms 已提交
53
	private _isExiting: boolean;
K
Kai Wood 已提交
54
	private _hadFocusOnExit: boolean;
55
	private _isLaunching: boolean;
D
Daniel Imms 已提交
56
	private _isVisible: boolean;
57
	private _isDisposed: boolean;
58
	private _onDisposed: Emitter<ITerminalInstance>;
D
Daniel Imms 已提交
59
	private _onDataForApi: Emitter<{ instance: ITerminalInstance, data: string }>;
60
	private _onProcessIdReady: Emitter<TerminalInstance>;
D
Daniel Imms 已提交
61
	private _onTitleChanged: Emitter<string>;
D
Daniel Imms 已提交
62
	private _process: cp.ChildProcess;
63
	private _processId: number;
D
Daniel Imms 已提交
64
	private _skipTerminalCommands: string[];
D
Daniel Imms 已提交
65
	private _title: string;
66 67
	private _instanceDisposables: lifecycle.IDisposable[];
	private _processDisposables: lifecycle.IDisposable[];
D
Daniel Imms 已提交
68 69 70
	private _wrapperElement: HTMLDivElement;
	private _xterm: any;
	private _xtermElement: HTMLDivElement;
71
	private _terminalHasTextContextKey: IContextKey<boolean>;
72 73
	private _cols: number;
	private _rows: number;
D
Daniel Imms 已提交
74

75 76 77
	private _widgetManager: TerminalWidgetManager;
	private _linkHandler: TerminalLinkHandler;

78
	public get id(): number { return this._id; }
79
	public get processId(): number { return this._processId; }
80
	public get onDisposed(): Event<ITerminalInstance> { return this._onDisposed.event; }
D
Daniel Imms 已提交
81
	public get onDataForApi(): Event<{ instance: ITerminalInstance, data: string }> { return this._onDataForApi.event; }
82
	public get onProcessIdReady(): Event<TerminalInstance> { return this._onProcessIdReady.event; }
D
Daniel Imms 已提交
83
	public get onTitleChanged(): Event<string> { return this._onTitleChanged.event; }
D
Daniel Imms 已提交
84
	public get title(): string { return this._title; }
K
Kai Wood 已提交
85
	public get hadFocusOnExit(): boolean { return this._hadFocusOnExit; }
86 87

	public constructor(
D
Daniel Imms 已提交
88 89 90
		private _terminalFocusContextKey: IContextKey<boolean>,
		private _configHelper: TerminalConfigHelper,
		private _container: HTMLElement,
91
		private _shellLaunchConfig: IShellLaunchConfig,
92
		@IContextKeyService private _contextKeyService: IContextKeyService,
D
Daniel Imms 已提交
93
		@IKeybindingService private _keybindingService: IKeybindingService,
94
		@IMessageService private _messageService: IMessageService,
95
		@IPanelService private _panelService: IPanelService,
96
		@IWorkspaceContextService private _contextService: IWorkspaceContextService,
97 98
		@IWorkbenchEditorService private _editorService: IWorkbenchEditorService,
		@IInstantiationService private _instantiationService: IInstantiationService
99
	) {
100 101
		this._instanceDisposables = [];
		this._processDisposables = [];
D
Daniel Imms 已提交
102
		this._skipTerminalCommands = [];
D
Daniel Imms 已提交
103
		this._isExiting = false;
K
Kai Wood 已提交
104
		this._hadFocusOnExit = false;
105
		this._isLaunching = true;
D
Daniel Imms 已提交
106
		this._isVisible = false;
107
		this._isDisposed = false;
D
Daniel Imms 已提交
108
		this._id = TerminalInstance._idCounter++;
109
		this._terminalHasTextContextKey = KEYBINDING_CONTEXT_TERMINAL_TEXT_SELECTED.bindTo(this._contextKeyService);
D
Daniel Imms 已提交
110

111
		this._onDisposed = new Emitter<TerminalInstance>();
D
Daniel Imms 已提交
112
		this._onDataForApi = new Emitter<{ instance: ITerminalInstance, data: string }>();
113 114
		this._onProcessIdReady = new Emitter<TerminalInstance>();
		this._onTitleChanged = new Emitter<string>();
115

116
		this._initDimensions();
D
Daniel Imms 已提交
117
		this._createProcess(this._contextService.getWorkspace(), this._shellLaunchConfig);
118
		this._createXterm();
D
Daniel Imms 已提交
119

120
		// Only attach xterm.js to the DOM if the terminal panel has been opened before.
D
Daniel Imms 已提交
121 122
		if (_container) {
			this.attachToElement(_container);
123 124 125
		}
	}

D
Daniel Imms 已提交
126
	public addDisposable(disposable: lifecycle.IDisposable): void {
127
		this._instanceDisposables.push(disposable);
D
Daniel Imms 已提交
128 129
	}

130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
	private _initDimensions(): void {
		// The terminal panel needs to have been created
		if (!this._container) {
			return;
		}

		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._evaluateColsAndRows(width, height);
	}

	/**
	 * Evaluates and sets the cols and rows of the terminal if possible.
	 * @param width The width of the container.
	 * @param height The height of the container.
D
Daniel Imms 已提交
146
	 * @return The terminal's width if it requires a layout.
147
	 */
D
Daniel Imms 已提交
148
	private _evaluateColsAndRows(width: number, height: number): number {
149 150 151 152 153 154 155 156 157 158 159
		const dimension = this._getDimension(width, height);
		if (!dimension) {
			return null;
		}
		const font = this._configHelper.getFont();
		this._cols = Math.floor(dimension.width / font.charWidth);
		this._rows = Math.floor(dimension.height / font.charHeight);
		return dimension.width;
	}

	private _getDimension(width: number, height: number): Dimension {
160 161 162
		// The font needs to have been initialized
		const font = this._configHelper.getFont();
		if (!font || !font.charWidth || !font.charHeight) {
D
Daniel Imms 已提交
163
			return null;
164 165 166 167
		}

		// The panel is minimized
		if (!height) {
168
			return TerminalInstance._lastKnownDimensions;
169 170 171 172 173 174 175 176 177 178 179 180 181 182
		} 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
			if (this._xterm) {
				this._xterm.emit('scroll', this._xterm.ydisp);
			}
		}

		const padding = parseInt(getComputedStyle(document.querySelector('.terminal-outer-container')).paddingLeft.split('px')[0], 10);
		// Use left padding as right padding, right padding is not defined in CSS just in case
		// xterm.js causes an unexpected overflow.
		const innerWidth = width - padding * 2;
183 184
		TerminalInstance._lastKnownDimensions = new Dimension(innerWidth, height);
		return TerminalInstance._lastKnownDimensions;
185 186
	}

187 188 189 190
	/**
	 * Create xterm.js instance and attach data listeners.
	 */
	protected _createXterm(): void {
191
		this._xterm = xterm({
192
			scrollback: this._configHelper.config.scrollback
193
		});
194 195 196
		if (this._shellLaunchConfig.initialText) {
			this._xterm.writeln(this._shellLaunchConfig.initialText);
		}
197
		this._process.on('message', (message) => this._sendPtyDataToXterm(message));
D
Daniel Imms 已提交
198
		this._xterm.on('data', (data) => {
199 200 201 202 203 204
			if (this._process) {
				this._process.send({
					event: 'input',
					data: this._sanitizeInput(data)
				});
			}
D
Daniel Imms 已提交
205 206
			return false;
		});
207 208
		this._linkHandler = this._instantiationService.createInstance(TerminalLinkHandler, this._xterm, platform.platform);
		this._linkHandler.registerLocalLinkHandler();
209 210 211 212 213 214 215 216 217 218 219 220 221
	}

	public attachToElement(container: HTMLElement): void {
		if (this._wrapperElement) {
			throw new Error('The terminal instance has already been attached to a container');
		}

		this._container = container;
		this._wrapperElement = document.createElement('div');
		DOM.addClass(this._wrapperElement, 'terminal-wrapper');
		this._xtermElement = document.createElement('div');

		this._xterm.open(this._xtermElement);
D
Daniel Imms 已提交
222
		this._xterm.attachCustomKeydownHandler((event: KeyboardEvent) => {
223 224 225 226 227
			// Disable all input if the terminal is exiting
			if (this._isExiting) {
				return false;
			}

228 229
			// Skip processing by xterm.js of keyboard events that resolve to commands described
			// within commandsToSkipShell
D
Daniel Imms 已提交
230
			const standardKeyboardEvent = new StandardKeyboardEvent(event);
231
			const resolveResult = this._keybindingService.softDispatch(standardKeyboardEvent, standardKeyboardEvent.target);
D
Daniel Imms 已提交
232
			if (resolveResult && this._skipTerminalCommands.some(k => k === resolveResult.commandId)) {
D
Daniel Imms 已提交
233 234 235 236 237 238 239 240
				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;
			}
241
			return undefined;
D
Daniel Imms 已提交
242
		});
243
		this._instanceDisposables.push(DOM.addDisposableListener(this._xterm.element, 'mouseup', (event: KeyboardEvent) => {
244 245 246
			// Wait until mouseup has propogated through the DOM before evaluating the new selection
			// state.
			setTimeout(() => {
247 248
				this._refreshSelectionContextKey();
			}, 0);
249
		}));
250 251

		// xterm.js currently drops selection on keyup as we need to handle this case.
252
		this._instanceDisposables.push(DOM.addDisposableListener(this._xterm.element, 'keyup', (event: KeyboardEvent) => {
253 254 255 256
			// Wait until keyup has propogated through the DOM before evaluating the new selection
			// state.
			setTimeout(() => {
				this._refreshSelectionContextKey();
257
			}, 0);
258
		}));
D
Daniel Imms 已提交
259

D
Daniel Imms 已提交
260 261
		const xtermHelper: HTMLElement = this._xterm.element.querySelector('.xterm-helpers');
		const focusTrap: HTMLElement = document.createElement('div');
262 263
		focusTrap.setAttribute('tabindex', '0');
		DOM.addClass(focusTrap, 'focus-trap');
264
		this._instanceDisposables.push(DOM.addDisposableListener(focusTrap, 'focus', (event: FocusEvent) => {
265 266 267 268
			let currentElement = focusTrap;
			while (!DOM.hasClass(currentElement, 'part')) {
				currentElement = currentElement.parentElement;
			}
D
Daniel Imms 已提交
269
			const hidePanelElement = <HTMLElement>currentElement.querySelector('.hide-panel-action');
270
			hidePanelElement.focus();
271
		}));
D
Daniel Imms 已提交
272
		xtermHelper.insertBefore(focusTrap, this._xterm.textarea);
273

274
		this._instanceDisposables.push(DOM.addDisposableListener(this._xterm.textarea, 'focus', (event: KeyboardEvent) => {
D
Daniel Imms 已提交
275
			this._terminalFocusContextKey.set(true);
276
		}));
277
		this._instanceDisposables.push(DOM.addDisposableListener(this._xterm.textarea, 'blur', (event: KeyboardEvent) => {
D
Daniel Imms 已提交
278
			this._terminalFocusContextKey.reset();
279
			this._refreshSelectionContextKey();
280
		}));
281
		this._instanceDisposables.push(DOM.addDisposableListener(this._xterm.element, 'focus', (event: KeyboardEvent) => {
D
Daniel Imms 已提交
282
			this._terminalFocusContextKey.set(true);
283
		}));
284
		this._instanceDisposables.push(DOM.addDisposableListener(this._xterm.element, 'blur', (event: KeyboardEvent) => {
D
Daniel Imms 已提交
285
			this._terminalFocusContextKey.reset();
286
			this._refreshSelectionContextKey();
287 288
		}));

D
Daniel Imms 已提交
289
		this._wrapperElement.appendChild(this._xtermElement);
290
		this._widgetManager = new TerminalWidgetManager(this._configHelper, this._wrapperElement);
291
		this._linkHandler.setWidgetManager(this._widgetManager);
D
Daniel Imms 已提交
292
		this._container.appendChild(this._wrapperElement);
293

294 295 296 297
		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 已提交
298
		this.setVisible(this._isVisible);
299
		this.updateConfig();
300 301
	}

D
Daniel Imms 已提交
302
	public registerLinkMatcher(regex: RegExp, handler: (url: string) => void, matchIndex?: number, validationCallback?: (uri: string, element: HTMLElement, callback: (isValid: boolean) => void) => void): number {
303
		return this._linkHandler.registerCustomLinkHandler(regex, handler, matchIndex, validationCallback);
304 305 306 307 308 309
	}

	public deregisterLinkMatcher(linkMatcherId: number): void {
		this._xterm.deregisterLinkMatcher(linkMatcherId);
	}

310 311 312 313
	public hasSelection(): boolean {
		return !document.getSelection().isCollapsed;
	}

D
Daniel Imms 已提交
314
	public copySelection(): void {
D
Daniel Imms 已提交
315 316 317
		if (document.activeElement.classList.contains('xterm')) {
			document.execCommand('copy');
		} else {
D
Daniel Imms 已提交
318
			this._messageService.show(Severity.Warning, nls.localize('terminal.integrated.copySelection.noSelection', 'Cannot copy terminal selection when terminal does not have focus'));
D
Daniel Imms 已提交
319
		}
D
Daniel Imms 已提交
320 321
	}

322
	public clearSelection(): void {
323
		window.getSelection().empty();
324 325
	}

D
Daniel Imms 已提交
326
	public dispose(): void {
327 328 329
		if (this._linkHandler) {
			this._linkHandler.dispose();
		}
K
Kai Wood 已提交
330 331 332
		if (this._xterm && this._xterm.element) {
			this._hadFocusOnExit = DOM.hasClass(this._xterm.element, 'focus');
		}
D
Daniel Imms 已提交
333 334 335
		if (this._wrapperElement) {
			this._container.removeChild(this._wrapperElement);
			this._wrapperElement = null;
D
Daniel Imms 已提交
336
		}
D
Daniel Imms 已提交
337 338 339
		if (this._xterm) {
			this._xterm.destroy();
			this._xterm = null;
D
Daniel Imms 已提交
340
		}
D
Daniel Imms 已提交
341 342 343
		if (this._process) {
			if (this._process.connected) {
				this._process.kill();
D
Daniel Imms 已提交
344
			}
D
Daniel Imms 已提交
345
			this._process = null;
D
Daniel Imms 已提交
346
		}
347 348 349 350
		if (!this._isDisposed) {
			this._isDisposed = true;
			this._onDisposed.fire(this);
		}
351 352
		this._processDisposables = lifecycle.dispose(this._processDisposables);
		this._instanceDisposables = lifecycle.dispose(this._instanceDisposables);
D
Daniel Imms 已提交
353 354
	}

D
Daniel Imms 已提交
355
	public focus(force?: boolean): void {
D
Daniel Imms 已提交
356
		if (!this._xterm) {
D
Daniel Imms 已提交
357 358
			return;
		}
D
Daniel Imms 已提交
359
		const text = window.getSelection().toString();
D
Daniel Imms 已提交
360
		if (!text || force) {
D
Daniel Imms 已提交
361
			this._xterm.focus();
D
Daniel Imms 已提交
362
		}
D
Daniel Imms 已提交
363 364 365
	}

	public paste(): void {
D
Daniel Imms 已提交
366 367
		this.focus();
		document.execCommand('paste');
D
Daniel Imms 已提交
368 369 370
	}

	public sendText(text: string, addNewLine: boolean): void {
371 372 373
		text = this._sanitizeInput(text);
		if (addNewLine && text.substr(text.length - 1) !== '\r') {
			text += '\r';
D
Daniel Imms 已提交
374
		}
D
Daniel Imms 已提交
375
		this._process.send({
D
Daniel Imms 已提交
376 377 378
			event: 'input',
			data: text
		});
D
Daniel Imms 已提交
379
	}
380 381

	public setVisible(visible: boolean): void {
D
Daniel Imms 已提交
382 383 384
		this._isVisible = visible;
		if (this._wrapperElement) {
			DOM.toggleClass(this._wrapperElement, 'active', visible);
385
		}
D
Daniel Imms 已提交
386
		if (visible && this._xterm) {
387 388 389 390 391 392
			// Trigger a manual scroll event which will sync the viewport and scroll bar. This is
			// necessary if the number of rows in the terminal has decreased while it was in the
			// background since scrollTop changes take no effect but the terminal's position does
			// change since the number of visible rows decreases.
			this._xterm.emit('scroll', this._xterm.ydisp);
		}
393 394
	}

395
	public scrollDownLine(): void {
D
Daniel Imms 已提交
396
		this._xterm.scrollDisp(1);
D
Daniel Imms 已提交
397 398
	}

399
	public scrollDownPage(): void {
400
		this._xterm.scrollPages(1);
401 402
	}

403 404 405 406
	public scrollToBottom(): void {
		this._xterm.scrollToBottom();
	}

407
	public scrollUpLine(): void {
D
Daniel Imms 已提交
408
		this._xterm.scrollDisp(-1);
D
Daniel Imms 已提交
409
	}
410

411
	public scrollUpPage(): void {
412
		this._xterm.scrollPages(-1);
413 414
	}

415 416 417 418
	public scrollToTop(): void {
		this._xterm.scrollToTop();
	}

D
Daniel Imms 已提交
419 420 421 422
	public clear(): void {
		this._xterm.clear();
	}

423
	private _refreshSelectionContextKey() {
424 425 426
		const activePanel = this._panelService.getActivePanel();
		const isFocused = activePanel && activePanel.getId() === TERMINAL_PANEL_ID;
		this._terminalHasTextContextKey.set(isFocused && !window.getSelection().isCollapsed);
427 428
	}

D
Daniel Imms 已提交
429
	private _sanitizeInput(data: any) {
430
		return typeof data === 'string' ? data.replace(TerminalInstance.WINDOWS_EOL_REGEX, '\r') : data;
C
Christof Marti 已提交
431 432
	}

433 434 435 436 437
	protected _getCwd(shell: IShellLaunchConfig, workspace: IWorkspace): string {
		if (shell.cwd) {
			return shell.cwd;
		}

B
Benjamin Pasero 已提交
438
		let cwd: string;
D
Daniel Imms 已提交
439 440

		// TODO: Handle non-existent customCwd
441
		if (!shell.ignoreConfigurationCwd) {
442
			// Evaluate custom cwd first
443
			const customCwd = this._configHelper.config.cwd;
444 445 446 447 448 449
			if (customCwd) {
				if (path.isAbsolute(customCwd)) {
					cwd = customCwd;
				} else if (workspace) {
					cwd = path.normalize(path.join(workspace.resource.fsPath, customCwd));
				}
D
Daniel Imms 已提交
450 451 452 453 454
			}
		}

		// If there was no custom cwd or it was relative with no workspace
		if (!cwd) {
455
			cwd = workspace ? workspace.resource.fsPath : os.homedir();
D
Daniel Imms 已提交
456 457 458 459 460
		}

		return TerminalInstance._sanitizeCwd(cwd);
	}

461
	protected _createProcess(workspace: IWorkspace, shell: IShellLaunchConfig): void {
462
		const locale = this._configHelper.config.setLocaleVariables ? platform.locale : undefined;
D
Daniel Imms 已提交
463
		if (!shell.executable) {
464
			this._configHelper.mergeDefaultShellPathAndArgs(shell);
P
Pine Wu 已提交
465
		}
466
		const env = TerminalInstance.createTerminalEnv(process.env, shell, this._getCwd(shell, workspace), locale, this._cols, this._rows);
D
Daniel Imms 已提交
467
		this._title = shell.name || '';
D
Daniel Imms 已提交
468
		this._process = cp.fork('./terminalProcess', [], {
469 470 471
			env: env,
			cwd: URI.parse(path.dirname(require.toUrl('./terminalProcess'))).fsPath
		});
D
Daniel Imms 已提交
472
		if (!shell.name) {
473
			// Only listen for process title changes when a name is not provided
D
Daniel Imms 已提交
474
			this._process.on('message', (message) => {
475
				if (message.type === 'title') {
D
Daniel Imms 已提交
476
					this._title = message.content ? message.content : '';
477
					this._onTitleChanged.fire(this._title);
478
				}
479 480
			});
		}
481 482 483 484 485 486
		this._process.on('message', (message) => {
			if (message.type === 'pid') {
				this._processId = message.content;
				this._onProcessIdReady.fire(this);
			}
		});
487 488 489 490 491 492
		this._process.on('exit', exitCode => this._onPtyProcessExit(exitCode));
		setTimeout(() => {
			this._isLaunching = false;
		}, LAUNCHING_DURATION);
	}

493 494
	private _sendPtyDataToXterm(message: { type: string, content: string }): void {
		if (message.type === 'data') {
D
Daniel Imms 已提交
495 496 497
			if (this._widgetManager) {
				this._widgetManager.closeMessage();
			}
D
Daniel Imms 已提交
498 499 500
			if (this._xterm) {
				this._xterm.write(message.content);
			}
501 502 503
		}
	}

504 505 506 507 508 509 510 511
	private _onPtyProcessExit(exitCode: number): void {
		// Prevent dispose functions being triggered multiple times
		if (this._isExiting) {
			return;
		}

		this._isExiting = true;
		let exitCodeMessage: string;
512
		if (exitCode) {
513 514 515
			exitCodeMessage = nls.localize('terminal.integrated.exitedWithCode', 'The terminal process terminated with exit code: {0}', exitCode);
		}

516 517 518 519 520
		// Only trigger wait on exit when the exit was triggered by the process, not through the
		// `workbench.action.terminal.kill` command
		const triggeredByProcess = exitCode !== null;

		if (triggeredByProcess && this._shellLaunchConfig.waitOnExit) {
521
			if (exitCode) {
522 523 524 525 526
				this._xterm.writeln(exitCodeMessage);
			}
			this._xterm.writeln(nls.localize('terminal.integrated.waitOnExit', 'Press any key to close the terminal'));
			// Disable all input if the terminal is exiting and listen for next keypress
			this._xterm.setOption('disableStdin', true);
527 528 529 530 531 532
			if (this._xterm.textarea) {
				this._processDisposables.push(DOM.addDisposableListener(this._xterm.textarea, 'keypress', (event: KeyboardEvent) => {
					this.dispose();
					event.preventDefault();
				}));
			}
533 534
		} else {
			this.dispose();
535
			if (exitCode) {
536 537
				if (this._isLaunching) {
					let args = '';
538 539 540
					if (typeof this._shellLaunchConfig.args === 'string') {
						args = this._shellLaunchConfig.args;
					} else if (this._shellLaunchConfig.args && this._shellLaunchConfig.args.length) {
541 542 543 544 545 546
						args = ' ' + this._shellLaunchConfig.args.map(a => {
							if (a.indexOf(' ') !== -1) {
								return `'${a}'`;
							}
							return a;
						}).join(' ');
547
					}
548 549 550
					this._messageService.show(Severity.Error, nls.localize('terminal.integrated.launchFailed', 'The terminal process command `{0}{1}` failed to launch (exit code: {2})', this._shellLaunchConfig.executable, args, exitCode));
				} else {
					this._messageService.show(Severity.Error, exitCodeMessage);
551 552
				}
			}
553
		}
554 555
	}

556 557
	public reuseTerminal(shell?: IShellLaunchConfig): void {
		// Kill and clean up old process
558 559 560 561 562 563 564
		if (this._process) {
			this._process.removeAllListeners('exit');
			if (this._process.connected) {
				this._process.kill();
			}
			this._process = null;
		}
565 566 567
		lifecycle.dispose(this._processDisposables);
		this._processDisposables = [];

568 569
		// Ensure new processes' output starts at start of new line
		this._xterm.write('\n\x1b[G');
570

571 572 573 574 575
		// Print initialText if specified
		if (shell.initialText) {
			this._xterm.writeln(shell.initialText);
		}

576
		// Initialize new process
577
		const oldTitle = this._title;
D
Daniel Imms 已提交
578
		this._createProcess(this._contextService.getWorkspace(), shell);
579 580 581
		if (oldTitle !== this._title) {
			this._onTitleChanged.fire(this._title);
		}
582
		this._process.on('message', (message) => this._sendPtyDataToXterm(message));
583 584

		// Clean up waitOnExit state
585 586
		if (this._isExiting && this._shellLaunchConfig.waitOnExit) {
			this._xterm.setOption('disableStdin', false);
587
			this._isExiting = false;
588
		}
589

590 591 592 593
		// Set the new shell launch config
		this._shellLaunchConfig = shell;
	}

594 595
	// TODO: This should be private/protected
	// TODO: locale should not be optional
596
	public static createTerminalEnv(parentEnv: IStringDictionary<string>, shell: IShellLaunchConfig, cwd: string, locale?: string, cols?: number, rows?: number): IStringDictionary<string> {
597
		const env = shell.env ? shell.env : TerminalInstance._cloneEnv(parentEnv);
598 599
		env['PTYPID'] = process.pid.toString();
		env['PTYSHELL'] = shell.executable;
D
Daniel Imms 已提交
600
		if (shell.args) {
601 602 603 604 605
			if (typeof shell.args === 'string') {
				env[`PTYSHELLCMDLINE`] = shell.args;
			} else {
				shell.args.forEach((arg, i) => env[`PTYSHELLARG${i}`] = arg);
			}
D
Daniel Imms 已提交
606
		}
D
Daniel Imms 已提交
607
		env['PTYCWD'] = cwd;
608
		env['LANG'] = TerminalInstance._getLangEnvVariable(locale);
609 610 611 612
		if (cols && rows) {
			env['PTYCOLS'] = cols.toString();
			env['PTYROWS'] = rows.toString();
		}
613
		return env;
614 615
	}

D
Dirk Baeumer 已提交
616 617
	public onData(listener: (data: string) => void): lifecycle.IDisposable {
		let callback = (message) => {
618 619 620
			if (message.type === 'data') {
				listener(message.content);
			}
D
Dirk Baeumer 已提交
621 622 623 624
		};
		this._process.on('message', callback);
		return {
			dispose: () => {
625 626 627
				if (this._process) {
					this._process.removeListener('message', callback);
				}
D
Dirk Baeumer 已提交
628 629
			}
		};
630 631
	}

D
Dirk Baeumer 已提交
632
	public onExit(listener: (exitCode: number) => void): lifecycle.IDisposable {
633
		this._process.on('exit', listener);
D
Dirk Baeumer 已提交
634 635
		return {
			dispose: () => {
636 637 638
				if (this._process) {
					this._process.removeListener('exit', listener);
				}
D
Dirk Baeumer 已提交
639 640
			}
		};
641 642
	}

D
Daniel Imms 已提交
643
	private static _sanitizeCwd(cwd: string) {
644 645 646
		// 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 已提交
647
		}
648
		return cwd;
D
Daniel Imms 已提交
649 650
	}

D
Daniel Imms 已提交
651
	private static _cloneEnv(env: IStringDictionary<string>): IStringDictionary<string> {
D
Daniel Imms 已提交
652
		const newEnv: IStringDictionary<string> = Object.create(null);
653 654
		Object.keys(env).forEach((key) => {
			newEnv[key] = env[key];
655
		});
656
		return newEnv;
657 658
	}

659 660
	private static _getLangEnvVariable(locale?: string) {
		const parts = locale ? locale.split('-') : [];
661
		const n = parts.length;
662
		if (n === 0) {
D
Daniel Imms 已提交
663 664
			// Fallback to en_US to prevent possible encoding issues.
			return 'en_US.UTF-8';
665 666 667 668 669 670 671 672 673 674 675 676 677
		}
		if (n === 1) {
			// app.getLocale can return just a language without a variant, fill in the variant for
			// supported languages as many shells expect a 2-part locale.
			const languageVariants = {
				de: 'DE',
				en: 'US',
				es: 'ES',
				fr: 'FR',
				it: 'IT',
				ja: 'JP',
				ko: 'KR',
				ru: 'RU',
678
				zh: 'CN'
679
			};
D
Daniel Imms 已提交
680 681
			if (parts[0] in languageVariants) {
				parts.push(languageVariants[parts[0]]);
682 683 684 685
			}
		} else {
			// Ensure the variant is uppercase
			parts[1] = parts[1].toUpperCase();
D
Daniel Imms 已提交
686
		}
687
		return parts.join('_') + '.UTF-8';
D
Daniel Imms 已提交
688
	}
D
Daniel Imms 已提交
689

690
	public updateConfig(): void {
691 692 693 694
		this._setCursorBlink(this._configHelper.config.cursorBlinking);
		this._setCursorStyle(this._configHelper.config.cursorStyle);
		this._setCommandsToSkipShell(this._configHelper.config.commandsToSkipShell);
		this._setScrollback(this._configHelper.config.scrollback);
695 696 697
	}

	private _setCursorBlink(blink: boolean): void {
D
Daniel Imms 已提交
698
		if (this._xterm && this._xterm.getOption('cursorBlink') !== blink) {
D
Daniel Imms 已提交
699
			this._xterm.setOption('cursorBlink', blink);
D
Daniel Imms 已提交
700
			this._xterm.refresh(0, this._xterm.rows - 1);
D
Daniel Imms 已提交
701 702 703
		}
	}

704 705 706 707 708 709 710 711
	private _setCursorStyle(style: string): void {
		if (this._xterm && this._xterm.getOption('cursorStyle') !== style) {
			// 'line' is used instead of bar in VS Code to be consistent with editor.cursorStyle
			const xtermOption = style === 'line' ? 'bar' : style;
			this._xterm.setOption('cursorStyle', xtermOption);
		}
	}

712
	private _setCommandsToSkipShell(commands: string[]): void {
D
Daniel Imms 已提交
713
		this._skipTerminalCommands = commands;
D
Daniel Imms 已提交
714 715
	}

716
	private _setScrollback(lineCount: number): void {
D
Daniel Imms 已提交
717 718 719 720 721
		if (this._xterm && this._xterm.getOption('scrollback') !== lineCount) {
			this._xterm.setOption('scrollback', lineCount);
		}
	}

722
	public layout(dimension: Dimension): void {
D
Daniel Imms 已提交
723 724
		const terminalWidth = this._evaluateColsAndRows(dimension.width, dimension.height);
		if (!terminalWidth) {
D
Daniel Imms 已提交
725 726
			return;
		}
D
Daniel Imms 已提交
727
		if (this._xterm) {
728
			this._xterm.resize(this._cols, this._rows);
D
Daniel Imms 已提交
729
			this._xterm.element.style.width = terminalWidth + 'px';
D
Daniel Imms 已提交
730
		}
D
Daniel Imms 已提交
731 732
		if (this._process.connected) {
			this._process.send({
D
Daniel Imms 已提交
733
				event: 'resize',
734 735
				cols: this._cols,
				rows: this._rows
D
Daniel Imms 已提交
736 737 738
			});
		}
	}
739

D
Daniel Imms 已提交
740 741 742 743 744
	public enableApiOnData(): void {
		// Only send data through IPC if the API explicitly requests it.
		this.onData(data => this._onDataForApi.fire({ instance: this, data }));
	}

745 746 747
	public static setTerminalProcessFactory(factory: ITerminalProcessFactory): void {
		this._terminalProcessFactory = factory;
	}
748
}