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

'use strict';

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

enum WindowError {
	UNRESPONSIVE,
	CRASHED
}

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

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

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

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

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

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

74
	workspace?: IWorkspaceIdentifier;
75
	folderUri?: URI;
B
Benjamin Pasero 已提交
76 77 78 79 80 81

	initialStartup?: boolean;

	filesToOpen?: IPath[];
	filesToCreate?: IPath[];
	filesToDiff?: IPath[];
82
	filesToWait?: IPathsToWaitFor;
B
Benjamin Pasero 已提交
83 84

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

88
	emptyWindowBackupFolder?: string;
B
Benjamin Pasero 已提交
89 90
}

B
Benjamin Pasero 已提交
91
interface IPathToOpen extends IPath {
92

93
	// the workspace for a Code instance to open
94
	workspace?: IWorkspaceIdentifier;
95

96
	// the folder path for a Code instance to open
97
	folderUri?: URI;
98 99 100 101 102 103 104 105

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

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

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

108
	_serviceBrand: any;
E
Erich Gamma 已提交
109

110
	private static readonly windowsStateStorageKey = 'windowsState';
E
Erich Gamma 已提交
111

112
	private static WINDOWS: ICodeWindow[] = [];
E
Erich Gamma 已提交
113

B
Benjamin Pasero 已提交
114
	private initialUserEnv: IProcessEnvironment;
115

E
Erich Gamma 已提交
116
	private windowsState: IWindowsState;
117
	private lastClosedWindowState: IWindowState;
E
Erich Gamma 已提交
118

119
	private dialogs: Dialogs;
120
	private workspacesManager: WorkspacesManager;
B
Benjamin Pasero 已提交
121

122 123
	private _onWindowReady = new Emitter<ICodeWindow>();
	onWindowReady: CommonEvent<ICodeWindow> = this._onWindowReady.event;
124 125 126 127

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

128 129 130
	private _onWindowLoad = new Emitter<number>();
	onWindowLoad: CommonEvent<number> = this._onWindowLoad.event;

131 132
	private _onActiveWindowChanged = new Emitter<ICodeWindow>();
	onActiveWindowChanged: CommonEvent<ICodeWindow> = this._onActiveWindowChanged.event;
133

134 135 136
	private _onWindowReload = new Emitter<number>();
	onWindowReload: CommonEvent<number> = this._onWindowReload.event;

B
Benjamin Pasero 已提交
137 138 139
	private _onWindowsCountChanged = new Emitter<IWindowsCountChangedEvent>();
	onWindowsCountChanged: CommonEvent<IWindowsCountChangedEvent> = this._onWindowsCountChanged.event;

J
Joao Moreno 已提交
140
	constructor(
B
Benjamin Pasero 已提交
141
		private readonly machineId: string,
J
Joao Moreno 已提交
142
		@ILogService private logService: ILogService,
B
Benjamin Pasero 已提交
143
		@IStateService private stateService: IStateService,
144
		@IEnvironmentService private environmentService: IEnvironmentService,
B
Benjamin Pasero 已提交
145
		@ILifecycleService private lifecycleService: ILifecycleService,
B
Benjamin Pasero 已提交
146
		@IBackupMainService private backupMainService: IBackupMainService,
B
Benjamin Pasero 已提交
147
		@ITelemetryService telemetryService: ITelemetryService,
148
		@IConfigurationService private configurationService: IConfigurationService,
B
Benjamin Pasero 已提交
149 150
		@IHistoryMainService private historyMainService: IHistoryMainService,
		@IWorkspacesMainService private workspacesMainService: IWorkspacesMainService,
151
		@IInstantiationService private instantiationService: IInstantiationService
152
	) {
153
		this.windowsState = this.getWindowsState();
154 155 156
		if (!Array.isArray(this.windowsState.openedWindows)) {
			this.windowsState.openedWindows = [];
		}
157

B
Benjamin Pasero 已提交
158
		this.dialogs = new Dialogs(environmentService, telemetryService, stateService, this);
B
Benjamin Pasero 已提交
159
		this.workspacesManager = new WorkspacesManager(workspacesMainService, backupMainService, environmentService, this);
160
	}
J
Joao Moreno 已提交
161

162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
	private getWindowsState(): IWindowsState {
		const windowsState = this.stateService.getItem<IWindowsState>(WindowsManager.windowsStateStorageKey) || { openedWindows: [] };
		if (windowsState.lastActiveWindow) {
			windowsState.lastActiveWindow = this.revive(windowsState.lastActiveWindow);
		}
		if (windowsState.lastPluginDevelopmentHostWindow) {
			windowsState.lastPluginDevelopmentHostWindow = this.revive(windowsState.lastPluginDevelopmentHostWindow);
		}
		if (windowsState.openedWindows) {
			windowsState.openedWindows = windowsState.openedWindows.map(windowState => this.revive(windowState));
		}
		return windowsState;
	}

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

B
Benjamin Pasero 已提交
186
	ready(initialUserEnv: IProcessEnvironment): void {
187
		this.initialUserEnv = initialUserEnv;
188 189

		this.registerListeners();
E
Erich Gamma 已提交
190 191 192
	}

	private registerListeners(): void {
193

194 195 196 197 198 199 200
		// React to windows focus changes
		app.on('browser-window-focus', () => {
			setTimeout(() => {
				this._onActiveWindowChanged.fire(this.getLastActiveWindow());
			});
		});

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

B
Benjamin Pasero 已提交
205
			const win = this.getWindowById(windowId);
E
Erich Gamma 已提交
206 207 208 209
			if (win) {
				win.setReady();

				// Event
210
				this._onWindowReady.fire(win);
E
Erich Gamma 已提交
211 212 213
			}
		});

214 215 216 217 218 219 220 221 222 223 224
		// 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');
				}
			});
		}

225 226
		// Handle various lifecycle events around windows
		this.lifecycleService.onBeforeWindowUnload(e => this.onBeforeWindowUnload(e));
227
		this.lifecycleService.onBeforeWindowClose(win => this.onBeforeWindowClose(win as ICodeWindow));
228
		this.lifecycleService.onBeforeShutdown(() => this.onBeforeShutdown());
229 230 231 232 233 234 235 236
		this.onWindowsCountChanged(e => {
			if (e.newCount - e.oldCount > 0) {
				// clear last closed window state when a new window opens. this helps on macOS where
				// otherwise closing the last window, opening a new window and then quitting would
				// use the state of the previously closed window when restarting.
				this.lastClosedWindowState = void 0;
			}
		});
237 238
	}

239
	// Note that onBeforeShutdown() and onBeforeWindowClose() are fired in different order depending on the OS:
240
	// - macOS: since the app will not quit when closing the last window, you will always first get
241
	//          the onBeforeShutdown() event followed by N onbeforeWindowClose() events for each window
242 243
	// - 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()
244
	//          and then onBeforeShutdown(). Using the quit action however will first issue onBeforeShutdown()
245
	//          and then onBeforeWindowClose().
246 247 248 249 250 251 252
	//
	// 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
253
	// - onBeforeShutdown(N): number of windows reported in this event handler
254 255 256
	// - onBeforeWindowClose(N, M): number of windows reported and quitRequested boolean in this event handler
	//
	// macOS
257 258 259
	// 	-     quit(1): onBeforeShutdown(1), onBeforeWindowClose(1, true)
	// 	-     quit(2): onBeforeShutdown(2), onBeforeWindowClose(2, true), onBeforeWindowClose(2, true)
	// 	-     quit(0): onBeforeShutdown(0)
260 261 262
	// 	-    close(1): onBeforeWindowClose(1, false)
	//
	// Windows
263 264
	// 	-     quit(1): onBeforeShutdown(1), onBeforeWindowClose(1, true)
	// 	-     quit(2): onBeforeShutdown(2), onBeforeWindowClose(2, true), onBeforeWindowClose(2, true)
265
	// 	-    close(1): onBeforeWindowClose(2, false)[not last window]
266 267
	// 	-    close(1): onBeforeWindowClose(1, false), onBeforeShutdown(0)[last window]
	// 	- closeAll(2): onBeforeWindowClose(2, false), onBeforeWindowClose(2, false), onBeforeShutdown(0)
268 269
	//
	// Linux
270 271
	// 	-     quit(1): onBeforeShutdown(1), onBeforeWindowClose(1, true)
	// 	-     quit(2): onBeforeShutdown(2), onBeforeWindowClose(2, true), onBeforeWindowClose(2, true)
272
	// 	-    close(1): onBeforeWindowClose(2, false)[not last window]
273 274
	// 	-    close(1): onBeforeWindowClose(1, false), onBeforeShutdown(0)[last window]
	// 	- closeAll(2): onBeforeWindowClose(2, false), onBeforeWindowClose(2, false), onBeforeShutdown(0)
275
	//
276
	private onBeforeShutdown(): void {
277
		const currentWindowsState: IWindowsState = {
278
			openedWindows: [],
279
			lastPluginDevelopmentHostWindow: this.windowsState.lastPluginDevelopmentHostWindow,
280
			lastActiveWindow: this.lastClosedWindowState
281 282 283 284 285 286 287 288
		};

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

290
			if (activeWindow) {
291
				currentWindowsState.lastActiveWindow = this.toWindowState(activeWindow);
E
Erich Gamma 已提交
292
			}
293 294 295 296 297
		}

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

301
		// 3.) All windows (except extension host) for N >= 2 to support restoreWindows: all or for auto update
302 303 304 305 306
		//
		// 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) {
307
			currentWindowsState.openedWindows = WindowsManager.WINDOWS.filter(w => !w.isExtensionDevelopmentHost).map(w => this.toWindowState(w));
308
		}
E
Erich Gamma 已提交
309

310
		// Persist
B
Benjamin Pasero 已提交
311
		this.stateService.setItem(WindowsManager.windowsStateStorageKey, currentWindowsState);
312
	}
313

314
	// See note on #onBeforeShutdown() for details how these events are flowing
315
	private onBeforeWindowClose(win: ICodeWindow): void {
316
		if (this.lifecycleService.isQuitRequested) {
317 318 319 320
			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
321
		const state: IWindowState = this.toWindowState(win);
322 323 324 325
		if (win.isExtensionDevelopmentHost && !win.isExtensionTestHost) {
			this.windowsState.lastPluginDevelopmentHostWindow = state; // do not let test run window state overwrite our extension development state
		}

326
		// Any non extension host window with same workspace or folder
327
		else if (!win.isExtensionDevelopmentHost && (!!win.openedWorkspace || !!win.openedFolderUri)) {
328
			this.windowsState.openedWindows.forEach(o => {
B
fix npe  
Benjamin Pasero 已提交
329
				const sameWorkspace = win.openedWorkspace && o.workspace && o.workspace.id === win.openedWorkspace.id;
S
Sandeep Somavarapu 已提交
330
				const sameFolder = win.openedFolderUri && o.folderUri && isEqual(o.folderUri, win.openedFolderUri, hasToIgnoreCase(o.folderUri));
331 332

				if (sameWorkspace || sameFolder) {
333 334 335 336 337 338 339
					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.
340 341 342
		// 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) {
343 344
			this.lastClosedWindowState = state;
		}
E
Erich Gamma 已提交
345 346
	}

347
	private toWindowState(win: ICodeWindow): IWindowState {
348
		return {
349
			workspace: win.openedWorkspace,
350
			folderUri: win.openedFolderUri,
351 352 353 354 355
			backupPath: win.backupPath,
			uiState: win.serializeWindowState()
		};
	}

B
Benjamin Pasero 已提交
356
	open(openConfig: IOpenConfiguration): ICodeWindow[] {
357
		this.logService.trace('windowsManager#open');
358
		openConfig = this.validateOpenConfig(openConfig);
359

360
		let pathsToOpen = this.getPathsToOpen(openConfig);
361 362 363

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

370 371
		let filesToOpen = pathsToOpen.filter(path => !!path.fileUri && !path.createFilePath);
		let filesToCreate = pathsToOpen.filter(path => !!path.fileUri && path.createFilePath);
372 373 374 375

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

382 383 384 385 386 387
		// When run with --wait, make sure we keep the paths to wait for
		let filesToWait: IPathsToWaitFor;
		if (openConfig.cli.wait && openConfig.cli.waitMarkerFilePath) {
			filesToWait = { paths: [...filesToDiff, ...filesToOpen, ...filesToCreate], waitMarkerFilePath: openConfig.cli.waitMarkerFilePath };
		}

388 389 390
		//
		// These are windows to open to show workspaces
		//
B
Benjamin Pasero 已提交
391
		const workspacesToOpen = arrays.distinct(pathsToOpen.filter(win => !!win.workspace).map(win => win.workspace), workspace => workspace.id); // prevent duplicates
392 393 394 395

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

398
		//
399
		// These are windows to restore because of hot-exit or from previous session (only performed once on startup!)
400
		//
401
		let foldersToRestore: URI[] = [];
402 403
		let workspacesToRestore: IWorkspaceIdentifier[] = [];
		let emptyToRestore: string[] = [];
B
Benjamin Pasero 已提交
404
		if (openConfig.initialStartup && !openConfig.cli.extensionDevelopmentPath && !openConfig.cli['disable-restore-windows']) {
405
			foldersToRestore = this.backupMainService.getFolderBackupPaths();
406

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

B
Benjamin Pasero 已提交
410
			emptyToRestore = this.backupMainService.getEmptyWindowBackupPaths();
411
			emptyToRestore.push(...pathsToOpen.filter(w => !w.workspace && !w.folderUri && w.backupPath).map(w => basename(w.backupPath))); // add empty windows with backupPath
412 413
			emptyToRestore = arrays.distinct(emptyToRestore); // prevent duplicates
		}
414

415 416 417
		//
		// These are empty windows to open
		//
418
		const emptyToOpen = pathsToOpen.filter(win => !win.workspace && !win.folderUri && !win.fileUri && !win.backupPath).length;
419

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

423
		// Make sure to pass focus to the most relevant of the windows if we open multiple
424
		if (usedWindows.length > 1) {
425

426
			let focusLastActive = this.windowsState.lastActiveWindow && !openConfig.forceEmpty && !openConfig.cli._.length && !asArray(openConfig.cli['file-uri']).length && !asArray(openConfig.cli['folder-uri']).length && !asArray(openConfig.urisToOpen).length;
427 428
			let focusLastOpened = true;
			let focusLastWindow = true;
429

430 431
			// 1.) focus last active window if we are not instructed to open any paths
			if (focusLastActive) {
432 433 434
				const lastActiveWindw = usedWindows.filter(w => w.backupPath === this.windowsState.lastActiveWindow.backupPath);
				if (lastActiveWindw.length) {
					lastActiveWindw[0].focus();
435 436
					focusLastOpened = false;
					focusLastWindow = false;
437 438 439
				}
			}

440 441 442 443 444
			// 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 (
445 446 447
						(usedWindow.openedWorkspace && workspacesToRestore.some(workspace => workspace.id === usedWindow.openedWorkspace.id)) || 							// skip over restored workspace
						(usedWindow.openedFolderUri && foldersToRestore.some(folder => isEqual(folder, usedWindow.openedFolderUri, hasToIgnoreCase(folder)))) ||	// skip over restored folder
						(usedWindow.backupPath && emptyToRestore.some(empty => empty === basename(usedWindow.backupPath)))													// skip over restored empty window
448 449 450 451 452 453 454 455 456 457 458 459
					) {
						continue;
					}

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

			// 3.) finally, always ensure to have at least last used window focused
			if (focusLastWindow) {
460
				usedWindows[usedWindows.length - 1].focus();
461 462
			}
		}
463

464 465 466
		// Remember in recent document list (unless this opens for extension development)
		// Also do not add paths when files are opened for diffing, only if opened individually
		if (!usedWindows.some(w => w.isExtensionDevelopmentHost) && !openConfig.cli.diff) {
467
			const recentlyOpenedWorkspaces: (IWorkspaceIdentifier | ISingleFolderWorkspaceIdentifier)[] = [];
468
			const recentlyOpenedFiles: URI[] = [];
469

B
Benjamin Pasero 已提交
470
			pathsToOpen.forEach(win => {
471 472
				if (win.workspace || win.folderUri) {
					recentlyOpenedWorkspaces.push(win.workspace || win.folderUri);
473 474
				} else if (win.fileUri) {
					recentlyOpenedFiles.push(win.fileUri);
475 476 477
				}
			});

478 479 480
			if (!this.environmentService.skipAddToRecentlyOpened) {
				this.historyMainService.addRecentlyOpened(recentlyOpenedWorkspaces, recentlyOpenedFiles);
			}
481
		}
482

483
		// If we got started with --wait from the CLI, we need to signal to the outside when the window
484 485
		// 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.
486
		if (openConfig.context === OpenContext.CLI && openConfig.cli.wait && openConfig.cli.waitMarkerFilePath && usedWindows.length === 1 && usedWindows[0]) {
487
			this.waitForWindowCloseOrLoad(usedWindows[0].id).done(() => fs.unlink(openConfig.cli.waitMarkerFilePath, error => void 0));
488 489
		}

490 491 492
		return usedWindows;
	}

493 494 495 496 497 498 499 500 501 502
	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;
	}

503 504
	private doOpen(
		openConfig: IOpenConfiguration,
505 506
		workspacesToOpen: IWorkspaceIdentifier[],
		workspacesToRestore: IWorkspaceIdentifier[],
507 508
		foldersToOpen: URI[],
		foldersToRestore: URI[],
509 510 511 512
		emptyToRestore: string[],
		emptyToOpen: number,
		filesToOpen: IPath[],
		filesToCreate: IPath[],
513
		filesToDiff: IPath[],
514
		filesToWait: IPathsToWaitFor,
515
		foldersToAdd: URI[]
516
	) {
517
		const usedWindows: ICodeWindow[] = [];
518

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

522 523 524 525 526 527 528 529 530 531 532
		// Handle folders to add by looking for the last active workspace (not on initial startup)
		if (!openConfig.initialStartup && foldersToAdd.length > 0) {
			const lastActiveWindow = this.getLastActiveWindow();
			if (lastActiveWindow) {
				usedWindows.push(this.doAddFoldersToExistingWidow(lastActiveWindow, foldersToAdd));
			}

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

B
Benjamin Pasero 已提交
533
		// 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
534 535
		const potentialWindowsCount = foldersToOpen.length + foldersToRestore.length + workspacesToOpen.length + workspacesToRestore.length + emptyToRestore.length;
		if (potentialWindowsCount === 0 && (filesToOpen.length > 0 || filesToCreate.length > 0 || filesToDiff.length > 0)) {
E
Erich Gamma 已提交
536

537
			// Find suitable window or folder path to open files in
538
			const fileToCheck = filesToOpen[0] || filesToCreate[0] || filesToDiff[0];
539
			let bestWindowOrFolder = findBestWindowOrFolderForFile({
540 541 542 543
				windows: WindowsManager.WINDOWS,
				newWindow: openFilesInNewWindow,
				reuseWindow: openConfig.forceReuseWindow,
				context: openConfig.context,
544
				fileUri: fileToCheck && fileToCheck.fileUri,
B
Benjamin Pasero 已提交
545
				workspaceResolver: workspace => this.workspacesMainService.resolveWorkspaceSync(workspace.configPath)
546
			});
B
Benjamin Pasero 已提交
547

548 549 550
			// Special case: we started with --wait and we got back a folder to open. In this case
			// we actually prefer to not open the folder but operate purely on the file.
			if (typeof bestWindowOrFolder === 'string' && filesToWait) {
551
				//TODO@Ben: #54483 This should not happen
552
				console.error(`This should not happen`, bestWindowOrFolder, WindowsManager.WINDOWS);
553 554 555
				bestWindowOrFolder = !openFilesInNewWindow ? this.getLastActiveWindow() : null;
			}

556 557 558 559 560 561 562 563 564
			// 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
565 566
				else if (bestWindowOrFolder.openedFolderUri) {
					foldersToOpen.push(bestWindowOrFolder.openedFolderUri);
567 568 569 570 571 572
				}

				// Window is empty
				else {

					// Do open files
573
					usedWindows.push(this.doOpenFilesInExistingWindow(openConfig, bestWindowOrFolder, filesToOpen, filesToCreate, filesToDiff, filesToWait));
574 575 576 577 578

					// Reset these because we handled them
					filesToOpen = [];
					filesToCreate = [];
					filesToDiff = [];
579
					filesToWait = void 0;
580
				}
581 582 583 584
			}

			// We found a suitable folder to open: add it to foldersToOpen
			else if (typeof bestWindowOrFolder === 'string') {
585
				//TODO@Ben: #54483 Ben This should not happen
586 587
				// foldersToOpen.push(bestWindowOrFolder);
				console.error(`This should not happen`, bestWindowOrFolder, WindowsManager.WINDOWS);
E
Erich Gamma 已提交
588 589
			}

590
			// Finally, if no window or folder is found, just open the files in an empty window
E
Erich Gamma 已提交
591
			else {
B
Benjamin Pasero 已提交
592
				usedWindows.push(this.openInBrowserWindow({
B
Benjamin Pasero 已提交
593 594 595 596 597 598
					userEnv: openConfig.userEnv,
					cli: openConfig.cli,
					initialStartup: openConfig.initialStartup,
					filesToOpen,
					filesToCreate,
					filesToDiff,
599
					filesToWait,
600 601
					forceNewWindow: true,
					forceNewTabbedWindow: openConfig.forceNewTabbedWindow
B
Benjamin Pasero 已提交
602
				}));
E
Erich Gamma 已提交
603

604 605 606 607
				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
				filesToDiff = [];
608
				filesToWait = void 0;
E
Erich Gamma 已提交
609 610 611
			}
		}

612
		// Handle workspaces to open (instructed and to restore)
613
		const allWorkspacesToOpen = arrays.distinct([...workspacesToRestore, ...workspacesToOpen], workspace => workspace.id); // prevent duplicates
614 615 616 617 618 619 620 621
		if (allWorkspacesToOpen.length > 0) {

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

				// Do open files
622
				usedWindows.push(this.doOpenFilesInExistingWindow(openConfig, windowOnWorkspace, filesToOpen, filesToCreate, filesToDiff, filesToWait));
623 624 625 626 627

				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
				filesToDiff = [];
628
				filesToWait = void 0;
629 630 631 632 633 634

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

			// Open remaining ones
			allWorkspacesToOpen.forEach(workspaceToOpen => {
635
				if (windowsOnWorkspace.some(win => win.openedWorkspace.id === workspaceToOpen.id)) {
636 637 638 639
					return; // ignore folders that are already open
				}

				// Do open folder
640
				usedWindows.push(this.doOpenFolderOrWorkspace(openConfig, { workspace: workspaceToOpen }, openFolderInNewWindow, filesToOpen, filesToCreate, filesToDiff, filesToWait));
641 642 643 644 645

				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
				filesToDiff = [];
646
				filesToWait = void 0;
647 648 649 650 651

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

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

655
		if (allFoldersToOpen.length > 0) {
E
Erich Gamma 已提交
656 657

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

662
				// Do open files
663
				usedWindows.push(this.doOpenFilesInExistingWindow(openConfig, windowOnFolderPath, filesToOpen, filesToCreate, filesToDiff, filesToWait));
664

E
Erich Gamma 已提交
665 666 667
				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
668
				filesToDiff = [];
669
				filesToWait = void 0;
E
Erich Gamma 已提交
670

B
Benjamin Pasero 已提交
671
				openFolderInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
672 673 674
			}

			// Open remaining ones
675
			allFoldersToOpen.forEach(folderToOpen => {
676

S
Sandeep Somavarapu 已提交
677
				if (windowsOnFolderPath.some(win => isEqual(win.openedFolderUri, folderToOpen, hasToIgnoreCase(win.openedFolderUri)))) {
E
Erich Gamma 已提交
678 679 680
					return; // ignore folders that are already open
				}

681
				// Do open folder
682
				usedWindows.push(this.doOpenFolderOrWorkspace(openConfig, { folderUri: folderToOpen }, openFolderInNewWindow, filesToOpen, filesToCreate, filesToDiff, filesToWait));
E
Erich Gamma 已提交
683 684 685 686

				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
687
				filesToDiff = [];
688
				filesToWait = void 0;
E
Erich Gamma 已提交
689

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

694
		// Handle empty to restore
695
		if (emptyToRestore.length > 0) {
696
			emptyToRestore.forEach(emptyWindowBackupFolder => {
B
Benjamin Pasero 已提交
697
				usedWindows.push(this.openInBrowserWindow({
B
Benjamin Pasero 已提交
698 699 700 701 702 703
					userEnv: openConfig.userEnv,
					cli: openConfig.cli,
					initialStartup: openConfig.initialStartup,
					filesToOpen,
					filesToCreate,
					filesToDiff,
704
					filesToWait,
B
Benjamin Pasero 已提交
705
					forceNewWindow: true,
706
					forceNewTabbedWindow: openConfig.forceNewTabbedWindow,
707
					emptyWindowBackupFolder
B
Benjamin Pasero 已提交
708
				}));
709

B
wip  
Benjamin Pasero 已提交
710 711 712 713
				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
				filesToDiff = [];
714
				filesToWait = void 0;
B
wip  
Benjamin Pasero 已提交
715

B
Benjamin Pasero 已提交
716
				openFolderInNewWindow = true; // any other folders to open must open in new window then
717 718
			});
		}
B
Benjamin Pasero 已提交
719

720 721
		// Handle empty to open (only if no other window opened)
		if (usedWindows.length === 0) {
722
			for (let i = 0; i < emptyToOpen; i++) {
B
Benjamin Pasero 已提交
723
				usedWindows.push(this.openInBrowserWindow({
B
Benjamin Pasero 已提交
724 725 726
					userEnv: openConfig.userEnv,
					cli: openConfig.cli,
					initialStartup: openConfig.initialStartup,
727 728
					forceNewWindow: openFolderInNewWindow,
					forceNewTabbedWindow: openConfig.forceNewTabbedWindow
B
Benjamin Pasero 已提交
729
				}));
E
Erich Gamma 已提交
730

731
				openFolderInNewWindow = true; // any other window to open must open in new window then
732 733
			}
		}
E
Erich Gamma 已提交
734

735
		return arrays.distinct(usedWindows);
E
Erich Gamma 已提交
736 737
	}

738
	private doOpenFilesInExistingWindow(configuration: IOpenConfiguration, window: ICodeWindow, filesToOpen: IPath[], filesToCreate: IPath[], filesToDiff: IPath[], filesToWait: IPathsToWaitFor): ICodeWindow {
739 740 741
		window.focus(); // make sure window has focus

		window.ready().then(readyWindow => {
742 743
			const termProgram = configuration.userEnv ? configuration.userEnv['TERM_PROGRAM'] : void 0;
			readyWindow.send('vscode:openFiles', { filesToOpen, filesToCreate, filesToDiff, filesToWait, termProgram });
744
		});
B
Benjamin Pasero 已提交
745 746

		return window;
747 748
	}

749
	private doAddFoldersToExistingWidow(window: ICodeWindow, foldersToAdd: URI[]): ICodeWindow {
750 751 752 753 754 755 756 757 758
		window.focus(); // make sure window has focus

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

		return window;
	}

B
Benjamin Pasero 已提交
759 760 761 762 763
	private doOpenFolderOrWorkspace(openConfig: IOpenConfiguration, folderOrWorkspace: IPathToOpen, forceNewWindow: boolean, filesToOpen: IPath[], filesToCreate: IPath[], filesToDiff: IPath[], filesToWait: IPathsToWaitFor, windowToUse?: ICodeWindow): ICodeWindow {
		if (!forceNewWindow && !windowToUse && typeof openConfig.contextWindowId === 'number') {
			windowToUse = this.getWindowById(openConfig.contextWindowId); // fix for https://github.com/Microsoft/vscode/issues/49587
		}

764 765 766 767
		const browserWindow = this.openInBrowserWindow({
			userEnv: openConfig.userEnv,
			cli: openConfig.cli,
			initialStartup: openConfig.initialStartup,
768
			workspace: folderOrWorkspace.workspace,
769
			folderUri: folderOrWorkspace.folderUri,
770 771 772
			filesToOpen,
			filesToCreate,
			filesToDiff,
773
			filesToWait,
B
Benjamin Pasero 已提交
774
			forceNewWindow,
775
			forceNewTabbedWindow: openConfig.forceNewTabbedWindow,
776
			windowToUse
777 778 779 780 781
		});

		return browserWindow;
	}

B
Benjamin Pasero 已提交
782 783
	private getPathsToOpen(openConfig: IOpenConfiguration): IPathToOpen[] {
		let windowsToOpen: IPathToOpen[];
784
		let isCommandLineOrAPICall = false;
E
Erich Gamma 已提交
785

786
		// Extract paths: from API
S
Sandeep Somavarapu 已提交
787
		if (openConfig.urisToOpen && openConfig.urisToOpen.length > 0) {
788
			windowsToOpen = this.doExtractPathsFromAPI(openConfig);
789
			isCommandLineOrAPICall = true;
E
Erich Gamma 已提交
790 791
		}

B
Benjamin Pasero 已提交
792 793
		// Check for force empty
		else if (openConfig.forceEmpty) {
794
			windowsToOpen = [Object.create(null)];
E
Erich Gamma 已提交
795 796
		}

797
		// Extract paths: from CLI
798
		else if (openConfig.cli._.length > 0 || asArray(openConfig.cli['folder-uri']).length > 0 || asArray(openConfig.cli['file-uri']).length > 0) {
799
			windowsToOpen = this.doExtractPathsFromCLI(openConfig.cli);
800
			isCommandLineOrAPICall = true;
B
Benjamin Pasero 已提交
801 802
		}

803
		// Extract windows: from previous session
B
Benjamin Pasero 已提交
804
		else {
805
			windowsToOpen = this.doGetWindowsFromLastSession();
B
Benjamin Pasero 已提交
806 807
		}

808 809
		// Convert multiple folders into workspace (if opened via API or CLI)
		// This will ensure to open these folders in one window instead of multiple
810 811
		// If we are in addMode, we should not do this because in that case all
		// folders should be added to the existing window.
812
		if (!openConfig.addMode && isCommandLineOrAPICall) {
813
			const foldersToOpen = windowsToOpen.filter(path => !!path.folderUri);
814
			if (foldersToOpen.length > 1) {
815
				const workspace = this.workspacesMainService.createWorkspaceSync(foldersToOpen.map(folder => ({ uri: folder.folderUri })));
816 817 818

				// Add workspace and remove folders thereby
				windowsToOpen.push({ workspace });
819
				windowsToOpen = windowsToOpen.filter(path => !path.folderUri);
820 821 822
			}
		}

823
		return windowsToOpen;
E
Erich Gamma 已提交
824 825
	}

826
	private doExtractPathsFromAPI(openConfig: IOpenConfiguration): IPath[] {
S
Sandeep Somavarapu 已提交
827
		let pathsToOpen = openConfig.urisToOpen.map(pathToOpen => {
828
			const path = this.parseUri(pathToOpen, openConfig.forceOpenWorkspaceAsFile, { gotoLineMode: openConfig.cli && openConfig.cli.goto, forceOpenWorkspaceAsFile: openConfig.forceOpenWorkspaceAsFile });
829 830 831

			// Warn if the requested path to open does not exist
			if (!path) {
832
				const options: Electron.MessageBoxOptions = {
833 834
					title: product.nameLong,
					type: 'info',
835 836
					buttons: [localize('ok', "OK")],
					message: localize('pathNotExistTitle', "Path does not exist"),
837
					detail: localize('pathNotExistDetail', "The path '{0}' does not seem to exist anymore on disk.", pathToOpen.scheme === Schemas.file ? pathToOpen.fsPath : pathToOpen.path),
838 839 840
					noLink: true
				};

841
				this.dialogs.showMessageBox(options, this.getFocusedWindow());
842
			}
B
Benjamin Pasero 已提交
843

844 845 846 847 848 849 850 851 852 853
			return path;
		});

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

		return pathsToOpen;
	}

	private doExtractPathsFromCLI(cli: ParsedArgs): IPath[] {
854 855 856
		const pathsToOpen = [];

		// folder uris
857 858 859 860 861 862 863 864 865
		const folderUris = asArray(cli['folder-uri']);
		if (folderUris.length) {
			pathsToOpen.push(...arrays.coalesce(folderUris.map(candidate => this.parseUri(this.parseUriArg(candidate), false, { ignoreFileNotFound: true, gotoLineMode: cli.goto }))));
		}

		// file uris
		const fileUris = asArray(cli['file-uri']);
		if (fileUris.length) {
			pathsToOpen.push(...arrays.coalesce(fileUris.map(candidate => this.parseUri(this.parseUriArg(candidate), true, { ignoreFileNotFound: true, gotoLineMode: cli.goto }))));
866 867 868 869 870 871 872
		}

		// folder or file paths
		if (cli._ && cli._.length) {
			pathsToOpen.push(...arrays.coalesce(cli._.map(candidate => this.parsePath(candidate, { ignoreFileNotFound: true, gotoLineMode: cli.goto }))));
		}

873 874
		if (pathsToOpen.length > 0) {
			return pathsToOpen;
B
Benjamin Pasero 已提交
875 876 877 878 879 880
		}

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

B
Benjamin Pasero 已提交
881
	private doGetWindowsFromLastSession(): IPathToOpen[] {
882 883
		const restoreWindows = this.getRestoreWindowsSetting();
		const lastActiveWindow = this.windowsState.lastActiveWindow;
B
Benjamin Pasero 已提交
884

885
		switch (restoreWindows) {
B
Benjamin Pasero 已提交
886

887
			// none: we always open an empty window
888 889
			case 'none':
				return [Object.create(null)];
B
Benjamin Pasero 已提交
890

891
			// one: restore last opened workspace/folder or empty window
892 893
			case 'one':
				if (lastActiveWindow) {
B
Benjamin Pasero 已提交
894

895
					// workspace
B
Benjamin Pasero 已提交
896 897 898 899 900 901
					const candidateWorkspace = lastActiveWindow.workspace;
					if (candidateWorkspace) {
						const validatedWorkspace = this.parsePath(candidateWorkspace.configPath);
						if (validatedWorkspace && validatedWorkspace.workspace) {
							return [validatedWorkspace];
						}
902 903 904
					}

					// folder (if path is valid)
905
					else if (lastActiveWindow.folderUri) {
906
						const validatedFolder = this.parseUri(lastActiveWindow.folderUri, false);
907
						if (validatedFolder && validatedFolder.folderUri) {
908
							return [validatedFolder];
909 910
						}
					}
B
Benjamin Pasero 已提交
911

912
					// otherwise use backup path to restore empty windows
913 914 915 916 917 918 919 920 921 922
					else if (lastActiveWindow.backupPath) {
						return [{ backupPath: lastActiveWindow.backupPath }];
					}
				}
				break;

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

925
				// Workspaces
B
Benjamin Pasero 已提交
926
				const workspaceCandidates = this.windowsState.openedWindows.filter(w => !!w.workspace).map(w => w.workspace);
927
				if (lastActiveWindow && lastActiveWindow.workspace) {
B
Benjamin Pasero 已提交
928
					workspaceCandidates.push(lastActiveWindow.workspace);
929
				}
B
Benjamin Pasero 已提交
930
				windowsToOpen.push(...workspaceCandidates.map(candidate => this.parsePath(candidate.configPath)).filter(window => window && window.workspace));
B
Benjamin Pasero 已提交
931

932
				// Folders
933 934 935
				const folderCandidates = this.windowsState.openedWindows.filter(w => !!w.folderUri).map(w => w.folderUri);
				if (lastActiveWindow && lastActiveWindow.folderUri) {
					folderCandidates.push(lastActiveWindow.folderUri);
936
				}
937
				windowsToOpen.push(...folderCandidates.map(candidate => this.parseUri(candidate, false)).filter(window => window && window.folderUri));
B
Benjamin Pasero 已提交
938

939 940
				// Windows that were Empty
				if (restoreWindows === 'all') {
941 942
					const lastOpenedEmpty = this.windowsState.openedWindows.filter(w => !w.workspace && !w.folderUri && w.backupPath).map(w => w.backupPath);
					const lastActiveEmpty = lastActiveWindow && !lastActiveWindow.workspace && !lastActiveWindow.folderUri && lastActiveWindow.backupPath;
943 944 945 946 947 948 949 950 951 952 953 954
					if (lastActiveEmpty) {
						lastOpenedEmpty.push(lastActiveEmpty);
					}

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

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

				break;
B
Benjamin Pasero 已提交
955
		}
E
Erich Gamma 已提交
956

957
		// Always fallback to empty window
B
Benjamin Pasero 已提交
958
		return [Object.create(null)];
E
Erich Gamma 已提交
959 960
	}

961 962 963 964 965
	private getRestoreWindowsSetting(): RestoreWindowsSetting {
		let restoreWindows: RestoreWindowsSetting;
		if (this.lifecycleService.wasRestarted) {
			restoreWindows = 'all'; // always reopen all windows when an update was applied
		} else {
966
			const windowConfig = this.configurationService.getValue<IWindowSettings>('window');
967
			restoreWindows = ((windowConfig && windowConfig.restoreWindows) || 'one') as RestoreWindowsSetting;
968 969 970 971 972 973 974 975 976

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

		return restoreWindows;
	}

977
	private parseUriArg(arg: string): URI {
978 979 980 981 982 983 984
		// Do not support if user has passed folder path on Windows
		if (isWindows && /^([a-z])\:(.*)$/i.test(arg)) {
			return null;
		}
		return URI.parse(arg);
	}

985
	private parseUri(anyUri: URI, isFile: boolean, options?: { ignoreFileNotFound?: boolean, gotoLineMode?: boolean, forceOpenWorkspaceAsFile?: boolean; }): IPathToOpen {
S
Sandeep Somavarapu 已提交
986
		if (!anyUri || !anyUri.scheme) {
987 988 989 990 991 992
			return null;
		}

		if (anyUri.scheme === Schemas.file) {
			return this.parsePath(anyUri.fsPath, options);
		}
993 994 995 996 997
		if (isFile) {
			return {
				fileUri: anyUri
			};
		}
998 999 1000 1001 1002
		return {
			folderUri: anyUri
		};
	}

B
Benjamin Pasero 已提交
1003
	private parsePath(anyPath: string, options?: { ignoreFileNotFound?: boolean, gotoLineMode?: boolean, forceOpenWorkspaceAsFile?: boolean; }): IPathToOpen {
E
Erich Gamma 已提交
1004 1005 1006 1007
		if (!anyPath) {
			return null;
		}

1008
		let parsedPath: IPathWithLineAndColumn;
1009 1010 1011

		const gotoLineMode = options && options.gotoLineMode;
		if (options && options.gotoLineMode) {
J
Joao Moreno 已提交
1012
			parsedPath = parseLineAndColumnAware(anyPath);
E
Erich Gamma 已提交
1013 1014 1015
			anyPath = parsedPath.path;
		}

1016
		const candidate = normalize(anyPath);
E
Erich Gamma 已提交
1017
		try {
B
Benjamin Pasero 已提交
1018
			const candidateStat = fs.statSync(candidate);
E
Erich Gamma 已提交
1019
			if (candidateStat) {
1020
				if (candidateStat.isFile()) {
1021

1022 1023
					// Workspace (unless disabled via flag)
					if (!options || !options.forceOpenWorkspaceAsFile) {
B
Benjamin Pasero 已提交
1024
						const workspace = this.workspacesMainService.resolveWorkspaceSync(candidate);
1025
						if (workspace) {
1026
							return { workspace: { id: workspace.id, configPath: workspace.configPath } };
1027
						}
1028 1029 1030
					}

					// File
1031
					return {
1032
						fileUri: URI.file(candidate),
E
Erich Gamma 已提交
1033
						lineNumber: gotoLineMode ? parsedPath.line : void 0,
1034
						columnNumber: gotoLineMode ? parsedPath.column : void 0
1035 1036 1037
					};
				}

1038 1039 1040 1041 1042
				// 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 {
1043
						folderUri: URI.file(candidate)
1044 1045
					};
				}
E
Erich Gamma 已提交
1046 1047
			}
		} catch (error) {
1048 1049
			const fileUri = URI.file(candidate);
			this.historyMainService.removeFromRecentlyOpened([fileUri]); // since file does not seem to exist anymore, remove from recent
1050

1051
			if (options && options.ignoreFileNotFound) {
1052
				return { fileUri, createFilePath: true }; // assume this is a file that does not yet exist
E
Erich Gamma 已提交
1053 1054 1055 1056 1057 1058
			}
		}

		return null;
	}

B
Benjamin Pasero 已提交
1059 1060 1061
	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
1062
		const windowConfig = this.configurationService.getValue<IWindowSettings>('window');
1063 1064 1065
		const openFolderInNewWindowConfig = (windowConfig && windowConfig.openFoldersInNewWindow) || 'default' /* default */;
		const openFilesInNewWindowConfig = (windowConfig && windowConfig.openFilesInNewWindow) || 'off' /* default */;

B
Benjamin Pasero 已提交
1066
		let openFolderInNewWindow = (openConfig.preferNewWindow || openConfig.forceNewWindow) && !openConfig.forceReuseWindow;
1067 1068
		if (!openConfig.forceNewWindow && !openConfig.forceReuseWindow && (openFolderInNewWindowConfig === 'on' || openFolderInNewWindowConfig === 'off')) {
			openFolderInNewWindow = (openFolderInNewWindowConfig === 'on');
B
Benjamin Pasero 已提交
1069 1070 1071 1072 1073 1074 1075
		}

		// 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 {
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088

			// 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 已提交
1089 1090
			}

1091
			// finally check for overrides of default
1092 1093
			if (!openConfig.cli.extensionDevelopmentPath && (openFilesInNewWindowConfig === 'on' || openFilesInNewWindowConfig === 'off')) {
				openFilesInNewWindow = (openFilesInNewWindowConfig === 'on');
B
Benjamin Pasero 已提交
1094 1095 1096 1097 1098 1099
			}
		}

		return { openFolderInNewWindow, openFilesInNewWindow };
	}

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

B
Benjamin Pasero 已提交
1102 1103 1104
		// 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.
1105 1106 1107 1108
		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 已提交
1109

B
Benjamin Pasero 已提交
1110 1111
			return;
		}
1112 1113 1114
		let folderUris = asArray(openConfig.cli['folder-uri']);
		let fileUris = asArray(openConfig.cli['file-uri']);
		let cliArgs = openConfig.cli._;
E
Erich Gamma 已提交
1115

1116
		// Fill in previously opened workspace unless an explicit path is provided and we are not unit testing
1117
		if (!cliArgs.length && !folderUris.length && !fileUris.length && !openConfig.cli.extensionTestsPath) {
1118
			const extensionDevelopmentWindowState = this.windowsState.lastPluginDevelopmentHostWindow;
1119
			const workspaceToOpen = extensionDevelopmentWindowState && (extensionDevelopmentWindowState.workspace || extensionDevelopmentWindowState.folderUri);
1120
			if (workspaceToOpen) {
1121
				if (isSingleFolderWorkspaceIdentifier(workspaceToOpen)) {
1122
					if (workspaceToOpen.scheme === Schemas.file) {
1123
						cliArgs = [workspaceToOpen.fsPath];
1124
					} else {
1125
						folderUris = [workspaceToOpen.toString()];
1126 1127
					}
				} else {
1128
					cliArgs = [workspaceToOpen.configPath];
1129
				}
E
Erich Gamma 已提交
1130 1131 1132
			}
		}

1133
		// Make sure we are not asked to open a workspace or folder that is already opened
1134 1135
		if (cliArgs.length && cliArgs.some(path => !!findWindowOnWorkspaceOrFolderUri(WindowsManager.WINDOWS, URI.file(path)))) {
			cliArgs = [];
E
Erich Gamma 已提交
1136
		}
1137 1138 1139 1140 1141 1142 1143

		if (folderUris.length && folderUris.some(uri => !!findWindowOnWorkspaceOrFolderUri(WindowsManager.WINDOWS, this.parseUriArg(uri)))) {
			folderUris = [];
		}

		if (fileUris.length && fileUris.some(uri => !!findWindowOnWorkspaceOrFolderUri(WindowsManager.WINDOWS, this.parseUriArg(uri)))) {
			fileUris = [];
1144
		}
E
Erich Gamma 已提交
1145

1146 1147 1148 1149
		openConfig.cli._ = cliArgs;
		openConfig.cli['folder-uri'] = folderUris;
		openConfig.cli['file-uri'] = fileUris;

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

1154
	private openInBrowserWindow(options: IOpenBrowserWindowOptions): ICodeWindow {
1155

B
Benjamin Pasero 已提交
1156 1157 1158
		// Build IWindowConfiguration from config and options
		const configuration: IWindowConfiguration = mixin({}, options.cli); // inherit all properties from CLI
		configuration.appRoot = this.environmentService.appRoot;
1159
		configuration.machineId = this.machineId;
B
Benjamin Pasero 已提交
1160 1161 1162
		configuration.execPath = process.execPath;
		configuration.userEnv = assign({}, this.initialUserEnv, options.userEnv || {});
		configuration.isInitialStartup = options.initialStartup;
1163
		configuration.workspace = options.workspace;
1164
		configuration.folderUri = options.folderUri;
B
Benjamin Pasero 已提交
1165 1166 1167
		configuration.filesToOpen = options.filesToOpen;
		configuration.filesToCreate = options.filesToCreate;
		configuration.filesToDiff = options.filesToDiff;
1168
		configuration.filesToWait = options.filesToWait;
B
Benjamin Pasero 已提交
1169 1170
		configuration.nodeCachedDataDir = this.environmentService.nodeCachedDataDir;

1171
		// if we know the backup folder upfront (for empty windows to restore), we can set it
1172
		// directly here which helps for restoring UI state associated with that window.
B
Benjamin Pasero 已提交
1173
		// For all other cases we first call into registerEmptyWindowBackupSync() to set it before
1174
		// loading the window.
1175
		if (options.emptyWindowBackupFolder) {
1176
			configuration.backupPath = join(this.environmentService.backupHome, options.emptyWindowBackupFolder);
1177 1178
		}

1179
		let window: ICodeWindow;
1180
		if (!options.forceNewWindow && !options.forceNewTabbedWindow) {
1181 1182 1183
			window = options.windowToUse || this.getLastActiveWindow();
			if (window) {
				window.focus();
E
Erich Gamma 已提交
1184 1185 1186 1187
			}
		}

		// New window
1188
		if (!window) {
1189
			const windowConfig = this.configurationService.getValue<IWindowSettings>('window');
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
			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 {
1200
				allowFullscreen = this.lifecycleService.wasRestarted || (windowConfig && windowConfig.restoreFullscreen);
1201 1202 1203 1204 1205
			}

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

1207
			// Create the window
1208
			window = this.instantiationService.createInstance(CodeWindow, {
1209
				state,
1210
				extensionDevelopmentPath: configuration.extensionDevelopmentPath,
1211
				isExtensionTestHost: !!configuration.extensionTestsPath
1212
			});
1213

1214 1215 1216 1217 1218 1219 1220 1221
			// Add as window tab if configured (macOS only)
			if (options.forceNewTabbedWindow) {
				const activeWindow = this.getLastActiveWindow();
				if (activeWindow) {
					activeWindow.addTabbedWindow(window);
				}
			}

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

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

E
Erich Gamma 已提交
1228
			// Window Events
1229 1230 1231 1232 1233
			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 已提交
1234 1235

			// Lifecycle
1236
			this.lifecycleService.registerWindow(window);
E
Erich Gamma 已提交
1237 1238 1239 1240 1241 1242
		}

		// Existing window
		else {

			// Some configuration things get inherited if the window is being reused and we are
B
Benjamin Pasero 已提交
1243
			// in extension development host mode. These options are all development related.
1244
			const currentWindowConfig = window.config;
A
Alex Dima 已提交
1245 1246
			if (!configuration.extensionDevelopmentPath && currentWindowConfig && !!currentWindowConfig.extensionDevelopmentPath) {
				configuration.extensionDevelopmentPath = currentWindowConfig.extensionDevelopmentPath;
B
Benjamin Pasero 已提交
1247
				configuration.verbose = currentWindowConfig.verbose;
1248
				configuration.debugBrkPluginHost = currentWindowConfig.debugBrkPluginHost;
1249
				configuration.debugId = currentWindowConfig.debugId;
1250
				configuration.debugPluginHost = currentWindowConfig.debugPluginHost;
1251
				configuration['extensions-dir'] = currentWindowConfig['extensions-dir'];
E
Erich Gamma 已提交
1252 1253 1254 1255
			}
		}

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

B
Benjamin Pasero 已提交
1259 1260
				// Register window for backups
				if (!configuration.extensionDevelopmentPath) {
1261
					if (configuration.workspace) {
B
Benjamin Pasero 已提交
1262
						configuration.backupPath = this.backupMainService.registerWorkspaceBackupSync(configuration.workspace);
1263
					} else if (configuration.folderUri) {
1264
						configuration.backupPath = this.backupMainService.registerFolderBackupSync(configuration.folderUri);
B
Benjamin Pasero 已提交
1265
					} else {
B
Benjamin Pasero 已提交
1266
						configuration.backupPath = this.backupMainService.registerEmptyWindowBackupSync(options.emptyWindowBackupFolder);
B
Benjamin Pasero 已提交
1267
					}
B
Benjamin Pasero 已提交
1268 1269
				}

E
Erich Gamma 已提交
1270
				// Load it
1271
				window.load(configuration);
1272 1273 1274

				// Signal event
				this._onWindowLoad.fire(window.id);
E
Erich Gamma 已提交
1275 1276
			}
		});
1277

1278
		return window;
E
Erich Gamma 已提交
1279 1280
	}

1281
	private getNewWindowState(configuration: IWindowConfiguration): INewWindowState {
1282
		const lastActive = this.getLastActiveWindow();
E
Erich Gamma 已提交
1283

1284 1285
		// Restore state unless we are running extension tests
		if (!configuration.extensionTestsPath) {
E
Erich Gamma 已提交
1286

1287 1288 1289
			// extension development host Window - load from stored settings if any
			if (!!configuration.extensionDevelopmentPath && this.windowsState.lastPluginDevelopmentHostWindow) {
				return this.windowsState.lastPluginDevelopmentHostWindow.uiState;
1290 1291
			}

1292 1293 1294 1295 1296 1297 1298 1299 1300
			// 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
1301 1302
			if (configuration.folderUri) {
				const stateForFolder = this.windowsState.openedWindows.filter(o => o.folderUri && isEqual(o.folderUri, configuration.folderUri, hasToIgnoreCase(o.folderUri))).map(o => o.uiState);
1303 1304 1305
				if (stateForFolder.length) {
					return stateForFolder[0];
				}
1306 1307
			}

1308 1309 1310 1311 1312 1313
			// 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 已提交
1314 1315
			}

1316 1317 1318 1319 1320
			// First Window
			const lastActiveState = this.lastClosedWindowState || this.windowsState.lastActiveWindow;
			if (!lastActive && lastActiveState) {
				return lastActiveState.uiState;
			}
E
Erich Gamma 已提交
1321 1322 1323 1324 1325 1326 1327
		}

		//
		// 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
1328
		let displayToUse: Electron.Display;
B
Benjamin Pasero 已提交
1329
		const displays = screen.getAllDisplays();
E
Erich Gamma 已提交
1330 1331 1332 1333 1334 1335 1336 1337 1338 1339

		// 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 已提交
1340
			if (isMacintosh) {
B
Benjamin Pasero 已提交
1341
				const cursorPoint = screen.getCursorScreenPoint();
E
Erich Gamma 已提交
1342 1343 1344 1345 1346 1347 1348 1349
				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());
			}

1350
			// fallback to primary display or first display
E
Erich Gamma 已提交
1351
			if (!displayToUse) {
1352
				displayToUse = screen.getPrimaryDisplay() || displays[0];
E
Erich Gamma 已提交
1353 1354 1355
			}
		}

1356 1357 1358
		// 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.
1359
		let state = defaultWindowState() as INewWindowState;
1360 1361
		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 已提交
1362

1363
		// Check for newWindowDimensions setting and adjust accordingly
1364
		const windowConfig = this.configurationService.getValue<IWindowSettings>('window');
1365 1366 1367 1368 1369 1370 1371 1372 1373
		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 已提交
1374 1375 1376 1377 1378 1379 1380
				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;
				}

1381 1382 1383 1384 1385 1386 1387 1388
				ensureNoOverlap = false;
			}
		}

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

1389 1390
		state.hasDefaultState = true; // flag as default state

1391
		return state;
E
Erich Gamma 已提交
1392 1393
	}

J
Joao Moreno 已提交
1394
	private ensureNoOverlap(state: ISingleWindowState): ISingleWindowState {
E
Erich Gamma 已提交
1395 1396 1397 1398
		if (WindowsManager.WINDOWS.length === 0) {
			return state;
		}

1399 1400
		const existingWindowBounds = WindowsManager.WINDOWS.map(win => win.getBounds());
		while (existingWindowBounds.some(b => b.x === state.x || b.y === state.y)) {
E
Erich Gamma 已提交
1401 1402 1403 1404 1405 1406 1407
			state.x += 30;
			state.y += 30;
		}

		return state;
	}

B
Benjamin Pasero 已提交
1408
	reload(win: ICodeWindow, cli?: ParsedArgs): void {
B
Benjamin Pasero 已提交
1409 1410 1411 1412

		// Only reload when the window has not vetoed this
		this.lifecycleService.unload(win, UnloadReason.RELOAD).done(veto => {
			if (!veto) {
1413
				win.reload(void 0, cli);
B
Benjamin Pasero 已提交
1414 1415 1416 1417 1418 1419 1420

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

B
Benjamin Pasero 已提交
1421
	closeWorkspace(win: ICodeWindow): void {
1422 1423 1424 1425 1426 1427
		this.openInBrowserWindow({
			cli: this.environmentService.args,
			windowToUse: win
		});
	}

B
Benjamin Pasero 已提交
1428
	saveAndEnterWorkspace(win: ICodeWindow, path: string): TPromise<IEnterWorkspaceResult> {
1429
		return this.workspacesManager.saveAndEnterWorkspace(win, path).then(result => this.doEnterWorkspace(win, result));
1430
	}
1431

1432 1433 1434 1435
	enterWorkspace(win: ICodeWindow, path: string): TPromise<IEnterWorkspaceResult> {
		return this.workspacesManager.enterWorkspace(win, path).then(result => this.doEnterWorkspace(win, result));
	}

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

1440
	private doEnterWorkspace(win: ICodeWindow, result: IEnterWorkspaceResult): IEnterWorkspaceResult {
1441

1442
		// Mark as recently opened
B
Benjamin Pasero 已提交
1443
		this.historyMainService.addRecentlyOpened([result.workspace], []);
1444

1445 1446 1447
		// Trigger Eevent to indicate load of workspace into window
		this._onWindowReady.fire(win);

1448
		return result;
1449 1450
	}

B
Benjamin Pasero 已提交
1451
	pickWorkspaceAndOpen(options: INativeOpenDialogOptions): void {
1452
		this.workspacesManager.pickWorkspaceAndOpen(options);
1453 1454 1455
	}

	private onBeforeWindowUnload(e: IWindowUnloadEvent): void {
1456 1457
		const windowClosing = (e.reason === UnloadReason.CLOSE);
		const windowLoading = (e.reason === UnloadReason.LOAD);
1458 1459 1460 1461 1462
		if (!windowClosing && !windowLoading) {
			return; // only interested when window is closing or loading
		}

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

1467
		if (e.window.config && !!e.window.config.extensionDevelopmentPath) {
1468 1469 1470 1471
			// do not ask to save workspace when doing extension development
			// but still delete it.
			this.workspacesMainService.deleteUntitledWorkspaceSync(workspace);
			return;
1472 1473
		}

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

1478
		// Handle untitled workspaces with prompt as needed
B
Benjamin Pasero 已提交
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
		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
			return TPromise.timeout(0).then(() => veto);
		}));
1490 1491
	}

B
Benjamin Pasero 已提交
1492
	focusLastActive(cli: ParsedArgs, context: OpenContext): ICodeWindow {
B
Benjamin Pasero 已提交
1493
		const lastActive = this.getLastActiveWindow();
E
Erich Gamma 已提交
1494
		if (lastActive) {
B
Benjamin Pasero 已提交
1495
			lastActive.focus();
1496 1497

			return lastActive;
E
Erich Gamma 已提交
1498 1499
		}

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

B
Benjamin Pasero 已提交
1504
	getLastActiveWindow(): ICodeWindow {
1505
		return getLastActiveWindow(WindowsManager.WINDOWS);
E
Erich Gamma 已提交
1506 1507
	}

B
Benjamin Pasero 已提交
1508
	openNewWindow(context: OpenContext): ICodeWindow[] {
J
Joao Moreno 已提交
1509
		return this.open({ context, cli: this.environmentService.args, forceNewWindow: true, forceEmpty: true });
E
Erich Gamma 已提交
1510 1511
	}

1512 1513 1514 1515
	openNewTabbedWindow(context: OpenContext): ICodeWindow[] {
		return this.open({ context, cli: this.environmentService.args, forceNewTabbedWindow: true, forceEmpty: true });
	}

B
Benjamin Pasero 已提交
1516
	waitForWindowCloseOrLoad(windowId: number): TPromise<void> {
1517
		return new TPromise<void>(c => {
1518
			function handler(id: number) {
1519
				if (id === windowId) {
1520 1521 1522
					closeListener.dispose();
					loadListener.dispose();

1523 1524
					c(null);
				}
1525 1526 1527 1528
			}

			const closeListener = this.onWindowClose(id => handler(id));
			const loadListener = this.onWindowLoad(id => handler(id));
1529 1530 1531
		});
	}

B
Benjamin Pasero 已提交
1532
	sendToFocused(channel: string, ...args: any[]): void {
E
Erich Gamma 已提交
1533 1534 1535
		const focusedWindow = this.getFocusedWindow() || this.getLastActiveWindow();

		if (focusedWindow) {
1536
			focusedWindow.sendWhenReady(channel, ...args);
E
Erich Gamma 已提交
1537 1538 1539
		}
	}

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

1546
			w.sendWhenReady(channel, payload);
E
Erich Gamma 已提交
1547 1548 1549
		});
	}

B
Benjamin Pasero 已提交
1550
	getFocusedWindow(): ICodeWindow {
B
Benjamin Pasero 已提交
1551
		const win = BrowserWindow.getFocusedWindow();
E
Erich Gamma 已提交
1552 1553 1554 1555 1556 1557 1558
		if (win) {
			return this.getWindowById(win.id);
		}

		return null;
	}

B
Benjamin Pasero 已提交
1559
	getWindowById(windowId: number): ICodeWindow {
1560
		const res = WindowsManager.WINDOWS.filter(w => w.id === windowId);
E
Erich Gamma 已提交
1561 1562 1563 1564 1565 1566 1567
		if (res && res.length === 1) {
			return res[0];
		}

		return null;
	}

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

B
Benjamin Pasero 已提交
1572
	getWindowCount(): number {
E
Erich Gamma 已提交
1573 1574 1575
		return WindowsManager.WINDOWS.length;
	}

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

		// Unresponsive
		if (error === WindowError.UNRESPONSIVE) {
1581
			this.dialogs.showMessageBox({
B
Benjamin Pasero 已提交
1582
				title: product.nameLong,
E
Erich Gamma 已提交
1583
				type: 'warning',
1584
				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"))],
1585 1586
				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 已提交
1587
				noLink: true
1588 1589 1590 1591
			}, window).then(result => {
				if (!window.win) {
					return; // Return early if the window has been going down already
				}
1592

1593 1594 1595 1596 1597 1598 1599
				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 已提交
1600 1601 1602 1603
		}

		// Crashed
		else {
1604
			this.dialogs.showMessageBox({
B
Benjamin Pasero 已提交
1605
				title: product.nameLong,
E
Erich Gamma 已提交
1606
				type: 'warning',
1607
				buttons: [mnemonicButtonLabel(localize({ key: 'reopen', comment: ['&& denotes a mnemonic'] }, "&&Reopen")), mnemonicButtonLabel(localize({ key: 'close', comment: ['&& denotes a mnemonic'] }, "&&Close"))],
1608 1609
				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 已提交
1610
				noLink: true
1611 1612 1613 1614
			}, window).then(result => {
				if (!window.win) {
					return; // Return early if the window has been going down already
				}
1615

1616 1617 1618 1619 1620 1621 1622
				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 已提交
1623 1624 1625
		}
	}

1626
	private onWindowClosed(win: ICodeWindow): void {
E
Erich Gamma 已提交
1627 1628 1629 1630 1631

		// Tell window
		win.dispose();

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

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

B
Benjamin Pasero 已提交
1640
	pickFileFolderAndOpen(options: INativeOpenDialogOptions): void {
B
Benjamin Pasero 已提交
1641
		this.doPickAndOpen(options, true /* pick folders */, true /* pick files */);
1642 1643
	}

B
Benjamin Pasero 已提交
1644
	pickFolderAndOpen(options: INativeOpenDialogOptions): void {
B
Benjamin Pasero 已提交
1645
		this.doPickAndOpen(options, true /* pick folders */, false /* pick files */);
1646 1647
	}

B
Benjamin Pasero 已提交
1648
	pickFileAndOpen(options: INativeOpenDialogOptions): void {
B
Benjamin Pasero 已提交
1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673
		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 已提交
1674
				// __GDPR__TODO__ classify event
B
Benjamin Pasero 已提交
1675 1676 1677 1678 1679 1680 1681 1682
				internalOptions.telemetryEventName = 'openFileFolder';
			} else if (pickFolders) {
				internalOptions.telemetryEventName = 'openFolder';
			} else {
				internalOptions.telemetryEventName = 'openFile';
			}
		}

1683 1684 1685
		this.dialogs.pickAndOpen(internalOptions);
	}

B
Benjamin Pasero 已提交
1686
	showMessageBox(options: Electron.MessageBoxOptions, win?: ICodeWindow): TPromise<IMessageBoxResult> {
1687 1688 1689
		return this.dialogs.showMessageBox(options, win);
	}

B
Benjamin Pasero 已提交
1690
	showSaveDialog(options: Electron.SaveDialogOptions, win?: ICodeWindow): TPromise<string> {
1691 1692 1693
		return this.dialogs.showSaveDialog(options, win);
	}

B
Benjamin Pasero 已提交
1694
	showOpenDialog(options: Electron.OpenDialogOptions, win?: ICodeWindow): TPromise<string[]> {
1695
		return this.dialogs.showOpenDialog(options, win);
B
Benjamin Pasero 已提交
1696 1697
	}

B
Benjamin Pasero 已提交
1698
	quit(): void {
B
Benjamin Pasero 已提交
1699 1700 1701

		// 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.
1702 1703 1704
		const window = this.getFocusedWindow();
		if (window && window.isExtensionDevelopmentHost && this.getWindowCount() > 1) {
			window.win.close();
B
Benjamin Pasero 已提交
1705 1706 1707 1708 1709 1710 1711 1712
		}

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

B
Benjamin Pasero 已提交
1716
interface IInternalNativeOpenDialogOptions extends INativeOpenDialogOptions {
B
Benjamin Pasero 已提交
1717 1718 1719 1720
	pickFolders?: boolean;
	pickFiles?: boolean;
}

1721
class Dialogs {
B
Benjamin Pasero 已提交
1722

1723
	private static readonly workingDirPickerStorageKey = 'pickerWorkingDir';
1724

1725 1726 1727
	private mapWindowToDialogQueue: Map<number, Queue<any>>;
	private noWindowDialogQueue: Queue<any>;

B
Benjamin Pasero 已提交
1728 1729 1730
	constructor(
		private environmentService: IEnvironmentService,
		private telemetryService: ITelemetryService,
B
Benjamin Pasero 已提交
1731
		private stateService: IStateService,
B
Benjamin Pasero 已提交
1732
		private windowsMainService: IWindowsMainService,
B
Benjamin Pasero 已提交
1733
	) {
1734 1735
		this.mapWindowToDialogQueue = new Map<number, Queue<any>>();
		this.noWindowDialogQueue = new Queue<any>();
B
Benjamin Pasero 已提交
1736 1737
	}

B
Benjamin Pasero 已提交
1738
	pickAndOpen(options: INativeOpenDialogOptions): void {
1739
		this.getFileOrFolderUris(options).then(paths => {
B
Benjamin Pasero 已提交
1740 1741 1742 1743
			const numberOfPaths = paths ? paths.length : 0;

			// Telemetry
			if (options.telemetryEventName) {
K
kieferrm 已提交
1744
				// __GDPR__TODO__ Dynamic event names and dynamic properties. Can not be registered statically.
B
Benjamin Pasero 已提交
1745 1746 1747 1748 1749 1750 1751 1752 1753
				this.telemetryService.publicLog(options.telemetryEventName, {
					...options.telemetryExtraData,
					outcome: numberOfPaths ? 'success' : 'canceled',
					numberOfPaths
				});
			}

			// Open
			if (numberOfPaths) {
1754 1755 1756
				this.windowsMainService.open({
					context: OpenContext.DIALOG,
					cli: this.environmentService.args,
S
Sandeep Somavarapu 已提交
1757
					urisToOpen: paths,
1758 1759 1760
					forceNewWindow: options.forceNewWindow,
					forceOpenWorkspaceAsFile: options.dialogOptions && !equals(options.dialogOptions.filters, WORKSPACE_FILTER)
				});
1761 1762 1763 1764
			}
		});
	}

1765
	private getFileOrFolderUris(options: IInternalNativeOpenDialogOptions): TPromise<URI[]> {
1766

B
Benjamin Pasero 已提交
1767 1768 1769 1770 1771 1772 1773
		// Ensure dialog options
		if (!options.dialogOptions) {
			options.dialogOptions = Object.create(null);
		}

		// Ensure defaultPath
		if (!options.dialogOptions.defaultPath) {
1774
			options.dialogOptions.defaultPath = this.stateService.getItem<string>(Dialogs.workingDirPickerStorageKey);
1775 1776
		}

B
Benjamin Pasero 已提交
1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789
		// Ensure properties
		if (typeof options.pickFiles === 'boolean' || typeof options.pickFolders === 'boolean') {
			options.dialogOptions.properties = void 0; // let it override based on the booleans

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

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

1790 1791 1792 1793
		if (isMacintosh) {
			options.dialogOptions.properties.push('treatPackageAsDirectory'); // always drill into .app files
		}

B
Benjamin Pasero 已提交
1794
		// Show Dialog
1795
		const focusedWindow = this.windowsMainService.getWindowById(options.windowId) || this.windowsMainService.getFocusedWindow();
1796 1797 1798 1799 1800 1801 1802

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

1803
				return paths.map(path => URI.file(path));
1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823
			}

			return void 0;
		});
	}

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

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

		return windowDialogQueue;
	}

B
Benjamin Pasero 已提交
1824
	showMessageBox(options: Electron.MessageBoxOptions, window?: ICodeWindow): TPromise<IMessageBoxResult> {
1825 1826
		return this.getDialogQueue(window).queue(() => {
			return new TPromise((c, e) => {
B
Benjamin Pasero 已提交
1827 1828 1829
				dialog.showMessageBox(window ? window.win : void 0, options, (response: number, checkboxChecked: boolean) => {
					c({ button: response, checkboxChecked });
				});
1830 1831 1832 1833
			});
		});
	}

B
Benjamin Pasero 已提交
1834
	showSaveDialog(options: Electron.SaveDialogOptions, window?: ICodeWindow): TPromise<string> {
B
Benjamin Pasero 已提交
1835

1836 1837 1838
		function normalizePath(path: string): string {
			if (path && isMacintosh) {
				path = normalizeNFC(path); // normalize paths returned from the OS
1839
			}
1840

1841 1842
			return path;
		}
1843

1844 1845
		return this.getDialogQueue(window).queue(() => {
			return new TPromise((c, e) => {
B
Benjamin Pasero 已提交
1846 1847 1848
				dialog.showSaveDialog(window ? window.win : void 0, options, path => {
					c(normalizePath(path));
				});
1849 1850 1851 1852
			});
		});
	}

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

1855 1856 1857 1858 1859 1860
		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;
1861
		}
B
Benjamin Pasero 已提交
1862

1863 1864
		return this.getDialogQueue(window).queue(() => {
			return new TPromise((c, e) => {
B
Benjamin Pasero 已提交
1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880

				// Ensure the path exists (if provided)
				let validatePathPromise: TPromise<void> = TPromise.as(void 0);
				if (options.defaultPath) {
					validatePathPromise = exists(options.defaultPath).then(exists => {
						if (!exists) {
							options.defaultPath = void 0;
						}
					});
				}

				// Show dialog and wrap as promise
				validatePathPromise.then(() => {
					dialog.showOpenDialog(window ? window.win : void 0, options, paths => {
						c(normalizePaths(paths));
					});
B
Benjamin Pasero 已提交
1881
				});
1882 1883
			});
		});
1884
	}
1885 1886 1887 1888 1889
}

class WorkspacesManager {

	constructor(
1890 1891
		private workspacesMainService: IWorkspacesMainService,
		private backupMainService: IBackupMainService,
1892 1893 1894 1895 1896
		private environmentService: IEnvironmentService,
		private windowsMainService: IWindowsMainService
	) {
	}

B
Benjamin Pasero 已提交
1897
	saveAndEnterWorkspace(window: ICodeWindow, path: string): TPromise<IEnterWorkspaceResult> {
1898 1899 1900 1901 1902 1903 1904
		if (!window || !window.win || window.readyState !== ReadyState.READY || !window.openedWorkspace || !path || !this.isValidTargetWorkspacePath(window, path)) {
			return TPromise.as(null); // return early if the window is not ready or disposed or does not have a workspace
		}

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

1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921
	enterWorkspace(window: ICodeWindow, path: string): TPromise<IEnterWorkspaceResult> {
		if (!window || !window.win || window.readyState !== ReadyState.READY) {
			return TPromise.as(null); // return early if the window is not ready or disposed
		}

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

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

	}

B
Benjamin Pasero 已提交
1922
	createAndEnterWorkspace(window: ICodeWindow, folders?: IWorkspaceFolderCreationData[], path?: string): TPromise<IEnterWorkspaceResult> {
1923
		if (!window || !window.win || window.readyState !== ReadyState.READY) {
1924 1925 1926
			return TPromise.as(null); // return early if the window is not ready or disposed
		}

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

1932
			return this.workspacesMainService.createWorkspace(folders).then(workspace => {
1933 1934
				return this.doSaveAndOpenWorkspace(window, workspace, path);
			});
1935
		});
1936

1937 1938
	}

1939
	private isValidTargetWorkspacePath(window: ICodeWindow, path?: string): TPromise<boolean> {
1940
		if (!path) {
1941
			return TPromise.wrap(true);
1942 1943 1944
		}

		if (window.openedWorkspace && window.openedWorkspace.configPath === path) {
1945
			return TPromise.wrap(false); // window is already opened on a workspace with that path
1946 1947 1948
		}

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

1959
			return this.windowsMainService.showMessageBox(options, this.windowsMainService.getFocusedWindow()).then(() => false);
1960 1961
		}

1962
		return TPromise.wrap(true); // OK
1963 1964
	}

1965
	private doSaveAndOpenWorkspace(window: ICodeWindow, workspace: IWorkspaceIdentifier, path?: string): TPromise<IEnterWorkspaceResult> {
1966 1967
		let savePromise: TPromise<IWorkspaceIdentifier>;
		if (path) {
1968
			savePromise = this.workspacesMainService.saveWorkspace(workspace, path);
1969 1970 1971 1972
		} else {
			savePromise = TPromise.as(workspace);
		}

1973 1974
		return savePromise.then(workspace => this.doOpenWorkspace(window, workspace));
	}
1975

1976 1977
	private doOpenWorkspace(window: ICodeWindow, workspace: IWorkspaceIdentifier): IEnterWorkspaceResult {
		window.focus();
1978

1979 1980 1981 1982 1983
		// Register window for backups and migrate current backups over
		let backupPath: string;
		if (!window.config.extensionDevelopmentPath) {
			backupPath = this.backupMainService.registerWorkspaceBackupSync(workspace, window.config.backupPath);
		}
1984

1985
		// Update window configuration properly based on transition to workspace
1986
		window.config.folderUri = void 0;
1987 1988 1989 1990
		window.config.workspace = workspace;
		window.config.backupPath = backupPath;

		return { workspace, backupPath };
1991 1992
	}

B
Benjamin Pasero 已提交
1993
	pickWorkspaceAndOpen(options: INativeOpenDialogOptions): void {
1994
		const window = this.windowsMainService.getWindowById(options.windowId) || this.windowsMainService.getFocusedWindow() || this.windowsMainService.getLastActiveWindow();
1995 1996 1997 1998 1999 2000 2001 2002

		this.windowsMainService.pickFileAndOpen({
			windowId: window ? window.id : void 0,
			dialogOptions: {
				buttonLabel: mnemonicButtonLabel(localize({ key: 'openWorkspace', comment: ['&& denotes a mnemonic'] }, "&&Open")),
				title: localize('openWorkspaceTitle', "Open Workspace"),
				filters: WORKSPACE_FILTER,
				properties: ['openFile'],
2003
				defaultPath: options.dialogOptions && options.dialogOptions.defaultPath
2004
			},
2005 2006 2007
			forceNewWindow: options.forceNewWindow,
			telemetryEventName: options.telemetryEventName,
			telemetryExtraData: options.telemetryExtraData
2008 2009 2010
		});
	}

B
Benjamin Pasero 已提交
2011
	promptToSaveUntitledWorkspace(window: ICodeWindow, workspace: IWorkspaceIdentifier): TPromise<boolean> {
2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044
		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;
		}

2045 2046 2047 2048 2049 2050 2051 2052 2053
		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:
2054
					this.workspacesMainService.deleteUntitledWorkspaceSync(workspace);
2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065
					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) {
2066
							return this.workspacesMainService.saveWorkspace(workspace, target).then(() => false, () => false);
2067
						}
2068

2069 2070
						return true; // keep veto if no target was provided
					});
2071 2072
				}
			}
2073
		});
2074 2075
	}

2076
	private getUntitledWorkspaceSaveDialogDefaultPath(workspace?: IWorkspaceIdentifier | ISingleFolderWorkspaceIdentifier): string {
2077
		if (workspace) {
2078
			if (isSingleFolderWorkspaceIdentifier(workspace)) {
2079
				return workspace.scheme === Schemas.file ? dirname(workspace.fsPath) : void 0;
J
Johannes Rieken 已提交
2080 2081
			}

2082
			const resolvedWorkspace = this.workspacesMainService.resolveWorkspaceSync(workspace.configPath);
J
Johannes Rieken 已提交
2083 2084 2085 2086 2087
			if (resolvedWorkspace && resolvedWorkspace.folders.length > 0) {
				for (const folder of resolvedWorkspace.folders) {
					if (folder.uri.scheme === Schemas.file) {
						return dirname(folder.uri.fsPath);
					}
2088 2089 2090
				}
			}
		}
2091

J
Johannes Rieken 已提交
2092
		return void 0;
2093
	}
J
Johannes Rieken 已提交
2094
}