windows.ts 46.8 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

'use strict';

J
Joao Moreno 已提交
8
import * as path from 'path';
B
Benjamin Pasero 已提交
9
import * as os from 'os';
B
Benjamin Pasero 已提交
10
import * as fs from 'original-fs';
J
Joao Moreno 已提交
11 12 13
import * as platform from 'vs/base/common/platform';
import * as nls from 'vs/nls';
import * as paths from 'vs/base/common/paths';
14
import * as types from 'vs/base/common/types';
J
Joao Moreno 已提交
15
import * as arrays from 'vs/base/common/arrays';
16
import { assign, mixin } from 'vs/base/common/objects';
J
Joao Moreno 已提交
17
import { EventEmitter } from 'events';
18
import { IBackupService } from 'vs/code/electron-main/backup';
19
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
J
Joao Moreno 已提交
20
import { IStorageService } from 'vs/code/electron-main/storage';
21
import { IPath, VSCodeWindow, ReadyState, IWindowConfiguration, IWindowState as ISingleWindowState, defaultWindowState, IWindowSettings } from 'vs/code/electron-main/window';
B
Benjamin Pasero 已提交
22
import { ipcMain as ipc, app, screen, crashReporter, BrowserWindow, dialog, shell } from 'electron';
23
import { IPathWithLineAndColumn, parseLineAndColumnAware } from 'vs/code/electron-main/paths';
24
import { ILifecycleService } from 'vs/code/electron-main/lifecycle';
25
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
J
Joao Moreno 已提交
26
import { IUpdateService, IUpdate } from 'vs/code/electron-main/update-manager';
B
Benjamin Pasero 已提交
27
import { ILogService } from 'vs/code/electron-main/log';
S
Sandeep Somavarapu 已提交
28
import { IWindowEventService } from 'vs/code/common/windows';
J
Johannes Rieken 已提交
29
import { createDecorator, IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
S
Sandeep Somavarapu 已提交
30
import CommonEvent, { Emitter } from 'vs/base/common/event';
B
Benjamin Pasero 已提交
31
import product from 'vs/platform/product';
32
import Uri from 'vs/base/common/uri';
B
Benjamin Pasero 已提交
33
import { ParsedArgs } from 'vs/platform/environment/node/argv';
E
Erich Gamma 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46

const EventTypes = {
	OPEN: 'open',
	CLOSE: 'close',
	READY: 'ready'
};

enum WindowError {
	UNRESPONSIVE,
	CRASHED
}

export interface IOpenConfiguration {
B
Benjamin Pasero 已提交
47
	cli: ParsedArgs;
48
	userEnv?: platform.IProcessEnvironment;
E
Erich Gamma 已提交
49
	pathsToOpen?: string[];
50
	preferNewWindow?: boolean;
E
Erich Gamma 已提交
51 52
	forceNewWindow?: boolean;
	forceEmpty?: boolean;
J
Joao Moreno 已提交
53
	windowToUse?: VSCodeWindow;
54
	diffMode?: boolean;
55
	restoreBackups?: boolean;
E
Erich Gamma 已提交
56 57 58 59
}

interface IWindowState {
	workspacePath?: string;
J
Joao Moreno 已提交
60
	uiState: ISingleWindowState;
E
Erich Gamma 已提交
61 62 63 64 65 66 67 68
}

interface IWindowsState {
	lastActiveWindow?: IWindowState;
	lastPluginDevelopmentHostWindow?: IWindowState;
	openedFolders: IWindowState[];
}

69
export interface IRecentPathsList {
E
Erich Gamma 已提交
70 71 72 73
	folders: string[];
	files: string[];
}

74 75 76 77 78
interface ILogEntry {
	severity: string;
	arguments: any;
}

79 80 81
interface INativeOpenDialogOptions {
	pickFolders?: boolean;
	pickFiles?: boolean;
82 83
	path?: string;
	forceNewWindow?: boolean;
84 85
}

86 87 88 89 90 91
const ReopenFoldersSetting = {
	ALL: 'all',
	ONE: 'one',
	NONE: 'none'
};

J
renames  
Joao Moreno 已提交
92
export const IWindowsService = createDecorator<IWindowsService>('windowsService');
J
Joao Moreno 已提交
93

J
renames  
Joao Moreno 已提交
94
export interface IWindowsService {
95
	_serviceBrand: any;
J
Joao Moreno 已提交
96 97 98

	// TODO make proper events
	// events
J
Joao Moreno 已提交
99 100
	onOpen(clb: (path: IPath) => void): () => void;
	onReady(clb: (win: VSCodeWindow) => void): () => void;
J
Joao Moreno 已提交
101
	onClose(clb: (id: number) => void): () => void;
S
Sandeep Somavarapu 已提交
102 103
	onNewWindowOpen: CommonEvent<number>;
	onWindowFocus: CommonEvent<number>;
J
Joao Moreno 已提交
104 105

	// methods
106
	ready(initialUserEnv: platform.IProcessEnvironment): void;
B
Benjamin Pasero 已提交
107
	reload(win: VSCodeWindow, cli?: ParsedArgs): void;
J
Joao Moreno 已提交
108
	open(openConfig: IOpenConfiguration): VSCodeWindow[];
J
Joao Moreno 已提交
109 110 111 112
	openPluginDevelopmentHostWindow(openConfig: IOpenConfiguration): void;
	openFileFolderPicker(forceNewWindow?: boolean): void;
	openFilePicker(forceNewWindow?: boolean): void;
	openFolderPicker(forceNewWindow?: boolean): void;
113
	openAccessibilityOptions(): void;
B
Benjamin Pasero 已提交
114
	focusLastActive(cli: ParsedArgs): VSCodeWindow;
J
Joao Moreno 已提交
115 116
	getLastActiveWindow(): VSCodeWindow;
	findWindow(workspacePath: string, filePath?: string, extensionDevelopmentPath?: string): VSCodeWindow;
J
Joao Moreno 已提交
117 118 119
	openNewWindow(): void;
	sendToFocused(channel: string, ...args: any[]): void;
	sendToAll(channel: string, payload: any, windowIdsToIgnore?: number[]): void;
J
Joao Moreno 已提交
120 121 122
	getFocusedWindow(): VSCodeWindow;
	getWindowById(windowId: number): VSCodeWindow;
	getWindows(): VSCodeWindow[];
J
Joao Moreno 已提交
123
	getWindowCount(): number;
124 125 126
	getRecentPathsList(): IRecentPathsList;
	removeFromRecentPathsList(path: string);
	clearRecentPathsList(): void;
J
Joao Moreno 已提交
127 128
}

S
Sandeep Somavarapu 已提交
129 130 131 132
export class WindowEventService implements IWindowEventService {

	_serviceBrand: any;

J
Johannes Rieken 已提交
133
	constructor( @IWindowsService private windowsService: IWindowsService) { }
S
Sandeep Somavarapu 已提交
134 135 136 137 138 139 140 141 142 143

	public get onWindowFocus(): CommonEvent<number> {
		return this.windowsService.onWindowFocus;
	}

	public get onNewWindowOpen(): CommonEvent<number> {
		return this.windowsService.onNewWindowOpen;
	}
}

J
renames  
Joao Moreno 已提交
144
export class WindowsManager implements IWindowsService {
J
Joao Moreno 已提交
145

146
	_serviceBrand: any;
E
Erich Gamma 已提交
147

148
	private static MAX_TOTAL_RECENT_ENTRIES = 100;
149

150
	private static recentPathsListStorageKey = 'openedPathsList';
151
	private static workingDirPickerStorageKey = 'pickerWorkingDir';
E
Erich Gamma 已提交
152 153
	private static windowsStateStorageKey = 'windowsState';

J
Joao Moreno 已提交
154
	private static WINDOWS: VSCodeWindow[] = [];
E
Erich Gamma 已提交
155

J
Joao Moreno 已提交
156
	private eventEmitter = new EventEmitter();
157
	private initialUserEnv: platform.IProcessEnvironment;
E
Erich Gamma 已提交
158 159
	private windowsState: IWindowsState;

S
Sandeep Somavarapu 已提交
160 161 162 163 164 165
	private _onFocus = new Emitter<number>();
	onWindowFocus: CommonEvent<number> = this._onFocus.event;

	private _onNewWindow = new Emitter<number>();
	onNewWindowOpen: CommonEvent<number> = this._onNewWindow.event;

J
Joao Moreno 已提交
166 167 168
	constructor(
		@IInstantiationService private instantiationService: IInstantiationService,
		@ILogService private logService: ILogService,
J
Joao Moreno 已提交
169
		@IStorageService private storageService: IStorageService,
170
		@IEnvironmentService private environmentService: IEnvironmentService,
J
Joao Moreno 已提交
171
		@ILifecycleService private lifecycleService: ILifecycleService,
B
Benjamin Pasero 已提交
172
		@IUpdateService private updateService: IUpdateService,
173 174
		@IConfigurationService private configurationService: IConfigurationService,
		@IBackupService private backupService: IBackupService
175
	) { }
J
Joao Moreno 已提交
176

J
Joao Moreno 已提交
177
	onOpen(clb: (path: IPath) => void): () => void {
J
Joao Moreno 已提交
178 179 180 181 182
		this.eventEmitter.addListener(EventTypes.OPEN, clb);

		return () => this.eventEmitter.removeListener(EventTypes.OPEN, clb);
	}

J
Joao Moreno 已提交
183
	onReady(clb: (win: VSCodeWindow) => void): () => void {
J
Joao Moreno 已提交
184 185 186 187 188 189 190 191 192 193 194
		this.eventEmitter.addListener(EventTypes.READY, clb);

		return () => this.eventEmitter.removeListener(EventTypes.READY, clb);
	}

	onClose(clb: (id: number) => void): () => void {
		this.eventEmitter.addListener(EventTypes.CLOSE, clb);

		return () => this.eventEmitter.removeListener(EventTypes.CLOSE, clb);
	}

195
	public ready(initialUserEnv: platform.IProcessEnvironment): void {
E
Erich Gamma 已提交
196 197
		this.registerListeners();

198
		this.initialUserEnv = initialUserEnv;
J
Joao Moreno 已提交
199
		this.windowsState = this.storageService.getItem<IWindowsState>(WindowsManager.windowsStateStorageKey) || { openedFolders: [] };
E
Erich Gamma 已提交
200 201 202
	}

	private registerListeners(): void {
203
		app.on('activate', (event: Event, hasVisibleWindows: boolean) => {
J
Joao Moreno 已提交
204
			this.logService.log('App#activate');
E
Erich Gamma 已提交
205

G
Giorgos Retsinas 已提交
206
			// Mac only event: open new window when we get activated
E
Erich Gamma 已提交
207
			if (!hasVisibleWindows) {
G
Giorgos Retsinas 已提交
208
				this.openNewWindow();
E
Erich Gamma 已提交
209 210 211 212 213 214
			}
		});

		let macOpenFiles: string[] = [];
		let runningTimeout: number = null;
		app.on('open-file', (event: Event, path: string) => {
J
Joao Moreno 已提交
215
			this.logService.log('App#open-file: ', path);
E
Erich Gamma 已提交
216 217 218 219 220 221 222 223 224 225 226 227 228
			event.preventDefault();

			// Keep in array because more might come!
			macOpenFiles.push(path);

			// Clear previous handler if any
			if (runningTimeout !== null) {
				clearTimeout(runningTimeout);
				runningTimeout = null;
			}

			// Handle paths delayed in case more are coming!
			runningTimeout = setTimeout(() => {
229
				this.open({ cli: this.environmentService.args, pathsToOpen: macOpenFiles, preferNewWindow: true /* dropping on the dock prefers to open in a new window */ });
E
Erich Gamma 已提交
230 231 232 233 234 235
				macOpenFiles = [];
				runningTimeout = null;
			}, 100);
		});

		ipc.on('vscode:startCrashReporter', (event: any, config: any) => {
J
Joao Moreno 已提交
236
			this.logService.log('IPC#vscode:startCrashReporter');
237

E
Erich Gamma 已提交
238 239 240
			crashReporter.start(config);
		});

B
Benjamin Pasero 已提交
241
		ipc.on('vscode:windowOpen', (event, paths: string[], forceNewWindow?: boolean) => {
J
Joao Moreno 已提交
242
			this.logService.log('IPC#vscode-windowOpen: ', paths);
E
Erich Gamma 已提交
243 244

			if (paths && paths.length) {
245
				this.open({ cli: this.environmentService.args, pathsToOpen: paths, forceNewWindow: forceNewWindow });
E
Erich Gamma 已提交
246 247 248
			}
		});

B
Benjamin Pasero 已提交
249
		ipc.on('vscode:workbenchLoaded', (event, windowId: number) => {
J
Joao Moreno 已提交
250
			this.logService.log('IPC#vscode-workbenchLoaded');
E
Erich Gamma 已提交
251

B
Benjamin Pasero 已提交
252
			const win = this.getWindowById(windowId);
E
Erich Gamma 已提交
253 254 255 256
			if (win) {
				win.setReady();

				// Event
J
Joao Moreno 已提交
257
				this.eventEmitter.emit(EventTypes.READY, win);
E
Erich Gamma 已提交
258 259 260
			}
		});

261
		ipc.on('vscode:openFilePicker', (event, forceNewWindow?: boolean, path?: string) => {
J
Joao Moreno 已提交
262
			this.logService.log('IPC#vscode-openFilePicker');
E
Erich Gamma 已提交
263

264
			this.openFilePicker(forceNewWindow, path);
E
Erich Gamma 已提交
265 266
		});

267
		ipc.on('vscode:openFolderPicker', (event, forceNewWindow?: boolean) => {
J
Joao Moreno 已提交
268
			this.logService.log('IPC#vscode-openFolderPicker');
E
Erich Gamma 已提交
269

270 271 272 273
			this.openFolderPicker(forceNewWindow);
		});

		ipc.on('vscode:openFileFolderPicker', (event, forceNewWindow?: boolean) => {
J
Joao Moreno 已提交
274
			this.logService.log('IPC#vscode-openFileFolderPicker');
275 276

			this.openFileFolderPicker(forceNewWindow);
E
Erich Gamma 已提交
277 278
		});

B
Benjamin Pasero 已提交
279
		ipc.on('vscode:closeFolder', (event, windowId: number) => {
J
Joao Moreno 已提交
280
			this.logService.log('IPC#vscode-closeFolder');
E
Erich Gamma 已提交
281

B
Benjamin Pasero 已提交
282
			const win = this.getWindowById(windowId);
E
Erich Gamma 已提交
283
			if (win) {
284
				this.open({ cli: this.environmentService.args, forceEmpty: true, windowToUse: win });
E
Erich Gamma 已提交
285 286 287
			}
		});

B
Benjamin Pasero 已提交
288
		ipc.on('vscode:openNewWindow', () => {
J
Joao Moreno 已提交
289
			this.logService.log('IPC#vscode-openNewWindow');
E
Erich Gamma 已提交
290

B
Benjamin Pasero 已提交
291
			this.openNewWindow();
E
Erich Gamma 已提交
292 293
		});

B
Benjamin Pasero 已提交
294
		ipc.on('vscode:reloadWindow', (event, windowId: number) => {
J
Joao Moreno 已提交
295
			this.logService.log('IPC#vscode:reloadWindow');
E
Erich Gamma 已提交
296

B
Benjamin Pasero 已提交
297
			const vscodeWindow = this.getWindowById(windowId);
E
Erich Gamma 已提交
298 299 300 301 302
			if (vscodeWindow) {
				this.reload(vscodeWindow);
			}
		});

B
Benjamin Pasero 已提交
303
		ipc.on('vscode:toggleFullScreen', (event, windowId: number) => {
J
Joao Moreno 已提交
304
			this.logService.log('IPC#vscode:toggleFullScreen');
E
Erich Gamma 已提交
305

B
Benjamin Pasero 已提交
306
			const vscodeWindow = this.getWindowById(windowId);
E
Erich Gamma 已提交
307 308 309 310 311
			if (vscodeWindow) {
				vscodeWindow.toggleFullScreen();
			}
		});

312
		ipc.on('vscode:setFullScreen', (event, windowId: number, fullscreen: boolean) => {
J
Joao Moreno 已提交
313
			this.logService.log('IPC#vscode:setFullScreen');
314

B
Benjamin Pasero 已提交
315
			const vscodeWindow = this.getWindowById(windowId);
316 317 318 319 320 321
			if (vscodeWindow) {
				vscodeWindow.win.setFullScreen(fullscreen);
			}
		});

		ipc.on('vscode:toggleDevTools', (event, windowId: number) => {
J
Joao Moreno 已提交
322
			this.logService.log('IPC#vscode:toggleDevTools');
323

B
Benjamin Pasero 已提交
324
			const vscodeWindow = this.getWindowById(windowId);
325 326 327 328 329 330
			if (vscodeWindow) {
				vscodeWindow.win.webContents.toggleDevTools();
			}
		});

		ipc.on('vscode:openDevTools', (event, windowId: number) => {
J
Joao Moreno 已提交
331
			this.logService.log('IPC#vscode:openDevTools');
332

B
Benjamin Pasero 已提交
333
			const vscodeWindow = this.getWindowById(windowId);
334 335 336 337 338 339 340
			if (vscodeWindow) {
				vscodeWindow.win.webContents.openDevTools();
				vscodeWindow.win.show();
			}
		});

		ipc.on('vscode:setRepresentedFilename', (event, windowId: number, fileName: string) => {
J
Joao Moreno 已提交
341
			this.logService.log('IPC#vscode:setRepresentedFilename');
342

B
Benjamin Pasero 已提交
343
			const vscodeWindow = this.getWindowById(windowId);
344 345 346 347 348 349
			if (vscodeWindow) {
				vscodeWindow.win.setRepresentedFilename(fileName);
			}
		});

		ipc.on('vscode:setMenuBarVisibility', (event, windowId: number, visibility: boolean) => {
J
Joao Moreno 已提交
350
			this.logService.log('IPC#vscode:setMenuBarVisibility');
351

B
Benjamin Pasero 已提交
352
			const vscodeWindow = this.getWindowById(windowId);
353 354 355 356 357 358
			if (vscodeWindow) {
				vscodeWindow.win.setMenuBarVisibility(visibility);
			}
		});

		ipc.on('vscode:flashFrame', (event, windowId: number) => {
J
Joao Moreno 已提交
359
			this.logService.log('IPC#vscode:flashFrame');
360

B
Benjamin Pasero 已提交
361
			const vscodeWindow = this.getWindowById(windowId);
362 363 364 365 366
			if (vscodeWindow) {
				vscodeWindow.win.flashFrame(!vscodeWindow.win.isFocused());
			}
		});

367 368 369
		ipc.on('vscode:openRecent', (event, windowId: number) => {
			this.logService.log('IPC#vscode:openRecent');

B
Benjamin Pasero 已提交
370
			const vscodeWindow = this.getWindowById(windowId);
371
			if (vscodeWindow) {
372
				const recents = this.getRecentPathsList(vscodeWindow.config.workspacePath, vscodeWindow.config.filesToOpen);
373 374 375 376 377

				vscodeWindow.send('vscode:openRecent', recents.files, recents.folders);
			}
		});

378
		ipc.on('vscode:focusWindow', (event, windowId: number) => {
J
Joao Moreno 已提交
379
			this.logService.log('IPC#vscode:focusWindow');
380

B
Benjamin Pasero 已提交
381
			const vscodeWindow = this.getWindowById(windowId);
382 383 384 385 386
			if (vscodeWindow) {
				vscodeWindow.win.focus();
			}
		});

387 388 389 390 391 392 393 394 395
		ipc.on('vscode:showWindow', (event, windowId: number) => {
			this.logService.log('IPC#vscode:showWindow');

			let vscodeWindow = this.getWindowById(windowId);
			if (vscodeWindow) {
				vscodeWindow.win.show();
			}
		});

396
		ipc.on('vscode:setDocumentEdited', (event, windowId: number, edited: boolean) => {
J
Joao Moreno 已提交
397
			this.logService.log('IPC#vscode:setDocumentEdited');
398

B
Benjamin Pasero 已提交
399
			const vscodeWindow = this.getWindowById(windowId);
400 401 402 403 404
			if (vscodeWindow && vscodeWindow.win.isDocumentEdited() !== edited) {
				vscodeWindow.win.setDocumentEdited(edited);
			}
		});

B
Benjamin Pasero 已提交
405
		ipc.on('vscode:toggleMenuBar', (event, windowId: number) => {
J
Joao Moreno 已提交
406
			this.logService.log('IPC#vscode:toggleMenuBar');
407 408

			// Update in settings
B
Benjamin Pasero 已提交
409 410
			const menuBarHidden = this.storageService.getItem(VSCodeWindow.menuBarHiddenKey, false);
			const newMenuBarHidden = !menuBarHidden;
J
Joao Moreno 已提交
411
			this.storageService.setItem(VSCodeWindow.menuBarHiddenKey, newMenuBarHidden);
412 413 414

			// Update across windows
			WindowsManager.WINDOWS.forEach(w => w.setMenuBarVisibility(!newMenuBarHidden));
415 416 417

			// Inform user if menu bar is now hidden
			if (newMenuBarHidden) {
B
Benjamin Pasero 已提交
418
				const vscodeWindow = this.getWindowById(windowId);
419 420 421 422
				if (vscodeWindow) {
					vscodeWindow.send('vscode:showInfoMessage', nls.localize('hiddenMenuBar', "You can still access the menu bar by pressing the **Alt** key."));
				}
			}
423 424
		});

J
Joao Moreno 已提交
425 426 427 428 429 430 431 432 433 434 435 436 437 438
		ipc.on('vscode:setHeaders', (event, windowId: number, urls: string[], headers: any) => {
			this.logService.log('IPC#vscode:setHeaders');

			const vscodeWindow = this.getWindowById(windowId);

			if (!vscodeWindow || !urls || !urls.length || !headers) {
				return;
			}

			vscodeWindow.win.webContents.session.webRequest.onBeforeSendHeaders({ urls }, (details, cb) => {
				cb({ cancel: false, requestHeaders: assign(details.requestHeaders, headers) });
			});
		});

B
Benjamin Pasero 已提交
439
		ipc.on('vscode:broadcast', (event, windowId: number, target: string, broadcast: { channel: string; payload: any; }) => {
440
			if (broadcast.channel && !types.isUndefinedOrNull(broadcast.payload)) {
J
Joao Moreno 已提交
441
				this.logService.log('IPC#vscode:broadcast', target, broadcast.channel, broadcast.payload);
B
Benjamin Pasero 已提交
442

443 444 445 446
				// Handle specific events on main side
				this.onBroadcast(broadcast.channel, broadcast.payload);

				// Send to windows
447
				if (target) {
B
Benjamin Pasero 已提交
448
					const otherWindowsWithTarget = WindowsManager.WINDOWS.filter(w => w.id !== windowId && typeof w.openedWorkspacePath === 'string');
449 450 451 452 453
					const directTargetMatch = otherWindowsWithTarget.filter(w => this.isPathEqual(target, w.openedWorkspacePath));
					const parentTargetMatch = otherWindowsWithTarget.filter(w => paths.isEqualOrParent(target, w.openedWorkspacePath));

					const targetWindow = directTargetMatch.length ? directTargetMatch[0] : parentTargetMatch[0]; // prefer direct match over parent match
					if (targetWindow) {
454 455 456 457 458
						targetWindow.send('vscode:broadcast', broadcast);
					}
				} else {
					this.sendToAll('vscode:broadcast', broadcast, [windowId]);
				}
E
Erich Gamma 已提交
459
			}
460 461
		});

B
Benjamin Pasero 已提交
462
		ipc.on('vscode:log', (event, logEntry: ILogEntry) => {
B
Benjamin Pasero 已提交
463
			const args = [];
464
			try {
B
Benjamin Pasero 已提交
465
				const parsed = JSON.parse(logEntry.arguments);
466 467 468 469 470 471 472
				args.push(...Object.getOwnPropertyNames(parsed).map(o => parsed[o]));
			} catch (error) {
				args.push(logEntry.arguments);
			}

			console[logEntry.severity].apply(console, args);
		});
E
Erich Gamma 已提交
473

474
		ipc.on('vscode:closeExtensionHostWindow', (event, extensionDevelopmentPath: string) => {
J
Joao Moreno 已提交
475
			this.logService.log('IPC#vscode:closeExtensionHostWindow', extensionDevelopmentPath);
B
Benjamin Pasero 已提交
476

477 478 479 480 481 482
			const windowOnExtension = this.findWindow(null, null, extensionDevelopmentPath);
			if (windowOnExtension) {
				windowOnExtension.win.close();
			}
		});

483
		ipc.on('vscode:switchWindow', (event, windowId: number) => {
484 485
			const windows = this.getWindows();
			const window = this.getWindowById(windowId);
486
			window.send('vscode:switchWindow', windows.map(w => {
J
Johannes Rieken 已提交
487
				return { path: w.openedWorkspacePath, title: w.win.getTitle(), id: w.id };
488 489 490
			}));
		});

B
Benjamin Pasero 已提交
491 492 493 494 495 496
		ipc.on('vscode:showItemInFolder', (event, path: string) => {
			this.logService.log('IPC#vscode-showItemInFolder');

			shell.showItemInFolder(path);
		});

B
Benjamin Pasero 已提交
497 498 499 500 501 502
		ipc.on('vscode:openExternal', (event, url: string) => {
			this.logService.log('IPC#vscode-openExternal');

			shell.openExternal(url);
		});

B
Benjamin Pasero 已提交
503
		this.updateService.on('update-downloaded', (update: IUpdate) => {
E
Erich Gamma 已提交
504 505 506 507 508 509 510 511 512
			this.sendToFocused('vscode:telemetry', { eventName: 'update:downloaded', data: { version: update.version } });

			this.sendToAll('vscode:update-downloaded', JSON.stringify({
				releaseNotes: update.releaseNotes,
				version: update.version,
				date: update.date
			}));
		});

B
Benjamin Pasero 已提交
513
		ipc.on('vscode:update-apply', () => {
J
Joao Moreno 已提交
514
			this.logService.log('IPC#vscode:update-apply');
E
Erich Gamma 已提交
515

B
Benjamin Pasero 已提交
516 517
			if (this.updateService.availableUpdate) {
				this.updateService.availableUpdate.quitAndUpdate();
E
Erich Gamma 已提交
518 519 520
			}
		});

B
Benjamin Pasero 已提交
521
		this.updateService.on('update-not-available', (explicit: boolean) => {
E
Erich Gamma 已提交
522 523 524 525 526 527 528
			this.sendToFocused('vscode:telemetry', { eventName: 'update:notAvailable', data: { explicit } });

			if (explicit) {
				this.sendToFocused('vscode:update-not-available', '');
			}
		});

J
Joao Moreno 已提交
529
		this.updateService.on('update-available', (url: string, version: string) => {
J
Joao Moreno 已提交
530
			if (url) {
J
Joao Moreno 已提交
531
				this.sendToFocused('vscode:update-available', url, version);
J
Joao Moreno 已提交
532 533 534
			}
		});

J
Joao Moreno 已提交
535
		this.lifecycleService.onBeforeQuit(() => {
E
Erich Gamma 已提交
536 537 538 539 540 541 542 543

			// 0-1 window open: Do not keep the list but just rely on the active window to be stored
			if (WindowsManager.WINDOWS.length < 2) {
				this.windowsState.openedFolders = [];
				return;
			}

			// 2-N windows open: Keep a list of windows that are opened on a specific folder to restore it in the next session as needed
J
Joao Moreno 已提交
544
			this.windowsState.openedFolders = WindowsManager.WINDOWS.filter(w => w.readyState === ReadyState.READY && !!w.openedWorkspacePath && !w.isPluginDevelopmentHost).map(w => {
E
Erich Gamma 已提交
545 546 547
				return <IWindowState>{
					workspacePath: w.openedWorkspacePath,
					uiState: w.serializeWindowState()
B
Benjamin Pasero 已提交
548
				};
E
Erich Gamma 已提交
549 550 551 552
			});
		});

		app.on('will-quit', () => {
J
Joao Moreno 已提交
553
			this.storageService.setItem(WindowsManager.windowsStateStorageKey, this.windowsState);
E
Erich Gamma 已提交
554
		});
555 556

		let loggedStartupTimes = false;
J
Joao Moreno 已提交
557
		this.onReady(window => {
558 559 560 561 562 563
			if (loggedStartupTimes) {
				return; // only for the first window
			}

			loggedStartupTimes = true;

B
Benjamin Pasero 已提交
564
			this.logStartupTimes(window);
565
		});
E
Erich Gamma 已提交
566 567
	}

B
Benjamin Pasero 已提交
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
	private logStartupTimes(window: VSCodeWindow): void {
		let totalmem: number;
		let cpus: { count: number; speed: number; model: string; };

		try {
			totalmem = os.totalmem();

			const rawCpus = os.cpus();
			if (rawCpus && rawCpus.length > 0) {
				cpus = { count: rawCpus.length, speed: rawCpus[0].speed, model: rawCpus[0].model };
			}
		} catch (error) {
			this.logService.log(error); // be on the safe side with these hardware method calls
		}

B
Benjamin Pasero 已提交
583
		window.send('vscode:telemetry', { eventName: 'startupTime', data: { ellapsed: Date.now() - global.vscodeStart, totalmem, cpus } });
B
Benjamin Pasero 已提交
584 585
	}

586 587 588
	private onBroadcast(event: string, payload: any): void {

		// Theme changes
589 590
		if (event === 'vscode:changeColorTheme' && typeof payload === 'string') {
			this.storageService.setItem(VSCodeWindow.colorThemeStorageKey, payload);
591 592 593
		}
	}

B
Benjamin Pasero 已提交
594
	public reload(win: VSCodeWindow, cli?: ParsedArgs): void {
E
Erich Gamma 已提交
595 596

		// Only reload when the window has not vetoed this
597
		this.lifecycleService.unload(win).done(veto => {
E
Erich Gamma 已提交
598 599 600 601 602 603
			if (!veto) {
				win.reload(cli);
			}
		});
	}

J
Joao Moreno 已提交
604 605
	public open(openConfig: IOpenConfiguration): VSCodeWindow[] {
		let iPathsToOpen: IPath[];
B
Benjamin Pasero 已提交
606
		const usedWindows: VSCodeWindow[] = [];
E
Erich Gamma 已提交
607 608 609

		// Find paths from provided paths if any
		if (openConfig.pathsToOpen && openConfig.pathsToOpen.length > 0) {
610
			iPathsToOpen = openConfig.pathsToOpen.map(pathToOpen => {
B
Benjamin Pasero 已提交
611
				const iPath = this.toIPath(pathToOpen, false, openConfig.cli && openConfig.cli.goto);
E
Erich Gamma 已提交
612 613 614

				// Warn if the requested path to open does not exist
				if (!iPath) {
B
Benjamin Pasero 已提交
615
					const options: Electron.ShowMessageBoxOptions = {
B
Benjamin Pasero 已提交
616
						title: product.nameLong,
E
Erich Gamma 已提交
617 618 619 620 621 622 623
						type: 'info',
						buttons: [nls.localize('ok', "OK")],
						message: nls.localize('pathNotExistTitle', "Path does not exist"),
						detail: nls.localize('pathNotExistDetail', "The path '{0}' does not seem to exist anymore on disk.", pathToOpen),
						noLink: true
					};

B
Benjamin Pasero 已提交
624
					const activeWindow = BrowserWindow.getFocusedWindow();
E
Erich Gamma 已提交
625
					if (activeWindow) {
626
						dialog.showMessageBox(activeWindow, options);
E
Erich Gamma 已提交
627
					} else {
628
						dialog.showMessageBox(options);
E
Erich Gamma 已提交
629 630 631 632 633 634 635 636 637 638
					}
				}

				return iPath;
			});

			// get rid of nulls
			iPathsToOpen = arrays.coalesce(iPathsToOpen);

			if (iPathsToOpen.length === 0) {
639
				return null; // indicate to outside that open failed
E
Erich Gamma 已提交
640 641 642 643 644 645 646 647 648 649
			}
		}

		// Check for force empty
		else if (openConfig.forceEmpty) {
			iPathsToOpen = [Object.create(null)];
		}

		// Otherwise infer from command line arguments
		else {
B
Benjamin Pasero 已提交
650
			const ignoreFileNotFound = openConfig.cli._.length > 0; // we assume the user wants to create this file from command line
E
Erich Gamma 已提交
651 652 653
			iPathsToOpen = this.cliToPaths(openConfig.cli, ignoreFileNotFound);
		}

654 655 656 657
		let configuration: IWindowConfiguration;
		let openInNewWindow = openConfig.preferNewWindow || openConfig.forceNewWindow;

		// Restore any existing backup workspaces
658
		if (openConfig.restoreBackups) {
659 660 661 662 663 664
			const workspacesWithBackups = this.backupService.getWorkspaceBackupPathsSync();

			workspacesWithBackups.forEach(workspacePath => {
				const untitledToRestore = this.backupService.getWorkspaceUntitledFileBackupsSync(Uri.file(workspacePath)).map(filePath => {
					return { filePath: filePath };
				});
665
				configuration = this.toConfiguration(this.getWindowUserEnv(openConfig), openConfig.cli, workspacePath, [], [], [], untitledToRestore);
666 667 668 669
				const browserWindow = this.openInBrowserWindow(configuration, openInNewWindow, openInNewWindow ? void 0 : openConfig.windowToUse);
				usedWindows.push(browserWindow);

				openInNewWindow = true; // any other folders to open must open in new window then
670
			});
671 672
		}

J
Joao Moreno 已提交
673 674
		let filesToOpen: IPath[] = [];
		let filesToDiff: IPath[] = [];
675 676 677
		let foldersToOpen = iPathsToOpen.filter(iPath => iPath.workspacePath && !iPath.filePath);
		let emptyToOpen = iPathsToOpen.filter(iPath => !iPath.workspacePath && !iPath.filePath);
		let filesToCreate = iPathsToOpen.filter(iPath => !!iPath.filePath && iPath.createFilePath);
678 679

		// Diff mode needs special care
680
		const candidates = iPathsToOpen.filter(iPath => !!iPath.filePath && !iPath.createFilePath);
681 682 683 684 685 686 687
		if (openConfig.diffMode) {
			if (candidates.length === 2) {
				filesToDiff = candidates;
			} else {
				emptyToOpen = [Object.create(null)]; // improper use of diffMode, open empty
			}

688
			foldersToOpen = []; // diff is always in empty workspace
B
Benjamin Pasero 已提交
689
			filesToCreate = []; // diff ignores other files that do not exist
690 691 692 693 694
		} else {
			filesToOpen = candidates;
		}

		// Handle files to open/diff or to create when we dont open a folder
695
		if (!foldersToOpen.length && (filesToOpen.length > 0 || filesToCreate.length > 0 || filesToDiff.length > 0)) {
E
Erich Gamma 已提交
696

B
Benjamin Pasero 已提交
697
			// const the user settings override how files are open in a new window or same window unless we are forced
698 699 700 701 702 703
			let openFilesInNewWindow: boolean;
			if (openConfig.forceNewWindow) {
				openFilesInNewWindow = true;
			} else {
				openFilesInNewWindow = openConfig.preferNewWindow;
				if (openFilesInNewWindow && !openConfig.cli.extensionDevelopmentPath) { // can be overriden via settings (not for PDE though!)
704 705 706 707
					const windowConfig = this.configurationService.getConfiguration<IWindowSettings>('window');
					if (windowConfig && !windowConfig.openFilesInNewWindow) {
						openFilesInNewWindow = false; // do not open in new window if user configured this explicitly
					}
708
				}
E
Erich Gamma 已提交
709 710 711
			}

			// Open Files in last instance if any and flag tells us so
B
Benjamin Pasero 已提交
712
			const lastActiveWindow = this.getLastActiveWindow();
E
Erich Gamma 已提交
713
			if (!openFilesInNewWindow && lastActiveWindow) {
B
Benjamin Pasero 已提交
714
				lastActiveWindow.focus();
715
				lastActiveWindow.ready().then(readyWindow => {
716
					readyWindow.send('vscode:openFiles', { filesToOpen, filesToCreate, filesToDiff });
E
Erich Gamma 已提交
717
				});
718 719

				usedWindows.push(lastActiveWindow);
E
Erich Gamma 已提交
720 721 722 723
			}

			// Otherwise open instance with files
			else {
724
				configuration = this.toConfiguration(this.getWindowUserEnv(openConfig), openConfig.cli, null, filesToOpen, filesToCreate, filesToDiff);
B
Benjamin Pasero 已提交
725
				const browserWindow = this.openInBrowserWindow(configuration, true /* new window */);
726
				usedWindows.push(browserWindow);
E
Erich Gamma 已提交
727 728 729 730 731 732 733 734 735

				openConfig.forceNewWindow = true; // any other folders to open must open in new window then
			}
		}

		// Handle folders to open
		if (foldersToOpen.length > 0) {

			// Check for existing instances
736
			const windowsOnWorkspacePath = arrays.coalesce(foldersToOpen.map(iPath => this.findWindow(iPath.workspacePath)));
E
Erich Gamma 已提交
737
			if (windowsOnWorkspacePath.length > 0) {
B
Benjamin Pasero 已提交
738
				const browserWindow = windowsOnWorkspacePath[0];
739
				browserWindow.focus(); // just focus one of them
740
				browserWindow.ready().then(readyWindow => {
741
					readyWindow.send('vscode:openFiles', { filesToOpen, filesToCreate, filesToDiff });
E
Erich Gamma 已提交
742 743
				});

744 745
				usedWindows.push(browserWindow);

E
Erich Gamma 已提交
746 747 748
				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
749
				filesToDiff = [];
E
Erich Gamma 已提交
750

751
				openInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
752 753 754
			}

			// Open remaining ones
755 756
			foldersToOpen.forEach(folderToOpen => {
				if (windowsOnWorkspacePath.some(win => this.isPathEqual(win.openedWorkspacePath, folderToOpen.workspacePath))) {
E
Erich Gamma 已提交
757 758 759
					return; // ignore folders that are already open
				}

760
				configuration = this.toConfiguration(this.getWindowUserEnv(openConfig), openConfig.cli, folderToOpen.workspacePath, filesToOpen, filesToCreate, filesToDiff);
B
Benjamin Pasero 已提交
761
				const browserWindow = this.openInBrowserWindow(configuration, openInNewWindow, openInNewWindow ? void 0 : openConfig.windowToUse);
762
				usedWindows.push(browserWindow);
E
Erich Gamma 已提交
763 764 765 766

				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
767
				filesToDiff = [];
E
Erich Gamma 已提交
768

769
				openInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
770 771 772 773 774 775
			});
		}

		// Handle empty
		if (emptyToOpen.length > 0) {
			emptyToOpen.forEach(() => {
B
Benjamin Pasero 已提交
776 777
				const configuration = this.toConfiguration(this.getWindowUserEnv(openConfig), openConfig.cli);
				const browserWindow = this.openInBrowserWindow(configuration, openInNewWindow, openInNewWindow ? void 0 : openConfig.windowToUse);
778
				usedWindows.push(browserWindow);
E
Erich Gamma 已提交
779

780
				openInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
781 782 783
			});
		}

784
		// Remember in recent document list (unless this opens for extension development)
785
		// Also do not add paths when files are opened for diffing, only if opened individually
786
		if (!usedWindows.some(w => w.isPluginDevelopmentHost) && !openConfig.cli.diff) {
787 788 789 790 791 792 793
			iPathsToOpen.forEach(iPath => {
				if (iPath.filePath || iPath.workspacePath) {
					app.addRecentDocument(iPath.filePath || iPath.workspacePath);
					this.addToRecentPathsList(iPath.filePath || iPath.workspacePath, !!iPath.filePath);
				}
			});
		}
E
Erich Gamma 已提交
794 795

		// Emit events
796
		iPathsToOpen.forEach(iPath => this.eventEmitter.emit(EventTypes.OPEN, iPath));
E
Erich Gamma 已提交
797

798 799 800
		// Register new paths for backup
		this.backupService.pushWorkspaceBackupPathsSync(iPathsToOpen.filter(p => p.workspacePath).map(p => Uri.file(p.workspacePath)));

801
		return arrays.distinct(usedWindows);
E
Erich Gamma 已提交
802 803
	}

804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
	private addToRecentPathsList(path?: string, isFile?: boolean): void {
		if (!path) {
			return;
		}

		const mru = this.getRecentPathsList();
		if (isFile) {
			mru.files.unshift(path);
			mru.files = arrays.distinct(mru.files, (f) => platform.isLinux ? f : f.toLowerCase());
		} else {
			mru.folders.unshift(path);
			mru.folders = arrays.distinct(mru.folders, (f) => platform.isLinux ? f : f.toLowerCase());
		}

		// Make sure its bounded
		mru.folders = mru.folders.slice(0, WindowsManager.MAX_TOTAL_RECENT_ENTRIES);
		mru.files = mru.files.slice(0, WindowsManager.MAX_TOTAL_RECENT_ENTRIES);

		this.storageService.setItem(WindowsManager.recentPathsListStorageKey, mru);
	}

	public removeFromRecentPathsList(path: string): void {
		const mru = this.getRecentPathsList();

		let index = mru.files.indexOf(path);
		if (index >= 0) {
			mru.files.splice(index, 1);
		}

		index = mru.folders.indexOf(path);
		if (index >= 0) {
			mru.folders.splice(index, 1);
		}

		this.storageService.setItem(WindowsManager.recentPathsListStorageKey, mru);
	}

	public clearRecentPathsList(): void {
		this.storageService.setItem(WindowsManager.recentPathsListStorageKey, { folders: [], files: [] });
		app.clearRecentDocuments();
	}

	public getRecentPathsList(workspacePath?: string, filesToOpen?: IPath[]): IRecentPathsList {
		let files: string[];
		let folders: string[];

		// Get from storage
		const storedRecents = this.storageService.getItem<IRecentPathsList>(WindowsManager.recentPathsListStorageKey);
		if (storedRecents) {
			files = storedRecents.files || [];
			folders = storedRecents.folders || [];
		} else {
			files = [];
			folders = [];
		}

		// Add currently files to open to the beginning if any
		if (filesToOpen) {
			files.unshift(...filesToOpen.map(f => f.filePath));
		}

		// Add current workspace path to beginning if set
		if (workspacePath) {
			folders.unshift(workspacePath);
		}

		// Clear those dupes
		files = arrays.distinct(files);
		folders = arrays.distinct(folders);

		return { files, folders };
	}

877
	private getWindowUserEnv(openConfig: IOpenConfiguration): platform.IProcessEnvironment {
878 879 880
		return assign({}, this.initialUserEnv, openConfig.userEnv || {});
	}

E
Erich Gamma 已提交
881 882 883 884 885
	public openPluginDevelopmentHostWindow(openConfig: IOpenConfiguration): void {

		// Reload an existing plugin development host window on the same path
		// We currently do not allow more than one extension development window
		// on the same plugin path.
886
		let res = WindowsManager.WINDOWS.filter(w => w.config && this.isPathEqual(w.config.extensionDevelopmentPath, openConfig.cli.extensionDevelopmentPath));
E
Erich Gamma 已提交
887 888
		if (res && res.length === 1) {
			this.reload(res[0], openConfig.cli);
B
Benjamin Pasero 已提交
889
			res[0].focus(); // make sure it gets focus and is restored
E
Erich Gamma 已提交
890 891 892 893

			return;
		}

894
		// Fill in previously opened workspace unless an explicit path is provided and we are not unit testing
B
Benjamin Pasero 已提交
895
		if (openConfig.cli._.length === 0 && !openConfig.cli.extensionTestsPath) {
B
Benjamin Pasero 已提交
896
			const workspaceToOpen = this.windowsState.lastPluginDevelopmentHostWindow && this.windowsState.lastPluginDevelopmentHostWindow.workspacePath;
E
Erich Gamma 已提交
897
			if (workspaceToOpen) {
B
Benjamin Pasero 已提交
898
				openConfig.cli._ = [workspaceToOpen];
E
Erich Gamma 已提交
899 900 901 902
			}
		}

		// Make sure we are not asked to open a path that is already opened
B
Benjamin Pasero 已提交
903 904
		if (openConfig.cli._.length > 0) {
			res = WindowsManager.WINDOWS.filter(w => w.openedWorkspacePath && openConfig.cli._.indexOf(w.openedWorkspacePath) >= 0);
E
Erich Gamma 已提交
905
			if (res.length) {
B
Benjamin Pasero 已提交
906
				openConfig.cli._ = [];
E
Erich Gamma 已提交
907 908 909 910
			}
		}

		// Open it
B
Benjamin Pasero 已提交
911
		this.open({ cli: openConfig.cli, forceNewWindow: true, forceEmpty: openConfig.cli._.length === 0 });
E
Erich Gamma 已提交
912 913
	}

914
	private toConfiguration(userEnv: platform.IProcessEnvironment, cli: ParsedArgs, workspacePath?: string, filesToOpen?: IPath[], filesToCreate?: IPath[], filesToDiff?: IPath[], untitledToRestore?: IPath[]): IWindowConfiguration {
B
Benjamin Pasero 已提交
915
		const configuration: IWindowConfiguration = mixin({}, cli); // inherit all properties from CLI
916
		configuration.appRoot = this.environmentService.appRoot;
B
Benjamin Pasero 已提交
917 918
		configuration.execPath = process.execPath;
		configuration.userEnv = userEnv;
E
Erich Gamma 已提交
919 920 921
		configuration.workspacePath = workspacePath;
		configuration.filesToOpen = filesToOpen;
		configuration.filesToCreate = filesToCreate;
922
		configuration.filesToDiff = filesToDiff;
923
		configuration.untitledToRestore = untitledToRestore;
E
Erich Gamma 已提交
924 925 926 927

		return configuration;
	}

J
Joao Moreno 已提交
928
	private toIPath(anyPath: string, ignoreFileNotFound?: boolean, gotoLineMode?: boolean): IPath {
E
Erich Gamma 已提交
929 930 931 932
		if (!anyPath) {
			return null;
		}

933
		let parsedPath: IPathWithLineAndColumn;
E
Erich Gamma 已提交
934
		if (gotoLineMode) {
J
Joao Moreno 已提交
935
			parsedPath = parseLineAndColumnAware(anyPath);
E
Erich Gamma 已提交
936 937 938
			anyPath = parsedPath.path;
		}

B
Benjamin Pasero 已提交
939
		const candidate = path.normalize(anyPath);
E
Erich Gamma 已提交
940
		try {
B
Benjamin Pasero 已提交
941
			const candidateStat = fs.statSync(candidate);
E
Erich Gamma 已提交
942 943 944 945 946
			if (candidateStat) {
				return candidateStat.isFile() ?
					{
						filePath: candidate,
						lineNumber: gotoLineMode ? parsedPath.line : void 0,
947
						columnNumber: gotoLineMode ? parsedPath.column : void 0
E
Erich Gamma 已提交
948 949 950 951 952 953 954 955 956 957 958 959
					} :
					{ workspacePath: candidate };
			}
		} catch (error) {
			if (ignoreFileNotFound) {
				return { filePath: candidate, createFilePath: true }; // assume this is a file that does not yet exist
			}
		}

		return null;
	}

B
Benjamin Pasero 已提交
960
	private cliToPaths(cli: ParsedArgs, ignoreFileNotFound?: boolean): IPath[] {
E
Erich Gamma 已提交
961 962 963

		// Check for pass in candidate or last opened path
		let candidates: string[] = [];
B
Benjamin Pasero 已提交
964 965
		if (cli._.length > 0) {
			candidates = cli._;
E
Erich Gamma 已提交
966 967 968 969
		}

		// No path argument, check settings for what to do now
		else {
970 971 972 973
			let reopenFolders: string;
			if (this.lifecycleService.wasUpdated) {
				reopenFolders = ReopenFoldersSetting.ALL; // always reopen all folders when an update was applied
			} else {
974 975
				const windowConfig = this.configurationService.getConfiguration<IWindowSettings>('window');
				reopenFolders = (windowConfig && windowConfig.reopenFolders) || ReopenFoldersSetting.ONE;
976 977
			}

B
Benjamin Pasero 已提交
978
			const lastActiveFolder = this.windowsState.lastActiveWindow && this.windowsState.lastActiveWindow.workspacePath;
E
Erich Gamma 已提交
979 980

			// Restore all
981
			if (reopenFolders === ReopenFoldersSetting.ALL) {
B
Benjamin Pasero 已提交
982
				const lastOpenedFolders = this.windowsState.openedFolders.map(o => o.workspacePath);
E
Erich Gamma 已提交
983 984 985 986 987 988 989 990 991 992 993

				// If we have a last active folder, move it to the end
				if (lastActiveFolder) {
					lastOpenedFolders.splice(lastOpenedFolders.indexOf(lastActiveFolder), 1);
					lastOpenedFolders.push(lastActiveFolder);
				}

				candidates.push(...lastOpenedFolders);
			}

			// Restore last active
994
			else if (lastActiveFolder && (reopenFolders === ReopenFoldersSetting.ONE || reopenFolders !== ReopenFoldersSetting.NONE)) {
E
Erich Gamma 已提交
995 996 997 998
				candidates.push(lastActiveFolder);
			}
		}

999
		const iPaths = candidates.map(candidate => this.toIPath(candidate, ignoreFileNotFound, cli.goto)).filter(path => !!path);
E
Erich Gamma 已提交
1000 1001 1002 1003 1004 1005 1006 1007
		if (iPaths.length > 0) {
			return iPaths;
		}

		// No path provided, return empty to open empty
		return [Object.create(null)];
	}

J
Joao Moreno 已提交
1008 1009
	private openInBrowserWindow(configuration: IWindowConfiguration, forceNewWindow?: boolean, windowToUse?: VSCodeWindow): VSCodeWindow {
		let vscodeWindow: VSCodeWindow;
E
Erich Gamma 已提交
1010 1011 1012 1013 1014

		if (!forceNewWindow) {
			vscodeWindow = windowToUse || this.getLastActiveWindow();

			if (vscodeWindow) {
B
Benjamin Pasero 已提交
1015
				vscodeWindow.focus();
E
Erich Gamma 已提交
1016 1017 1018 1019 1020
			}
		}

		// New window
		if (!vscodeWindow) {
1021 1022
			const windowConfig = this.configurationService.getConfiguration<IWindowSettings>('window');

J
Joao Moreno 已提交
1023
			vscodeWindow = this.instantiationService.createInstance(VSCodeWindow, {
1024
				state: this.getNewWindowState(configuration),
1025
				extensionDevelopmentPath: configuration.extensionDevelopmentPath,
1026
				allowFullscreen: this.lifecycleService.wasUpdated || (windowConfig && windowConfig.restoreFullscreen)
1027 1028
			});

E
Erich Gamma 已提交
1029 1030 1031
			WindowsManager.WINDOWS.push(vscodeWindow);

			// Window Events
1032 1033
			vscodeWindow.win.webContents.removeAllListeners('devtools-reload-page'); // remove built in listener so we can handle this on our own
			vscodeWindow.win.webContents.on('devtools-reload-page', () => this.reload(vscodeWindow));
1034 1035
			vscodeWindow.win.webContents.on('crashed', () => this.onWindowError(vscodeWindow, WindowError.CRASHED));
			vscodeWindow.win.on('unresponsive', () => this.onWindowError(vscodeWindow, WindowError.UNRESPONSIVE));
E
Erich Gamma 已提交
1036 1037
			vscodeWindow.win.on('close', () => this.onBeforeWindowClose(vscodeWindow));
			vscodeWindow.win.on('closed', () => this.onWindowClosed(vscodeWindow));
S
Sandeep Somavarapu 已提交
1038
			vscodeWindow.win.on('focus', () => this._onFocus.fire(vscodeWindow.id));
E
Erich Gamma 已提交
1039

S
Sandeep Somavarapu 已提交
1040
			this._onNewWindow.fire(vscodeWindow.id);
E
Erich Gamma 已提交
1041
			// Lifecycle
J
Joao Moreno 已提交
1042
			this.lifecycleService.registerWindow(vscodeWindow);
E
Erich Gamma 已提交
1043 1044 1045 1046 1047 1048 1049
		}

		// Existing window
		else {

			// Some configuration things get inherited if the window is being reused and we are
			// in plugin development host mode. These options are all development related.
B
Benjamin Pasero 已提交
1050
			const currentWindowConfig = vscodeWindow.config;
A
Alex Dima 已提交
1051 1052
			if (!configuration.extensionDevelopmentPath && currentWindowConfig && !!currentWindowConfig.extensionDevelopmentPath) {
				configuration.extensionDevelopmentPath = currentWindowConfig.extensionDevelopmentPath;
B
Benjamin Pasero 已提交
1053
				configuration.verbose = currentWindowConfig.verbose;
1054
				configuration.debugBrkPluginHost = currentWindowConfig.debugBrkPluginHost;
1055
				configuration.debugPluginHost = currentWindowConfig.debugPluginHost;
B
Benjamin Pasero 已提交
1056
				configuration.extensionHomePath = currentWindowConfig.extensionHomePath;
E
Erich Gamma 已提交
1057 1058 1059 1060
			}
		}

		// Only load when the window has not vetoed this
1061
		this.lifecycleService.unload(vscodeWindow).done(veto => {
E
Erich Gamma 已提交
1062 1063 1064 1065 1066 1067
			if (!veto) {

				// Load it
				vscodeWindow.load(configuration);
			}
		});
1068 1069

		return vscodeWindow;
E
Erich Gamma 已提交
1070 1071
	}

J
Joao Moreno 已提交
1072
	private getNewWindowState(configuration: IWindowConfiguration): ISingleWindowState {
E
Erich Gamma 已提交
1073 1074

		// plugin development host Window - load from stored settings if any
A
Alex Dima 已提交
1075
		if (!!configuration.extensionDevelopmentPath && this.windowsState.lastPluginDevelopmentHostWindow) {
E
Erich Gamma 已提交
1076 1077 1078 1079 1080
			return this.windowsState.lastPluginDevelopmentHostWindow.uiState;
		}

		// Known Folder - load from stored settings if any
		if (configuration.workspacePath) {
B
Benjamin Pasero 已提交
1081
			const stateForWorkspace = this.windowsState.openedFolders.filter(o => this.isPathEqual(o.workspacePath, configuration.workspacePath)).map(o => o.uiState);
E
Erich Gamma 已提交
1082 1083 1084 1085 1086 1087
			if (stateForWorkspace.length) {
				return stateForWorkspace[0];
			}
		}

		// First Window
B
Benjamin Pasero 已提交
1088
		const lastActive = this.getLastActiveWindow();
E
Erich Gamma 已提交
1089 1090 1091 1092 1093 1094 1095 1096 1097
		if (!lastActive && this.windowsState.lastActiveWindow) {
			return this.windowsState.lastActiveWindow.uiState;
		}

		//
		// In any other case, we do not have any stored settings for the window state, so we come up with something smart
		//

		// We want the new window to open on the same display that the last active one is in
1098
		let displayToUse: Electron.Display;
B
Benjamin Pasero 已提交
1099
		const displays = screen.getAllDisplays();
E
Erich Gamma 已提交
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110

		// Single Display
		if (displays.length === 1) {
			displayToUse = displays[0];
		}

		// Multi Display
		else {

			// on mac there is 1 menu per window so we need to use the monitor where the cursor currently is
			if (platform.isMacintosh) {
B
Benjamin Pasero 已提交
1111
				const cursorPoint = screen.getCursorScreenPoint();
E
Erich Gamma 已提交
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
				displayToUse = screen.getDisplayNearestPoint(cursorPoint);
			}

			// if we have a last active window, use that display for the new window
			if (!displayToUse && lastActive) {
				displayToUse = screen.getDisplayMatching(lastActive.getBounds());
			}

			// fallback to first display
			if (!displayToUse) {
				displayToUse = displays[0];
			}
		}

B
Benjamin Pasero 已提交
1126
		const defaultState = defaultWindowState();
E
Erich Gamma 已提交
1127 1128 1129 1130 1131 1132
		defaultState.x = displayToUse.bounds.x + (displayToUse.bounds.width / 2) - (defaultState.width / 2);
		defaultState.y = displayToUse.bounds.y + (displayToUse.bounds.height / 2) - (defaultState.height / 2);

		return this.ensureNoOverlap(defaultState);
	}

J
Joao Moreno 已提交
1133
	private ensureNoOverlap(state: ISingleWindowState): ISingleWindowState {
E
Erich Gamma 已提交
1134 1135 1136 1137
		if (WindowsManager.WINDOWS.length === 0) {
			return state;
		}

1138 1139
		const existingWindowBounds = WindowsManager.WINDOWS.map(win => win.getBounds());
		while (existingWindowBounds.some(b => b.x === state.x || b.y === state.y)) {
E
Erich Gamma 已提交
1140 1141 1142 1143 1144 1145 1146
			state.x += 30;
			state.y += 30;
		}

		return state;
	}

1147
	public openFileFolderPicker(forceNewWindow?: boolean): void {
1148
		this.doPickAndOpen({ pickFolders: true, pickFiles: true, forceNewWindow });
1149 1150
	}

1151 1152
	public openFilePicker(forceNewWindow?: boolean, path?: string): void {
		this.doPickAndOpen({ pickFiles: true, forceNewWindow, path });
1153 1154 1155
	}

	public openFolderPicker(forceNewWindow?: boolean): void {
1156
		this.doPickAndOpen({ pickFolders: true, forceNewWindow });
E
Erich Gamma 已提交
1157 1158
	}

1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
	public openAccessibilityOptions(): void {
		let win = new BrowserWindow({
			alwaysOnTop: true,
			skipTaskbar: true,
			resizable: false,
			width: 450,
			height: 300,
			show: true,
			title: nls.localize('accessibilityOptionsWindowTitle', "Accessibility Options")
		});

		win.setMenuBarVisibility(false);

		win.loadURL('chrome://accessibility');
	}

1175
	private doPickAndOpen(options: INativeOpenDialogOptions): void {
1176
		this.getFileOrFolderPaths(options, (paths: string[]) => {
E
Erich Gamma 已提交
1177
			if (paths && paths.length) {
1178
				this.open({ cli: this.environmentService.args, pathsToOpen: paths, forceNewWindow: options.forceNewWindow });
E
Erich Gamma 已提交
1179 1180 1181 1182
			}
		});
	}

1183
	private getFileOrFolderPaths(options: INativeOpenDialogOptions, clb: (paths: string[]) => void): void {
B
Benjamin Pasero 已提交
1184 1185
		const workingDir = options.path || this.storageService.getItem<string>(WindowsManager.workingDirPickerStorageKey);
		const focussedWindow = this.getFocusedWindow();
E
Erich Gamma 已提交
1186

B
Benjamin Pasero 已提交
1187
		let pickerProperties: ('openFile' | 'openDirectory' | 'multiSelections' | 'createDirectory')[];
1188
		if (options.pickFiles && options.pickFolders) {
E
Erich Gamma 已提交
1189 1190
			pickerProperties = ['multiSelections', 'openDirectory', 'openFile', 'createDirectory'];
		} else {
1191
			pickerProperties = ['multiSelections', options.pickFolders ? 'openDirectory' : 'openFile', 'createDirectory'];
E
Erich Gamma 已提交
1192 1193
		}

1194
		dialog.showOpenDialog(focussedWindow && focussedWindow.win, {
E
Erich Gamma 已提交
1195 1196
			defaultPath: workingDir,
			properties: pickerProperties
1197
		}, paths => {
E
Erich Gamma 已提交
1198 1199 1200
			if (paths && paths.length > 0) {

				// Remember path in storage for next time
J
Joao Moreno 已提交
1201
				this.storageService.setItem(WindowsManager.workingDirPickerStorageKey, path.dirname(paths[0]));
E
Erich Gamma 已提交
1202 1203 1204 1205 1206 1207 1208 1209 1210

				// Return
				clb(paths);
			} else {
				clb(void (0));
			}
		});
	}

B
Benjamin Pasero 已提交
1211
	public focusLastActive(cli: ParsedArgs): VSCodeWindow {
B
Benjamin Pasero 已提交
1212
		const lastActive = this.getLastActiveWindow();
E
Erich Gamma 已提交
1213
		if (lastActive) {
B
Benjamin Pasero 已提交
1214
			lastActive.focus();
1215 1216

			return lastActive;
E
Erich Gamma 已提交
1217 1218 1219
		}

		// No window - open new one
1220 1221 1222 1223
		this.windowsState.openedFolders = []; // make sure we do not open too much
		const res = this.open({ cli: cli });

		return res && res[0];
E
Erich Gamma 已提交
1224 1225
	}

J
Joao Moreno 已提交
1226
	public getLastActiveWindow(): VSCodeWindow {
E
Erich Gamma 已提交
1227
		if (WindowsManager.WINDOWS.length) {
1228 1229
			const lastFocussedDate = Math.max.apply(Math, WindowsManager.WINDOWS.map(w => w.lastFocusTime));
			const res = WindowsManager.WINDOWS.filter(w => w.lastFocusTime === lastFocussedDate);
E
Erich Gamma 已提交
1230 1231 1232 1233 1234 1235 1236 1237
			if (res && res.length) {
				return res[0];
			}
		}

		return null;
	}

J
Joao Moreno 已提交
1238
	public findWindow(workspacePath: string, filePath?: string, extensionDevelopmentPath?: string): VSCodeWindow {
E
Erich Gamma 已提交
1239 1240 1241
		if (WindowsManager.WINDOWS.length) {

			// Sort the last active window to the front of the array of windows to test
B
Benjamin Pasero 已提交
1242 1243
			const windowsToTest = WindowsManager.WINDOWS.slice(0);
			const lastActiveWindow = this.getLastActiveWindow();
E
Erich Gamma 已提交
1244 1245 1246 1247 1248 1249
			if (lastActiveWindow) {
				windowsToTest.splice(windowsToTest.indexOf(lastActiveWindow), 1);
				windowsToTest.unshift(lastActiveWindow);
			}

			// Find it
1250
			const res = windowsToTest.filter(w => {
E
Erich Gamma 已提交
1251 1252

				// match on workspace
1253
				if (typeof w.openedWorkspacePath === 'string' && (this.isPathEqual(w.openedWorkspacePath, workspacePath))) {
E
Erich Gamma 已提交
1254 1255 1256 1257
					return true;
				}

				// match on file
B
Benjamin Pasero 已提交
1258
				if (typeof w.openedFilePath === 'string' && this.isPathEqual(w.openedFilePath, filePath)) {
E
Erich Gamma 已提交
1259 1260 1261 1262 1263 1264 1265 1266
					return true;
				}

				// match on file path
				if (typeof w.openedWorkspacePath === 'string' && filePath && paths.isEqualOrParent(filePath, w.openedWorkspacePath)) {
					return true;
				}

1267 1268 1269 1270 1271
				// match on extension development path
				if (typeof extensionDevelopmentPath === 'string' && w.extensionDevelopmentPath === extensionDevelopmentPath) {
					return true;
				}

E
Erich Gamma 已提交
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
				return false;
			});

			if (res && res.length) {
				return res[0];
			}
		}

		return null;
	}

	public openNewWindow(): void {
1284
		this.open({ cli: this.environmentService.args, forceNewWindow: true, forceEmpty: true });
E
Erich Gamma 已提交
1285 1286 1287 1288 1289 1290
	}

	public sendToFocused(channel: string, ...args: any[]): void {
		const focusedWindow = this.getFocusedWindow() || this.getLastActiveWindow();

		if (focusedWindow) {
1291
			focusedWindow.sendWhenReady(channel, ...args);
E
Erich Gamma 已提交
1292 1293 1294 1295
		}
	}

	public sendToAll(channel: string, payload: any, windowIdsToIgnore?: number[]): void {
1296
		WindowsManager.WINDOWS.forEach(w => {
B
Benjamin Pasero 已提交
1297
			if (windowIdsToIgnore && windowIdsToIgnore.indexOf(w.id) >= 0) {
E
Erich Gamma 已提交
1298 1299 1300
				return; // do not send if we are instructed to ignore it
			}

1301
			w.sendWhenReady(channel, payload);
E
Erich Gamma 已提交
1302 1303 1304
		});
	}

J
Joao Moreno 已提交
1305
	public getFocusedWindow(): VSCodeWindow {
B
Benjamin Pasero 已提交
1306
		const win = BrowserWindow.getFocusedWindow();
E
Erich Gamma 已提交
1307 1308 1309 1310 1311 1312 1313
		if (win) {
			return this.getWindowById(win.id);
		}

		return null;
	}

J
Joao Moreno 已提交
1314
	public getWindowById(windowId: number): VSCodeWindow {
1315
		const res = WindowsManager.WINDOWS.filter(w => w.id === windowId);
E
Erich Gamma 已提交
1316 1317 1318 1319 1320 1321 1322
		if (res && res.length === 1) {
			return res[0];
		}

		return null;
	}

J
Joao Moreno 已提交
1323
	public getWindows(): VSCodeWindow[] {
E
Erich Gamma 已提交
1324 1325 1326 1327 1328 1329 1330
		return WindowsManager.WINDOWS;
	}

	public getWindowCount(): number {
		return WindowsManager.WINDOWS.length;
	}

J
Joao Moreno 已提交
1331
	private onWindowError(vscodeWindow: VSCodeWindow, error: WindowError): void {
E
Erich Gamma 已提交
1332 1333 1334 1335
		console.error(error === WindowError.CRASHED ? '[VS Code]: render process crashed!' : '[VS Code]: detected unresponsive');

		// Unresponsive
		if (error === WindowError.UNRESPONSIVE) {
1336
			dialog.showMessageBox(vscodeWindow.win, {
B
Benjamin Pasero 已提交
1337
				title: product.nameLong,
E
Erich Gamma 已提交
1338
				type: 'warning',
B
Benjamin Pasero 已提交
1339
				buttons: [nls.localize('reopen', "Reopen"), nls.localize('wait', "Keep Waiting"), nls.localize('close', "Close")],
1340
				message: nls.localize('appStalled', "The window is no longer responding"),
B
Benjamin Pasero 已提交
1341
				detail: nls.localize('appStalledDetail', "You can reopen or close the window or keep waiting."),
E
Erich Gamma 已提交
1342
				noLink: true
1343
			}, result => {
E
Erich Gamma 已提交
1344
				if (result === 0) {
1345 1346
					vscodeWindow.reload();
				} else if (result === 2) {
1347
					this.onBeforeWindowClose(vscodeWindow); // 'close' event will not be fired on destroy(), so run it manually
1348
					vscodeWindow.win.destroy(); // make sure to destroy the window as it is unresponsive
E
Erich Gamma 已提交
1349 1350 1351 1352 1353 1354
				}
			});
		}

		// Crashed
		else {
1355
			dialog.showMessageBox(vscodeWindow.win, {
B
Benjamin Pasero 已提交
1356
				title: product.nameLong,
E
Erich Gamma 已提交
1357
				type: 'warning',
B
Benjamin Pasero 已提交
1358
				buttons: [nls.localize('reopen', "Reopen"), nls.localize('close', "Close")],
1359
				message: nls.localize('appCrashed', "The window has crashed"),
B
Benjamin Pasero 已提交
1360
				detail: nls.localize('appCrashedDetail', "We are sorry for the inconvenience! You can reopen the window to continue where you left off."),
E
Erich Gamma 已提交
1361
				noLink: true
1362
			}, result => {
1363 1364 1365
				if (result === 0) {
					vscodeWindow.reload();
				} else if (result === 1) {
1366
					this.onBeforeWindowClose(vscodeWindow); // 'close' event will not be fired on destroy(), so run it manually
1367 1368
					vscodeWindow.win.destroy(); // make sure to destroy the window as it has crashed
				}
E
Erich Gamma 已提交
1369 1370 1371 1372
			});
		}
	}

J
Joao Moreno 已提交
1373 1374
	private onBeforeWindowClose(win: VSCodeWindow): void {
		if (win.readyState !== ReadyState.READY) {
E
Erich Gamma 已提交
1375 1376 1377 1378
			return; // only persist windows that are fully loaded
		}

		// On Window close, update our stored state of this window
B
Benjamin Pasero 已提交
1379
		const state: IWindowState = { workspacePath: win.openedWorkspacePath, uiState: win.serializeWindowState() };
E
Erich Gamma 已提交
1380 1381 1382 1383 1384 1385
		if (win.isPluginDevelopmentHost) {
			this.windowsState.lastPluginDevelopmentHostWindow = state;
		} else {
			this.windowsState.lastActiveWindow = state;

			this.windowsState.openedFolders.forEach(o => {
B
Benjamin Pasero 已提交
1386
				if (this.isPathEqual(o.workspacePath, win.openedWorkspacePath)) {
E
Erich Gamma 已提交
1387 1388 1389 1390 1391 1392
					o.uiState = state.uiState;
				}
			});
		}
	}

J
Joao Moreno 已提交
1393
	private onWindowClosed(win: VSCodeWindow): void {
E
Erich Gamma 已提交
1394 1395 1396 1397 1398

		// Tell window
		win.dispose();

		// Remove from our list so that Electron can clean it up
B
Benjamin Pasero 已提交
1399
		const index = WindowsManager.WINDOWS.indexOf(win);
E
Erich Gamma 已提交
1400 1401 1402
		WindowsManager.WINDOWS.splice(index, 1);

		// Emit
J
Joao Moreno 已提交
1403
		this.eventEmitter.emit(EventTypes.CLOSE, win.id);
E
Erich Gamma 已提交
1404
	}
B
Benjamin Pasero 已提交
1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428

	private isPathEqual(pathA: string, pathB: string): boolean {
		if (pathA === pathB) {
			return true;
		}

		if (!pathA || !pathB) {
			return false;
		}

		pathA = path.normalize(pathA);
		pathB = path.normalize(pathB);

		if (pathA === pathB) {
			return true;
		}

		if (!platform.isLinux) {
			pathA = pathA.toLowerCase();
			pathB = pathB.toLowerCase();
		}

		return pathA === pathB;
	}
1429
}