terminalInstance.ts 10.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');
16 17 18 19 20 21 22 23 24 25 26
import { Dimension } from 'vs/base/browser/builder';
import { IContextKey } from 'vs/platform/contextkey/common/contextkey';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IMessageService, Severity } from 'vs/platform/message/common/message';
import { IStringDictionary } from 'vs/base/common/collections';
import { ITerminalInstance } from 'vs/workbench/parts/terminal/electron-browser/terminal';
import { IWorkspace } 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';
import { TerminalConfigHelper, IShell } from 'vs/workbench/parts/terminal/electron-browser/terminalConfigHelper';
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
	private process: cp.ChildProcess;
	private xterm: any;
45
	private wrapperElement: HTMLDivElement;
D
Daniel Imms 已提交
46
	private xtermElement: HTMLDivElement;
47 48

	public constructor(
49 50 51 52
		private terminalFocusContextKey: IContextKey<boolean>,
		private onExitCallback: (TerminalInstance) => void,
		private configHelper: TerminalConfigHelper,
		private container: HTMLElement,
53
		private workspace: IWorkspace,
54 55
		name: string,
		shellPath: string,
D
Daniel Imms 已提交
56
		@IKeybindingService private keybindingService: IKeybindingService,
57
		@IMessageService private messageService: IMessageService
58
	) {
59
		this._id = TerminalInstance.ID_COUNTER++;
D
Daniel Imms 已提交
60
		this._onTitleChanged = new Emitter<string>();
61
		this.createProcess(workspace, name, shellPath);
62 63 64 65 66 67

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

D
Daniel Imms 已提交
68 69 70 71
	public addDisposable(disposable: lifecycle.IDisposable): void {
		this.toDispose.push(disposable);
	}

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

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

D
Daniel Imms 已提交
81
		this.xterm = xterm();
D
Daniel Imms 已提交
82
		this.xterm.open(this.xtermElement);
83

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

111 112 113 114 115 116 117 118 119 120 121 122 123 124
		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);

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

D
Daniel Imms 已提交
138
		this.wrapperElement.appendChild(this.xtermElement);
139
		this.container.appendChild(this.wrapperElement);
140 141

		this.layout(new Dimension(this.container.offsetWidth, this.container.offsetHeight));
142 143
	}

D
Daniel Imms 已提交
144
	public copySelection(): void {
D
Daniel Imms 已提交
145 146 147 148 149
		if (document.activeElement.classList.contains('xterm')) {
			document.execCommand('copy');
		} else {
			this.messageService.show(Severity.Warning, nls.localize('terminal.integrated.copySelection.noSelection', 'Cannot copy terminal selection when terminal does not have focus'));
		}
D
Daniel Imms 已提交
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
	}

	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 已提交
172 173 174 175 176 177 178 179
	public focus(force?: boolean): void {
		if (!this.xterm) {
			return;
		}
		let text = window.getSelection().toString();
		if (!text || force) {
			this.xterm.focus();
		}
D
Daniel Imms 已提交
180 181 182
	}

	public paste(): void {
D
Daniel Imms 已提交
183 184
		this.focus();
		document.execCommand('paste');
D
Daniel Imms 已提交
185 186 187
	}

	public sendText(text: string, addNewLine: boolean): void {
D
Daniel Imms 已提交
188 189 190 191 192 193 194
		if (addNewLine && text.substr(text.length - os.EOL.length) !== os.EOL) {
			text += os.EOL;
		}
		this.process.send({
			event: 'input',
			data: text
		});
D
Daniel Imms 已提交
195
	}
196 197 198

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

D
Daniel Imms 已提交
201
	public scrollDown(): void {
D
Daniel Imms 已提交
202
		this.xterm.scrollDisp(1);
D
Daniel Imms 已提交
203 204 205
	}

	public scrollUp(): void {
D
Daniel Imms 已提交
206
		this.xterm.scrollDisp(-1);
D
Daniel Imms 已提交
207
	}
208

C
Christof Marti 已提交
209
	private sanitizeInput(data: any) {
210
		return typeof data === 'string' ? data.replace(TerminalInstance.EOL_REGEX, os.EOL) : data;
C
Christof Marti 已提交
211 212
	}

213
	private createProcess(workspace: IWorkspace, name?: string, shellPath?: string) {
214
		let locale = this.configHelper.isSetLocaleVariables() ? platform.locale : undefined;
215
		let shell = shellPath ? { executable: shellPath, args: [] } : this.configHelper.getShell();
216
		let env = this.createTerminalEnv(process.env, shell, workspace, locale);
217 218 219 220 221 222 223 224 225
		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 已提交
226 227
					this._title = message.content ? message.content : '';
					this._onTitleChanged.fire();
228
				}
229 230
			});
		}
231 232 233 234 235 236 237 238 239 240
		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));
				}
			}
		});
241 242
	}

243 244 245 246 247 248 249 250 251 252 253 254
	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;
255 256
	}

257 258 259 260
	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 已提交
261
		}
262
		return cwd;
D
Daniel Imms 已提交
263 264
	}

265 266 267 268
	private cloneEnv(env: IStringDictionary<string>): IStringDictionary<string> {
		let newEnv: IStringDictionary<string> = Object.create(null);
		Object.keys(env).forEach((key) => {
			newEnv[key] = env[key];
269
		});
270
		return newEnv;
271 272
	}

273 274 275 276 277
	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 已提交
278
		}
279
		return parts.join('_') + '.UTF-8';
D
Daniel Imms 已提交
280
	}
D
Daniel Imms 已提交
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297

	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 {
298 299
		let font = this.configHelper.getFont();
		if (!font || !font.charWidth || !font.charHeight) {
D
Daniel Imms 已提交
300 301 302 303 304 305 306
			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;
307 308
		let cols = Math.floor(innerWidth / font.charWidth);
		let rows = Math.floor(dimension.height / font.charHeight);
D
Daniel Imms 已提交
309 310 311 312 313 314 315 316 317 318 319 320
		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
			});
		}
	}
321
}