terminalInstance.ts 21.0 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
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 26
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { TabFocus } from 'vs/editor/common/config/commonEditorConfig';
27
import { TerminalConfigHelper } from 'vs/workbench/parts/terminal/electron-browser/terminalConfigHelper';
28

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

32 33 34 35 36 37 38 39 40
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
		});
	}
}

41
export class TerminalInstance implements ITerminalInstance {
42
	private static readonly EOL_REGEX = /\r?\n/g;
C
Christof Marti 已提交
43

44
	private static _terminalProcessFactory: ITerminalProcessFactory = new StandardTerminalProcessFactory();
D
Daniel Imms 已提交
45 46
	private static _idCounter = 1;

47
	private _id: number;
D
Daniel Imms 已提交
48
	private _isExiting: boolean;
K
Kai Wood 已提交
49
	private _hadFocusOnExit: boolean;
50
	private _isLaunching: boolean;
D
Daniel Imms 已提交
51
	private _isVisible: boolean;
52
	private _onDisposed: Emitter<ITerminalInstance>;
53
	private _onProcessIdReady: Emitter<TerminalInstance>;
D
Daniel Imms 已提交
54
	private _onTitleChanged: Emitter<string>;
D
Daniel Imms 已提交
55
	private _process: cp.ChildProcess;
56
	private _processId: number;
D
Daniel Imms 已提交
57
	private _skipTerminalCommands: string[];
D
Daniel Imms 已提交
58
	private _title: string;
59 60
	private _instanceDisposables: lifecycle.IDisposable[];
	private _processDisposables: lifecycle.IDisposable[];
D
Daniel Imms 已提交
61 62 63
	private _wrapperElement: HTMLDivElement;
	private _xterm: any;
	private _xtermElement: HTMLDivElement;
64
	private _terminalHasTextContextKey: IContextKey<boolean>;
D
Daniel Imms 已提交
65

66
	public get id(): number { return this._id; }
67
	public get processId(): number { return this._processId; }
68
	public get onDisposed(): Event<ITerminalInstance> { return this._onDisposed.event; }
69
	public get onProcessIdReady(): Event<TerminalInstance> { return this._onProcessIdReady.event; }
D
Daniel Imms 已提交
70
	public get onTitleChanged(): Event<string> { return this._onTitleChanged.event; }
D
Daniel Imms 已提交
71
	public get title(): string { return this._title; }
K
Kai Wood 已提交
72
	public get hadFocusOnExit(): boolean { return this._hadFocusOnExit; }
73 74

	public constructor(
D
Daniel Imms 已提交
75 76 77
		private _terminalFocusContextKey: IContextKey<boolean>,
		private _configHelper: TerminalConfigHelper,
		private _container: HTMLElement,
78
		private _shellLaunchConfig: IShellLaunchConfig,
79
		@IContextKeyService private _contextKeyService: IContextKeyService,
D
Daniel Imms 已提交
80
		@IKeybindingService private _keybindingService: IKeybindingService,
81
		@IMessageService private _messageService: IMessageService,
82 83
		@IPanelService private _panelService: IPanelService,
		@IWorkspaceContextService private _contextService: IWorkspaceContextService
84
	) {
85 86
		this._instanceDisposables = [];
		this._processDisposables = [];
D
Daniel Imms 已提交
87
		this._skipTerminalCommands = [];
D
Daniel Imms 已提交
88
		this._isExiting = false;
K
Kai Wood 已提交
89
		this._hadFocusOnExit = false;
90
		this._isLaunching = true;
D
Daniel Imms 已提交
91 92
		this._isVisible = false;
		this._id = TerminalInstance._idCounter++;
93
		this._terminalHasTextContextKey = KEYBINDING_CONTEXT_TERMINAL_TEXT_SELECTED.bindTo(this._contextKeyService);
D
Daniel Imms 已提交
94

95
		this._onDisposed = new Emitter<TerminalInstance>();
96 97
		this._onProcessIdReady = new Emitter<TerminalInstance>();
		this._onTitleChanged = new Emitter<string>();
98

D
Daniel Imms 已提交
99
		this._createProcess(this._contextService.getWorkspace(), this._shellLaunchConfig);
D
Daniel Imms 已提交
100 101 102

		if (_container) {
			this.attachToElement(_container);
103 104 105
		}
	}

D
Daniel Imms 已提交
106
	public addDisposable(disposable: lifecycle.IDisposable): void {
107
		this._instanceDisposables.push(disposable);
D
Daniel Imms 已提交
108 109
	}

110
	public attachToElement(container: HTMLElement): void {
D
Daniel Imms 已提交
111
		if (this._wrapperElement) {
112 113 114
			throw new Error('The terminal instance has already been attached to a container');
		}

D
Daniel Imms 已提交
115 116 117 118
		this._container = container;
		this._wrapperElement = document.createElement('div');
		DOM.addClass(this._wrapperElement, 'terminal-wrapper');
		this._xtermElement = document.createElement('div');
119

120 121 122
		this._xterm = xterm({
			scrollback: this._configHelper.getScrollback()
		});
D
Daniel Imms 已提交
123
		this._xterm.open(this._xtermElement);
124

125
		this._process.on('message', (message) => this._sendPtyDataToXterm(message));
D
Daniel Imms 已提交
126
		this._xterm.on('data', (data) => {
127 128 129 130 131 132
			if (this._process) {
				this._process.send({
					event: 'input',
					data: this._sanitizeInput(data)
				});
			}
D
Daniel Imms 已提交
133 134
			return false;
		});
D
Daniel Imms 已提交
135
		this._xterm.attachCustomKeydownHandler((event: KeyboardEvent) => {
136 137 138 139 140
			// Disable all input if the terminal is exiting
			if (this._isExiting) {
				return false;
			}

141 142
			// Skip processing by xterm.js of keyboard events that resolve to commands described
			// within commandsToSkipShell
D
Daniel Imms 已提交
143
			const standardKeyboardEvent = new StandardKeyboardEvent(event);
144
			const keybinding = standardKeyboardEvent.toKeybinding();
D
Daniel Imms 已提交
145 146
			const resolveResult = this._keybindingService.resolve(keybinding, standardKeyboardEvent.target);
			if (resolveResult && this._skipTerminalCommands.some(k => k === resolveResult.commandId)) {
D
Daniel Imms 已提交
147 148 149 150 151 152 153 154 155
				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;
			}
		});
156
		this._instanceDisposables.push(DOM.addDisposableListener(this._xterm.element, 'mouseup', (event: KeyboardEvent) => {
157 158 159
			// Wait until mouseup has propogated through the DOM before evaluating the new selection
			// state.
			setTimeout(() => {
160 161
				this._refreshSelectionContextKey();
			}, 0);
162
		}));
163 164

		// xterm.js currently drops selection on keyup as we need to handle this case.
165
		this._instanceDisposables.push(DOM.addDisposableListener(this._xterm.element, 'keyup', (event: KeyboardEvent) => {
166 167 168 169
			// Wait until keyup has propogated through the DOM before evaluating the new selection
			// state.
			setTimeout(() => {
				this._refreshSelectionContextKey();
170
			}, 0);
171
		}));
D
Daniel Imms 已提交
172

D
Daniel Imms 已提交
173 174
		const xtermHelper: HTMLElement = this._xterm.element.querySelector('.xterm-helpers');
		const focusTrap: HTMLElement = document.createElement('div');
175 176
		focusTrap.setAttribute('tabindex', '0');
		DOM.addClass(focusTrap, 'focus-trap');
177
		this._instanceDisposables.push(DOM.addDisposableListener(focusTrap, 'focus', (event: FocusEvent) => {
178 179 180 181
			let currentElement = focusTrap;
			while (!DOM.hasClass(currentElement, 'part')) {
				currentElement = currentElement.parentElement;
			}
D
Daniel Imms 已提交
182
			const hidePanelElement = <HTMLElement>currentElement.querySelector('.hide-panel-action');
183
			hidePanelElement.focus();
184
		}));
D
Daniel Imms 已提交
185
		xtermHelper.insertBefore(focusTrap, this._xterm.textarea);
186

187
		this._instanceDisposables.push(DOM.addDisposableListener(this._xterm.textarea, 'focus', (event: KeyboardEvent) => {
D
Daniel Imms 已提交
188
			this._terminalFocusContextKey.set(true);
189
		}));
190
		this._instanceDisposables.push(DOM.addDisposableListener(this._xterm.textarea, 'blur', (event: KeyboardEvent) => {
D
Daniel Imms 已提交
191
			this._terminalFocusContextKey.reset();
192
			this._refreshSelectionContextKey();
193
		}));
194
		this._instanceDisposables.push(DOM.addDisposableListener(this._xterm.element, 'focus', (event: KeyboardEvent) => {
D
Daniel Imms 已提交
195
			this._terminalFocusContextKey.set(true);
196
		}));
197
		this._instanceDisposables.push(DOM.addDisposableListener(this._xterm.element, 'blur', (event: KeyboardEvent) => {
D
Daniel Imms 已提交
198
			this._terminalFocusContextKey.reset();
199
			this._refreshSelectionContextKey();
200 201
		}));

D
Daniel Imms 已提交
202 203
		this._wrapperElement.appendChild(this._xtermElement);
		this._container.appendChild(this._wrapperElement);
204

205 206 207 208
		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 已提交
209
		this.setVisible(this._isVisible);
210
		this.updateConfig();
211 212
	}

213 214 215 216
	public hasSelection(): boolean {
		return !document.getSelection().isCollapsed;
	}

D
Daniel Imms 已提交
217
	public copySelection(): void {
D
Daniel Imms 已提交
218 219 220
		if (document.activeElement.classList.contains('xterm')) {
			document.execCommand('copy');
		} else {
D
Daniel Imms 已提交
221
			this._messageService.show(Severity.Warning, nls.localize('terminal.integrated.copySelection.noSelection', 'Cannot copy terminal selection when terminal does not have focus'));
D
Daniel Imms 已提交
222
		}
D
Daniel Imms 已提交
223 224
	}

225 226 227 228
	public clearSelection(): void {
		document.getSelection().empty();
	}

D
Daniel Imms 已提交
229
	public dispose(): void {
K
Kai Wood 已提交
230 231 232
		if (this._xterm && this._xterm.element) {
			this._hadFocusOnExit = DOM.hasClass(this._xterm.element, 'focus');
		}
D
Daniel Imms 已提交
233 234 235
		if (this._wrapperElement) {
			this._container.removeChild(this._wrapperElement);
			this._wrapperElement = null;
D
Daniel Imms 已提交
236
		}
D
Daniel Imms 已提交
237 238 239
		if (this._xterm) {
			this._xterm.destroy();
			this._xterm = null;
D
Daniel Imms 已提交
240
		}
D
Daniel Imms 已提交
241 242 243
		if (this._process) {
			if (this._process.connected) {
				this._process.kill();
D
Daniel Imms 已提交
244
			}
D
Daniel Imms 已提交
245
			this._process = null;
D
Daniel Imms 已提交
246
		}
247
		this._onDisposed.fire(this);
248 249
		this._processDisposables = lifecycle.dispose(this._processDisposables);
		this._instanceDisposables = lifecycle.dispose(this._instanceDisposables);
D
Daniel Imms 已提交
250 251
	}

D
Daniel Imms 已提交
252
	public focus(force?: boolean): void {
D
Daniel Imms 已提交
253
		if (!this._xterm) {
D
Daniel Imms 已提交
254 255
			return;
		}
D
Daniel Imms 已提交
256
		const text = window.getSelection().toString();
D
Daniel Imms 已提交
257
		if (!text || force) {
D
Daniel Imms 已提交
258
			this._xterm.focus();
D
Daniel Imms 已提交
259
		}
D
Daniel Imms 已提交
260 261 262
	}

	public paste(): void {
D
Daniel Imms 已提交
263 264
		this.focus();
		document.execCommand('paste');
D
Daniel Imms 已提交
265 266 267
	}

	public sendText(text: string, addNewLine: boolean): void {
D
Daniel Imms 已提交
268 269 270
		if (addNewLine && text.substr(text.length - os.EOL.length) !== os.EOL) {
			text += os.EOL;
		}
D
Daniel Imms 已提交
271
		this._process.send({
D
Daniel Imms 已提交
272 273 274
			event: 'input',
			data: text
		});
D
Daniel Imms 已提交
275
	}
276 277

	public setVisible(visible: boolean): void {
D
Daniel Imms 已提交
278 279 280
		this._isVisible = visible;
		if (this._wrapperElement) {
			DOM.toggleClass(this._wrapperElement, 'active', visible);
281
		}
D
Daniel Imms 已提交
282
		if (visible && this._xterm) {
283 284 285 286 287 288
			// 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);
		}
289 290
	}

291
	public scrollDownLine(): void {
D
Daniel Imms 已提交
292
		this._xterm.scrollDisp(1);
D
Daniel Imms 已提交
293 294
	}

295
	public scrollDownPage(): void {
296
		this._xterm.scrollPages(1);
297 298
	}

299 300 301 302
	public scrollToBottom(): void {
		this._xterm.scrollToBottom();
	}

303
	public scrollUpLine(): void {
D
Daniel Imms 已提交
304
		this._xterm.scrollDisp(-1);
D
Daniel Imms 已提交
305
	}
306

307
	public scrollUpPage(): void {
308
		this._xterm.scrollPages(-1);
309 310
	}

311 312 313 314
	public scrollToTop(): void {
		this._xterm.scrollToTop();
	}

D
Daniel Imms 已提交
315 316 317 318
	public clear(): void {
		this._xterm.clear();
	}

319
	private _refreshSelectionContextKey() {
320 321 322
		const activePanel = this._panelService.getActivePanel();
		const isFocused = activePanel && activePanel.getId() === TERMINAL_PANEL_ID;
		this._terminalHasTextContextKey.set(isFocused && !window.getSelection().isCollapsed);
323 324
	}

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

329 330 331 332 333
	protected _getCwd(shell: IShellLaunchConfig, workspace: IWorkspace): string {
		if (shell.cwd) {
			return shell.cwd;
		}

B
Benjamin Pasero 已提交
334
		let cwd: string;
D
Daniel Imms 已提交
335 336

		// TODO: Handle non-existent customCwd
337
		if (!shell.ignoreConfigurationCwd) {
338
			// Evaluate custom cwd first
D
Daniel Imms 已提交
339
			const customCwd = this._configHelper.getCwd();
340 341 342 343 344 345
			if (customCwd) {
				if (path.isAbsolute(customCwd)) {
					cwd = customCwd;
				} else if (workspace) {
					cwd = path.normalize(path.join(workspace.resource.fsPath, customCwd));
				}
D
Daniel Imms 已提交
346 347 348 349 350
			}
		}

		// If there was no custom cwd or it was relative with no workspace
		if (!cwd) {
351
			cwd = workspace ? workspace.resource.fsPath : os.homedir();
D
Daniel Imms 已提交
352 353 354 355 356
		}

		return TerminalInstance._sanitizeCwd(cwd);
	}

357
	protected _createProcess(workspace: IWorkspace, shell: IShellLaunchConfig): void {
D
Daniel Imms 已提交
358
		const locale = this._configHelper.isSetLocaleVariables() ? platform.locale : undefined;
D
Daniel Imms 已提交
359
		if (!shell.executable) {
360
			this._configHelper.mergeDefaultShellPathAndArgs(shell);
P
Pine Wu 已提交
361
		}
362
		const env = TerminalInstance.createTerminalEnv(process.env, shell, this._getCwd(shell, workspace), locale);
D
Daniel Imms 已提交
363
		this._title = shell.name || '';
D
Daniel Imms 已提交
364
		this._process = cp.fork('./terminalProcess', [], {
365 366 367
			env: env,
			cwd: URI.parse(path.dirname(require.toUrl('./terminalProcess'))).fsPath
		});
D
Daniel Imms 已提交
368
		if (!shell.name) {
369
			// Only listen for process title changes when a name is not provided
D
Daniel Imms 已提交
370
			this._process.on('message', (message) => {
371
				if (message.type === 'title') {
D
Daniel Imms 已提交
372
					this._title = message.content ? message.content : '';
373
					this._onTitleChanged.fire(this._title);
374
				}
375 376
			});
		}
377 378 379 380 381 382
		this._process.on('message', (message) => {
			if (message.type === 'pid') {
				this._processId = message.content;
				this._onProcessIdReady.fire(this);
			}
		});
383 384 385 386 387 388
		this._process.on('exit', exitCode => this._onPtyProcessExit(exitCode));
		setTimeout(() => {
			this._isLaunching = false;
		}, LAUNCHING_DURATION);
	}

389 390 391 392 393 394 395 396 397
	private _sendPtyDataToXterm(message: { type: string, content: string }): void {
		if (!this._xterm) {
			return;
		}
		if (message.type === 'data') {
			this._xterm.write(message.content);
		}
	}

398 399 400 401 402 403 404 405
	private _onPtyProcessExit(exitCode: number): void {
		// Prevent dispose functions being triggered multiple times
		if (this._isExiting) {
			return;
		}

		this._isExiting = true;
		let exitCodeMessage: string;
406
		if (exitCode) {
407 408 409
			exitCodeMessage = nls.localize('terminal.integrated.exitedWithCode', 'The terminal process terminated with exit code: {0}', exitCode);
		}

410 411 412 413 414
		// 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) {
415
			if (exitCode) {
416 417 418 419 420
				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);
421
			this._processDisposables.push(DOM.addDisposableListener(this._xterm.textarea, 'keypress', (event: KeyboardEvent) => {
422
				this.dispose();
423
				event.preventDefault();
424
			}));
425 426
		} else {
			this.dispose();
427
			if (exitCode) {
428 429 430 431 432 433 434 435 436
				if (this._isLaunching) {
					let args = '';
					if (this._shellLaunchConfig.args && this._shellLaunchConfig.args.length) {
						args = ' ' + this._shellLaunchConfig.args.map(a => {
							if (a.indexOf(' ') !== -1) {
								return `'${a}'`;
							}
							return a;
						}).join(' ');
437
					}
438 439 440
					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);
441 442
				}
			}
443
		}
444 445
	}

446 447
	public reuseTerminal(shell?: IShellLaunchConfig): void {
		// Kill and clean up old process
448 449 450 451 452 453 454
		if (this._process) {
			this._process.removeAllListeners('exit');
			if (this._process.connected) {
				this._process.kill();
			}
			this._process = null;
		}
455 456 457
		lifecycle.dispose(this._processDisposables);
		this._processDisposables = [];

458 459
		// Ensure new processes' output starts at start of new line
		this._xterm.write('\n\x1b[G');
460 461

		// Initialize new process
D
Daniel Imms 已提交
462
		this._createProcess(this._contextService.getWorkspace(), shell);
463
		this._process.on('message', (message) => this._sendPtyDataToXterm(message));
464 465

		// Clean up waitOnExit state
466 467
		if (this._isExiting && this._shellLaunchConfig.waitOnExit) {
			this._xterm.setOption('disableStdin', false);
468
			this._isExiting = false;
469
		}
470

471 472 473 474
		// Set the new shell launch config
		this._shellLaunchConfig = shell;
	}

475 476
	// TODO: This should be private/protected
	// TODO: locale should not be optional
477
	public static createTerminalEnv(parentEnv: IStringDictionary<string>, shell: IShellLaunchConfig, cwd: string, locale?: string): IStringDictionary<string> {
478
		const env = shell.env ? shell.env : TerminalInstance._cloneEnv(parentEnv);
479 480
		env['PTYPID'] = process.pid.toString();
		env['PTYSHELL'] = shell.executable;
D
Daniel Imms 已提交
481 482 483 484 485
		if (shell.args) {
			shell.args.forEach((arg, i) => {
				env[`PTYSHELLARG${i}`] = arg;
			});
		}
D
Daniel Imms 已提交
486
		env['PTYCWD'] = cwd;
487
		if (locale) {
D
Daniel Imms 已提交
488
			env['LANG'] = TerminalInstance._getLangEnvVariable(locale);
489 490
		}
		return env;
491 492
	}

D
Dirk Baeumer 已提交
493 494
	public onData(listener: (data: string) => void): lifecycle.IDisposable {
		let callback = (message) => {
495 496 497
			if (message.type === 'data') {
				listener(message.content);
			}
D
Dirk Baeumer 已提交
498 499 500 501
		};
		this._process.on('message', callback);
		return {
			dispose: () => {
502 503 504
				if (this._process) {
					this._process.removeListener('message', callback);
				}
D
Dirk Baeumer 已提交
505 506
			}
		};
507 508
	}

D
Dirk Baeumer 已提交
509
	public onExit(listener: (exitCode: number) => void): lifecycle.IDisposable {
510
		this._process.on('exit', listener);
D
Dirk Baeumer 已提交
511 512
		return {
			dispose: () => {
513 514 515
				if (this._process) {
					this._process.removeListener('exit', listener);
				}
D
Dirk Baeumer 已提交
516 517
			}
		};
518 519
	}

D
Daniel Imms 已提交
520
	private static _sanitizeCwd(cwd: string) {
521 522 523
		// 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 已提交
524
		}
525
		return cwd;
D
Daniel Imms 已提交
526 527
	}

D
Daniel Imms 已提交
528
	private static _cloneEnv(env: IStringDictionary<string>): IStringDictionary<string> {
D
Daniel Imms 已提交
529
		const newEnv: IStringDictionary<string> = Object.create(null);
530 531
		Object.keys(env).forEach((key) => {
			newEnv[key] = env[key];
532
		});
533
		return newEnv;
534 535
	}

D
Daniel Imms 已提交
536
	private static _getLangEnvVariable(locale: string) {
537 538 539 540
		const parts = locale.split('-');
		const n = parts.length;
		if (n > 1) {
			parts[n - 1] = parts[n - 1].toUpperCase();
D
Daniel Imms 已提交
541
		}
542
		return parts.join('_') + '.UTF-8';
D
Daniel Imms 已提交
543
	}
D
Daniel Imms 已提交
544

545 546
	public updateConfig(): void {
		this._setCursorBlink(this._configHelper.getCursorBlink());
547
		this._setCursorStyle(this._configHelper.getCursorStyle());
548 549 550 551 552
		this._setCommandsToSkipShell(this._configHelper.getCommandsToSkipShell());
		this._setScrollback(this._configHelper.getScrollback());
	}

	private _setCursorBlink(blink: boolean): void {
D
Daniel Imms 已提交
553
		if (this._xterm && this._xterm.getOption('cursorBlink') !== blink) {
D
Daniel Imms 已提交
554
			this._xterm.setOption('cursorBlink', blink);
D
Daniel Imms 已提交
555
			this._xterm.refresh(0, this._xterm.rows - 1);
D
Daniel Imms 已提交
556 557 558
		}
	}

559 560 561 562 563 564 565 566
	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);
		}
	}

567
	private _setCommandsToSkipShell(commands: string[]): void {
D
Daniel Imms 已提交
568
		this._skipTerminalCommands = commands;
D
Daniel Imms 已提交
569 570
	}

571
	private _setScrollback(lineCount: number): void {
D
Daniel Imms 已提交
572
		if (this._xterm && this._xterm.getOption('scrollback') !== lineCount) {
573
			console.log('set scrollback to: ' + lineCount);
D
Daniel Imms 已提交
574 575 576 577
			this._xterm.setOption('scrollback', lineCount);
		}
	}

578
	public layout(dimension: { width: number, height: number }): void {
D
Daniel Imms 已提交
579
		const font = this._configHelper.getFont();
580
		if (!font || !font.charWidth || !font.charHeight) {
D
Daniel Imms 已提交
581 582 583 584
			return;
		}
		if (!dimension.height) { // Minimized
			return;
585 586 587 588 589 590
		} 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 已提交
591
		}
592
		const padding = parseInt(getComputedStyle(document.querySelector('.terminal-outer-container')).paddingLeft.split('px')[0], 10);
D
Daniel Imms 已提交
593 594 595
		// Use left padding as right padding, right padding is not defined in CSS just in case
		// xterm.js causes an unexpected overflow.
		const innerWidth = dimension.width - padding * 2;
D
Daniel Imms 已提交
596 597
		const cols = Math.floor(innerWidth / font.charWidth);
		const rows = Math.floor(dimension.height / font.charHeight);
D
Daniel Imms 已提交
598 599 600
		if (this._xterm) {
			this._xterm.resize(cols, rows);
			this._xterm.element.style.width = innerWidth + 'px';
D
Daniel Imms 已提交
601
		}
D
Daniel Imms 已提交
602 603
		if (this._process.connected) {
			this._process.send({
D
Daniel Imms 已提交
604 605 606 607 608 609
				event: 'resize',
				cols: cols,
				rows: rows
			});
		}
	}
610 611 612 613

	public static setTerminalProcessFactory(factory: ITerminalProcessFactory): void {
		this._terminalProcessFactory = factory;
	}
614
}