terminalInstance.ts 16.1 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');
A
Alex Dima 已提交
15
import {IContextKey} from 'vs/platform/contextkey/common/contextkey';
C
Christof Marti 已提交
16
import {IMessageService, Severity} from 'vs/platform/message/common/message';
17 18 19
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';
20
import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace';
21
import {Keybinding} from 'vs/base/common/keyCodes';
22
import {StandardKeyboardEvent} from 'vs/base/browser/keyboardEvent';
23
import {TabFocus} from 'vs/editor/common/config/commonEditorConfig';
24

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

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

34
	private isExiting: boolean = false;
35
	private toDispose: lifecycle.IDisposable[] = [];
36
	private skipTerminalKeybindings: Keybinding[] = [];
37 38 39
	private process: cp.ChildProcess;
	private xterm: any;
	// TODO: Improve HTML element names?
40
	private wrapperElement: HTMLDivElement;
41
	private terminalDomElement: HTMLDivElement;
42 43

	public constructor(
44 45 46 47
		private terminalFocusContextKey: IContextKey<boolean>,
		private onExitCallback: (TerminalInstance) => void,
		private configHelper: TerminalConfigHelper,
		private container: HTMLElement,
48
		private contextService: IWorkspaceContextService,
C
Christof Marti 已提交
49
		private messageService: IMessageService,
50
		private terminalService: ITerminalService
51
	) {
52 53 54 55 56 57 58 59 60 61 62 63 64
		this._id = TerminalInstance.ID_COUNTER++;
		this.createProcess();

		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');
		}

65
		this.wrapperElement = document.createElement('div');
D
Tidy up  
Daniel Imms 已提交
66
		DOM.addClass(this.wrapperElement, 'terminal-wrapper');
67 68
		this.terminalDomElement = document.createElement('div');

69
		this.xterm.open(this.terminalDomElement);
70

71 72 73
		this.wrapperElement = document.createElement('div');
		DOM.addClass(this.wrapperElement, 'terminal-wrapper');
		this.terminalDomElement = document.createElement('div');
74 75 76 77 78 79 80 81 82 83 84 85 86 87
		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);

88
		this.toDispose.push(DOM.addDisposableListener(this.xterm.textarea, 'focus', (event: KeyboardEvent) => {
D
Daniel Imms 已提交
89
			this.terminalFocusContextKey.set(true);
90 91
		}));
		this.toDispose.push(DOM.addDisposableListener(this.xterm.textarea, 'blur', (event: KeyboardEvent) => {
D
Daniel Imms 已提交
92
			this.terminalFocusContextKey.reset();
93
		}));
94
		this.toDispose.push(DOM.addDisposableListener(this.xterm.element, 'focus', (event: KeyboardEvent) => {
D
Daniel Imms 已提交
95
			this.terminalFocusContextKey.set(true);
96 97
		}));
		this.toDispose.push(DOM.addDisposableListener(this.xterm.element, 'blur', (event: KeyboardEvent) => {
D
Daniel Imms 已提交
98
			this.terminalFocusContextKey.reset();
99 100
		}));

101
		this.wrapperElement.appendChild(this.terminalDomElement);
102 103 104 105 106 107 108 109 110 111 112
		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);
113 114
	}

115 116 117
	public scrollDown(): void {}
	public scrollUp(): void {}

C
Christof Marti 已提交
118
	private sanitizeInput(data: any) {
119
		return typeof data === 'string' ? data.replace(TerminalInstance.EOL_REGEX, os.EOL) : data;
C
Christof Marti 已提交
120 121
	}

122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
	private createProcess(name?: string) {
		let locale = this.configHelper.isSetLocaleVariables() ? platform.locale : undefined;
		let env = this.createTerminalEnv(process.env, this.configHelper.getShell(), this.contextService.getWorkspace(), locale);
		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();
				}
138 139
			});
		}
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
		this.xterm = xterm();
		this.process.on('message', (message) => {
			if (message.type === 'data') {
				this.xterm.write(message.content);
			}
		});
		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);
			}
		});
		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;
			}
172

173 174 175 176 177
			// If tab focus mode is on, tab is not passed to the terminal
			if (TabFocus.getTabFocusMode() && event.keyCode === 9) {
				return false;
			}
		});
178 179
	}

180 181 182 183 184 185 186 187 188 189 190 191
	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;
192 193
	}

194 195 196 197
	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 已提交
198
		}
199
		return cwd;
D
Daniel Imms 已提交
200 201
	}

202 203 204 205
	private cloneEnv(env: IStringDictionary<string>): IStringDictionary<string> {
		let newEnv: IStringDictionary<string> = Object.create(null);
		Object.keys(env).forEach((key) => {
			newEnv[key] = env[key];
206
		});
207
		return newEnv;
208 209
	}

210 211 212 213 214
	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 已提交
215
		}
216
		return parts.join('_') + '.UTF-8';
D
Daniel Imms 已提交
217
	}
218
}
D
Daniel Imms 已提交
219

220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
// 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';
243

244
// export class TerminalInstance {
245

246
// 	public id: number;
247

248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 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 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
// 	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);
// 	}
// }