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

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

42 43 44
const enum WindowError {
	UNRESPONSIVE = 1,
	CRASHED = 2
E
Erich Gamma 已提交
45 46
}

47 48 49 50
interface INewWindowState extends ISingleWindowState {
	hasDefaultState?: boolean;
}

51
interface IWindowState {
52
	workspace?: IWorkspaceIdentifier;
53
	folderUri?: URI;
54
	backupPath: string;
M
Martin Aeschlimann 已提交
55
	remoteAuthority?: string;
J
Joao Moreno 已提交
56
	uiState: ISingleWindowState;
E
Erich Gamma 已提交
57 58
}

59 60 61 62
interface IBackwardCompatibleWindowState extends IWindowState {
	folderPath?: string;
}

E
Erich Gamma 已提交
63 64 65
interface IWindowsState {
	lastActiveWindow?: IWindowState;
	lastPluginDevelopmentHostWindow?: IWindowState;
66
	openedWindows: IWindowState[];
E
Erich Gamma 已提交
67 68
}

69
type RestoreWindowsSetting = 'all' | 'folders' | 'one' | 'none';
70

B
Benjamin Pasero 已提交
71 72 73
interface IOpenBrowserWindowOptions {
	userEnv?: IProcessEnvironment;
	cli?: ParsedArgs;
74

75
	workspace?: IWorkspaceIdentifier;
76
	folderUri?: URI;
B
Benjamin Pasero 已提交
77

M
Martin Aeschlimann 已提交
78 79
	remoteAuthority: string;

B
Benjamin Pasero 已提交
80 81
	initialStartup?: boolean;

82
	fileInputs?: IFileInputs;
B
Benjamin Pasero 已提交
83 84

	forceNewWindow?: boolean;
85
	forceNewTabbedWindow?: boolean;
86
	windowToUse?: ICodeWindow;
B
Benjamin Pasero 已提交
87

88 89 90 91 92 93 94
	emptyWindowBackupInfo?: IEmptyWindowBackupInfo;
}

interface IPathParseOptions {
	ignoreFileNotFound?: boolean;
	gotoLineMode?: boolean;
	forceOpenWorkspaceAsFile?: boolean;
M
Martin Aeschlimann 已提交
95
	remoteAuthority?: string;
96 97 98 99 100 101 102
}

interface IFileInputs {
	filesToOpen: IPath[];
	filesToCreate: IPath[];
	filesToDiff: IPath[];
	filesToWait?: IPathsToWaitFor;
M
Martin Aeschlimann 已提交
103
	remoteAuthority?: string;
B
Benjamin Pasero 已提交
104 105
}

B
Benjamin Pasero 已提交
106
interface IPathToOpen extends IPath {
107

108
	// the workspace for a Code instance to open
109
	workspace?: IWorkspaceIdentifier;
110

111
	// the folder path for a Code instance to open
112
	folderUri?: URI;
113

114
	// the backup path for a Code instance to use
115 116
	backupPath?: string;

M
Martin Aeschlimann 已提交
117 118 119
	// the remote authority for the Code instance to open. Undefined if not remote.
	remoteAuthority?: string;

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

J
Joao Moreno 已提交
124
export class WindowsManager implements IWindowsMainService {
J
Joao Moreno 已提交
125

126
	_serviceBrand: any;
E
Erich Gamma 已提交
127

128
	private static readonly windowsStateStorageKey = 'windowsState';
E
Erich Gamma 已提交
129

130
	private static WINDOWS: ICodeWindow[] = [];
E
Erich Gamma 已提交
131

B
Benjamin Pasero 已提交
132
	private initialUserEnv: IProcessEnvironment;
133

E
Erich Gamma 已提交
134
	private windowsState: IWindowsState;
135
	private lastClosedWindowState: IWindowState;
E
Erich Gamma 已提交
136

137
	private dialogs: Dialogs;
138
	private workspacesManager: WorkspacesManager;
B
Benjamin Pasero 已提交
139

140 141
	private _onWindowReady = new Emitter<ICodeWindow>();
	onWindowReady: CommonEvent<ICodeWindow> = this._onWindowReady.event;
142 143 144 145

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

146 147 148
	private _onWindowLoad = new Emitter<number>();
	onWindowLoad: CommonEvent<number> = this._onWindowLoad.event;

149 150
	private _onActiveWindowChanged = new Emitter<ICodeWindow>();
	onActiveWindowChanged: CommonEvent<ICodeWindow> = this._onActiveWindowChanged.event;
151

152 153 154
	private _onWindowReload = new Emitter<number>();
	onWindowReload: CommonEvent<number> = this._onWindowReload.event;

B
Benjamin Pasero 已提交
155 156 157
	private _onWindowsCountChanged = new Emitter<IWindowsCountChangedEvent>();
	onWindowsCountChanged: CommonEvent<IWindowsCountChangedEvent> = this._onWindowsCountChanged.event;

J
Joao Moreno 已提交
158
	constructor(
B
Benjamin Pasero 已提交
159
		private readonly machineId: string,
J
Joao Moreno 已提交
160
		@ILogService private logService: ILogService,
B
Benjamin Pasero 已提交
161
		@IStateService private stateService: IStateService,
162
		@IEnvironmentService private environmentService: IEnvironmentService,
B
Benjamin Pasero 已提交
163
		@ILifecycleService private lifecycleService: ILifecycleService,
B
Benjamin Pasero 已提交
164
		@IBackupMainService private backupMainService: IBackupMainService,
165
		@ITelemetryService private telemetryService: ITelemetryService,
166
		@IConfigurationService private configurationService: IConfigurationService,
B
Benjamin Pasero 已提交
167 168
		@IHistoryMainService private historyMainService: IHistoryMainService,
		@IWorkspacesMainService private workspacesMainService: IWorkspacesMainService,
169
		@IInstantiationService private instantiationService: IInstantiationService
170
	) {
171
		this.windowsState = this.getWindowsState();
172 173 174
		if (!Array.isArray(this.windowsState.openedWindows)) {
			this.windowsState.openedWindows = [];
		}
175

B
Benjamin Pasero 已提交
176
		this.dialogs = new Dialogs(environmentService, telemetryService, stateService, this);
B
Benjamin Pasero 已提交
177
		this.workspacesManager = new WorkspacesManager(workspacesMainService, backupMainService, environmentService, this);
178
	}
J
Joao Moreno 已提交
179

180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
	private getWindowsState(): IWindowsState {
		const windowsState = this.stateService.getItem<IWindowsState>(WindowsManager.windowsStateStorageKey) || { openedWindows: [] };
		if (windowsState.lastActiveWindow) {
			windowsState.lastActiveWindow = this.revive(windowsState.lastActiveWindow);
		}
		if (windowsState.lastPluginDevelopmentHostWindow) {
			windowsState.lastPluginDevelopmentHostWindow = this.revive(windowsState.lastPluginDevelopmentHostWindow);
		}
		if (windowsState.openedWindows) {
			windowsState.openedWindows = windowsState.openedWindows.map(windowState => this.revive(windowState));
		}
		return windowsState;
	}

	private revive(windowState: IWindowState): IWindowState {
		if (windowState.folderUri) {
			windowState.folderUri = URI.revive(windowState.folderUri);
		}
		if ((<IBackwardCompatibleWindowState>windowState).folderPath) {
			windowState.folderUri = URI.file((<IBackwardCompatibleWindowState>windowState).folderPath);
		}
		return windowState;
	}

B
Benjamin Pasero 已提交
204
	ready(initialUserEnv: IProcessEnvironment): void {
205
		this.initialUserEnv = initialUserEnv;
206 207

		this.registerListeners();
E
Erich Gamma 已提交
208 209 210
	}

	private registerListeners(): void {
211

212 213 214 215 216 217 218
		// React to windows focus changes
		app.on('browser-window-focus', () => {
			setTimeout(() => {
				this._onActiveWindowChanged.fire(this.getLastActiveWindow());
			});
		});

219
		// React to workbench loaded events from windows
220
		ipc.on('vscode:workbenchLoaded', (event: any, windowId: number) => {
J
Joao Moreno 已提交
221
			this.logService.trace('IPC#vscode-workbenchLoaded');
E
Erich Gamma 已提交
222

B
Benjamin Pasero 已提交
223
			const win = this.getWindowById(windowId);
E
Erich Gamma 已提交
224 225 226 227
			if (win) {
				win.setReady();

				// Event
228
				this._onWindowReady.fire(win);
E
Erich Gamma 已提交
229 230 231
			}
		});

232 233 234 235 236 237 238 239 240 241 242
		// 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');
				}
			});
		}

243 244
		// Handle various lifecycle events around windows
		this.lifecycleService.onBeforeWindowUnload(e => this.onBeforeWindowUnload(e));
245
		this.lifecycleService.onBeforeWindowClose(win => this.onBeforeWindowClose(win as ICodeWindow));
246
		this.lifecycleService.onBeforeShutdown(() => this.onBeforeShutdown());
247 248 249 250 251 252 253 254
		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;
			}
		});
255 256
	}

257
	// Note that onBeforeShutdown() and onBeforeWindowClose() are fired in different order depending on the OS:
258
	// - macOS: since the app will not quit when closing the last window, you will always first get
259
	//          the onBeforeShutdown() event followed by N onbeforeWindowClose() events for each window
260 261
	// - 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()
262
	//          and then onBeforeShutdown(). Using the quit action however will first issue onBeforeShutdown()
263
	//          and then onBeforeWindowClose().
264 265 266 267 268 269 270
	//
	// 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
271
	// - onBeforeShutdown(N): number of windows reported in this event handler
272 273 274
	// - onBeforeWindowClose(N, M): number of windows reported and quitRequested boolean in this event handler
	//
	// macOS
275 276 277
	// 	-     quit(1): onBeforeShutdown(1), onBeforeWindowClose(1, true)
	// 	-     quit(2): onBeforeShutdown(2), onBeforeWindowClose(2, true), onBeforeWindowClose(2, true)
	// 	-     quit(0): onBeforeShutdown(0)
278 279 280
	// 	-    close(1): onBeforeWindowClose(1, false)
	//
	// Windows
281 282
	// 	-     quit(1): onBeforeShutdown(1), onBeforeWindowClose(1, true)
	// 	-     quit(2): onBeforeShutdown(2), onBeforeWindowClose(2, true), onBeforeWindowClose(2, true)
283
	// 	-    close(1): onBeforeWindowClose(2, false)[not last window]
284 285
	// 	-    close(1): onBeforeWindowClose(1, false), onBeforeShutdown(0)[last window]
	// 	- closeAll(2): onBeforeWindowClose(2, false), onBeforeWindowClose(2, false), onBeforeShutdown(0)
286 287
	//
	// Linux
288 289
	// 	-     quit(1): onBeforeShutdown(1), onBeforeWindowClose(1, true)
	// 	-     quit(2): onBeforeShutdown(2), onBeforeWindowClose(2, true), onBeforeWindowClose(2, true)
290
	// 	-    close(1): onBeforeWindowClose(2, false)[not last window]
291 292
	// 	-    close(1): onBeforeWindowClose(1, false), onBeforeShutdown(0)[last window]
	// 	- closeAll(2): onBeforeWindowClose(2, false), onBeforeWindowClose(2, false), onBeforeShutdown(0)
293
	//
294
	private onBeforeShutdown(): void {
295
		const currentWindowsState: IWindowsState = {
296
			openedWindows: [],
297
			lastPluginDevelopmentHostWindow: this.windowsState.lastPluginDevelopmentHostWindow,
298
			lastActiveWindow: this.lastClosedWindowState
299 300 301 302 303 304 305 306
		};

		// 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 已提交
307

308
			if (activeWindow) {
309
				currentWindowsState.lastActiveWindow = this.toWindowState(activeWindow);
E
Erich Gamma 已提交
310
			}
311 312 313 314 315
		}

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

319
		// 3.) All windows (except extension host) for N >= 2 to support restoreWindows: all or for auto update
320 321 322 323 324
		//
		// 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) {
325
			currentWindowsState.openedWindows = WindowsManager.WINDOWS.filter(w => !w.isExtensionDevelopmentHost).map(w => this.toWindowState(w));
326
		}
E
Erich Gamma 已提交
327

328
		// Persist
B
Benjamin Pasero 已提交
329
		this.stateService.setItem(WindowsManager.windowsStateStorageKey, currentWindowsState);
330
	}
331

332
	// See note on #onBeforeShutdown() for details how these events are flowing
333
	private onBeforeWindowClose(win: ICodeWindow): void {
B
Benjamin Pasero 已提交
334
		if (this.lifecycleService.quitRequested) {
335 336 337 338
			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
339
		const state: IWindowState = this.toWindowState(win);
340 341 342 343
		if (win.isExtensionDevelopmentHost && !win.isExtensionTestHost) {
			this.windowsState.lastPluginDevelopmentHostWindow = state; // do not let test run window state overwrite our extension development state
		}

344
		// Any non extension host window with same workspace or folder
345
		else if (!win.isExtensionDevelopmentHost && (!!win.openedWorkspace || !!win.openedFolderUri)) {
346
			this.windowsState.openedWindows.forEach(o => {
B
fix npe  
Benjamin Pasero 已提交
347
				const sameWorkspace = win.openedWorkspace && o.workspace && o.workspace.id === win.openedWorkspace.id;
348
				const sameFolder = win.openedFolderUri && o.folderUri && isEqual(o.folderUri, win.openedFolderUri);
349 350

				if (sameWorkspace || sameFolder) {
351 352 353 354 355 356 357
					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.
358 359 360
		// 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) {
361 362
			this.lastClosedWindowState = state;
		}
E
Erich Gamma 已提交
363 364
	}

365
	private toWindowState(win: ICodeWindow): IWindowState {
366
		return {
367
			workspace: win.openedWorkspace,
368
			folderUri: win.openedFolderUri,
369
			backupPath: win.backupPath,
M
Martin Aeschlimann 已提交
370
			remoteAuthority: win.remoteAuthority,
371 372 373 374
			uiState: win.serializeWindowState()
		};
	}

B
Benjamin Pasero 已提交
375
	open(openConfig: IOpenConfiguration): ICodeWindow[] {
376
		this.logService.trace('windowsManager#open');
377
		openConfig = this.validateOpenConfig(openConfig);
378

379
		let pathsToOpen = this.getPathsToOpen(openConfig);
380 381 382

		// When run with --add, take the folders that are to be opened as
		// folders that should be added to the currently active window.
383
		let foldersToAdd: URI[] = [];
384
		if (openConfig.addMode) {
385 386
			foldersToAdd = pathsToOpen.filter(path => !!path.folderUri).map(path => path.folderUri);
			pathsToOpen = pathsToOpen.filter(path => !path.folderUri);
387
		}
E
Erich Gamma 已提交
388

389 390 391 392 393
		// collect all file inputs
		let fileInputs: IFileInputs = void 0;
		for (const path of pathsToOpen) {
			if (path.fileUri) {
				if (!fileInputs) {
M
Martin Aeschlimann 已提交
394
					fileInputs = { filesToCreate: [], filesToOpen: [], filesToDiff: [], remoteAuthority: path.remoteAuthority };
395 396 397 398 399 400 401 402
				}
				if (!path.createFilePath) {
					fileInputs.filesToOpen.push(path);
				} else {
					fileInputs.filesToCreate.push(path);
				}
			}
		}
403 404 405

		// When run with --diff, take the files to open as files to diff
		// if there are exactly two files provided.
406 407 408 409
		if (fileInputs && openConfig.diffMode && fileInputs.filesToOpen.length === 2) {
			fileInputs.filesToDiff = fileInputs.filesToOpen;
			fileInputs.filesToOpen = [];
			fileInputs.filesToCreate = []; // diff ignores other files that do not exist
E
Erich Gamma 已提交
410 411
		}

412
		// When run with --wait, make sure we keep the paths to wait for
413 414
		if (fileInputs && openConfig.cli.wait && openConfig.cli.waitMarkerFilePath) {
			fileInputs.filesToWait = { paths: [...fileInputs.filesToDiff, ...fileInputs.filesToOpen, ...fileInputs.filesToCreate], waitMarkerFilePath: openConfig.cli.waitMarkerFilePath };
415 416
		}

417 418 419
		//
		// These are windows to open to show workspaces
		//
B
Benjamin Pasero 已提交
420
		const workspacesToOpen = arrays.distinct(pathsToOpen.filter(win => !!win.workspace).map(win => win.workspace), workspace => workspace.id); // prevent duplicates
421 422 423 424

		//
		// These are windows to open to show either folders or files (including diffing files or creating them)
		//
425
		const foldersToOpen = arrays.distinct(pathsToOpen.filter(win => win.folderUri && !win.fileUri).map(win => win.folderUri), folder => getComparisonKey(folder)); // prevent duplicates
426

427
		//
428
		// These are windows to restore because of hot-exit or from previous session (only performed once on startup!)
429
		//
430
		let foldersToRestore: URI[] = [];
431
		let workspacesToRestore: IWorkspaceIdentifier[] = [];
432
		let emptyToRestore: IEmptyWindowBackupInfo[] = [];
B
Benjamin Pasero 已提交
433
		if (openConfig.initialStartup && !openConfig.cli.extensionDevelopmentPath && !openConfig.cli['disable-restore-windows']) {
434
			foldersToRestore = this.backupMainService.getFolderBackupPaths();
435

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

B
Benjamin Pasero 已提交
439
			emptyToRestore = this.backupMainService.getEmptyWindowBackupPaths();
M
Martin Aeschlimann 已提交
440
			emptyToRestore.push(...pathsToOpen.filter(w => !w.workspace && !w.folderUri && w.backupPath).map(w => ({ backupFolder: basename(w.backupPath), remoteAuthority: w.remoteAuthority }))); // add empty windows with backupPath
441
			emptyToRestore = arrays.distinct(emptyToRestore, info => info.backupFolder); // prevent duplicates
442
		}
443

444 445 446
		//
		// These are empty windows to open
		//
447
		const emptyToOpen = pathsToOpen.filter(win => !win.workspace && !win.folderUri && !win.fileUri && !win.backupPath).length;
448

449
		// Open based on config
450
		const usedWindows = this.doOpen(openConfig, workspacesToOpen, workspacesToRestore, foldersToOpen, foldersToRestore, emptyToRestore, emptyToOpen, fileInputs, foldersToAdd);
451

452
		// Make sure to pass focus to the most relevant of the windows if we open multiple
453
		if (usedWindows.length > 1) {
454

M
Martin Aeschlimann 已提交
455
			let focusLastActive = this.windowsState.lastActiveWindow && !openConfig.forceEmpty && !hasArgs(openConfig.cli._) && !hasArgs(openConfig.cli['file-uri']) && !hasArgs(openConfig.cli['folder-uri']) && !(openConfig.urisToOpen && openConfig.urisToOpen.length);
456 457
			let focusLastOpened = true;
			let focusLastWindow = true;
458

459 460
			// 1.) focus last active window if we are not instructed to open any paths
			if (focusLastActive) {
461 462 463
				const lastActiveWindw = usedWindows.filter(w => w.backupPath === this.windowsState.lastActiveWindow.backupPath);
				if (lastActiveWindw.length) {
					lastActiveWindw[0].focus();
464 465
					focusLastOpened = false;
					focusLastWindow = false;
466 467 468
				}
			}

469 470 471 472 473
			// 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 (
474 475 476
						(usedWindow.openedWorkspace && workspacesToRestore.some(workspace => workspace.id === usedWindow.openedWorkspace.id)) ||	// skip over restored workspace
						(usedWindow.openedFolderUri && foldersToRestore.some(folder => isEqual(folder, usedWindow.openedFolderUri))) ||				// skip over restored folder
						(usedWindow.backupPath && emptyToRestore.some(empty => empty.backupFolder === basename(usedWindow.backupPath)))				// skip over restored empty window
477 478 479 480 481 482 483 484 485 486 487 488
					) {
						continue;
					}

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

			// 3.) finally, always ensure to have at least last used window focused
			if (focusLastWindow) {
489
				usedWindows[usedWindows.length - 1].focus();
490 491
			}
		}
492

493 494 495
		// 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) {
496
			const recentlyOpenedWorkspaces: (IWorkspaceIdentifier | ISingleFolderWorkspaceIdentifier)[] = [];
497
			const recentlyOpenedFiles: URI[] = [];
498

B
Benjamin Pasero 已提交
499
			pathsToOpen.forEach(win => {
500 501
				if (win.workspace || win.folderUri) {
					recentlyOpenedWorkspaces.push(win.workspace || win.folderUri);
502 503
				} else if (win.fileUri) {
					recentlyOpenedFiles.push(win.fileUri);
504 505 506
				}
			});

507 508 509
			if (!this.environmentService.skipAddToRecentlyOpened) {
				this.historyMainService.addRecentlyOpened(recentlyOpenedWorkspaces, recentlyOpenedFiles);
			}
510
		}
511

512
		// If we got started with --wait from the CLI, we need to signal to the outside when the window
513 514
		// 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.
515
		if (openConfig.context === OpenContext.CLI && openConfig.cli.wait && openConfig.cli.waitMarkerFilePath && usedWindows.length === 1 && usedWindows[0]) {
516
			this.waitForWindowCloseOrLoad(usedWindows[0].id).then(() => fs.unlink(openConfig.cli.waitMarkerFilePath, error => void 0));
517 518
		}

519 520 521
		return usedWindows;
	}

522 523 524 525 526 527 528 529 530 531
	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;
	}

532 533
	private doOpen(
		openConfig: IOpenConfiguration,
534 535
		workspacesToOpen: IWorkspaceIdentifier[],
		workspacesToRestore: IWorkspaceIdentifier[],
536 537
		foldersToOpen: URI[],
		foldersToRestore: URI[],
538
		emptyToRestore: IEmptyWindowBackupInfo[],
539
		emptyToOpen: number,
540
		fileInputs: IFileInputs | undefined,
541
		foldersToAdd: URI[]
542
	) {
543
		const usedWindows: ICodeWindow[] = [];
544

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

548 549
		// Handle folders to add by looking for the last active workspace (not on initial startup)
		if (!openConfig.initialStartup && foldersToAdd.length > 0) {
M
Martin Aeschlimann 已提交
550 551
			const authority = getRemoteAuthority(foldersToAdd[0]);
			const lastActiveWindow = this.getLastActiveWindowForAuthority(authority);
552
			if (lastActiveWindow) {
553
				usedWindows.push(this.doAddFoldersToExistingWindow(lastActiveWindow, foldersToAdd));
554 555 556 557 558 559
			}

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

B
Benjamin Pasero 已提交
560
		// 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
561
		const potentialWindowsCount = foldersToOpen.length + foldersToRestore.length + workspacesToOpen.length + workspacesToRestore.length + emptyToRestore.length;
562
		if (potentialWindowsCount === 0 && fileInputs) {
E
Erich Gamma 已提交
563

564
			// Find suitable window or folder path to open files in
565
			const fileToCheck = fileInputs.filesToOpen[0] || fileInputs.filesToCreate[0] || fileInputs.filesToDiff[0];
M
Martin Aeschlimann 已提交
566 567
			// only look at the windows with correct authority
			const windows = WindowsManager.WINDOWS.filter(w => w.remoteAuthority === fileInputs.remoteAuthority);
568

569
			let bestWindowOrFolder = findBestWindowOrFolderForFile({
570
				windows,
571 572 573
				newWindow: openFilesInNewWindow,
				reuseWindow: openConfig.forceReuseWindow,
				context: openConfig.context,
574
				fileUri: fileToCheck && fileToCheck.fileUri,
B
Benjamin Pasero 已提交
575
				workspaceResolver: workspace => this.workspacesMainService.resolveWorkspaceSync(workspace.configPath)
576
			});
B
Benjamin Pasero 已提交
577

578 579 580 581 582 583 584 585 586
			// 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
587 588
				else if (bestWindowOrFolder.openedFolderUri) {
					foldersToOpen.push(bestWindowOrFolder.openedFolderUri);
589 590 591 592 593 594
				}

				// Window is empty
				else {

					// Do open files
595
					usedWindows.push(this.doOpenFilesInExistingWindow(openConfig, bestWindowOrFolder, fileInputs));
596 597

					// Reset these because we handled them
598
					fileInputs = void 0;
599
				}
600 601 602
			}

			// Finally, if no window or folder is found, just open the files in an empty window
E
Erich Gamma 已提交
603
			else {
B
Benjamin Pasero 已提交
604
				usedWindows.push(this.openInBrowserWindow({
B
Benjamin Pasero 已提交
605 606 607
					userEnv: openConfig.userEnv,
					cli: openConfig.cli,
					initialStartup: openConfig.initialStartup,
608
					fileInputs,
609
					forceNewWindow: true,
M
Martin Aeschlimann 已提交
610
					remoteAuthority: fileInputs.remoteAuthority,
611
					forceNewTabbedWindow: openConfig.forceNewTabbedWindow
B
Benjamin Pasero 已提交
612
				}));
E
Erich Gamma 已提交
613

614
				// Reset these because we handled them
615
				fileInputs = void 0;
E
Erich Gamma 已提交
616 617 618
			}
		}

619
		// Handle workspaces to open (instructed and to restore)
620
		const allWorkspacesToOpen = arrays.distinct([...workspacesToRestore, ...workspacesToOpen], workspace => workspace.id); // prevent duplicates
621 622 623 624 625 626
		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];
M
Martin Aeschlimann 已提交
627
				const fileInputsForWindow = (fileInputs && fileInputs.remoteAuthority === windowOnWorkspace.remoteAuthority) ? fileInputs : void 0;
628 629

				// Do open files
630
				usedWindows.push(this.doOpenFilesInExistingWindow(openConfig, windowOnWorkspace, fileInputsForWindow));
631 632

				// Reset these because we handled them
633 634 635
				if (fileInputsForWindow) {
					fileInputs = void 0;
				}
636 637 638 639 640 641

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

			// Open remaining ones
			allWorkspacesToOpen.forEach(workspaceToOpen => {
642
				if (windowsOnWorkspace.some(win => win.openedWorkspace.id === workspaceToOpen.id)) {
643 644 645
					return; // ignore folders that are already open
				}

M
Martin Aeschlimann 已提交
646
				const fileInputsForWindow = (fileInputs && !fileInputs.remoteAuthority) ? fileInputs : void 0;
647

648
				// Do open folder
649
				usedWindows.push(this.doOpenFolderOrWorkspace(openConfig, { workspace: workspaceToOpen }, openFolderInNewWindow, fileInputsForWindow));
650 651

				// Reset these because we handled them
652 653 654
				if (fileInputsForWindow) {
					fileInputs = void 0;
				}
655 656 657 658 659

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

660
		// Handle folders to open (instructed and to restore)
661 662
		const allFoldersToOpen = arrays.distinct([...foldersToRestore, ...foldersToOpen], folder => getComparisonKey(folder)); // prevent duplicates

663
		if (allFoldersToOpen.length > 0) {
E
Erich Gamma 已提交
664 665

			// Check for existing instances
666
			const windowsOnFolderPath = arrays.coalesce(allFoldersToOpen.map(folderToOpen => findWindowOnWorkspace(WindowsManager.WINDOWS, folderToOpen)));
667
			if (windowsOnFolderPath.length > 0) {
668
				const windowOnFolderPath = windowsOnFolderPath[0];
M
Martin Aeschlimann 已提交
669
				const fileInputsForWindow = fileInputs && fileInputs.remoteAuthority === windowOnFolderPath.remoteAuthority ? fileInputs : void 0;
E
Erich Gamma 已提交
670

671
				// Do open files
672
				usedWindows.push(this.doOpenFilesInExistingWindow(openConfig, windowOnFolderPath, fileInputsForWindow));
673

E
Erich Gamma 已提交
674
				// Reset these because we handled them
675 676 677
				if (fileInputsForWindow) {
					fileInputs = void 0;
				}
E
Erich Gamma 已提交
678

B
Benjamin Pasero 已提交
679
				openFolderInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
680 681 682
			}

			// Open remaining ones
683
			allFoldersToOpen.forEach(folderToOpen => {
684

685
				if (windowsOnFolderPath.some(win => isEqual(win.openedFolderUri, folderToOpen))) {
E
Erich Gamma 已提交
686 687 688
					return; // ignore folders that are already open
				}

M
Martin Aeschlimann 已提交
689 690
				const remoteAuthority = getRemoteAuthority(folderToOpen);
				const fileInputsForWindow = (fileInputs && fileInputs.remoteAuthority === remoteAuthority) ? fileInputs : void 0;
691

692
				// Do open folder
M
Martin Aeschlimann 已提交
693
				usedWindows.push(this.doOpenFolderOrWorkspace(openConfig, { folderUri: folderToOpen, remoteAuthority }, openFolderInNewWindow, fileInputsForWindow));
E
Erich Gamma 已提交
694 695

				// Reset these because we handled them
696 697 698
				if (fileInputsForWindow) {
					fileInputs = void 0;
				}
E
Erich Gamma 已提交
699

B
Benjamin Pasero 已提交
700
				openFolderInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
701 702 703
			});
		}

704
		// Handle empty to restore
705
		if (emptyToRestore.length > 0) {
706
			emptyToRestore.forEach(emptyWindowBackupInfo => {
M
Martin Aeschlimann 已提交
707 708
				const remoteAuthority = emptyWindowBackupInfo.remoteAuthority;
				const fileInputsForWindow = (fileInputs && fileInputs.remoteAuthority === remoteAuthority) ? fileInputs : void 0;
709

B
Benjamin Pasero 已提交
710
				usedWindows.push(this.openInBrowserWindow({
B
Benjamin Pasero 已提交
711 712 713
					userEnv: openConfig.userEnv,
					cli: openConfig.cli,
					initialStartup: openConfig.initialStartup,
714
					fileInputs: fileInputsForWindow,
M
Martin Aeschlimann 已提交
715
					remoteAuthority,
B
Benjamin Pasero 已提交
716
					forceNewWindow: true,
717
					forceNewTabbedWindow: openConfig.forceNewTabbedWindow,
718
					emptyWindowBackupInfo
B
Benjamin Pasero 已提交
719
				}));
720

B
wip  
Benjamin Pasero 已提交
721
				// Reset these because we handled them
722 723 724
				if (fileInputsForWindow) {
					fileInputs = void 0;
				}
B
wip  
Benjamin Pasero 已提交
725

B
Benjamin Pasero 已提交
726
				openFolderInNewWindow = true; // any other folders to open must open in new window then
727 728
			});
		}
B
Benjamin Pasero 已提交
729

730
		// Handle empty to open (only if no other window opened)
731 732 733 734
		if (usedWindows.length === 0 || fileInputs) {
			if (fileInputs && !emptyToOpen) {
				emptyToOpen++;
			}
M
Martin Aeschlimann 已提交
735
			const remoteAuthority = fileInputs ? fileInputs.remoteAuthority : (openConfig.cli && openConfig.cli.remote || void 0);
736
			for (let i = 0; i < emptyToOpen; i++) {
B
Benjamin Pasero 已提交
737
				usedWindows.push(this.openInBrowserWindow({
B
Benjamin Pasero 已提交
738 739 740
					userEnv: openConfig.userEnv,
					cli: openConfig.cli,
					initialStartup: openConfig.initialStartup,
M
Martin Aeschlimann 已提交
741
					remoteAuthority,
742
					forceNewWindow: openFolderInNewWindow,
743 744
					forceNewTabbedWindow: openConfig.forceNewTabbedWindow,
					fileInputs
B
Benjamin Pasero 已提交
745
				}));
E
Erich Gamma 已提交
746

747 748
				// Reset these because we handled them
				fileInputs = void 0;
749
				openFolderInNewWindow = true; // any other window to open must open in new window then
750 751
			}
		}
E
Erich Gamma 已提交
752

753
		return arrays.distinct(usedWindows);
E
Erich Gamma 已提交
754 755
	}

756
	private doOpenFilesInExistingWindow(configuration: IOpenConfiguration, window: ICodeWindow, fileInputs?: IFileInputs): ICodeWindow {
757 758
		window.focus(); // make sure window has focus

B
Benjamin Pasero 已提交
759 760 761 762 763 764 765 766 767 768 769 770 771
		const params: { filesToOpen?, filesToCreate?, filesToDiff?, filesToWait?, termProgram?} = {};
		if (fileInputs) {
			params.filesToOpen = fileInputs.filesToOpen;
			params.filesToCreate = fileInputs.filesToCreate;
			params.filesToDiff = fileInputs.filesToDiff;
			params.filesToWait = fileInputs.filesToWait;
		}

		if (configuration.userEnv) {
			params.termProgram = configuration.userEnv['TERM_PROGRAM'];
		}

		window.sendWhenReady('vscode:openFiles', params);
B
Benjamin Pasero 已提交
772 773

		return window;
774 775
	}

776
	private doAddFoldersToExistingWindow(window: ICodeWindow, foldersToAdd: URI[]): ICodeWindow {
777 778
		window.focus(); // make sure window has focus

B
Benjamin Pasero 已提交
779
		window.sendWhenReady('vscode:addFolders', { foldersToAdd });
780 781 782 783

		return window;
	}

784
	private doOpenFolderOrWorkspace(openConfig: IOpenConfiguration, folderOrWorkspace: IPathToOpen, forceNewWindow: boolean, fileInputs: IFileInputs, windowToUse?: ICodeWindow): ICodeWindow {
B
Benjamin Pasero 已提交
785 786 787 788
		if (!forceNewWindow && !windowToUse && typeof openConfig.contextWindowId === 'number') {
			windowToUse = this.getWindowById(openConfig.contextWindowId); // fix for https://github.com/Microsoft/vscode/issues/49587
		}

789 790 791 792
		const browserWindow = this.openInBrowserWindow({
			userEnv: openConfig.userEnv,
			cli: openConfig.cli,
			initialStartup: openConfig.initialStartup,
793
			workspace: folderOrWorkspace.workspace,
794
			folderUri: folderOrWorkspace.folderUri,
795
			fileInputs,
M
Martin Aeschlimann 已提交
796
			remoteAuthority: folderOrWorkspace.remoteAuthority,
B
Benjamin Pasero 已提交
797
			forceNewWindow,
798
			forceNewTabbedWindow: openConfig.forceNewTabbedWindow,
799
			windowToUse
800 801 802 803 804
		});

		return browserWindow;
	}

B
Benjamin Pasero 已提交
805 806
	private getPathsToOpen(openConfig: IOpenConfiguration): IPathToOpen[] {
		let windowsToOpen: IPathToOpen[];
807
		let isCommandLineOrAPICall = false;
E
Erich Gamma 已提交
808

809
		// Extract paths: from API
S
Sandeep Somavarapu 已提交
810
		if (openConfig.urisToOpen && openConfig.urisToOpen.length > 0) {
811
			windowsToOpen = this.doExtractPathsFromAPI(openConfig);
812
			isCommandLineOrAPICall = true;
E
Erich Gamma 已提交
813 814
		}

B
Benjamin Pasero 已提交
815 816
		// Check for force empty
		else if (openConfig.forceEmpty) {
817
			windowsToOpen = [Object.create(null)];
E
Erich Gamma 已提交
818 819
		}

820
		// Extract paths: from CLI
M
Martin Aeschlimann 已提交
821
		else if (hasArgs(openConfig.cli._) || hasArgs(openConfig.cli['folder-uri']) || hasArgs(openConfig.cli['file-uri'])) {
822
			windowsToOpen = this.doExtractPathsFromCLI(openConfig.cli);
823
			isCommandLineOrAPICall = true;
B
Benjamin Pasero 已提交
824 825
		}

826
		// Extract windows: from previous session
B
Benjamin Pasero 已提交
827
		else {
828
			windowsToOpen = this.doGetWindowsFromLastSession();
B
Benjamin Pasero 已提交
829 830
		}

831 832
		// Convert multiple folders into workspace (if opened via API or CLI)
		// This will ensure to open these folders in one window instead of multiple
833 834
		// If we are in addMode, we should not do this because in that case all
		// folders should be added to the existing window.
835
		if (!openConfig.addMode && isCommandLineOrAPICall) {
836
			const foldersToOpen = windowsToOpen.filter(path => !!path.folderUri);
837
			if (foldersToOpen.length > 1) {
838
				const workspace = this.workspacesMainService.createWorkspaceSync(foldersToOpen.map(folder => ({ uri: folder.folderUri })));
839 840

				// Add workspace and remove folders thereby
M
Martin Aeschlimann 已提交
841
				windowsToOpen.push({ workspace, remoteAuthority: foldersToOpen[0].remoteAuthority });
842
				windowsToOpen = windowsToOpen.filter(path => !path.folderUri);
843 844 845
			}
		}

846
		return windowsToOpen;
E
Erich Gamma 已提交
847 848
	}

849
	private doExtractPathsFromAPI(openConfig: IOpenConfiguration): IPathToOpen[] {
M
Matt Bierner 已提交
850
		const pathsToOpen: IPathToOpen[] = [];
851 852
		const cli = openConfig.cli;
		let parseOptions: IPathParseOptions = { gotoLineMode: cli && cli.goto, forceOpenWorkspaceAsFile: openConfig.forceOpenWorkspaceAsFile };
M
Martin Aeschlimann 已提交
853 854 855 856 857 858 859 860 861
		for (const pathToOpen of openConfig.urisToOpen) {
			if (!pathToOpen) {
				continue;
			}

			const path = this.parseUri(pathToOpen, openConfig.forceOpenWorkspaceAsFile, parseOptions);
			if (path) {
				pathsToOpen.push(path);
			} else {
862

B
Benjamin Pasero 已提交
863
				// Warn about the invalid URI or path
M
Martin Aeschlimann 已提交
864 865 866 867 868 869 870 871
				let message, detail;
				if (pathToOpen.scheme === Schemas.file) {
					message = localize('pathNotExistTitle', "Path does not exist");
					detail = localize('pathNotExistDetail', "The path '{0}' does not seem to exist anymore on disk.", pathToOpen.fsPath);
				} else {
					message = localize('uriInvalidTitle', "URI can not be opened");
					detail = localize('uriInvalidDetail', "The URI '{0}' is not valid and can not be opened.", pathToOpen.toString());
				}
872
				const options: Electron.MessageBoxOptions = {
873 874
					title: product.nameLong,
					type: 'info',
875
					buttons: [localize('ok', "OK")],
M
Martin Aeschlimann 已提交
876 877
					message,
					detail,
878 879 880
					noLink: true
				};

881
				this.dialogs.showMessageBox(options, this.getFocusedWindow());
882
			}
M
Martin Aeschlimann 已提交
883
		}
884 885 886 887
		return pathsToOpen;
	}

	private doExtractPathsFromCLI(cli: ParsedArgs): IPath[] {
M
Matt Bierner 已提交
888
		const pathsToOpen: IPathToOpen[] = [];
M
Martin Aeschlimann 已提交
889
		const parseOptions: IPathParseOptions = { ignoreFileNotFound: true, gotoLineMode: cli.goto, remoteAuthority: cli.remote || void 0 };
890 891

		// folder uris
892
		const folderUris = asArray(cli['folder-uri']);
M
Martin Aeschlimann 已提交
893 894 895 896 897
		for (let folderUri of folderUris) {
			const path = this.parseUri(this.argToUri(folderUri), false, parseOptions);
			if (path) {
				pathsToOpen.push(path);
			}
898 899 900 901
		}

		// file uris
		const fileUris = asArray(cli['file-uri']);
M
Martin Aeschlimann 已提交
902 903 904 905 906
		for (let fileUri of fileUris) {
			const path = this.parseUri(this.argToUri(fileUri), true, parseOptions);
			if (path) {
				pathsToOpen.push(path);
			}
907 908 909
		}

		// folder or file paths
M
Martin Aeschlimann 已提交
910 911 912 913 914 915
		const cliArgs = asArray(cli._);
		for (let cliArg of cliArgs) {
			const path = this.parsePath(cliArg, parseOptions);
			if (path) {
				pathsToOpen.push(path);
			}
916 917
		}

M
Martin Aeschlimann 已提交
918
		if (pathsToOpen.length) {
919
			return pathsToOpen;
B
Benjamin Pasero 已提交
920 921 922 923 924 925
		}

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

B
Benjamin Pasero 已提交
926
	private doGetWindowsFromLastSession(): IPathToOpen[] {
927
		const restoreWindows = this.getRestoreWindowsSetting();
B
Benjamin Pasero 已提交
928

929
		switch (restoreWindows) {
B
Benjamin Pasero 已提交
930

931
			// none: we always open an empty window
932 933
			case 'none':
				return [Object.create(null)];
B
Benjamin Pasero 已提交
934

935
			// one: restore last opened workspace/folder or empty window
936 937
			// all: restore all windows
			// folders: restore last opened folders only
938
			case 'one':
939 940
			case 'all':
			case 'folders':
941 942 943
				const openedWindows: IWindowState[] = [];
				if (restoreWindows !== 'one') {
					openedWindows.push(...this.windowsState.openedWindows);
944
				}
945 946
				if (this.windowsState.lastActiveWindow) {
					openedWindows.push(this.windowsState.lastActiveWindow);
947
				}
948

949 950 951
				const windowsToOpen: IPathToOpen[] = [];
				for (const openedWindow of openedWindows) {
					if (openedWindow.workspace) { // Workspaces
M
Martin Aeschlimann 已提交
952
						const pathToOpen = this.parsePath(openedWindow.workspace.configPath, { remoteAuthority: openedWindow.remoteAuthority });
953 954 955 956
						if (pathToOpen && pathToOpen.workspace) {
							windowsToOpen.push(pathToOpen);
						}
					} else if (openedWindow.folderUri) { // Folders
M
Martin Aeschlimann 已提交
957
						const pathToOpen = this.parseUri(openedWindow.folderUri, false, { remoteAuthority: openedWindow.remoteAuthority });
958 959 960 961
						if (pathToOpen && pathToOpen.folderUri) {
							windowsToOpen.push(pathToOpen);
						}
					} else if (restoreWindows !== 'folders' && openedWindow.backupPath) { // Windows that were Empty
M
Martin Aeschlimann 已提交
962
						windowsToOpen.push({ backupPath: openedWindow.backupPath, remoteAuthority: openedWindow.remoteAuthority });
963
					}
964 965 966 967 968 969 970
				}

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

				break;
B
Benjamin Pasero 已提交
971
		}
E
Erich Gamma 已提交
972

973
		// Always fallback to empty window
B
Benjamin Pasero 已提交
974
		return [Object.create(null)];
E
Erich Gamma 已提交
975 976
	}

977 978 979 980 981
	private getRestoreWindowsSetting(): RestoreWindowsSetting {
		let restoreWindows: RestoreWindowsSetting;
		if (this.lifecycleService.wasRestarted) {
			restoreWindows = 'all'; // always reopen all windows when an update was applied
		} else {
982
			const windowConfig = this.configurationService.getValue<IWindowSettings>('window');
983
			restoreWindows = ((windowConfig && windowConfig.restoreWindows) || 'one') as RestoreWindowsSetting;
984 985 986 987 988 989 990 991 992

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

		return restoreWindows;
	}

M
Martin Aeschlimann 已提交
993 994 995 996
	private argToUri(arg: string): URI {
		try {
			let uri = URI.parse(arg);
			if (!uri.scheme) {
M
Martin Aeschlimann 已提交
997
				this.logService.error(`Invalid URI input string, scheme missing: ${arg}`);
M
Martin Aeschlimann 已提交
998 999 1000 1001
				return null;
			}
			return uri;
		} catch (e) {
M
Martin Aeschlimann 已提交
1002
			this.logService.error(`Invalid URI input string: ${arg}, ${e.message}`);
1003
		}
M
Martin Aeschlimann 已提交
1004
		return null;
1005 1006
	}

1007
	private parseUri(uri: URI, isFile: boolean, options?: IPathParseOptions): IPathToOpen {
M
Martin Aeschlimann 已提交
1008
		if (!uri || !uri.scheme) {
1009 1010
			return null;
		}
M
Martin Aeschlimann 已提交
1011 1012
		if (uri.scheme === Schemas.file) {
			return this.parsePath(uri.fsPath, options);
1013
		}
M
Martin Aeschlimann 已提交
1014 1015 1016 1017

		// open remote if either specified in the cli or if it's a remotehost URI
		const remoteAuthority = options && options.remoteAuthority || getRemoteAuthority(uri);

1018 1019 1020 1021 1022
		// normalize URI
		uri = normalizePath(uri);
		if (endsWith(uri.path, '/')) {
			uri = uri.with({ path: uri.path.substr(0, uri.path.length - 1) });
		}
1023
		if (isFile) {
1024 1025 1026 1027 1028
			if (options && options.gotoLineMode) {
				const parsedPath = parseLineAndColumnAware(uri.path);
				return {
					fileUri: uri.with({ path: parsedPath.path }),
					lineNumber: parsedPath.line,
M
Martin Aeschlimann 已提交
1029 1030
					columnNumber: parsedPath.column,
					remoteAuthority
1031 1032
				};
			}
1033
			return {
M
Martin Aeschlimann 已提交
1034 1035
				fileUri: uri,
				remoteAuthority
1036 1037
			};
		}
1038
		return {
M
Martin Aeschlimann 已提交
1039 1040
			folderUri: uri,
			remoteAuthority
1041 1042 1043
		};
	}

1044
	private parsePath(anyPath: string, options?: IPathParseOptions): IPathToOpen {
E
Erich Gamma 已提交
1045 1046 1047 1048
		if (!anyPath) {
			return null;
		}

1049
		let parsedPath: IPathWithLineAndColumn;
1050 1051 1052

		const gotoLineMode = options && options.gotoLineMode;
		if (options && options.gotoLineMode) {
J
Joao Moreno 已提交
1053
			parsedPath = parseLineAndColumnAware(anyPath);
E
Erich Gamma 已提交
1054 1055 1056
			anyPath = parsedPath.path;
		}

M
Martin Aeschlimann 已提交
1057 1058 1059
		// open remote if either specified in the cli even if it is a local file. TODO: Future idea: resolve in remote host context.
		const remoteAuthority = options && options.remoteAuthority;

1060
		const candidate = normalize(anyPath);
E
Erich Gamma 已提交
1061
		try {
B
Benjamin Pasero 已提交
1062
			const candidateStat = fs.statSync(candidate);
E
Erich Gamma 已提交
1063
			if (candidateStat) {
1064
				if (candidateStat.isFile()) {
1065

1066 1067
					// Workspace (unless disabled via flag)
					if (!options || !options.forceOpenWorkspaceAsFile) {
B
Benjamin Pasero 已提交
1068
						const workspace = this.workspacesMainService.resolveWorkspaceSync(candidate);
1069
						if (workspace) {
M
Martin Aeschlimann 已提交
1070
							return { workspace: { id: workspace.id, configPath: workspace.configPath }, remoteAuthority };
1071
						}
1072 1073 1074
					}

					// File
1075
					return {
1076
						fileUri: URI.file(candidate),
E
Erich Gamma 已提交
1077
						lineNumber: gotoLineMode ? parsedPath.line : void 0,
M
Martin Aeschlimann 已提交
1078 1079
						columnNumber: gotoLineMode ? parsedPath.column : void 0,
						remoteAuthority
1080 1081 1082
					};
				}

1083 1084 1085 1086 1087
				// Folder (we check for isDirectory() because e.g. paths like /dev/null
				// are neither file nor folder but some external tools might pass them
				// over to us)
				else if (candidateStat.isDirectory()) {
					return {
M
Martin Aeschlimann 已提交
1088 1089
						folderUri: URI.file(candidate),
						remoteAuthority
1090 1091
					};
				}
E
Erich Gamma 已提交
1092 1093
			}
		} catch (error) {
1094 1095
			const fileUri = URI.file(candidate);
			this.historyMainService.removeFromRecentlyOpened([fileUri]); // since file does not seem to exist anymore, remove from recent
1096

1097
			if (options && options.ignoreFileNotFound) {
M
Martin Aeschlimann 已提交
1098
				return { fileUri, createFilePath: true, remoteAuthority }; // assume this is a file that does not yet exist
E
Erich Gamma 已提交
1099 1100 1101 1102 1103 1104
			}
		}

		return null;
	}

B
Benjamin Pasero 已提交
1105 1106 1107
	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
1108
		const windowConfig = this.configurationService.getValue<IWindowSettings>('window');
1109 1110 1111
		const openFolderInNewWindowConfig = (windowConfig && windowConfig.openFoldersInNewWindow) || 'default' /* default */;
		const openFilesInNewWindowConfig = (windowConfig && windowConfig.openFilesInNewWindow) || 'off' /* default */;

B
Benjamin Pasero 已提交
1112
		let openFolderInNewWindow = (openConfig.preferNewWindow || openConfig.forceNewWindow) && !openConfig.forceReuseWindow;
1113 1114
		if (!openConfig.forceNewWindow && !openConfig.forceReuseWindow && (openFolderInNewWindowConfig === 'on' || openFolderInNewWindowConfig === 'off')) {
			openFolderInNewWindow = (openFolderInNewWindowConfig === 'on');
B
Benjamin Pasero 已提交
1115 1116 1117 1118 1119 1120 1121
		}

		// 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 {
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134

			// macOS: by default we open files in a new window if this is triggered via DOCK context
			if (isMacintosh) {
				if (openConfig.context === OpenContext.DOCK) {
					openFilesInNewWindow = true;
				}
			}

			// Linux/Windows: by default we open files in the new window unless triggered via DIALOG or MENU context
			else {
				if (openConfig.context !== OpenContext.DIALOG && openConfig.context !== OpenContext.MENU) {
					openFilesInNewWindow = true;
				}
B
Benjamin Pasero 已提交
1135 1136
			}

1137
			// finally check for overrides of default
1138 1139
			if (!openConfig.cli.extensionDevelopmentPath && (openFilesInNewWindowConfig === 'on' || openFilesInNewWindowConfig === 'off')) {
				openFilesInNewWindow = (openFilesInNewWindowConfig === 'on');
B
Benjamin Pasero 已提交
1140 1141 1142 1143 1144 1145
			}
		}

		return { openFolderInNewWindow, openFilesInNewWindow };
	}

B
Benjamin Pasero 已提交
1146
	openExtensionDevelopmentHostWindow(openConfig: IOpenConfiguration): void {
E
Erich Gamma 已提交
1147

B
Benjamin Pasero 已提交
1148 1149 1150
		// 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.
1151 1152 1153 1154
		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 已提交
1155

B
Benjamin Pasero 已提交
1156 1157
			return;
		}
1158 1159 1160
		let folderUris = asArray(openConfig.cli['folder-uri']);
		let fileUris = asArray(openConfig.cli['file-uri']);
		let cliArgs = openConfig.cli._;
E
Erich Gamma 已提交
1161

1162
		// Fill in previously opened workspace unless an explicit path is provided and we are not unit testing
1163
		if (!cliArgs.length && !folderUris.length && !fileUris.length && !openConfig.cli.extensionTestsPath) {
1164
			const extensionDevelopmentWindowState = this.windowsState.lastPluginDevelopmentHostWindow;
1165
			const workspaceToOpen = extensionDevelopmentWindowState && (extensionDevelopmentWindowState.workspace || extensionDevelopmentWindowState.folderUri);
1166
			if (workspaceToOpen) {
1167
				if (isSingleFolderWorkspaceIdentifier(workspaceToOpen)) {
1168
					if (workspaceToOpen.scheme === Schemas.file) {
1169
						cliArgs = [workspaceToOpen.fsPath];
1170
					} else {
1171
						folderUris = [workspaceToOpen.toString()];
1172 1173
					}
				} else {
1174
					cliArgs = [workspaceToOpen.configPath];
1175
				}
E
Erich Gamma 已提交
1176 1177 1178
			}
		}

1179
		// Make sure we are not asked to open a workspace or folder that is already opened
1180 1181
		if (cliArgs.length && cliArgs.some(path => !!findWindowOnWorkspaceOrFolderUri(WindowsManager.WINDOWS, URI.file(path)))) {
			cliArgs = [];
E
Erich Gamma 已提交
1182
		}
1183

M
Martin Aeschlimann 已提交
1184
		if (folderUris.length && folderUris.some(uri => !!findWindowOnWorkspaceOrFolderUri(WindowsManager.WINDOWS, this.argToUri(uri)))) {
1185 1186 1187
			folderUris = [];
		}

M
Martin Aeschlimann 已提交
1188
		if (fileUris.length && fileUris.some(uri => !!findWindowOnWorkspaceOrFolderUri(WindowsManager.WINDOWS, this.argToUri(uri)))) {
1189
			fileUris = [];
1190
		}
E
Erich Gamma 已提交
1191

1192 1193 1194 1195
		openConfig.cli._ = cliArgs;
		openConfig.cli['folder-uri'] = folderUris;
		openConfig.cli['file-uri'] = fileUris;

B
Benjamin Pasero 已提交
1196
		// Open it
1197
		this.open({ context: openConfig.context, cli: openConfig.cli, forceNewWindow: true, forceEmpty: !cliArgs.length && !folderUris.length && !fileUris.length, userEnv: openConfig.userEnv });
E
Erich Gamma 已提交
1198 1199
	}

1200
	private openInBrowserWindow(options: IOpenBrowserWindowOptions): ICodeWindow {
1201

B
Benjamin Pasero 已提交
1202 1203 1204
		// Build IWindowConfiguration from config and options
		const configuration: IWindowConfiguration = mixin({}, options.cli); // inherit all properties from CLI
		configuration.appRoot = this.environmentService.appRoot;
1205
		configuration.machineId = this.machineId;
1206
		configuration.nodeCachedDataDir = this.environmentService.nodeCachedDataDir;
1207
		configuration.mainPid = process.pid;
B
Benjamin Pasero 已提交
1208 1209 1210
		configuration.execPath = process.execPath;
		configuration.userEnv = assign({}, this.initialUserEnv, options.userEnv || {});
		configuration.isInitialStartup = options.initialStartup;
1211
		configuration.workspace = options.workspace;
1212
		configuration.folderUri = options.folderUri;
M
Martin Aeschlimann 已提交
1213
		configuration.remoteAuthority = options.remoteAuthority;
1214 1215 1216 1217 1218 1219 1220 1221

		const fileInputs = options.fileInputs;
		if (fileInputs) {
			configuration.filesToOpen = fileInputs.filesToOpen;
			configuration.filesToCreate = fileInputs.filesToCreate;
			configuration.filesToDiff = fileInputs.filesToDiff;
			configuration.filesToWait = fileInputs.filesToWait;
		}
B
Benjamin Pasero 已提交
1222

1223
		// if we know the backup folder upfront (for empty windows to restore), we can set it
1224
		// directly here which helps for restoring UI state associated with that window.
B
Benjamin Pasero 已提交
1225
		// For all other cases we first call into registerEmptyWindowBackupSync() to set it before
1226
		// loading the window.
1227 1228
		if (options.emptyWindowBackupInfo) {
			configuration.backupPath = join(this.environmentService.backupHome, options.emptyWindowBackupInfo.backupFolder);
1229 1230
		}

1231
		let window: ICodeWindow;
1232
		if (!options.forceNewWindow && !options.forceNewTabbedWindow) {
1233 1234 1235
			window = options.windowToUse || this.getLastActiveWindow();
			if (window) {
				window.focus();
E
Erich Gamma 已提交
1236 1237 1238 1239
			}
		}

		// New window
1240
		if (!window) {
1241
			const windowConfig = this.configurationService.getValue<IWindowSettings>('window');
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
			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 {
1252
				allowFullscreen = this.lifecycleService.wasRestarted || (windowConfig && windowConfig.restoreFullscreen);
1253 1254 1255 1256 1257
			}

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

1259
			// Create the window
1260
			window = this.instantiationService.createInstance(CodeWindow, {
1261
				state,
1262
				extensionDevelopmentPath: configuration.extensionDevelopmentPath,
1263
				isExtensionTestHost: !!configuration.extensionTestsPath
1264
			});
1265

1266 1267 1268 1269 1270 1271 1272 1273
			// Add as window tab if configured (macOS only)
			if (options.forceNewTabbedWindow) {
				const activeWindow = this.getLastActiveWindow();
				if (activeWindow) {
					activeWindow.addTabbedWindow(window);
				}
			}

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

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

E
Erich Gamma 已提交
1280
			// Window Events
1281 1282 1283 1284 1285
			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 已提交
1286 1287

			// Lifecycle
B
Benjamin Pasero 已提交
1288
			(this.lifecycleService as LifecycleService).registerWindow(window);
E
Erich Gamma 已提交
1289 1290 1291 1292 1293 1294
		}

		// Existing window
		else {

			// Some configuration things get inherited if the window is being reused and we are
B
Benjamin Pasero 已提交
1295
			// in extension development host mode. These options are all development related.
1296
			const currentWindowConfig = window.config;
A
Alex Dima 已提交
1297 1298
			if (!configuration.extensionDevelopmentPath && currentWindowConfig && !!currentWindowConfig.extensionDevelopmentPath) {
				configuration.extensionDevelopmentPath = currentWindowConfig.extensionDevelopmentPath;
B
Benjamin Pasero 已提交
1299
				configuration.verbose = currentWindowConfig.verbose;
1300
				configuration.debugBrkPluginHost = currentWindowConfig.debugBrkPluginHost;
1301
				configuration.debugId = currentWindowConfig.debugId;
1302
				configuration.debugPluginHost = currentWindowConfig.debugPluginHost;
1303
				configuration['extensions-dir'] = currentWindowConfig['extensions-dir'];
E
Erich Gamma 已提交
1304 1305 1306
			}
		}

1307 1308 1309 1310 1311 1312 1313
		// If the window was already loaded, make sure to unload it
		// first and only load the new configuration if that was
		// not vetoed
		if (window.isReady) {
			this.lifecycleService.unload(window, UnloadReason.LOAD).then(veto => {
				if (!veto) {
					this.doOpenInBrowserWindow(window, configuration, options);
B
Benjamin Pasero 已提交
1314
				}
1315 1316 1317 1318 1319 1320 1321
			});
		} else {
			this.doOpenInBrowserWindow(window, configuration, options);
		}

		return window;
	}
B
Benjamin Pasero 已提交
1322

1323
	private doOpenInBrowserWindow(window: ICodeWindow, configuration: IWindowConfiguration, options: IOpenBrowserWindowOptions): void {
1324

1325 1326 1327 1328 1329 1330 1331 1332 1333
		// Register window for backups
		if (!configuration.extensionDevelopmentPath) {
			if (configuration.workspace) {
				configuration.backupPath = this.backupMainService.registerWorkspaceBackupSync(configuration.workspace);
			} else if (configuration.folderUri) {
				configuration.backupPath = this.backupMainService.registerFolderBackupSync(configuration.folderUri);
			} else {
				const backupFolder = options.emptyWindowBackupInfo && options.emptyWindowBackupInfo.backupFolder;
				configuration.backupPath = this.backupMainService.registerEmptyWindowBackupSync({ backupFolder, remoteAuthority: configuration.remoteAuthority });
E
Erich Gamma 已提交
1334
			}
1335
		}
1336

1337 1338 1339 1340 1341
		// Load it
		window.load(configuration);

		// Signal event
		this._onWindowLoad.fire(window.id);
E
Erich Gamma 已提交
1342 1343
	}

1344
	private getNewWindowState(configuration: IWindowConfiguration): INewWindowState {
1345
		const lastActive = this.getLastActiveWindow();
E
Erich Gamma 已提交
1346

1347 1348
		// Restore state unless we are running extension tests
		if (!configuration.extensionTestsPath) {
E
Erich Gamma 已提交
1349

1350 1351 1352
			// extension development host Window - load from stored settings if any
			if (!!configuration.extensionDevelopmentPath && this.windowsState.lastPluginDevelopmentHostWindow) {
				return this.windowsState.lastPluginDevelopmentHostWindow.uiState;
1353 1354
			}

1355 1356 1357 1358 1359 1360 1361 1362 1363
			// 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
1364
			if (configuration.folderUri) {
1365
				const stateForFolder = this.windowsState.openedWindows.filter(o => o.folderUri && isEqual(o.folderUri, configuration.folderUri)).map(o => o.uiState);
1366 1367 1368
				if (stateForFolder.length) {
					return stateForFolder[0];
				}
1369 1370
			}

1371 1372 1373 1374 1375 1376
			// 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 已提交
1377 1378
			}

1379 1380 1381 1382 1383
			// First Window
			const lastActiveState = this.lastClosedWindowState || this.windowsState.lastActiveWindow;
			if (!lastActive && lastActiveState) {
				return lastActiveState.uiState;
			}
E
Erich Gamma 已提交
1384 1385 1386 1387 1388 1389 1390
		}

		//
		// 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
1391
		let displayToUse: Electron.Display;
B
Benjamin Pasero 已提交
1392
		const displays = screen.getAllDisplays();
E
Erich Gamma 已提交
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402

		// 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 已提交
1403
			if (isMacintosh) {
B
Benjamin Pasero 已提交
1404
				const cursorPoint = screen.getCursorScreenPoint();
E
Erich Gamma 已提交
1405 1406 1407 1408 1409 1410 1411 1412
				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());
			}

1413
			// fallback to primary display or first display
E
Erich Gamma 已提交
1414
			if (!displayToUse) {
1415
				displayToUse = screen.getPrimaryDisplay() || displays[0];
E
Erich Gamma 已提交
1416 1417 1418
			}
		}

1419 1420 1421
		// Compute x/y based on display bounds
		// Note: important to use Math.round() because Electron does not seem to be too happy about
		// display coordinates that are not absolute numbers.
1422
		let state = defaultWindowState() as INewWindowState;
1423 1424
		state.x = Math.round(displayToUse.bounds.x + (displayToUse.bounds.width / 2) - (state.width / 2));
		state.y = Math.round(displayToUse.bounds.y + (displayToUse.bounds.height / 2) - (state.height / 2));
E
Erich Gamma 已提交
1425

1426
		// Check for newWindowDimensions setting and adjust accordingly
1427
		const windowConfig = this.configurationService.getValue<IWindowSettings>('window');
1428 1429 1430 1431 1432 1433 1434 1435 1436
		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 已提交
1437 1438 1439 1440 1441 1442 1443
				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;
				}

1444 1445 1446 1447 1448 1449 1450 1451
				ensureNoOverlap = false;
			}
		}

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

1452 1453
		state.hasDefaultState = true; // flag as default state

1454
		return state;
E
Erich Gamma 已提交
1455 1456
	}

J
Joao Moreno 已提交
1457
	private ensureNoOverlap(state: ISingleWindowState): ISingleWindowState {
E
Erich Gamma 已提交
1458 1459 1460 1461
		if (WindowsManager.WINDOWS.length === 0) {
			return state;
		}

1462 1463
		const existingWindowBounds = WindowsManager.WINDOWS.map(win => win.getBounds());
		while (existingWindowBounds.some(b => b.x === state.x || b.y === state.y)) {
E
Erich Gamma 已提交
1464 1465 1466 1467 1468 1469 1470
			state.x += 30;
			state.y += 30;
		}

		return state;
	}

B
Benjamin Pasero 已提交
1471
	reload(win: ICodeWindow, cli?: ParsedArgs): void {
B
Benjamin Pasero 已提交
1472 1473

		// Only reload when the window has not vetoed this
1474
		this.lifecycleService.unload(win, UnloadReason.RELOAD).then(veto => {
B
Benjamin Pasero 已提交
1475
			if (!veto) {
1476
				win.reload(void 0, cli);
B
Benjamin Pasero 已提交
1477 1478 1479 1480 1481 1482 1483

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

B
Benjamin Pasero 已提交
1484
	closeWorkspace(win: ICodeWindow): void {
1485 1486
		this.openInBrowserWindow({
			cli: this.environmentService.args,
M
Martin Aeschlimann 已提交
1487 1488
			windowToUse: win,
			remoteAuthority: win.remoteAuthority
1489 1490 1491
		});
	}

B
Benjamin Pasero 已提交
1492
	saveAndEnterWorkspace(win: ICodeWindow, path: string): TPromise<IEnterWorkspaceResult> {
1493
		return this.workspacesManager.saveAndEnterWorkspace(win, path).then(result => this.doEnterWorkspace(win, result));
1494
	}
1495

1496 1497 1498 1499
	enterWorkspace(win: ICodeWindow, path: string): TPromise<IEnterWorkspaceResult> {
		return this.workspacesManager.enterWorkspace(win, path).then(result => this.doEnterWorkspace(win, result));
	}

B
Benjamin Pasero 已提交
1500
	createAndEnterWorkspace(win: ICodeWindow, folders?: IWorkspaceFolderCreationData[], path?: string): TPromise<IEnterWorkspaceResult> {
1501
		return this.workspacesManager.createAndEnterWorkspace(win, folders, path).then(result => this.doEnterWorkspace(win, result));
1502
	}
1503

1504
	private doEnterWorkspace(win: ICodeWindow, result: IEnterWorkspaceResult): IEnterWorkspaceResult {
1505

1506
		// Mark as recently opened
B
Benjamin Pasero 已提交
1507
		this.historyMainService.addRecentlyOpened([result.workspace], []);
1508

1509 1510 1511
		// Trigger Eevent to indicate load of workspace into window
		this._onWindowReady.fire(win);

1512
		return result;
1513 1514
	}

B
Benjamin Pasero 已提交
1515
	pickWorkspaceAndOpen(options: INativeOpenDialogOptions): void {
1516
		this.workspacesManager.pickWorkspaceAndOpen(options);
1517 1518 1519
	}

	private onBeforeWindowUnload(e: IWindowUnloadEvent): void {
1520 1521
		const windowClosing = (e.reason === UnloadReason.CLOSE);
		const windowLoading = (e.reason === UnloadReason.LOAD);
1522 1523 1524 1525 1526
		if (!windowClosing && !windowLoading) {
			return; // only interested when window is closing or loading
		}

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

1531
		if (e.window.config && !!e.window.config.extensionDevelopmentPath) {
1532 1533 1534 1535
			// do not ask to save workspace when doing extension development
			// but still delete it.
			this.workspacesMainService.deleteUntitledWorkspaceSync(workspace);
			return;
1536 1537
		}

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

1542
		// Handle untitled workspaces with prompt as needed
B
Benjamin Pasero 已提交
1543 1544 1545 1546 1547 1548 1549 1550 1551
		e.veto(this.workspacesManager.promptToSaveUntitledWorkspace(this.getWindowById(e.window.id), workspace).then(veto => {
			if (veto) {
				return veto;
			}

			// Bug in electron: somehow we need this timeout so that the window closes properly. That
			// might be related to the fact that the untitled workspace prompt shows up async and this
			// code can execute before the dialog is fully closed which then blocks the window from closing.
			// Issue: https://github.com/Microsoft/vscode/issues/41989
1552
			return timeout(0).then(() => veto);
B
Benjamin Pasero 已提交
1553
		}));
1554 1555
	}

B
Benjamin Pasero 已提交
1556
	focusLastActive(cli: ParsedArgs, context: OpenContext): ICodeWindow {
B
Benjamin Pasero 已提交
1557
		const lastActive = this.getLastActiveWindow();
E
Erich Gamma 已提交
1558
		if (lastActive) {
B
Benjamin Pasero 已提交
1559
			lastActive.focus();
1560 1561

			return lastActive;
E
Erich Gamma 已提交
1562 1563
		}

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

B
Benjamin Pasero 已提交
1568
	getLastActiveWindow(): ICodeWindow {
1569
		return getLastActiveWindow(WindowsManager.WINDOWS);
E
Erich Gamma 已提交
1570 1571
	}

M
Martin Aeschlimann 已提交
1572 1573 1574 1575
	getLastActiveWindowForAuthority(remoteAuthority: string): ICodeWindow {
		return getLastActiveWindow(WindowsManager.WINDOWS.filter(w => w.remoteAuthority === remoteAuthority));
	}

1576 1577
	openNewWindow(context: OpenContext, options?: INewWindowOptions): ICodeWindow[] {
		let cli = this.environmentService.args;
M
Martin Aeschlimann 已提交
1578 1579 1580 1581
		let remote = options && options.remoteAuthority || void 0;
		if (cli && (cli.remote !== remote)) {
			cli = { ...cli, remote };
		}
1582
		return this.open({ context, cli, forceNewWindow: true, forceEmpty: true });
E
Erich Gamma 已提交
1583 1584
	}

1585 1586 1587 1588
	openNewTabbedWindow(context: OpenContext): ICodeWindow[] {
		return this.open({ context, cli: this.environmentService.args, forceNewTabbedWindow: true, forceEmpty: true });
	}

B
Benjamin Pasero 已提交
1589 1590
	waitForWindowCloseOrLoad(windowId: number): Thenable<void> {
		return new Promise<void>(resolve => {
1591
			function handler(id: number) {
1592
				if (id === windowId) {
1593 1594 1595
					closeListener.dispose();
					loadListener.dispose();

B
Benjamin Pasero 已提交
1596
					resolve(null);
1597
				}
1598 1599 1600 1601
			}

			const closeListener = this.onWindowClose(id => handler(id));
			const loadListener = this.onWindowLoad(id => handler(id));
1602 1603 1604
		});
	}

B
Benjamin Pasero 已提交
1605
	sendToFocused(channel: string, ...args: any[]): void {
E
Erich Gamma 已提交
1606 1607 1608
		const focusedWindow = this.getFocusedWindow() || this.getLastActiveWindow();

		if (focusedWindow) {
1609
			focusedWindow.sendWhenReady(channel, ...args);
E
Erich Gamma 已提交
1610 1611 1612
		}
	}

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

1619
			w.sendWhenReady(channel, payload);
E
Erich Gamma 已提交
1620 1621 1622
		});
	}

B
Benjamin Pasero 已提交
1623
	getFocusedWindow(): ICodeWindow {
B
Benjamin Pasero 已提交
1624
		const win = BrowserWindow.getFocusedWindow();
E
Erich Gamma 已提交
1625 1626 1627 1628 1629 1630 1631
		if (win) {
			return this.getWindowById(win.id);
		}

		return null;
	}

B
Benjamin Pasero 已提交
1632
	getWindowById(windowId: number): ICodeWindow {
1633
		const res = WindowsManager.WINDOWS.filter(w => w.id === windowId);
E
Erich Gamma 已提交
1634 1635 1636 1637 1638 1639 1640
		if (res && res.length === 1) {
			return res[0];
		}

		return null;
	}

B
Benjamin Pasero 已提交
1641
	getWindows(): ICodeWindow[] {
E
Erich Gamma 已提交
1642 1643 1644
		return WindowsManager.WINDOWS;
	}

B
Benjamin Pasero 已提交
1645
	getWindowCount(): number {
E
Erich Gamma 已提交
1646 1647 1648
		return WindowsManager.WINDOWS.length;
	}

1649
	private onWindowError(window: ICodeWindow, error: WindowError): void {
B
Benjamin Pasero 已提交
1650
		this.logService.error(error === WindowError.CRASHED ? '[VS Code]: render process crashed!' : '[VS Code]: detected unresponsive');
E
Erich Gamma 已提交
1651

1652 1653 1654 1655 1656 1657 1658
		/* __GDPR__
			"windowerror" : {
				"type" : { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth", "isMeasurement": true },
			}
		*/
		this.telemetryService.publicLog('windowerror', { type: error });

E
Erich Gamma 已提交
1659 1660
		// Unresponsive
		if (error === WindowError.UNRESPONSIVE) {
1661
			this.dialogs.showMessageBox({
B
Benjamin Pasero 已提交
1662
				title: product.nameLong,
E
Erich Gamma 已提交
1663
				type: 'warning',
1664
				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"))],
1665 1666
				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 已提交
1667
				noLink: true
1668 1669 1670 1671
			}, window).then(result => {
				if (!window.win) {
					return; // Return early if the window has been going down already
				}
1672

1673 1674 1675 1676 1677 1678 1679
				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 已提交
1680 1681 1682 1683
		}

		// Crashed
		else {
1684
			this.dialogs.showMessageBox({
B
Benjamin Pasero 已提交
1685
				title: product.nameLong,
E
Erich Gamma 已提交
1686
				type: 'warning',
1687
				buttons: [mnemonicButtonLabel(localize({ key: 'reopen', comment: ['&& denotes a mnemonic'] }, "&&Reopen")), mnemonicButtonLabel(localize({ key: 'close', comment: ['&& denotes a mnemonic'] }, "&&Close"))],
1688 1689
				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 已提交
1690
				noLink: true
1691 1692 1693 1694
			}, window).then(result => {
				if (!window.win) {
					return; // Return early if the window has been going down already
				}
1695

1696 1697 1698 1699 1700 1701 1702
				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 已提交
1703 1704 1705
		}
	}

1706
	private onWindowClosed(win: ICodeWindow): void {
E
Erich Gamma 已提交
1707 1708 1709 1710 1711

		// Tell window
		win.dispose();

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

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

B
Benjamin Pasero 已提交
1720
	pickFileFolderAndOpen(options: INativeOpenDialogOptions): void {
B
Benjamin Pasero 已提交
1721
		this.doPickAndOpen(options, true /* pick folders */, true /* pick files */);
1722 1723
	}

B
Benjamin Pasero 已提交
1724
	pickFolderAndOpen(options: INativeOpenDialogOptions): void {
B
Benjamin Pasero 已提交
1725
		this.doPickAndOpen(options, true /* pick folders */, false /* pick files */);
1726 1727
	}

B
Benjamin Pasero 已提交
1728
	pickFileAndOpen(options: INativeOpenDialogOptions): void {
B
Benjamin Pasero 已提交
1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753
		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) {
K
kieferrm 已提交
1754
				// __GDPR__TODO__ classify event
B
Benjamin Pasero 已提交
1755 1756 1757 1758 1759 1760 1761 1762
				internalOptions.telemetryEventName = 'openFileFolder';
			} else if (pickFolders) {
				internalOptions.telemetryEventName = 'openFolder';
			} else {
				internalOptions.telemetryEventName = 'openFile';
			}
		}

1763 1764 1765
		this.dialogs.pickAndOpen(internalOptions);
	}

B
Benjamin Pasero 已提交
1766
	showMessageBox(options: Electron.MessageBoxOptions, win?: ICodeWindow): Thenable<IMessageBoxResult> {
1767 1768 1769
		return this.dialogs.showMessageBox(options, win);
	}

B
Benjamin Pasero 已提交
1770
	showSaveDialog(options: Electron.SaveDialogOptions, win?: ICodeWindow): Thenable<string> {
1771 1772 1773
		return this.dialogs.showSaveDialog(options, win);
	}

B
Benjamin Pasero 已提交
1774
	showOpenDialog(options: Electron.OpenDialogOptions, win?: ICodeWindow): Thenable<string[]> {
1775
		return this.dialogs.showOpenDialog(options, win);
B
Benjamin Pasero 已提交
1776 1777
	}

B
Benjamin Pasero 已提交
1778
	quit(): void {
B
Benjamin Pasero 已提交
1779 1780 1781

		// 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.
1782 1783 1784
		const window = this.getFocusedWindow();
		if (window && window.isExtensionDevelopmentHost && this.getWindowCount() > 1) {
			window.win.close();
B
Benjamin Pasero 已提交
1785 1786 1787 1788 1789 1790 1791 1792
		}

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

B
Benjamin Pasero 已提交
1796
interface IInternalNativeOpenDialogOptions extends INativeOpenDialogOptions {
B
Benjamin Pasero 已提交
1797 1798 1799 1800
	pickFolders?: boolean;
	pickFiles?: boolean;
}

1801
class Dialogs {
B
Benjamin Pasero 已提交
1802

1803
	private static readonly workingDirPickerStorageKey = 'pickerWorkingDir';
1804

1805 1806 1807
	private mapWindowToDialogQueue: Map<number, Queue<any>>;
	private noWindowDialogQueue: Queue<any>;

B
Benjamin Pasero 已提交
1808 1809 1810
	constructor(
		private environmentService: IEnvironmentService,
		private telemetryService: ITelemetryService,
B
Benjamin Pasero 已提交
1811
		private stateService: IStateService,
B
Benjamin Pasero 已提交
1812
		private windowsMainService: IWindowsMainService,
B
Benjamin Pasero 已提交
1813
	) {
1814 1815
		this.mapWindowToDialogQueue = new Map<number, Queue<any>>();
		this.noWindowDialogQueue = new Queue<any>();
B
Benjamin Pasero 已提交
1816 1817
	}

B
Benjamin Pasero 已提交
1818
	pickAndOpen(options: INativeOpenDialogOptions): void {
1819
		this.getFileOrFolderUris(options).then(paths => {
B
Benjamin Pasero 已提交
1820 1821 1822 1823
			const numberOfPaths = paths ? paths.length : 0;

			// Telemetry
			if (options.telemetryEventName) {
K
kieferrm 已提交
1824
				// __GDPR__TODO__ Dynamic event names and dynamic properties. Can not be registered statically.
B
Benjamin Pasero 已提交
1825 1826 1827 1828 1829 1830 1831 1832 1833
				this.telemetryService.publicLog(options.telemetryEventName, {
					...options.telemetryExtraData,
					outcome: numberOfPaths ? 'success' : 'canceled',
					numberOfPaths
				});
			}

			// Open
			if (numberOfPaths) {
1834 1835 1836
				this.windowsMainService.open({
					context: OpenContext.DIALOG,
					cli: this.environmentService.args,
S
Sandeep Somavarapu 已提交
1837
					urisToOpen: paths,
1838 1839 1840
					forceNewWindow: options.forceNewWindow,
					forceOpenWorkspaceAsFile: options.dialogOptions && !equals(options.dialogOptions.filters, WORKSPACE_FILTER)
				});
1841 1842 1843 1844
			}
		});
	}

1845
	private getFileOrFolderUris(options: IInternalNativeOpenDialogOptions): TPromise<URI[]> {
1846

B
Benjamin Pasero 已提交
1847 1848 1849 1850 1851 1852 1853
		// Ensure dialog options
		if (!options.dialogOptions) {
			options.dialogOptions = Object.create(null);
		}

		// Ensure defaultPath
		if (!options.dialogOptions.defaultPath) {
1854
			options.dialogOptions.defaultPath = this.stateService.getItem<string>(Dialogs.workingDirPickerStorageKey);
1855 1856
		}

B
Benjamin Pasero 已提交
1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869
		// 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'];
		}

1870 1871 1872 1873
		if (isMacintosh) {
			options.dialogOptions.properties.push('treatPackageAsDirectory'); // always drill into .app files
		}

B
Benjamin Pasero 已提交
1874
		// Show Dialog
1875
		const focusedWindow = this.windowsMainService.getWindowById(options.windowId) || this.windowsMainService.getFocusedWindow();
1876 1877 1878 1879 1880 1881 1882

		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]));

1883
				return paths.map(path => URI.file(path));
1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903
			}

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

B
Benjamin Pasero 已提交
1904
	showMessageBox(options: Electron.MessageBoxOptions, window?: ICodeWindow): Thenable<IMessageBoxResult> {
1905
		return this.getDialogQueue(window).queue(() => {
B
Benjamin Pasero 已提交
1906
			return new Promise(resolve => {
B
Benjamin Pasero 已提交
1907
				dialog.showMessageBox(window ? window.win : void 0, options, (response: number, checkboxChecked: boolean) => {
B
Benjamin Pasero 已提交
1908
					resolve({ button: response, checkboxChecked });
B
Benjamin Pasero 已提交
1909
				});
1910 1911 1912 1913
			});
		});
	}

B
Benjamin Pasero 已提交
1914
	showSaveDialog(options: Electron.SaveDialogOptions, window?: ICodeWindow): Thenable<string> {
B
Benjamin Pasero 已提交
1915

1916 1917 1918
		function normalizePath(path: string): string {
			if (path && isMacintosh) {
				path = normalizeNFC(path); // normalize paths returned from the OS
1919
			}
1920

1921 1922
			return path;
		}
1923

1924
		return this.getDialogQueue(window).queue(() => {
B
Benjamin Pasero 已提交
1925
			return new Promise(resolve => {
B
Benjamin Pasero 已提交
1926
				dialog.showSaveDialog(window ? window.win : void 0, options, path => {
B
Benjamin Pasero 已提交
1927
					resolve(normalizePath(path));
B
Benjamin Pasero 已提交
1928
				});
1929 1930 1931 1932
			});
		});
	}

B
Benjamin Pasero 已提交
1933
	showOpenDialog(options: Electron.OpenDialogOptions, window?: ICodeWindow): Thenable<string[]> {
B
Benjamin Pasero 已提交
1934

1935 1936 1937 1938 1939 1940
		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;
1941
		}
B
Benjamin Pasero 已提交
1942

1943
		return this.getDialogQueue(window).queue(() => {
B
Benjamin Pasero 已提交
1944
			return new Promise(resolve => {
B
Benjamin Pasero 已提交
1945 1946

				// Ensure the path exists (if provided)
B
Benjamin Pasero 已提交
1947
				let validatePathPromise: Promise<void> = Promise.resolve();
B
Benjamin Pasero 已提交
1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958
				if (options.defaultPath) {
					validatePathPromise = exists(options.defaultPath).then(exists => {
						if (!exists) {
							options.defaultPath = void 0;
						}
					});
				}

				// Show dialog and wrap as promise
				validatePathPromise.then(() => {
					dialog.showOpenDialog(window ? window.win : void 0, options, paths => {
B
Benjamin Pasero 已提交
1959
						resolve(normalizePaths(paths));
B
Benjamin Pasero 已提交
1960
					});
B
Benjamin Pasero 已提交
1961
				});
1962 1963
			});
		});
1964
	}
1965 1966 1967 1968 1969
}

class WorkspacesManager {

	constructor(
1970 1971
		private workspacesMainService: IWorkspacesMainService,
		private backupMainService: IBackupMainService,
1972 1973 1974 1975 1976
		private environmentService: IEnvironmentService,
		private windowsMainService: IWindowsMainService
	) {
	}

B
Benjamin Pasero 已提交
1977
	saveAndEnterWorkspace(window: ICodeWindow, path: string): TPromise<IEnterWorkspaceResult> {
B
Benjamin Pasero 已提交
1978
		if (!window || !window.win || !window.isReady || !window.openedWorkspace || !path || !this.isValidTargetWorkspacePath(window, path)) {
1979 1980 1981 1982 1983 1984
			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);
	}

1985
	enterWorkspace(window: ICodeWindow, path: string): TPromise<IEnterWorkspaceResult> {
B
Benjamin Pasero 已提交
1986
		if (!window || !window.win || !window.isReady) {
1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001
			return TPromise.as(null); // return early if the window is not ready or disposed
		}

		return this.isValidTargetWorkspacePath(window, path).then(isValid => {
			if (!isValid) {
				return TPromise.as<IEnterWorkspaceResult>(null); // return early if the workspace is not valid
			}

			return this.workspacesMainService.resolveWorkspace(path).then(workspace => {
				return this.doOpenWorkspace(window, workspace);
			});
		});

	}

B
Benjamin Pasero 已提交
2002
	createAndEnterWorkspace(window: ICodeWindow, folders?: IWorkspaceFolderCreationData[], path?: string): TPromise<IEnterWorkspaceResult> {
B
Benjamin Pasero 已提交
2003
		if (!window || !window.win || !window.isReady) {
2004 2005 2006
			return TPromise.as(null); // return early if the window is not ready or disposed
		}

2007 2008 2009 2010 2011
		return this.isValidTargetWorkspacePath(window, path).then(isValid => {
			if (!isValid) {
				return TPromise.as(null); // return early if the workspace is not valid
			}

2012
			return this.workspacesMainService.createWorkspace(folders).then(workspace => {
2013 2014
				return this.doSaveAndOpenWorkspace(window, workspace, path);
			});
2015
		});
2016

2017 2018
	}

2019
	private isValidTargetWorkspacePath(window: ICodeWindow, path?: string): TPromise<boolean> {
2020
		if (!path) {
2021
			return TPromise.wrap(true);
2022 2023 2024
		}

		if (window.openedWorkspace && window.openedWorkspace.configPath === path) {
2025
			return TPromise.wrap(false); // window is already opened on a workspace with that path
2026 2027 2028
		}

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

2039
			return this.windowsMainService.showMessageBox(options, this.windowsMainService.getFocusedWindow()).then(() => false);
2040 2041
		}

2042
		return TPromise.wrap(true); // OK
2043 2044
	}

2045
	private doSaveAndOpenWorkspace(window: ICodeWindow, workspace: IWorkspaceIdentifier, path?: string): TPromise<IEnterWorkspaceResult> {
2046 2047
		let savePromise: TPromise<IWorkspaceIdentifier>;
		if (path) {
2048
			savePromise = this.workspacesMainService.saveWorkspace(workspace, path);
2049 2050 2051 2052
		} else {
			savePromise = TPromise.as(workspace);
		}

2053 2054
		return savePromise.then(workspace => this.doOpenWorkspace(window, workspace));
	}
2055

2056 2057
	private doOpenWorkspace(window: ICodeWindow, workspace: IWorkspaceIdentifier): IEnterWorkspaceResult {
		window.focus();
2058

2059 2060 2061 2062 2063
		// Register window for backups and migrate current backups over
		let backupPath: string;
		if (!window.config.extensionDevelopmentPath) {
			backupPath = this.backupMainService.registerWorkspaceBackupSync(workspace, window.config.backupPath);
		}
2064

2065
		// Update window configuration properly based on transition to workspace
2066
		window.config.folderUri = void 0;
2067 2068 2069 2070
		window.config.workspace = workspace;
		window.config.backupPath = backupPath;

		return { workspace, backupPath };
2071 2072
	}

B
Benjamin Pasero 已提交
2073
	pickWorkspaceAndOpen(options: INativeOpenDialogOptions): void {
2074
		const window = this.windowsMainService.getWindowById(options.windowId) || this.windowsMainService.getFocusedWindow() || this.windowsMainService.getLastActiveWindow();
2075 2076 2077 2078 2079 2080 2081 2082

		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'],
2083
				defaultPath: options.dialogOptions && options.dialogOptions.defaultPath
2084
			},
2085 2086 2087
			forceNewWindow: options.forceNewWindow,
			telemetryEventName: options.telemetryEventName,
			telemetryExtraData: options.telemetryExtraData
2088 2089 2090
		});
	}

B
Benjamin Pasero 已提交
2091
	promptToSaveUntitledWorkspace(window: ICodeWindow, workspace: IWorkspaceIdentifier): TPromise<boolean> {
2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124
		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;
		}

2125 2126 2127 2128 2129 2130 2131 2132 2133
		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:
2134
					this.workspacesMainService.deleteUntitledWorkspaceSync(workspace);
2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145
					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) {
2146
							return this.workspacesMainService.saveWorkspace(workspace, target).then(() => false, () => false);
2147
						}
2148

2149 2150
						return true; // keep veto if no target was provided
					});
2151 2152
				}
			}
2153
		});
2154 2155
	}

2156
	private getUntitledWorkspaceSaveDialogDefaultPath(workspace?: IWorkspaceIdentifier | ISingleFolderWorkspaceIdentifier): string {
2157
		if (workspace) {
2158
			if (isSingleFolderWorkspaceIdentifier(workspace)) {
2159
				return workspace.scheme === Schemas.file ? dirname(workspace.fsPath) : void 0;
J
Johannes Rieken 已提交
2160 2161
			}

2162
			const resolvedWorkspace = this.workspacesMainService.resolveWorkspaceSync(workspace.configPath);
J
Johannes Rieken 已提交
2163 2164 2165 2166 2167
			if (resolvedWorkspace && resolvedWorkspace.folders.length > 0) {
				for (const folder of resolvedWorkspace.folders) {
					if (folder.uri.scheme === Schemas.file) {
						return dirname(folder.uri.fsPath);
					}
2168 2169 2170
				}
			}
		}
2171

J
Johannes Rieken 已提交
2172
		return void 0;
2173
	}
J
Johannes Rieken 已提交
2174
}