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

import DOM = require('vs/base/browser/dom');
J
Johannes Rieken 已提交
7
import Event, { Emitter } from 'vs/base/common/event';
8 9
import URI from 'vs/base/common/uri';
import cp = require('child_process');
10
import lifecycle = require('vs/base/common/lifecycle');
C
Christof Marti 已提交
11
import nls = require('vs/nls');
C
Christof Marti 已提交
12
import os = require('os');
13 14
import path = require('path');
import platform = require('vs/base/common/platform');
15
import xterm = require('xterm');
16
import { Dimension } from 'vs/base/browser/builder';
17
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
18 19
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<TerminalInstance>;
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 onClosed(): Event<TerminalInstance> { 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
		}
282 283
	}

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

288
	public scrollDownPage(): void {
289
		this._xterm.scrollPages(1);
290 291
	}

292 293 294 295
	public scrollToBottom(): void {
		this._xterm.scrollToBottom();
	}

296
	public scrollUpLine(): void {
D
Daniel Imms 已提交
297
		this._xterm.scrollDisp(-1);
D
Daniel Imms 已提交
298
	}
299

300
	public scrollUpPage(): void {
301
		this._xterm.scrollPages(-1);
302 303
	}

304 305 306 307
	public scrollToTop(): void {
		this._xterm.scrollToTop();
	}

D
Daniel Imms 已提交
308 309 310 311
	public clear(): void {
		this._xterm.clear();
	}

312
	private _refreshSelectionContextKey() {
313 314 315
		const activePanel = this._panelService.getActivePanel();
		const isFocused = activePanel && activePanel.getId() === TERMINAL_PANEL_ID;
		this._terminalHasTextContextKey.set(isFocused && !window.getSelection().isCollapsed);
316 317
	}

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

322 323 324 325 326
	protected _getCwd(shell: IShellLaunchConfig, workspace: IWorkspace): string {
		if (shell.cwd) {
			return shell.cwd;
		}

B
Benjamin Pasero 已提交
327
		let cwd: string;
D
Daniel Imms 已提交
328 329

		// TODO: Handle non-existent customCwd
330
		if (!shell.ignoreConfigurationCwd) {
331
			// Evaluate custom cwd first
D
Daniel Imms 已提交
332
			const customCwd = this._configHelper.getCwd();
333 334 335 336 337 338
			if (customCwd) {
				if (path.isAbsolute(customCwd)) {
					cwd = customCwd;
				} else if (workspace) {
					cwd = path.normalize(path.join(workspace.resource.fsPath, customCwd));
				}
D
Daniel Imms 已提交
339 340 341 342 343
			}
		}

		// If there was no custom cwd or it was relative with no workspace
		if (!cwd) {
344
			cwd = workspace ? workspace.resource.fsPath : os.homedir();
D
Daniel Imms 已提交
345 346 347 348 349
		}

		return TerminalInstance._sanitizeCwd(cwd);
	}

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

382 383 384 385 386 387 388 389 390
	private _sendPtyDataToXterm(message: { type: string, content: string }): void {
		if (!this._xterm) {
			return;
		}
		if (message.type === 'data') {
			this._xterm.write(message.content);
		}
	}

391 392 393 394 395 396 397 398
	private _onPtyProcessExit(exitCode: number): void {
		// Prevent dispose functions being triggered multiple times
		if (this._isExiting) {
			return;
		}

		this._isExiting = true;
		let exitCodeMessage: string;
399
		if (exitCode) {
400 401 402
			exitCodeMessage = nls.localize('terminal.integrated.exitedWithCode', 'The terminal process terminated with exit code: {0}', exitCode);
		}

403 404 405 406 407
		// 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) {
408
			if (exitCode) {
409 410 411 412 413
				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);
414
			this._processDisposables.push(DOM.addDisposableListener(this._xterm.textarea, 'keypress', () => {
415
				this.dispose();
416
			}));
417 418
		} else {
			this.dispose();
419
			if (exitCode) {
420 421 422 423 424 425 426 427 428
				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(' ');
429
					}
430 431 432
					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);
433 434
				}
			}
435
		}
436 437
	}

438 439
	public reuseTerminal(shell?: IShellLaunchConfig): void {
		// Kill and clean up old process
440 441 442 443 444 445 446
		if (this._process) {
			this._process.removeAllListeners('exit');
			if (this._process.connected) {
				this._process.kill();
			}
			this._process = null;
		}
447 448 449
		lifecycle.dispose(this._processDisposables);
		this._processDisposables = [];

450 451
		// Ensure new processes' output starts at start of new line
		this._xterm.write('\n\x1b[G');
452 453

		// Initialize new process
D
Daniel Imms 已提交
454
		this._createProcess(this._contextService.getWorkspace(), shell);
455
		this._process.on('message', (message) => this._sendPtyDataToXterm(message));
456 457

		// Clean up waitOnExit state
458 459
		if (this._isExiting && this._shellLaunchConfig.waitOnExit) {
			this._xterm.setOption('disableStdin', false);
460
			this._isExiting = false;
461
		}
462

463 464 465 466
		// Set the new shell launch config
		this._shellLaunchConfig = shell;
	}

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

485 486 487 488 489 490 491 492
	public onData(listener: (data: string) => void): void {
		this._process.on('message', (message) => {
			if (message.type === 'data') {
				listener(message.content);
			}
		});
	}

493 494 495 496
	public onExit(listener: (exitCode: number) => void): void {
		this._process.on('exit', listener);
	}

D
Daniel Imms 已提交
497
	private static _sanitizeCwd(cwd: string) {
498 499 500
		// 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 已提交
501
		}
502
		return cwd;
D
Daniel Imms 已提交
503 504
	}

D
Daniel Imms 已提交
505
	private static _cloneEnv(env: IStringDictionary<string>): IStringDictionary<string> {
D
Daniel Imms 已提交
506
		const newEnv: IStringDictionary<string> = Object.create(null);
507 508
		Object.keys(env).forEach((key) => {
			newEnv[key] = env[key];
509
		});
510
		return newEnv;
511 512
	}

D
Daniel Imms 已提交
513
	private static _getLangEnvVariable(locale: string) {
514 515 516 517
		const parts = locale.split('-');
		const n = parts.length;
		if (n > 1) {
			parts[n - 1] = parts[n - 1].toUpperCase();
D
Daniel Imms 已提交
518
		}
519
		return parts.join('_') + '.UTF-8';
D
Daniel Imms 已提交
520
	}
D
Daniel Imms 已提交
521

522 523 524 525 526 527 528
	public updateConfig(): void {
		this._setCursorBlink(this._configHelper.getCursorBlink());
		this._setCommandsToSkipShell(this._configHelper.getCommandsToSkipShell());
		this._setScrollback(this._configHelper.getScrollback());
	}

	private _setCursorBlink(blink: boolean): void {
D
Daniel Imms 已提交
529
		if (this._xterm && this._xterm.getOption('cursorBlink') !== blink) {
D
Daniel Imms 已提交
530
			this._xterm.setOption('cursorBlink', blink);
D
Daniel Imms 已提交
531
			this._xterm.refresh(0, this._xterm.rows - 1);
D
Daniel Imms 已提交
532 533 534
		}
	}

535
	private _setCommandsToSkipShell(commands: string[]): void {
D
Daniel Imms 已提交
536
		this._skipTerminalCommands = commands;
D
Daniel Imms 已提交
537 538
	}

539
	private _setScrollback(lineCount: number): void {
D
Daniel Imms 已提交
540
		if (this._xterm && this._xterm.getOption('scrollback') !== lineCount) {
541
			console.log('set scrollback to: ' + lineCount);
D
Daniel Imms 已提交
542 543 544 545
			this._xterm.setOption('scrollback', lineCount);
		}
	}

546
	public layout(dimension: { width: number, height: number }): void {
D
Daniel Imms 已提交
547
		const font = this._configHelper.getFont();
548
		if (!font || !font.charWidth || !font.charHeight) {
D
Daniel Imms 已提交
549 550 551 552
			return;
		}
		if (!dimension.height) { // Minimized
			return;
553 554 555 556 557 558
		} 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 已提交
559
		}
560
		const padding = parseInt(getComputedStyle(document.querySelector('.terminal-outer-container')).paddingLeft.split('px')[0], 10);
D
Daniel Imms 已提交
561 562 563
		// 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 已提交
564 565
		const cols = Math.floor(innerWidth / font.charWidth);
		const rows = Math.floor(dimension.height / font.charHeight);
D
Daniel Imms 已提交
566 567 568
		if (this._xterm) {
			this._xterm.resize(cols, rows);
			this._xterm.element.style.width = innerWidth + 'px';
D
Daniel Imms 已提交
569
		}
D
Daniel Imms 已提交
570 571
		if (this._process.connected) {
			this._process.send({
D
Daniel Imms 已提交
572 573 574 575 576 577
				event: 'resize',
				cols: cols,
				rows: rows
			});
		}
	}
578 579 580 581

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