windows.ts 69.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';

8
import { basename, normalize, join, dirname } from 'path';
B
Benjamin Pasero 已提交
9
import * as fs from 'original-fs';
B
Benjamin Pasero 已提交
10
import { localize } from 'vs/nls';
J
Joao Moreno 已提交
11
import * as arrays from 'vs/base/common/arrays';
12
import { assign, mixin, equals } from 'vs/base/common/objects';
D
Daniel Imms 已提交
13
import { IBackupMainService } from 'vs/platform/backup/common/backup';
J
Joao Moreno 已提交
14
import { IEnvironmentService, ParsedArgs } from 'vs/platform/environment/common/environment';
B
Benjamin Pasero 已提交
15
import { IStateService } from 'vs/platform/state/common/state';
16
import { CodeWindow, IWindowState as ISingleWindowState, defaultWindowState, WindowMode } from 'vs/code/electron-main/window';
17
import { ipcMain as ipc, screen, BrowserWindow, dialog, systemPreferences, app } from 'electron';
B
Benjamin Pasero 已提交
18
import { IPathWithLineAndColumn, parseLineAndColumnAware } from 'vs/code/node/paths';
19
import { ILifecycleService, UnloadReason, IWindowUnloadEvent } from 'vs/platform/lifecycle/electron-main/lifecycleMain';
20
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
21
import { ILogService } from 'vs/platform/log/common/log';
22
import { IWindowSettings, OpenContext, IPath, IWindowConfiguration, INativeOpenDialogOptions, ReadyState, IPathsToWaitFor, IEnterWorkspaceResult, IMessageBoxResult } from 'vs/platform/windows/common/windows';
23
import { getLastActiveWindow, findBestWindowOrFolderForFile, findWindowOnWorkspace, findWindowOnExtensionDevelopmentPath, findWindowOnWorkspaceOrFolderPath } from 'vs/code/node/windowsFinder';
24
import CommonEvent, { Emitter } from 'vs/base/common/event';
25
import product from 'vs/platform/node/product';
B
Benjamin Pasero 已提交
26
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
27
import { isEqual } from 'vs/base/common/paths';
28
import { IWindowsMainService, IOpenConfiguration, IWindowsCountChangedEvent, ICodeWindow } from 'vs/platform/windows/electron-main/windows';
B
Benjamin Pasero 已提交
29
import { IHistoryMainService } from 'vs/platform/history/common/history';
B
Benjamin Pasero 已提交
30
import { IProcessEnvironment, isLinux, isMacintosh, isWindows } from 'vs/base/common/platform';
31
import { TPromise } from 'vs/base/common/winjs.base';
32
import { IWorkspacesMainService, IWorkspaceIdentifier, ISingleFolderWorkspaceIdentifier, WORKSPACE_FILTER, isSingleFolderWorkspaceIdentifier, IWorkspaceFolderCreationData } from 'vs/platform/workspaces/common/workspaces';
B
Benjamin Pasero 已提交
33
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
34
import { mnemonicButtonLabel } from 'vs/base/common/labels';
J
Johannes Rieken 已提交
35
import { Schemas } from 'vs/base/common/network';
36
import { normalizeNFC } from 'vs/base/common/strings';
37
import URI from 'vs/base/common/uri';
38
import { Queue } from 'vs/base/common/async';
E
Erich Gamma 已提交
39 40 41 42 43 44

enum WindowError {
	UNRESPONSIVE,
	CRASHED
}

45 46 47 48
interface INewWindowState extends ISingleWindowState {
	hasDefaultState?: boolean;
}

49
interface IWindowState {
50
	workspace?: IWorkspaceIdentifier;
51
	folderPath?: string;
52
	backupPath: string;
J
Joao Moreno 已提交
53
	uiState: ISingleWindowState;
E
Erich Gamma 已提交
54 55 56 57 58
}

interface IWindowsState {
	lastActiveWindow?: IWindowState;
	lastPluginDevelopmentHostWindow?: IWindowState;
59
	openedWindows: IWindowState[];
E
Erich Gamma 已提交
60 61
}

62
type RestoreWindowsSetting = 'all' | 'folders' | 'one' | 'none';
63

B
Benjamin Pasero 已提交
64 65 66
interface IOpenBrowserWindowOptions {
	userEnv?: IProcessEnvironment;
	cli?: ParsedArgs;
67

68
	workspace?: IWorkspaceIdentifier;
69
	folderPath?: string;
B
Benjamin Pasero 已提交
70 71 72 73 74 75

	initialStartup?: boolean;

	filesToOpen?: IPath[];
	filesToCreate?: IPath[];
	filesToDiff?: IPath[];
76
	filesToWait?: IPathsToWaitFor;
B
Benjamin Pasero 已提交
77 78 79 80

	forceNewWindow?: boolean;
	windowToUse?: CodeWindow;

81
	emptyWindowBackupFolder?: string;
B
Benjamin Pasero 已提交
82 83
}

B
Benjamin Pasero 已提交
84
interface IPathToOpen extends IPath {
85

86
	// the workspace for a Code instance to open
87
	workspace?: IWorkspaceIdentifier;
88

89 90
	// the folder path for a Code instance to open
	folderPath?: string;
91 92 93 94 95 96 97 98

	// the backup spath for a Code instance to use
	backupPath?: string;

	// indicator to create the file path in the Code instance
	createFilePath?: boolean;
}

J
Joao Moreno 已提交
99
export class WindowsManager implements IWindowsMainService {
J
Joao Moreno 已提交
100

101
	_serviceBrand: any;
E
Erich Gamma 已提交
102

103
	private static readonly windowsStateStorageKey = 'windowsState';
E
Erich Gamma 已提交
104

B
Benjamin Pasero 已提交
105
	private static WINDOWS: CodeWindow[] = [];
E
Erich Gamma 已提交
106

B
Benjamin Pasero 已提交
107
	private initialUserEnv: IProcessEnvironment;
108

E
Erich Gamma 已提交
109
	private windowsState: IWindowsState;
110
	private lastClosedWindowState: IWindowState;
E
Erich Gamma 已提交
111

112
	private dialogs: Dialogs;
113
	private workspacesManager: WorkspacesManager;
B
Benjamin Pasero 已提交
114

B
Benjamin Pasero 已提交
115 116
	private _onWindowReady = new Emitter<CodeWindow>();
	onWindowReady: CommonEvent<CodeWindow> = this._onWindowReady.event;
117 118 119 120

	private _onWindowClose = new Emitter<number>();
	onWindowClose: CommonEvent<number> = this._onWindowClose.event;

121 122 123
	private _onWindowLoad = new Emitter<number>();
	onWindowLoad: CommonEvent<number> = this._onWindowLoad.event;

124 125 126
	private _onActiveWindowChanged = new Emitter<CodeWindow>();
	onActiveWindowChanged: CommonEvent<CodeWindow> = this._onActiveWindowChanged.event;

127 128 129
	private _onWindowReload = new Emitter<number>();
	onWindowReload: CommonEvent<number> = this._onWindowReload.event;

B
Benjamin Pasero 已提交
130 131 132
	private _onWindowsCountChanged = new Emitter<IWindowsCountChangedEvent>();
	onWindowsCountChanged: CommonEvent<IWindowsCountChangedEvent> = this._onWindowsCountChanged.event;

J
Joao Moreno 已提交
133
	constructor(
B
Benjamin Pasero 已提交
134
		private readonly machineId: string,
J
Joao Moreno 已提交
135
		@ILogService private logService: ILogService,
B
Benjamin Pasero 已提交
136
		@IStateService private stateService: IStateService,
137
		@IEnvironmentService private environmentService: IEnvironmentService,
B
Benjamin Pasero 已提交
138
		@ILifecycleService private lifecycleService: ILifecycleService,
B
Benjamin Pasero 已提交
139
		@IBackupMainService private backupMainService: IBackupMainService,
B
Benjamin Pasero 已提交
140
		@ITelemetryService telemetryService: ITelemetryService,
141
		@IConfigurationService private configurationService: IConfigurationService,
B
Benjamin Pasero 已提交
142 143
		@IHistoryMainService private historyMainService: IHistoryMainService,
		@IWorkspacesMainService private workspacesMainService: IWorkspacesMainService,
144
		@IInstantiationService private instantiationService: IInstantiationService
145
	) {
B
Benjamin Pasero 已提交
146
		this.windowsState = this.stateService.getItem<IWindowsState>(WindowsManager.windowsStateStorageKey) || { openedWindows: [] };
147 148 149
		if (!Array.isArray(this.windowsState.openedWindows)) {
			this.windowsState.openedWindows = [];
		}
150

151
		this.dialogs = new Dialogs(environmentService, telemetryService, stateService, this);
B
Benjamin Pasero 已提交
152
		this.workspacesManager = new WorkspacesManager(workspacesMainService, backupMainService, environmentService, this);
153
	}
J
Joao Moreno 已提交
154

B
Benjamin Pasero 已提交
155
	public ready(initialUserEnv: IProcessEnvironment): void {
156
		this.initialUserEnv = initialUserEnv;
157 158

		this.registerListeners();
E
Erich Gamma 已提交
159 160 161
	}

	private registerListeners(): void {
162

163 164 165 166 167 168 169
		// React to windows focus changes
		app.on('browser-window-focus', () => {
			setTimeout(() => {
				this._onActiveWindowChanged.fire(this.getLastActiveWindow());
			});
		});

170
		// React to workbench loaded events from windows
M
Matt Bierner 已提交
171
		ipc.on('vscode:workbenchLoaded', (_event: any, windowId: number) => {
J
Joao Moreno 已提交
172
			this.logService.trace('IPC#vscode-workbenchLoaded');
E
Erich Gamma 已提交
173

B
Benjamin Pasero 已提交
174
			const win = this.getWindowById(windowId);
E
Erich Gamma 已提交
175 176 177 178
			if (win) {
				win.setReady();

				// Event
179
				this._onWindowReady.fire(win);
E
Erich Gamma 已提交
180 181 182
			}
		});

183 184 185 186 187 188 189 190 191 192 193
		// React to HC color scheme changes (Windows)
		if (isWindows) {
			systemPreferences.on('inverted-color-scheme-changed', () => {
				if (systemPreferences.isInvertedColorScheme()) {
					this.sendToAll('vscode:enterHighContrast');
				} else {
					this.sendToAll('vscode:leaveHighContrast');
				}
			});
		}

194 195
		// Handle various lifecycle events around windows
		this.lifecycleService.onBeforeWindowUnload(e => this.onBeforeWindowUnload(e));
B
Benjamin Pasero 已提交
196
		this.lifecycleService.onBeforeWindowClose(win => this.onBeforeWindowClose(win as CodeWindow));
197
		this.lifecycleService.onBeforeQuit(() => this.onBeforeQuit());
198 199 200 201 202 203 204 205
		this.onWindowsCountChanged(e => {
			if (e.newCount - e.oldCount > 0) {
				// clear last closed window state when a new window opens. this helps on macOS where
				// otherwise closing the last window, opening a new window and then quitting would
				// use the state of the previously closed window when restarting.
				this.lastClosedWindowState = void 0;
			}
		});
206 207
	}

208 209 210 211 212 213 214
	// Note that onBeforeQuit() and onBeforeWindowClose() are fired in different order depending on the OS:
	// - macOS: since the app will not quit when closing the last window, you will always first get
	//          the onBeforeQuit() event followed by N onbeforeWindowClose() events for each window
	// - other: on other OS, closing the last window will quit the app so the order depends on the
	//          user interaction: closing the last window will first trigger onBeforeWindowClose()
	//          and then onBeforeQuit(). Using the quit action however will first issue onBeforeQuit()
	//          and then onBeforeWindowClose().
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
	//
	// Here is the behaviour on different OS dependig on action taken (Electron 1.7.x):
	//
	// Legend
	// -  quit(N): quit application with N windows opened
	// - close(1): close one window via the window close button
	// - closeAll: close all windows via the taskbar command
	// - onBeforeQuit(N): number of windows reported in this event handler
	// - onBeforeWindowClose(N, M): number of windows reported and quitRequested boolean in this event handler
	//
	// macOS
	// 	-     quit(1): onBeforeQuit(1), onBeforeWindowClose(1, true)
	// 	-     quit(2): onBeforeQuit(2), onBeforeWindowClose(2, true), onBeforeWindowClose(2, true)
	// 	-     quit(0): onBeforeQuit(0)
	// 	-    close(1): onBeforeWindowClose(1, false)
	//
	// Windows
	// 	-     quit(1): onBeforeQuit(1), onBeforeWindowClose(1, true)
	// 	-     quit(2): onBeforeQuit(2), onBeforeWindowClose(2, true), onBeforeWindowClose(2, true)
	// 	-    close(1): onBeforeWindowClose(2, false)[not last window]
	// 	-    close(1): onBeforeWindowClose(1, false), onBeforequit(0)[last window]
	// 	- closeAll(2): onBeforeWindowClose(2, false), onBeforeWindowClose(2, false), onBeforeQuit(0)
	//
	// Linux
	// 	-     quit(1): onBeforeQuit(1), onBeforeWindowClose(1, true)
	// 	-     quit(2): onBeforeQuit(2), onBeforeWindowClose(2, true), onBeforeWindowClose(2, true)
	// 	-    close(1): onBeforeWindowClose(2, false)[not last window]
	// 	-    close(1): onBeforeWindowClose(1, false), onBeforequit(0)[last window]
	// 	- closeAll(2): onBeforeWindowClose(2, false), onBeforeWindowClose(2, false), onBeforeQuit(0)
	//
245
	private onBeforeQuit(): void {
246
		const currentWindowsState: IWindowsState = {
247
			openedWindows: [],
248
			lastPluginDevelopmentHostWindow: this.windowsState.lastPluginDevelopmentHostWindow,
249
			lastActiveWindow: this.lastClosedWindowState
250 251 252 253 254 255 256 257
		};

		// 1.) Find a last active window (pick any other first window otherwise)
		if (!currentWindowsState.lastActiveWindow) {
			let activeWindow = this.getLastActiveWindow();
			if (!activeWindow || activeWindow.isExtensionDevelopmentHost) {
				activeWindow = WindowsManager.WINDOWS.filter(w => !w.isExtensionDevelopmentHost)[0];
			}
E
Erich Gamma 已提交
258

259
			if (activeWindow) {
260
				currentWindowsState.lastActiveWindow = this.toWindowState(activeWindow);
E
Erich Gamma 已提交
261
			}
262 263 264 265 266
		}

		// 2.) Find extension host window
		const extensionHostWindow = WindowsManager.WINDOWS.filter(w => w.isExtensionDevelopmentHost && !w.isExtensionTestHost)[0];
		if (extensionHostWindow) {
267
			currentWindowsState.lastPluginDevelopmentHostWindow = this.toWindowState(extensionHostWindow);
268
		}
E
Erich Gamma 已提交
269

270
		// 3.) All windows (except extension host) for N >= 2 to support restoreWindows: all or for auto update
271 272 273 274 275
		//
		// Carefull here: asking a window for its window state after it has been closed returns bogus values (width: 0, height: 0)
		// so if we ever want to persist the UI state of the last closed window (window count === 1), it has
		// to come from the stored lastClosedWindowState on Win/Linux at least
		if (this.getWindowCount() > 1) {
276
			currentWindowsState.openedWindows = WindowsManager.WINDOWS.filter(w => !w.isExtensionDevelopmentHost).map(w => this.toWindowState(w));
277
		}
E
Erich Gamma 已提交
278

279
		// Persist
B
Benjamin Pasero 已提交
280
		this.stateService.setItem(WindowsManager.windowsStateStorageKey, currentWindowsState);
281
	}
282

283
	// See note on #onBeforeQuit() for details how these events are flowing
B
Benjamin Pasero 已提交
284
	private onBeforeWindowClose(win: CodeWindow): void {
285 286 287 288 289
		if (this.lifecycleService.isQuitRequested()) {
			return; // during quit, many windows close in parallel so let it be handled in the before-quit handler
		}

		// On Window close, update our stored UI state of this window
290
		const state: IWindowState = this.toWindowState(win);
291 292 293 294
		if (win.isExtensionDevelopmentHost && !win.isExtensionTestHost) {
			this.windowsState.lastPluginDevelopmentHostWindow = state; // do not let test run window state overwrite our extension development state
		}

295
		// Any non extension host window with same workspace or folder
296
		else if (!win.isExtensionDevelopmentHost && (!!win.openedWorkspace || !!win.openedFolderPath)) {
297
			this.windowsState.openedWindows.forEach(o => {
B
fix npe  
Benjamin Pasero 已提交
298
				const sameWorkspace = win.openedWorkspace && o.workspace && o.workspace.id === win.openedWorkspace.id;
299 300 301
				const sameFolder = win.openedFolderPath && isEqual(o.folderPath, win.openedFolderPath, !isLinux /* ignorecase */);

				if (sameWorkspace || sameFolder) {
302 303 304 305 306 307 308
					o.uiState = state.uiState;
				}
			});
		}

		// On Windows and Linux closing the last window will trigger quit. Since we are storing all UI state
		// before quitting, we need to remember the UI state of this window to be able to persist it.
309 310 311
		// On macOS we keep the last closed window state ready in case the user wants to quit right after or
		// wants to open another window, in which case we use this state over the persisted one.
		if (this.getWindowCount() === 1) {
312 313
			this.lastClosedWindowState = state;
		}
E
Erich Gamma 已提交
314 315
	}

316 317
	private toWindowState(win: CodeWindow): IWindowState {
		return {
318
			workspace: win.openedWorkspace,
319 320 321 322 323 324
			folderPath: win.openedFolderPath,
			backupPath: win.backupPath,
			uiState: win.serializeWindowState()
		};
	}

B
Benjamin Pasero 已提交
325
	public open(openConfig: IOpenConfiguration): CodeWindow[] {
326
		openConfig = this.validateOpenConfig(openConfig);
327

328
		let pathsToOpen = this.getPathsToOpen(openConfig);
329 330 331

		// When run with --add, take the folders that are to be opened as
		// folders that should be added to the currently active window.
332
		let foldersToAdd: IPath[] = [];
333
		if (openConfig.addMode) {
334 335 336
			foldersToAdd = pathsToOpen.filter(path => !!path.folderPath).map(path => ({ filePath: path.folderPath }));
			pathsToOpen = pathsToOpen.filter(path => !path.folderPath);
		}
E
Erich Gamma 已提交
337

B
Benjamin Pasero 已提交
338 339
		let filesToOpen = pathsToOpen.filter(path => !!path.filePath && !path.createFilePath);
		let filesToCreate = pathsToOpen.filter(path => !!path.filePath && path.createFilePath);
340 341 342 343

		// When run with --diff, take the files to open as files to diff
		// if there are exactly two files provided.
		let filesToDiff: IPath[] = [];
344 345 346 347
		if (openConfig.diffMode && filesToOpen.length === 2) {
			filesToDiff = filesToOpen;
			filesToOpen = [];
			filesToCreate = []; // diff ignores other files that do not exist
E
Erich Gamma 已提交
348 349
		}

350 351 352 353 354 355
		// When run with --wait, make sure we keep the paths to wait for
		let filesToWait: IPathsToWaitFor;
		if (openConfig.cli.wait && openConfig.cli.waitMarkerFilePath) {
			filesToWait = { paths: [...filesToDiff, ...filesToOpen, ...filesToCreate], waitMarkerFilePath: openConfig.cli.waitMarkerFilePath };
		}

356 357 358
		//
		// These are windows to open to show workspaces
		//
B
Benjamin Pasero 已提交
359
		const workspacesToOpen = arrays.distinct(pathsToOpen.filter(win => !!win.workspace).map(win => win.workspace), workspace => workspace.id); // prevent duplicates
360 361 362 363

		//
		// These are windows to open to show either folders or files (including diffing files or creating them)
		//
B
Benjamin Pasero 已提交
364
		const foldersToOpen = arrays.distinct(pathsToOpen.filter(win => win.folderPath && !win.filePath).map(win => win.folderPath), folder => isLinux ? folder : folder.toLowerCase()); // prevent duplicates
365

366
		//
367
		// These are windows to restore because of hot-exit or from previous session (only performed once on startup!)
368
		//
369 370 371 372
		let foldersToRestore: string[] = [];
		let workspacesToRestore: IWorkspaceIdentifier[] = [];
		let emptyToRestore: string[] = [];
		if (openConfig.initialStartup && !openConfig.cli.extensionDevelopmentPath) {
B
Benjamin Pasero 已提交
373
			foldersToRestore = this.backupMainService.getFolderBackupPaths();
374

B
Benjamin Pasero 已提交
375 376
			workspacesToRestore = this.backupMainService.getWorkspaceBackups();						// collect from workspaces with hot-exit backups
			workspacesToRestore.push(...this.workspacesMainService.getUntitledWorkspacesSync());	// collect from previous window session
377

B
Benjamin Pasero 已提交
378
			emptyToRestore = this.backupMainService.getEmptyWindowBackupPaths();
379
			emptyToRestore.push(...pathsToOpen.filter(w => !w.workspace && !w.folderPath && w.backupPath).map(w => basename(w.backupPath))); // add empty windows with backupPath
380 381
			emptyToRestore = arrays.distinct(emptyToRestore); // prevent duplicates
		}
382

383 384 385
		//
		// These are empty windows to open
		//
B
Benjamin Pasero 已提交
386
		const emptyToOpen = pathsToOpen.filter(win => !win.workspace && !win.folderPath && !win.filePath && !win.backupPath).length;
387

388
		// Open based on config
389
		const usedWindows = this.doOpen(openConfig, workspacesToOpen, workspacesToRestore, foldersToOpen, foldersToRestore, emptyToRestore, emptyToOpen, filesToOpen, filesToCreate, filesToDiff, filesToWait, foldersToAdd);
390

391
		// Make sure to pass focus to the most relevant of the windows if we open multiple
392
		if (usedWindows.length > 1) {
393 394 395
			let focusLastActive = this.windowsState.lastActiveWindow && !openConfig.forceEmpty && !openConfig.cli._.length && (!openConfig.pathsToOpen || !openConfig.pathsToOpen.length);
			let focusLastOpened = true;
			let focusLastWindow = true;
396

397 398
			// 1.) focus last active window if we are not instructed to open any paths
			if (focusLastActive) {
399 400 401
				const lastActiveWindw = usedWindows.filter(w => w.backupPath === this.windowsState.lastActiveWindow.backupPath);
				if (lastActiveWindw.length) {
					lastActiveWindw[0].focus();
402 403
					focusLastOpened = false;
					focusLastWindow = false;
404 405 406
				}
			}

407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
			// 2.) if instructed to open paths, focus last window which is not restored
			if (focusLastOpened) {
				for (let i = usedWindows.length - 1; i >= 0; i--) {
					const usedWindow = usedWindows[i];
					if (
						(usedWindow.openedWorkspace && workspacesToRestore.some(workspace => workspace.id === usedWindow.openedWorkspace.id)) || 	// skip over restored workspace
						(usedWindow.openedFolderPath && foldersToRestore.some(folder => folder === usedWindow.openedFolderPath)) ||					// skip over restored folder
						(usedWindow.backupPath && emptyToRestore.some(empty => empty === basename(usedWindow.backupPath)))							// skip over restored empty window
					) {
						continue;
					}

					usedWindow.focus();
					focusLastWindow = false;
					break;
				}
			}

			// 3.) finally, always ensure to have at least last used window focused
			if (focusLastWindow) {
427
				usedWindows[usedWindows.length - 1].focus();
428 429
			}
		}
430

431 432 433
		// Remember in recent document list (unless this opens for extension development)
		// Also do not add paths when files are opened for diffing, only if opened individually
		if (!usedWindows.some(w => w.isExtensionDevelopmentHost) && !openConfig.cli.diff) {
434
			const recentlyOpenedWorkspaces: (IWorkspaceIdentifier | ISingleFolderWorkspaceIdentifier)[] = [];
435
			const recentlyOpenedFiles: string[] = [];
436

B
Benjamin Pasero 已提交
437
			pathsToOpen.forEach(win => {
438 439 440 441
				if (win.workspace || win.folderPath) {
					recentlyOpenedWorkspaces.push(win.workspace || win.folderPath);
				} else if (win.filePath) {
					recentlyOpenedFiles.push(win.filePath);
442 443 444
				}
			});

445 446 447
			if (!this.environmentService.skipAddToRecentlyOpened) {
				this.historyMainService.addRecentlyOpened(recentlyOpenedWorkspaces, recentlyOpenedFiles);
			}
448
		}
449

450
		// If we got started with --wait from the CLI, we need to signal to the outside when the window
451 452
		// used for the edit operation is closed or loaded to a different folder so that the waiting
		// process can continue. We do this by deleting the waitMarkerFilePath.
453
		if (openConfig.context === OpenContext.CLI && openConfig.cli.wait && openConfig.cli.waitMarkerFilePath && usedWindows.length === 1 && usedWindows[0]) {
454
			this.waitForWindowCloseOrLoad(usedWindows[0].id).done(() => fs.unlink(openConfig.cli.waitMarkerFilePath, error => void 0));
455 456
		}

457 458 459
		return usedWindows;
	}

460 461 462 463 464 465 466 467 468 469
	private validateOpenConfig(config: IOpenConfiguration): IOpenConfiguration {

		// Make sure addMode is only enabled if we have an active window
		if (config.addMode && (config.initialStartup || !this.getLastActiveWindow())) {
			config.addMode = false;
		}

		return config;
	}

470 471
	private doOpen(
		openConfig: IOpenConfiguration,
472 473
		workspacesToOpen: IWorkspaceIdentifier[],
		workspacesToRestore: IWorkspaceIdentifier[],
474 475 476 477 478 479
		foldersToOpen: string[],
		foldersToRestore: string[],
		emptyToRestore: string[],
		emptyToOpen: number,
		filesToOpen: IPath[],
		filesToCreate: IPath[],
480
		filesToDiff: IPath[],
481
		filesToWait: IPathsToWaitFor,
482
		foldersToAdd: IPath[]
483
	) {
484
		const usedWindows: CodeWindow[] = [];
485

B
Benjamin Pasero 已提交
486 487
		// Settings can decide if files/folders open in new window or not
		let { openFolderInNewWindow, openFilesInNewWindow } = this.shouldOpenNewWindow(openConfig);
488

489 490 491 492 493 494 495 496 497 498 499
		// Handle folders to add by looking for the last active workspace (not on initial startup)
		if (!openConfig.initialStartup && foldersToAdd.length > 0) {
			const lastActiveWindow = this.getLastActiveWindow();
			if (lastActiveWindow) {
				usedWindows.push(this.doAddFoldersToExistingWidow(lastActiveWindow, foldersToAdd));
			}

			// Reset because we handled them
			foldersToAdd = [];
		}

B
Benjamin Pasero 已提交
500
		// Handle files to open/diff or to create when we dont open a folder and we do not restore any folder/untitled from hot-exit
501 502
		const potentialWindowsCount = foldersToOpen.length + foldersToRestore.length + workspacesToOpen.length + workspacesToRestore.length + emptyToRestore.length;
		if (potentialWindowsCount === 0 && (filesToOpen.length > 0 || filesToCreate.length > 0 || filesToDiff.length > 0)) {
E
Erich Gamma 已提交
503

504
			// Find suitable window or folder path to open files in
505
			const fileToCheck = filesToOpen[0] || filesToCreate[0] || filesToDiff[0];
506
			let bestWindowOrFolder = findBestWindowOrFolderForFile({
507 508 509 510 511
				windows: WindowsManager.WINDOWS,
				newWindow: openFilesInNewWindow,
				reuseWindow: openConfig.forceReuseWindow,
				context: openConfig.context,
				filePath: fileToCheck && fileToCheck.filePath,
512
				userHome: this.environmentService.userHome,
B
Benjamin Pasero 已提交
513
				workspaceResolver: workspace => this.workspacesMainService.resolveWorkspaceSync(workspace.configPath)
514
			});
B
Benjamin Pasero 已提交
515

516 517 518 519 520 521
			// Special case: we started with --wait and we got back a folder to open. In this case
			// we actually prefer to not open the folder but operate purely on the file.
			if (typeof bestWindowOrFolder === 'string' && filesToWait) {
				bestWindowOrFolder = !openFilesInNewWindow ? this.getLastActiveWindow() : null;
			}

522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
			// We found a window to open the files in
			if (bestWindowOrFolder instanceof CodeWindow) {

				// Window is workspace
				if (bestWindowOrFolder.openedWorkspace) {
					workspacesToOpen.push(bestWindowOrFolder.openedWorkspace);
				}

				// Window is single folder
				else if (bestWindowOrFolder.openedFolderPath) {
					foldersToOpen.push(bestWindowOrFolder.openedFolderPath);
				}

				// Window is empty
				else {

					// Do open files
539
					usedWindows.push(this.doOpenFilesInExistingWindow(bestWindowOrFolder, filesToOpen, filesToCreate, filesToDiff, filesToWait));
540 541 542 543 544

					// Reset these because we handled them
					filesToOpen = [];
					filesToCreate = [];
					filesToDiff = [];
545
					filesToWait = void 0;
546
				}
547 548 549 550 551
			}

			// We found a suitable folder to open: add it to foldersToOpen
			else if (typeof bestWindowOrFolder === 'string') {
				foldersToOpen.push(bestWindowOrFolder);
E
Erich Gamma 已提交
552 553
			}

554
			// Finally, if no window or folder is found, just open the files in an empty window
E
Erich Gamma 已提交
555
			else {
B
Benjamin Pasero 已提交
556
				usedWindows.push(this.openInBrowserWindow({
B
Benjamin Pasero 已提交
557 558 559 560 561 562
					userEnv: openConfig.userEnv,
					cli: openConfig.cli,
					initialStartup: openConfig.initialStartup,
					filesToOpen,
					filesToCreate,
					filesToDiff,
563
					filesToWait,
B
Benjamin Pasero 已提交
564
					forceNewWindow: true
B
Benjamin Pasero 已提交
565
				}));
E
Erich Gamma 已提交
566

567 568 569 570
				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
				filesToDiff = [];
571
				filesToWait = void 0;
E
Erich Gamma 已提交
572 573 574
			}
		}

575
		// Handle workspaces to open (instructed and to restore)
576
		const allWorkspacesToOpen = arrays.distinct([...workspacesToRestore, ...workspacesToOpen], workspace => workspace.id); // prevent duplicates
577 578 579 580 581 582 583 584
		if (allWorkspacesToOpen.length > 0) {

			// Check for existing instances
			const windowsOnWorkspace = arrays.coalesce(allWorkspacesToOpen.map(workspaceToOpen => findWindowOnWorkspace(WindowsManager.WINDOWS, workspaceToOpen)));
			if (windowsOnWorkspace.length > 0) {
				const windowOnWorkspace = windowsOnWorkspace[0];

				// Do open files
585
				usedWindows.push(this.doOpenFilesInExistingWindow(windowOnWorkspace, filesToOpen, filesToCreate, filesToDiff, filesToWait));
586 587 588 589 590

				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
				filesToDiff = [];
591
				filesToWait = void 0;
592 593 594 595 596 597

				openFolderInNewWindow = true; // any other folders to open must open in new window then
			}

			// Open remaining ones
			allWorkspacesToOpen.forEach(workspaceToOpen => {
598
				if (windowsOnWorkspace.some(win => win.openedWorkspace.id === workspaceToOpen.id)) {
599 600 601 602
					return; // ignore folders that are already open
				}

				// Do open folder
603
				usedWindows.push(this.doOpenFolderOrWorkspace(openConfig, { workspace: workspaceToOpen }, openFolderInNewWindow, filesToOpen, filesToCreate, filesToDiff, filesToWait));
604 605 606 607 608

				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
				filesToDiff = [];
609
				filesToWait = void 0;
610 611 612 613 614

				openFolderInNewWindow = true; // any other folders to open must open in new window then
			});
		}

615
		// Handle folders to open (instructed and to restore)
616
		const allFoldersToOpen = arrays.distinct([...foldersToRestore, ...foldersToOpen], folder => isLinux ? folder : folder.toLowerCase()); // prevent duplicates
617
		if (allFoldersToOpen.length > 0) {
E
Erich Gamma 已提交
618 619

			// Check for existing instances
620
			const windowsOnFolderPath = arrays.coalesce(allFoldersToOpen.map(folderToOpen => findWindowOnWorkspace(WindowsManager.WINDOWS, folderToOpen)));
621
			if (windowsOnFolderPath.length > 0) {
622
				const windowOnFolderPath = windowsOnFolderPath[0];
E
Erich Gamma 已提交
623

624
				// Do open files
625
				usedWindows.push(this.doOpenFilesInExistingWindow(windowOnFolderPath, filesToOpen, filesToCreate, filesToDiff, filesToWait));
626

E
Erich Gamma 已提交
627 628 629
				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
630
				filesToDiff = [];
631
				filesToWait = void 0;
E
Erich Gamma 已提交
632

B
Benjamin Pasero 已提交
633
				openFolderInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
634 635 636
			}

			// Open remaining ones
637
			allFoldersToOpen.forEach(folderToOpen => {
638
				if (windowsOnFolderPath.some(win => isEqual(win.openedFolderPath, folderToOpen, !isLinux /* ignorecase */))) {
E
Erich Gamma 已提交
639 640 641
					return; // ignore folders that are already open
				}

642
				// Do open folder
643
				usedWindows.push(this.doOpenFolderOrWorkspace(openConfig, { folderPath: folderToOpen }, openFolderInNewWindow, filesToOpen, filesToCreate, filesToDiff, filesToWait));
E
Erich Gamma 已提交
644 645 646 647

				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
648
				filesToDiff = [];
649
				filesToWait = void 0;
E
Erich Gamma 已提交
650

B
Benjamin Pasero 已提交
651
				openFolderInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
652 653 654
			});
		}

655
		// Handle empty to restore
656
		if (emptyToRestore.length > 0) {
657
			emptyToRestore.forEach(emptyWindowBackupFolder => {
B
Benjamin Pasero 已提交
658
				usedWindows.push(this.openInBrowserWindow({
B
Benjamin Pasero 已提交
659 660 661 662 663 664
					userEnv: openConfig.userEnv,
					cli: openConfig.cli,
					initialStartup: openConfig.initialStartup,
					filesToOpen,
					filesToCreate,
					filesToDiff,
665
					filesToWait,
B
Benjamin Pasero 已提交
666
					forceNewWindow: true,
667
					emptyWindowBackupFolder
B
Benjamin Pasero 已提交
668
				}));
669

B
wip  
Benjamin Pasero 已提交
670 671 672 673
				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
				filesToDiff = [];
674
				filesToWait = void 0;
B
wip  
Benjamin Pasero 已提交
675

B
Benjamin Pasero 已提交
676
				openFolderInNewWindow = true; // any other folders to open must open in new window then
677 678
			});
		}
B
Benjamin Pasero 已提交
679

680 681
		// Handle empty to open (only if no other window opened)
		if (usedWindows.length === 0) {
682
			for (let i = 0; i < emptyToOpen; i++) {
B
Benjamin Pasero 已提交
683
				usedWindows.push(this.openInBrowserWindow({
B
Benjamin Pasero 已提交
684 685 686
					userEnv: openConfig.userEnv,
					cli: openConfig.cli,
					initialStartup: openConfig.initialStartup,
687
					forceNewWindow: openFolderInNewWindow
B
Benjamin Pasero 已提交
688
				}));
E
Erich Gamma 已提交
689

690
				openFolderInNewWindow = true; // any other window to open must open in new window then
691 692
			}
		}
E
Erich Gamma 已提交
693

694
		return arrays.distinct(usedWindows);
E
Erich Gamma 已提交
695 696
	}

697
	private doOpenFilesInExistingWindow(window: CodeWindow, filesToOpen: IPath[], filesToCreate: IPath[], filesToDiff: IPath[], filesToWait: IPathsToWaitFor): CodeWindow {
698 699 700
		window.focus(); // make sure window has focus

		window.ready().then(readyWindow => {
701
			readyWindow.send('vscode:openFiles', { filesToOpen, filesToCreate, filesToDiff, filesToWait });
702
		});
B
Benjamin Pasero 已提交
703 704

		return window;
705 706
	}

707 708 709 710 711 712 713 714 715 716
	private doAddFoldersToExistingWidow(window: CodeWindow, foldersToAdd: IPath[]): CodeWindow {
		window.focus(); // make sure window has focus

		window.ready().then(readyWindow => {
			readyWindow.send('vscode:addFolders', { foldersToAdd });
		});

		return window;
	}

717
	private doOpenFolderOrWorkspace(openConfig: IOpenConfiguration, folderOrWorkspace: IPathToOpen, openInNewWindow: boolean, filesToOpen: IPath[], filesToCreate: IPath[], filesToDiff: IPath[], filesToWait: IPathsToWaitFor, windowToUse?: CodeWindow): CodeWindow {
718 719 720 721
		const browserWindow = this.openInBrowserWindow({
			userEnv: openConfig.userEnv,
			cli: openConfig.cli,
			initialStartup: openConfig.initialStartup,
722
			workspace: folderOrWorkspace.workspace,
723 724 725 726
			folderPath: folderOrWorkspace.folderPath,
			filesToOpen,
			filesToCreate,
			filesToDiff,
727
			filesToWait,
728 729
			forceNewWindow: openInNewWindow,
			windowToUse
730 731 732 733 734
		});

		return browserWindow;
	}

B
Benjamin Pasero 已提交
735 736
	private getPathsToOpen(openConfig: IOpenConfiguration): IPathToOpen[] {
		let windowsToOpen: IPathToOpen[];
737
		let isCommandLineOrAPICall = false;
E
Erich Gamma 已提交
738

739
		// Extract paths: from API
B
Benjamin Pasero 已提交
740
		if (openConfig.pathsToOpen && openConfig.pathsToOpen.length > 0) {
741
			windowsToOpen = this.doExtractPathsFromAPI(openConfig);
742
			isCommandLineOrAPICall = true;
E
Erich Gamma 已提交
743 744
		}

B
Benjamin Pasero 已提交
745 746
		// Check for force empty
		else if (openConfig.forceEmpty) {
747
			windowsToOpen = [Object.create(null)];
E
Erich Gamma 已提交
748 749
		}

750
		// Extract paths: from CLI
B
Benjamin Pasero 已提交
751
		else if (openConfig.cli._.length > 0) {
752
			windowsToOpen = this.doExtractPathsFromCLI(openConfig.cli);
753
			isCommandLineOrAPICall = true;
B
Benjamin Pasero 已提交
754 755
		}

756
		// Extract windows: from previous session
B
Benjamin Pasero 已提交
757
		else {
758
			windowsToOpen = this.doGetWindowsFromLastSession();
B
Benjamin Pasero 已提交
759 760
		}

761 762
		// Convert multiple folders into workspace (if opened via API or CLI)
		// This will ensure to open these folders in one window instead of multiple
763 764
		// If we are in addMode, we should not do this because in that case all
		// folders should be added to the existing window.
765
		if (!openConfig.addMode && isCommandLineOrAPICall) {
766 767
			const foldersToOpen = windowsToOpen.filter(path => !!path.folderPath);
			if (foldersToOpen.length > 1) {
B
Benjamin Pasero 已提交
768
				const workspace = this.workspacesMainService.createWorkspaceSync(foldersToOpen.map(folder => ({ uri: URI.file(folder.folderPath) })));
769 770 771 772 773 774 775

				// Add workspace and remove folders thereby
				windowsToOpen.push({ workspace });
				windowsToOpen = windowsToOpen.filter(path => !path.folderPath);
			}
		}

776
		return windowsToOpen;
E
Erich Gamma 已提交
777 778
	}

779 780 781
	private doExtractPathsFromAPI(openConfig: IOpenConfiguration): IPath[] {
		let pathsToOpen = openConfig.pathsToOpen.map(pathToOpen => {
			const path = this.parsePath(pathToOpen, { gotoLineMode: openConfig.cli && openConfig.cli.goto, forceOpenWorkspaceAsFile: openConfig.forceOpenWorkspaceAsFile });
782 783 784

			// Warn if the requested path to open does not exist
			if (!path) {
785
				const options: Electron.MessageBoxOptions = {
786 787
					title: product.nameLong,
					type: 'info',
788 789 790
					buttons: [localize('ok', "OK")],
					message: localize('pathNotExistTitle', "Path does not exist"),
					detail: localize('pathNotExistDetail', "The path '{0}' does not seem to exist anymore on disk.", pathToOpen),
791 792 793
					noLink: true
				};

794
				this.dialogs.showMessageBox(options, this.getFocusedWindow());
795
			}
B
Benjamin Pasero 已提交
796

797 798 799 800 801 802 803 804 805 806
			return path;
		});

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

		return pathsToOpen;
	}

	private doExtractPathsFromCLI(cli: ParsedArgs): IPath[] {
807
		const pathsToOpen = arrays.coalesce(cli._.map(candidate => this.parsePath(candidate, { ignoreFileNotFound: true, gotoLineMode: cli.goto })));
808 809
		if (pathsToOpen.length > 0) {
			return pathsToOpen;
B
Benjamin Pasero 已提交
810 811 812 813 814 815
		}

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

B
Benjamin Pasero 已提交
816
	private doGetWindowsFromLastSession(): IPathToOpen[] {
817 818
		const restoreWindows = this.getRestoreWindowsSetting();
		const lastActiveWindow = this.windowsState.lastActiveWindow;
B
Benjamin Pasero 已提交
819

820
		switch (restoreWindows) {
B
Benjamin Pasero 已提交
821

822
			// none: we always open an empty window
823 824
			case 'none':
				return [Object.create(null)];
B
Benjamin Pasero 已提交
825

826
			// one: restore last opened workspace/folder or empty window
827 828
			case 'one':
				if (lastActiveWindow) {
B
Benjamin Pasero 已提交
829

830
					// workspace
B
Benjamin Pasero 已提交
831 832 833 834 835 836
					const candidateWorkspace = lastActiveWindow.workspace;
					if (candidateWorkspace) {
						const validatedWorkspace = this.parsePath(candidateWorkspace.configPath);
						if (validatedWorkspace && validatedWorkspace.workspace) {
							return [validatedWorkspace];
						}
837 838 839 840 841
					}

					// folder (if path is valid)
					else if (lastActiveWindow.folderPath) {
						const validatedFolder = this.parsePath(lastActiveWindow.folderPath);
B
Benjamin Pasero 已提交
842
						if (validatedFolder && validatedFolder.folderPath) {
843
							return [validatedFolder];
844 845
						}
					}
B
Benjamin Pasero 已提交
846

847
					// otherwise use backup path to restore empty windows
848 849 850 851 852 853 854 855 856 857
					else if (lastActiveWindow.backupPath) {
						return [{ backupPath: lastActiveWindow.backupPath }];
					}
				}
				break;

			// all: restore all windows
			// folders: restore last opened folders only
			case 'all':
			case 'folders':
B
Benjamin Pasero 已提交
858
				const windowsToOpen: IPathToOpen[] = [];
859

860
				// Workspaces
B
Benjamin Pasero 已提交
861
				const workspaceCandidates = this.windowsState.openedWindows.filter(w => !!w.workspace).map(w => w.workspace);
862
				if (lastActiveWindow && lastActiveWindow.workspace) {
B
Benjamin Pasero 已提交
863
					workspaceCandidates.push(lastActiveWindow.workspace);
864
				}
B
Benjamin Pasero 已提交
865
				windowsToOpen.push(...workspaceCandidates.map(candidate => this.parsePath(candidate.configPath)).filter(window => window && window.workspace));
B
Benjamin Pasero 已提交
866

867
				// Folders
B
Benjamin Pasero 已提交
868
				const folderCandidates = this.windowsState.openedWindows.filter(w => !!w.folderPath).map(w => w.folderPath);
869
				if (lastActiveWindow && lastActiveWindow.folderPath) {
B
Benjamin Pasero 已提交
870
					folderCandidates.push(lastActiveWindow.folderPath);
871
				}
B
Benjamin Pasero 已提交
872
				windowsToOpen.push(...folderCandidates.map(candidate => this.parsePath(candidate)).filter(window => window && window.folderPath));
B
Benjamin Pasero 已提交
873

874 875
				// Windows that were Empty
				if (restoreWindows === 'all') {
876 877
					const lastOpenedEmpty = this.windowsState.openedWindows.filter(w => !w.workspace && !w.folderPath && w.backupPath).map(w => w.backupPath);
					const lastActiveEmpty = lastActiveWindow && !lastActiveWindow.workspace && !lastActiveWindow.folderPath && lastActiveWindow.backupPath;
878 879 880 881 882 883 884 885 886 887 888 889
					if (lastActiveEmpty) {
						lastOpenedEmpty.push(lastActiveEmpty);
					}

					windowsToOpen.push(...lastOpenedEmpty.map(backupPath => ({ backupPath })));
				}

				if (windowsToOpen.length > 0) {
					return windowsToOpen;
				}

				break;
B
Benjamin Pasero 已提交
890
		}
E
Erich Gamma 已提交
891

892
		// Always fallback to empty window
B
Benjamin Pasero 已提交
893
		return [Object.create(null)];
E
Erich Gamma 已提交
894 895
	}

896 897 898 899 900
	private getRestoreWindowsSetting(): RestoreWindowsSetting {
		let restoreWindows: RestoreWindowsSetting;
		if (this.lifecycleService.wasRestarted) {
			restoreWindows = 'all'; // always reopen all windows when an update was applied
		} else {
901
			const windowConfig = this.configurationService.getValue<IWindowSettings>('window');
902
			restoreWindows = ((windowConfig && windowConfig.restoreWindows) || 'one') as RestoreWindowsSetting;
903 904 905 906 907 908 909 910 911

			if (['all', 'folders', 'one', 'none'].indexOf(restoreWindows) === -1) {
				restoreWindows = 'one';
			}
		}

		return restoreWindows;
	}

B
Benjamin Pasero 已提交
912
	private parsePath(anyPath: string, options?: { ignoreFileNotFound?: boolean, gotoLineMode?: boolean, forceOpenWorkspaceAsFile?: boolean; }): IPathToOpen {
E
Erich Gamma 已提交
913 914 915 916
		if (!anyPath) {
			return null;
		}

917
		let parsedPath: IPathWithLineAndColumn;
918 919 920

		const gotoLineMode = options && options.gotoLineMode;
		if (options && options.gotoLineMode) {
J
Joao Moreno 已提交
921
			parsedPath = parseLineAndColumnAware(anyPath);
E
Erich Gamma 已提交
922 923 924
			anyPath = parsedPath.path;
		}

925
		const candidate = normalize(anyPath);
E
Erich Gamma 已提交
926
		try {
B
Benjamin Pasero 已提交
927
			const candidateStat = fs.statSync(candidate);
E
Erich Gamma 已提交
928
			if (candidateStat) {
929
				if (candidateStat.isFile()) {
930

931 932
					// Workspace (unless disabled via flag)
					if (!options || !options.forceOpenWorkspaceAsFile) {
B
Benjamin Pasero 已提交
933
						const workspace = this.workspacesMainService.resolveWorkspaceSync(candidate);
934
						if (workspace) {
935
							return { workspace: { id: workspace.id, configPath: workspace.configPath } };
936
						}
937 938 939
					}

					// File
940
					return {
941
						filePath: candidate,
E
Erich Gamma 已提交
942
						lineNumber: gotoLineMode ? parsedPath.line : void 0,
943
						columnNumber: gotoLineMode ? parsedPath.column : void 0
944 945 946 947 948 949 950
					};
				}

				// Folder
				return {
					folderPath: candidate
				};
E
Erich Gamma 已提交
951 952
			}
		} catch (error) {
B
Benjamin Pasero 已提交
953
			this.historyMainService.removeFromRecentlyOpened([candidate]); // since file does not seem to exist anymore, remove from recent
954

955
			if (options && options.ignoreFileNotFound) {
E
Erich Gamma 已提交
956 957 958 959 960 961 962
				return { filePath: candidate, createFilePath: true }; // assume this is a file that does not yet exist
			}
		}

		return null;
	}

B
Benjamin Pasero 已提交
963 964 965
	private shouldOpenNewWindow(openConfig: IOpenConfiguration): { openFolderInNewWindow: boolean; openFilesInNewWindow: boolean; } {

		// let the user settings override how folders are open in a new window or same window unless we are forced
966
		const windowConfig = this.configurationService.getValue<IWindowSettings>('window');
967 968 969
		const openFolderInNewWindowConfig = (windowConfig && windowConfig.openFoldersInNewWindow) || 'default' /* default */;
		const openFilesInNewWindowConfig = (windowConfig && windowConfig.openFilesInNewWindow) || 'off' /* default */;

B
Benjamin Pasero 已提交
970
		let openFolderInNewWindow = (openConfig.preferNewWindow || openConfig.forceNewWindow) && !openConfig.forceReuseWindow;
971 972
		if (!openConfig.forceNewWindow && !openConfig.forceReuseWindow && (openFolderInNewWindowConfig === 'on' || openFolderInNewWindowConfig === 'off')) {
			openFolderInNewWindow = (openFolderInNewWindowConfig === 'on');
B
Benjamin Pasero 已提交
973 974 975 976 977 978 979 980 981 982 983
		}

		// let the user settings override how files are open in a new window or same window unless we are forced (not for extension development though)
		let openFilesInNewWindow: boolean;
		if (openConfig.forceNewWindow || openConfig.forceReuseWindow) {
			openFilesInNewWindow = openConfig.forceNewWindow && !openConfig.forceReuseWindow;
		} else {
			if (openConfig.context === OpenContext.DOCK) {
				openFilesInNewWindow = true; // only on macOS do we allow to open files in a new window if this is triggered via DOCK context
			}

984 985
			if (!openConfig.cli.extensionDevelopmentPath && (openFilesInNewWindowConfig === 'on' || openFilesInNewWindowConfig === 'off')) {
				openFilesInNewWindow = (openFilesInNewWindowConfig === 'on');
B
Benjamin Pasero 已提交
986 987 988 989 990 991
			}
		}

		return { openFolderInNewWindow, openFilesInNewWindow };
	}

B
Benjamin Pasero 已提交
992
	public openExtensionDevelopmentHostWindow(openConfig: IOpenConfiguration): void {
E
Erich Gamma 已提交
993

B
Benjamin Pasero 已提交
994 995 996
		// Reload an existing extension development host window on the same path
		// We currently do not allow more than one extension development window
		// on the same extension path.
997 998 999 1000
		const existingWindow = findWindowOnExtensionDevelopmentPath(WindowsManager.WINDOWS, openConfig.cli.extensionDevelopmentPath);
		if (existingWindow) {
			this.reload(existingWindow, openConfig.cli);
			existingWindow.focus(); // make sure it gets focus and is restored
E
Erich Gamma 已提交
1001

B
Benjamin Pasero 已提交
1002 1003
			return;
		}
E
Erich Gamma 已提交
1004

1005
		// Fill in previously opened workspace unless an explicit path is provided and we are not unit testing
B
Benjamin Pasero 已提交
1006
		if (openConfig.cli._.length === 0 && !openConfig.cli.extensionTestsPath) {
1007 1008 1009 1010
			const extensionDevelopmentWindowState = this.windowsState.lastPluginDevelopmentHostWindow;
			const workspaceToOpen = extensionDevelopmentWindowState && (extensionDevelopmentWindowState.workspace || extensionDevelopmentWindowState.folderPath);
			if (workspaceToOpen) {
				openConfig.cli._ = [isSingleFolderWorkspaceIdentifier(workspaceToOpen) ? workspaceToOpen : workspaceToOpen.configPath];
E
Erich Gamma 已提交
1011 1012 1013
			}
		}

1014 1015 1016
		// Make sure we are not asked to open a workspace or folder that is already opened
		if (openConfig.cli._.some(path => !!findWindowOnWorkspaceOrFolderPath(WindowsManager.WINDOWS, path))) {
			openConfig.cli._ = [];
E
Erich Gamma 已提交
1017 1018
		}

B
Benjamin Pasero 已提交
1019 1020
		// Open it
		this.open({ context: openConfig.context, cli: openConfig.cli, forceNewWindow: true, forceEmpty: openConfig.cli._.length === 0, userEnv: openConfig.userEnv });
E
Erich Gamma 已提交
1021 1022
	}

B
Benjamin Pasero 已提交
1023 1024 1025 1026 1027
	private openInBrowserWindow(options: IOpenBrowserWindowOptions): CodeWindow {

		// Build IWindowConfiguration from config and options
		const configuration: IWindowConfiguration = mixin({}, options.cli); // inherit all properties from CLI
		configuration.appRoot = this.environmentService.appRoot;
1028
		configuration.machineId = this.machineId;
B
Benjamin Pasero 已提交
1029 1030 1031
		configuration.execPath = process.execPath;
		configuration.userEnv = assign({}, this.initialUserEnv, options.userEnv || {});
		configuration.isInitialStartup = options.initialStartup;
1032
		configuration.workspace = options.workspace;
1033
		configuration.folderPath = options.folderPath;
B
Benjamin Pasero 已提交
1034 1035 1036
		configuration.filesToOpen = options.filesToOpen;
		configuration.filesToCreate = options.filesToCreate;
		configuration.filesToDiff = options.filesToDiff;
1037
		configuration.filesToWait = options.filesToWait;
B
Benjamin Pasero 已提交
1038 1039
		configuration.nodeCachedDataDir = this.environmentService.nodeCachedDataDir;

1040
		// if we know the backup folder upfront (for empty windows to restore), we can set it
1041
		// directly here which helps for restoring UI state associated with that window.
B
Benjamin Pasero 已提交
1042
		// For all other cases we first call into registerEmptyWindowBackupSync() to set it before
1043
		// loading the window.
1044
		if (options.emptyWindowBackupFolder) {
1045
			configuration.backupPath = join(this.environmentService.backupHome, options.emptyWindowBackupFolder);
1046 1047
		}

1048
		let window: CodeWindow;
B
Benjamin Pasero 已提交
1049
		if (!options.forceNewWindow) {
1050 1051 1052
			window = options.windowToUse || this.getLastActiveWindow();
			if (window) {
				window.focus();
E
Erich Gamma 已提交
1053 1054 1055 1056
			}
		}

		// New window
1057
		if (!window) {
1058
			const windowConfig = this.configurationService.getValue<IWindowSettings>('window');
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
			const state = this.getNewWindowState(configuration);

			// Window state is not from a previous session: only allow fullscreen if we inherit it or user wants fullscreen
			let allowFullscreen: boolean;
			if (state.hasDefaultState) {
				allowFullscreen = (windowConfig && windowConfig.newWindowDimensions && ['fullscreen', 'inherit'].indexOf(windowConfig.newWindowDimensions) >= 0);
			}

			// Window state is from a previous session: only allow fullscreen when we got updated or user wants to restore
			else {
1069
				allowFullscreen = this.lifecycleService.wasRestarted || (windowConfig && windowConfig.restoreFullscreen);
1070 1071 1072 1073 1074
			}

			if (state.mode === WindowMode.Fullscreen && !allowFullscreen) {
				state.mode = WindowMode.Normal;
			}
1075

1076
			window = this.instantiationService.createInstance(CodeWindow, {
1077
				state,
1078
				extensionDevelopmentPath: configuration.extensionDevelopmentPath,
1079
				isExtensionTestHost: !!configuration.extensionTestsPath
1080
			});
1081

B
Benjamin Pasero 已提交
1082
			// Add to our list of windows
1083
			WindowsManager.WINDOWS.push(window);
E
Erich Gamma 已提交
1084

B
Benjamin Pasero 已提交
1085 1086 1087
			// Indicate number change via event
			this._onWindowsCountChanged.fire({ oldCount: WindowsManager.WINDOWS.length - 1, newCount: WindowsManager.WINDOWS.length });

E
Erich Gamma 已提交
1088
			// Window Events
1089 1090 1091 1092 1093
			window.win.webContents.removeAllListeners('devtools-reload-page'); // remove built in listener so we can handle this on our own
			window.win.webContents.on('devtools-reload-page', () => this.reload(window));
			window.win.webContents.on('crashed', () => this.onWindowError(window, WindowError.CRASHED));
			window.win.on('unresponsive', () => this.onWindowError(window, WindowError.UNRESPONSIVE));
			window.win.on('closed', () => this.onWindowClosed(window));
E
Erich Gamma 已提交
1094 1095

			// Lifecycle
1096
			this.lifecycleService.registerWindow(window);
E
Erich Gamma 已提交
1097 1098 1099 1100 1101 1102
		}

		// Existing window
		else {

			// Some configuration things get inherited if the window is being reused and we are
B
Benjamin Pasero 已提交
1103
			// in extension development host mode. These options are all development related.
1104
			const currentWindowConfig = window.config;
A
Alex Dima 已提交
1105 1106
			if (!configuration.extensionDevelopmentPath && currentWindowConfig && !!currentWindowConfig.extensionDevelopmentPath) {
				configuration.extensionDevelopmentPath = currentWindowConfig.extensionDevelopmentPath;
B
Benjamin Pasero 已提交
1107
				configuration.verbose = currentWindowConfig.verbose;
1108
				configuration.debugBrkPluginHost = currentWindowConfig.debugBrkPluginHost;
1109
				configuration.debugId = currentWindowConfig.debugId;
1110
				configuration.debugPluginHost = currentWindowConfig.debugPluginHost;
1111
				configuration['extensions-dir'] = currentWindowConfig['extensions-dir'];
E
Erich Gamma 已提交
1112 1113 1114 1115
			}
		}

		// Only load when the window has not vetoed this
1116
		this.lifecycleService.unload(window, UnloadReason.LOAD).done(veto => {
E
Erich Gamma 已提交
1117 1118
			if (!veto) {

B
Benjamin Pasero 已提交
1119 1120
				// Register window for backups
				if (!configuration.extensionDevelopmentPath) {
1121
					if (configuration.workspace) {
B
Benjamin Pasero 已提交
1122
						configuration.backupPath = this.backupMainService.registerWorkspaceBackupSync(configuration.workspace);
1123
					} else if (configuration.folderPath) {
B
Benjamin Pasero 已提交
1124
						configuration.backupPath = this.backupMainService.registerFolderBackupSync(configuration.folderPath);
B
Benjamin Pasero 已提交
1125
					} else {
B
Benjamin Pasero 已提交
1126
						configuration.backupPath = this.backupMainService.registerEmptyWindowBackupSync(options.emptyWindowBackupFolder);
B
Benjamin Pasero 已提交
1127
					}
B
Benjamin Pasero 已提交
1128 1129
				}

E
Erich Gamma 已提交
1130
				// Load it
1131
				window.load(configuration);
1132 1133 1134

				// Signal event
				this._onWindowLoad.fire(window.id);
E
Erich Gamma 已提交
1135 1136
			}
		});
1137

1138
		return window;
E
Erich Gamma 已提交
1139 1140
	}

1141
	private getNewWindowState(configuration: IWindowConfiguration): INewWindowState {
1142
		const lastActive = this.getLastActiveWindow();
E
Erich Gamma 已提交
1143

1144 1145
		// Restore state unless we are running extension tests
		if (!configuration.extensionTestsPath) {
E
Erich Gamma 已提交
1146

1147 1148 1149
			// extension development host Window - load from stored settings if any
			if (!!configuration.extensionDevelopmentPath && this.windowsState.lastPluginDevelopmentHostWindow) {
				return this.windowsState.lastPluginDevelopmentHostWindow.uiState;
1150 1151
			}

1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
			// Known Workspace - load from stored settings
			if (configuration.workspace) {
				const stateForWorkspace = this.windowsState.openedWindows.filter(o => o.workspace && o.workspace.id === configuration.workspace.id).map(o => o.uiState);
				if (stateForWorkspace.length) {
					return stateForWorkspace[0];
				}
			}

			// Known Folder - load from stored settings
			if (configuration.folderPath) {
				const stateForFolder = this.windowsState.openedWindows.filter(o => isEqual(o.folderPath, configuration.folderPath, !isLinux /* ignorecase */)).map(o => o.uiState);
				if (stateForFolder.length) {
					return stateForFolder[0];
				}
1166 1167
			}

1168 1169 1170 1171 1172 1173
			// Empty windows with backups
			else if (configuration.backupPath) {
				const stateForEmptyWindow = this.windowsState.openedWindows.filter(o => o.backupPath === configuration.backupPath).map(o => o.uiState);
				if (stateForEmptyWindow.length) {
					return stateForEmptyWindow[0];
				}
E
Erich Gamma 已提交
1174 1175
			}

1176 1177 1178 1179 1180
			// First Window
			const lastActiveState = this.lastClosedWindowState || this.windowsState.lastActiveWindow;
			if (!lastActive && lastActiveState) {
				return lastActiveState.uiState;
			}
E
Erich Gamma 已提交
1181 1182 1183 1184 1185 1186 1187
		}

		//
		// 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
1188
		let displayToUse: Electron.Display;
B
Benjamin Pasero 已提交
1189
		const displays = screen.getAllDisplays();
E
Erich Gamma 已提交
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199

		// 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
B
Benjamin Pasero 已提交
1200
			if (isMacintosh) {
B
Benjamin Pasero 已提交
1201
				const cursorPoint = screen.getCursorScreenPoint();
E
Erich Gamma 已提交
1202 1203 1204 1205 1206 1207 1208 1209
				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());
			}

1210
			// fallback to primary display or first display
E
Erich Gamma 已提交
1211
			if (!displayToUse) {
1212
				displayToUse = screen.getPrimaryDisplay() || displays[0];
E
Erich Gamma 已提交
1213 1214 1215
			}
		}

1216
		let state = defaultWindowState() as INewWindowState;
1217 1218
		state.x = displayToUse.bounds.x + (displayToUse.bounds.width / 2) - (state.width / 2);
		state.y = displayToUse.bounds.y + (displayToUse.bounds.height / 2) - (state.height / 2);
E
Erich Gamma 已提交
1219

1220
		// Check for newWindowDimensions setting and adjust accordingly
1221
		const windowConfig = this.configurationService.getValue<IWindowSettings>('window');
1222 1223 1224 1225 1226 1227 1228 1229 1230
		let ensureNoOverlap = true;
		if (windowConfig && windowConfig.newWindowDimensions) {
			if (windowConfig.newWindowDimensions === 'maximized') {
				state.mode = WindowMode.Maximized;
				ensureNoOverlap = false;
			} else if (windowConfig.newWindowDimensions === 'fullscreen') {
				state.mode = WindowMode.Fullscreen;
				ensureNoOverlap = false;
			} else if (windowConfig.newWindowDimensions === 'inherit' && lastActive) {
B
Benjamin Pasero 已提交
1231 1232 1233 1234 1235 1236 1237
				const lastActiveState = lastActive.serializeWindowState();
				if (lastActiveState.mode === WindowMode.Fullscreen) {
					state.mode = WindowMode.Fullscreen; // only take mode (fixes https://github.com/Microsoft/vscode/issues/19331)
				} else {
					state = lastActiveState;
				}

1238 1239 1240 1241 1242 1243 1244 1245
				ensureNoOverlap = false;
			}
		}

		if (ensureNoOverlap) {
			state = this.ensureNoOverlap(state);
		}

1246 1247
		state.hasDefaultState = true; // flag as default state

1248
		return state;
E
Erich Gamma 已提交
1249 1250
	}

J
Joao Moreno 已提交
1251
	private ensureNoOverlap(state: ISingleWindowState): ISingleWindowState {
E
Erich Gamma 已提交
1252 1253 1254 1255
		if (WindowsManager.WINDOWS.length === 0) {
			return state;
		}

1256 1257
		const existingWindowBounds = WindowsManager.WINDOWS.map(win => win.getBounds());
		while (existingWindowBounds.some(b => b.x === state.x || b.y === state.y)) {
E
Erich Gamma 已提交
1258 1259 1260 1261 1262 1263 1264
			state.x += 30;
			state.y += 30;
		}

		return state;
	}

B
Benjamin Pasero 已提交
1265 1266 1267 1268 1269
	public reload(win: CodeWindow, cli?: ParsedArgs): void {

		// Only reload when the window has not vetoed this
		this.lifecycleService.unload(win, UnloadReason.RELOAD).done(veto => {
			if (!veto) {
1270
				win.reload(void 0, cli);
B
Benjamin Pasero 已提交
1271 1272 1273 1274 1275 1276 1277

				// Emit
				this._onWindowReload.fire(win.id);
			}
		});
	}

1278 1279 1280 1281 1282 1283 1284
	public closeWorkspace(win: CodeWindow): void {
		this.openInBrowserWindow({
			cli: this.environmentService.args,
			windowToUse: win
		});
	}

1285 1286
	public saveAndEnterWorkspace(win: CodeWindow, path: string): TPromise<IEnterWorkspaceResult> {
		return this.workspacesManager.saveAndEnterWorkspace(win, path).then(result => this.doEnterWorkspace(win, result));
1287
	}
1288

1289 1290
	public createAndEnterWorkspace(win: CodeWindow, folders?: IWorkspaceFolderCreationData[], path?: string): TPromise<IEnterWorkspaceResult> {
		return this.workspacesManager.createAndEnterWorkspace(win, folders, path).then(result => this.doEnterWorkspace(win, result));
1291
	}
1292

1293
	private doEnterWorkspace(win: CodeWindow, result: IEnterWorkspaceResult): IEnterWorkspaceResult {
1294

1295
		// Mark as recently opened
B
Benjamin Pasero 已提交
1296
		this.historyMainService.addRecentlyOpened([result.workspace], []);
1297

1298 1299 1300
		// Trigger Eevent to indicate load of workspace into window
		this._onWindowReady.fire(win);

1301
		return result;
1302 1303
	}

1304 1305
	public pickWorkspaceAndOpen(options: INativeOpenDialogOptions): void {
		this.workspacesManager.pickWorkspaceAndOpen(options);
1306 1307 1308
	}

	private onBeforeWindowUnload(e: IWindowUnloadEvent): void {
1309 1310
		const windowClosing = (e.reason === UnloadReason.CLOSE);
		const windowLoading = (e.reason === UnloadReason.LOAD);
1311 1312 1313 1314 1315
		if (!windowClosing && !windowLoading) {
			return; // only interested when window is closing or loading
		}

		const workspace = e.window.openedWorkspace;
B
Benjamin Pasero 已提交
1316
		if (!workspace || !this.workspacesMainService.isUntitledWorkspace(workspace)) {
1317 1318 1319
			return; // only care about untitled workspaces to ask for saving
		}

1320 1321 1322 1323
		if (e.window.config && !!e.window.config.extensionDevelopmentPath) {
			return; // do not ask to save workspace when doing extension development
		}

1324 1325 1326 1327
		if (windowClosing && !isMacintosh && this.getWindowCount() === 1) {
			return; // Windows/Linux: quits when last window is closed, so do not ask then
		}

1328
		// Handle untitled workspaces with prompt as needed
1329
		e.veto(this.workspacesManager.promptToSaveUntitledWorkspace(this.getWindowById(e.window.id), workspace));
1330 1331
	}

B
Benjamin Pasero 已提交
1332
	public focusLastActive(cli: ParsedArgs, context: OpenContext): CodeWindow {
B
Benjamin Pasero 已提交
1333
		const lastActive = this.getLastActiveWindow();
E
Erich Gamma 已提交
1334
		if (lastActive) {
B
Benjamin Pasero 已提交
1335
			lastActive.focus();
1336 1337

			return lastActive;
E
Erich Gamma 已提交
1338 1339
		}

B
Benjamin Pasero 已提交
1340
		// No window - open new empty one
1341
		return this.open({ context, cli, forceEmpty: true })[0];
E
Erich Gamma 已提交
1342 1343
	}

B
Benjamin Pasero 已提交
1344
	public getLastActiveWindow(): CodeWindow {
1345
		return getLastActiveWindow(WindowsManager.WINDOWS);
E
Erich Gamma 已提交
1346 1347
	}

1348 1349
	public openNewWindow(context: OpenContext): void {
		this.open({ context, cli: this.environmentService.args, forceNewWindow: true, forceEmpty: true });
E
Erich Gamma 已提交
1350 1351
	}

1352
	public waitForWindowCloseOrLoad(windowId: number): TPromise<void> {
1353
		return new TPromise<void>(c => {
1354
			function handler(id: number) {
1355
				if (id === windowId) {
1356 1357 1358
					closeListener.dispose();
					loadListener.dispose();

1359 1360
					c(null);
				}
1361 1362 1363 1364
			}

			const closeListener = this.onWindowClose(id => handler(id));
			const loadListener = this.onWindowLoad(id => handler(id));
1365 1366 1367
		});
	}

E
Erich Gamma 已提交
1368 1369 1370 1371
	public sendToFocused(channel: string, ...args: any[]): void {
		const focusedWindow = this.getFocusedWindow() || this.getLastActiveWindow();

		if (focusedWindow) {
1372
			focusedWindow.sendWhenReady(channel, ...args);
E
Erich Gamma 已提交
1373 1374 1375
		}
	}

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

1382
			w.sendWhenReady(channel, payload);
E
Erich Gamma 已提交
1383 1384 1385
		});
	}

B
Benjamin Pasero 已提交
1386
	public getFocusedWindow(): CodeWindow {
B
Benjamin Pasero 已提交
1387
		const win = BrowserWindow.getFocusedWindow();
E
Erich Gamma 已提交
1388 1389 1390 1391 1392 1393 1394
		if (win) {
			return this.getWindowById(win.id);
		}

		return null;
	}

B
Benjamin Pasero 已提交
1395
	public getWindowById(windowId: number): CodeWindow {
1396
		const res = WindowsManager.WINDOWS.filter(w => w.id === windowId);
E
Erich Gamma 已提交
1397 1398 1399 1400 1401 1402 1403
		if (res && res.length === 1) {
			return res[0];
		}

		return null;
	}

B
Benjamin Pasero 已提交
1404
	public getWindows(): CodeWindow[] {
E
Erich Gamma 已提交
1405 1406 1407 1408 1409 1410 1411
		return WindowsManager.WINDOWS;
	}

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

1412
	private onWindowError(window: CodeWindow, error: WindowError): void {
B
Benjamin Pasero 已提交
1413
		this.logService.error(error === WindowError.CRASHED ? '[VS Code]: render process crashed!' : '[VS Code]: detected unresponsive');
E
Erich Gamma 已提交
1414 1415 1416

		// Unresponsive
		if (error === WindowError.UNRESPONSIVE) {
1417
			this.dialogs.showMessageBox({
B
Benjamin Pasero 已提交
1418
				title: product.nameLong,
E
Erich Gamma 已提交
1419
				type: 'warning',
1420
				buttons: [mnemonicButtonLabel(localize({ key: 'reopen', comment: ['&& denotes a mnemonic'] }, "&&Reopen")), mnemonicButtonLabel(localize({ key: 'wait', comment: ['&& denotes a mnemonic'] }, "&&Keep Waiting")), mnemonicButtonLabel(localize({ key: 'close', comment: ['&& denotes a mnemonic'] }, "&&Close"))],
1421 1422
				message: localize('appStalled', "The window is no longer responding"),
				detail: localize('appStalledDetail', "You can reopen or close the window or keep waiting."),
E
Erich Gamma 已提交
1423
				noLink: true
1424 1425 1426 1427
			}, window).then(result => {
				if (!window.win) {
					return; // Return early if the window has been going down already
				}
1428

1429 1430 1431 1432 1433 1434 1435
				if (result.button === 0) {
					window.reload();
				} else if (result.button === 2) {
					this.onBeforeWindowClose(window); // 'close' event will not be fired on destroy(), so run it manually
					window.win.destroy(); // make sure to destroy the window as it is unresponsive
				}
			});
E
Erich Gamma 已提交
1436 1437 1438 1439
		}

		// Crashed
		else {
1440
			this.dialogs.showMessageBox({
B
Benjamin Pasero 已提交
1441
				title: product.nameLong,
E
Erich Gamma 已提交
1442
				type: 'warning',
1443
				buttons: [mnemonicButtonLabel(localize({ key: 'reopen', comment: ['&& denotes a mnemonic'] }, "&&Reopen")), mnemonicButtonLabel(localize({ key: 'close', comment: ['&& denotes a mnemonic'] }, "&&Close"))],
1444 1445
				message: localize('appCrashed', "The window has crashed"),
				detail: localize('appCrashedDetail', "We are sorry for the inconvenience! You can reopen the window to continue where you left off."),
E
Erich Gamma 已提交
1446
				noLink: true
1447 1448 1449 1450
			}, window).then(result => {
				if (!window.win) {
					return; // Return early if the window has been going down already
				}
1451

1452 1453 1454 1455 1456 1457 1458
				if (result.button === 0) {
					window.reload();
				} else if (result.button === 1) {
					this.onBeforeWindowClose(window); // 'close' event will not be fired on destroy(), so run it manually
					window.win.destroy(); // make sure to destroy the window as it has crashed
				}
			});
E
Erich Gamma 已提交
1459 1460 1461
		}
	}

B
Benjamin Pasero 已提交
1462
	private onWindowClosed(win: CodeWindow): void {
E
Erich Gamma 已提交
1463 1464 1465 1466 1467

		// Tell window
		win.dispose();

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

		// Emit
B
Benjamin Pasero 已提交
1472
		this._onWindowsCountChanged.fire({ oldCount: WindowsManager.WINDOWS.length + 1, newCount: WindowsManager.WINDOWS.length });
1473
		this._onWindowClose.fire(win.id);
E
Erich Gamma 已提交
1474
	}
B
Benjamin Pasero 已提交
1475

B
Benjamin Pasero 已提交
1476 1477
	public pickFileFolderAndOpen(options: INativeOpenDialogOptions): void {
		this.doPickAndOpen(options, true /* pick folders */, true /* pick files */);
1478 1479
	}

B
Benjamin Pasero 已提交
1480 1481
	public pickFolderAndOpen(options: INativeOpenDialogOptions): void {
		this.doPickAndOpen(options, true /* pick folders */, false /* pick files */);
1482 1483
	}

B
Benjamin Pasero 已提交
1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517
	public pickFileAndOpen(options: INativeOpenDialogOptions): void {
		this.doPickAndOpen(options, false /* pick folders */, true /* pick files */);
	}

	private doPickAndOpen(options: INativeOpenDialogOptions, pickFolders: boolean, pickFiles: boolean): void {
		const internalOptions = options as IInternalNativeOpenDialogOptions;

		internalOptions.pickFolders = pickFolders;
		internalOptions.pickFiles = pickFiles;

		if (!internalOptions.dialogOptions) {
			internalOptions.dialogOptions = Object.create(null);
		}

		if (!internalOptions.dialogOptions.title) {
			if (pickFolders && pickFiles) {
				internalOptions.dialogOptions.title = localize('open', "Open");
			} else if (pickFolders) {
				internalOptions.dialogOptions.title = localize('openFolder', "Open Folder");
			} else {
				internalOptions.dialogOptions.title = localize('openFile', "Open File");
			}
		}

		if (!internalOptions.telemetryEventName) {
			if (pickFolders && pickFiles) {
				internalOptions.telemetryEventName = 'openFileFolder';
			} else if (pickFolders) {
				internalOptions.telemetryEventName = 'openFolder';
			} else {
				internalOptions.telemetryEventName = 'openFile';
			}
		}

1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530
		this.dialogs.pickAndOpen(internalOptions);
	}

	public showMessageBox(options: Electron.MessageBoxOptions, win?: CodeWindow): TPromise<IMessageBoxResult> {
		return this.dialogs.showMessageBox(options, win);
	}

	public showSaveDialog(options: Electron.SaveDialogOptions, win?: CodeWindow): TPromise<string> {
		return this.dialogs.showSaveDialog(options, win);
	}

	public showOpenDialog(options: Electron.OpenDialogOptions, win?: CodeWindow): TPromise<string[]> {
		return this.dialogs.showOpenDialog(options, win);
B
Benjamin Pasero 已提交
1531 1532 1533 1534 1535 1536
	}

	public quit(): void {

		// If the user selected to exit from an extension development host window, do not quit, but just
		// close the window unless this is the last window that is opened.
1537 1538 1539
		const window = this.getFocusedWindow();
		if (window && window.isExtensionDevelopmentHost && this.getWindowCount() > 1) {
			window.win.close();
B
Benjamin Pasero 已提交
1540 1541 1542 1543 1544 1545 1546 1547
		}

		// Otherwise: normal quit
		else {
			setTimeout(() => {
				this.lifecycleService.quit();
			}, 10 /* delay to unwind callback stack (IPC) */);
		}
1548
	}
B
Benjamin Pasero 已提交
1549 1550
}

B
Benjamin Pasero 已提交
1551
interface IInternalNativeOpenDialogOptions extends INativeOpenDialogOptions {
B
Benjamin Pasero 已提交
1552 1553 1554 1555
	pickFolders?: boolean;
	pickFiles?: boolean;
}

1556
class Dialogs {
B
Benjamin Pasero 已提交
1557

1558
	private static readonly workingDirPickerStorageKey = 'pickerWorkingDir';
1559

1560 1561 1562
	private mapWindowToDialogQueue: Map<number, Queue<any>>;
	private noWindowDialogQueue: Queue<any>;

B
Benjamin Pasero 已提交
1563 1564 1565
	constructor(
		private environmentService: IEnvironmentService,
		private telemetryService: ITelemetryService,
B
Benjamin Pasero 已提交
1566
		private stateService: IStateService,
B
Benjamin Pasero 已提交
1567 1568
		private windowsMainService: IWindowsMainService
	) {
1569 1570
		this.mapWindowToDialogQueue = new Map<number, Queue<any>>();
		this.noWindowDialogQueue = new Queue<any>();
B
Benjamin Pasero 已提交
1571 1572
	}

B
Benjamin Pasero 已提交
1573
	public pickAndOpen(options: INativeOpenDialogOptions): void {
1574
		this.getFileOrFolderPaths(options).then(paths => {
B
Benjamin Pasero 已提交
1575 1576 1577 1578
			const numberOfPaths = paths ? paths.length : 0;

			// Telemetry
			if (options.telemetryEventName) {
K
kieferrm 已提交
1579
				// __GDPR__TODO__ Dynamic event names and dynamic properties. Can not be registered statically.
B
Benjamin Pasero 已提交
1580 1581 1582 1583 1584 1585 1586 1587 1588
				this.telemetryService.publicLog(options.telemetryEventName, {
					...options.telemetryExtraData,
					outcome: numberOfPaths ? 'success' : 'canceled',
					numberOfPaths
				});
			}

			// Open
			if (numberOfPaths) {
1589 1590 1591 1592 1593 1594 1595
				this.windowsMainService.open({
					context: OpenContext.DIALOG,
					cli: this.environmentService.args,
					pathsToOpen: paths,
					forceNewWindow: options.forceNewWindow,
					forceOpenWorkspaceAsFile: options.dialogOptions && !equals(options.dialogOptions.filters, WORKSPACE_FILTER)
				});
1596 1597 1598 1599
			}
		});
	}

1600
	private getFileOrFolderPaths(options: IInternalNativeOpenDialogOptions): TPromise<string[]> {
1601

B
Benjamin Pasero 已提交
1602 1603 1604 1605 1606 1607 1608
		// Ensure dialog options
		if (!options.dialogOptions) {
			options.dialogOptions = Object.create(null);
		}

		// Ensure defaultPath
		if (!options.dialogOptions.defaultPath) {
1609
			options.dialogOptions.defaultPath = this.stateService.getItem<string>(Dialogs.workingDirPickerStorageKey);
1610 1611
		}

B
Benjamin Pasero 已提交
1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624
		// Ensure properties
		if (typeof options.pickFiles === 'boolean' || typeof options.pickFolders === 'boolean') {
			options.dialogOptions.properties = void 0; // let it override based on the booleans

			if (options.pickFiles && options.pickFolders) {
				options.dialogOptions.properties = ['multiSelections', 'openDirectory', 'openFile', 'createDirectory'];
			}
		}

		if (!options.dialogOptions.properties) {
			options.dialogOptions.properties = ['multiSelections', options.pickFolders ? 'openDirectory' : 'openFile', 'createDirectory'];
		}

1625 1626 1627 1628
		if (isMacintosh) {
			options.dialogOptions.properties.push('treatPackageAsDirectory'); // always drill into .app files
		}

B
Benjamin Pasero 已提交
1629
		// Show Dialog
1630
		const focusedWindow = this.windowsMainService.getWindowById(options.windowId) || this.windowsMainService.getFocusedWindow();
1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670

		return this.showOpenDialog(options.dialogOptions, focusedWindow).then(paths => {
			if (paths && paths.length > 0) {

				// Remember path in storage for next time
				this.stateService.setItem(Dialogs.workingDirPickerStorageKey, dirname(paths[0]));

				return paths;
			}

			return void 0;
		});
	}

	private getDialogQueue(window?: ICodeWindow): Queue<any> {
		if (!window) {
			return this.noWindowDialogQueue;
		}

		let windowDialogQueue = this.mapWindowToDialogQueue.get(window.id);
		if (!windowDialogQueue) {
			windowDialogQueue = new Queue<any>();
			this.mapWindowToDialogQueue.set(window.id, windowDialogQueue);
		}

		return windowDialogQueue;
	}

	public showMessageBox(options: Electron.MessageBoxOptions, window?: ICodeWindow): TPromise<IMessageBoxResult> {
		return this.getDialogQueue(window).queue(() => {
			return new TPromise((c, e) => {
				dialog.showMessageBox(window ? window.win : void 0, options, (response: number, checkboxChecked: boolean) => c({ button: response, checkboxChecked }));
			});
		});
	}

	public showSaveDialog(options: Electron.SaveDialogOptions, window?: ICodeWindow): TPromise<string> {
		function normalizePath(path: string): string {
			if (path && isMacintosh) {
				path = normalizeNFC(path); // normalize paths returned from the OS
1671
			}
1672

1673 1674
			return path;
		}
1675

1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689
		return this.getDialogQueue(window).queue(() => {
			return new TPromise((c, e) => {
				dialog.showSaveDialog(window ? window.win : void 0, options, path => c(normalizePath(path)));
			});
		});
	}

	public showOpenDialog(options: Electron.OpenDialogOptions, window?: ICodeWindow): TPromise<string[]> {
		function normalizePaths(paths: string[]): string[] {
			if (paths && paths.length > 0 && isMacintosh) {
				paths = paths.map(path => normalizeNFC(path)); // normalize paths returned from the OS
			}

			return paths;
1690
		}
B
Benjamin Pasero 已提交
1691

1692 1693 1694 1695 1696
		return this.getDialogQueue(window).queue(() => {
			return new TPromise((c, e) => {
				dialog.showOpenDialog(window ? window.win : void 0, options, paths => c(normalizePaths(paths)));
			});
		});
1697
	}
1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709
}

class WorkspacesManager {

	constructor(
		private workspacesService: IWorkspacesMainService,
		private backupService: IBackupMainService,
		private environmentService: IEnvironmentService,
		private windowsMainService: IWindowsMainService
	) {
	}

1710
	public saveAndEnterWorkspace(window: CodeWindow, path: string): TPromise<IEnterWorkspaceResult> {
1711 1712 1713 1714 1715 1716 1717
		if (!window || !window.win || window.readyState !== ReadyState.READY || !window.openedWorkspace || !path || !this.isValidTargetWorkspacePath(window, path)) {
			return TPromise.as(null); // return early if the window is not ready or disposed or does not have a workspace
		}

		return this.doSaveAndOpenWorkspace(window, window.openedWorkspace, path);
	}

1718
	public createAndEnterWorkspace(window: CodeWindow, folders?: IWorkspaceFolderCreationData[], path?: string): TPromise<IEnterWorkspaceResult> {
1719
		if (!window || !window.win || window.readyState !== ReadyState.READY) {
1720 1721 1722
			return TPromise.as(null); // return early if the window is not ready or disposed
		}

1723 1724 1725 1726 1727 1728 1729 1730
		return this.isValidTargetWorkspacePath(window, path).then(isValid => {
			if (!isValid) {
				return TPromise.as(null); // return early if the workspace is not valid
			}

			return this.workspacesService.createWorkspace(folders).then(workspace => {
				return this.doSaveAndOpenWorkspace(window, workspace, path);
			});
1731
		});
1732

1733 1734
	}

1735
	private isValidTargetWorkspacePath(window: CodeWindow, path?: string): TPromise<boolean> {
1736
		if (!path) {
1737
			return TPromise.wrap(true);
1738 1739 1740
		}

		if (window.openedWorkspace && window.openedWorkspace.configPath === path) {
1741
			return TPromise.wrap(false); // window is already opened on a workspace with that path
1742 1743 1744 1745 1746 1747 1748 1749 1750
		}

		// Prevent overwriting a workspace that is currently opened in another window
		if (findWindowOnWorkspace(this.windowsMainService.getWindows(), { id: this.workspacesService.getWorkspaceId(path), configPath: path })) {
			const options: Electron.MessageBoxOptions = {
				title: product.nameLong,
				type: 'info',
				buttons: [localize('ok', "OK")],
				message: localize('workspaceOpenedMessage', "Unable to save workspace '{0}'", basename(path)),
1751
				detail: localize('workspaceOpenedDetail', "The workspace is already opened in another window. Please close that window first and then try again."),
1752 1753 1754
				noLink: true
			};

1755
			return this.windowsMainService.showMessageBox(options, this.windowsMainService.getFocusedWindow()).then(() => false);
1756 1757
		}

1758
		return TPromise.wrap(true); // OK
1759 1760
	}

1761
	private doSaveAndOpenWorkspace(window: CodeWindow, workspace: IWorkspaceIdentifier, path?: string): TPromise<IEnterWorkspaceResult> {
1762 1763 1764 1765 1766 1767 1768 1769 1770 1771
		let savePromise: TPromise<IWorkspaceIdentifier>;
		if (path) {
			savePromise = this.workspacesService.saveWorkspace(workspace, path);
		} else {
			savePromise = TPromise.as(workspace);
		}

		return savePromise.then(workspace => {
			window.focus();

1772 1773 1774 1775 1776
			// Register window for backups and migrate current backups over
			let backupPath: string;
			if (!window.config.extensionDevelopmentPath) {
				backupPath = this.backupService.registerWorkspaceBackupSync(workspace, window.config.backupPath);
			}
1777

1778 1779 1780 1781
			// Update window configuration properly based on transition to workspace
			window.config.folderPath = void 0;
			window.config.workspace = workspace;
			window.config.backupPath = backupPath;
1782

1783
			return { workspace, backupPath };
1784 1785 1786
		});
	}

1787 1788
	public pickWorkspaceAndOpen(options: INativeOpenDialogOptions): void {
		const window = this.windowsMainService.getWindowById(options.windowId) || this.windowsMainService.getFocusedWindow() || this.windowsMainService.getLastActiveWindow();
1789 1790 1791 1792 1793 1794 1795 1796

		this.windowsMainService.pickFileAndOpen({
			windowId: window ? window.id : void 0,
			dialogOptions: {
				buttonLabel: mnemonicButtonLabel(localize({ key: 'openWorkspace', comment: ['&& denotes a mnemonic'] }, "&&Open")),
				title: localize('openWorkspaceTitle', "Open Workspace"),
				filters: WORKSPACE_FILTER,
				properties: ['openFile'],
1797
				defaultPath: options.dialogOptions && options.dialogOptions.defaultPath
1798
			},
1799 1800 1801
			forceNewWindow: options.forceNewWindow,
			telemetryEventName: options.telemetryEventName,
			telemetryExtraData: options.telemetryExtraData
1802 1803 1804
		});
	}

1805
	public promptToSaveUntitledWorkspace(window: ICodeWindow, workspace: IWorkspaceIdentifier): TPromise<boolean> {
1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838
		enum ConfirmResult {
			SAVE,
			DONT_SAVE,
			CANCEL
		}

		const save = { label: mnemonicButtonLabel(localize({ key: 'save', comment: ['&& denotes a mnemonic'] }, "&&Save")), result: ConfirmResult.SAVE };
		const dontSave = { label: mnemonicButtonLabel(localize({ key: 'doNotSave', comment: ['&& denotes a mnemonic'] }, "Do&&n't Save")), result: ConfirmResult.DONT_SAVE };
		const cancel = { label: localize('cancel', "Cancel"), result: ConfirmResult.CANCEL };

		const buttons: { label: string; result: ConfirmResult; }[] = [];
		if (isWindows) {
			buttons.push(save, dontSave, cancel);
		} else if (isLinux) {
			buttons.push(dontSave, cancel, save);
		} else {
			buttons.push(save, cancel, dontSave);
		}

		const options: Electron.MessageBoxOptions = {
			title: this.environmentService.appNameLong,
			message: localize('saveWorkspaceMessage', "Do you want to save your workspace configuration as a file?"),
			detail: localize('saveWorkspaceDetail', "Save your workspace if you plan to open it again."),
			noLink: true,
			type: 'warning',
			buttons: buttons.map(button => button.label),
			cancelId: buttons.indexOf(cancel)
		};

		if (isLinux) {
			options.defaultId = 2;
		}

1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861
		return this.windowsMainService.showMessageBox(options, window).then(res => {
			switch (buttons[res.button].result) {

				// Cancel: veto unload
				case ConfirmResult.CANCEL:
					return true;

				// Don't Save: delete workspace
				case ConfirmResult.DONT_SAVE:
					this.workspacesService.deleteUntitledWorkspaceSync(workspace);
					return false;

				// Save: save workspace, but do not veto unload
				case ConfirmResult.SAVE: {
					return this.windowsMainService.showSaveDialog({
						buttonLabel: mnemonicButtonLabel(localize({ key: 'save', comment: ['&& denotes a mnemonic'] }, "&&Save")),
						title: localize('saveWorkspace', "Save Workspace"),
						filters: WORKSPACE_FILTER,
						defaultPath: this.getUntitledWorkspaceSaveDialogDefaultPath(workspace)
					}, window).then(target => {
						if (target) {
							return this.workspacesService.saveWorkspace(workspace, target).then(() => false, () => false);
						}
1862

1863 1864
						return true; // keep veto if no target was provided
					});
1865 1866
				}
			}
1867
		});
1868 1869
	}

1870
	private getUntitledWorkspaceSaveDialogDefaultPath(workspace?: IWorkspaceIdentifier | ISingleFolderWorkspaceIdentifier): string {
1871 1872
		if (workspace) {
			if (isSingleFolderWorkspaceIdentifier(workspace)) {
J
Johannes Rieken 已提交
1873 1874 1875 1876 1877 1878 1879 1880 1881
				return dirname(workspace);
			}

			const resolvedWorkspace = this.workspacesService.resolveWorkspaceSync(workspace.configPath);
			if (resolvedWorkspace && resolvedWorkspace.folders.length > 0) {
				for (const folder of resolvedWorkspace.folders) {
					if (folder.uri.scheme === Schemas.file) {
						return dirname(folder.uri.fsPath);
					}
1882 1883 1884
				}
			}
		}
1885

J
Johannes Rieken 已提交
1886
		return void 0;
1887
	}
J
Johannes Rieken 已提交
1888
}