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

'use strict';

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

enum WindowError {
	UNRESPONSIVE,
	CRASHED
}

43 44 45 46
interface INewWindowState extends ISingleWindowState {
	hasDefaultState?: boolean;
}

47
interface ILegacyWindowState extends IWindowState {
E
Erich Gamma 已提交
48
	workspacePath?: string;
49 50 51
}

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

58 59 60 61
interface ILegacyWindowsState extends IWindowsState {
	openedFolders?: IWindowState[];
}

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
	folderPath?: string;
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 85 86

	forceNewWindow?: boolean;
	windowToUse?: CodeWindow;

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

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

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

95 96
	// the folder path for a Code instance to open
	folderPath?: string;
97 98 99 100 101 102 103 104

	// 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 已提交
105
export class WindowsManager implements IWindowsMainService {
J
Joao Moreno 已提交
106

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

	private static windowsStateStorageKey = 'windowsState';

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

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

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

B
Benjamin Pasero 已提交
118
	private fileDialog: FileDialog;
119
	private workspacesManager: WorkspacesManager;
B
Benjamin Pasero 已提交
120

B
Benjamin Pasero 已提交
121 122
	private _onWindowReady = new Emitter<CodeWindow>();
	onWindowReady: CommonEvent<CodeWindow> = this._onWindowReady.event;
123 124 125 126

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

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

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

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

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

J
Joao Moreno 已提交
139 140
	constructor(
		@ILogService private logService: ILogService,
J
Joao Moreno 已提交
141
		@IStorageService private storageService: IStorageService,
142
		@IEnvironmentService private environmentService: IEnvironmentService,
B
Benjamin Pasero 已提交
143
		@ILifecycleService private lifecycleService: ILifecycleService,
144
		@IBackupMainService private backupService: IBackupMainService,
145
		@ITelemetryService private telemetryService: ITelemetryService,
146
		@IConfigurationService private configurationService: IConfigurationService,
B
Benjamin Pasero 已提交
147
		@IHistoryMainService private historyService: IHistoryMainService,
148 149
		@IWorkspacesMainService private workspacesService: IWorkspacesMainService,
		@IInstantiationService private instantiationService: IInstantiationService
150
	) {
151
		this.windowsState = this.storageService.getItem<IWindowsState>(WindowsManager.windowsStateStorageKey) || { openedWindows: [] };
152

153
		this.fileDialog = new FileDialog(environmentService, telemetryService, storageService, this);
154
		this.workspacesManager = new WorkspacesManager(workspacesService, lifecycleService, backupService, environmentService, this);
155

156 157
		this.migrateLegacyWindowState();
	}
158

159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
	private migrateLegacyWindowState(): void {
		const state: ILegacyWindowsState = this.windowsState;

		// TODO@Ben migration from previous openedFolders to new openedWindows property
		if (Array.isArray(state.openedFolders) && state.openedFolders.length > 0) {
			state.openedWindows = state.openedFolders;
			state.openedFolders = void 0;
		} else if (!state.openedWindows) {
			state.openedWindows = [];
		}

		// TODO@Ben migration from previous workspacePath in window state to folderPath
		const states: ILegacyWindowState[] = [];
		states.push(state.lastActiveWindow);
		states.push(state.lastPluginDevelopmentHostWindow);
		states.push(...state.openedWindows);
		states.forEach(state => {
176 177 178 179 180
			if (!state) {
				return;
			}

			if (typeof state.workspacePath === 'string') {
181 182 183 184
				state.folderPath = state.workspacePath;
				state.workspacePath = void 0;
			}
		});
185
	}
J
Joao Moreno 已提交
186

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

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

	private registerListeners(): void {
194

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

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

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

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

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

226 227
		// Handle various lifecycle events around windows
		this.lifecycleService.onBeforeWindowUnload(e => this.onBeforeWindowUnload(e));
B
Benjamin Pasero 已提交
228
		this.lifecycleService.onBeforeWindowClose(win => this.onBeforeWindowClose(win as CodeWindow));
229
		this.lifecycleService.onBeforeQuit(() => this.onBeforeQuit());
230 231 232 233 234 235 236 237
		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;
			}
		});
238 239
	}

240 241 242 243 244 245 246
	// Note that onBeforeQuit() and onBeforeWindowClose() are fired in different order depending on the OS:
	// - macOS: since the app will not quit when closing the last window, you will always first get
	//          the onBeforeQuit() event followed by N onbeforeWindowClose() events for each window
	// - other: on other OS, closing the last window will quit the app so the order depends on the
	//          user interaction: closing the last window will first trigger onBeforeWindowClose()
	//          and then onBeforeQuit(). Using the quit action however will first issue onBeforeQuit()
	//          and then onBeforeWindowClose().
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
	//
	// Here is the behaviour on different OS dependig on action taken (Electron 1.7.x):
	//
	// Legend
	// -  quit(N): quit application with N windows opened
	// - close(1): close one window via the window close button
	// - closeAll: close all windows via the taskbar command
	// - onBeforeQuit(N): number of windows reported in this event handler
	// - onBeforeWindowClose(N, M): number of windows reported and quitRequested boolean in this event handler
	//
	// macOS
	// 	-     quit(1): onBeforeQuit(1), onBeforeWindowClose(1, true)
	// 	-     quit(2): onBeforeQuit(2), onBeforeWindowClose(2, true), onBeforeWindowClose(2, true)
	// 	-     quit(0): onBeforeQuit(0)
	// 	-    close(1): onBeforeWindowClose(1, false)
	//
	// Windows
	// 	-     quit(1): onBeforeQuit(1), onBeforeWindowClose(1, true)
	// 	-     quit(2): onBeforeQuit(2), onBeforeWindowClose(2, true), onBeforeWindowClose(2, true)
	// 	-    close(1): onBeforeWindowClose(2, false)[not last window]
	// 	-    close(1): onBeforeWindowClose(1, false), onBeforequit(0)[last window]
	// 	- closeAll(2): onBeforeWindowClose(2, false), onBeforeWindowClose(2, false), onBeforeQuit(0)
	//
	// Linux
	// 	-     quit(1): onBeforeQuit(1), onBeforeWindowClose(1, true)
	// 	-     quit(2): onBeforeQuit(2), onBeforeWindowClose(2, true), onBeforeWindowClose(2, true)
	// 	-    close(1): onBeforeWindowClose(2, false)[not last window]
	// 	-    close(1): onBeforeWindowClose(1, false), onBeforequit(0)[last window]
	// 	- closeAll(2): onBeforeWindowClose(2, false), onBeforeWindowClose(2, false), onBeforeQuit(0)
	//
277
	private onBeforeQuit(): void {
278
		const currentWindowsState: ILegacyWindowsState = {
279
			openedWindows: [],
280
			lastPluginDevelopmentHostWindow: this.windowsState.lastPluginDevelopmentHostWindow,
281
			lastActiveWindow: this.lastClosedWindowState
282 283 284 285 286 287 288 289
		};

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

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

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

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

311 312 313
		// Persist
		this.storageService.setItem(WindowsManager.windowsStateStorageKey, currentWindowsState);
	}
314

315
	// See note on #onBeforeQuit() for details how these events are flowing
B
Benjamin Pasero 已提交
316
	private onBeforeWindowClose(win: CodeWindow): void {
317 318 319 320 321
		if (this.lifecycleService.isQuitRequested()) {
			return; // during quit, many windows close in parallel so let it be handled in the before-quit handler
		}

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

327
		// Any non extension host window with same workspace or folder
328
		else if (!win.isExtensionDevelopmentHost && (!!win.openedWorkspace || !!win.openedFolderPath)) {
329
			this.windowsState.openedWindows.forEach(o => {
B
fix npe  
Benjamin Pasero 已提交
330
				const sameWorkspace = win.openedWorkspace && o.workspace && o.workspace.id === win.openedWorkspace.id;
331 332 333
				const sameFolder = win.openedFolderPath && isEqual(o.folderPath, win.openedFolderPath, !isLinux /* ignorecase */);

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

348 349
	private toWindowState(win: CodeWindow): IWindowState {
		return {
350
			workspace: win.openedWorkspace,
351 352 353 354 355 356
			folderPath: win.openedFolderPath,
			backupPath: win.backupPath,
			uiState: win.serializeWindowState()
		};
	}

B
Benjamin Pasero 已提交
357
	public open(openConfig: IOpenConfiguration): CodeWindow[] {
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: IPath[] = [];
365 366 367 368
		if (openConfig.addMode && product.quality !== 'stable') { // TODO@Ben multi root
			foldersToAdd = pathsToOpen.filter(path => !!path.folderPath).map(path => ({ filePath: path.folderPath }));
			pathsToOpen = pathsToOpen.filter(path => !path.folderPath);
		}
E
Erich Gamma 已提交
369

B
Benjamin Pasero 已提交
370 371
		let filesToOpen = pathsToOpen.filter(path => !!path.filePath && !path.createFilePath);
		let filesToCreate = pathsToOpen.filter(path => !!path.filePath && 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)
		//
B
Benjamin Pasero 已提交
396
		const foldersToOpen = arrays.distinct(pathsToOpen.filter(win => win.folderPath && !win.filePath).map(win => win.folderPath), folder => isLinux ? folder : folder.toLowerCase()); // 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 402 403 404 405 406
		let foldersToRestore: string[] = [];
		let workspacesToRestore: IWorkspaceIdentifier[] = [];
		let emptyToRestore: string[] = [];
		if (openConfig.initialStartup && !openConfig.cli.extensionDevelopmentPath) {
			foldersToRestore = this.backupService.getFolderBackupPaths();

407 408
			workspacesToRestore = this.backupService.getWorkspaceBackups();						// collect from workspaces with hot-exit backups
			workspacesToRestore.push(...this.workspacesService.getUntitledWorkspacesSync());	// collect from previous window session
409 410

			emptyToRestore = this.backupService.getEmptyWindowBackupPaths();
411
			emptyToRestore.push(...pathsToOpen.filter(w => !w.workspace && !w.folderPath && 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
		//
B
Benjamin Pasero 已提交
418
		const emptyToOpen = pathsToOpen.filter(win => !win.workspace && !win.folderPath && !win.filePath && !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 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
		// Make sure to pass focus to one of the windows if we open multiple
		if (usedWindows.length > 1) {
			let focusLast = true;

			// Only focus the last active window if the user did not open a specific path via
			// CLI or API. In those cases we do not want windows to get focus from previous
			// session but actually one of the windows the user explicitly asked to open.
			const focusLastActive = !openConfig.forceEmpty && !openConfig.cli._.length && (!openConfig.pathsToOpen || !openConfig.pathsToOpen.length);
			if (focusLastActive && this.windowsState.lastActiveWindow) {
				const lastActiveWindw = usedWindows.filter(w => w.backupPath === this.windowsState.lastActiveWindow.backupPath);
				if (lastActiveWindw.length) {
					lastActiveWindw[0].focus();
					focusLast = false;
				}
			}

			// Otherwise: focus last window we opened
			if (focusLast) {
				usedWindows[usedWindows.length - 1].focus();
442 443
			}
		}
444

445 446 447
		// 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) {
448
			const recentlyOpenedWorkspaces: (IWorkspaceIdentifier | ISingleFolderWorkspaceIdentifier)[] = [];
449
			const recentlyOpenedFiles: string[] = [];
450

B
Benjamin Pasero 已提交
451
			pathsToOpen.forEach(win => {
452 453 454 455
				if (win.workspace || win.folderPath) {
					recentlyOpenedWorkspaces.push(win.workspace || win.folderPath);
				} else if (win.filePath) {
					recentlyOpenedFiles.push(win.filePath);
456 457 458
				}
			});

459
			this.historyService.addRecentlyOpened(recentlyOpenedWorkspaces, recentlyOpenedFiles);
460
		}
461

462
		// If we got started with --wait from the CLI, we need to signal to the outside when the window
463 464
		// 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.
465
		if (openConfig.context === OpenContext.CLI && openConfig.cli.wait && openConfig.cli.waitMarkerFilePath && usedWindows.length === 1 && usedWindows[0]) {
466
			this.waitForWindowCloseOrLoad(usedWindows[0].id).done(() => fs.unlink(openConfig.cli.waitMarkerFilePath, error => void 0));
467 468
		}

469 470 471
		return usedWindows;
	}

472 473 474 475 476 477 478 479 480 481
	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;
	}

482 483
	private doOpen(
		openConfig: IOpenConfiguration,
484 485
		workspacesToOpen: IWorkspaceIdentifier[],
		workspacesToRestore: IWorkspaceIdentifier[],
486 487 488 489 490 491
		foldersToOpen: string[],
		foldersToRestore: string[],
		emptyToRestore: string[],
		emptyToOpen: number,
		filesToOpen: IPath[],
		filesToCreate: IPath[],
492
		filesToDiff: IPath[],
493
		filesToWait: IPathsToWaitFor,
494
		foldersToAdd: IPath[]
495
	) {
496
		const usedWindows: CodeWindow[] = [];
497

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

501 502 503 504 505 506 507 508 509 510 511
		// 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 已提交
512
		// 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
513 514
		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 已提交
515

516
			// Find suitable window or folder path to open files in
517
			const fileToCheck = filesToOpen[0] || filesToCreate[0] || filesToDiff[0];
518
			let bestWindowOrFolder = findBestWindowOrFolderForFile({
519 520 521 522 523
				windows: WindowsManager.WINDOWS,
				newWindow: openFilesInNewWindow,
				reuseWindow: openConfig.forceReuseWindow,
				context: openConfig.context,
				filePath: fileToCheck && fileToCheck.filePath,
524 525
				userHome: this.environmentService.userHome,
				workspaceResolver: workspace => this.workspacesService.resolveWorkspaceSync(workspace.configPath)
526
			});
B
Benjamin Pasero 已提交
527

528 529 530 531 532 533
			// Special case: we started with --wait and we got back a folder to open. In this case
			// we actually prefer to not open the folder but operate purely on the file.
			if (typeof bestWindowOrFolder === 'string' && filesToWait) {
				bestWindowOrFolder = !openFilesInNewWindow ? this.getLastActiveWindow() : null;
			}

534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
			// We found a window to open the files in
			if (bestWindowOrFolder instanceof CodeWindow) {

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

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

				// Window is empty
				else {

					// Do open files
551
					usedWindows.push(this.doOpenFilesInExistingWindow(bestWindowOrFolder, filesToOpen, filesToCreate, filesToDiff, filesToWait));
552 553 554 555 556

					// Reset these because we handled them
					filesToOpen = [];
					filesToCreate = [];
					filesToDiff = [];
557
					filesToWait = void 0;
558
				}
559 560 561 562 563
			}

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

566
			// Finally, if no window or folder is found, just open the files in an empty window
E
Erich Gamma 已提交
567
			else {
B
Benjamin Pasero 已提交
568
				usedWindows.push(this.openInBrowserWindow({
B
Benjamin Pasero 已提交
569 570 571 572 573 574
					userEnv: openConfig.userEnv,
					cli: openConfig.cli,
					initialStartup: openConfig.initialStartup,
					filesToOpen,
					filesToCreate,
					filesToDiff,
575
					filesToWait,
B
Benjamin Pasero 已提交
576
					forceNewWindow: true
B
Benjamin Pasero 已提交
577
				}));
E
Erich Gamma 已提交
578

579 580 581 582
				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
				filesToDiff = [];
583
				filesToWait = void 0;
E
Erich Gamma 已提交
584 585 586
			}
		}

587
		// Handle workspaces to open (instructed and to restore)
588
		const allWorkspacesToOpen = arrays.distinct([...workspacesToRestore, ...workspacesToOpen], workspace => workspace.id); // prevent duplicates
589 590 591 592 593 594 595 596
		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
597
				usedWindows.push(this.doOpenFilesInExistingWindow(windowOnWorkspace, filesToOpen, filesToCreate, filesToDiff, filesToWait));
598 599 600 601 602

				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
				filesToDiff = [];
603
				filesToWait = void 0;
604 605 606 607 608 609

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

			// Open remaining ones
			allWorkspacesToOpen.forEach(workspaceToOpen => {
610
				if (windowsOnWorkspace.some(win => win.openedWorkspace.id === workspaceToOpen.id)) {
611 612 613 614
					return; // ignore folders that are already open
				}

				// Do open folder
615
				usedWindows.push(this.doOpenFolderOrWorkspace(openConfig, { workspace: workspaceToOpen }, openFolderInNewWindow, filesToOpen, filesToCreate, filesToDiff, filesToWait));
616 617 618 619 620

				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
				filesToDiff = [];
621
				filesToWait = void 0;
622 623 624 625 626

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

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

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

636
				// Do open files
637
				usedWindows.push(this.doOpenFilesInExistingWindow(windowOnFolderPath, filesToOpen, filesToCreate, filesToDiff, filesToWait));
638

E
Erich Gamma 已提交
639 640 641
				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
642
				filesToDiff = [];
643
				filesToWait = void 0;
E
Erich Gamma 已提交
644

B
Benjamin Pasero 已提交
645
				openFolderInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
646 647 648
			}

			// Open remaining ones
649
			allFoldersToOpen.forEach(folderToOpen => {
650
				if (windowsOnFolderPath.some(win => isEqual(win.openedFolderPath, folderToOpen, !isLinux /* ignorecase */))) {
E
Erich Gamma 已提交
651 652 653
					return; // ignore folders that are already open
				}

654
				// Do open folder
655
				usedWindows.push(this.doOpenFolderOrWorkspace(openConfig, { folderPath: folderToOpen }, openFolderInNewWindow, filesToOpen, filesToCreate, filesToDiff, filesToWait));
E
Erich Gamma 已提交
656 657 658 659

				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
660
				filesToDiff = [];
661
				filesToWait = void 0;
E
Erich Gamma 已提交
662

B
Benjamin Pasero 已提交
663
				openFolderInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
664 665 666
			});
		}

667
		// Handle empty to restore
668
		if (emptyToRestore.length > 0) {
669
			emptyToRestore.forEach(emptyWindowBackupFolder => {
B
Benjamin Pasero 已提交
670
				usedWindows.push(this.openInBrowserWindow({
B
Benjamin Pasero 已提交
671 672 673 674 675 676
					userEnv: openConfig.userEnv,
					cli: openConfig.cli,
					initialStartup: openConfig.initialStartup,
					filesToOpen,
					filesToCreate,
					filesToDiff,
677
					filesToWait,
B
Benjamin Pasero 已提交
678
					forceNewWindow: true,
679
					emptyWindowBackupFolder
B
Benjamin Pasero 已提交
680
				}));
681

B
wip  
Benjamin Pasero 已提交
682 683 684 685
				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
				filesToDiff = [];
686
				filesToWait = void 0;
B
wip  
Benjamin Pasero 已提交
687

B
Benjamin Pasero 已提交
688
				openFolderInNewWindow = true; // any other folders to open must open in new window then
689 690
			});
		}
B
Benjamin Pasero 已提交
691

692 693
		// Handle empty to open (only if no other window opened)
		if (usedWindows.length === 0) {
694
			for (let i = 0; i < emptyToOpen; i++) {
B
Benjamin Pasero 已提交
695
				usedWindows.push(this.openInBrowserWindow({
B
Benjamin Pasero 已提交
696 697 698
					userEnv: openConfig.userEnv,
					cli: openConfig.cli,
					initialStartup: openConfig.initialStartup,
699
					forceNewWindow: openFolderInNewWindow
B
Benjamin Pasero 已提交
700
				}));
E
Erich Gamma 已提交
701

702
				openFolderInNewWindow = true; // any other window to open must open in new window then
703 704
			}
		}
E
Erich Gamma 已提交
705

706
		return arrays.distinct(usedWindows);
E
Erich Gamma 已提交
707 708
	}

709
	private doOpenFilesInExistingWindow(window: CodeWindow, filesToOpen: IPath[], filesToCreate: IPath[], filesToDiff: IPath[], filesToWait: IPathsToWaitFor): CodeWindow {
710 711 712
		window.focus(); // make sure window has focus

		window.ready().then(readyWindow => {
713
			readyWindow.send('vscode:openFiles', { filesToOpen, filesToCreate, filesToDiff, filesToWait });
714
		});
B
Benjamin Pasero 已提交
715 716

		return window;
717 718
	}

719 720 721 722 723 724 725 726 727 728
	private doAddFoldersToExistingWidow(window: CodeWindow, foldersToAdd: IPath[]): CodeWindow {
		window.focus(); // make sure window has focus

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

		return window;
	}

729
	private doOpenFolderOrWorkspace(openConfig: IOpenConfiguration, folderOrWorkspace: IPathToOpen, openInNewWindow: boolean, filesToOpen: IPath[], filesToCreate: IPath[], filesToDiff: IPath[], filesToWait: IPathsToWaitFor, windowToUse?: CodeWindow): CodeWindow {
730 731 732 733
		const browserWindow = this.openInBrowserWindow({
			userEnv: openConfig.userEnv,
			cli: openConfig.cli,
			initialStartup: openConfig.initialStartup,
734
			workspace: folderOrWorkspace.workspace,
735 736 737 738
			folderPath: folderOrWorkspace.folderPath,
			filesToOpen,
			filesToCreate,
			filesToDiff,
739
			filesToWait,
740 741
			forceNewWindow: openInNewWindow,
			windowToUse
742 743 744 745 746
		});

		return browserWindow;
	}

B
Benjamin Pasero 已提交
747 748
	private getPathsToOpen(openConfig: IOpenConfiguration): IPathToOpen[] {
		let windowsToOpen: IPathToOpen[];
749
		let isCommandLineOrAPICall = false;
E
Erich Gamma 已提交
750

751
		// Extract paths: from API
B
Benjamin Pasero 已提交
752
		if (openConfig.pathsToOpen && openConfig.pathsToOpen.length > 0) {
753
			windowsToOpen = this.doExtractPathsFromAPI(openConfig);
754
			isCommandLineOrAPICall = true;
E
Erich Gamma 已提交
755 756
		}

B
Benjamin Pasero 已提交
757 758
		// Check for force empty
		else if (openConfig.forceEmpty) {
759
			windowsToOpen = [Object.create(null)];
E
Erich Gamma 已提交
760 761
		}

762
		// Extract paths: from CLI
B
Benjamin Pasero 已提交
763
		else if (openConfig.cli._.length > 0) {
764
			windowsToOpen = this.doExtractPathsFromCLI(openConfig.cli);
765
			isCommandLineOrAPICall = true;
B
Benjamin Pasero 已提交
766 767
		}

768
		// Extract windows: from previous session
B
Benjamin Pasero 已提交
769
		else {
770
			windowsToOpen = this.doGetWindowsFromLastSession();
B
Benjamin Pasero 已提交
771 772
		}

773 774
		// Convert multiple folders into workspace (if opened via API or CLI)
		// This will ensure to open these folders in one window instead of multiple
775 776 777
		// If we are in addMode, we should not do this because in that case all
		// folders should be added to the existing window.
		if (!openConfig.addMode && isCommandLineOrAPICall && product.quality !== 'stable') { // TODO@Ben multi root
778 779 780 781 782 783 784 785 786 787
			const foldersToOpen = windowsToOpen.filter(path => !!path.folderPath);
			if (foldersToOpen.length > 1) {
				const workspace = this.workspacesService.createWorkspaceSync(foldersToOpen.map(folder => folder.folderPath));

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

788
		return windowsToOpen;
E
Erich Gamma 已提交
789 790
	}

791 792 793
	private doExtractPathsFromAPI(openConfig: IOpenConfiguration): IPath[] {
		let pathsToOpen = openConfig.pathsToOpen.map(pathToOpen => {
			const path = this.parsePath(pathToOpen, { gotoLineMode: openConfig.cli && openConfig.cli.goto, forceOpenWorkspaceAsFile: openConfig.forceOpenWorkspaceAsFile });
794 795 796

			// Warn if the requested path to open does not exist
			if (!path) {
797
				const options: Electron.MessageBoxOptions = {
798 799
					title: product.nameLong,
					type: 'info',
800 801 802
					buttons: [localize('ok', "OK")],
					message: localize('pathNotExistTitle', "Path does not exist"),
					detail: localize('pathNotExistDetail', "The path '{0}' does not seem to exist anymore on disk.", pathToOpen),
803 804 805 806 807 808 809 810 811 812
					noLink: true
				};

				const activeWindow = BrowserWindow.getFocusedWindow();
				if (activeWindow) {
					dialog.showMessageBox(activeWindow, options);
				} else {
					dialog.showMessageBox(options);
				}
			}
B
Benjamin Pasero 已提交
813

814 815 816 817 818 819 820 821 822 823
			return path;
		});

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

		return pathsToOpen;
	}

	private doExtractPathsFromCLI(cli: ParsedArgs): IPath[] {
824
		const pathsToOpen = arrays.coalesce(cli._.map(candidate => this.parsePath(candidate, { ignoreFileNotFound: true, gotoLineMode: cli.goto })));
825 826
		if (pathsToOpen.length > 0) {
			return pathsToOpen;
B
Benjamin Pasero 已提交
827 828 829 830 831 832
		}

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

B
Benjamin Pasero 已提交
833
	private doGetWindowsFromLastSession(): IPathToOpen[] {
834 835
		const restoreWindows = this.getRestoreWindowsSetting();
		const lastActiveWindow = this.windowsState.lastActiveWindow;
B
Benjamin Pasero 已提交
836

837
		switch (restoreWindows) {
B
Benjamin Pasero 已提交
838

839
			// none: we always open an empty window
840 841
			case 'none':
				return [Object.create(null)];
B
Benjamin Pasero 已提交
842

843
			// one: restore last opened workspace/folder or empty window
844 845
			case 'one':
				if (lastActiveWindow) {
B
Benjamin Pasero 已提交
846

847
					// workspace
B
Benjamin Pasero 已提交
848 849 850 851 852 853
					const candidateWorkspace = lastActiveWindow.workspace;
					if (candidateWorkspace) {
						const validatedWorkspace = this.parsePath(candidateWorkspace.configPath);
						if (validatedWorkspace && validatedWorkspace.workspace) {
							return [validatedWorkspace];
						}
854 855 856 857 858
					}

					// folder (if path is valid)
					else if (lastActiveWindow.folderPath) {
						const validatedFolder = this.parsePath(lastActiveWindow.folderPath);
B
Benjamin Pasero 已提交
859
						if (validatedFolder && validatedFolder.folderPath) {
860
							return [validatedFolder];
861 862
						}
					}
B
Benjamin Pasero 已提交
863

864
					// otherwise use backup path to restore empty windows
865 866 867 868 869 870 871 872 873 874
					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 已提交
875
				const windowsToOpen: IPathToOpen[] = [];
876

877
				// Workspaces
B
Benjamin Pasero 已提交
878
				const workspaceCandidates = this.windowsState.openedWindows.filter(w => !!w.workspace).map(w => w.workspace);
879
				if (lastActiveWindow && lastActiveWindow.workspace) {
B
Benjamin Pasero 已提交
880
					workspaceCandidates.push(lastActiveWindow.workspace);
881
				}
B
Benjamin Pasero 已提交
882
				windowsToOpen.push(...workspaceCandidates.map(candidate => this.parsePath(candidate.configPath)).filter(window => window && window.workspace));
B
Benjamin Pasero 已提交
883

884
				// Folders
B
Benjamin Pasero 已提交
885
				const folderCandidates = this.windowsState.openedWindows.filter(w => !!w.folderPath).map(w => w.folderPath);
886
				if (lastActiveWindow && lastActiveWindow.folderPath) {
B
Benjamin Pasero 已提交
887
					folderCandidates.push(lastActiveWindow.folderPath);
888
				}
B
Benjamin Pasero 已提交
889
				windowsToOpen.push(...folderCandidates.map(candidate => this.parsePath(candidate)).filter(window => window && window.folderPath));
B
Benjamin Pasero 已提交
890

891 892
				// Windows that were Empty
				if (restoreWindows === 'all') {
893 894
					const lastOpenedEmpty = this.windowsState.openedWindows.filter(w => !w.workspace && !w.folderPath && w.backupPath).map(w => w.backupPath);
					const lastActiveEmpty = lastActiveWindow && !lastActiveWindow.workspace && !lastActiveWindow.folderPath && lastActiveWindow.backupPath;
895 896 897 898 899 900 901 902 903 904 905 906
					if (lastActiveEmpty) {
						lastOpenedEmpty.push(lastActiveEmpty);
					}

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

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

				break;
B
Benjamin Pasero 已提交
907
		}
E
Erich Gamma 已提交
908

909
		// Always fallback to empty window
B
Benjamin Pasero 已提交
910
		return [Object.create(null)];
E
Erich Gamma 已提交
911 912
	}

913 914 915 916 917 918
	private getRestoreWindowsSetting(): RestoreWindowsSetting {
		let restoreWindows: RestoreWindowsSetting;
		if (this.lifecycleService.wasRestarted) {
			restoreWindows = 'all'; // always reopen all windows when an update was applied
		} else {
			const windowConfig = this.configurationService.getConfiguration<IWindowSettings>('window');
919
			restoreWindows = ((windowConfig && windowConfig.restoreWindows) || 'one') as RestoreWindowsSetting;
920

B
fix npe  
Benjamin Pasero 已提交
921
			if (restoreWindows === 'one' /* default */ && windowConfig && windowConfig.reopenFolders) {
922 923 924 925 926 927 928 929 930 931 932
				restoreWindows = windowConfig.reopenFolders; // TODO@Ben migration
			}

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

		return restoreWindows;
	}

B
Benjamin Pasero 已提交
933
	private parsePath(anyPath: string, options?: { ignoreFileNotFound?: boolean, gotoLineMode?: boolean, forceOpenWorkspaceAsFile?: boolean; }): IPathToOpen {
E
Erich Gamma 已提交
934 935 936 937
		if (!anyPath) {
			return null;
		}

938
		let parsedPath: IPathWithLineAndColumn;
939 940 941

		const gotoLineMode = options && options.gotoLineMode;
		if (options && options.gotoLineMode) {
J
Joao Moreno 已提交
942
			parsedPath = parseLineAndColumnAware(anyPath);
E
Erich Gamma 已提交
943 944 945
			anyPath = parsedPath.path;
		}

946
		const candidate = normalize(anyPath);
E
Erich Gamma 已提交
947
		try {
B
Benjamin Pasero 已提交
948
			const candidateStat = fs.statSync(candidate);
E
Erich Gamma 已提交
949
			if (candidateStat) {
950
				if (candidateStat.isFile()) {
951

952 953 954 955
					// Workspace (unless disabled via flag)
					if (!options || !options.forceOpenWorkspaceAsFile) {
						const workspace = this.workspacesService.resolveWorkspaceSync(candidate);
						if (workspace) {
956
							return { workspace: { id: workspace.id, configPath: workspace.configPath } };
957
						}
958 959 960
					}

					// File
961
					return {
962
						filePath: candidate,
E
Erich Gamma 已提交
963
						lineNumber: gotoLineMode ? parsedPath.line : void 0,
964
						columnNumber: gotoLineMode ? parsedPath.column : void 0
965 966 967 968 969 970 971
					};
				}

				// Folder
				return {
					folderPath: candidate
				};
E
Erich Gamma 已提交
972 973
			}
		} catch (error) {
974
			this.historyService.removeFromRecentlyOpened([candidate]); // since file does not seem to exist anymore, remove from recent
975

976
			if (options && options.ignoreFileNotFound) {
E
Erich Gamma 已提交
977 978 979 980 981 982 983
				return { filePath: candidate, createFilePath: true }; // assume this is a file that does not yet exist
			}
		}

		return null;
	}

B
Benjamin Pasero 已提交
984 985 986 987
	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
		const windowConfig = this.configurationService.getConfiguration<IWindowSettings>('window');
988 989 990
		const openFolderInNewWindowConfig = (windowConfig && windowConfig.openFoldersInNewWindow) || 'default' /* default */;
		const openFilesInNewWindowConfig = (windowConfig && windowConfig.openFilesInNewWindow) || 'off' /* default */;

B
Benjamin Pasero 已提交
991
		let openFolderInNewWindow = (openConfig.preferNewWindow || openConfig.forceNewWindow) && !openConfig.forceReuseWindow;
992 993
		if (!openConfig.forceNewWindow && !openConfig.forceReuseWindow && (openFolderInNewWindowConfig === 'on' || openFolderInNewWindowConfig === 'off')) {
			openFolderInNewWindow = (openFolderInNewWindowConfig === 'on');
B
Benjamin Pasero 已提交
994 995 996 997 998 999 1000 1001 1002 1003 1004
		}

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

1005 1006
			if (!openConfig.cli.extensionDevelopmentPath && (openFilesInNewWindowConfig === 'on' || openFilesInNewWindowConfig === 'off')) {
				openFilesInNewWindow = (openFilesInNewWindowConfig === 'on');
B
Benjamin Pasero 已提交
1007 1008 1009 1010 1011 1012
			}
		}

		return { openFolderInNewWindow, openFilesInNewWindow };
	}

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

B
Benjamin Pasero 已提交
1015 1016 1017
		// 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.
1018 1019 1020 1021
		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 已提交
1022

B
Benjamin Pasero 已提交
1023 1024
			return;
		}
E
Erich Gamma 已提交
1025

1026
		// Fill in previously opened workspace unless an explicit path is provided and we are not unit testing
B
Benjamin Pasero 已提交
1027
		if (openConfig.cli._.length === 0 && !openConfig.cli.extensionTestsPath) {
1028 1029 1030 1031
			const extensionDevelopmentWindowState = this.windowsState.lastPluginDevelopmentHostWindow;
			const workspaceToOpen = extensionDevelopmentWindowState && (extensionDevelopmentWindowState.workspace || extensionDevelopmentWindowState.folderPath);
			if (workspaceToOpen) {
				openConfig.cli._ = [isSingleFolderWorkspaceIdentifier(workspaceToOpen) ? workspaceToOpen : workspaceToOpen.configPath];
E
Erich Gamma 已提交
1032 1033 1034
			}
		}

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

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

B
Benjamin Pasero 已提交
1044 1045 1046 1047 1048 1049 1050 1051
	private openInBrowserWindow(options: IOpenBrowserWindowOptions): CodeWindow {

		// Build IWindowConfiguration from config and options
		const configuration: IWindowConfiguration = mixin({}, options.cli); // inherit all properties from CLI
		configuration.appRoot = this.environmentService.appRoot;
		configuration.execPath = process.execPath;
		configuration.userEnv = assign({}, this.initialUserEnv, options.userEnv || {});
		configuration.isInitialStartup = options.initialStartup;
1052
		configuration.workspace = options.workspace;
1053
		configuration.folderPath = options.folderPath;
B
Benjamin Pasero 已提交
1054 1055 1056
		configuration.filesToOpen = options.filesToOpen;
		configuration.filesToCreate = options.filesToCreate;
		configuration.filesToDiff = options.filesToDiff;
1057
		configuration.filesToWait = options.filesToWait;
B
Benjamin Pasero 已提交
1058 1059
		configuration.nodeCachedDataDir = this.environmentService.nodeCachedDataDir;

1060
		// if we know the backup folder upfront (for empty windows to restore), we can set it
1061
		// directly here which helps for restoring UI state associated with that window.
B
Benjamin Pasero 已提交
1062
		// For all other cases we first call into registerEmptyWindowBackupSync() to set it before
1063
		// loading the window.
1064
		if (options.emptyWindowBackupFolder) {
1065
			configuration.backupPath = join(this.environmentService.backupHome, options.emptyWindowBackupFolder);
1066 1067
		}

1068
		let window: CodeWindow;
B
Benjamin Pasero 已提交
1069
		if (!options.forceNewWindow) {
1070 1071 1072
			window = options.windowToUse || this.getLastActiveWindow();
			if (window) {
				window.focus();
E
Erich Gamma 已提交
1073 1074 1075 1076
			}
		}

		// New window
1077
		if (!window) {
1078
			const windowConfig = this.configurationService.getConfiguration<IWindowSettings>('window');
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
			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 {
1089
				allowFullscreen = this.lifecycleService.wasRestarted || (windowConfig && windowConfig.restoreFullscreen);
1090 1091 1092 1093 1094
			}

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

1096
			window = this.instantiationService.createInstance(CodeWindow, {
1097
				state,
1098
				extensionDevelopmentPath: configuration.extensionDevelopmentPath,
1099
				isExtensionTestHost: !!configuration.extensionTestsPath
1100
			});
1101

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

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

E
Erich Gamma 已提交
1108
			// Window Events
1109 1110 1111 1112 1113
			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 已提交
1114 1115

			// Lifecycle
1116
			this.lifecycleService.registerWindow(window);
E
Erich Gamma 已提交
1117 1118 1119 1120 1121 1122
		}

		// Existing window
		else {

			// Some configuration things get inherited if the window is being reused and we are
B
Benjamin Pasero 已提交
1123
			// in extension development host mode. These options are all development related.
1124
			const currentWindowConfig = window.config;
A
Alex Dima 已提交
1125 1126
			if (!configuration.extensionDevelopmentPath && currentWindowConfig && !!currentWindowConfig.extensionDevelopmentPath) {
				configuration.extensionDevelopmentPath = currentWindowConfig.extensionDevelopmentPath;
B
Benjamin Pasero 已提交
1127
				configuration.verbose = currentWindowConfig.verbose;
1128
				configuration.debugBrkPluginHost = currentWindowConfig.debugBrkPluginHost;
1129
				configuration.debugId = currentWindowConfig.debugId;
1130
				configuration.debugPluginHost = currentWindowConfig.debugPluginHost;
1131
				configuration['extensions-dir'] = currentWindowConfig['extensions-dir'];
E
Erich Gamma 已提交
1132 1133 1134 1135
			}
		}

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

B
Benjamin Pasero 已提交
1139 1140
				// Register window for backups
				if (!configuration.extensionDevelopmentPath) {
1141 1142
					if (configuration.workspace) {
						configuration.backupPath = this.backupService.registerWorkspaceBackupSync(configuration.workspace);
1143
					} else if (configuration.folderPath) {
B
Benjamin Pasero 已提交
1144
						configuration.backupPath = this.backupService.registerFolderBackupSync(configuration.folderPath);
B
Benjamin Pasero 已提交
1145 1146 1147
					} else {
						configuration.backupPath = this.backupService.registerEmptyWindowBackupSync(options.emptyWindowBackupFolder);
					}
B
Benjamin Pasero 已提交
1148 1149
				}

E
Erich Gamma 已提交
1150
				// Load it
1151
				window.load(configuration);
1152 1153 1154

				// Signal event
				this._onWindowLoad.fire(window.id);
E
Erich Gamma 已提交
1155 1156
			}
		});
1157

1158
		return window;
E
Erich Gamma 已提交
1159 1160
	}

1161
	private getNewWindowState(configuration: IWindowConfiguration): INewWindowState {
1162
		const lastActive = this.getLastActiveWindow();
E
Erich Gamma 已提交
1163

1164 1165
		// Restore state unless we are running extension tests
		if (!configuration.extensionTestsPath) {
E
Erich Gamma 已提交
1166

1167 1168 1169
			// extension development host Window - load from stored settings if any
			if (!!configuration.extensionDevelopmentPath && this.windowsState.lastPluginDevelopmentHostWindow) {
				return this.windowsState.lastPluginDevelopmentHostWindow.uiState;
1170 1171
			}

1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
			// Known Workspace - load from stored settings
			if (configuration.workspace) {
				const stateForWorkspace = this.windowsState.openedWindows.filter(o => o.workspace && o.workspace.id === configuration.workspace.id).map(o => o.uiState);
				if (stateForWorkspace.length) {
					return stateForWorkspace[0];
				}
			}

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

1188 1189 1190 1191 1192 1193
			// 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 已提交
1194 1195
			}

1196 1197 1198 1199 1200
			// First Window
			const lastActiveState = this.lastClosedWindowState || this.windowsState.lastActiveWindow;
			if (!lastActive && lastActiveState) {
				return lastActiveState.uiState;
			}
E
Erich Gamma 已提交
1201 1202 1203 1204 1205 1206 1207
		}

		//
		// 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
1208
		let displayToUse: Electron.Display;
B
Benjamin Pasero 已提交
1209
		const displays = screen.getAllDisplays();
E
Erich Gamma 已提交
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219

		// 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 已提交
1220
			if (isMacintosh) {
B
Benjamin Pasero 已提交
1221
				const cursorPoint = screen.getCursorScreenPoint();
E
Erich Gamma 已提交
1222 1223 1224 1225 1226 1227 1228 1229
				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());
			}

1230
			// fallback to primary display or first display
E
Erich Gamma 已提交
1231
			if (!displayToUse) {
1232
				displayToUse = screen.getPrimaryDisplay() || displays[0];
E
Erich Gamma 已提交
1233 1234 1235
			}
		}

1236
		let state = defaultWindowState() as INewWindowState;
1237 1238
		state.x = displayToUse.bounds.x + (displayToUse.bounds.width / 2) - (state.width / 2);
		state.y = displayToUse.bounds.y + (displayToUse.bounds.height / 2) - (state.height / 2);
E
Erich Gamma 已提交
1239

1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
		// Check for newWindowDimensions setting and adjust accordingly
		const windowConfig = this.configurationService.getConfiguration<IWindowSettings>('window');
		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 已提交
1251 1252 1253 1254 1255 1256 1257
				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;
				}

1258 1259 1260 1261 1262 1263 1264 1265
				ensureNoOverlap = false;
			}
		}

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

1266 1267
		state.hasDefaultState = true; // flag as default state

1268
		return state;
E
Erich Gamma 已提交
1269 1270
	}

J
Joao Moreno 已提交
1271
	private ensureNoOverlap(state: ISingleWindowState): ISingleWindowState {
E
Erich Gamma 已提交
1272 1273 1274 1275
		if (WindowsManager.WINDOWS.length === 0) {
			return state;
		}

1276 1277
		const existingWindowBounds = WindowsManager.WINDOWS.map(win => win.getBounds());
		while (existingWindowBounds.some(b => b.x === state.x || b.y === state.y)) {
E
Erich Gamma 已提交
1278 1279 1280 1281 1282 1283 1284
			state.x += 30;
			state.y += 30;
		}

		return state;
	}

B
Benjamin Pasero 已提交
1285 1286 1287 1288 1289
	public reload(win: CodeWindow, cli?: ParsedArgs): void {

		// Only reload when the window has not vetoed this
		this.lifecycleService.unload(win, UnloadReason.RELOAD).done(veto => {
			if (!veto) {
1290
				win.reload(void 0, cli);
B
Benjamin Pasero 已提交
1291 1292 1293 1294 1295 1296 1297

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

1298 1299 1300 1301 1302 1303 1304
	public closeWorkspace(win: CodeWindow): void {
		this.openInBrowserWindow({
			cli: this.environmentService.args,
			windowToUse: win
		});
	}

1305 1306
	public saveAndEnterWorkspace(win: CodeWindow, path: string): TPromise<IEnterWorkspaceResult> {
		return this.workspacesManager.saveAndEnterWorkspace(win, path).then(result => this.doEnterWorkspace(win, result));
1307
	}
1308

1309 1310
	public createAndEnterWorkspace(win: CodeWindow, folders?: string[], path?: string): TPromise<IEnterWorkspaceResult> {
		return this.workspacesManager.createAndEnterWorkspace(win, folders, path).then(result => this.doEnterWorkspace(win, result));
1311
	}
1312

1313
	private doEnterWorkspace(win: CodeWindow, result: IEnterWorkspaceResult): IEnterWorkspaceResult {
1314

1315
		// Mark as recently opened
1316
		this.historyService.addRecentlyOpened([result.workspace], []);
1317

1318 1319 1320
		// Trigger Eevent to indicate load of workspace into window
		this._onWindowReady.fire(win);

1321
		return result;
1322 1323
	}

1324 1325
	public openWorkspace(win?: CodeWindow): void {
		this.workspacesManager.openWorkspace(win);
1326 1327 1328
	}

	private onBeforeWindowUnload(e: IWindowUnloadEvent): void {
1329 1330
		const windowClosing = (e.reason === UnloadReason.CLOSE);
		const windowLoading = (e.reason === UnloadReason.LOAD);
1331 1332 1333 1334 1335 1336 1337 1338 1339
		if (!windowClosing && !windowLoading) {
			return; // only interested when window is closing or loading
		}

		const workspace = e.window.openedWorkspace;
		if (!workspace || !this.workspacesService.isUntitledWorkspace(workspace)) {
			return; // only care about untitled workspaces to ask for saving
		}

1340 1341 1342 1343
		if (e.window.config && !!e.window.config.extensionDevelopmentPath) {
			return; // do not ask to save workspace when doing extension development
		}

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

1348 1349
		// Handle untitled workspaces with prompt as needed
		this.workspacesManager.promptToSaveUntitledWorkspace(e, workspace);
1350 1351
	}

B
Benjamin Pasero 已提交
1352
	public focusLastActive(cli: ParsedArgs, context: OpenContext): CodeWindow {
B
Benjamin Pasero 已提交
1353
		const lastActive = this.getLastActiveWindow();
E
Erich Gamma 已提交
1354
		if (lastActive) {
B
Benjamin Pasero 已提交
1355
			lastActive.focus();
1356 1357

			return lastActive;
E
Erich Gamma 已提交
1358 1359
		}

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

B
Benjamin Pasero 已提交
1364
	public getLastActiveWindow(): CodeWindow {
1365
		return getLastActiveWindow(WindowsManager.WINDOWS);
E
Erich Gamma 已提交
1366 1367
	}

1368 1369
	public openNewWindow(context: OpenContext): void {
		this.open({ context, cli: this.environmentService.args, forceNewWindow: true, forceEmpty: true });
E
Erich Gamma 已提交
1370 1371
	}

1372
	public waitForWindowCloseOrLoad(windowId: number): TPromise<void> {
1373
		return new TPromise<void>(c => {
1374
			function handler(id: number) {
1375
				if (id === windowId) {
1376 1377 1378
					closeListener.dispose();
					loadListener.dispose();

1379 1380
					c(null);
				}
1381 1382 1383 1384
			}

			const closeListener = this.onWindowClose(id => handler(id));
			const loadListener = this.onWindowLoad(id => handler(id));
1385 1386 1387
		});
	}

E
Erich Gamma 已提交
1388 1389 1390 1391
	public sendToFocused(channel: string, ...args: any[]): void {
		const focusedWindow = this.getFocusedWindow() || this.getLastActiveWindow();

		if (focusedWindow) {
1392
			focusedWindow.sendWhenReady(channel, ...args);
E
Erich Gamma 已提交
1393 1394 1395
		}
	}

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

1402
			w.sendWhenReady(channel, payload);
E
Erich Gamma 已提交
1403 1404 1405
		});
	}

B
Benjamin Pasero 已提交
1406
	public getFocusedWindow(): CodeWindow {
B
Benjamin Pasero 已提交
1407
		const win = BrowserWindow.getFocusedWindow();
E
Erich Gamma 已提交
1408 1409 1410 1411 1412 1413 1414
		if (win) {
			return this.getWindowById(win.id);
		}

		return null;
	}

B
Benjamin Pasero 已提交
1415
	public getWindowById(windowId: number): CodeWindow {
1416
		const res = WindowsManager.WINDOWS.filter(w => w.id === windowId);
E
Erich Gamma 已提交
1417 1418 1419 1420 1421 1422 1423
		if (res && res.length === 1) {
			return res[0];
		}

		return null;
	}

B
Benjamin Pasero 已提交
1424
	public getWindows(): CodeWindow[] {
E
Erich Gamma 已提交
1425 1426 1427 1428 1429 1430 1431
		return WindowsManager.WINDOWS;
	}

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

1432
	private onWindowError(window: CodeWindow, error: WindowError): void {
B
Benjamin Pasero 已提交
1433
		this.logService.error(error === WindowError.CRASHED ? '[VS Code]: render process crashed!' : '[VS Code]: detected unresponsive');
E
Erich Gamma 已提交
1434 1435 1436

		// Unresponsive
		if (error === WindowError.UNRESPONSIVE) {
1437
			dialog.showMessageBox(window.win, {
B
Benjamin Pasero 已提交
1438
				title: product.nameLong,
E
Erich Gamma 已提交
1439
				type: 'warning',
1440 1441 1442
				buttons: [localize('reopen', "Reopen"), localize('wait', "Keep Waiting"), localize('close', "Close")],
				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 已提交
1443
				noLink: true
1444
			}, result => {
1445
				if (!window.win) {
1446 1447 1448
					return; // Return early if the window has been going down already
				}

E
Erich Gamma 已提交
1449
				if (result === 0) {
1450
					window.reload();
1451
				} else if (result === 2) {
1452 1453
					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 已提交
1454 1455 1456 1457 1458 1459
				}
			});
		}

		// Crashed
		else {
1460
			dialog.showMessageBox(window.win, {
B
Benjamin Pasero 已提交
1461
				title: product.nameLong,
E
Erich Gamma 已提交
1462
				type: 'warning',
1463 1464 1465
				buttons: [localize('reopen', "Reopen"), localize('close', "Close")],
				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 已提交
1466
				noLink: true
1467
			}, result => {
1468
				if (!window.win) {
1469 1470 1471
					return; // Return early if the window has been going down already
				}

1472
				if (result === 0) {
1473
					window.reload();
1474
				} else if (result === 1) {
1475 1476
					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
1477
				}
E
Erich Gamma 已提交
1478 1479 1480 1481
			});
		}
	}

B
Benjamin Pasero 已提交
1482
	private onWindowClosed(win: CodeWindow): void {
E
Erich Gamma 已提交
1483 1484 1485 1486 1487

		// Tell window
		win.dispose();

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

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

B
Benjamin Pasero 已提交
1496 1497
	public pickFileFolderAndOpen(options: INativeOpenDialogOptions): void {
		this.doPickAndOpen(options, true /* pick folders */, true /* pick files */);
1498 1499
	}

B
Benjamin Pasero 已提交
1500 1501
	public pickFolderAndOpen(options: INativeOpenDialogOptions): void {
		this.doPickAndOpen(options, true /* pick folders */, false /* pick files */);
1502 1503
	}

B
Benjamin Pasero 已提交
1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538
	public pickFileAndOpen(options: INativeOpenDialogOptions): void {
		this.doPickAndOpen(options, false /* pick folders */, true /* pick files */);
	}

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

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

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

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

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

		this.fileDialog.pickAndOpen(internalOptions);
B
Benjamin Pasero 已提交
1539 1540 1541 1542 1543 1544
	}

	public quit(): void {

		// If the user selected to exit from an extension development host window, do not quit, but just
		// close the window unless this is the last window that is opened.
1545 1546 1547
		const window = this.getFocusedWindow();
		if (window && window.isExtensionDevelopmentHost && this.getWindowCount() > 1) {
			window.win.close();
B
Benjamin Pasero 已提交
1548 1549 1550 1551 1552 1553 1554 1555
		}

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

B
Benjamin Pasero 已提交
1559
interface IInternalNativeOpenDialogOptions extends INativeOpenDialogOptions {
B
Benjamin Pasero 已提交
1560 1561 1562 1563 1564 1565 1566
	pickFolders?: boolean;
	pickFiles?: boolean;
}

class FileDialog {

	private static workingDirPickerStorageKey = 'pickerWorkingDir';
1567

B
Benjamin Pasero 已提交
1568 1569 1570 1571 1572 1573 1574 1575
	constructor(
		private environmentService: IEnvironmentService,
		private telemetryService: ITelemetryService,
		private storageService: IStorageService,
		private windowsMainService: IWindowsMainService
	) {
	}

B
Benjamin Pasero 已提交
1576
	public pickAndOpen(options: INativeOpenDialogOptions): void {
1577
		this.getFileOrFolderPaths(options, (paths: string[]) => {
B
Benjamin Pasero 已提交
1578 1579 1580 1581
			const numberOfPaths = paths ? paths.length : 0;

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

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

B
Benjamin Pasero 已提交
1603
	public getFileOrFolderPaths(options: IInternalNativeOpenDialogOptions, clb: (paths: string[]) => void): void {
1604

B
Benjamin Pasero 已提交
1605 1606 1607 1608 1609 1610 1611 1612
		// Ensure dialog options
		if (!options.dialogOptions) {
			options.dialogOptions = Object.create(null);
		}

		// Ensure defaultPath
		if (!options.dialogOptions.defaultPath) {
			options.dialogOptions.defaultPath = this.storageService.getItem<string>(FileDialog.workingDirPickerStorageKey);
1613 1614
		}

B
Benjamin Pasero 已提交
1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627
		// 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'];
		}

1628 1629 1630 1631
		if (isMacintosh) {
			options.dialogOptions.properties.push('treatPackageAsDirectory'); // always drill into .app files
		}

B
Benjamin Pasero 已提交
1632
		// Show Dialog
1633 1634
		const focusedWindow = this.windowsMainService.getWindowById(options.windowId) || this.windowsMainService.getFocusedWindow();
		dialog.showOpenDialog(focusedWindow && focusedWindow.win, options.dialogOptions, paths => {
1635
			if (paths && paths.length > 0) {
1636 1637 1638
				if (isMacintosh) {
					paths = paths.map(path => normalizeNFC(path)); // normalize paths returned from the OS
				}
1639 1640

				// Remember path in storage for next time
1641
				this.storageService.setItem(FileDialog.workingDirPickerStorageKey, dirname(paths[0]));
1642 1643

				// Return
B
Benjamin Pasero 已提交
1644
				return clb(paths);
1645
			}
B
Benjamin Pasero 已提交
1646 1647

			return clb(void (0));
1648 1649
		});
	}
1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662
}

class WorkspacesManager {

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

1663
	public saveAndEnterWorkspace(window: CodeWindow, path: string): TPromise<IEnterWorkspaceResult> {
1664 1665 1666 1667 1668 1669 1670
		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);
	}

1671
	public createAndEnterWorkspace(window: CodeWindow, folders?: string[], path?: string): TPromise<IEnterWorkspaceResult> {
1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696
		if (!window || !window.win || window.readyState !== ReadyState.READY || !this.isValidTargetWorkspacePath(window, path)) {
			return TPromise.as(null); // return early if the window is not ready or disposed
		}

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

	private isValidTargetWorkspacePath(window: CodeWindow, path?: string): boolean {
		if (!path) {
			return true;
		}

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

		// Prevent overwriting a workspace that is currently opened in another window
		if (findWindowOnWorkspace(this.windowsMainService.getWindows(), { id: this.workspacesService.getWorkspaceId(path), configPath: path })) {
			const options: Electron.MessageBoxOptions = {
				title: product.nameLong,
				type: 'info',
				buttons: [localize('ok', "OK")],
				message: localize('workspaceOpenedMessage', "Unable to save workspace '{0}'", basename(path)),
1697
				detail: localize('workspaceOpenedDetail', "The workspace is already opened in another window. Please close that window first and then try again."),
1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713
				noLink: true
			};

			const activeWindow = BrowserWindow.getFocusedWindow();
			if (activeWindow) {
				dialog.showMessageBox(activeWindow, options);
			} else {
				dialog.showMessageBox(options);
			}

			return false;
		}

		return true; // OK
	}

1714
	private doSaveAndOpenWorkspace(window: CodeWindow, workspace: IWorkspaceIdentifier, path?: string): TPromise<IEnterWorkspaceResult> {
1715 1716 1717 1718 1719 1720 1721 1722 1723 1724
		let savePromise: TPromise<IWorkspaceIdentifier>;
		if (path) {
			savePromise = this.workspacesService.saveWorkspace(workspace, path);
		} else {
			savePromise = TPromise.as(workspace);
		}

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

1725 1726 1727 1728 1729
			// Register window for backups and migrate current backups over
			let backupPath: string;
			if (!window.config.extensionDevelopmentPath) {
				backupPath = this.backupService.registerWorkspaceBackupSync(workspace, window.config.backupPath);
			}
1730

1731 1732 1733 1734
			// Update window configuration properly based on transition to workspace
			window.config.folderPath = void 0;
			window.config.workspace = workspace;
			window.config.backupPath = backupPath;
1735

1736
			return { workspace, backupPath };
1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810
		});
	}

	public openWorkspace(window = this.windowsMainService.getLastActiveWindow()): void {
		let defaultPath: string;
		if (window && window.openedWorkspace && !this.workspacesService.isUntitledWorkspace(window.openedWorkspace)) {
			defaultPath = dirname(window.openedWorkspace.configPath);
		} else {
			defaultPath = this.getWorkspaceDialogDefaultPath(window ? (window.openedWorkspace || window.openedFolderPath) : void 0);
		}

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

	public promptToSaveUntitledWorkspace(e: IWindowUnloadEvent, workspace: IWorkspaceIdentifier): void {
		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;
		}

		const res = dialog.showMessageBox(e.window.win, options);

		switch (buttons[res].result) {

			// Cancel: veto unload
			case ConfirmResult.CANCEL:
				e.veto(true);
				break;

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

			// Save: save workspace, but do not veto unload
			case ConfirmResult.SAVE: {
1811
				let target = dialog.showSaveDialog(e.window.win, {
1812 1813 1814 1815 1816 1817 1818
					buttonLabel: mnemonicButtonLabel(localize({ key: 'save', comment: ['&& denotes a mnemonic'] }, "&&Save")),
					title: localize('saveWorkspace', "Save Workspace"),
					filters: WORKSPACE_FILTER,
					defaultPath: this.getWorkspaceDialogDefaultPath(workspace)
				});

				if (target) {
1819 1820 1821 1822
					if (isMacintosh) {
						target = normalizeNFC(target); // normalize paths returned from the OS
					}

1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833
					e.veto(this.workspacesService.saveWorkspace(workspace, target).then(() => false, () => false));
				} else {
					e.veto(true); // keep veto if no target was provided
				}
			}
		}
	}

	private getWorkspaceDialogDefaultPath(workspace?: IWorkspaceIdentifier | ISingleFolderWorkspaceIdentifier): string {
		if (workspace) {
			if (isSingleFolderWorkspaceIdentifier(workspace)) {
J
Johannes Rieken 已提交
1834 1835 1836 1837 1838 1839 1840 1841 1842
				return dirname(workspace);
			}

			const resolvedWorkspace = this.workspacesService.resolveWorkspaceSync(workspace.configPath);
			if (resolvedWorkspace && resolvedWorkspace.folders.length > 0) {
				for (const folder of resolvedWorkspace.folders) {
					if (folder.uri.scheme === Schemas.file) {
						return dirname(folder.uri.fsPath);
					}
1843 1844 1845
				}
			}
		}
J
Johannes Rieken 已提交
1846
		return void 0;
1847
	}
J
Johannes Rieken 已提交
1848
}