terminalInstance.ts 27.8 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.
 *--------------------------------------------------------------------------------------------*/

D
Daniel Imms 已提交
6 7
import * as cp from 'child_process';
import * as os from 'os';
8
import * as path from 'path';
D
Daniel Imms 已提交
9 10 11 12
import * as lifecycle from 'vs/base/common/lifecycle';
import * as nls from 'vs/nls';
import * as platform from 'vs/base/common/platform';
import * as dom from 'vs/base/browser/dom';
J
Johannes Rieken 已提交
13
import Event, { Emitter } from 'vs/base/common/event';
D
Daniel Imms 已提交
14
import Uri from 'vs/base/common/uri';
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 33
import { registerThemingParticipant, ITheme, ICssStyleCollector } from 'vs/platform/theme/common/themeService';
import { scrollbarSliderBackground, scrollbarSliderHoverBackground, scrollbarSliderActiveBackground } from 'vs/platform/theme/common/colorRegistry';
34

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

38 39 40 41
class StandardTerminalProcessFactory implements ITerminalProcessFactory {
	public create(env: { [key: string]: string }): cp.ChildProcess {
		return cp.fork('./terminalProcess', [], {
			env,
D
Daniel Imms 已提交
42
			cwd: Uri.parse(path.dirname(require.toUrl('./terminalProcess'))).fsPath
43 44 45 46
		});
	}
}

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

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

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

77 78 79
	private _widgetManager: TerminalWidgetManager;
	private _linkHandler: TerminalLinkHandler;

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

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

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

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

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

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

132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
	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 已提交
148
	 * @return The terminal's width if it requires a layout.
149
	 */
D
Daniel Imms 已提交
150
	private _evaluateColsAndRows(width: number, height: number): number {
151 152 153 154 155 156 157 158 159 160 161
		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 {
162 163 164
		// The font needs to have been initialized
		const font = this._configHelper.getFont();
		if (!font || !font.charWidth || !font.charHeight) {
D
Daniel Imms 已提交
165
			return null;
166 167 168 169
		}

		// The panel is minimized
		if (!height) {
170
			return TerminalInstance._lastKnownDimensions;
171 172 173 174 175 176 177 178 179 180 181 182 183 184
		} 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;
185 186
		TerminalInstance._lastKnownDimensions = new Dimension(innerWidth, height);
		return TerminalInstance._lastKnownDimensions;
187 188
	}

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

	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');
D
Daniel Imms 已提交
220
		dom.addClass(this._wrapperElement, 'terminal-wrapper');
221 222
		this._xtermElement = document.createElement('div');

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

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

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

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

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

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

296 297 298 299
		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 已提交
300
		this.setVisible(this._isVisible);
301
		this.updateConfig();
302 303 304 305 306 307

		// If IShellLaunchConfig.waitOnExit was true and the process finished before the terminal
		// panel was initialized.
		if (this._xterm.getOption('disableStdin')) {
			this._attachPressAnyKeyToCloseListener();
		}
308 309
	}

D
Daniel Imms 已提交
310
	public registerLinkMatcher(regex: RegExp, handler: (url: string) => void, matchIndex?: number, validationCallback?: (uri: string, element: HTMLElement, callback: (isValid: boolean) => void) => void): number {
311
		return this._linkHandler.registerCustomLinkHandler(regex, handler, matchIndex, validationCallback);
312 313 314 315 316 317
	}

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

318 319 320 321
	public hasSelection(): boolean {
		return !document.getSelection().isCollapsed;
	}

D
Daniel Imms 已提交
322
	public copySelection(): void {
D
Daniel Imms 已提交
323 324 325
		if (document.activeElement.classList.contains('xterm')) {
			document.execCommand('copy');
		} else {
D
Daniel Imms 已提交
326
			this._messageService.show(Severity.Warning, nls.localize('terminal.integrated.copySelection.noSelection', 'Cannot copy terminal selection when terminal does not have focus'));
D
Daniel Imms 已提交
327
		}
D
Daniel Imms 已提交
328 329
	}

330
	public clearSelection(): void {
331
		window.getSelection().empty();
332 333
	}

D
Daniel Imms 已提交
334
	public dispose(): void {
335 336 337
		if (this._linkHandler) {
			this._linkHandler.dispose();
		}
K
Kai Wood 已提交
338
		if (this._xterm && this._xterm.element) {
D
Daniel Imms 已提交
339
			this._hadFocusOnExit = dom.hasClass(this._xterm.element, 'focus');
K
Kai Wood 已提交
340
		}
D
Daniel Imms 已提交
341 342 343
		if (this._wrapperElement) {
			this._container.removeChild(this._wrapperElement);
			this._wrapperElement = null;
D
Daniel Imms 已提交
344
		}
D
Daniel Imms 已提交
345 346 347
		if (this._xterm) {
			this._xterm.destroy();
			this._xterm = null;
D
Daniel Imms 已提交
348
		}
D
Daniel Imms 已提交
349 350 351
		if (this._process) {
			if (this._process.connected) {
				this._process.kill();
D
Daniel Imms 已提交
352
			}
D
Daniel Imms 已提交
353
			this._process = null;
D
Daniel Imms 已提交
354
		}
355 356 357 358
		if (!this._isDisposed) {
			this._isDisposed = true;
			this._onDisposed.fire(this);
		}
359 360
		this._processDisposables = lifecycle.dispose(this._processDisposables);
		this._instanceDisposables = lifecycle.dispose(this._instanceDisposables);
D
Daniel Imms 已提交
361 362
	}

D
Daniel Imms 已提交
363
	public focus(force?: boolean): void {
D
Daniel Imms 已提交
364
		if (!this._xterm) {
D
Daniel Imms 已提交
365 366
			return;
		}
D
Daniel Imms 已提交
367
		const text = window.getSelection().toString();
D
Daniel Imms 已提交
368
		if (!text || force) {
D
Daniel Imms 已提交
369
			this._xterm.focus();
D
Daniel Imms 已提交
370
		}
D
Daniel Imms 已提交
371 372 373
	}

	public paste(): void {
D
Daniel Imms 已提交
374 375
		this.focus();
		document.execCommand('paste');
D
Daniel Imms 已提交
376 377 378
	}

	public sendText(text: string, addNewLine: boolean): void {
379 380 381
		text = this._sanitizeInput(text);
		if (addNewLine && text.substr(text.length - 1) !== '\r') {
			text += '\r';
D
Daniel Imms 已提交
382
		}
D
Daniel Imms 已提交
383
		this._process.send({
D
Daniel Imms 已提交
384 385 386
			event: 'input',
			data: text
		});
D
Daniel Imms 已提交
387
	}
388 389

	public setVisible(visible: boolean): void {
D
Daniel Imms 已提交
390 391
		this._isVisible = visible;
		if (this._wrapperElement) {
D
Daniel Imms 已提交
392
			dom.toggleClass(this._wrapperElement, 'active', visible);
393
		}
D
Daniel Imms 已提交
394
		if (visible && this._xterm) {
395 396 397 398 399 400
			// 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);
		}
401 402
	}

403
	public scrollDownLine(): void {
D
Daniel Imms 已提交
404
		this._xterm.scrollDisp(1);
D
Daniel Imms 已提交
405 406
	}

407
	public scrollDownPage(): void {
408
		this._xterm.scrollPages(1);
409 410
	}

411 412 413 414
	public scrollToBottom(): void {
		this._xterm.scrollToBottom();
	}

415
	public scrollUpLine(): void {
D
Daniel Imms 已提交
416
		this._xterm.scrollDisp(-1);
D
Daniel Imms 已提交
417
	}
418

419
	public scrollUpPage(): void {
420
		this._xterm.scrollPages(-1);
421 422
	}

423 424 425 426
	public scrollToTop(): void {
		this._xterm.scrollToTop();
	}

D
Daniel Imms 已提交
427 428 429 430
	public clear(): void {
		this._xterm.clear();
	}

431
	private _refreshSelectionContextKey() {
432 433 434
		const activePanel = this._panelService.getActivePanel();
		const isFocused = activePanel && activePanel.getId() === TERMINAL_PANEL_ID;
		this._terminalHasTextContextKey.set(isFocused && !window.getSelection().isCollapsed);
435 436
	}

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

441 442 443 444 445
	protected _getCwd(shell: IShellLaunchConfig, workspace: IWorkspace): string {
		if (shell.cwd) {
			return shell.cwd;
		}

B
Benjamin Pasero 已提交
446
		let cwd: string;
D
Daniel Imms 已提交
447 448

		// TODO: Handle non-existent customCwd
449
		if (!shell.ignoreConfigurationCwd) {
450
			// Evaluate custom cwd first
451
			const customCwd = this._configHelper.config.cwd;
452 453 454 455 456 457
			if (customCwd) {
				if (path.isAbsolute(customCwd)) {
					cwd = customCwd;
				} else if (workspace) {
					cwd = path.normalize(path.join(workspace.resource.fsPath, customCwd));
				}
D
Daniel Imms 已提交
458 459 460 461 462
			}
		}

		// If there was no custom cwd or it was relative with no workspace
		if (!cwd) {
463
			cwd = workspace ? workspace.resource.fsPath : os.homedir();
D
Daniel Imms 已提交
464 465 466 467 468
		}

		return TerminalInstance._sanitizeCwd(cwd);
	}

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

501 502
	private _sendPtyDataToXterm(message: { type: string, content: string }): void {
		if (message.type === 'data') {
D
Daniel Imms 已提交
503 504 505
			if (this._widgetManager) {
				this._widgetManager.closeMessage();
			}
D
Daniel Imms 已提交
506 507 508
			if (this._xterm) {
				this._xterm.write(message.content);
			}
509 510 511
		}
	}

512 513 514 515 516 517 518 519
	private _onPtyProcessExit(exitCode: number): void {
		// Prevent dispose functions being triggered multiple times
		if (this._isExiting) {
			return;
		}

		this._isExiting = true;
		let exitCodeMessage: string;
520
		if (exitCode) {
521 522 523
			exitCodeMessage = nls.localize('terminal.integrated.exitedWithCode', 'The terminal process terminated with exit code: {0}', exitCode);
		}

524 525 526 527 528
		// 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) {
529
			if (exitCode) {
530 531
				this._xterm.writeln(exitCodeMessage);
			}
532 533 534 535
			let message = typeof this._shellLaunchConfig.waitOnExit === 'string'
				? this._shellLaunchConfig.waitOnExit
				: nls.localize('terminal.integrated.waitOnExit', 'Press any key to close the terminal');
			this._xterm.writeln(message);
536 537
			// Disable all input if the terminal is exiting and listen for next keypress
			this._xterm.setOption('disableStdin', true);
538
			if (this._xterm.textarea) {
539
				this._attachPressAnyKeyToCloseListener();
540
			}
541 542
		} else {
			this.dispose();
543
			if (exitCode) {
544 545
				if (this._isLaunching) {
					let args = '';
546 547 548
					if (typeof this._shellLaunchConfig.args === 'string') {
						args = this._shellLaunchConfig.args;
					} else if (this._shellLaunchConfig.args && this._shellLaunchConfig.args.length) {
549 550 551 552 553 554
						args = ' ' + this._shellLaunchConfig.args.map(a => {
							if (a.indexOf(' ') !== -1) {
								return `'${a}'`;
							}
							return a;
						}).join(' ');
555
					}
556 557 558
					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);
559 560
				}
			}
561
		}
562 563
	}

564
	private _attachPressAnyKeyToCloseListener() {
D
Daniel Imms 已提交
565
		this._processDisposables.push(dom.addDisposableListener(this._xterm.textarea, 'keypress', (event: KeyboardEvent) => {
566 567 568 569 570
			this.dispose();
			event.preventDefault();
		}));
	}

571 572
	public reuseTerminal(shell?: IShellLaunchConfig): void {
		// Kill and clean up old process
573 574 575 576 577 578 579
		if (this._process) {
			this._process.removeAllListeners('exit');
			if (this._process.connected) {
				this._process.kill();
			}
			this._process = null;
		}
580 581 582
		lifecycle.dispose(this._processDisposables);
		this._processDisposables = [];

583 584
		// Ensure new processes' output starts at start of new line
		this._xterm.write('\n\x1b[G');
585

586 587 588 589 590
		// Print initialText if specified
		if (shell.initialText) {
			this._xterm.writeln(shell.initialText);
		}

591
		// Initialize new process
592
		const oldTitle = this._title;
D
Daniel Imms 已提交
593
		this._createProcess(this._contextService.getWorkspace(), shell);
594 595 596
		if (oldTitle !== this._title) {
			this._onTitleChanged.fire(this._title);
		}
597
		this._process.on('message', (message) => this._sendPtyDataToXterm(message));
598 599

		// Clean up waitOnExit state
600 601
		if (this._isExiting && this._shellLaunchConfig.waitOnExit) {
			this._xterm.setOption('disableStdin', false);
602
			this._isExiting = false;
603
		}
604

605 606 607 608
		// Set the new shell launch config
		this._shellLaunchConfig = shell;
	}

609 610
	// TODO: This should be private/protected
	// TODO: locale should not be optional
611
	public static createTerminalEnv(parentEnv: IStringDictionary<string>, shell: IShellLaunchConfig, cwd: string, locale?: string, cols?: number, rows?: number): IStringDictionary<string> {
612
		const env = shell.env ? shell.env : TerminalInstance._cloneEnv(parentEnv);
613 614
		env['PTYPID'] = process.pid.toString();
		env['PTYSHELL'] = shell.executable;
D
Daniel Imms 已提交
615
		if (shell.args) {
616 617 618 619 620
			if (typeof shell.args === 'string') {
				env[`PTYSHELLCMDLINE`] = shell.args;
			} else {
				shell.args.forEach((arg, i) => env[`PTYSHELLARG${i}`] = arg);
			}
D
Daniel Imms 已提交
621
		}
D
Daniel Imms 已提交
622
		env['PTYCWD'] = cwd;
623
		env['LANG'] = TerminalInstance._getLangEnvVariable(locale);
624 625 626 627
		if (cols && rows) {
			env['PTYCOLS'] = cols.toString();
			env['PTYROWS'] = rows.toString();
		}
628
		env['AMD_ENTRYPOINT'] = 'vs/workbench/parts/terminal/node/terminalProcess';
629
		return env;
630 631
	}

D
Dirk Baeumer 已提交
632 633
	public onData(listener: (data: string) => void): lifecycle.IDisposable {
		let callback = (message) => {
634 635 636
			if (message.type === 'data') {
				listener(message.content);
			}
D
Dirk Baeumer 已提交
637 638 639 640
		};
		this._process.on('message', callback);
		return {
			dispose: () => {
641 642 643
				if (this._process) {
					this._process.removeListener('message', callback);
				}
D
Dirk Baeumer 已提交
644 645
			}
		};
646 647
	}

D
Dirk Baeumer 已提交
648
	public onExit(listener: (exitCode: number) => void): lifecycle.IDisposable {
649
		this._process.on('exit', listener);
D
Dirk Baeumer 已提交
650 651
		return {
			dispose: () => {
652 653 654
				if (this._process) {
					this._process.removeListener('exit', listener);
				}
D
Dirk Baeumer 已提交
655 656
			}
		};
657 658
	}

D
Daniel Imms 已提交
659
	private static _sanitizeCwd(cwd: string) {
660 661 662
		// 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 已提交
663
		}
664
		return cwd;
D
Daniel Imms 已提交
665 666
	}

D
Daniel Imms 已提交
667
	private static _cloneEnv(env: IStringDictionary<string>): IStringDictionary<string> {
D
Daniel Imms 已提交
668
		const newEnv: IStringDictionary<string> = Object.create(null);
669 670
		Object.keys(env).forEach((key) => {
			newEnv[key] = env[key];
671
		});
672
		return newEnv;
673 674
	}

675 676
	private static _getLangEnvVariable(locale?: string) {
		const parts = locale ? locale.split('-') : [];
677
		const n = parts.length;
678
		if (n === 0) {
D
Daniel Imms 已提交
679 680
			// Fallback to en_US to prevent possible encoding issues.
			return 'en_US.UTF-8';
681 682 683 684 685 686 687 688 689 690 691 692 693
		}
		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',
694
				zh: 'CN'
695
			};
D
Daniel Imms 已提交
696 697
			if (parts[0] in languageVariants) {
				parts.push(languageVariants[parts[0]]);
698 699 700 701
			}
		} else {
			// Ensure the variant is uppercase
			parts[1] = parts[1].toUpperCase();
D
Daniel Imms 已提交
702
		}
703
		return parts.join('_') + '.UTF-8';
D
Daniel Imms 已提交
704
	}
D
Daniel Imms 已提交
705

706
	public updateConfig(): void {
707 708 709 710
		this._setCursorBlink(this._configHelper.config.cursorBlinking);
		this._setCursorStyle(this._configHelper.config.cursorStyle);
		this._setCommandsToSkipShell(this._configHelper.config.commandsToSkipShell);
		this._setScrollback(this._configHelper.config.scrollback);
711 712 713
	}

	private _setCursorBlink(blink: boolean): void {
D
Daniel Imms 已提交
714
		if (this._xterm && this._xterm.getOption('cursorBlink') !== blink) {
D
Daniel Imms 已提交
715
			this._xterm.setOption('cursorBlink', blink);
D
Daniel Imms 已提交
716
			this._xterm.refresh(0, this._xterm.rows - 1);
D
Daniel Imms 已提交
717 718 719
		}
	}

720 721 722 723 724 725 726 727
	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);
		}
	}

728
	private _setCommandsToSkipShell(commands: string[]): void {
D
Daniel Imms 已提交
729
		this._skipTerminalCommands = commands;
D
Daniel Imms 已提交
730 731
	}

732
	private _setScrollback(lineCount: number): void {
D
Daniel Imms 已提交
733 734 735 736 737
		if (this._xterm && this._xterm.getOption('scrollback') !== lineCount) {
			this._xterm.setOption('scrollback', lineCount);
		}
	}

738
	public layout(dimension: Dimension): void {
D
Daniel Imms 已提交
739 740
		const terminalWidth = this._evaluateColsAndRows(dimension.width, dimension.height);
		if (!terminalWidth) {
D
Daniel Imms 已提交
741 742
			return;
		}
D
Daniel Imms 已提交
743
		if (this._xterm) {
744
			this._xterm.resize(this._cols, this._rows);
D
Daniel Imms 已提交
745
			this._xterm.element.style.width = terminalWidth + 'px';
D
Daniel Imms 已提交
746
		}
D
Daniel Imms 已提交
747 748
		if (this._process.connected) {
			this._process.send({
D
Daniel Imms 已提交
749
				event: 'resize',
750 751
				cols: this._cols,
				rows: this._rows
D
Daniel Imms 已提交
752 753 754
			});
		}
	}
755

D
Daniel Imms 已提交
756 757 758 759 760
	public enableApiOnData(): void {
		// Only send data through IPC if the API explicitly requests it.
		this.onData(data => this._onDataForApi.fire({ instance: this, data }));
	}

761 762 763
	public static setTerminalProcessFactory(factory: ITerminalProcessFactory): void {
		this._terminalProcessFactory = factory;
	}
764
}
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781

registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => {

	// Scrollbar
	const scrollbarSliderBackgroundColor = theme.getColor(scrollbarSliderBackground);
	if (scrollbarSliderBackgroundColor) {
		collector.addRule(`
			.monaco-workbench .panel.integrated-terminal .xterm.focus .xterm-viewport,
			.monaco-workbench .panel.integrated-terminal .xterm:focus .xterm-viewport,
			.monaco-workbench .panel.integrated-terminal .xterm:hover .xterm-viewport { background-color: ${scrollbarSliderBackgroundColor}; }`
		);
	}

	const scrollbarSliderHoverBackgroundColor = theme.getColor(scrollbarSliderHoverBackground);
	if (scrollbarSliderHoverBackgroundColor) {
		collector.addRule(`.monaco-workbench .panel.integrated-terminal .xterm .xterm-viewport::-webkit-scrollbar-thumb:hover { background-color: ${scrollbarSliderHoverBackgroundColor}; }`);
	}
782 783 784 785 786

	const scrollbarSliderActiveBackgroundColor = theme.getColor(scrollbarSliderActiveBackground);
	if (scrollbarSliderActiveBackgroundColor) {
		collector.addRule(`.monaco-workbench .panel.integrated-terminal .xterm .xterm-viewport::-webkit-scrollbar-thumb:active { background-color: ${scrollbarSliderActiveBackgroundColor}; }`);
	}
787
});