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

J
Joao Moreno 已提交
8
import * as path 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 } 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 34
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { mnemonicLabel } from 'vs/base/common/labels';
E
Erich Gamma 已提交
35 36 37 38 39 40

enum WindowError {
	UNRESPONSIVE,
	CRASHED
}

41 42 43 44
interface INewWindowState extends ISingleWindowState {
	hasDefaultState?: boolean;
}

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

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

56 57 58 59
interface ILegacyWindowsState extends IWindowsState {
	openedFolders?: IWindowState[];
}

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

66
type RestoreWindowsSetting = 'all' | 'folders' | 'one' | 'none';
67

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

72
	workspace?: IWorkspaceIdentifier;
73
	folderPath?: string;
B
Benjamin Pasero 已提交
74 75 76 77 78 79 80 81 82 83

	initialStartup?: boolean;

	filesToOpen?: IPath[];
	filesToCreate?: IPath[];
	filesToDiff?: IPath[];

	forceNewWindow?: boolean;
	windowToUse?: CodeWindow;

84
	emptyWindowBackupFolder?: string;
B
Benjamin Pasero 已提交
85 86
}

87 88
interface IWindowToOpen extends IPath {

89
	// the workspace for a Code instance to open
90
	workspace?: IWorkspaceIdentifier;
91

92 93
	// the folder path for a Code instance to open
	folderPath?: string;
94 95 96 97 98 99 100 101

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

104
	_serviceBrand: any;
E
Erich Gamma 已提交
105 106 107

	private static windowsStateStorageKey = 'windowsState';

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

B
Benjamin Pasero 已提交
110
	private initialUserEnv: IProcessEnvironment;
111

E
Erich Gamma 已提交
112
	private windowsState: IWindowsState;
113
	private lastClosedWindowState: IWindowState;
E
Erich Gamma 已提交
114

B
Benjamin Pasero 已提交
115 116
	private fileDialog: FileDialog;

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

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

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

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

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

J
Joao Moreno 已提交
132 133
	constructor(
		@ILogService private logService: ILogService,
J
Joao Moreno 已提交
134
		@IStorageService private storageService: IStorageService,
135
		@IEnvironmentService private environmentService: IEnvironmentService,
B
Benjamin Pasero 已提交
136
		@ILifecycleService private lifecycleService: ILifecycleService,
137
		@IBackupMainService private backupService: IBackupMainService,
138
		@ITelemetryService private telemetryService: ITelemetryService,
139
		@IConfigurationService private configurationService: IConfigurationService,
B
Benjamin Pasero 已提交
140
		@IHistoryMainService private historyService: IHistoryMainService,
141 142
		@IWorkspacesMainService private workspacesService: IWorkspacesMainService,
		@IInstantiationService private instantiationService: IInstantiationService
143
	) {
144
		this.windowsState = this.storageService.getItem<IWindowsState>(WindowsManager.windowsStateStorageKey) || { openedWindows: [] };
145
		this.fileDialog = new FileDialog(environmentService, telemetryService, storageService, this);
146

147 148
		this.migrateLegacyWindowState();
	}
149

150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
	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 => {
167 168 169 170 171
			if (!state) {
				return;
			}

			if (typeof state.workspacePath === 'string') {
172 173 174
				state.folderPath = state.workspacePath;
				state.workspacePath = void 0;
			}
175 176 177 178 179

			// TODO@Ben migration to new workspace ID
			if (state.workspace) {
				state.workspace.id = this.workspacesService.getWorkspaceId(state.workspace.configPath);
			}
180
		});
181
	}
J
Joao Moreno 已提交
182

B
Benjamin Pasero 已提交
183
	public ready(initialUserEnv: IProcessEnvironment): void {
184
		this.initialUserEnv = initialUserEnv;
185 186

		this.registerListeners();
E
Erich Gamma 已提交
187 188 189
	}

	private registerListeners(): void {
190

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

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

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

				// Event
207
				this._onWindowReady.fire(win);
E
Erich Gamma 已提交
208 209 210
			}
		});

211 212 213 214 215 216 217 218 219 220 221
		// 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');
				}
			});
		}

222 223
		// Handle various lifecycle events around windows
		this.lifecycleService.onBeforeWindowUnload(e => this.onBeforeWindowUnload(e));
B
Benjamin Pasero 已提交
224
		this.lifecycleService.onBeforeWindowClose(win => this.onBeforeWindowClose(win as CodeWindow));
225
		this.lifecycleService.onBeforeQuit(() => this.onBeforeQuit());
226 227
	}

228 229 230 231 232 233 234 235
	// 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().
	private onBeforeQuit(): void {
236
		const currentWindowsState: ILegacyWindowsState = {
237 238
			openedWindows: [],
			openedFolders: [], // TODO@Ben migration so that old clients do not fail over data (prevents NPEs)
239
			lastPluginDevelopmentHostWindow: this.windowsState.lastPluginDevelopmentHostWindow,
240
			lastActiveWindow: this.lastClosedWindowState
241 242 243 244 245 246 247 248
		};

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

250
			if (activeWindow) {
251
				currentWindowsState.lastActiveWindow = this.toWindowState(activeWindow);
E
Erich Gamma 已提交
252
			}
253 254 255 256 257
		}

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

261
		// 3.) All windows (except extension host) for N >= 2 to support restoreWindows: all or for auto update
262 263 264 265 266
		//
		// 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) {
267
			currentWindowsState.openedWindows = WindowsManager.WINDOWS.filter(w => !w.isExtensionDevelopmentHost).map(w => this.toWindowState(w));
268
		}
E
Erich Gamma 已提交
269

270 271 272
		// Persist
		this.storageService.setItem(WindowsManager.windowsStateStorageKey, currentWindowsState);
	}
273

274
	// See note on #onBeforeQuit() for details how these events are flowing
B
Benjamin Pasero 已提交
275
	private onBeforeWindowClose(win: CodeWindow): void {
276 277 278 279 280
		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
281
		const state: IWindowState = this.toWindowState(win);
282 283 284 285
		if (win.isExtensionDevelopmentHost && !win.isExtensionTestHost) {
			this.windowsState.lastPluginDevelopmentHostWindow = state; // do not let test run window state overwrite our extension development state
		}

286
		// Any non extension host window with same workspace or folder
287
		else if (!win.isExtensionDevelopmentHost && (!!win.openedWorkspace || !!win.openedFolderPath)) {
288
			this.windowsState.openedWindows.forEach(o => {
B
fix npe  
Benjamin Pasero 已提交
289
				const sameWorkspace = win.openedWorkspace && o.workspace && o.workspace.id === win.openedWorkspace.id;
290 291 292
				const sameFolder = win.openedFolderPath && isEqual(o.folderPath, win.openedFolderPath, !isLinux /* ignorecase */);

				if (sameWorkspace || sameFolder) {
293 294 295 296 297 298 299
					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.
300 301 302
		// 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) {
303 304
			this.lastClosedWindowState = state;
		}
E
Erich Gamma 已提交
305 306
	}

307 308
	private toWindowState(win: CodeWindow): IWindowState {
		return {
309
			workspace: win.openedWorkspace,
310 311 312 313 314 315
			folderPath: win.openedFolderPath,
			backupPath: win.backupPath,
			uiState: win.serializeWindowState()
		};
	}

B
Benjamin Pasero 已提交
316
	public open(openConfig: IOpenConfiguration): CodeWindow[] {
317
		const windowsToOpen = this.getWindowsToOpen(openConfig);
E
Erich Gamma 已提交
318

319 320 321 322 323 324 325 326 327
		let filesToOpen = windowsToOpen.filter(path => !!path.filePath && !path.createFilePath);
		let filesToCreate = windowsToOpen.filter(path => !!path.filePath && path.createFilePath);
		let filesToDiff: IPath[];
		if (openConfig.diffMode && filesToOpen.length === 2) {
			filesToDiff = filesToOpen;
			filesToOpen = [];
			filesToCreate = []; // diff ignores other files that do not exist
		} else {
			filesToDiff = [];
E
Erich Gamma 已提交
328 329
		}

330 331 332
		//
		// These are windows to open to show workspaces
		//
333
		const workspacesToOpen = arrays.distinct(windowsToOpen.filter(win => !!win.workspace).map(win => win.workspace), workspace => workspace.id); // prevent duplicates
334 335 336 337 338 339

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

340
		//
341
		// These are windows to restore because of hot-exit or from previous session (only performed once on startup!)
342
		//
343 344 345 346 347 348
		let foldersToRestore: string[] = [];
		let workspacesToRestore: IWorkspaceIdentifier[] = [];
		let emptyToRestore: string[] = [];
		if (openConfig.initialStartup && !openConfig.cli.extensionDevelopmentPath) {
			foldersToRestore = this.backupService.getFolderBackupPaths();

349 350
			workspacesToRestore = this.backupService.getWorkspaceBackups();						// collect from workspaces with hot-exit backups
			workspacesToRestore.push(...this.workspacesService.getUntitledWorkspacesSync());	// collect from previous window session
351 352 353 354 355

			emptyToRestore = this.backupService.getEmptyWindowBackupPaths();
			emptyToRestore.push(...windowsToOpen.filter(w => !w.workspace && !w.folderPath && w.backupPath).map(w => path.basename(w.backupPath))); // add empty windows with backupPath
			emptyToRestore = arrays.distinct(emptyToRestore); // prevent duplicates
		}
356

357 358 359
		//
		// These are empty windows to open
		//
360
		const emptyToOpen = windowsToOpen.filter(win => !win.workspace && !win.folderPath && !win.filePath && !win.backupPath).length;
361

362
		// Open based on config
363
		const usedWindows = this.doOpen(openConfig, workspacesToOpen, workspacesToRestore, foldersToOpen, foldersToRestore, emptyToRestore, emptyToOpen, filesToOpen, filesToCreate, filesToDiff);
364 365 366 367 368 369 370 371

		// Make sure the last active window gets focus if we opened multiple
		if (usedWindows.length > 1 && this.windowsState.lastActiveWindow) {
			let lastActiveWindw = usedWindows.filter(w => w.backupPath === this.windowsState.lastActiveWindow.backupPath);
			if (lastActiveWindw.length) {
				lastActiveWindw[0].focus();
			}
		}
372

373 374 375
		// 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) {
376
			const recentlyOpenedWorkspaces: (IWorkspaceIdentifier | ISingleFolderWorkspaceIdentifier)[] = [];
377
			const recentlyOpenedFiles: string[] = [];
378 379

			windowsToOpen.forEach(win => {
380 381 382 383
				if (win.workspace || win.folderPath) {
					recentlyOpenedWorkspaces.push(win.workspace || win.folderPath);
				} else if (win.filePath) {
					recentlyOpenedFiles.push(win.filePath);
384 385 386
				}
			});

387
			this.historyService.addRecentlyOpened(recentlyOpenedWorkspaces, recentlyOpenedFiles);
388
		}
389

390 391 392 393 394 395 396
		// If we got started with --wait from the CLI, we need to signal to the outside when the window
		// used for the edit operation is closed so that the waiting process can continue. We do this by
		// deleting the waitMarkerFilePath.
		if (openConfig.context === OpenContext.CLI && openConfig.cli.wait && openConfig.cli.waitMarkerFilePath && usedWindows.length === 1 && usedWindows[0]) {
			this.waitForWindowClose(usedWindows[0].id).done(() => fs.unlink(openConfig.cli.waitMarkerFilePath, error => void 0));
		}

397 398 399 400 401
		return usedWindows;
	}

	private doOpen(
		openConfig: IOpenConfiguration,
402 403
		workspacesToOpen: IWorkspaceIdentifier[],
		workspacesToRestore: IWorkspaceIdentifier[],
404 405 406 407 408 409 410 411 412
		foldersToOpen: string[],
		foldersToRestore: string[],
		emptyToRestore: string[],
		emptyToOpen: number,
		filesToOpen: IPath[],
		filesToCreate: IPath[],
		filesToDiff: IPath[]
	) {

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

B
Benjamin Pasero 已提交
416
		// 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
B
Benjamin Pasero 已提交
417
		const usedWindows: CodeWindow[] = [];
418 419
		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 已提交
420

421
			// Find suitable window or folder path to open files in
422
			const fileToCheck = filesToOpen[0] || filesToCreate[0] || filesToDiff[0];
B
Benjamin Pasero 已提交
423
			const bestWindowOrFolder = findBestWindowOrFolderForFile({
424 425 426 427 428
				windows: WindowsManager.WINDOWS,
				newWindow: openFilesInNewWindow,
				reuseWindow: openConfig.forceReuseWindow,
				context: openConfig.context,
				filePath: fileToCheck && fileToCheck.filePath,
429 430
				userHome: this.environmentService.userHome,
				workspaceResolver: workspace => this.workspacesService.resolveWorkspaceSync(workspace.configPath)
431
			});
B
Benjamin Pasero 已提交
432

433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
			// 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
					usedWindows.push(this.doOpenFilesInExistingWindow(bestWindowOrFolder, filesToOpen, filesToCreate, filesToDiff));

					// Reset these because we handled them
					filesToOpen = [];
					filesToCreate = [];
					filesToDiff = [];
				}
457 458 459 460 461
			}

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

464
			// Finally, if no window or folder is found, just open the files in an empty window
E
Erich Gamma 已提交
465
			else {
B
Benjamin Pasero 已提交
466
				usedWindows.push(this.openInBrowserWindow({
B
Benjamin Pasero 已提交
467 468 469 470 471 472 473
					userEnv: openConfig.userEnv,
					cli: openConfig.cli,
					initialStartup: openConfig.initialStartup,
					filesToOpen,
					filesToCreate,
					filesToDiff,
					forceNewWindow: true
B
Benjamin Pasero 已提交
474
				}));
E
Erich Gamma 已提交
475

476 477 478 479
				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
				filesToDiff = [];
E
Erich Gamma 已提交
480 481 482
			}
		}

483
		// Handle workspaces to open (instructed and to restore)
484
		const allWorkspacesToOpen = arrays.distinct([...workspacesToOpen, ...workspacesToRestore], workspace => workspace.id); // prevent duplicates
485 486 487 488 489 490 491 492
		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
B
Benjamin Pasero 已提交
493
				usedWindows.push(this.doOpenFilesInExistingWindow(windowOnWorkspace, filesToOpen, filesToCreate, filesToDiff));
494 495 496 497 498 499 500 501 502 503 504

				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
				filesToDiff = [];

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

			// Open remaining ones
			allWorkspacesToOpen.forEach(workspaceToOpen => {
505
				if (windowsOnWorkspace.some(win => win.openedWorkspace.id === workspaceToOpen.id)) {
506 507 508 509
					return; // ignore folders that are already open
				}

				// Do open folder
510
				usedWindows.push(this.doOpenFolderOrWorkspace(openConfig, { workspace: workspaceToOpen }, openFolderInNewWindow, filesToOpen, filesToCreate, filesToDiff));
511 512 513 514 515 516 517 518 519 520

				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
				filesToDiff = [];

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

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

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

530
				// Do open files
B
Benjamin Pasero 已提交
531
				usedWindows.push(this.doOpenFilesInExistingWindow(windowOnFolderPath, filesToOpen, filesToCreate, filesToDiff));
532

E
Erich Gamma 已提交
533 534 535
				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
536
				filesToDiff = [];
E
Erich Gamma 已提交
537

B
Benjamin Pasero 已提交
538
				openFolderInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
539 540 541
			}

			// Open remaining ones
542
			allFoldersToOpen.forEach(folderToOpen => {
543
				if (windowsOnFolderPath.some(win => isEqual(win.openedFolderPath, folderToOpen, !isLinux /* ignorecase */))) {
E
Erich Gamma 已提交
544 545 546
					return; // ignore folders that are already open
				}

547 548
				// Do open folder
				usedWindows.push(this.doOpenFolderOrWorkspace(openConfig, { folderPath: folderToOpen }, openFolderInNewWindow, filesToOpen, filesToCreate, filesToDiff));
E
Erich Gamma 已提交
549 550 551 552

				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
553
				filesToDiff = [];
E
Erich Gamma 已提交
554

B
Benjamin Pasero 已提交
555
				openFolderInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
556 557 558
			});
		}

559
		// Handle empty to restore
560
		if (emptyToRestore.length > 0) {
561
			emptyToRestore.forEach(emptyWindowBackupFolder => {
B
Benjamin Pasero 已提交
562
				usedWindows.push(this.openInBrowserWindow({
B
Benjamin Pasero 已提交
563 564 565 566 567 568 569
					userEnv: openConfig.userEnv,
					cli: openConfig.cli,
					initialStartup: openConfig.initialStartup,
					filesToOpen,
					filesToCreate,
					filesToDiff,
					forceNewWindow: true,
570
					emptyWindowBackupFolder
B
Benjamin Pasero 已提交
571
				}));
572

B
wip  
Benjamin Pasero 已提交
573 574 575 576 577
				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
				filesToDiff = [];

B
Benjamin Pasero 已提交
578
				openFolderInNewWindow = true; // any other folders to open must open in new window then
579 580
			});
		}
B
Benjamin Pasero 已提交
581

582 583
		// Handle empty to open (only if no other window opened)
		if (usedWindows.length === 0) {
584
			for (let i = 0; i < emptyToOpen; i++) {
B
Benjamin Pasero 已提交
585
				usedWindows.push(this.openInBrowserWindow({
B
Benjamin Pasero 已提交
586 587 588
					userEnv: openConfig.userEnv,
					cli: openConfig.cli,
					initialStartup: openConfig.initialStartup,
589
					forceNewWindow: openFolderInNewWindow
B
Benjamin Pasero 已提交
590
				}));
E
Erich Gamma 已提交
591

592
				openFolderInNewWindow = true; // any other window to open must open in new window then
593 594
			}
		}
E
Erich Gamma 已提交
595

596
		return arrays.distinct(usedWindows);
E
Erich Gamma 已提交
597 598
	}

B
Benjamin Pasero 已提交
599
	private doOpenFilesInExistingWindow(window: CodeWindow, filesToOpen: IPath[], filesToCreate: IPath[], filesToDiff: IPath[]): CodeWindow {
600 601 602 603 604
		window.focus(); // make sure window has focus

		window.ready().then(readyWindow => {
			readyWindow.send('vscode:openFiles', { filesToOpen, filesToCreate, filesToDiff });
		});
B
Benjamin Pasero 已提交
605 606

		return window;
607 608
	}

609
	private doOpenFolderOrWorkspace(openConfig: IOpenConfiguration, folderOrWorkspace: IWindowToOpen, openInNewWindow: boolean, filesToOpen: IPath[], filesToCreate: IPath[], filesToDiff: IPath[], windowToUse?: CodeWindow): CodeWindow {
610 611 612 613
		const browserWindow = this.openInBrowserWindow({
			userEnv: openConfig.userEnv,
			cli: openConfig.cli,
			initialStartup: openConfig.initialStartup,
614
			workspace: folderOrWorkspace.workspace,
615 616 617 618
			folderPath: folderOrWorkspace.folderPath,
			filesToOpen,
			filesToCreate,
			filesToDiff,
619 620
			forceNewWindow: openInNewWindow,
			windowToUse
621 622 623 624 625
		});

		return browserWindow;
	}

626 627
	private getWindowsToOpen(openConfig: IOpenConfiguration): IWindowToOpen[] {
		let windowsToOpen: IWindowToOpen[];
E
Erich Gamma 已提交
628

629
		// Extract paths: from API
B
Benjamin Pasero 已提交
630
		if (openConfig.pathsToOpen && openConfig.pathsToOpen.length > 0) {
631
			windowsToOpen = this.doExtractPathsFromAPI(openConfig);
E
Erich Gamma 已提交
632 633
		}

B
Benjamin Pasero 已提交
634 635
		// Check for force empty
		else if (openConfig.forceEmpty) {
636
			windowsToOpen = [Object.create(null)];
E
Erich Gamma 已提交
637 638
		}

639
		// Extract paths: from CLI
B
Benjamin Pasero 已提交
640
		else if (openConfig.cli._.length > 0) {
641
			windowsToOpen = this.doExtractPathsFromCLI(openConfig.cli);
B
Benjamin Pasero 已提交
642 643
		}

644
		// Extract windows: from previous session
B
Benjamin Pasero 已提交
645
		else {
646
			windowsToOpen = this.doGetWindowsFromLastSession();
B
Benjamin Pasero 已提交
647 648
		}

649
		return windowsToOpen;
E
Erich Gamma 已提交
650 651
	}

652 653 654
	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 });
655 656 657 658 659 660

			// Warn if the requested path to open does not exist
			if (!path) {
				const options: Electron.ShowMessageBoxOptions = {
					title: product.nameLong,
					type: 'info',
661 662 663
					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),
664 665 666 667 668 669 670 671 672 673
					noLink: true
				};

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

675 676 677 678 679 680 681 682 683 684
			return path;
		});

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

		return pathsToOpen;
	}

	private doExtractPathsFromCLI(cli: ParsedArgs): IPath[] {
685
		const pathsToOpen = arrays.coalesce(cli._.map(candidate => this.parsePath(candidate, { ignoreFileNotFound: true, gotoLineMode: cli.goto })));
686 687
		if (pathsToOpen.length > 0) {
			return pathsToOpen;
B
Benjamin Pasero 已提交
688 689 690 691 692 693
		}

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

694 695 696
	private doGetWindowsFromLastSession(): IWindowToOpen[] {
		const restoreWindows = this.getRestoreWindowsSetting();
		const lastActiveWindow = this.windowsState.lastActiveWindow;
B
Benjamin Pasero 已提交
697

698
		switch (restoreWindows) {
B
Benjamin Pasero 已提交
699

700
			// none: we always open an empty window
701 702
			case 'none':
				return [Object.create(null)];
B
Benjamin Pasero 已提交
703

704
			// one: restore last opened workspace/folder or empty window
705 706
			case 'one':
				if (lastActiveWindow) {
B
Benjamin Pasero 已提交
707

708
					// workspace
B
Benjamin Pasero 已提交
709 710 711 712 713 714
					const candidateWorkspace = lastActiveWindow.workspace;
					if (candidateWorkspace) {
						const validatedWorkspace = this.parsePath(candidateWorkspace.configPath);
						if (validatedWorkspace && validatedWorkspace.workspace) {
							return [validatedWorkspace];
						}
715 716 717 718 719
					}

					// folder (if path is valid)
					else if (lastActiveWindow.folderPath) {
						const validatedFolder = this.parsePath(lastActiveWindow.folderPath);
B
Benjamin Pasero 已提交
720
						if (validatedFolder && validatedFolder.folderPath) {
721
							return [validatedFolder];
722 723
						}
					}
B
Benjamin Pasero 已提交
724

725
					// otherwise use backup path to restore empty windows
726 727 728 729 730 731 732 733 734 735
					else if (lastActiveWindow.backupPath) {
						return [{ backupPath: lastActiveWindow.backupPath }];
					}
				}
				break;

			// all: restore all windows
			// folders: restore last opened folders only
			case 'all':
			case 'folders':
736
				const windowsToOpen: IWindowToOpen[] = [];
737

738
				// Workspaces
B
Benjamin Pasero 已提交
739
				const workspaceCandidates = this.windowsState.openedWindows.filter(w => !!w.workspace).map(w => w.workspace);
740
				if (lastActiveWindow && lastActiveWindow.workspace) {
B
Benjamin Pasero 已提交
741
					workspaceCandidates.push(lastActiveWindow.workspace);
742
				}
B
Benjamin Pasero 已提交
743
				windowsToOpen.push(...workspaceCandidates.map(candidate => this.parsePath(candidate.configPath)).filter(window => window && window.workspace));
B
Benjamin Pasero 已提交
744

745
				// Folders
B
Benjamin Pasero 已提交
746
				const folderCandidates = this.windowsState.openedWindows.filter(w => !!w.folderPath).map(w => w.folderPath);
747
				if (lastActiveWindow && lastActiveWindow.folderPath) {
B
Benjamin Pasero 已提交
748
					folderCandidates.push(lastActiveWindow.folderPath);
749
				}
B
Benjamin Pasero 已提交
750
				windowsToOpen.push(...folderCandidates.map(candidate => this.parsePath(candidate)).filter(window => window && window.folderPath));
B
Benjamin Pasero 已提交
751

752 753
				// Windows that were Empty
				if (restoreWindows === 'all') {
754 755
					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;
756 757 758 759 760 761 762 763 764 765 766 767
					if (lastActiveEmpty) {
						lastOpenedEmpty.push(lastActiveEmpty);
					}

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

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

				break;
B
Benjamin Pasero 已提交
768
		}
E
Erich Gamma 已提交
769

770
		// Always fallback to empty window
B
Benjamin Pasero 已提交
771
		return [Object.create(null)];
E
Erich Gamma 已提交
772 773
	}

774 775 776 777 778 779
	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');
780
			restoreWindows = ((windowConfig && windowConfig.restoreWindows) || 'one') as RestoreWindowsSetting;
781

B
fix npe  
Benjamin Pasero 已提交
782
			if (restoreWindows === 'one' /* default */ && windowConfig && windowConfig.reopenFolders) {
783 784 785 786 787 788 789 790 791 792 793
				restoreWindows = windowConfig.reopenFolders; // TODO@Ben migration
			}

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

		return restoreWindows;
	}

794
	private parsePath(anyPath: string, options?: { ignoreFileNotFound?: boolean, gotoLineMode?: boolean, forceOpenWorkspaceAsFile?: boolean; }): IWindowToOpen {
E
Erich Gamma 已提交
795 796 797 798
		if (!anyPath) {
			return null;
		}

799
		let parsedPath: IPathWithLineAndColumn;
800 801 802

		const gotoLineMode = options && options.gotoLineMode;
		if (options && options.gotoLineMode) {
J
Joao Moreno 已提交
803
			parsedPath = parseLineAndColumnAware(anyPath);
E
Erich Gamma 已提交
804 805 806
			anyPath = parsedPath.path;
		}

B
Benjamin Pasero 已提交
807
		const candidate = path.normalize(anyPath);
E
Erich Gamma 已提交
808
		try {
B
Benjamin Pasero 已提交
809
			const candidateStat = fs.statSync(candidate);
E
Erich Gamma 已提交
810
			if (candidateStat) {
811
				if (candidateStat.isFile()) {
812

813 814 815 816
					// Workspace (unless disabled via flag)
					if (!options || !options.forceOpenWorkspaceAsFile) {
						const workspace = this.workspacesService.resolveWorkspaceSync(candidate);
						if (workspace) {
817
							return { workspace: { id: workspace.id, configPath: workspace.configPath } };
818
						}
819 820 821
					}

					// File
822
					return {
823
						filePath: candidate,
E
Erich Gamma 已提交
824
						lineNumber: gotoLineMode ? parsedPath.line : void 0,
825
						columnNumber: gotoLineMode ? parsedPath.column : void 0
826 827 828 829 830 831 832
					};
				}

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

837
			if (options && options.ignoreFileNotFound) {
E
Erich Gamma 已提交
838 839 840 841 842 843 844
				return { filePath: candidate, createFilePath: true }; // assume this is a file that does not yet exist
			}
		}

		return null;
	}

B
Benjamin Pasero 已提交
845 846 847 848
	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');
849 850 851
		const openFolderInNewWindowConfig = (windowConfig && windowConfig.openFoldersInNewWindow) || 'default' /* default */;
		const openFilesInNewWindowConfig = (windowConfig && windowConfig.openFilesInNewWindow) || 'off' /* default */;

B
Benjamin Pasero 已提交
852
		let openFolderInNewWindow = (openConfig.preferNewWindow || openConfig.forceNewWindow) && !openConfig.forceReuseWindow;
853 854
		if (!openConfig.forceNewWindow && !openConfig.forceReuseWindow && (openFolderInNewWindowConfig === 'on' || openFolderInNewWindowConfig === 'off')) {
			openFolderInNewWindow = (openFolderInNewWindowConfig === 'on');
B
Benjamin Pasero 已提交
855 856 857 858 859 860 861 862 863 864 865
		}

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

866 867
			if (!openConfig.cli.extensionDevelopmentPath && (openFilesInNewWindowConfig === 'on' || openFilesInNewWindowConfig === 'off')) {
				openFilesInNewWindow = (openFilesInNewWindowConfig === 'on');
B
Benjamin Pasero 已提交
868 869 870 871 872 873
			}
		}

		return { openFolderInNewWindow, openFilesInNewWindow };
	}

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

B
Benjamin Pasero 已提交
876 877 878
		// 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.
879 880 881 882
		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 已提交
883

B
Benjamin Pasero 已提交
884 885
			return;
		}
E
Erich Gamma 已提交
886

887
		// Fill in previously opened workspace unless an explicit path is provided and we are not unit testing
B
Benjamin Pasero 已提交
888
		if (openConfig.cli._.length === 0 && !openConfig.cli.extensionTestsPath) {
889 890 891 892
			const extensionDevelopmentWindowState = this.windowsState.lastPluginDevelopmentHostWindow;
			const workspaceToOpen = extensionDevelopmentWindowState && (extensionDevelopmentWindowState.workspace || extensionDevelopmentWindowState.folderPath);
			if (workspaceToOpen) {
				openConfig.cli._ = [isSingleFolderWorkspaceIdentifier(workspaceToOpen) ? workspaceToOpen : workspaceToOpen.configPath];
E
Erich Gamma 已提交
893 894 895
			}
		}

896 897 898
		// 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 已提交
899 900
		}

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

B
Benjamin Pasero 已提交
905 906 907 908 909 910 911 912
	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;
913
		configuration.workspace = options.workspace;
914
		configuration.folderPath = options.folderPath;
B
Benjamin Pasero 已提交
915 916 917 918 919
		configuration.filesToOpen = options.filesToOpen;
		configuration.filesToCreate = options.filesToCreate;
		configuration.filesToDiff = options.filesToDiff;
		configuration.nodeCachedDataDir = this.environmentService.nodeCachedDataDir;

920
		// if we know the backup folder upfront (for empty windows to restore), we can set it
921
		// directly here which helps for restoring UI state associated with that window.
B
Benjamin Pasero 已提交
922
		// For all other cases we first call into registerEmptyWindowBackupSync() to set it before
923
		// loading the window.
924 925
		if (options.emptyWindowBackupFolder) {
			configuration.backupPath = path.join(this.environmentService.backupHome, options.emptyWindowBackupFolder);
926 927
		}

928
		let window: CodeWindow;
B
Benjamin Pasero 已提交
929
		if (!options.forceNewWindow) {
930 931 932
			window = options.windowToUse || this.getLastActiveWindow();
			if (window) {
				window.focus();
E
Erich Gamma 已提交
933 934 935 936
			}
		}

		// New window
937
		if (!window) {
938
			const windowConfig = this.configurationService.getConfiguration<IWindowSettings>('window');
939 940 941 942 943 944 945 946 947 948
			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 {
949
				allowFullscreen = this.lifecycleService.wasRestarted || (windowConfig && windowConfig.restoreFullscreen);
950 951 952 953 954
			}

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

956
			window = this.instantiationService.createInstance(CodeWindow, {
957
				state,
958
				extensionDevelopmentPath: configuration.extensionDevelopmentPath,
959
				isExtensionTestHost: !!configuration.extensionTestsPath
960
			});
961

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

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

E
Erich Gamma 已提交
968
			// Window Events
969 970 971 972 973
			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 已提交
974 975

			// Lifecycle
976
			this.lifecycleService.registerWindow(window);
E
Erich Gamma 已提交
977 978 979 980 981 982
		}

		// Existing window
		else {

			// Some configuration things get inherited if the window is being reused and we are
B
Benjamin Pasero 已提交
983
			// in extension development host mode. These options are all development related.
984
			const currentWindowConfig = window.config;
A
Alex Dima 已提交
985 986
			if (!configuration.extensionDevelopmentPath && currentWindowConfig && !!currentWindowConfig.extensionDevelopmentPath) {
				configuration.extensionDevelopmentPath = currentWindowConfig.extensionDevelopmentPath;
B
Benjamin Pasero 已提交
987
				configuration.verbose = currentWindowConfig.verbose;
988
				configuration.debugBrkPluginHost = currentWindowConfig.debugBrkPluginHost;
989
				configuration.debugId = currentWindowConfig.debugId;
990
				configuration.debugPluginHost = currentWindowConfig.debugPluginHost;
991
				configuration['extensions-dir'] = currentWindowConfig['extensions-dir'];
E
Erich Gamma 已提交
992 993 994 995
			}
		}

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

B
Benjamin Pasero 已提交
999 1000
				// Register window for backups
				if (!configuration.extensionDevelopmentPath) {
1001 1002
					if (configuration.workspace) {
						configuration.backupPath = this.backupService.registerWorkspaceBackupSync(configuration.workspace);
1003
					} else if (configuration.folderPath) {
B
Benjamin Pasero 已提交
1004
						configuration.backupPath = this.backupService.registerFolderBackupSync(configuration.folderPath);
B
Benjamin Pasero 已提交
1005 1006 1007
					} else {
						configuration.backupPath = this.backupService.registerEmptyWindowBackupSync(options.emptyWindowBackupFolder);
					}
B
Benjamin Pasero 已提交
1008 1009
				}

E
Erich Gamma 已提交
1010
				// Load it
1011
				window.load(configuration);
E
Erich Gamma 已提交
1012 1013
			}
		});
1014

1015
		return window;
E
Erich Gamma 已提交
1016 1017
	}

1018
	private getNewWindowState(configuration: IWindowConfiguration): INewWindowState {
1019
		const lastActive = this.getLastActiveWindow();
E
Erich Gamma 已提交
1020

1021 1022
		// Restore state unless we are running extension tests
		if (!configuration.extensionTestsPath) {
E
Erich Gamma 已提交
1023

1024 1025 1026
			// extension development host Window - load from stored settings if any
			if (!!configuration.extensionDevelopmentPath && this.windowsState.lastPluginDevelopmentHostWindow) {
				return this.windowsState.lastPluginDevelopmentHostWindow.uiState;
1027 1028
			}

1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
			// 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];
				}
1043 1044
			}

1045 1046 1047 1048 1049 1050
			// 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 已提交
1051 1052
			}

1053 1054 1055 1056 1057
			// First Window
			const lastActiveState = this.lastClosedWindowState || this.windowsState.lastActiveWindow;
			if (!lastActive && lastActiveState) {
				return lastActiveState.uiState;
			}
E
Erich Gamma 已提交
1058 1059 1060 1061 1062 1063 1064
		}

		//
		// 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
1065
		let displayToUse: Electron.Display;
B
Benjamin Pasero 已提交
1066
		const displays = screen.getAllDisplays();
E
Erich Gamma 已提交
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076

		// 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 已提交
1077
			if (isMacintosh) {
B
Benjamin Pasero 已提交
1078
				const cursorPoint = screen.getCursorScreenPoint();
E
Erich Gamma 已提交
1079 1080 1081 1082 1083 1084 1085 1086
				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());
			}

1087
			// fallback to primary display or first display
E
Erich Gamma 已提交
1088
			if (!displayToUse) {
1089
				displayToUse = screen.getPrimaryDisplay() || displays[0];
E
Erich Gamma 已提交
1090 1091 1092
			}
		}

1093
		let state = defaultWindowState() as INewWindowState;
1094 1095
		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 已提交
1096

1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
		// 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 已提交
1108 1109 1110 1111 1112 1113 1114
				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;
				}

1115 1116 1117 1118 1119 1120 1121 1122
				ensureNoOverlap = false;
			}
		}

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

1123 1124
		state.hasDefaultState = true; // flag as default state

1125
		return state;
E
Erich Gamma 已提交
1126 1127
	}

J
Joao Moreno 已提交
1128
	private ensureNoOverlap(state: ISingleWindowState): ISingleWindowState {
E
Erich Gamma 已提交
1129 1130 1131 1132
		if (WindowsManager.WINDOWS.length === 0) {
			return state;
		}

1133 1134
		const existingWindowBounds = WindowsManager.WINDOWS.map(win => win.getBounds());
		while (existingWindowBounds.some(b => b.x === state.x || b.y === state.y)) {
E
Erich Gamma 已提交
1135 1136 1137 1138 1139 1140 1141
			state.x += 30;
			state.y += 30;
		}

		return state;
	}

B
Benjamin Pasero 已提交
1142 1143 1144 1145 1146
	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) {
1147
				win.reload(void 0, cli);
B
Benjamin Pasero 已提交
1148 1149 1150 1151 1152 1153 1154

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

1155 1156 1157 1158 1159 1160 1161
	public closeWorkspace(win: CodeWindow): void {
		this.openInBrowserWindow({
			cli: this.environmentService.args,
			windowToUse: win
		});
	}

1162 1163 1164 1165 1166 1167 1168 1169
	public saveAndOpenWorkspace(window: CodeWindow, path: string): TPromise<void> {
		if (!window || !window.win || window.readyState !== ReadyState.READY || !window.openedWorkspace || !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);
	}

1170 1171 1172 1173 1174 1175
	public createAndOpenWorkspace(window: CodeWindow, folders?: string[], path?: string): TPromise<void> {
		if (!window || !window.win || window.readyState !== ReadyState.READY) {
			return TPromise.as(null); // return early if the window is not ready or disposed
		}

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

1180 1181 1182 1183 1184 1185 1186
	private doSaveAndOpenWorkspace(window: CodeWindow, workspace: IWorkspaceIdentifier, path?: string): TPromise<void> {
		let savePromise: TPromise<IWorkspaceIdentifier>;
		if (path) {
			savePromise = this.workspacesService.saveWorkspace(workspace, path);
		} else {
			savePromise = TPromise.as(workspace);
		}
1187

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

1191 1192 1193
			// Only open workspace when the window has not vetoed this
			return this.lifecycleService.unload(window, UnloadReason.RELOAD, workspace).done(veto => {
				if (!veto) {
1194

1195 1196 1197 1198
					// Register window for backups and migrate current backups over
					let backupPath: string;
					if (window.config && !window.config.extensionDevelopmentPath) {
						backupPath = this.backupService.registerWorkspaceBackupSync(workspace, window.config.backupPath);
1199
					}
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209

					// Craft a new window configuration to use for the transition
					const configuration: IWindowConfiguration = mixin({}, window.config);
					configuration.folderPath = void 0;
					configuration.workspace = workspace;
					configuration.backupPath = backupPath;

					// Reload
					window.reload(configuration);
				}
1210 1211 1212 1213
			});
		});
	}

1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
	public openWorkspace(window: CodeWindow = this.getLastActiveWindow()): void {
		let defaultPath: string;
		if (window && window.openedWorkspace && !this.workspacesService.isUntitledWorkspace(window.openedWorkspace)) {
			defaultPath = path.dirname(window.openedWorkspace.configPath);
		} else {
			defaultPath = this.getWorkspaceDialogDefaultPath(window ? (window.openedWorkspace || window.openedFolderPath) : void 0);
		}

		this.pickFileAndOpen({
			windowId: window ? window.id : void 0,
			dialogOptions: {
1225
				buttonLabel: mnemonicLabel(localize({ key: 'openWorkspace', comment: ['&& denotes a mnemonic'] }, "&&Open")),
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
				title: localize('openWorkspaceTitle', "Open Workspace"),
				filters: WORKSPACE_FILTER,
				properties: ['openFile'],
				defaultPath
			}
		});
	}

	private getWorkspaceDialogDefaultPath(workspace?: IWorkspaceIdentifier | ISingleFolderWorkspaceIdentifier): string {
		let defaultPath: string;
		if (workspace) {
			if (isSingleFolderWorkspaceIdentifier(workspace)) {
				defaultPath = path.dirname(workspace);
			} else {
				const resolvedWorkspace = this.workspacesService.resolveWorkspaceSync(workspace.configPath);
1241 1242
				if (resolvedWorkspace && resolvedWorkspace.folders.length > 0) {
					defaultPath = path.dirname(resolvedWorkspace.folders[0].path);
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
				}
			}
		}

		return defaultPath;
	}

	private onBeforeWindowUnload(e: IWindowUnloadEvent): void {
		const windowClosing = e.reason === UnloadReason.CLOSE;
		const windowLoading = e.reason === UnloadReason.LOAD;
		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
		}

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

		this.promptToSaveUntitledWorkspace(e, workspace);
	}

	private promptToSaveUntitledWorkspace(e: IWindowUnloadEvent, workspace: IWorkspaceIdentifier): void {
		enum ConfirmResult {
			SAVE,
			DONT_SAVE,
			CANCEL
		}

1276 1277
		const save = { label: mnemonicLabel(localize({ key: 'save', comment: ['&& denotes a mnemonic'] }, "&&Save")), result: ConfirmResult.SAVE };
		const dontSave = { label: mnemonicLabel(localize({ key: 'doNotSave', comment: ['&& denotes a mnemonic'] }, "Do&&n't Save")), result: ConfirmResult.DONT_SAVE };
1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
		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.ShowMessageBoxOptions = {
			title: this.environmentService.appNameLong,
B
Benjamin Pasero 已提交
1291 1292
			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."),
1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
			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: {
				const target = dialog.showSaveDialog(e.window.win, {
1321
					buttonLabel: mnemonicLabel(localize({ key: 'save', comment: ['&& denotes a mnemonic'] }, "&&Save")),
1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335
					title: localize('saveWorkspace', "Save Workspace"),
					filters: WORKSPACE_FILTER,
					defaultPath: this.getWorkspaceDialogDefaultPath(workspace)
				});

				if (target) {
					e.veto(this.workspacesService.saveWorkspace(workspace, target).then(() => false, () => false));
				} else {
					e.veto(true); // keep veto if no target was provided
				}
			}
		}
	}

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

			return lastActive;
E
Erich Gamma 已提交
1342 1343
		}

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

B
Benjamin Pasero 已提交
1348
	public getLastActiveWindow(): CodeWindow {
1349
		return getLastActiveWindow(WindowsManager.WINDOWS);
E
Erich Gamma 已提交
1350 1351
	}

1352 1353
	public openNewWindow(context: OpenContext): void {
		this.open({ context, cli: this.environmentService.args, forceNewWindow: true, forceEmpty: true });
E
Erich Gamma 已提交
1354 1355
	}

1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
	public waitForWindowClose(windowId: number): TPromise<void> {
		return new TPromise<void>(c => {
			const toDispose = this.onWindowClose(id => {
				if (id === windowId) {
					toDispose.dispose();
					c(null);
				}
			});
		});
	}

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

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

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

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

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

		return null;
	}

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

		return null;
	}

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

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

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

		// Unresponsive
		if (error === WindowError.UNRESPONSIVE) {
1416
			dialog.showMessageBox(window.win, {
B
Benjamin Pasero 已提交
1417
				title: product.nameLong,
E
Erich Gamma 已提交
1418
				type: 'warning',
1419 1420 1421
				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 已提交
1422
				noLink: true
1423
			}, result => {
1424
				if (!window.win) {
1425 1426 1427
					return; // Return early if the window has been going down already
				}

E
Erich Gamma 已提交
1428
				if (result === 0) {
1429
					window.reload();
1430
				} else if (result === 2) {
1431 1432
					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 已提交
1433 1434 1435 1436 1437 1438
				}
			});
		}

		// Crashed
		else {
1439
			dialog.showMessageBox(window.win, {
B
Benjamin Pasero 已提交
1440
				title: product.nameLong,
E
Erich Gamma 已提交
1441
				type: 'warning',
1442 1443 1444
				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 已提交
1445
				noLink: true
1446
			}, result => {
1447
				if (!window.win) {
1448 1449 1450
					return; // Return early if the window has been going down already
				}

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

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

		// Tell window
		win.dispose();

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

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

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

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

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

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

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

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

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

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

		this.fileDialog.pickAndOpen(internalOptions);
B
Benjamin Pasero 已提交
1518 1519 1520 1521 1522 1523
	}

	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.
1524 1525 1526
		const window = this.getFocusedWindow();
		if (window && window.isExtensionDevelopmentHost && this.getWindowCount() > 1) {
			window.win.close();
B
Benjamin Pasero 已提交
1527 1528 1529 1530 1531 1532 1533 1534
		}

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

B
Benjamin Pasero 已提交
1538
interface IInternalNativeOpenDialogOptions extends INativeOpenDialogOptions {
B
Benjamin Pasero 已提交
1539 1540 1541 1542 1543 1544 1545
	pickFolders?: boolean;
	pickFiles?: boolean;
}

class FileDialog {

	private static workingDirPickerStorageKey = 'pickerWorkingDir';
1546

B
Benjamin Pasero 已提交
1547 1548 1549 1550 1551 1552 1553 1554
	constructor(
		private environmentService: IEnvironmentService,
		private telemetryService: ITelemetryService,
		private storageService: IStorageService,
		private windowsMainService: IWindowsMainService
	) {
	}

B
Benjamin Pasero 已提交
1555
	public pickAndOpen(options: INativeOpenDialogOptions): void {
1556
		this.getFileOrFolderPaths(options, (paths: string[]) => {
B
Benjamin Pasero 已提交
1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569
			const numberOfPaths = paths ? paths.length : 0;

			// Telemetry
			if (options.telemetryEventName) {
				this.telemetryService.publicLog(options.telemetryEventName, {
					...options.telemetryExtraData,
					outcome: numberOfPaths ? 'success' : 'canceled',
					numberOfPaths
				});
			}

			// Open
			if (numberOfPaths) {
1570 1571 1572 1573 1574 1575 1576
				this.windowsMainService.open({
					context: OpenContext.DIALOG,
					cli: this.environmentService.args,
					pathsToOpen: paths,
					forceNewWindow: options.forceNewWindow,
					forceOpenWorkspaceAsFile: options.dialogOptions && !equals(options.dialogOptions.filters, WORKSPACE_FILTER)
				});
1577 1578 1579 1580
			}
		});
	}

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

B
Benjamin Pasero 已提交
1583 1584 1585 1586 1587 1588 1589 1590
		// 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);
1591 1592
		}

B
Benjamin Pasero 已提交
1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
		// 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'];
		}

		// Show Dialog
1607 1608
		const focusedWindow = this.windowsMainService.getWindowById(options.windowId) || this.windowsMainService.getFocusedWindow();
		dialog.showOpenDialog(focusedWindow && focusedWindow.win, options.dialogOptions, paths => {
1609 1610 1611
			if (paths && paths.length > 0) {

				// Remember path in storage for next time
B
Benjamin Pasero 已提交
1612
				this.storageService.setItem(FileDialog.workingDirPickerStorageKey, path.dirname(paths[0]));
1613 1614

				// Return
B
Benjamin Pasero 已提交
1615
				return clb(paths);
1616
			}
B
Benjamin Pasero 已提交
1617 1618

			return clb(void (0));
1619 1620
		});
	}
1621
}