terminalInstance.ts 18.6 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');
D
Daniel Imms 已提交
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');
D
Daniel Imms 已提交
16
import {Dimension} from 'vs/base/browser/builder';
A
Alex Dima 已提交
17
import {IContextKey} from 'vs/platform/contextkey/common/contextkey';
D
Daniel Imms 已提交
18
import {IKeybindingService} from 'vs/platform/keybinding/common/keybinding';
C
Christof Marti 已提交
19
import {IMessageService, Severity} from 'vs/platform/message/common/message';
20 21
import {ITerminalInstance, ITerminalService} from 'vs/workbench/parts/terminal/electron-browser/terminal';
import {IStringDictionary} from 'vs/base/common/collections';
D
Daniel Imms 已提交
22
import {TerminalConfigHelper, IShell, ITerminalFont} from 'vs/workbench/parts/terminal/electron-browser/terminalConfigHelper';
D
Daniel Imms 已提交
23
import {IWorkspaceContextService, IWorkspace} from 'vs/platform/workspace/common/workspace';
24
import {Keybinding} from 'vs/base/common/keyCodes';
25
import {StandardKeyboardEvent} from 'vs/base/browser/keyboardEvent';
26
import {TabFocus} from 'vs/editor/common/config/commonEditorConfig';
27

28 29 30
export class TerminalInstance implements ITerminalInstance {
	private static ID_COUNTER = 1;
	private static EOL_REGEX = /\r?\n/g;
C
Christof Marti 已提交
31

D
Daniel Imms 已提交
32

33 34
	private _id: number;
	private _title: string;
D
Daniel Imms 已提交
35
	private _onTitleChanged: Emitter<string>;
36 37
	public get id(): number { return this._id; }
	public get title(): string { return this._title; }
D
Daniel Imms 已提交
38
	public get onTitleChanged(): Event<string> { return this._onTitleChanged.event; }
C
Christof Marti 已提交
39

40
	private isExiting: boolean = false;
41
	private toDispose: lifecycle.IDisposable[] = [];
42
	private skipTerminalKeybindings: Keybinding[] = [];
43 44 45
	private process: cp.ChildProcess;
	private xterm: any;
	// TODO: Improve HTML element names?
46
	private wrapperElement: HTMLDivElement;
47
	private terminalDomElement: HTMLDivElement;
48
	// TODO: Is font needed, just grab off configHelper?
D
Daniel Imms 已提交
49
	private font: ITerminalFont;
50 51

	public constructor(
52 53 54 55
		private terminalFocusContextKey: IContextKey<boolean>,
		private onExitCallback: (TerminalInstance) => void,
		private configHelper: TerminalConfigHelper,
		private container: HTMLElement,
56 57
		name: string,
		shellPath: string,
D
Daniel Imms 已提交
58
		@IKeybindingService private keybindingService: IKeybindingService,
D
Daniel Imms 已提交
59
		@IMessageService private messageService: IMessageService,
D
Daniel Imms 已提交
60 61
		@ITerminalService private terminalService: ITerminalService,
		@IWorkspaceContextService private contextService: IWorkspaceContextService
62
	) {
63
		this._id = TerminalInstance.ID_COUNTER++;
D
Daniel Imms 已提交
64
		this._onTitleChanged = new Emitter<string>();
65
		this.createProcess(name, shellPath);
66 67 68 69 70 71 72 73 74 75 76

		if (container) {
			this.attachToElement(container);
		}
	}

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

77 78
		this.setFont(this.configHelper.getFont());

79
		this.wrapperElement = document.createElement('div');
D
Tidy up  
Daniel Imms 已提交
80
		DOM.addClass(this.wrapperElement, 'terminal-wrapper');
81 82
		this.terminalDomElement = document.createElement('div');

D
Daniel Imms 已提交
83
		this.xterm = xterm();
84
		this.xterm.open(this.terminalDomElement);
85

D
Daniel Imms 已提交
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
		this.process.on('message', (message) => {
			if (message.type === 'data') {
				this.xterm.write(message.content);
			}
		});
		this.xterm.on('data', (data) => {
			this.process.send({
				event: 'input',
				data: this.sanitizeInput(data)
			});
			return false;
		});
		this.xterm.attachCustomKeydownHandler((event: KeyboardEvent) => {
			// Allow the toggle tab mode keybinding to pass through the terminal so that focus can
			// be escaped
			let standardKeyboardEvent = new StandardKeyboardEvent(event);
			if (this.skipTerminalKeybindings.some((k) => standardKeyboardEvent.equals(k.value))) {
				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;
			}
		});

113 114 115 116 117 118 119 120 121 122 123 124 125 126
		let xtermHelper: HTMLElement = this.xterm.element.querySelector('.xterm-helpers');
		let focusTrap: HTMLElement = document.createElement('div');
		focusTrap.setAttribute('tabindex', '0');
		DOM.addClass(focusTrap, 'focus-trap');
		focusTrap.addEventListener('focus', function (event: FocusEvent) {
			let currentElement = focusTrap;
			while (!DOM.hasClass(currentElement, 'part')) {
				currentElement = currentElement.parentElement;
			}
			let hidePanelElement = <HTMLElement>currentElement.querySelector('.hide-panel-action');
			hidePanelElement.focus();
		});
		xtermHelper.insertBefore(focusTrap, this.xterm.textarea);

127
		this.toDispose.push(DOM.addDisposableListener(this.xterm.textarea, 'focus', (event: KeyboardEvent) => {
D
Daniel Imms 已提交
128
			this.terminalFocusContextKey.set(true);
129 130
		}));
		this.toDispose.push(DOM.addDisposableListener(this.xterm.textarea, 'blur', (event: KeyboardEvent) => {
D
Daniel Imms 已提交
131
			this.terminalFocusContextKey.reset();
132
		}));
133
		this.toDispose.push(DOM.addDisposableListener(this.xterm.element, 'focus', (event: KeyboardEvent) => {
D
Daniel Imms 已提交
134
			this.terminalFocusContextKey.set(true);
135 136
		}));
		this.toDispose.push(DOM.addDisposableListener(this.xterm.element, 'blur', (event: KeyboardEvent) => {
D
Daniel Imms 已提交
137
			this.terminalFocusContextKey.reset();
138 139
		}));

140
		this.wrapperElement.appendChild(this.terminalDomElement);
141
		this.container.appendChild(this.wrapperElement);
142 143

		this.layout(new Dimension(this.container.offsetWidth, this.container.offsetHeight));
144 145
	}

D
Daniel Imms 已提交
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
	public copySelection(): void {
		// TODO: Implement
	}

	public dispose(): void {
		if (this.wrapperElement) {
			this.container.removeChild(this.wrapperElement);
			this.wrapperElement = null;
		}
		if (this.xterm) {
			this.xterm.destroy();
			this.xterm = null;
		}
		if (this.process) {
			if (this.process.connected) {
				this.process.disconnect();
				this.process.kill();
			}
			this.process = null;
		}
		this.toDispose = lifecycle.dispose(this.toDispose);
		this.onExitCallback(this);
	}

D
Daniel Imms 已提交
170 171 172 173 174 175 176 177 178
	// TODO: Document, the purpose of force is not clear
	public focus(force?: boolean): void {
		if (!this.xterm) {
			return;
		}
		let text = window.getSelection().toString();
		if (!text || force) {
			this.xterm.focus();
		}
D
Daniel Imms 已提交
179 180 181 182 183 184 185 186 187
	}

	public paste(): void {
		// TODO: Implement
	}

	public sendText(text: string, addNewLine: boolean): void {
		// TODO: Implement
	}
188 189 190

	public setVisible(visible: boolean): void {
		DOM.toggleClass(this.wrapperElement, 'active', visible);
191 192
	}

D
Daniel Imms 已提交
193 194 195 196 197 198 199
	public scrollDown(): void {
		// TODO: Implement
	}

	public scrollUp(): void {
		// TODO: Implement
	}
200

C
Christof Marti 已提交
201
	private sanitizeInput(data: any) {
202
		return typeof data === 'string' ? data.replace(TerminalInstance.EOL_REGEX, os.EOL) : data;
C
Christof Marti 已提交
203 204
	}

205
	private createProcess(name?: string, shellPath?: string) {
206
		let locale = this.configHelper.isSetLocaleVariables() ? platform.locale : undefined;
207 208
		let shell = shellPath ? { executable: shellPath, args: [] } : this.configHelper.getShell();
		let env = this.createTerminalEnv(process.env, shell, this.contextService.getWorkspace(), locale);
209 210 211 212 213 214 215 216 217
		this._title = name ? name : '';
		this.process = cp.fork('./terminalProcess', [], {
			env: env,
			cwd: URI.parse(path.dirname(require.toUrl('./terminalProcess'))).fsPath
		});
		if (!name) {
			// Only listen for process title changes when a name is not provided
			this.process.on('message', (message) => {
				if (message.type === 'title') {
D
Daniel Imms 已提交
218
					this._title = message.content ? message.content : '';
219
					// TODO: Send title change notification to service/panel
D
Daniel Imms 已提交
220
					this._onTitleChanged.fire();
221
				}
222 223
			});
		}
224 225 226 227 228 229 230 231 232 233
		this.process.on('exit', (exitCode) => {
			// Prevent dispose functions being triggered multiple times
			if (!this.isExiting) {
				this.isExiting = true;
				this.dispose();
				if (exitCode) {
					this.messageService.show(Severity.Error, nls.localize('terminal.integrated.exitedWithCode', 'The terminal process terminated with exit code: {0}', exitCode));
				}
			}
		});
234 235
	}

236 237 238 239 240 241 242 243 244 245 246 247
	public createTerminalEnv(parentEnv: IStringDictionary<string>, shell: IShell, workspace: IWorkspace, locale?: string): IStringDictionary<string> {
		let env = this.cloneEnv(parentEnv);
		env['PTYPID'] = process.pid.toString();
		env['PTYSHELL'] = shell.executable;
		shell.args.forEach((arg, i) => {
			env[`PTYSHELLARG${i}`] = arg;
		});
		env['PTYCWD'] = this.sanitizeCwd(workspace ? workspace.resource.fsPath : os.homedir());
		if (locale) {
			env['LANG'] = this.getLangEnvVariable(locale);
		}
		return env;
248 249
	}

250 251 252 253
	private sanitizeCwd(cwd: string) {
		// 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 已提交
254
		}
255
		return cwd;
D
Daniel Imms 已提交
256 257
	}

258 259 260 261
	private cloneEnv(env: IStringDictionary<string>): IStringDictionary<string> {
		let newEnv: IStringDictionary<string> = Object.create(null);
		Object.keys(env).forEach((key) => {
			newEnv[key] = env[key];
262
		});
263
		return newEnv;
264 265
	}

266 267 268 269 270
	private getLangEnvVariable(locale: string) {
		const parts = locale.split('-');
		const n = parts.length;
		if (n > 1) {
			parts[n - 1] = parts[n - 1].toUpperCase();
D
Daniel Imms 已提交
271
		}
272
		return parts.join('_') + '.UTF-8';
D
Daniel Imms 已提交
273
	}
D
Daniel Imms 已提交
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316

	public setFont(font: ITerminalFont): void {
		this.font = font;
	}

	public setCursorBlink(blink: boolean): void {
		if (this.xterm && this.xterm.cursorBlink !== blink) {
			this.xterm.cursorBlink = blink;
			this.xterm.refresh(0, this.xterm.rows - 1);
		}
	}

	public setCommandsToSkipShell(commands: string[]): void {
		this.skipTerminalKeybindings = commands.map((c) => {
			return this.keybindingService.lookupKeybindings(c);
		}).reduce((prev, curr) => {
			return prev.concat(curr);
		});
	}

	public layout(dimension: Dimension): void {
		if (!this.font || !this.font.charWidth || !this.font.charHeight) {
			return;
		}
		if (!dimension.height) { // Minimized
			return;
		}
		let leftPadding = parseInt(getComputedStyle(document.querySelector('.terminal-outer-container')).paddingLeft.split('px')[0], 10);
		let innerWidth = dimension.width - leftPadding;
		let cols = Math.floor(innerWidth / this.font.charWidth);
		let rows = Math.floor(dimension.height / this.font.charHeight);
		if (this.xterm) {
			this.xterm.resize(cols, rows);
			this.xterm.element.style.width = innerWidth + 'px';
		}
		if (this.process.connected) {
			this.process.send({
				event: 'resize',
				cols: cols,
				rows: rows
			});
		}
	}
317
}
D
Daniel Imms 已提交
318

319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
// import DOM = require('vs/base/browser/dom');
// import URI from 'vs/base/common/uri';
// import cp = require('child_process');
// import lifecycle = require('vs/base/common/lifecycle');
// import nls = require('vs/nls');
// import os = require('os');
// import path = require('path');
// import platform = require('vs/base/common/platform');
// import xterm = require('xterm');
// import {Dimension} from 'vs/base/browser/builder';
// import {IContextMenuService} from 'vs/platform/contextview/browser/contextView';
// import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation';
// import {IKeybindingService} from 'vs/platform/keybinding/common/keybinding';
// import {IContextKey} from 'vs/platform/contextkey/common/contextkey';
// import {IMessageService, Severity} from 'vs/platform/message/common/message';
// import {ITerminalFont} from 'vs/workbench/parts/terminal/electron-browser/terminalConfigHelper';
// import {ITerminalInstance, ITerminalService} from 'vs/workbench/parts/terminal/electron-browser/terminal';
// import {IStringDictionary} from 'vs/base/common/collections';
// import {IShell, TerminalConfigHelper} from 'vs/workbench/parts/terminal/electron-browser/terminalConfigHelper';
// import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace';
// import {Keybinding} from 'vs/base/common/keyCodes';
// import {StandardKeyboardEvent} from 'vs/base/browser/keyboardEvent';
// import {TabFocus} from 'vs/editor/common/config/commonEditorConfig';
342

343
// export class TerminalInstance {
344

345
// 	public id: number;
346

347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
// 	private static eolRegex = /\r?\n/g;

// 	private isExiting: boolean = false;
// 	private skipTerminalKeybindings: Keybinding[] = [];

// 	private toDispose: lifecycle.IDisposable[];
// 	private xterm;
// 	private terminalDomElement: HTMLDivElement;
// 	private wrapperElement: HTMLDivElement;
// 	private font: ITerminalFont;

// 	public constructor(
// 		private terminalProcess: ITerminalProcess,
// 		private parentDomElement: HTMLElement,
// 		private contextMenuService: IContextMenuService,
// 		private contextService: IWorkspaceContextService,
// 		private instantiationService: IInstantiationService,
// 		private keybindingService: IKeybindingService,
// 		private terminalService: ITerminalService,
// 		private messageService: IMessageService,
// 		private terminalFocusContextKey: IContextKey<boolean>,
// 		private onExitCallback: (TerminalInstance) => void
// 	) {
// 		this.toDispose = [];
// 		this.wrapperElement = document.createElement('div');
// 		DOM.addClass(this.wrapperElement, 'terminal-wrapper');
// 		this.terminalDomElement = document.createElement('div');
// 		this.xterm = xterm();

// 		this.id = this.terminalProcess.process.pid;
// 		this.terminalProcess.process.on('message', (message) => {
// 			if (message.type === 'data') {
// 				this.xterm.write(message.content);
// 			}
// 		});
// 		this.xterm.on('data', (data) => {
// 			this.terminalProcess.process.send({
// 				event: 'input',
// 				data: this.sanitizeInput(data)
// 			});
// 			return false;
// 		});
// 		this.xterm.attachCustomKeydownHandler((event: KeyboardEvent) => {
// 			// Allow the toggle tab mode keybinding to pass through the terminal so that focus can
// 			// be escaped
// 			let standardKeyboardEvent = new StandardKeyboardEvent(event);
// 			if (this.skipTerminalKeybindings.some((k) => standardKeyboardEvent.equals(k.value))) {
// 				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;
// 			}
// 		});
// 		this.terminalProcess.process.on('exit', (exitCode) => {
// 			// Prevent dispose functions being triggered multiple times
// 			if (!this.isExiting) {
// 				this.isExiting = true;
// 				this.dispose();
// 				if (exitCode) {
// 					this.messageService.show(Severity.Error, nls.localize('terminal.integrated.exitedWithCode', 'The terminal process terminated with exit code: {0}', exitCode));
// 				}
// 				this.onExitCallback(this);
// 			}
// 		});

// 		this.xterm.open(this.terminalDomElement);


// 		let xtermHelper: HTMLElement = this.xterm.element.querySelector('.xterm-helpers');
// 		let focusTrap: HTMLElement = document.createElement('div');
// 		focusTrap.setAttribute('tabindex', '0');
// 		DOM.addClass(focusTrap, 'focus-trap');
// 		focusTrap.addEventListener('focus', function (event: FocusEvent) {
// 			let currentElement = focusTrap;
// 			while (!DOM.hasClass(currentElement, 'part')) {
// 				currentElement = currentElement.parentElement;
// 			}
// 			let hidePanelElement = <HTMLElement>currentElement.querySelector('.hide-panel-action');
// 			hidePanelElement.focus();
// 		});
// 		xtermHelper.insertBefore(focusTrap, this.xterm.textarea);

// 		this.toDispose.push(DOM.addDisposableListener(this.xterm.textarea, 'focus', (event: KeyboardEvent) => {
// 			this.terminalFocusContextKey.set(true);
// 		}));
// 		this.toDispose.push(DOM.addDisposableListener(this.xterm.textarea, 'blur', (event: KeyboardEvent) => {
// 			this.terminalFocusContextKey.reset();
// 		}));
// 		this.toDispose.push(DOM.addDisposableListener(this.xterm.element, 'focus', (event: KeyboardEvent) => {
// 			this.terminalFocusContextKey.set(true);
// 		}));
// 		this.toDispose.push(DOM.addDisposableListener(this.xterm.element, 'blur', (event: KeyboardEvent) => {
// 			this.terminalFocusContextKey.reset();
// 		}));

// 		this.wrapperElement.appendChild(this.terminalDomElement);
// 		this.parentDomElement.appendChild(this.wrapperElement);
// 	}

// 	private sanitizeInput(data: any) {
// 		return typeof data === 'string' ? data.replace(TerminalInstance.eolRegex, os.EOL) : data;
// 	}

// 	public layout(dimension: Dimension): void {
// 		if (!this.font || !this.font.charWidth || !this.font.charHeight) {
// 			return;
// 		}
// 		if (!dimension.height) { // Minimized
// 			return;
// 		}
// 		let leftPadding = parseInt(getComputedStyle(document.querySelector('.terminal-outer-container')).paddingLeft.split('px')[0], 10);
// 		let innerWidth = dimension.width - leftPadding;
// 		let cols = Math.floor(innerWidth / this.font.charWidth);
// 		let rows = Math.floor(dimension.height / this.font.charHeight);
// 		if (this.xterm) {
// 			this.xterm.resize(cols, rows);
// 			this.xterm.element.style.width = innerWidth + 'px';
// 		}
// 		if (this.terminalProcess.process.connected) {
// 			this.terminalProcess.process.send({
// 				event: 'resize',
// 				cols: cols,
// 				rows: rows
// 			});
// 		}
// 	}

// 	public toggleVisibility(visible: boolean) {
// 		DOM.toggleClass(this.wrapperElement, 'active', visible);
// 	}

// 	public setFont(font: ITerminalFont): void {
// 		this.font = font;
// 	}

// 	public setCursorBlink(blink: boolean): void {
// 		if (this.xterm && this.xterm.cursorBlink !== blink) {
// 			this.xterm.cursorBlink = blink;
// 			this.xterm.refresh(0, this.xterm.rows - 1);
// 		}
// 	}

// 	public setCommandsToSkipShell(commands: string[]): void {
// 		this.skipTerminalKeybindings = commands.map((c) => {
// 			return this.keybindingService.lookupKeybindings(c);
// 		}).reduce((prev, curr) => {
// 			return prev.concat(curr);
// 		});
// 	}

// 	public sendText(text: string, addNewLine: boolean): void {;
// 		if (addNewLine && text.substr(text.length - os.EOL.length) !== os.EOL) {
// 			text += os.EOL;
// 		}
// 		this.terminalProcess.process.send({
// 			event: 'input',
// 			data: text
// 		});
// 	}

// 	public focus(force?: boolean): void {
// 		if (!this.xterm) {
// 			return;
// 		}
// 		let text = window.getSelection().toString();
// 		if (!text || force) {
// 			this.xterm.focus();
// 		}
// 	}

// 	public scrollDown(): void {
// 		this.xterm.scrollDisp(1);
// 	}

// 	public scrollUp(): void {
// 		this.xterm.scrollDisp(-1);
// 	}

// 	public dispose(): void {
// 		if (this.wrapperElement) {
// 			this.parentDomElement.removeChild(this.wrapperElement);
// 			this.wrapperElement = null;
// 		}
// 		if (this.xterm) {
// 			this.xterm.destroy();
// 			this.xterm = null;
// 		}
// 		if (this.terminalProcess) {
// 			this.terminalService.killTerminalProcess(this.terminalProcess);
// 			this.terminalProcess = null;
// 		}
// 		this.toDispose = lifecycle.dispose(this.toDispose);
// 	}
// }