windows.ts 81.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';
B
Benjamin Pasero 已提交
16
import { ipcMain as ipc, screen, BrowserWindow, dialog, systemPreferences } 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 { IWorkspacesMainService, IWorkspaceIdentifier, WORKSPACE_FILTER, ISingleFolderWorkspaceIdentifier, isSingleFolderWorkspaceIdentifier } from 'vs/platform/workspaces/common/workspaces';
B
Benjamin Pasero 已提交
30
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
31
import { mnemonicButtonLabel } from 'vs/base/common/labels';
J
Johannes Rieken 已提交
32
import { Schemas } from 'vs/base/common/network';
33
import { normalizeNFC } from 'vs/base/common/normalization';
34
import { URI, UriComponents } from 'vs/base/common/uri';
35
import { Queue, timeout } from 'vs/base/common/async';
B
Benjamin Pasero 已提交
36
import { exists } from 'vs/base/node/pfs';
M
Martin Aeschlimann 已提交
37
import { getComparisonKey, isEqual, normalizePath, basename as resourcesBasename, fsPath } from 'vs/base/common/resources';
38
import { endsWith } from 'vs/base/common/strings';
M
Martin Aeschlimann 已提交
39
import { getRemoteAuthority } from 'vs/platform/remote/common/remoteHosts';
E
Erich Gamma 已提交
40

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

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

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

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

64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
interface ISerializedWindowsState {
	lastActiveWindow?: ISerializedWindowState;
	lastPluginDevelopmentHostWindow?: ISerializedWindowState;
	openedWindows: ISerializedWindowState[];
}

interface ISerializedWindowState {
	workspaceIdentifier?: { id: string; configURIPath: string };
	folder?: string;
	backupPath: string;
	remoteAuthority?: string;
	uiState: ISingleWindowState;

	// deprecated
	folderUri?: UriComponents;
	folderPath?: string;
	workspace?: { id: string; configPath: string };

}

84
type RestoreWindowsSetting = 'all' | 'folders' | 'one' | 'none';
85

B
Benjamin Pasero 已提交
86 87 88
interface IOpenBrowserWindowOptions {
	userEnv?: IProcessEnvironment;
	cli?: ParsedArgs;
89

90
	workspace?: IWorkspaceIdentifier;
91
	folderUri?: URI;
B
Benjamin Pasero 已提交
92

M
Martin Aeschlimann 已提交
93 94
	remoteAuthority: string;

B
Benjamin Pasero 已提交
95 96
	initialStartup?: boolean;

97
	fileInputs?: IFileInputs;
B
Benjamin Pasero 已提交
98 99

	forceNewWindow?: boolean;
100
	forceNewTabbedWindow?: boolean;
101
	windowToUse?: ICodeWindow;
B
Benjamin Pasero 已提交
102

103 104 105 106 107 108 109
	emptyWindowBackupInfo?: IEmptyWindowBackupInfo;
}

interface IPathParseOptions {
	ignoreFileNotFound?: boolean;
	gotoLineMode?: boolean;
	forceOpenWorkspaceAsFile?: boolean;
M
Martin Aeschlimann 已提交
110
	remoteAuthority?: string;
111 112 113 114 115 116 117
}

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

M
Martin Aeschlimann 已提交
121 122 123 124
enum URIType {
	FILE, FOLDER, WORKSPACE
}

B
Benjamin Pasero 已提交
125
interface IPathToOpen extends IPath {
126

127
	// the workspace for a Code instance to open
128
	workspace?: IWorkspaceIdentifier;
129

130
	// the folder path for a Code instance to open
131
	folderUri?: URI;
132

133
	// the backup path for a Code instance to use
134 135
	backupPath?: string;

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

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

J
Joao Moreno 已提交
143
export class WindowsManager implements IWindowsMainService {
J
Joao Moreno 已提交
144

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

147
	private static readonly windowsStateStorageKey = 'windowsState';
E
Erich Gamma 已提交
148

149
	private static WINDOWS: ICodeWindow[] = [];
E
Erich Gamma 已提交
150

B
Benjamin Pasero 已提交
151
	private initialUserEnv: IProcessEnvironment;
152

E
Erich Gamma 已提交
153
	private windowsState: IWindowsState;
154
	private lastClosedWindowState: IWindowState;
E
Erich Gamma 已提交
155

156
	private dialogs: Dialogs;
157
	private workspacesManager: WorkspacesManager;
B
Benjamin Pasero 已提交
158

159 160
	private _onWindowReady = new Emitter<ICodeWindow>();
	onWindowReady: CommonEvent<ICodeWindow> = this._onWindowReady.event;
161 162 163 164

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

165 166 167
	private _onWindowLoad = new Emitter<number>();
	onWindowLoad: CommonEvent<number> = this._onWindowLoad.event;

B
Benjamin Pasero 已提交
168 169 170
	private _onWindowsCountChanged = new Emitter<IWindowsCountChangedEvent>();
	onWindowsCountChanged: CommonEvent<IWindowsCountChangedEvent> = this._onWindowsCountChanged.event;

J
Joao Moreno 已提交
171
	constructor(
B
Benjamin Pasero 已提交
172
		private readonly machineId: string,
173 174 175 176 177 178 179 180 181 182
		@ILogService private readonly logService: ILogService,
		@IStateService private readonly stateService: IStateService,
		@IEnvironmentService private readonly environmentService: IEnvironmentService,
		@ILifecycleService private readonly lifecycleService: ILifecycleService,
		@IBackupMainService private readonly backupMainService: IBackupMainService,
		@ITelemetryService private readonly telemetryService: ITelemetryService,
		@IConfigurationService private readonly configurationService: IConfigurationService,
		@IHistoryMainService private readonly historyMainService: IHistoryMainService,
		@IWorkspacesMainService private readonly workspacesMainService: IWorkspacesMainService,
		@IInstantiationService private readonly instantiationService: IInstantiationService
183
	) {
184
		this.windowsState = this.getWindowsState();
185 186 187
		if (!Array.isArray(this.windowsState.openedWindows)) {
			this.windowsState.openedWindows = [];
		}
188

B
Benjamin Pasero 已提交
189
		this.dialogs = new Dialogs(environmentService, telemetryService, stateService, this);
190
		this.workspacesManager = new WorkspacesManager(workspacesMainService, backupMainService, environmentService, historyMainService, this);
191
	}
J
Joao Moreno 已提交
192

193
	private getWindowsState(): IWindowsState {
194 195 196
		const result: IWindowsState = { openedWindows: [] };
		const windowsState = this.stateService.getItem<ISerializedWindowsState>(WindowsManager.windowsStateStorageKey) || { openedWindows: [] };

197
		if (windowsState.lastActiveWindow) {
198
			result.lastActiveWindow = this.deserialize(windowsState.lastActiveWindow);
199 200
		}
		if (windowsState.lastPluginDevelopmentHostWindow) {
201
			result.lastPluginDevelopmentHostWindow = this.deserialize(windowsState.lastPluginDevelopmentHostWindow);
202
		}
203 204
		if (Array.isArray(windowsState.openedWindows)) {
			result.openedWindows = windowsState.openedWindows.map(windowState => this.deserialize(windowState));
205
		}
206
		return result;
207 208
	}

209 210 211 212 213 214 215 216
	private deserialize(windowState: ISerializedWindowState): IWindowState {
		const result: IWindowState = { backupPath: windowState.backupPath, remoteAuthority: windowState.remoteAuthority, uiState: windowState.uiState };
		if (windowState.folder) {
			result.folderUri = URI.parse(windowState.folder);
		} else if (windowState.folderUri) {
			result.folderUri = URI.revive(windowState.folderUri);
		} else if (windowState.folderPath) {
			result.folderUri = URI.file(windowState.folderPath);
217
		}
218 219 220 221
		if (windowState.workspaceIdentifier) {
			result.workspace = { id: windowState.workspaceIdentifier.id, configPath: URI.parse(windowState.workspaceIdentifier.configURIPath) };
		} else if (windowState.workspace) {
			result.workspace = { id: windowState.workspace.id, configPath: URI.file(windowState.workspace.configPath) };
222
		}
223
		return result;
224 225
	}

B
Benjamin Pasero 已提交
226
	ready(initialUserEnv: IProcessEnvironment): void {
227
		this.initialUserEnv = initialUserEnv;
228 229

		this.registerListeners();
E
Erich Gamma 已提交
230 231 232
	}

	private registerListeners(): void {
233

B
Benjamin Pasero 已提交
234 235 236
		// React to workbench ready events from windows
		ipc.on('vscode:workbenchReady', (event: any, windowId: number) => {
			this.logService.trace('IPC#vscode-workbenchReady');
E
Erich Gamma 已提交
237

B
Benjamin Pasero 已提交
238
			const win = this.getWindowById(windowId);
E
Erich Gamma 已提交
239 240 241 242
			if (win) {
				win.setReady();

				// Event
243
				this._onWindowReady.fire(win);
E
Erich Gamma 已提交
244 245 246
			}
		});

247 248 249 250 251 252 253 254 255 256 257
		// 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');
				}
			});
		}

258 259
		// Handle various lifecycle events around windows
		this.lifecycleService.onBeforeWindowUnload(e => this.onBeforeWindowUnload(e));
B
Benjamin Pasero 已提交
260
		this.lifecycleService.onBeforeWindowClose(window => this.onBeforeWindowClose(window));
261
		this.lifecycleService.onBeforeShutdown(() => this.onBeforeShutdown());
262 263 264 265 266
		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.
R
Rob Lourens 已提交
267
				this.lastClosedWindowState = undefined;
268 269
			}
		});
270 271
	}

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

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

323
			if (activeWindow) {
324
				currentWindowsState.lastActiveWindow = this.toWindowState(activeWindow);
E
Erich Gamma 已提交
325
			}
326 327 328 329 330
		}

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

334
		// 3.) All windows (except extension host) for N >= 2 to support restoreWindows: all or for auto update
335 336 337 338 339
		//
		// 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) {
340
			currentWindowsState.openedWindows = WindowsManager.WINDOWS.filter(w => !w.isExtensionDevelopmentHost).map(w => this.toWindowState(w));
341
		}
E
Erich Gamma 已提交
342

343
		// Persist
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
		this.stateService.setItem(WindowsManager.windowsStateStorageKey, this.serializeWindowsState(currentWindowsState));
	}

	private serializeWindowsState(windowsState: IWindowsState): ISerializedWindowsState {
		return {
			lastActiveWindow: windowsState.lastActiveWindow && this.serialize(windowsState.lastActiveWindow),
			lastPluginDevelopmentHostWindow: windowsState.lastPluginDevelopmentHostWindow && this.serialize(windowsState.lastPluginDevelopmentHostWindow),
			openedWindows: windowsState.openedWindows.map(ws => this.serialize(ws))
		};
	}

	private serialize(windowState: IWindowState): ISerializedWindowState {
		return {
			workspaceIdentifier: windowState.workspace && { id: windowState.workspace.id, configURIPath: windowState.workspace.configPath.toString() },
			folder: windowState.folderUri && windowState.folderUri.toString(),
			backupPath: windowState.backupPath,
			remoteAuthority: windowState.remoteAuthority,
			uiState: windowState.uiState
		};
363
	}
364

365
	// See note on #onBeforeShutdown() for details how these events are flowing
366
	private onBeforeWindowClose(win: ICodeWindow): void {
B
Benjamin Pasero 已提交
367
		if (this.lifecycleService.quitRequested) {
368 369 370 371
			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
372
		const state: IWindowState = this.toWindowState(win);
373 374 375 376
		if (win.isExtensionDevelopmentHost && !win.isExtensionTestHost) {
			this.windowsState.lastPluginDevelopmentHostWindow = state; // do not let test run window state overwrite our extension development state
		}

377
		// Any non extension host window with same workspace or folder
378
		else if (!win.isExtensionDevelopmentHost && (!!win.openedWorkspace || !!win.openedFolderUri)) {
379
			this.windowsState.openedWindows.forEach(o => {
B
fix npe  
Benjamin Pasero 已提交
380
				const sameWorkspace = win.openedWorkspace && o.workspace && o.workspace.id === win.openedWorkspace.id;
381
				const sameFolder = win.openedFolderUri && o.folderUri && isEqual(o.folderUri, win.openedFolderUri);
382 383

				if (sameWorkspace || sameFolder) {
384 385 386 387 388 389 390
					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.
391 392 393
		// 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) {
394 395
			this.lastClosedWindowState = state;
		}
E
Erich Gamma 已提交
396 397
	}

398
	private toWindowState(win: ICodeWindow): IWindowState {
399
		return {
400
			workspace: win.openedWorkspace,
401
			folderUri: win.openedFolderUri,
402
			backupPath: win.backupPath,
M
Martin Aeschlimann 已提交
403
			remoteAuthority: win.remoteAuthority,
404 405 406 407
			uiState: win.serializeWindowState()
		};
	}

B
Benjamin Pasero 已提交
408
	open(openConfig: IOpenConfiguration): ICodeWindow[] {
409
		this.logService.trace('windowsManager#open');
410
		openConfig = this.validateOpenConfig(openConfig);
411

412
		let pathsToOpen = this.getPathsToOpen(openConfig);
413 414 415

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

422
		// collect all file inputs
423
		let fileInputs: IFileInputs | undefined;
424 425 426
		for (const path of pathsToOpen) {
			if (path.fileUri) {
				if (!fileInputs) {
M
Martin Aeschlimann 已提交
427
					fileInputs = { filesToCreate: [], filesToOpen: [], filesToDiff: [], remoteAuthority: path.remoteAuthority };
428 429 430 431 432 433 434 435
				}
				if (!path.createFilePath) {
					fileInputs.filesToOpen.push(path);
				} else {
					fileInputs.filesToCreate.push(path);
				}
			}
		}
436 437 438

		// When run with --diff, take the files to open as files to diff
		// if there are exactly two files provided.
439 440 441 442
		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 已提交
443 444
		}

445
		// When run with --wait, make sure we keep the paths to wait for
446 447
		if (fileInputs && openConfig.cli.wait && openConfig.cli.waitMarkerFilePath) {
			fileInputs.filesToWait = { paths: [...fileInputs.filesToDiff, ...fileInputs.filesToOpen, ...fileInputs.filesToCreate], waitMarkerFilePath: openConfig.cli.waitMarkerFilePath };
448 449
		}

450 451 452
		//
		// These are windows to open to show workspaces
		//
B
Benjamin Pasero 已提交
453
		const workspacesToOpen = arrays.distinct(pathsToOpen.filter(win => !!win.workspace).map(win => win.workspace), workspace => workspace.id); // prevent duplicates
454 455 456 457

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

460
		//
461
		// These are windows to restore because of hot-exit or from previous session (only performed once on startup!)
462
		//
463
		let foldersToRestore: URI[] = [];
464
		let workspacesToRestore: IWorkspaceIdentifier[] = [];
465
		let emptyToRestore: IEmptyWindowBackupInfo[] = [];
B
Benjamin Pasero 已提交
466
		if (openConfig.initialStartup && !openConfig.cli.extensionDevelopmentPath && !openConfig.cli['disable-restore-windows']) {
467
			foldersToRestore = this.backupMainService.getFolderBackupPaths();
468

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

B
Benjamin Pasero 已提交
472
			emptyToRestore = this.backupMainService.getEmptyWindowBackupPaths();
M
Martin Aeschlimann 已提交
473
			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
474
			emptyToRestore = arrays.distinct(emptyToRestore, info => info.backupFolder); // prevent duplicates
475
		}
476

477 478 479
		//
		// These are empty windows to open
		//
480
		const emptyToOpen = pathsToOpen.filter(win => !win.workspace && !win.folderUri && !win.fileUri && !win.backupPath).length;
481

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

485
		// Make sure to pass focus to the most relevant of the windows if we open multiple
486
		if (usedWindows.length > 1) {
487

M
Martin Aeschlimann 已提交
488
			let focusLastActive = this.windowsState.lastActiveWindow && !openConfig.forceEmpty && !hasArgs(openConfig.cli._) && !hasArgs(openConfig.cli['file-uri']) && !hasArgs(openConfig.cli['folder-uri']) && !hasArgs(openConfig.cli['workspace-uri']) && !(openConfig.urisToOpen && openConfig.urisToOpen.length);
489 490
			let focusLastOpened = true;
			let focusLastWindow = true;
491

492 493
			// 1.) focus last active window if we are not instructed to open any paths
			if (focusLastActive) {
494 495 496
				const lastActiveWindw = usedWindows.filter(w => w.backupPath === this.windowsState.lastActiveWindow.backupPath);
				if (lastActiveWindw.length) {
					lastActiveWindw[0].focus();
497 498
					focusLastOpened = false;
					focusLastWindow = false;
499 500 501
				}
			}

502 503 504 505 506
			// 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 (
507 508 509
						(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
510 511 512 513 514 515 516 517 518 519 520 521
					) {
						continue;
					}

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

			// 3.) finally, always ensure to have at least last used window focused
			if (focusLastWindow) {
522
				usedWindows[usedWindows.length - 1].focus();
523 524
			}
		}
525

526 527
		// 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
528
		if (!usedWindows.some(w => w.isExtensionDevelopmentHost) && !openConfig.diffMode) {
529
			const recentlyOpenedWorkspaces: Array<IWorkspaceIdentifier | ISingleFolderWorkspaceIdentifier> = [];
530
			const recentlyOpenedFiles: URI[] = [];
531

B
Benjamin Pasero 已提交
532
			pathsToOpen.forEach(win => {
533 534
				if (win.workspace || win.folderUri) {
					recentlyOpenedWorkspaces.push(win.workspace || win.folderUri);
535 536
				} else if (win.fileUri) {
					recentlyOpenedFiles.push(win.fileUri);
537 538 539
				}
			});

540 541 542
			if (!this.environmentService.skipAddToRecentlyOpened) {
				this.historyMainService.addRecentlyOpened(recentlyOpenedWorkspaces, recentlyOpenedFiles);
			}
543
		}
544

545
		// If we got started with --wait from the CLI, we need to signal to the outside when the window
546 547
		// 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.
548
		if (openConfig.context === OpenContext.CLI && openConfig.cli.wait && openConfig.cli.waitMarkerFilePath && usedWindows.length === 1 && usedWindows[0]) {
R
Rob Lourens 已提交
549
			this.waitForWindowCloseOrLoad(usedWindows[0].id).then(() => fs.unlink(openConfig.cli.waitMarkerFilePath, error => undefined));
550 551
		}

552 553 554
		return usedWindows;
	}

555 556 557 558 559 560 561 562 563 564
	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;
	}

565 566
	private doOpen(
		openConfig: IOpenConfiguration,
567 568
		workspacesToOpen: IWorkspaceIdentifier[],
		workspacesToRestore: IWorkspaceIdentifier[],
569 570
		foldersToOpen: URI[],
		foldersToRestore: URI[],
571
		emptyToRestore: IEmptyWindowBackupInfo[],
572
		emptyToOpen: number,
573
		fileInputs: IFileInputs | undefined,
574
		foldersToAdd: URI[]
575
	) {
576
		const usedWindows: ICodeWindow[] = [];
577

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

581 582
		// Handle folders to add by looking for the last active workspace (not on initial startup)
		if (!openConfig.initialStartup && foldersToAdd.length > 0) {
M
Martin Aeschlimann 已提交
583 584
			const authority = getRemoteAuthority(foldersToAdd[0]);
			const lastActiveWindow = this.getLastActiveWindowForAuthority(authority);
585
			if (lastActiveWindow) {
586
				usedWindows.push(this.doAddFoldersToExistingWindow(lastActiveWindow, foldersToAdd));
587 588 589
			}
		}

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

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

599
			let bestWindowOrFolder = findBestWindowOrFolderForFile({
600
				windows,
601 602
				newWindow: openFilesInNewWindow,
				context: openConfig.context,
603
				fileUri: fileToCheck && fileToCheck.fileUri,
M
Martin Aeschlimann 已提交
604
				workspaceResolver: workspace => workspace.configPath.scheme === Schemas.file && this.workspacesMainService.resolveWorkspaceSync(fsPath(workspace.configPath))
605
			});
B
Benjamin Pasero 已提交
606

607 608 609 610 611 612 613 614 615
			// 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
616 617
				else if (bestWindowOrFolder.openedFolderUri) {
					foldersToOpen.push(bestWindowOrFolder.openedFolderUri);
618 619 620 621 622 623
				}

				// Window is empty
				else {

					// Do open files
624
					usedWindows.push(this.doOpenFilesInExistingWindow(openConfig, bestWindowOrFolder, fileInputs));
625 626

					// Reset these because we handled them
R
Rob Lourens 已提交
627
					fileInputs = undefined;
628
				}
629 630 631
			}

			// Finally, if no window or folder is found, just open the files in an empty window
E
Erich Gamma 已提交
632
			else {
B
Benjamin Pasero 已提交
633
				usedWindows.push(this.openInBrowserWindow({
B
Benjamin Pasero 已提交
634 635 636
					userEnv: openConfig.userEnv,
					cli: openConfig.cli,
					initialStartup: openConfig.initialStartup,
637
					fileInputs,
638
					forceNewWindow: true,
M
Martin Aeschlimann 已提交
639
					remoteAuthority: fileInputs.remoteAuthority,
640
					forceNewTabbedWindow: openConfig.forceNewTabbedWindow
B
Benjamin Pasero 已提交
641
				}));
E
Erich Gamma 已提交
642

643
				// Reset these because we handled them
R
Rob Lourens 已提交
644
				fileInputs = undefined;
E
Erich Gamma 已提交
645 646 647
			}
		}

648
		// Handle workspaces to open (instructed and to restore)
649
		const allWorkspacesToOpen = arrays.distinct([...workspacesToRestore, ...workspacesToOpen], workspace => workspace.id); // prevent duplicates
650 651 652 653 654 655
		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];
R
Rob Lourens 已提交
656
				const fileInputsForWindow = (fileInputs && fileInputs.remoteAuthority === windowOnWorkspace.remoteAuthority) ? fileInputs : undefined;
657 658

				// Do open files
659
				usedWindows.push(this.doOpenFilesInExistingWindow(openConfig, windowOnWorkspace, fileInputsForWindow));
660 661

				// Reset these because we handled them
662
				if (fileInputsForWindow) {
R
Rob Lourens 已提交
663
					fileInputs = undefined;
664
				}
665 666 667 668 669 670

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

			// Open remaining ones
			allWorkspacesToOpen.forEach(workspaceToOpen => {
671
				if (windowsOnWorkspace.some(win => win.openedWorkspace.id === workspaceToOpen.id)) {
672 673 674
					return; // ignore folders that are already open
				}

R
Rob Lourens 已提交
675
				const fileInputsForWindow = (fileInputs && !fileInputs.remoteAuthority) ? fileInputs : undefined;
676

677
				// Do open folder
678
				usedWindows.push(this.doOpenFolderOrWorkspace(openConfig, { workspace: workspaceToOpen }, openFolderInNewWindow, fileInputsForWindow));
679 680

				// Reset these because we handled them
681
				if (fileInputsForWindow) {
R
Rob Lourens 已提交
682
					fileInputs = undefined;
683
				}
684 685 686 687 688

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

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

692
		if (allFoldersToOpen.length > 0) {
E
Erich Gamma 已提交
693 694

			// Check for existing instances
695
			const windowsOnFolderPath = arrays.coalesce(allFoldersToOpen.map(folderToOpen => findWindowOnWorkspace(WindowsManager.WINDOWS, folderToOpen)));
696
			if (windowsOnFolderPath.length > 0) {
697
				const windowOnFolderPath = windowsOnFolderPath[0];
R
Rob Lourens 已提交
698
				const fileInputsForWindow = fileInputs && fileInputs.remoteAuthority === windowOnFolderPath.remoteAuthority ? fileInputs : undefined;
E
Erich Gamma 已提交
699

700
				// Do open files
701
				usedWindows.push(this.doOpenFilesInExistingWindow(openConfig, windowOnFolderPath, fileInputsForWindow));
702

E
Erich Gamma 已提交
703
				// Reset these because we handled them
704
				if (fileInputsForWindow) {
R
Rob Lourens 已提交
705
					fileInputs = undefined;
706
				}
E
Erich Gamma 已提交
707

B
Benjamin Pasero 已提交
708
				openFolderInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
709 710 711
			}

			// Open remaining ones
712
			allFoldersToOpen.forEach(folderToOpen => {
713

714
				if (windowsOnFolderPath.some(win => isEqual(win.openedFolderUri, folderToOpen))) {
E
Erich Gamma 已提交
715 716 717
					return; // ignore folders that are already open
				}

M
Martin Aeschlimann 已提交
718
				const remoteAuthority = getRemoteAuthority(folderToOpen);
R
Rob Lourens 已提交
719
				const fileInputsForWindow = (fileInputs && fileInputs.remoteAuthority === remoteAuthority) ? fileInputs : undefined;
720

721
				// Do open folder
M
Martin Aeschlimann 已提交
722
				usedWindows.push(this.doOpenFolderOrWorkspace(openConfig, { folderUri: folderToOpen, remoteAuthority }, openFolderInNewWindow, fileInputsForWindow));
E
Erich Gamma 已提交
723 724

				// Reset these because we handled them
725
				if (fileInputsForWindow) {
R
Rob Lourens 已提交
726
					fileInputs = undefined;
727
				}
E
Erich Gamma 已提交
728

B
Benjamin Pasero 已提交
729
				openFolderInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
730 731 732
			});
		}

733
		// Handle empty to restore
734
		if (emptyToRestore.length > 0) {
735
			emptyToRestore.forEach(emptyWindowBackupInfo => {
M
Martin Aeschlimann 已提交
736
				const remoteAuthority = emptyWindowBackupInfo.remoteAuthority;
R
Rob Lourens 已提交
737
				const fileInputsForWindow = (fileInputs && fileInputs.remoteAuthority === remoteAuthority) ? fileInputs : undefined;
738

B
Benjamin Pasero 已提交
739
				usedWindows.push(this.openInBrowserWindow({
B
Benjamin Pasero 已提交
740 741 742
					userEnv: openConfig.userEnv,
					cli: openConfig.cli,
					initialStartup: openConfig.initialStartup,
743
					fileInputs: fileInputsForWindow,
M
Martin Aeschlimann 已提交
744
					remoteAuthority,
B
Benjamin Pasero 已提交
745
					forceNewWindow: true,
746
					forceNewTabbedWindow: openConfig.forceNewTabbedWindow,
747
					emptyWindowBackupInfo
B
Benjamin Pasero 已提交
748
				}));
749

B
wip  
Benjamin Pasero 已提交
750
				// Reset these because we handled them
751
				if (fileInputsForWindow) {
R
Rob Lourens 已提交
752
					fileInputs = undefined;
753
				}
B
wip  
Benjamin Pasero 已提交
754

B
Benjamin Pasero 已提交
755
				openFolderInNewWindow = true; // any other folders to open must open in new window then
756 757
			});
		}
B
Benjamin Pasero 已提交
758

759
		// Handle empty to open (only if no other window opened)
760 761 762 763
		if (usedWindows.length === 0 || fileInputs) {
			if (fileInputs && !emptyToOpen) {
				emptyToOpen++;
			}
R
Rob Lourens 已提交
764
			const remoteAuthority = fileInputs ? fileInputs.remoteAuthority : (openConfig.cli && openConfig.cli.remote || undefined);
765
			for (let i = 0; i < emptyToOpen; i++) {
B
Benjamin Pasero 已提交
766
				usedWindows.push(this.openInBrowserWindow({
B
Benjamin Pasero 已提交
767 768 769
					userEnv: openConfig.userEnv,
					cli: openConfig.cli,
					initialStartup: openConfig.initialStartup,
M
Martin Aeschlimann 已提交
770
					remoteAuthority,
771
					forceNewWindow: openFolderInNewWindow,
772 773
					forceNewTabbedWindow: openConfig.forceNewTabbedWindow,
					fileInputs
B
Benjamin Pasero 已提交
774
				}));
E
Erich Gamma 已提交
775

776
				// Reset these because we handled them
R
Rob Lourens 已提交
777
				fileInputs = undefined;
778
				openFolderInNewWindow = true; // any other window to open must open in new window then
779 780
			}
		}
E
Erich Gamma 已提交
781

782
		return arrays.distinct(usedWindows);
E
Erich Gamma 已提交
783 784
	}

785
	private doOpenFilesInExistingWindow(configuration: IOpenConfiguration, window: ICodeWindow, fileInputs?: IFileInputs): ICodeWindow {
786 787
		window.focus(); // make sure window has focus

B
Benjamin Pasero 已提交
788 789 790 791 792 793 794 795 796 797 798 799 800
		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 已提交
801 802

		return window;
803 804
	}

805
	private doAddFoldersToExistingWindow(window: ICodeWindow, foldersToAdd: URI[]): ICodeWindow {
806 807
		window.focus(); // make sure window has focus

B
Benjamin Pasero 已提交
808
		window.sendWhenReady('vscode:addFolders', { foldersToAdd });
809 810 811 812

		return window;
	}

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

818 819 820 821
		const browserWindow = this.openInBrowserWindow({
			userEnv: openConfig.userEnv,
			cli: openConfig.cli,
			initialStartup: openConfig.initialStartup,
822
			workspace: folderOrWorkspace.workspace,
823
			folderUri: folderOrWorkspace.folderUri,
824
			fileInputs,
M
Martin Aeschlimann 已提交
825
			remoteAuthority: folderOrWorkspace.remoteAuthority,
B
Benjamin Pasero 已提交
826
			forceNewWindow,
827
			forceNewTabbedWindow: openConfig.forceNewTabbedWindow,
828
			windowToUse
829 830 831 832 833
		});

		return browserWindow;
	}

B
Benjamin Pasero 已提交
834 835
	private getPathsToOpen(openConfig: IOpenConfiguration): IPathToOpen[] {
		let windowsToOpen: IPathToOpen[];
836
		let isCommandLineOrAPICall = false;
E
Erich Gamma 已提交
837

838
		// Extract paths: from API
S
Sandeep Somavarapu 已提交
839
		if (openConfig.urisToOpen && openConfig.urisToOpen.length > 0) {
840
			windowsToOpen = this.doExtractPathsFromAPI(openConfig);
841
			isCommandLineOrAPICall = true;
E
Erich Gamma 已提交
842 843
		}

B
Benjamin Pasero 已提交
844 845
		// Check for force empty
		else if (openConfig.forceEmpty) {
846
			windowsToOpen = [Object.create(null)];
E
Erich Gamma 已提交
847 848
		}

849
		// Extract paths: from CLI
M
Martin Aeschlimann 已提交
850
		else if (hasArgs(openConfig.cli._) || hasArgs(openConfig.cli['folder-uri']) || hasArgs(openConfig.cli['file-uri']) || hasArgs(openConfig.cli['workspace-uri'])) {
851
			windowsToOpen = this.doExtractPathsFromCLI(openConfig.cli);
852
			isCommandLineOrAPICall = true;
B
Benjamin Pasero 已提交
853 854
		}

855
		// Extract windows: from previous session
B
Benjamin Pasero 已提交
856
		else {
857
			windowsToOpen = this.doGetWindowsFromLastSession();
B
Benjamin Pasero 已提交
858 859
		}

860 861
		// Convert multiple folders into workspace (if opened via API or CLI)
		// This will ensure to open these folders in one window instead of multiple
862 863
		// If we are in addMode, we should not do this because in that case all
		// folders should be added to the existing window.
864
		if (!openConfig.addMode && isCommandLineOrAPICall) {
865
			const foldersToOpen = windowsToOpen.filter(path => !!path.folderUri);
866
			if (foldersToOpen.length > 1 && foldersToOpen.every(f => f.folderUri.scheme === Schemas.file)) {
867
				const workspace = this.workspacesMainService.createUntitledWorkspaceSync(foldersToOpen.map(folder => ({ uri: folder.folderUri })));
868 869

				// Add workspace and remove folders thereby
M
Martin Aeschlimann 已提交
870
				windowsToOpen.push({ workspace, remoteAuthority: foldersToOpen[0].remoteAuthority });
871
				windowsToOpen = windowsToOpen.filter(path => !path.folderUri);
872 873 874
			}
		}

875
		return windowsToOpen;
E
Erich Gamma 已提交
876 877
	}

878
	private doExtractPathsFromAPI(openConfig: IOpenConfiguration): IPathToOpen[] {
M
Matt Bierner 已提交
879
		const pathsToOpen: IPathToOpen[] = [];
880 881
		const cli = openConfig.cli;
		let parseOptions: IPathParseOptions = { gotoLineMode: cli && cli.goto, forceOpenWorkspaceAsFile: openConfig.forceOpenWorkspaceAsFile };
M
Martin Aeschlimann 已提交
882 883 884 885 886
		for (const pathToOpen of openConfig.urisToOpen) {
			if (!pathToOpen) {
				continue;
			}

M
Martin Aeschlimann 已提交
887
			const path = this.parseUri(pathToOpen, openConfig.forceOpenWorkspaceAsFile ? URIType.FILE : URIType.FOLDER, parseOptions);
M
Martin Aeschlimann 已提交
888 889 890
			if (path) {
				pathsToOpen.push(path);
			} else {
891

B
Benjamin Pasero 已提交
892
				// Warn about the invalid URI or path
M
Martin Aeschlimann 已提交
893 894 895 896 897 898 899 900
				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());
				}
901
				const options: Electron.MessageBoxOptions = {
902 903
					title: product.nameLong,
					type: 'info',
904
					buttons: [localize('ok', "OK")],
M
Martin Aeschlimann 已提交
905 906
					message,
					detail,
907 908 909
					noLink: true
				};

910
				this.dialogs.showMessageBox(options, this.getFocusedWindow());
911
			}
M
Martin Aeschlimann 已提交
912
		}
913 914 915 916
		return pathsToOpen;
	}

	private doExtractPathsFromCLI(cli: ParsedArgs): IPath[] {
M
Matt Bierner 已提交
917
		const pathsToOpen: IPathToOpen[] = [];
R
Rob Lourens 已提交
918
		const parseOptions: IPathParseOptions = { ignoreFileNotFound: true, gotoLineMode: cli.goto, remoteAuthority: cli.remote || undefined };
919 920

		// folder uris
921
		const folderUris = asArray(cli['folder-uri']);
M
Martin Aeschlimann 已提交
922
		for (let folderUri of folderUris) {
M
Martin Aeschlimann 已提交
923
			const path = this.parseUri(this.argToUri(folderUri), URIType.FOLDER, parseOptions);
M
Martin Aeschlimann 已提交
924 925 926
			if (path) {
				pathsToOpen.push(path);
			}
927 928 929 930
		}

		// file uris
		const fileUris = asArray(cli['file-uri']);
M
Martin Aeschlimann 已提交
931
		for (let fileUri of fileUris) {
M
Martin Aeschlimann 已提交
932 933 934 935 936 937 938 939 940
			const path = this.parseUri(this.argToUri(fileUri), URIType.FILE, parseOptions);
			if (path) {
				pathsToOpen.push(path);
			}
		}

		const workspaceUris = asArray(cli['workspace-uri']);
		for (let workspaceUri of workspaceUris) {
			const path = this.parseUri(this.argToUri(workspaceUri), URIType.WORKSPACE, parseOptions);
M
Martin Aeschlimann 已提交
941 942 943
			if (path) {
				pathsToOpen.push(path);
			}
944 945
		}

M
Martin Aeschlimann 已提交
946

947
		// folder or file paths
M
Martin Aeschlimann 已提交
948 949 950 951 952 953
		const cliArgs = asArray(cli._);
		for (let cliArg of cliArgs) {
			const path = this.parsePath(cliArg, parseOptions);
			if (path) {
				pathsToOpen.push(path);
			}
954 955
		}

M
Martin Aeschlimann 已提交
956
		if (pathsToOpen.length) {
957
			return pathsToOpen;
B
Benjamin Pasero 已提交
958 959 960 961 962 963
		}

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

B
Benjamin Pasero 已提交
964
	private doGetWindowsFromLastSession(): IPathToOpen[] {
965
		const restoreWindows = this.getRestoreWindowsSetting();
B
Benjamin Pasero 已提交
966

967
		switch (restoreWindows) {
B
Benjamin Pasero 已提交
968

969
			// none: we always open an empty window
970 971
			case 'none':
				return [Object.create(null)];
B
Benjamin Pasero 已提交
972

973
			// one: restore last opened workspace/folder or empty window
974 975
			// all: restore all windows
			// folders: restore last opened folders only
976
			case 'one':
977 978
			case 'all':
			case 'folders':
979 980 981
				const openedWindows: IWindowState[] = [];
				if (restoreWindows !== 'one') {
					openedWindows.push(...this.windowsState.openedWindows);
982
				}
983 984
				if (this.windowsState.lastActiveWindow) {
					openedWindows.push(this.windowsState.lastActiveWindow);
985
				}
986

987 988 989
				const windowsToOpen: IPathToOpen[] = [];
				for (const openedWindow of openedWindows) {
					if (openedWindow.workspace) { // Workspaces
M
Martin Aeschlimann 已提交
990
						const pathToOpen = this.parseUri(openedWindow.workspace.configPath, URIType.WORKSPACE, { remoteAuthority: openedWindow.remoteAuthority });
991 992 993 994
						if (pathToOpen && pathToOpen.workspace) {
							windowsToOpen.push(pathToOpen);
						}
					} else if (openedWindow.folderUri) { // Folders
M
Martin Aeschlimann 已提交
995
						const pathToOpen = this.parseUri(openedWindow.folderUri, URIType.FOLDER, { remoteAuthority: openedWindow.remoteAuthority });
996 997 998 999
						if (pathToOpen && pathToOpen.folderUri) {
							windowsToOpen.push(pathToOpen);
						}
					} else if (restoreWindows !== 'folders' && openedWindow.backupPath) { // Windows that were Empty
M
Martin Aeschlimann 已提交
1000
						windowsToOpen.push({ backupPath: openedWindow.backupPath, remoteAuthority: openedWindow.remoteAuthority });
1001
					}
1002 1003 1004 1005 1006 1007 1008
				}

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

				break;
B
Benjamin Pasero 已提交
1009
		}
E
Erich Gamma 已提交
1010

1011
		// Always fallback to empty window
B
Benjamin Pasero 已提交
1012
		return [Object.create(null)];
E
Erich Gamma 已提交
1013 1014
	}

1015 1016 1017 1018 1019
	private getRestoreWindowsSetting(): RestoreWindowsSetting {
		let restoreWindows: RestoreWindowsSetting;
		if (this.lifecycleService.wasRestarted) {
			restoreWindows = 'all'; // always reopen all windows when an update was applied
		} else {
1020
			const windowConfig = this.configurationService.getValue<IWindowSettings>('window');
1021
			restoreWindows = ((windowConfig && windowConfig.restoreWindows) || 'one') as RestoreWindowsSetting;
1022 1023 1024 1025 1026 1027 1028 1029 1030

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

		return restoreWindows;
	}

1031
	private argToUri(arg: string): URI | null {
M
Martin Aeschlimann 已提交
1032 1033 1034
		try {
			let uri = URI.parse(arg);
			if (!uri.scheme) {
M
Martin Aeschlimann 已提交
1035
				this.logService.error(`Invalid URI input string, scheme missing: ${arg}`);
M
Martin Aeschlimann 已提交
1036 1037 1038 1039
				return null;
			}
			return uri;
		} catch (e) {
M
Martin Aeschlimann 已提交
1040
			this.logService.error(`Invalid URI input string: ${arg}, ${e.message}`);
1041
		}
M
Martin Aeschlimann 已提交
1042
		return null;
1043 1044
	}

1045
	private parseUri(uri: URI, type: URIType, options?: IPathParseOptions): IPathToOpen | null {
M
Martin Aeschlimann 已提交
1046
		if (!uri || !uri.scheme) {
1047 1048
			return null;
		}
M
Martin Aeschlimann 已提交
1049 1050
		if (uri.scheme === Schemas.file) {
			return this.parsePath(uri.fsPath, options);
1051
		}
M
Martin Aeschlimann 已提交
1052 1053 1054 1055

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

1056 1057
		// normalize URI
		uri = normalizePath(uri);
1058 1059 1060
		const uriPath = uri.path;
		if (uriPath.length > 2 && endsWith(uriPath, '/')) {
			uri = uri.with({ path: uriPath.substr(0, uriPath.length - 1) });
1061
		}
M
Martin Aeschlimann 已提交
1062
		if (type === URIType.FILE) {
1063 1064 1065 1066 1067
			if (options && options.gotoLineMode) {
				const parsedPath = parseLineAndColumnAware(uri.path);
				return {
					fileUri: uri.with({ path: parsedPath.path }),
					lineNumber: parsedPath.line,
M
Martin Aeschlimann 已提交
1068 1069
					columnNumber: parsedPath.column,
					remoteAuthority
1070 1071
				};
			}
1072
			return {
M
Martin Aeschlimann 已提交
1073 1074
				fileUri: uri,
				remoteAuthority
1075
			};
M
Martin Aeschlimann 已提交
1076 1077 1078 1079 1080
		} else if (type === URIType.WORKSPACE) {
			return {
				workspace: this.workspacesMainService.getWorkspaceIdentifier(uri),
				remoteAuthority
			};
1081
		}
1082
		return {
M
Martin Aeschlimann 已提交
1083 1084
			folderUri: uri,
			remoteAuthority
1085 1086 1087
		};
	}

1088
	private parsePath(anyPath: string, options?: IPathParseOptions): IPathToOpen | null {
E
Erich Gamma 已提交
1089 1090 1091 1092
		if (!anyPath) {
			return null;
		}

1093
		let parsedPath: IPathWithLineAndColumn;
1094 1095 1096

		const gotoLineMode = options && options.gotoLineMode;
		if (options && options.gotoLineMode) {
J
Joao Moreno 已提交
1097
			parsedPath = parseLineAndColumnAware(anyPath);
E
Erich Gamma 已提交
1098 1099 1100
			anyPath = parsedPath.path;
		}

M
Martin Aeschlimann 已提交
1101 1102 1103
		// 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;

1104
		const candidate = normalize(anyPath);
E
Erich Gamma 已提交
1105
		try {
B
Benjamin Pasero 已提交
1106
			const candidateStat = fs.statSync(candidate);
E
Erich Gamma 已提交
1107
			if (candidateStat) {
1108
				if (candidateStat.isFile()) {
1109

1110 1111
					// Workspace (unless disabled via flag)
					if (!options || !options.forceOpenWorkspaceAsFile) {
B
Benjamin Pasero 已提交
1112
						const workspace = this.workspacesMainService.resolveWorkspaceSync(candidate);
1113
						if (workspace) {
M
Martin Aeschlimann 已提交
1114
							return { workspace: { id: workspace.id, configPath: workspace.configPath }, remoteAuthority };
1115
						}
1116 1117 1118
					}

					// File
1119
					return {
1120
						fileUri: URI.file(candidate),
R
Rob Lourens 已提交
1121 1122
						lineNumber: gotoLineMode ? parsedPath.line : undefined,
						columnNumber: gotoLineMode ? parsedPath.column : undefined,
M
Martin Aeschlimann 已提交
1123
						remoteAuthority
1124 1125 1126
					};
				}

1127 1128 1129 1130 1131
				// 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 已提交
1132 1133
						folderUri: URI.file(candidate),
						remoteAuthority
1134 1135
					};
				}
E
Erich Gamma 已提交
1136 1137
			}
		} catch (error) {
S
Sandeep Somavarapu 已提交
1138
			this.historyMainService.removeFromRecentlyOpened([candidate]); // since file does not seem to exist anymore, remove from recent
1139

S
Sandeep Somavarapu 已提交
1140
			const fileUri = URI.file(candidate);
1141
			if (options && options.ignoreFileNotFound) {
M
Martin Aeschlimann 已提交
1142
				return { fileUri, createFilePath: true, remoteAuthority }; // assume this is a file that does not yet exist
E
Erich Gamma 已提交
1143 1144 1145 1146 1147 1148
			}
		}

		return null;
	}

B
Benjamin Pasero 已提交
1149 1150 1151
	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
1152
		const windowConfig = this.configurationService.getValue<IWindowSettings>('window');
1153 1154 1155
		const openFolderInNewWindowConfig = (windowConfig && windowConfig.openFoldersInNewWindow) || 'default' /* default */;
		const openFilesInNewWindowConfig = (windowConfig && windowConfig.openFilesInNewWindow) || 'off' /* default */;

B
Benjamin Pasero 已提交
1156
		let openFolderInNewWindow = (openConfig.preferNewWindow || openConfig.forceNewWindow) && !openConfig.forceReuseWindow;
1157 1158
		if (!openConfig.forceNewWindow && !openConfig.forceReuseWindow && (openFolderInNewWindowConfig === 'on' || openFolderInNewWindowConfig === 'off')) {
			openFolderInNewWindow = (openFolderInNewWindowConfig === 'on');
B
Benjamin Pasero 已提交
1159 1160 1161 1162 1163 1164 1165
		}

		// 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 {
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178

			// 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 已提交
1179 1180
			}

1181
			// finally check for overrides of default
1182 1183
			if (!openConfig.cli.extensionDevelopmentPath && (openFilesInNewWindowConfig === 'on' || openFilesInNewWindowConfig === 'off')) {
				openFilesInNewWindow = (openFilesInNewWindowConfig === 'on');
B
Benjamin Pasero 已提交
1184 1185 1186 1187 1188 1189
			}
		}

		return { openFolderInNewWindow, openFilesInNewWindow };
	}

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

B
Benjamin Pasero 已提交
1192 1193 1194
		// 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.
1195 1196 1197 1198
		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 已提交
1199

B
Benjamin Pasero 已提交
1200 1201
			return;
		}
1202 1203
		let folderUris = asArray(openConfig.cli['folder-uri']);
		let fileUris = asArray(openConfig.cli['file-uri']);
M
Martin Aeschlimann 已提交
1204
		let workspaceUris = asArray(openConfig.cli['workspace-uri']);
1205
		let cliArgs = openConfig.cli._;
E
Erich Gamma 已提交
1206

1207
		// Fill in previously opened workspace unless an explicit path is provided and we are not unit testing
1208
		if (!cliArgs.length && !folderUris.length && !fileUris.length && !openConfig.cli.extensionTestsPath) {
1209
			const extensionDevelopmentWindowState = this.windowsState.lastPluginDevelopmentHostWindow;
1210
			const workspaceToOpen = extensionDevelopmentWindowState && (extensionDevelopmentWindowState.workspace || extensionDevelopmentWindowState.folderUri);
1211
			if (workspaceToOpen) {
1212
				if (isSingleFolderWorkspaceIdentifier(workspaceToOpen)) {
1213
					if (workspaceToOpen.scheme === Schemas.file) {
1214
						cliArgs = [workspaceToOpen.fsPath];
1215
					} else {
1216
						folderUris = [workspaceToOpen.toString()];
1217 1218
					}
				} else {
M
Martin Aeschlimann 已提交
1219 1220 1221 1222 1223
					if (workspaceToOpen.configPath.scheme === Schemas.file) {
						cliArgs = [fsPath(workspaceToOpen.configPath)];
					} else {
						workspaceUris = [workspaceToOpen.configPath.toString()];
					}
1224
				}
E
Erich Gamma 已提交
1225 1226 1227
			}
		}

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

M
Martin Aeschlimann 已提交
1233
		if (folderUris.length && folderUris.some(uri => !!findWindowOnWorkspaceOrFolderUri(WindowsManager.WINDOWS, this.argToUri(uri)))) {
1234 1235 1236
			folderUris = [];
		}

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

M
Martin Aeschlimann 已提交
1241 1242 1243 1244
		if (workspaceUris.length && workspaceUris.some(uri => !!findWindowOnWorkspaceOrFolderUri(WindowsManager.WINDOWS, this.argToUri(uri)))) {
			workspaceUris = [];
		}

1245 1246 1247
		openConfig.cli._ = cliArgs;
		openConfig.cli['folder-uri'] = folderUris;
		openConfig.cli['file-uri'] = fileUris;
M
Martin Aeschlimann 已提交
1248
		openConfig.cli['workspace-uri'] = workspaceUris;
1249

B
Benjamin Pasero 已提交
1250
		// Open it
M
Martin Aeschlimann 已提交
1251
		this.open({ context: openConfig.context, cli: openConfig.cli, forceNewWindow: true, forceEmpty: !cliArgs.length && !folderUris.length && !fileUris.length && !workspaceUris.length, userEnv: openConfig.userEnv });
E
Erich Gamma 已提交
1252 1253
	}

1254
	private openInBrowserWindow(options: IOpenBrowserWindowOptions): ICodeWindow {
1255

B
Benjamin Pasero 已提交
1256 1257 1258
		// Build IWindowConfiguration from config and options
		const configuration: IWindowConfiguration = mixin({}, options.cli); // inherit all properties from CLI
		configuration.appRoot = this.environmentService.appRoot;
1259
		configuration.machineId = this.machineId;
1260
		configuration.nodeCachedDataDir = this.environmentService.nodeCachedDataDir;
1261
		configuration.mainPid = process.pid;
B
Benjamin Pasero 已提交
1262 1263 1264
		configuration.execPath = process.execPath;
		configuration.userEnv = assign({}, this.initialUserEnv, options.userEnv || {});
		configuration.isInitialStartup = options.initialStartup;
1265
		configuration.workspace = options.workspace;
1266
		configuration.folderUri = options.folderUri;
M
Martin Aeschlimann 已提交
1267
		configuration.remoteAuthority = options.remoteAuthority;
1268 1269 1270 1271 1272 1273 1274 1275

		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 已提交
1276

1277
		// if we know the backup folder upfront (for empty windows to restore), we can set it
1278
		// directly here which helps for restoring UI state associated with that window.
B
Benjamin Pasero 已提交
1279
		// For all other cases we first call into registerEmptyWindowBackupSync() to set it before
1280
		// loading the window.
1281 1282
		if (options.emptyWindowBackupInfo) {
			configuration.backupPath = join(this.environmentService.backupHome, options.emptyWindowBackupInfo.backupFolder);
1283 1284
		}

1285
		let window: ICodeWindow | undefined;
1286
		if (!options.forceNewWindow && !options.forceNewTabbedWindow) {
1287 1288 1289
			window = options.windowToUse || this.getLastActiveWindow();
			if (window) {
				window.focus();
E
Erich Gamma 已提交
1290 1291 1292 1293
			}
		}

		// New window
1294
		if (!window) {
1295
			const windowConfig = this.configurationService.getValue<IWindowSettings>('window');
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
			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 {
1306
				allowFullscreen = this.lifecycleService.wasRestarted || (windowConfig && windowConfig.restoreFullscreen);
1307 1308 1309 1310 1311
			}

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

1313
			// Create the window
1314
			window = this.instantiationService.createInstance(CodeWindow, {
1315
				state,
1316
				extensionDevelopmentPath: configuration.extensionDevelopmentPath,
1317
				isExtensionTestHost: !!configuration.extensionTestsPath
1318
			});
1319

1320 1321 1322 1323 1324 1325 1326 1327
			// Add as window tab if configured (macOS only)
			if (options.forceNewTabbedWindow) {
				const activeWindow = this.getLastActiveWindow();
				if (activeWindow) {
					activeWindow.addTabbedWindow(window);
				}
			}

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

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

E
Erich Gamma 已提交
1334
			// Window Events
1335 1336 1337 1338 1339
			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 已提交
1340 1341

			// Lifecycle
B
Benjamin Pasero 已提交
1342
			(this.lifecycleService as LifecycleService).registerWindow(window);
E
Erich Gamma 已提交
1343 1344 1345 1346 1347 1348
		}

		// Existing window
		else {

			// Some configuration things get inherited if the window is being reused and we are
B
Benjamin Pasero 已提交
1349
			// in extension development host mode. These options are all development related.
1350
			const currentWindowConfig = window.config;
A
Alex Dima 已提交
1351 1352
			if (!configuration.extensionDevelopmentPath && currentWindowConfig && !!currentWindowConfig.extensionDevelopmentPath) {
				configuration.extensionDevelopmentPath = currentWindowConfig.extensionDevelopmentPath;
B
Benjamin Pasero 已提交
1353
				configuration.verbose = currentWindowConfig.verbose;
1354
				configuration.debugBrkPluginHost = currentWindowConfig.debugBrkPluginHost;
1355
				configuration.debugId = currentWindowConfig.debugId;
1356
				configuration.debugPluginHost = currentWindowConfig.debugPluginHost;
1357
				configuration['extensions-dir'] = currentWindowConfig['extensions-dir'];
E
Erich Gamma 已提交
1358 1359 1360
			}
		}

1361 1362 1363 1364 1365 1366 1367
		// 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 已提交
1368
				}
1369 1370 1371 1372 1373 1374 1375
			});
		} else {
			this.doOpenInBrowserWindow(window, configuration, options);
		}

		return window;
	}
B
Benjamin Pasero 已提交
1376

1377
	private doOpenInBrowserWindow(window: ICodeWindow, configuration: IWindowConfiguration, options: IOpenBrowserWindowOptions): void {
1378

1379 1380 1381 1382 1383 1384 1385 1386 1387
		// 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 已提交
1388
			}
1389
		}
1390

1391 1392 1393 1394 1395
		// Load it
		window.load(configuration);

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

1398
	private getNewWindowState(configuration: IWindowConfiguration): INewWindowState {
1399
		const lastActive = this.getLastActiveWindow();
E
Erich Gamma 已提交
1400

1401 1402
		// Restore state unless we are running extension tests
		if (!configuration.extensionTestsPath) {
E
Erich Gamma 已提交
1403

1404 1405 1406
			// extension development host Window - load from stored settings if any
			if (!!configuration.extensionDevelopmentPath && this.windowsState.lastPluginDevelopmentHostWindow) {
				return this.windowsState.lastPluginDevelopmentHostWindow.uiState;
1407 1408
			}

1409 1410 1411 1412 1413 1414 1415 1416 1417
			// 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
1418
			if (configuration.folderUri) {
1419
				const stateForFolder = this.windowsState.openedWindows.filter(o => o.folderUri && isEqual(o.folderUri, configuration.folderUri)).map(o => o.uiState);
1420 1421 1422
				if (stateForFolder.length) {
					return stateForFolder[0];
				}
1423 1424
			}

1425 1426 1427 1428 1429 1430
			// 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 已提交
1431 1432
			}

1433 1434 1435 1436 1437
			// First Window
			const lastActiveState = this.lastClosedWindowState || this.windowsState.lastActiveWindow;
			if (!lastActive && lastActiveState) {
				return lastActiveState.uiState;
			}
E
Erich Gamma 已提交
1438 1439 1440 1441 1442 1443 1444
		}

		//
		// 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
1445
		let displayToUse: Electron.Display | undefined;
B
Benjamin Pasero 已提交
1446
		const displays = screen.getAllDisplays();
E
Erich Gamma 已提交
1447 1448 1449 1450 1451 1452 1453 1454 1455 1456

		// 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 已提交
1457
			if (isMacintosh) {
B
Benjamin Pasero 已提交
1458
				const cursorPoint = screen.getCursorScreenPoint();
E
Erich Gamma 已提交
1459 1460 1461 1462 1463 1464 1465 1466
				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());
			}

1467
			// fallback to primary display or first display
E
Erich Gamma 已提交
1468
			if (!displayToUse) {
1469
				displayToUse = screen.getPrimaryDisplay() || displays[0];
E
Erich Gamma 已提交
1470 1471 1472
			}
		}

1473 1474 1475
		// 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.
1476
		let state = defaultWindowState() as INewWindowState;
1477 1478
		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 已提交
1479

1480
		// Check for newWindowDimensions setting and adjust accordingly
1481
		const windowConfig = this.configurationService.getValue<IWindowSettings>('window');
1482 1483 1484 1485 1486 1487 1488 1489 1490
		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 已提交
1491 1492 1493 1494 1495 1496 1497
				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;
				}

1498 1499 1500 1501 1502 1503 1504 1505
				ensureNoOverlap = false;
			}
		}

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

1506 1507
		state.hasDefaultState = true; // flag as default state

1508
		return state;
E
Erich Gamma 已提交
1509 1510
	}

J
Joao Moreno 已提交
1511
	private ensureNoOverlap(state: ISingleWindowState): ISingleWindowState {
E
Erich Gamma 已提交
1512 1513 1514 1515
		if (WindowsManager.WINDOWS.length === 0) {
			return state;
		}

1516 1517
		const existingWindowBounds = WindowsManager.WINDOWS.map(win => win.getBounds());
		while (existingWindowBounds.some(b => b.x === state.x || b.y === state.y)) {
E
Erich Gamma 已提交
1518 1519 1520 1521 1522 1523 1524
			state.x += 30;
			state.y += 30;
		}

		return state;
	}

B
Benjamin Pasero 已提交
1525
	reload(win: ICodeWindow, cli?: ParsedArgs): void {
B
Benjamin Pasero 已提交
1526 1527

		// Only reload when the window has not vetoed this
1528
		this.lifecycleService.unload(win, UnloadReason.RELOAD).then(veto => {
B
Benjamin Pasero 已提交
1529
			if (!veto) {
R
Rob Lourens 已提交
1530
				win.reload(undefined, cli);
B
Benjamin Pasero 已提交
1531 1532 1533 1534
			}
		});
	}

B
Benjamin Pasero 已提交
1535
	closeWorkspace(win: ICodeWindow): void {
1536 1537
		this.openInBrowserWindow({
			cli: this.environmentService.args,
M
Martin Aeschlimann 已提交
1538 1539
			windowToUse: win,
			remoteAuthority: win.remoteAuthority
1540 1541 1542
		});
	}

M
Martin Aeschlimann 已提交
1543
	enterWorkspace(win: ICodeWindow, path: URI): Promise<IEnterWorkspaceResult> {
1544 1545 1546
		return this.workspacesManager.enterWorkspace(win, path).then(result => this.doEnterWorkspace(win, result));
	}

1547
	private doEnterWorkspace(win: ICodeWindow, result: IEnterWorkspaceResult): IEnterWorkspaceResult {
1548

1549
		// Mark as recently opened
B
Benjamin Pasero 已提交
1550
		this.historyMainService.addRecentlyOpened([result.workspace], []);
1551

1552 1553 1554
		// Trigger Eevent to indicate load of workspace into window
		this._onWindowReady.fire(win);

1555
		return result;
1556 1557
	}

B
Benjamin Pasero 已提交
1558
	pickWorkspaceAndOpen(options: INativeOpenDialogOptions): void {
1559
		this.workspacesManager.pickWorkspaceAndOpen(options);
1560 1561 1562
	}

	private onBeforeWindowUnload(e: IWindowUnloadEvent): void {
1563 1564
		const windowClosing = (e.reason === UnloadReason.CLOSE);
		const windowLoading = (e.reason === UnloadReason.LOAD);
1565 1566 1567 1568 1569
		if (!windowClosing && !windowLoading) {
			return; // only interested when window is closing or loading
		}

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

1574
		if (e.window.config && !!e.window.config.extensionDevelopmentPath) {
1575 1576 1577 1578
			// do not ask to save workspace when doing extension development
			// but still delete it.
			this.workspacesMainService.deleteUntitledWorkspaceSync(workspace);
			return;
1579 1580
		}

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

1585
		// Handle untitled workspaces with prompt as needed
B
Benjamin Pasero 已提交
1586 1587 1588 1589 1590 1591 1592 1593 1594
		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
1595
			return timeout(0).then(() => veto);
B
Benjamin Pasero 已提交
1596
		}));
1597 1598
	}

B
Benjamin Pasero 已提交
1599
	focusLastActive(cli: ParsedArgs, context: OpenContext): ICodeWindow {
B
Benjamin Pasero 已提交
1600
		const lastActive = this.getLastActiveWindow();
E
Erich Gamma 已提交
1601
		if (lastActive) {
B
Benjamin Pasero 已提交
1602
			lastActive.focus();
1603 1604

			return lastActive;
E
Erich Gamma 已提交
1605 1606
		}

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

B
Benjamin Pasero 已提交
1611
	getLastActiveWindow(): ICodeWindow {
1612
		return getLastActiveWindow(WindowsManager.WINDOWS);
E
Erich Gamma 已提交
1613 1614
	}

M
Martin Aeschlimann 已提交
1615 1616 1617 1618
	getLastActiveWindowForAuthority(remoteAuthority: string): ICodeWindow {
		return getLastActiveWindow(WindowsManager.WINDOWS.filter(w => w.remoteAuthority === remoteAuthority));
	}

1619 1620
	openNewWindow(context: OpenContext, options?: INewWindowOptions): ICodeWindow[] {
		let cli = this.environmentService.args;
R
Rob Lourens 已提交
1621
		let remote = options && options.remoteAuthority || undefined;
M
Martin Aeschlimann 已提交
1622 1623 1624
		if (cli && (cli.remote !== remote)) {
			cli = { ...cli, remote };
		}
1625
		return this.open({ context, cli, forceNewWindow: true, forceEmpty: true });
E
Erich Gamma 已提交
1626 1627
	}

1628 1629 1630 1631
	openNewTabbedWindow(context: OpenContext): ICodeWindow[] {
		return this.open({ context, cli: this.environmentService.args, forceNewTabbedWindow: true, forceEmpty: true });
	}

J
Johannes Rieken 已提交
1632
	waitForWindowCloseOrLoad(windowId: number): Promise<void> {
B
Benjamin Pasero 已提交
1633
		return new Promise<void>(resolve => {
1634
			function handler(id: number) {
1635
				if (id === windowId) {
1636 1637 1638
					closeListener.dispose();
					loadListener.dispose();

1639
					resolve();
1640
				}
1641 1642 1643 1644
			}

			const closeListener = this.onWindowClose(id => handler(id));
			const loadListener = this.onWindowLoad(id => handler(id));
1645 1646 1647
		});
	}

B
Benjamin Pasero 已提交
1648
	sendToFocused(channel: string, ...args: any[]): void {
E
Erich Gamma 已提交
1649 1650 1651
		const focusedWindow = this.getFocusedWindow() || this.getLastActiveWindow();

		if (focusedWindow) {
1652
			focusedWindow.sendWhenReady(channel, ...args);
E
Erich Gamma 已提交
1653 1654 1655
		}
	}

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

1662
			w.sendWhenReady(channel, payload);
E
Erich Gamma 已提交
1663 1664 1665
		});
	}

B
Benjamin Pasero 已提交
1666
	getFocusedWindow(): ICodeWindow {
B
Benjamin Pasero 已提交
1667
		const win = BrowserWindow.getFocusedWindow();
E
Erich Gamma 已提交
1668 1669 1670 1671 1672 1673 1674
		if (win) {
			return this.getWindowById(win.id);
		}

		return null;
	}

B
Benjamin Pasero 已提交
1675
	getWindowById(windowId: number): ICodeWindow {
1676
		const res = WindowsManager.WINDOWS.filter(w => w.id === windowId);
E
Erich Gamma 已提交
1677 1678 1679 1680 1681 1682 1683
		if (res && res.length === 1) {
			return res[0];
		}

		return null;
	}

B
Benjamin Pasero 已提交
1684
	getWindows(): ICodeWindow[] {
E
Erich Gamma 已提交
1685 1686 1687
		return WindowsManager.WINDOWS;
	}

B
Benjamin Pasero 已提交
1688
	getWindowCount(): number {
E
Erich Gamma 已提交
1689 1690 1691
		return WindowsManager.WINDOWS.length;
	}

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

1695 1696
		/* __GDPR__
			"windowerror" : {
K
kieferrm 已提交
1697
				"type" : { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth", "isMeasurement": true }
1698 1699 1700 1701
			}
		*/
		this.telemetryService.publicLog('windowerror', { type: error });

E
Erich Gamma 已提交
1702 1703
		// Unresponsive
		if (error === WindowError.UNRESPONSIVE) {
1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714
			if (window.isExtensionDevelopmentHost || window.isExtensionTestHost || (window.win && window.win.webContents && window.win.webContents.isDevToolsOpened())) {
				// TODO@Ben Workaround for https://github.com/Microsoft/vscode/issues/56994
				// In certain cases the window can report unresponsiveness because a breakpoint was hit
				// and the process is stopped executing. The most typical cases are:
				// - devtools are opened and debugging happens
				// - window is an extensions development host that is being debugged
				// - window is an extension test development host that is being debugged
				return;
			}

			// Show Dialog
1715
			this.dialogs.showMessageBox({
B
Benjamin Pasero 已提交
1716
				title: product.nameLong,
E
Erich Gamma 已提交
1717
				type: 'warning',
1718
				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"))],
1719 1720
				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 已提交
1721
				noLink: true
1722 1723 1724 1725
			}, window).then(result => {
				if (!window.win) {
					return; // Return early if the window has been going down already
				}
1726

1727 1728 1729 1730 1731 1732 1733
				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 已提交
1734 1735 1736 1737
		}

		// Crashed
		else {
1738
			this.dialogs.showMessageBox({
B
Benjamin Pasero 已提交
1739
				title: product.nameLong,
E
Erich Gamma 已提交
1740
				type: 'warning',
1741
				buttons: [mnemonicButtonLabel(localize({ key: 'reopen', comment: ['&& denotes a mnemonic'] }, "&&Reopen")), mnemonicButtonLabel(localize({ key: 'close', comment: ['&& denotes a mnemonic'] }, "&&Close"))],
1742 1743
				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 已提交
1744
				noLink: true
1745 1746 1747 1748
			}, window).then(result => {
				if (!window.win) {
					return; // Return early if the window has been going down already
				}
1749

1750 1751 1752 1753 1754 1755 1756
				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 已提交
1757 1758 1759
		}
	}

1760
	private onWindowClosed(win: ICodeWindow): void {
E
Erich Gamma 已提交
1761 1762 1763 1764 1765

		// Tell window
		win.dispose();

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

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

B
Benjamin Pasero 已提交
1774
	pickFileFolderAndOpen(options: INativeOpenDialogOptions): void {
B
Benjamin Pasero 已提交
1775
		this.doPickAndOpen(options, true /* pick folders */, true /* pick files */);
1776 1777
	}

B
Benjamin Pasero 已提交
1778
	pickFolderAndOpen(options: INativeOpenDialogOptions): void {
B
Benjamin Pasero 已提交
1779
		this.doPickAndOpen(options, true /* pick folders */, false /* pick files */);
1780 1781
	}

B
Benjamin Pasero 已提交
1782
	pickFileAndOpen(options: INativeOpenDialogOptions): void {
B
Benjamin Pasero 已提交
1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807
		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 已提交
1808
				// __GDPR__TODO__ classify event
B
Benjamin Pasero 已提交
1809 1810 1811 1812 1813 1814 1815 1816
				internalOptions.telemetryEventName = 'openFileFolder';
			} else if (pickFolders) {
				internalOptions.telemetryEventName = 'openFolder';
			} else {
				internalOptions.telemetryEventName = 'openFile';
			}
		}

1817 1818 1819
		this.dialogs.pickAndOpen(internalOptions);
	}

J
Johannes Rieken 已提交
1820
	showMessageBox(options: Electron.MessageBoxOptions, win?: ICodeWindow): Promise<IMessageBoxResult> {
1821 1822 1823
		return this.dialogs.showMessageBox(options, win);
	}

J
Johannes Rieken 已提交
1824
	showSaveDialog(options: Electron.SaveDialogOptions, win?: ICodeWindow): Promise<string> {
1825 1826 1827
		return this.dialogs.showSaveDialog(options, win);
	}

J
Johannes Rieken 已提交
1828
	showOpenDialog(options: Electron.OpenDialogOptions, win?: ICodeWindow): Promise<string[]> {
1829
		return this.dialogs.showOpenDialog(options, win);
B
Benjamin Pasero 已提交
1830 1831
	}

B
Benjamin Pasero 已提交
1832
	quit(): void {
B
Benjamin Pasero 已提交
1833 1834 1835

		// 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.
1836 1837 1838
		const window = this.getFocusedWindow();
		if (window && window.isExtensionDevelopmentHost && this.getWindowCount() > 1) {
			window.win.close();
B
Benjamin Pasero 已提交
1839 1840 1841 1842 1843 1844 1845 1846
		}

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

B
Benjamin Pasero 已提交
1850
interface IInternalNativeOpenDialogOptions extends INativeOpenDialogOptions {
B
Benjamin Pasero 已提交
1851 1852 1853 1854
	pickFolders?: boolean;
	pickFiles?: boolean;
}

1855
class Dialogs {
B
Benjamin Pasero 已提交
1856

1857
	private static readonly workingDirPickerStorageKey = 'pickerWorkingDir';
1858

1859 1860 1861
	private mapWindowToDialogQueue: Map<number, Queue<any>>;
	private noWindowDialogQueue: Queue<any>;

B
Benjamin Pasero 已提交
1862 1863 1864
	constructor(
		private environmentService: IEnvironmentService,
		private telemetryService: ITelemetryService,
B
Benjamin Pasero 已提交
1865
		private stateService: IStateService,
B
Benjamin Pasero 已提交
1866
		private windowsMainService: IWindowsMainService,
B
Benjamin Pasero 已提交
1867
	) {
1868 1869
		this.mapWindowToDialogQueue = new Map<number, Queue<any>>();
		this.noWindowDialogQueue = new Queue<any>();
B
Benjamin Pasero 已提交
1870 1871
	}

B
Benjamin Pasero 已提交
1872
	pickAndOpen(options: INativeOpenDialogOptions): void {
1873
		this.getFileOrFolderUris(options).then(paths => {
B
Benjamin Pasero 已提交
1874 1875 1876 1877
			const numberOfPaths = paths ? paths.length : 0;

			// Telemetry
			if (options.telemetryEventName) {
K
kieferrm 已提交
1878
				// __GDPR__TODO__ Dynamic event names and dynamic properties. Can not be registered statically.
B
Benjamin Pasero 已提交
1879 1880 1881 1882 1883 1884 1885 1886 1887
				this.telemetryService.publicLog(options.telemetryEventName, {
					...options.telemetryExtraData,
					outcome: numberOfPaths ? 'success' : 'canceled',
					numberOfPaths
				});
			}

			// Open
			if (numberOfPaths) {
1888 1889
				this.windowsMainService.open({
					context: OpenContext.DIALOG,
B
Benjamin Pasero 已提交
1890
					contextWindowId: options.windowId,
1891
					cli: this.environmentService.args,
S
Sandeep Somavarapu 已提交
1892
					urisToOpen: paths,
1893 1894 1895
					forceNewWindow: options.forceNewWindow,
					forceOpenWorkspaceAsFile: options.dialogOptions && !equals(options.dialogOptions.filters, WORKSPACE_FILTER)
				});
1896 1897 1898 1899
			}
		});
	}

J
Johannes Rieken 已提交
1900
	private getFileOrFolderUris(options: IInternalNativeOpenDialogOptions): Promise<URI[]> {
1901

B
Benjamin Pasero 已提交
1902 1903 1904 1905 1906 1907 1908
		// Ensure dialog options
		if (!options.dialogOptions) {
			options.dialogOptions = Object.create(null);
		}

		// Ensure defaultPath
		if (!options.dialogOptions.defaultPath) {
1909
			options.dialogOptions.defaultPath = this.stateService.getItem<string>(Dialogs.workingDirPickerStorageKey);
1910 1911
		}

B
Benjamin Pasero 已提交
1912 1913
		// Ensure properties
		if (typeof options.pickFiles === 'boolean' || typeof options.pickFolders === 'boolean') {
R
Rob Lourens 已提交
1914
			options.dialogOptions.properties = undefined; // let it override based on the booleans
B
Benjamin Pasero 已提交
1915 1916 1917 1918 1919 1920 1921 1922 1923 1924

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

1925 1926 1927 1928
		if (isMacintosh) {
			options.dialogOptions.properties.push('treatPackageAsDirectory'); // always drill into .app files
		}

B
Benjamin Pasero 已提交
1929
		// Show Dialog
1930
		const focusedWindow = this.windowsMainService.getWindowById(options.windowId) || this.windowsMainService.getFocusedWindow();
1931 1932 1933 1934 1935 1936 1937

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

1938
				return paths.map(path => URI.file(path));
1939 1940
			}

R
Rob Lourens 已提交
1941
			return undefined;
1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958
		});
	}

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

J
Johannes Rieken 已提交
1959
	showMessageBox(options: Electron.MessageBoxOptions, window?: ICodeWindow): Promise<IMessageBoxResult> {
1960
		return this.getDialogQueue(window).queue(() => {
B
Benjamin Pasero 已提交
1961
			return new Promise(resolve => {
R
Rob Lourens 已提交
1962
				dialog.showMessageBox(window ? window.win : undefined, options, (response: number, checkboxChecked: boolean) => {
B
Benjamin Pasero 已提交
1963
					resolve({ button: response, checkboxChecked });
B
Benjamin Pasero 已提交
1964
				});
1965 1966 1967 1968
			});
		});
	}

J
Johannes Rieken 已提交
1969
	showSaveDialog(options: Electron.SaveDialogOptions, window?: ICodeWindow): Promise<string> {
B
Benjamin Pasero 已提交
1970

1971 1972 1973
		function normalizePath(path: string): string {
			if (path && isMacintosh) {
				path = normalizeNFC(path); // normalize paths returned from the OS
1974
			}
1975

1976 1977
			return path;
		}
1978

1979
		return this.getDialogQueue(window).queue(() => {
B
Benjamin Pasero 已提交
1980
			return new Promise(resolve => {
R
Rob Lourens 已提交
1981
				dialog.showSaveDialog(window ? window.win : undefined, options, path => {
B
Benjamin Pasero 已提交
1982
					resolve(normalizePath(path));
B
Benjamin Pasero 已提交
1983
				});
1984 1985 1986 1987
			});
		});
	}

J
Johannes Rieken 已提交
1988
	showOpenDialog(options: Electron.OpenDialogOptions, window?: ICodeWindow): Promise<string[]> {
B
Benjamin Pasero 已提交
1989

1990 1991 1992 1993 1994 1995
		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;
1996
		}
B
Benjamin Pasero 已提交
1997

1998
		return this.getDialogQueue(window).queue(() => {
B
Benjamin Pasero 已提交
1999
			return new Promise(resolve => {
B
Benjamin Pasero 已提交
2000 2001

				// Ensure the path exists (if provided)
B
Benjamin Pasero 已提交
2002
				let validatePathPromise: Promise<void> = Promise.resolve();
B
Benjamin Pasero 已提交
2003 2004 2005
				if (options.defaultPath) {
					validatePathPromise = exists(options.defaultPath).then(exists => {
						if (!exists) {
R
Rob Lourens 已提交
2006
							options.defaultPath = undefined;
B
Benjamin Pasero 已提交
2007 2008 2009 2010 2011 2012
						}
					});
				}

				// Show dialog and wrap as promise
				validatePathPromise.then(() => {
R
Rob Lourens 已提交
2013
					dialog.showOpenDialog(window ? window.win : undefined, options, paths => {
B
Benjamin Pasero 已提交
2014
						resolve(normalizePaths(paths));
B
Benjamin Pasero 已提交
2015
					});
B
Benjamin Pasero 已提交
2016
				});
2017 2018
			});
		});
2019
	}
2020 2021 2022 2023 2024
}

class WorkspacesManager {

	constructor(
2025 2026
		private workspacesMainService: IWorkspacesMainService,
		private backupMainService: IBackupMainService,
2027
		private environmentService: IEnvironmentService,
2028 2029
		private historyMainService: IHistoryMainService,
		private windowsMainService: IWindowsMainService,
2030 2031 2032
	) {
	}

M
Martin Aeschlimann 已提交
2033
	enterWorkspace(window: ICodeWindow, path: URI): Promise<IEnterWorkspaceResult | null> {
B
Benjamin Pasero 已提交
2034
		if (!window || !window.win || !window.isReady) {
B
Benjamin Pasero 已提交
2035
			return Promise.resolve(null); // return early if the window is not ready or disposed
2036 2037 2038 2039
		}

		return this.isValidTargetWorkspacePath(window, path).then(isValid => {
			if (!isValid) {
B
Benjamin Pasero 已提交
2040
				return null; // return early if the workspace is not valid
2041
			}
M
Martin Aeschlimann 已提交
2042 2043
			const workspaceIdentifier = this.workspacesMainService.getWorkspaceIdentifier(path);
			return this.doOpenWorkspace(window, workspaceIdentifier);
2044 2045 2046 2047
		});

	}

M
Martin Aeschlimann 已提交
2048
	private isValidTargetWorkspacePath(window: ICodeWindow, path?: URI): Promise<boolean> {
2049
		if (!path) {
B
Benjamin Pasero 已提交
2050
			return Promise.resolve(true);
2051 2052
		}

M
Martin Aeschlimann 已提交
2053
		if (window.openedWorkspace && isEqual(window.openedWorkspace.configPath, path)) {
B
Benjamin Pasero 已提交
2054
			return Promise.resolve(false); // window is already opened on a workspace with that path
2055 2056 2057
		}

		// Prevent overwriting a workspace that is currently opened in another window
M
Martin Aeschlimann 已提交
2058
		if (findWindowOnWorkspace(this.windowsMainService.getWindows(), this.workspacesMainService.getWorkspaceIdentifier(path))) {
2059 2060 2061 2062
			const options: Electron.MessageBoxOptions = {
				title: product.nameLong,
				type: 'info',
				buttons: [localize('ok', "OK")],
M
Martin Aeschlimann 已提交
2063
				message: localize('workspaceOpenedMessage', "Unable to save workspace '{0}'", resourcesBasename(path)),
2064
				detail: localize('workspaceOpenedDetail', "The workspace is already opened in another window. Please close that window first and then try again."),
2065 2066 2067
				noLink: true
			};

2068
			return this.windowsMainService.showMessageBox(options, this.windowsMainService.getFocusedWindow()).then(() => false);
2069 2070
		}

B
Benjamin Pasero 已提交
2071
		return Promise.resolve(true); // OK
2072 2073
	}

2074 2075
	private doOpenWorkspace(window: ICodeWindow, workspace: IWorkspaceIdentifier): IEnterWorkspaceResult {
		window.focus();
2076

2077
		// Register window for backups and migrate current backups over
2078
		let backupPath: string | undefined;
2079 2080 2081
		if (!window.config.extensionDevelopmentPath) {
			backupPath = this.backupMainService.registerWorkspaceBackupSync(workspace, window.config.backupPath);
		}
2082

2083 2084 2085 2086 2087
		// if the window was opened on an untitled workspace, delete it.
		if (window.openedWorkspace && this.workspacesMainService.isUntitledWorkspace(window.openedWorkspace)) {
			this.workspacesMainService.deleteUntitledWorkspaceSync(window.openedWorkspace);
		}

2088
		// Update window configuration properly based on transition to workspace
R
Rob Lourens 已提交
2089
		window.config.folderUri = undefined;
2090 2091 2092 2093
		window.config.workspace = workspace;
		window.config.backupPath = backupPath;

		return { workspace, backupPath };
2094 2095
	}

B
Benjamin Pasero 已提交
2096
	pickWorkspaceAndOpen(options: INativeOpenDialogOptions): void {
2097
		const window = this.windowsMainService.getWindowById(options.windowId) || this.windowsMainService.getFocusedWindow() || this.windowsMainService.getLastActiveWindow();
2098 2099

		this.windowsMainService.pickFileAndOpen({
R
Rob Lourens 已提交
2100
			windowId: window ? window.id : undefined,
2101 2102 2103 2104 2105
			dialogOptions: {
				buttonLabel: mnemonicButtonLabel(localize({ key: 'openWorkspace', comment: ['&& denotes a mnemonic'] }, "&&Open")),
				title: localize('openWorkspaceTitle', "Open Workspace"),
				filters: WORKSPACE_FILTER,
				properties: ['openFile'],
2106
				defaultPath: options.dialogOptions && options.dialogOptions.defaultPath
2107
			},
2108 2109 2110
			forceNewWindow: options.forceNewWindow,
			telemetryEventName: options.telemetryEventName,
			telemetryExtraData: options.telemetryExtraData
2111 2112 2113
		});
	}

J
Johannes Rieken 已提交
2114
	promptToSaveUntitledWorkspace(window: ICodeWindow, workspace: IWorkspaceIdentifier): Promise<boolean> {
2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147
		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;
		}

2148 2149 2150 2151 2152 2153 2154 2155 2156
		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:
2157
					this.workspacesMainService.deleteUntitledWorkspaceSync(workspace);
2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168
					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) {
2169
							return this.workspacesMainService.saveWorkspaceAs(workspace, target).then(savedWorkspace => {
2170
								this.historyMainService.addRecentlyOpened([savedWorkspace], []);
2171
								this.workspacesMainService.deleteUntitledWorkspaceSync(workspace);
2172
								return false;
B
Benjamin Pasero 已提交
2173
							}, () => false);
2174
						}
2175

2176 2177
						return true; // keep veto if no target was provided
					});
2178 2179
				}
			}
2180
		});
2181 2182
	}

2183
	private getUntitledWorkspaceSaveDialogDefaultPath(workspace?: IWorkspaceIdentifier | ISingleFolderWorkspaceIdentifier): string | undefined {
2184
		if (workspace) {
2185
			if (isSingleFolderWorkspaceIdentifier(workspace)) {
R
Rob Lourens 已提交
2186
				return workspace.scheme === Schemas.file ? dirname(workspace.fsPath) : undefined;
J
Johannes Rieken 已提交
2187 2188
			}

M
Martin Aeschlimann 已提交
2189
			const resolvedWorkspace = workspace.configPath.scheme === Schemas.file && this.workspacesMainService.resolveWorkspaceSync(workspace.configPath.fsPath);
J
Johannes Rieken 已提交
2190 2191 2192 2193 2194
			if (resolvedWorkspace && resolvedWorkspace.folders.length > 0) {
				for (const folder of resolvedWorkspace.folders) {
					if (folder.uri.scheme === Schemas.file) {
						return dirname(folder.uri.fsPath);
					}
2195 2196 2197
				}
			}
		}
2198

R
Rob Lourens 已提交
2199
		return undefined;
2200
	}
J
Johannes Rieken 已提交
2201
}