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


'use strict';

import events = require('events');
import path = require('path');
import fs = require('fs');
12
import {ipcMain as ipc, app, screen, crashReporter, BrowserWindow, dialog} from 'electron';
E
Erich Gamma 已提交
13
import platform = require('vs/base/common/platform');
14 15 16
import { ICommandLineArguments, IProcessEnvironment, IEnvironmentService, IParsedPath, parseLineAndColumnAware } from 'vs/code/electron-main/env';
import window = require('vs/code/electron-main/window');
import { ILifecycleService } from 'vs/code/electron-main/lifecycle';
E
Erich Gamma 已提交
17 18 19 20
import nls = require('vs/nls');
import paths = require('vs/base/common/paths');
import arrays = require('vs/base/common/arrays');
import objects = require('vs/base/common/objects');
21 22 23
import storage = require('vs/code/electron-main/storage');
import {ISettingsService} from 'vs/code/electron-main/settings';
import {IUpdateService, IUpdate} from 'vs/code/electron-main/update-manager';
J
Joao Moreno 已提交
24 25
import { ILogService } from './log';
import {ServiceIdentifier, createDecorator, IInstantiationService} from 'vs/platform/instantiation/common/instantiation';
E
Erich Gamma 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38

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

enum WindowError {
	UNRESPONSIVE,
	CRASHED
}

export interface IOpenConfiguration {
J
Joao Moreno 已提交
39 40
	cli: ICommandLineArguments;
	userEnv?: IProcessEnvironment;
E
Erich Gamma 已提交
41
	pathsToOpen?: string[];
42
	preferNewWindow?: boolean;
E
Erich Gamma 已提交
43 44 45
	forceNewWindow?: boolean;
	forceEmpty?: boolean;
	windowToUse?: window.VSCodeWindow;
46
	diffMode?: boolean;
E
Erich Gamma 已提交
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
}

interface IWindowState {
	workspacePath?: string;
	uiState: window.IWindowState;
}

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

export interface IOpenedPathsList {
	folders: string[];
	files: string[];
}

65 66 67 68 69
interface ILogEntry {
	severity: string;
	arguments: any;
}

70 71 72 73 74
interface INativeOpenDialogOptions {
	pickFolders?: boolean;
	pickFiles?: boolean;
}

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

J
renames  
Joao Moreno 已提交
77
export interface IWindowsService {
J
Joao Moreno 已提交
78 79 80 81 82 83 84 85 86
	serviceId: ServiceIdentifier<any>;

	// TODO make proper events
	// events
	onOpen(clb: (path: window.IPath) => void): () => void;
	onReady(clb: (win: window.VSCodeWindow) => void): () => void;
	onClose(clb: (id: number) => void): () => void;

	// methods
J
Joao Moreno 已提交
87 88
	ready(initialUserEnv: IProcessEnvironment): void;
	reload(win: window.VSCodeWindow, cli?: ICommandLineArguments): void;
J
Joao Moreno 已提交
89 90 91 92 93
	open(openConfig: IOpenConfiguration): window.VSCodeWindow[];
	openPluginDevelopmentHostWindow(openConfig: IOpenConfiguration): void;
	openFileFolderPicker(forceNewWindow?: boolean): void;
	openFilePicker(forceNewWindow?: boolean): void;
	openFolderPicker(forceNewWindow?: boolean): void;
J
Joao Moreno 已提交
94
	focusLastActive(cli: ICommandLineArguments): window.VSCodeWindow;
J
Joao Moreno 已提交
95 96 97 98 99 100 101 102 103 104 105
	getLastActiveWindow(): window.VSCodeWindow;
	findWindow(workspacePath: string, filePath?: string, extensionDevelopmentPath?: string): window.VSCodeWindow;
	openNewWindow(): void;
	sendToFocused(channel: string, ...args: any[]): void;
	sendToAll(channel: string, payload: any, windowIdsToIgnore?: number[]): void;
	getFocusedWindow(): window.VSCodeWindow;
	getWindowById(windowId: number): window.VSCodeWindow;
	getWindows(): window.VSCodeWindow[];
	getWindowCount(): number;
}

J
renames  
Joao Moreno 已提交
106
export class WindowsManager implements IWindowsService {
J
Joao Moreno 已提交
107

J
renames  
Joao Moreno 已提交
108
	serviceId = IWindowsService;
E
Erich Gamma 已提交
109 110 111

	public static openedPathsListStorageKey = 'openedPathsList';

112
	private static workingDirPickerStorageKey = 'pickerWorkingDir';
E
Erich Gamma 已提交
113 114 115 116
	private static windowsStateStorageKey = 'windowsState';

	private static WINDOWS: window.VSCodeWindow[] = [];

J
Joao Moreno 已提交
117
	private eventEmitter = new events.EventEmitter();
J
Joao Moreno 已提交
118
	private initialUserEnv: IProcessEnvironment;
E
Erich Gamma 已提交
119 120
	private windowsState: IWindowsState;

J
Joao Moreno 已提交
121 122 123 124
	constructor(
		@IInstantiationService private instantiationService: IInstantiationService,
		@ILogService private logService: ILogService,
		@storage.IStorageService private storageService: storage.IStorageService,
J
renames  
Joao Moreno 已提交
125
		@IEnvironmentService private envService: IEnvironmentService,
J
Joao Moreno 已提交
126
		@ILifecycleService private lifecycleService: ILifecycleService,
J
renames  
Joao Moreno 已提交
127 128
		@IUpdateService private updateManager: IUpdateService,
		@ISettingsService private settingsManager: ISettingsService
J
Joao Moreno 已提交
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
	) {	}

	onOpen(clb: (path: window.IPath) => void): () => void {
		this.eventEmitter.addListener(EventTypes.OPEN, clb);

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

	onReady(clb: (win: window.VSCodeWindow) => void): () => void {
		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);
	}

J
Joao Moreno 已提交
149
	public ready(initialUserEnv: IProcessEnvironment): void {
E
Erich Gamma 已提交
150 151
		this.registerListeners();

152
		this.initialUserEnv = initialUserEnv;
J
Joao Moreno 已提交
153
		this.windowsState = this.storageService.getItem<IWindowsState>(WindowsManager.windowsStateStorageKey) || { openedFolders: [] };
E
Erich Gamma 已提交
154 155 156
	}

	private registerListeners(): void {
157
		app.on('activate', (event: Event, hasVisibleWindows: boolean) => {
J
Joao Moreno 已提交
158
			this.logService.log('App#activate');
E
Erich Gamma 已提交
159 160 161 162 163

			// Mac only event: reopen last window when we get activated
			if (!hasVisibleWindows) {

				// We want to open the previously opened folder, so we dont pass on the path argument
J
Joao Moreno 已提交
164
				let cliArgWithoutPath = objects.clone(this.envService.cliArgs);
E
Erich Gamma 已提交
165 166 167
				cliArgWithoutPath.pathArguments = [];
				this.windowsState.openedFolders = []; // make sure we do not restore too much

B
Benjamin Pasero 已提交
168
				this.open({ cli: cliArgWithoutPath });
E
Erich Gamma 已提交
169 170 171 172 173 174
			}
		});

		let macOpenFiles: string[] = [];
		let runningTimeout: number = null;
		app.on('open-file', (event: Event, path: string) => {
J
Joao Moreno 已提交
175
			this.logService.log('App#open-file: ', path);
E
Erich Gamma 已提交
176 177 178 179 180 181 182 183 184 185 186 187 188
			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(() => {
J
Joao Moreno 已提交
189
				this.open({ cli: this.envService.cliArgs, pathsToOpen: macOpenFiles, preferNewWindow: true /* dropping on the dock prefers to open in a new window */ });
E
Erich Gamma 已提交
190 191 192 193 194
				macOpenFiles = [];
				runningTimeout = null;
			}, 100);
		});

J
Joao Moreno 已提交
195
		this.settingsManager.onChange((newSettings) => {
E
Erich Gamma 已提交
196
			this.sendToAll('vscode:optionsChange', JSON.stringify({ globalSettings: newSettings }));
197
		}, this);
E
Erich Gamma 已提交
198 199

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

E
Erich Gamma 已提交
202 203 204
			crashReporter.start(config);
		});

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

			if (paths && paths.length) {
J
Joao Moreno 已提交
209
				this.open({ cli: this.envService.cliArgs, pathsToOpen: paths, forceNewWindow: forceNewWindow });
E
Erich Gamma 已提交
210 211 212
			}
		});

B
Benjamin Pasero 已提交
213
		ipc.on('vscode:workbenchLoaded', (event, windowId: number) => {
J
Joao Moreno 已提交
214
			this.logService.log('IPC#vscode-workbenchLoaded');
E
Erich Gamma 已提交
215 216 217 218 219 220

			let win = this.getWindowById(windowId);
			if (win) {
				win.setReady();

				// Event
J
Joao Moreno 已提交
221
				this.eventEmitter.emit(EventTypes.READY, win);
E
Erich Gamma 已提交
222 223 224
			}
		});

B
Benjamin Pasero 已提交
225
		ipc.on('vscode:openFilePicker', () => {
J
Joao Moreno 已提交
226
			this.logService.log('IPC#vscode-openFilePicker');
E
Erich Gamma 已提交
227

B
Benjamin Pasero 已提交
228
			this.openFilePicker();
E
Erich Gamma 已提交
229 230
		});

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

234 235 236 237
			this.openFolderPicker(forceNewWindow);
		});

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

			this.openFileFolderPicker(forceNewWindow);
E
Erich Gamma 已提交
241 242
		});

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

			let win = this.getWindowById(windowId);
			if (win) {
J
Joao Moreno 已提交
248
				this.open({ cli: this.envService.cliArgs, forceEmpty: true, windowToUse: win });
E
Erich Gamma 已提交
249 250 251
			}
		});

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

B
Benjamin Pasero 已提交
255
			this.openNewWindow();
E
Erich Gamma 已提交
256 257
		});

B
Benjamin Pasero 已提交
258
		ipc.on('vscode:reloadWindow', (event, windowId: number) => {
J
Joao Moreno 已提交
259
			this.logService.log('IPC#vscode:reloadWindow');
E
Erich Gamma 已提交
260 261 262 263 264 265 266

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

B
Benjamin Pasero 已提交
267
		ipc.on('vscode:toggleFullScreen', (event, windowId: number) => {
J
Joao Moreno 已提交
268
			this.logService.log('IPC#vscode:toggleFullScreen');
E
Erich Gamma 已提交
269 270 271 272 273 274 275

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

276
		ipc.on('vscode:setFullScreen', (event, windowId: number, fullscreen: boolean) => {
J
Joao Moreno 已提交
277
			this.logService.log('IPC#vscode:setFullScreen');
278 279 280 281 282 283 284 285

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

		ipc.on('vscode:toggleDevTools', (event, windowId: number) => {
J
Joao Moreno 已提交
286
			this.logService.log('IPC#vscode:toggleDevTools');
287 288 289 290 291 292 293 294

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

		ipc.on('vscode:openDevTools', (event, windowId: number) => {
J
Joao Moreno 已提交
295
			this.logService.log('IPC#vscode:openDevTools');
296 297 298 299 300 301 302 303 304

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

		ipc.on('vscode:setRepresentedFilename', (event, windowId: number, fileName: string) => {
J
Joao Moreno 已提交
305
			this.logService.log('IPC#vscode:setRepresentedFilename');
306 307 308 309 310 311 312 313

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

		ipc.on('vscode:setMenuBarVisibility', (event, windowId: number, visibility: boolean) => {
J
Joao Moreno 已提交
314
			this.logService.log('IPC#vscode:setMenuBarVisibility');
315 316 317 318 319 320 321 322

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

		ipc.on('vscode:flashFrame', (event, windowId: number) => {
J
Joao Moreno 已提交
323
			this.logService.log('IPC#vscode:flashFrame');
324 325 326 327 328 329 330 331

			let vscodeWindow = this.getWindowById(windowId);
			if (vscodeWindow) {
				vscodeWindow.win.flashFrame(!vscodeWindow.win.isFocused());
			}
		});

		ipc.on('vscode:focusWindow', (event, windowId: number) => {
J
Joao Moreno 已提交
332
			this.logService.log('IPC#vscode:focusWindow');
333 334 335 336 337 338 339 340

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

		ipc.on('vscode:setDocumentEdited', (event, windowId: number, edited: boolean) => {
J
Joao Moreno 已提交
341
			this.logService.log('IPC#vscode:setDocumentEdited');
342 343 344 345 346 347 348

			let vscodeWindow = this.getWindowById(windowId);
			if (vscodeWindow && vscodeWindow.win.isDocumentEdited() !== edited) {
				vscodeWindow.win.setDocumentEdited(edited);
			}
		});

B
Benjamin Pasero 已提交
349
		ipc.on('vscode:toggleMenuBar', (event, windowId: number) => {
J
Joao Moreno 已提交
350
			this.logService.log('IPC#vscode:toggleMenuBar');
351 352

			// Update in settings
J
Joao Moreno 已提交
353
			let menuBarHidden = this.storageService.getItem(window.VSCodeWindow.menuBarHiddenKey, false);
354
			let newMenuBarHidden = !menuBarHidden;
J
Joao Moreno 已提交
355
			this.storageService.setItem(window.VSCodeWindow.menuBarHiddenKey, newMenuBarHidden);
356 357 358

			// Update across windows
			WindowsManager.WINDOWS.forEach(w => w.setMenuBarVisibility(!newMenuBarHidden));
359 360 361 362 363 364 365 366

			// Inform user if menu bar is now hidden
			if (newMenuBarHidden) {
				let vscodeWindow = this.getWindowById(windowId);
				if (vscodeWindow) {
					vscodeWindow.send('vscode:showInfoMessage', nls.localize('hiddenMenuBar', "You can still access the menu bar by pressing the **Alt** key."));
				}
			}
367 368
		});

B
Benjamin Pasero 已提交
369
		ipc.on('vscode:broadcast', (event, windowId: number, target: string, broadcast: { channel: string; payload: any; }) => {
E
Erich Gamma 已提交
370
			if (broadcast.channel && broadcast.payload) {
J
Joao Moreno 已提交
371
				this.logService.log('IPC#vscode:broadcast', target, broadcast.channel, broadcast.payload);
B
Benjamin Pasero 已提交
372

373 374 375 376
				// Handle specific events on main side
				this.onBroadcast(broadcast.channel, broadcast.payload);

				// Send to windows
377
				if (target) {
B
Benjamin Pasero 已提交
378
					const otherWindowsWithTarget = WindowsManager.WINDOWS.filter(w => w.id !== windowId && typeof w.openedWorkspacePath === 'string');
379 380 381 382 383
					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) {
384 385 386 387 388
						targetWindow.send('vscode:broadcast', broadcast);
					}
				} else {
					this.sendToAll('vscode:broadcast', broadcast, [windowId]);
				}
E
Erich Gamma 已提交
389
			}
390 391
		});

B
Benjamin Pasero 已提交
392
		ipc.on('vscode:log', (event, logEntry: ILogEntry) => {
393 394 395 396 397 398 399 400 401 402
			let args = [];
			try {
				let parsed = JSON.parse(logEntry.arguments);
				args.push(...Object.getOwnPropertyNames(parsed).map(o => parsed[o]));
			} catch (error) {
				args.push(logEntry.arguments);
			}

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

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

407 408 409 410 411 412
			const windowOnExtension = this.findWindow(null, null, extensionDevelopmentPath);
			if (windowOnExtension) {
				windowOnExtension.win.close();
			}
		});

J
Joao Moreno 已提交
413
		this.updateManager.on('update-downloaded', (update: IUpdate) => {
E
Erich Gamma 已提交
414 415 416 417 418 419 420 421 422
			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 已提交
423
		ipc.on('vscode:update-apply', () => {
J
Joao Moreno 已提交
424
			this.logService.log('IPC#vscode:update-apply');
E
Erich Gamma 已提交
425

J
Joao Moreno 已提交
426 427
			if (this.updateManager.availableUpdate) {
				this.updateManager.availableUpdate.quitAndUpdate();
E
Erich Gamma 已提交
428 429 430
			}
		});

J
Joao Moreno 已提交
431
		this.updateManager.on('update-not-available', (explicit: boolean) => {
E
Erich Gamma 已提交
432 433 434 435 436 437 438
			this.sendToFocused('vscode:telemetry', { eventName: 'update:notAvailable', data: { explicit } });

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

J
Joao Moreno 已提交
439
		this.updateManager.on('update-available', (url: string) => {
J
Joao Moreno 已提交
440 441 442 443 444
			if (url) {
				this.sendToFocused('vscode:update-available', url);
			}
		});

J
Joao Moreno 已提交
445
		this.lifecycleService.onBeforeQuit(() => {
E
Erich Gamma 已提交
446 447 448 449 450 451 452 453 454 455 456 457

			// 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
			this.windowsState.openedFolders = WindowsManager.WINDOWS.filter(w => w.readyState === window.ReadyState.READY && !!w.openedWorkspacePath && !w.isPluginDevelopmentHost).map(w => {
				return <IWindowState>{
					workspacePath: w.openedWorkspacePath,
					uiState: w.serializeWindowState()
B
Benjamin Pasero 已提交
458
				};
E
Erich Gamma 已提交
459 460 461 462
			});
		});

		app.on('will-quit', () => {
J
Joao Moreno 已提交
463
			this.storageService.setItem(WindowsManager.windowsStateStorageKey, this.windowsState);
E
Erich Gamma 已提交
464
		});
465 466

		let loggedStartupTimes = false;
J
Joao Moreno 已提交
467
		this.onReady(window => {
468 469 470 471 472 473 474 475
			if (loggedStartupTimes) {
				return; // only for the first window
			}

			loggedStartupTimes = true;

			window.send('vscode:telemetry', { eventName: 'startupTime', data: { ellapsed: Date.now() - global.vscodeStart } });
		});
E
Erich Gamma 已提交
476 477
	}

478 479 480 481
	private onBroadcast(event: string, payload: any): void {

		// Theme changes
		if (event === 'vscode:changeTheme' && typeof payload === 'string') {
J
Joao Moreno 已提交
482
			this.storageService.setItem(window.VSCodeWindow.themeStorageKey, payload);
483 484 485
		}
	}

J
Joao Moreno 已提交
486
	public reload(win: window.VSCodeWindow, cli?: ICommandLineArguments): void {
E
Erich Gamma 已提交
487 488

		// Only reload when the window has not vetoed this
J
Joao Moreno 已提交
489
		this.lifecycleService.unload(win).done((veto) => {
E
Erich Gamma 已提交
490 491 492 493 494 495
			if (!veto) {
				win.reload(cli);
			}
		});
	}

496
	public open(openConfig: IOpenConfiguration): window.VSCodeWindow[] {
E
Erich Gamma 已提交
497
		let iPathsToOpen: window.IPath[];
498
		let usedWindows: window.VSCodeWindow[] = [];
E
Erich Gamma 已提交
499 500 501 502 503 504 505 506 507

		// Find paths from provided paths if any
		if (openConfig.pathsToOpen && openConfig.pathsToOpen.length > 0) {
			iPathsToOpen = openConfig.pathsToOpen.map((pathToOpen) => {
				let iPath = this.toIPath(pathToOpen, false, openConfig.cli && openConfig.cli.gotoLineMode);

				// Warn if the requested path to open does not exist
				if (!iPath) {
					let options = {
J
Joao Moreno 已提交
508
						title: this.envService.product.nameLong,
E
Erich Gamma 已提交
509 510 511 512 513 514 515 516 517
						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
					};

					let activeWindow = BrowserWindow.getFocusedWindow();
					if (activeWindow) {
518
						dialog.showMessageBox(activeWindow, options);
E
Erich Gamma 已提交
519
					} else {
520
						dialog.showMessageBox(options);
E
Erich Gamma 已提交
521 522 523 524 525 526 527 528 529 530
					}
				}

				return iPath;
			});

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

			if (iPathsToOpen.length === 0) {
531
				return null; // indicate to outside that open failed
E
Erich Gamma 已提交
532 533 534 535 536 537 538 539 540 541 542 543 544 545
			}
		}

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

		// Otherwise infer from command line arguments
		else {
			let ignoreFileNotFound = openConfig.cli.pathArguments.length > 0; // we assume the user wants to create this file from command line
			iPathsToOpen = this.cliToPaths(openConfig.cli, ignoreFileNotFound);
		}

546 547
		let filesToOpen: window.IPath[] = [];
		let filesToDiff: window.IPath[] = [];
548 549 550 551 552 553
		let foldersToOpen = iPathsToOpen.filter((iPath) => iPath.workspacePath && !iPath.filePath && !iPath.installExtensionPath);
		let emptyToOpen = iPathsToOpen.filter((iPath) => !iPath.workspacePath && !iPath.filePath && !iPath.installExtensionPath);
		let extensionsToInstall = iPathsToOpen.filter((iPath) => iPath.installExtensionPath).map(ipath => ipath.filePath);
		let filesToCreate = iPathsToOpen.filter((iPath) => !!iPath.filePath && iPath.createFilePath && !iPath.installExtensionPath);

		// Diff mode needs special care
554
		let candidates = iPathsToOpen.filter((iPath) => !!iPath.filePath && !iPath.createFilePath && !iPath.installExtensionPath);
555 556 557 558 559 560 561
		if (openConfig.diffMode) {
			if (candidates.length === 2) {
				filesToDiff = candidates;
			} else {
				emptyToOpen = [Object.create(null)]; // improper use of diffMode, open empty
			}

562
			foldersToOpen = []; // diff is always in empty workspace
B
Benjamin Pasero 已提交
563
			filesToCreate = []; // diff ignores other files that do not exist
564 565 566 567
		} else {
			filesToOpen = candidates;
		}

E
Erich Gamma 已提交
568 569
		let configuration: window.IWindowConfiguration;

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

573 574 575 576 577 578 579
			// Let the user settings override how files are open in a new window or same window unless we are forced
			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!)
J
Joao Moreno 已提交
580
					openFilesInNewWindow = this.settingsManager.getValue('window.openFilesInNewWindow', openFilesInNewWindow);
581
				}
E
Erich Gamma 已提交
582 583 584 585 586
			}

			// Open Files in last instance if any and flag tells us so
			let lastActiveWindow = this.getLastActiveWindow();
			if (!openFilesInNewWindow && lastActiveWindow) {
B
Benjamin Pasero 已提交
587
				lastActiveWindow.focus();
E
Erich Gamma 已提交
588
				lastActiveWindow.ready().then((readyWindow) => {
589
					readyWindow.send('vscode:openFiles', {
E
Erich Gamma 已提交
590
						filesToOpen: filesToOpen,
591 592
						filesToCreate: filesToCreate,
						filesToDiff: filesToDiff
E
Erich Gamma 已提交
593 594 595
					});

					if (extensionsToInstall.length) {
596
						readyWindow.send('vscode:installExtensions', { extensionsToInstall });
E
Erich Gamma 已提交
597 598
					}
				});
599 600

				usedWindows.push(lastActiveWindow);
E
Erich Gamma 已提交
601 602 603 604
			}

			// Otherwise open instance with files
			else {
605
				configuration = this.toConfiguration(openConfig.userEnv || this.initialUserEnv, openConfig.cli, null, filesToOpen, filesToCreate, filesToDiff, extensionsToInstall);
606 607
				let browserWindow = this.openInBrowserWindow(configuration, true /* new window */);
				usedWindows.push(browserWindow);
E
Erich Gamma 已提交
608 609 610 611 612 613

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

		// Handle folders to open
614
		let openInNewWindow = openConfig.preferNewWindow || openConfig.forceNewWindow;
E
Erich Gamma 已提交
615 616 617 618 619
		if (foldersToOpen.length > 0) {

			// Check for existing instances
			let windowsOnWorkspacePath = arrays.coalesce(foldersToOpen.map((iPath) => this.findWindow(iPath.workspacePath)));
			if (windowsOnWorkspacePath.length > 0) {
620 621 622
				let browserWindow = windowsOnWorkspacePath[0];
				browserWindow.focus(); // just focus one of them
				browserWindow.ready().then((readyWindow) => {
623
					readyWindow.send('vscode:openFiles', {
E
Erich Gamma 已提交
624
						filesToOpen: filesToOpen,
625 626
						filesToCreate: filesToCreate,
						filesToDiff: filesToDiff
E
Erich Gamma 已提交
627 628 629
					});

					if (extensionsToInstall.length) {
630
						readyWindow.send('vscode:installExtensions', { extensionsToInstall });
E
Erich Gamma 已提交
631 632 633
					}
				});

634 635
				usedWindows.push(browserWindow);

E
Erich Gamma 已提交
636 637 638
				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
639
				filesToDiff = [];
E
Erich Gamma 已提交
640 641
				extensionsToInstall = [];

642
				openInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
643 644 645 646
			}

			// Open remaining ones
			foldersToOpen.forEach((folderToOpen) => {
B
Benjamin Pasero 已提交
647
				if (windowsOnWorkspacePath.some((win) => this.isPathEqual(win.openedWorkspacePath, folderToOpen.workspacePath))) {
E
Erich Gamma 已提交
648 649 650
					return; // ignore folders that are already open
				}

651
				configuration = this.toConfiguration(openConfig.userEnv || this.initialUserEnv, openConfig.cli, folderToOpen.workspacePath, filesToOpen, filesToCreate, filesToDiff, extensionsToInstall);
652
				let browserWindow = this.openInBrowserWindow(configuration, openInNewWindow, openInNewWindow ? void 0 : openConfig.windowToUse);
653
				usedWindows.push(browserWindow);
E
Erich Gamma 已提交
654 655 656 657

				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
658
				filesToDiff = [];
E
Erich Gamma 已提交
659 660
				extensionsToInstall = [];

661
				openInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
662 663 664 665 666 667
			});
		}

		// Handle empty
		if (emptyToOpen.length > 0) {
			emptyToOpen.forEach(() => {
668
				let configuration = this.toConfiguration(openConfig.userEnv || this.initialUserEnv, openConfig.cli);
669
				let browserWindow = this.openInBrowserWindow(configuration, openInNewWindow, openInNewWindow ? void 0 : openConfig.windowToUse);
670
				usedWindows.push(browserWindow);
E
Erich Gamma 已提交
671

672
				openInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
673 674 675 676 677 678 679 680 681 682 683
			});
		}

		// Remember in recent document list
		iPathsToOpen.forEach((iPath) => {
			if (iPath.filePath || iPath.workspacePath) {
				app.addRecentDocument(iPath.filePath || iPath.workspacePath);
			}
		});

		// Emit events
J
Joao Moreno 已提交
684
		iPathsToOpen.forEach((iPath) => this.eventEmitter.emit(EventTypes.OPEN, iPath));
E
Erich Gamma 已提交
685

686
		return arrays.distinct(usedWindows);
E
Erich Gamma 已提交
687 688 689 690 691 692 693
	}

	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.
A
Alex Dima 已提交
694
		let res = WindowsManager.WINDOWS.filter((w) => w.config && this.isPathEqual(w.config.extensionDevelopmentPath, openConfig.cli.extensionDevelopmentPath));
E
Erich Gamma 已提交
695 696
		if (res && res.length === 1) {
			this.reload(res[0], openConfig.cli);
B
Benjamin Pasero 已提交
697
			res[0].focus(); // make sure it gets focus and is restored
E
Erich Gamma 已提交
698 699 700 701

			return;
		}

702 703
		// Fill in previously opened workspace unless an explicit path is provided and we are not unit testing
		if (openConfig.cli.pathArguments.length === 0 && !openConfig.cli.extensionTestsPath) {
E
Erich Gamma 已提交
704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
			let workspaceToOpen = this.windowsState.lastPluginDevelopmentHostWindow && this.windowsState.lastPluginDevelopmentHostWindow.workspacePath;
			if (workspaceToOpen) {
				openConfig.cli.pathArguments = [workspaceToOpen];
			}
		}

		// Make sure we are not asked to open a path that is already opened
		if (openConfig.cli.pathArguments.length > 0) {
			res = WindowsManager.WINDOWS.filter((w) => w.openedWorkspacePath && openConfig.cli.pathArguments.indexOf(w.openedWorkspacePath) >= 0);
			if (res.length) {
				openConfig.cli.pathArguments = [];
			}
		}

		// Open it
		this.open({ cli: openConfig.cli, forceNewWindow: true, forceEmpty: openConfig.cli.pathArguments.length === 0 });
	}

J
Joao Moreno 已提交
722
	private toConfiguration(userEnv: IProcessEnvironment, cli: ICommandLineArguments, workspacePath?: string, filesToOpen?: window.IPath[], filesToCreate?: window.IPath[], filesToDiff?: window.IPath[], extensionsToInstall?: string[]): window.IWindowConfiguration {
E
Erich Gamma 已提交
723 724 725 726 727
		let configuration: window.IWindowConfiguration = objects.mixin({}, cli); // inherit all properties from CLI
		configuration.execPath = process.execPath;
		configuration.workspacePath = workspacePath;
		configuration.filesToOpen = filesToOpen;
		configuration.filesToCreate = filesToCreate;
728
		configuration.filesToDiff = filesToDiff;
E
Erich Gamma 已提交
729
		configuration.extensionsToInstall = extensionsToInstall;
J
Joao Moreno 已提交
730 731 732
		configuration.appName = this.envService.product.nameLong;
		configuration.applicationName = this.envService.product.applicationName;
		configuration.darwinBundleIdentifier = this.envService.product.darwinBundleIdentifier;
J
Joao Moreno 已提交
733 734
		configuration.appRoot = this.envService.appRoot;
		configuration.version = this.envService.version;
J
Joao Moreno 已提交
735
		configuration.commitHash = this.envService.product.commit;
J
Joao Moreno 已提交
736 737 738
		configuration.appSettingsHome = this.envService.appSettingsHome;
		configuration.appSettingsPath = this.envService.appSettingsPath;
		configuration.appKeybindingsPath = this.envService.appKeybindingsPath;
J
Joao Moreno 已提交
739
		configuration.userExtensionsHome = this.envService.userExtensionsHome;
J
Joao Moreno 已提交
740 741 742 743 744 745 746 747 748 749
		configuration.extensionTips = this.envService.product.extensionTips;
		configuration.mainIPCHandle = this.envService.mainIPCHandle;
		configuration.sharedIPCHandle = this.envService.sharedIPCHandle;
		configuration.isBuilt = this.envService.isBuilt;
		configuration.crashReporter = this.envService.product.crashReporter;
		configuration.extensionsGallery = this.envService.product.extensionsGallery;
		configuration.welcomePage = this.envService.product.welcomePage;
		configuration.productDownloadUrl = this.envService.product.downloadUrl;
		configuration.releaseNotesUrl = this.envService.product.releaseNotesUrl;
		configuration.licenseUrl = this.envService.product.licenseUrl;
J
Joao Moreno 已提交
750 751
		configuration.updateFeedUrl = this.updateManager.feedUrl;
		configuration.updateChannel = this.updateManager.channel;
J
Joao Moreno 已提交
752 753 754
		configuration.aiConfig = this.envService.product.aiConfig;
		configuration.sendASmile = this.envService.product.sendASmile;
		configuration.enableTelemetry = this.envService.product.enableTelemetry;
755
		configuration.userEnv = userEnv;
E
Erich Gamma 已提交
756

757 758 759 760
		const recents = this.getRecentlyOpenedPaths(workspacePath, filesToOpen);
		configuration.recentFiles = recents.files;
		configuration.recentFolders = recents.folders;

E
Erich Gamma 已提交
761 762 763
		return configuration;
	}

764 765 766
	private getRecentlyOpenedPaths(workspacePath?: string, filesToOpen?: window.IPath[]): IOpenedPathsList {
		let files: string[];
		let folders: string[];
E
Erich Gamma 已提交
767 768

		// Get from storage
J
Joao Moreno 已提交
769
		let storedRecents = this.storageService.getItem<IOpenedPathsList>(WindowsManager.openedPathsListStorageKey);
770 771 772 773 774 775
		if (storedRecents) {
			files = storedRecents.files || [];
			folders = storedRecents.folders || [];
		} else {
			files = [];
			folders = [];
E
Erich Gamma 已提交
776 777 778 779
		}

		// Add currently files to open to the beginning if any
		if (filesToOpen) {
780
			files.unshift(...filesToOpen.map(f => f.filePath));
E
Erich Gamma 已提交
781 782 783 784
		}

		// Add current workspace path to beginning if set
		if (workspacePath) {
785
			folders.unshift(workspacePath);
E
Erich Gamma 已提交
786 787
		}

788
		// Clear those dupes
789 790 791 792 793 794
		files = arrays.distinct(files);
		folders = arrays.distinct(folders);

		if (platform.isMacintosh && files.length > 0) {
			files = files.filter(f => folders.indexOf(f) < 0); // TODO@Ben migration (remove in the future)
		}
E
Erich Gamma 已提交
795

796
		// Make sure it is bounded
797 798 799 800
		files = files.slice(0, 10);
		folders = folders.slice(0, 10);

		return { files, folders };
E
Erich Gamma 已提交
801 802 803 804 805 806 807
	}

	private toIPath(anyPath: string, ignoreFileNotFound?: boolean, gotoLineMode?: boolean): window.IPath {
		if (!anyPath) {
			return null;
		}

J
Joao Moreno 已提交
808
		let parsedPath: IParsedPath;
E
Erich Gamma 已提交
809
		if (gotoLineMode) {
J
Joao Moreno 已提交
810
			parsedPath = parseLineAndColumnAware(anyPath);
E
Erich Gamma 已提交
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
			anyPath = parsedPath.path;
		}

		let candidate = path.normalize(anyPath);
		try {
			let candidateStat = fs.statSync(candidate);
			if (candidateStat) {
				return candidateStat.isFile() ?
					{
						filePath: candidate,
						lineNumber: gotoLineMode ? parsedPath.line : void 0,
						columnNumber: gotoLineMode ? parsedPath.column : void 0,
						installExtensionPath: /\.vsix$/i.test(candidate)
					} :
					{ workspacePath: candidate };
			}
		} catch (error) {
			if (ignoreFileNotFound) {
				return { filePath: candidate, createFilePath: true }; // assume this is a file that does not yet exist
			}
		}

		return null;
	}

J
Joao Moreno 已提交
836
	private cliToPaths(cli: ICommandLineArguments, ignoreFileNotFound?: boolean): window.IPath[] {
E
Erich Gamma 已提交
837 838 839 840 841 842 843 844 845

		// Check for pass in candidate or last opened path
		let candidates: string[] = [];
		if (cli.pathArguments.length > 0) {
			candidates = cli.pathArguments;
		}

		// No path argument, check settings for what to do now
		else {
J
Joao Moreno 已提交
846
			let reopenFolders = this.settingsManager.getValue('window.reopenFolders', 'one');
E
Erich Gamma 已提交
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
			let lastActiveFolder = this.windowsState.lastActiveWindow && this.windowsState.lastActiveWindow.workspacePath;

			// Restore all
			if (reopenFolders === 'all') {
				let lastOpenedFolders = this.windowsState.openedFolders.map(o => o.workspacePath);

				// 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
			else if (lastActiveFolder && (reopenFolders === 'one' || reopenFolders !== 'none')) {
				candidates.push(lastActiveFolder);
			}
		}

		let iPaths = candidates.map((candidate) => this.toIPath(candidate, ignoreFileNotFound, cli.gotoLineMode)).filter((path) => !!path);
		if (iPaths.length > 0) {
			return iPaths;
		}

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

877
	private openInBrowserWindow(configuration: window.IWindowConfiguration, forceNewWindow?: boolean, windowToUse?: window.VSCodeWindow): window.VSCodeWindow {
E
Erich Gamma 已提交
878 879 880 881 882 883
		let vscodeWindow: window.VSCodeWindow;

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

			if (vscodeWindow) {
B
Benjamin Pasero 已提交
884
				vscodeWindow.focus();
E
Erich Gamma 已提交
885 886 887 888 889
			}
		}

		// New window
		if (!vscodeWindow) {
J
Joao Moreno 已提交
890
			vscodeWindow = this.instantiationService.createInstance(window.VSCodeWindow, {
891
				state: this.getNewWindowState(configuration),
892
				extensionDevelopmentPath: configuration.extensionDevelopmentPath
893 894
			});

E
Erich Gamma 已提交
895 896 897
			WindowsManager.WINDOWS.push(vscodeWindow);

			// Window Events
898 899
			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));
900 901
			vscodeWindow.win.webContents.on('crashed', () => this.onWindowError(vscodeWindow, WindowError.CRASHED));
			vscodeWindow.win.on('unresponsive', () => this.onWindowError(vscodeWindow, WindowError.UNRESPONSIVE));
E
Erich Gamma 已提交
902 903 904 905
			vscodeWindow.win.on('close', () => this.onBeforeWindowClose(vscodeWindow));
			vscodeWindow.win.on('closed', () => this.onWindowClosed(vscodeWindow));

			// Lifecycle
J
Joao Moreno 已提交
906
			this.lifecycleService.registerWindow(vscodeWindow);
E
Erich Gamma 已提交
907 908 909 910 911 912 913 914
		}

		// 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.
			let currentWindowConfig = vscodeWindow.config;
A
Alex Dima 已提交
915 916
			if (!configuration.extensionDevelopmentPath && currentWindowConfig && !!currentWindowConfig.extensionDevelopmentPath) {
				configuration.extensionDevelopmentPath = currentWindowConfig.extensionDevelopmentPath;
E
Erich Gamma 已提交
917
				configuration.verboseLogging = currentWindowConfig.verboseLogging;
918
				configuration.logExtensionHostCommunication = currentWindowConfig.logExtensionHostCommunication;
919
				configuration.debugBrkFileWatcherPort = currentWindowConfig.debugBrkFileWatcherPort;
920 921
				configuration.debugBrkExtensionHost = currentWindowConfig.debugBrkExtensionHost;
				configuration.debugExtensionHostPort = currentWindowConfig.debugExtensionHostPort;
B
Benjamin Pasero 已提交
922
				configuration.extensionsHomePath = currentWindowConfig.extensionsHomePath;
E
Erich Gamma 已提交
923 924 925 926
			}
		}

		// Only load when the window has not vetoed this
J
Joao Moreno 已提交
927
		this.lifecycleService.unload(vscodeWindow).done((veto) => {
E
Erich Gamma 已提交
928 929 930 931 932 933
			if (!veto) {

				// Load it
				vscodeWindow.load(configuration);
			}
		});
934 935

		return vscodeWindow;
E
Erich Gamma 已提交
936 937 938 939 940
	}

	private getNewWindowState(configuration: window.IWindowConfiguration): window.IWindowState {

		// plugin development host Window - load from stored settings if any
A
Alex Dima 已提交
941
		if (!!configuration.extensionDevelopmentPath && this.windowsState.lastPluginDevelopmentHostWindow) {
E
Erich Gamma 已提交
942 943 944 945 946
			return this.windowsState.lastPluginDevelopmentHostWindow.uiState;
		}

		// Known Folder - load from stored settings if any
		if (configuration.workspacePath) {
B
Benjamin Pasero 已提交
947
			let stateForWorkspace = this.windowsState.openedFolders.filter(o => this.isPathEqual(o.workspacePath, configuration.workspacePath)).map(o => o.uiState);
E
Erich Gamma 已提交
948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
			if (stateForWorkspace.length) {
				return stateForWorkspace[0];
			}
		}

		// First Window
		let lastActive = this.getLastActiveWindow();
		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
964
		let displayToUse: Electron.Display;
E
Erich Gamma 已提交
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
		let displays = screen.getAllDisplays();

		// 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) {
				let cursorPoint = screen.getCursorScreenPoint();
				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];
			}
		}

		let defaultState = window.defaultWindowState();
		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);
	}

	private ensureNoOverlap(state: window.IWindowState): window.IWindowState {
		if (WindowsManager.WINDOWS.length === 0) {
			return state;
		}

		let existingWindowBounds = WindowsManager.WINDOWS.map((win) => win.getBounds());
		while (existingWindowBounds.some((b) => b.x === state.x || b.y === state.y)) {
			state.x += 30;
			state.y += 30;
		}

		return state;
	}

1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
	public openFileFolderPicker(forceNewWindow?: boolean): void {
		this.doPickAndOpen({ pickFolders: true, pickFiles: true }, forceNewWindow);
	}

	public openFilePicker(forceNewWindow?: boolean): void {
		this.doPickAndOpen({ pickFiles: true }, forceNewWindow);
	}

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

1025 1026
	private doPickAndOpen(options: INativeOpenDialogOptions, forceNewWindow?: boolean): void {
		this.getFileOrFolderPaths(options, (paths: string[]) => {
E
Erich Gamma 已提交
1027
			if (paths && paths.length) {
J
Joao Moreno 已提交
1028
				this.open({ cli: this.envService.cliArgs, pathsToOpen: paths, forceNewWindow });
E
Erich Gamma 已提交
1029 1030 1031 1032
			}
		});
	}

1033
	private getFileOrFolderPaths(options: INativeOpenDialogOptions, clb: (paths: string[]) => void): void {
J
Joao Moreno 已提交
1034
		let workingDir = this.storageService.getItem<string>(WindowsManager.workingDirPickerStorageKey);
E
Erich Gamma 已提交
1035 1036 1037
		let focussedWindow = this.getFocusedWindow();

		let pickerProperties: string[];
1038
		if (options.pickFiles && options.pickFolders) {
E
Erich Gamma 已提交
1039 1040
			pickerProperties = ['multiSelections', 'openDirectory', 'openFile', 'createDirectory'];
		} else {
1041
			pickerProperties = ['multiSelections', options.pickFolders ? 'openDirectory' : 'openFile', 'createDirectory'];
E
Erich Gamma 已提交
1042 1043
		}

1044
		dialog.showOpenDialog(focussedWindow && focussedWindow.win, {
E
Erich Gamma 已提交
1045 1046 1047 1048 1049 1050
			defaultPath: workingDir,
			properties: pickerProperties
		}, (paths) => {
			if (paths && paths.length > 0) {

				// Remember path in storage for next time
J
Joao Moreno 已提交
1051
				this.storageService.setItem(WindowsManager.workingDirPickerStorageKey, path.dirname(paths[0]));
E
Erich Gamma 已提交
1052 1053 1054 1055 1056 1057 1058 1059 1060

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

J
Joao Moreno 已提交
1061
	public focusLastActive(cli: ICommandLineArguments): window.VSCodeWindow {
E
Erich Gamma 已提交
1062 1063
		let lastActive = this.getLastActiveWindow();
		if (lastActive) {
B
Benjamin Pasero 已提交
1064
			lastActive.focus();
1065 1066

			return lastActive;
E
Erich Gamma 已提交
1067 1068 1069
		}

		// No window - open new one
1070 1071 1072 1073
		this.windowsState.openedFolders = []; // make sure we do not open too much
		const res = this.open({ cli: cli });

		return res && res[0];
E
Erich Gamma 已提交
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
	}

	public getLastActiveWindow(): window.VSCodeWindow {
		if (WindowsManager.WINDOWS.length) {
			let lastFocussedDate = Math.max.apply(Math, WindowsManager.WINDOWS.map((w) => w.lastFocusTime));
			let res = WindowsManager.WINDOWS.filter((w) => w.lastFocusTime === lastFocussedDate);
			if (res && res.length) {
				return res[0];
			}
		}

		return null;
	}

1088
	public findWindow(workspacePath: string, filePath?: string, extensionDevelopmentPath?: string): window.VSCodeWindow {
E
Erich Gamma 已提交
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
		if (WindowsManager.WINDOWS.length) {

			// Sort the last active window to the front of the array of windows to test
			let windowsToTest = WindowsManager.WINDOWS.slice(0);
			let lastActiveWindow = this.getLastActiveWindow();
			if (lastActiveWindow) {
				windowsToTest.splice(windowsToTest.indexOf(lastActiveWindow), 1);
				windowsToTest.unshift(lastActiveWindow);
			}

			// Find it
			let res = windowsToTest.filter((w) => {

				// match on workspace
1103
				if (typeof w.openedWorkspacePath === 'string' && (this.isPathEqual(w.openedWorkspacePath, workspacePath))) {
E
Erich Gamma 已提交
1104 1105 1106 1107
					return true;
				}

				// match on file
B
Benjamin Pasero 已提交
1108
				if (typeof w.openedFilePath === 'string' && this.isPathEqual(w.openedFilePath, filePath)) {
E
Erich Gamma 已提交
1109 1110 1111 1112 1113 1114 1115 1116
					return true;
				}

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

1117 1118 1119 1120 1121
				// match on extension development path
				if (typeof extensionDevelopmentPath === 'string' && w.extensionDevelopmentPath === extensionDevelopmentPath) {
					return true;
				}

E
Erich Gamma 已提交
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
				return false;
			});

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

		return null;
	}

	public openNewWindow(): void {
J
Joao Moreno 已提交
1134
		this.open({ cli: this.envService.cliArgs, forceNewWindow: true, forceEmpty: true });
E
Erich Gamma 已提交
1135 1136 1137 1138 1139 1140
	}

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

		if (focusedWindow) {
1141
			focusedWindow.sendWhenReady(channel, ...args);
E
Erich Gamma 已提交
1142 1143 1144 1145 1146
		}
	}

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

1151
			w.sendWhenReady(channel, payload);
E
Erich Gamma 已提交
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
		});
	}

	public getFocusedWindow(): window.VSCodeWindow {
		let win = BrowserWindow.getFocusedWindow();
		if (win) {
			return this.getWindowById(win.id);
		}

		return null;
	}

	public getWindowById(windowId: number): window.VSCodeWindow {
B
Benjamin Pasero 已提交
1165
		let res = WindowsManager.WINDOWS.filter((w) => w.id === windowId);
E
Erich Gamma 已提交
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
		if (res && res.length === 1) {
			return res[0];
		}

		return null;
	}

	public getWindows(): window.VSCodeWindow[] {
		return WindowsManager.WINDOWS;
	}

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

1181
	private onWindowError(vscodeWindow: window.VSCodeWindow, error: WindowError): void {
E
Erich Gamma 已提交
1182 1183 1184 1185
		console.error(error === WindowError.CRASHED ? '[VS Code]: render process crashed!' : '[VS Code]: detected unresponsive');

		// Unresponsive
		if (error === WindowError.UNRESPONSIVE) {
1186
			dialog.showMessageBox(vscodeWindow.win, {
J
Joao Moreno 已提交
1187
				title: this.envService.product.nameLong,
E
Erich Gamma 已提交
1188
				type: 'warning',
B
Benjamin Pasero 已提交
1189
				buttons: [nls.localize('reopen', "Reopen"), nls.localize('wait', "Keep Waiting"), nls.localize('close', "Close")],
1190
				message: nls.localize('appStalled', "The window is no longer responding"),
B
Benjamin Pasero 已提交
1191
				detail: nls.localize('appStalledDetail', "You can reopen or close the window or keep waiting."),
E
Erich Gamma 已提交
1192 1193 1194
				noLink: true
			}, (result) => {
				if (result === 0) {
1195 1196
					vscodeWindow.reload();
				} else if (result === 2) {
1197
					this.onBeforeWindowClose(vscodeWindow); // 'close' event will not be fired on destroy(), so run it manually
1198
					vscodeWindow.win.destroy(); // make sure to destroy the window as it is unresponsive
E
Erich Gamma 已提交
1199 1200 1201 1202 1203 1204
				}
			});
		}

		// Crashed
		else {
1205
			dialog.showMessageBox(vscodeWindow.win, {
J
Joao Moreno 已提交
1206
				title: this.envService.product.nameLong,
E
Erich Gamma 已提交
1207
				type: 'warning',
B
Benjamin Pasero 已提交
1208
				buttons: [nls.localize('reopen', "Reopen"), nls.localize('close', "Close")],
1209
				message: nls.localize('appCrashed', "The window has crashed"),
B
Benjamin Pasero 已提交
1210
				detail: nls.localize('appCrashedDetail', "We are sorry for the inconvenience! You can reopen the window to continue where you left off."),
E
Erich Gamma 已提交
1211 1212
				noLink: true
			}, (result) => {
1213 1214 1215
				if (result === 0) {
					vscodeWindow.reload();
				} else if (result === 1) {
1216
					this.onBeforeWindowClose(vscodeWindow); // 'close' event will not be fired on destroy(), so run it manually
1217 1218
					vscodeWindow.win.destroy(); // make sure to destroy the window as it has crashed
				}
E
Erich Gamma 已提交
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
			});
		}
	}

	private onBeforeWindowClose(win: window.VSCodeWindow): void {
		if (win.readyState !== window.ReadyState.READY) {
			return; // only persist windows that are fully loaded
		}

		// On Window close, update our stored state of this window
		let state: IWindowState = { workspacePath: win.openedWorkspacePath, uiState: win.serializeWindowState() };
		if (win.isPluginDevelopmentHost) {
			this.windowsState.lastPluginDevelopmentHostWindow = state;
		} else {
			this.windowsState.lastActiveWindow = state;

			this.windowsState.openedFolders.forEach(o => {
B
Benjamin Pasero 已提交
1236
				if (this.isPathEqual(o.workspacePath, win.openedWorkspacePath)) {
E
Erich Gamma 已提交
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
					o.uiState = state.uiState;
				}
			});
		}
	}

	private onWindowClosed(win: window.VSCodeWindow): void {

		// Tell window
		win.dispose();

		// Remove from our list so that Electron can clean it up
		let index = WindowsManager.WINDOWS.indexOf(win);
		WindowsManager.WINDOWS.splice(index, 1);

		// Emit
J
Joao Moreno 已提交
1253
		this.eventEmitter.emit(EventTypes.CLOSE, win.id);
E
Erich Gamma 已提交
1254
	}
B
Benjamin Pasero 已提交
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278

	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;
	}
J
Joao Moreno 已提交
1279
}