terminalInstance.ts 17.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');
7 8
import URI from 'vs/base/common/uri';
import cp = require('child_process');
9
import lifecycle = require('vs/base/common/lifecycle');
C
Christof Marti 已提交
10
import nls = require('vs/nls');
C
Christof Marti 已提交
11
import os = require('os');
12 13
import path = require('path');
import platform = require('vs/base/common/platform');
14
import xterm = require('xterm');
D
Daniel Imms 已提交
15
import {Dimension} from 'vs/base/browser/builder';
A
Alex Dima 已提交
16
import {IContextKey} from 'vs/platform/contextkey/common/contextkey';
D
Daniel Imms 已提交
17
import {IKeybindingService} from 'vs/platform/keybinding/common/keybinding';
C
Christof Marti 已提交
18
import {IMessageService, Severity} from 'vs/platform/message/common/message';
19 20
import {ITerminalInstance, ITerminalService} from 'vs/workbench/parts/terminal/electron-browser/terminal';
import {IStringDictionary} from 'vs/base/common/collections';
D
Daniel Imms 已提交
21
import {TerminalConfigHelper, IShell, ITerminalFont} from 'vs/workbench/parts/terminal/electron-browser/terminalConfigHelper';
D
Daniel Imms 已提交
22
import {IWorkspaceContextService, IWorkspace} from 'vs/platform/workspace/common/workspace';
23
import {Keybinding} from 'vs/base/common/keyCodes';
24
import {StandardKeyboardEvent} from 'vs/base/browser/keyboardEvent';
25
import {TabFocus} from 'vs/editor/common/config/commonEditorConfig';
26

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

31 32 33 34
	private _id: number;
	private _title: string;
	public get id(): number { return this._id; }
	public get title(): string { return this._title; }
C
Christof Marti 已提交
35

36
	private isExiting: boolean = false;
37
	private toDispose: lifecycle.IDisposable[] = [];
38
	private skipTerminalKeybindings: Keybinding[] = [];
39 40 41
	private process: cp.ChildProcess;
	private xterm: any;
	// TODO: Improve HTML element names?
42
	private wrapperElement: HTMLDivElement;
43
	private terminalDomElement: HTMLDivElement;
D
Daniel Imms 已提交
44
	private font: ITerminalFont;
45 46

	public constructor(
47 48 49 50
		private terminalFocusContextKey: IContextKey<boolean>,
		private onExitCallback: (TerminalInstance) => void,
		private configHelper: TerminalConfigHelper,
		private container: HTMLElement,
51 52
		name: string,
		shellPath: string,
D
Daniel Imms 已提交
53
		@IKeybindingService private keybindingService: IKeybindingService,
D
Daniel Imms 已提交
54
		@IMessageService private messageService: IMessageService,
D
Daniel Imms 已提交
55 56
		@ITerminalService private terminalService: ITerminalService,
		@IWorkspaceContextService private contextService: IWorkspaceContextService
57
	) {
58
		this._id = TerminalInstance.ID_COUNTER++;
59
		this.createProcess(name, shellPath);
60 61

		if (container) {
D
Daniel Imms 已提交
62
			console.log('attach to element', container);
63 64 65 66 67 68 69 70 71
			this.attachToElement(container);
		}
	}

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

72
		this.wrapperElement = document.createElement('div');
D
Tidy up  
Daniel Imms 已提交
73
		DOM.addClass(this.wrapperElement, 'terminal-wrapper');
74 75
		this.terminalDomElement = document.createElement('div');

D
Daniel Imms 已提交
76
		this.xterm = xterm();
77
		this.xterm.open(this.terminalDomElement);
78

D
Daniel Imms 已提交
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
		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;
			}
		});

106 107 108 109 110 111 112 113 114 115 116 117 118 119
		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);

120
		this.toDispose.push(DOM.addDisposableListener(this.xterm.textarea, 'focus', (event: KeyboardEvent) => {
D
Daniel Imms 已提交
121
			this.terminalFocusContextKey.set(true);
122 123
		}));
		this.toDispose.push(DOM.addDisposableListener(this.xterm.textarea, 'blur', (event: KeyboardEvent) => {
D
Daniel Imms 已提交
124
			this.terminalFocusContextKey.reset();
125
		}));
126
		this.toDispose.push(DOM.addDisposableListener(this.xterm.element, 'focus', (event: KeyboardEvent) => {
D
Daniel Imms 已提交
127
			this.terminalFocusContextKey.set(true);
128 129
		}));
		this.toDispose.push(DOM.addDisposableListener(this.xterm.element, 'blur', (event: KeyboardEvent) => {
D
Daniel Imms 已提交
130
			this.terminalFocusContextKey.reset();
131 132
		}));

133
		this.wrapperElement.appendChild(this.terminalDomElement);
134 135 136 137 138 139 140 141 142 143 144
		this.container.appendChild(this.wrapperElement);
	}

	public copySelection(): void {}
	public dispose(): void {}
	public focus(): void {}
	public paste(): void {}
	public sendText(text: string, addNewLine: boolean): void {}

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

147 148 149
	public scrollDown(): void {}
	public scrollUp(): void {}

C
Christof Marti 已提交
150
	private sanitizeInput(data: any) {
151
		return typeof data === 'string' ? data.replace(TerminalInstance.EOL_REGEX, os.EOL) : data;
C
Christof Marti 已提交
152 153
	}

154
	private createProcess(name?: string, shellPath?: string) {
155
		let locale = this.configHelper.isSetLocaleVariables() ? platform.locale : undefined;
156 157
		let shell = shellPath ? { executable: shellPath, args: [] } : this.configHelper.getShell();
		let env = this.createTerminalEnv(process.env, shell, this.contextService.getWorkspace(), locale);
158 159 160 161 162 163 164 165 166 167 168 169 170
		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') {
					process.title = message.content ? message.content : '';
					// TODO: Send title change notification to service/panel
					//this._onInstanceTitleChanged.fire();
				}
171 172
			});
		}
173 174 175 176 177 178 179 180 181 182 183
		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));
				}
				this.onExitCallback(this);
			}
		});
184 185
	}

186 187 188 189 190 191 192 193 194 195 196 197
	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;
198 199
	}

200 201 202 203
	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 已提交
204
		}
205
		return cwd;
D
Daniel Imms 已提交
206 207
	}

208 209 210 211
	private cloneEnv(env: IStringDictionary<string>): IStringDictionary<string> {
		let newEnv: IStringDictionary<string> = Object.create(null);
		Object.keys(env).forEach((key) => {
			newEnv[key] = env[key];
212
		});
213
		return newEnv;
214 215
	}

216 217 218 219 220
	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 已提交
221
		}
222
		return parts.join('_') + '.UTF-8';
D
Daniel Imms 已提交
223
	}
D
Daniel Imms 已提交
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266

	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
			});
		}
	}
267
}
D
Daniel Imms 已提交
268

269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
// 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';
292

293
// export class TerminalInstance {
294

295
// 	public id: number;
296

297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 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
// 	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);
// 	}
// }