windows.ts 44.8 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';
J
Joao Moreno 已提交
10 11 12
import * as platform from 'vs/base/common/platform';
import * as nls from 'vs/nls';
import * as paths from 'vs/base/common/paths';
13
import * as types from 'vs/base/common/types';
J
Joao Moreno 已提交
14
import * as arrays from 'vs/base/common/arrays';
15
import { assign, mixin } from 'vs/base/common/objects';
D
Daniel Imms 已提交
16
import { IBackupMainService } from 'vs/platform/backup/common/backup';
17
import { trim } from 'vs/base/common/strings';
J
Joao Moreno 已提交
18
import { IEnvironmentService, ParsedArgs } from 'vs/platform/environment/common/environment';
J
Joao Moreno 已提交
19
import { IStorageService } from 'vs/code/electron-main/storage';
20
import { IPath, VSCodeWindow, IWindowConfiguration, IWindowState as ISingleWindowState, defaultWindowState, ReadyState, WindowMode } from 'vs/code/electron-main/window';
21
import { ipcMain as ipc, app, screen, BrowserWindow, dialog } from 'electron';
22
import { IPathWithLineAndColumn, parseLineAndColumnAware } from 'vs/code/electron-main/paths';
23
import { ILifecycleService, UnloadReason } from 'vs/code/electron-main/lifecycle';
24
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
B
Benjamin Pasero 已提交
25
import { ILogService } from 'vs/code/electron-main/log';
26
import { getPathLabel } from 'vs/base/common/labels';
J
Johannes Rieken 已提交
27
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
28
import { IWindowSettings } from 'vs/platform/windows/common/windows';
C
Christof Marti 已提交
29
import { getLastActiveWindow, findBestWindowOrFolder } from 'vs/code/node/windowsUtils';
30
import CommonEvent, { Emitter } from 'vs/base/common/event';
31
import product from 'vs/platform/node/product';
C
Christof Marti 已提交
32
import { OpenContext } from 'vs/code/common/windows';
E
Erich Gamma 已提交
33 34 35 36 37 38 39

enum WindowError {
	UNRESPONSIVE,
	CRASHED
}

export interface IOpenConfiguration {
40
	context: OpenContext;
B
Benjamin Pasero 已提交
41
	cli: ParsedArgs;
42
	userEnv?: platform.IProcessEnvironment;
E
Erich Gamma 已提交
43
	pathsToOpen?: string[];
44
	preferNewWindow?: boolean;
E
Erich Gamma 已提交
45
	forceNewWindow?: boolean;
46
	forceReuseWindow?: boolean;
E
Erich Gamma 已提交
47
	forceEmpty?: boolean;
J
Joao Moreno 已提交
48
	windowToUse?: VSCodeWindow;
49
	diffMode?: boolean;
B
Benjamin Pasero 已提交
50
	initialStartup?: boolean;
E
Erich Gamma 已提交
51 52
}

53 54 55 56
interface INewWindowState extends ISingleWindowState {
	hasDefaultState?: boolean;
}

E
Erich Gamma 已提交
57 58
interface IWindowState {
	workspacePath?: string;
J
Joao Moreno 已提交
59
	uiState: ISingleWindowState;
E
Erich Gamma 已提交
60 61 62 63 64 65 66 67
}

interface IWindowsState {
	lastActiveWindow?: IWindowState;
	lastPluginDevelopmentHostWindow?: IWindowState;
	openedFolders: IWindowState[];
}

68
export interface IRecentPathsList {
E
Erich Gamma 已提交
69 70 71 72
	folders: string[];
	files: string[];
}

73 74 75
interface INativeOpenDialogOptions {
	pickFolders?: boolean;
	pickFiles?: boolean;
76 77
	path?: string;
	forceNewWindow?: boolean;
78
	window?: VSCodeWindow;
79 80
}

81 82 83 84 85 86
const ReopenFoldersSetting = {
	ALL: 'all',
	ONE: 'one',
	NONE: 'none'
};

J
Joao Moreno 已提交
87
export const IWindowsMainService = createDecorator<IWindowsMainService>('windowsMainService');
J
Joao Moreno 已提交
88

J
Joao Moreno 已提交
89
export interface IWindowsMainService {
90
	_serviceBrand: any;
J
Joao Moreno 已提交
91 92

	// events
93 94
	onWindowReady: CommonEvent<VSCodeWindow>;
	onWindowClose: CommonEvent<number>;
95
	onWindowReload: CommonEvent<number>;
B
Benjamin Pasero 已提交
96
	onPathsOpen: CommonEvent<IPath[]>;
97
	onRecentPathsChange: CommonEvent<void>;
J
Joao Moreno 已提交
98 99

	// methods
100
	ready(initialUserEnv: platform.IProcessEnvironment): void;
B
Benjamin Pasero 已提交
101
	reload(win: VSCodeWindow, cli?: ParsedArgs): void;
J
Joao Moreno 已提交
102
	open(openConfig: IOpenConfiguration): VSCodeWindow[];
B
Benjamin Pasero 已提交
103
	openExtensionDevelopmentHostWindow(openConfig: IOpenConfiguration): void;
J
Joao Moreno 已提交
104
	openFileFolderPicker(forceNewWindow?: boolean): void;
105 106
	openFilePicker(forceNewWindow?: boolean, path?: string, window?: VSCodeWindow): void;
	openFolderPicker(forceNewWindow?: boolean, window?: VSCodeWindow): void;
107
	openAccessibilityOptions(): void;
108
	focusLastActive(cli: ParsedArgs, context: OpenContext): VSCodeWindow;
J
Joao Moreno 已提交
109 110
	getLastActiveWindow(): VSCodeWindow;
	findWindow(workspacePath: string, filePath?: string, extensionDevelopmentPath?: string): VSCodeWindow;
111
	openNewWindow(context: OpenContext): void;
J
Joao Moreno 已提交
112 113
	sendToFocused(channel: string, ...args: any[]): void;
	sendToAll(channel: string, payload: any, windowIdsToIgnore?: number[]): void;
J
Joao Moreno 已提交
114 115 116
	getFocusedWindow(): VSCodeWindow;
	getWindowById(windowId: number): VSCodeWindow;
	getWindows(): VSCodeWindow[];
J
Joao Moreno 已提交
117
	getWindowCount(): number;
118
	addToRecentPathsList(paths: { path: string; isFile?: boolean; }[]): void;
J
Joao Moreno 已提交
119
	getRecentPathsList(workspacePath?: string, filesToOpen?: IPath[]): IRecentPathsList;
B
Benjamin Pasero 已提交
120 121
	removeFromRecentPathsList(path: string): void;
	removeFromRecentPathsList(paths: string[]): void;
122
	clearRecentPathsList(): void;
123
	quit(): void;
J
Joao Moreno 已提交
124 125
}

J
Joao Moreno 已提交
126
export class WindowsManager implements IWindowsMainService {
J
Joao Moreno 已提交
127

128
	_serviceBrand: any;
E
Erich Gamma 已提交
129

130
	private static MAX_TOTAL_RECENT_ENTRIES = 100;
131

132
	private static recentPathsListStorageKey = 'openedPathsList';
133
	private static workingDirPickerStorageKey = 'pickerWorkingDir';
E
Erich Gamma 已提交
134 135
	private static windowsStateStorageKey = 'windowsState';

J
Joao Moreno 已提交
136
	private static WINDOWS: VSCodeWindow[] = [];
E
Erich Gamma 已提交
137

138
	private initialUserEnv: platform.IProcessEnvironment;
E
Erich Gamma 已提交
139 140
	private windowsState: IWindowsState;

141 142 143 144 145 146 147 148 149
	private _onRecentPathsChange = new Emitter<void>();
	onRecentPathsChange: CommonEvent<void> = this._onRecentPathsChange.event;

	private _onWindowReady = new Emitter<VSCodeWindow>();
	onWindowReady: CommonEvent<VSCodeWindow> = this._onWindowReady.event;

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

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

B
Benjamin Pasero 已提交
153 154
	private _onPathsOpen = new Emitter<IPath[]>();
	onPathsOpen: CommonEvent<IPath> = this._onPathsOpen.event;
155

J
Joao Moreno 已提交
156 157
	constructor(
		@ILogService private logService: ILogService,
J
Joao Moreno 已提交
158
		@IStorageService private storageService: IStorageService,
159
		@IEnvironmentService private environmentService: IEnvironmentService,
B
Benjamin Pasero 已提交
160
		@ILifecycleService private lifecycleService: ILifecycleService,
161
		@IBackupMainService private backupService: IBackupMainService,
162
		@IConfigurationService private configurationService: IConfigurationService
163
	) { }
J
Joao Moreno 已提交
164

165
	public ready(initialUserEnv: platform.IProcessEnvironment): void {
E
Erich Gamma 已提交
166 167
		this.registerListeners();

168
		this.initialUserEnv = initialUserEnv;
J
Joao Moreno 已提交
169
		this.windowsState = this.storageService.getItem<IWindowsState>(WindowsManager.windowsStateStorageKey) || { openedFolders: [] };
170 171

		this.updateWindowsJumpList();
E
Erich Gamma 已提交
172 173 174
	}

	private registerListeners(): void {
175
		app.on('activate', (event: Event, hasVisibleWindows: boolean) => {
J
Joao Moreno 已提交
176
			this.logService.log('App#activate');
E
Erich Gamma 已提交
177

G
Giorgos Retsinas 已提交
178
			// Mac only event: open new window when we get activated
E
Erich Gamma 已提交
179
			if (!hasVisibleWindows) {
180
				this.openNewWindow(OpenContext.DOCK);
E
Erich Gamma 已提交
181 182 183 184 185 186
			}
		});

		let macOpenFiles: string[] = [];
		let runningTimeout: number = null;
		app.on('open-file', (event: Event, path: string) => {
J
Joao Moreno 已提交
187
			this.logService.log('App#open-file: ', path);
E
Erich Gamma 已提交
188 189 190 191 192 193 194 195 196 197 198 199 200
			event.preventDefault();

			// Keep in array because more might come!
			macOpenFiles.push(path);

			// Clear previous handler if any
			if (runningTimeout !== null) {
				clearTimeout(runningTimeout);
				runningTimeout = null;
			}

			// Handle paths delayed in case more are coming!
			runningTimeout = setTimeout(() => {
B
Benjamin Pasero 已提交
201 202 203 204 205 206
				this.open({
					context: OpenContext.DOCK /* can also be opening from finder while app is running */,
					cli: this.environmentService.args,
					pathsToOpen: macOpenFiles,
					preferNewWindow: true /* dropping on the dock or opening from finder prefers to open in a new window */
				});
E
Erich Gamma 已提交
207 208 209 210 211
				macOpenFiles = [];
				runningTimeout = null;
			}, 100);
		});

B
Benjamin Pasero 已提交
212
		ipc.on('vscode:workbenchLoaded', (event, windowId: number) => {
J
Joao Moreno 已提交
213
			this.logService.log('IPC#vscode-workbenchLoaded');
E
Erich Gamma 已提交
214

B
Benjamin Pasero 已提交
215
			const win = this.getWindowById(windowId);
E
Erich Gamma 已提交
216 217 218 219
			if (win) {
				win.setReady();

				// Event
220
				this._onWindowReady.fire(win);
E
Erich Gamma 已提交
221 222 223
			}
		});

B
Benjamin Pasero 已提交
224
		ipc.on('vscode:broadcast', (event, windowId: number, target: string, broadcast: { channel: string; payload: any; }) => {
225
			if (broadcast.channel && !types.isUndefinedOrNull(broadcast.payload)) {
J
Joao Moreno 已提交
226
				this.logService.log('IPC#vscode:broadcast', target, broadcast.channel, broadcast.payload);
B
Benjamin Pasero 已提交
227

228 229 230 231
				// Handle specific events on main side
				this.onBroadcast(broadcast.channel, broadcast.payload);

				// Send to windows
232
				if (target) {
B
Benjamin Pasero 已提交
233
					const otherWindowsWithTarget = WindowsManager.WINDOWS.filter(w => w.id !== windowId && typeof w.openedWorkspacePath === 'string');
234 235 236 237 238
					const directTargetMatch = otherWindowsWithTarget.filter(w => this.isPathEqual(target, w.openedWorkspacePath));
					const parentTargetMatch = otherWindowsWithTarget.filter(w => paths.isEqualOrParent(target, w.openedWorkspacePath));

					const targetWindow = directTargetMatch.length ? directTargetMatch[0] : parentTargetMatch[0]; // prefer direct match over parent match
					if (targetWindow) {
239 240 241 242 243
						targetWindow.send('vscode:broadcast', broadcast);
					}
				} else {
					this.sendToAll('vscode:broadcast', broadcast, [windowId]);
				}
E
Erich Gamma 已提交
244
			}
245 246
		});

J
Joao Moreno 已提交
247
		this.lifecycleService.onBeforeQuit(() => {
E
Erich Gamma 已提交
248 249 250 251 252 253 254 255

			// 0-1 window open: Do not keep the list but just rely on the active window to be stored
			if (WindowsManager.WINDOWS.length < 2) {
				this.windowsState.openedFolders = [];
				return;
			}

			// 2-N windows open: Keep a list of windows that are opened on a specific folder to restore it in the next session as needed
256
			this.windowsState.openedFolders = WindowsManager.WINDOWS.filter(w => w.readyState === ReadyState.READY && !!w.openedWorkspacePath && !w.isExtensionDevelopmentHost).map(w => {
E
Erich Gamma 已提交
257 258 259
				return <IWindowState>{
					workspacePath: w.openedWorkspacePath,
					uiState: w.serializeWindowState()
B
Benjamin Pasero 已提交
260
				};
E
Erich Gamma 已提交
261 262 263 264
			});
		});

		app.on('will-quit', () => {
J
Joao Moreno 已提交
265
			this.storageService.setItem(WindowsManager.windowsStateStorageKey, this.windowsState);
E
Erich Gamma 已提交
266
		});
267

268 269
		// Update jump list when recent paths change
		this.onRecentPathsChange(() => this.updateWindowsJumpList());
E
Erich Gamma 已提交
270 271
	}

272
	private onBroadcast(event: string, payload: any): void {
273 274

		// Theme changes
275 276
		if (event === 'vscode:changeColorTheme' && typeof payload === 'string') {
			this.storageService.setItem(VSCodeWindow.themeStorageKey, payload);
277
		}
278
	}
B
Benjamin Pasero 已提交
279
	public reload(win: VSCodeWindow, cli?: ParsedArgs): void {
E
Erich Gamma 已提交
280 281

		// Only reload when the window has not vetoed this
282
		this.lifecycleService.unload(win, UnloadReason.RELOAD).done(veto => {
E
Erich Gamma 已提交
283 284
			if (!veto) {
				win.reload(cli);
285 286 287

				// Emit
				this._onWindowReload.fire(win.id);
E
Erich Gamma 已提交
288 289 290 291
			}
		});
	}

J
Joao Moreno 已提交
292
	public open(openConfig: IOpenConfiguration): VSCodeWindow[] {
293 294
		const windowConfig = this.configurationService.getConfiguration<IWindowSettings>('window');

J
Joao Moreno 已提交
295
		let iPathsToOpen: IPath[];
B
Benjamin Pasero 已提交
296
		const usedWindows: VSCodeWindow[] = [];
E
Erich Gamma 已提交
297 298 299

		// Find paths from provided paths if any
		if (openConfig.pathsToOpen && openConfig.pathsToOpen.length > 0) {
300
			iPathsToOpen = openConfig.pathsToOpen.map(pathToOpen => {
B
Benjamin Pasero 已提交
301
				const iPath = this.toIPath(pathToOpen, false, openConfig.cli && openConfig.cli.goto);
E
Erich Gamma 已提交
302 303 304

				// Warn if the requested path to open does not exist
				if (!iPath) {
B
Benjamin Pasero 已提交
305
					const options: Electron.ShowMessageBoxOptions = {
B
Benjamin Pasero 已提交
306
						title: product.nameLong,
E
Erich Gamma 已提交
307 308 309 310 311 312 313
						type: 'info',
						buttons: [nls.localize('ok', "OK")],
						message: nls.localize('pathNotExistTitle', "Path does not exist"),
						detail: nls.localize('pathNotExistDetail', "The path '{0}' does not seem to exist anymore on disk.", pathToOpen),
						noLink: true
					};

B
Benjamin Pasero 已提交
314
					const activeWindow = BrowserWindow.getFocusedWindow();
E
Erich Gamma 已提交
315
					if (activeWindow) {
316
						dialog.showMessageBox(activeWindow, options);
E
Erich Gamma 已提交
317
					} else {
318
						dialog.showMessageBox(options);
E
Erich Gamma 已提交
319 320 321 322 323 324 325 326 327 328
					}
				}

				return iPath;
			});

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

			if (iPathsToOpen.length === 0) {
329
				return null; // indicate to outside that open failed
E
Erich Gamma 已提交
330 331 332 333 334 335 336 337 338 339
			}
		}

		// Check for force empty
		else if (openConfig.forceEmpty) {
			iPathsToOpen = [Object.create(null)];
		}

		// Otherwise infer from command line arguments
		else {
B
Benjamin Pasero 已提交
340
			const ignoreFileNotFound = openConfig.cli._.length > 0; // we assume the user wants to create this file from command line
E
Erich Gamma 已提交
341 342 343
			iPathsToOpen = this.cliToPaths(openConfig.cli, ignoreFileNotFound);
		}

344
		let foldersToOpen = arrays.distinct(iPathsToOpen.filter(iPath => iPath.workspacePath && !iPath.filePath).map(iPath => iPath.workspacePath), folder => platform.isLinux ? folder : folder.toLowerCase()); // prevent duplicates
345
		let foldersToRestore = (openConfig.initialStartup && !openConfig.cli.extensionDevelopmentPath) ? this.backupService.getWorkspaceBackupPaths() : [];
346 347 348
		let filesToOpen: IPath[] = [];
		let filesToDiff: IPath[] = [];
		let emptyToOpen = iPathsToOpen.filter(iPath => !iPath.workspacePath && !iPath.filePath);
349
		let emptyToRestore = (openConfig.initialStartup && !openConfig.cli.extensionDevelopmentPath) ? this.backupService.getEmptyWorkspaceBackupPaths() : [];
350 351 352 353 354 355 356 357 358 359 360
		let filesToCreate = iPathsToOpen.filter(iPath => !!iPath.filePath && iPath.createFilePath);

		// Diff mode needs special care
		const candidates = iPathsToOpen.filter(iPath => !!iPath.filePath && !iPath.createFilePath);
		if (openConfig.diffMode) {
			if (candidates.length === 2) {
				filesToDiff = candidates;
			} else {
				emptyToOpen = [Object.create(null)]; // improper use of diffMode, open empty
			}

361 362 363
			foldersToOpen = []; 	// diff is always in empty workspace
			foldersToRestore = [];	// diff is always in empty workspace
			filesToCreate = []; 	// diff ignores other files that do not exist
364 365 366 367
		} else {
			filesToOpen = candidates;
		}

368
		// let the user settings override how folders are open in a new window or same window unless we are forced
369
		let openFolderInNewWindow = (openConfig.preferNewWindow || openConfig.forceNewWindow) && !openConfig.forceReuseWindow;
370 371
		if (!openConfig.forceNewWindow && !openConfig.forceReuseWindow && windowConfig && (windowConfig.openFoldersInNewWindow === 'on' || windowConfig.openFoldersInNewWindow === 'off')) {
			openFolderInNewWindow = (windowConfig.openFoldersInNewWindow === 'on');
372
		}
373

B
Benjamin Pasero 已提交
374
		// 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
wip  
Benjamin Pasero 已提交
375
		if (!foldersToOpen.length && !foldersToRestore.length && !emptyToRestore.length && (filesToOpen.length > 0 || filesToCreate.length > 0 || filesToDiff.length > 0)) {
E
Erich Gamma 已提交
376

377
			// 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)
378
			let openFilesInNewWindow: boolean;
379 380
			if (openConfig.forceNewWindow || openConfig.forceReuseWindow) {
				openFilesInNewWindow = openConfig.forceNewWindow && !openConfig.forceReuseWindow;
381
			} else {
B
Benjamin Pasero 已提交
382
				if (openConfig.context === OpenContext.DOCK) {
383 384 385
					openFilesInNewWindow = true; // only on macOS do we allow to open files in a new window if this is triggered via DOCK context
				}

386
				if (!openConfig.cli.extensionDevelopmentPath && windowConfig && (windowConfig.openFilesInNewWindow === 'on' || windowConfig.openFilesInNewWindow === 'off' || <any>windowConfig.openFilesInNewWindow === false /* TODO@Ben migration */)) {
387
					openFilesInNewWindow = (windowConfig.openFilesInNewWindow === 'on');
388
				}
E
Erich Gamma 已提交
389 390 391
			}

			// Open Files in last instance if any and flag tells us so
392 393 394 395 396 397 398 399 400 401 402
			const fileToCheck = filesToOpen[0] || filesToCreate[0] || filesToDiff[0];
			const windowOrFolder = findBestWindowOrFolder({
				windows: WindowsManager.WINDOWS,
				newWindow: openFilesInNewWindow,
				reuseWindow: openConfig.forceReuseWindow,
				context: openConfig.context,
				filePath: fileToCheck && fileToCheck.filePath,
				userHome: this.environmentService.userHome
			});
			if (windowOrFolder instanceof VSCodeWindow) {
				windowOrFolder.focus();
403
				const files = { filesToOpen, filesToCreate, filesToDiff }; // copy to object because they get reset shortly after
404
				windowOrFolder.ready().then(readyWindow => {
405
					readyWindow.send('vscode:openFiles', files);
E
Erich Gamma 已提交
406
				});
407

408
				usedWindows.push(windowOrFolder);
E
Erich Gamma 已提交
409 410 411 412
			}

			// Otherwise open instance with files
			else {
413
				const configuration = this.toConfiguration(openConfig, windowOrFolder, filesToOpen, filesToCreate, filesToDiff);
B
Benjamin Pasero 已提交
414
				const browserWindow = this.openInBrowserWindow(configuration, true /* new window */);
415
				usedWindows.push(browserWindow);
E
Erich Gamma 已提交
416

B
Benjamin Pasero 已提交
417
				openFolderInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
418
			}
419 420 421 422 423

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

426 427 428
		// Handle folders to open (instructed and to restore)
		let allFoldersToOpen = arrays.distinct([...foldersToOpen, ...foldersToRestore], folder => platform.isLinux ? folder : folder.toLowerCase()); // prevent duplicates
		if (allFoldersToOpen.length > 0) {
E
Erich Gamma 已提交
429 430

			// Check for existing instances
431
			const windowsOnWorkspacePath = arrays.coalesce(allFoldersToOpen.map(folderToOpen => this.findWindow(folderToOpen)));
E
Erich Gamma 已提交
432
			if (windowsOnWorkspacePath.length > 0) {
B
Benjamin Pasero 已提交
433
				const browserWindow = windowsOnWorkspacePath[0];
434
				browserWindow.focus(); // just focus one of them
435
				const files = { filesToOpen, filesToCreate, filesToDiff }; // copy to object because they get reset shortly after
436
				browserWindow.ready().then(readyWindow => {
437
					readyWindow.send('vscode:openFiles', files);
E
Erich Gamma 已提交
438 439
				});

440 441
				usedWindows.push(browserWindow);

E
Erich Gamma 已提交
442 443 444
				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
445
				filesToDiff = [];
E
Erich Gamma 已提交
446

B
Benjamin Pasero 已提交
447
				openFolderInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
448 449 450
			}

			// Open remaining ones
451 452
			allFoldersToOpen.forEach(folderToOpen => {
				if (windowsOnWorkspacePath.some(win => this.isPathEqual(win.openedWorkspacePath, folderToOpen))) {
E
Erich Gamma 已提交
453 454 455
					return; // ignore folders that are already open
				}

456
				const configuration = this.toConfiguration(openConfig, folderToOpen, filesToOpen, filesToCreate, filesToDiff);
B
Benjamin Pasero 已提交
457
				const browserWindow = this.openInBrowserWindow(configuration, openFolderInNewWindow, openFolderInNewWindow ? void 0 : openConfig.windowToUse);
458
				usedWindows.push(browserWindow);
E
Erich Gamma 已提交
459 460 461 462

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

B
Benjamin Pasero 已提交
465
				openFolderInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
466 467 468 469
			});
		}

		// Handle empty
470
		if (emptyToRestore.length > 0) {
471
			emptyToRestore.forEach(emptyWorkspaceBackupFolder => {
B
wip  
Benjamin Pasero 已提交
472
				const configuration = this.toConfiguration(openConfig, void 0, filesToOpen, filesToCreate, filesToDiff);
473
				const browserWindow = this.openInBrowserWindow(configuration, true /* new window */, null, emptyWorkspaceBackupFolder);
474 475
				usedWindows.push(browserWindow);

B
wip  
Benjamin Pasero 已提交
476 477 478 479 480
				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
				filesToDiff = [];

B
Benjamin Pasero 已提交
481
				openFolderInNewWindow = true; // any other folders to open must open in new window then
482 483
			});
		}
B
Benjamin Pasero 已提交
484

485 486
		// Only open empty if no empty workspaces were restored
		else if (emptyToOpen.length > 0) {
E
Erich Gamma 已提交
487
			emptyToOpen.forEach(() => {
488
				const configuration = this.toConfiguration(openConfig);
B
Benjamin Pasero 已提交
489
				const browserWindow = this.openInBrowserWindow(configuration, openFolderInNewWindow, openFolderInNewWindow ? void 0 : openConfig.windowToUse);
490
				usedWindows.push(browserWindow);
E
Erich Gamma 已提交
491

B
Benjamin Pasero 已提交
492
				openFolderInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
493 494 495
			});
		}

496
		// Remember in recent document list (unless this opens for extension development)
497
		// Also do not add paths when files are opened for diffing, only if opened individually
498
		if (!usedWindows.some(w => w.isExtensionDevelopmentHost) && !openConfig.cli.diff) {
499 500
			const recentPaths: { path: string; isFile?: boolean; }[] = [];

501 502 503
			iPathsToOpen.forEach(iPath => {
				if (iPath.filePath || iPath.workspacePath) {
					app.addRecentDocument(iPath.filePath || iPath.workspacePath);
504
					recentPaths.push({ path: iPath.filePath || iPath.workspacePath, isFile: !!iPath.filePath });
505 506
				}
			});
E
Erich Gamma 已提交
507

508 509 510 511
			if (recentPaths.length) {
				this.addToRecentPathsList(recentPaths);
			}
		}
E
Erich Gamma 已提交
512

513
		// Emit events
B
Benjamin Pasero 已提交
514
		this._onPathsOpen.fire(iPathsToOpen);
515

516
		return arrays.distinct(usedWindows);
E
Erich Gamma 已提交
517 518
	}

519 520
	public addToRecentPathsList(paths: { path: string; isFile?: boolean; }[]): void {
		if (!paths || !paths.length) {
521 522 523 524
			return;
		}

		const mru = this.getRecentPathsList();
525
		paths.forEach(p => {
M
Martin Aeschlimann 已提交
526
			const { path, isFile } = p;
527

528 529 530 531 532 533 534 535 536 537 538 539
			if (isFile) {
				mru.files.unshift(path);
				mru.files = arrays.distinct(mru.files, (f) => platform.isLinux ? f : f.toLowerCase());
			} else {
				mru.folders.unshift(path);
				mru.folders = arrays.distinct(mru.folders, (f) => platform.isLinux ? f : f.toLowerCase());
			}

			// Make sure its bounded
			mru.folders = mru.folders.slice(0, WindowsManager.MAX_TOTAL_RECENT_ENTRIES);
			mru.files = mru.files.slice(0, WindowsManager.MAX_TOTAL_RECENT_ENTRIES);
		});
540 541

		this.storageService.setItem(WindowsManager.recentPathsListStorageKey, mru);
542
		this._onRecentPathsChange.fire();
543 544
	}

545 546 547 548 549 550 551 552 553 554
	public removeFromRecentPathsList(path: string): void;
	public removeFromRecentPathsList(paths: string[]): void;
	public removeFromRecentPathsList(arg1: any): void {
		let paths: string[];
		if (Array.isArray(arg1)) {
			paths = arg1;
		} else {
			paths = [arg1];
		}

555
		const mru = this.getRecentPathsList();
556
		let update = false;
557

558 559 560 561 562 563
		paths.forEach(path => {
			let index = mru.files.indexOf(path);
			if (index >= 0) {
				mru.files.splice(index, 1);
				update = true;
			}
564

565 566 567 568 569 570
			index = mru.folders.indexOf(path);
			if (index >= 0) {
				mru.folders.splice(index, 1);
				update = true;
			}
		});
571

572 573
		if (update) {
			this.storageService.setItem(WindowsManager.recentPathsListStorageKey, mru);
574
			this._onRecentPathsChange.fire();
575
		}
576 577 578 579 580
	}

	public clearRecentPathsList(): void {
		this.storageService.setItem(WindowsManager.recentPathsListStorageKey, { folders: [], files: [] });
		app.clearRecentDocuments();
581 582 583

		// Event
		this._onRecentPathsChange.fire();
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
	}

	public getRecentPathsList(workspacePath?: string, filesToOpen?: IPath[]): IRecentPathsList {
		let files: string[];
		let folders: string[];

		// Get from storage
		const storedRecents = this.storageService.getItem<IRecentPathsList>(WindowsManager.recentPathsListStorageKey);
		if (storedRecents) {
			files = storedRecents.files || [];
			folders = storedRecents.folders || [];
		} else {
			files = [];
			folders = [];
		}

		// Add currently files to open to the beginning if any
		if (filesToOpen) {
			files.unshift(...filesToOpen.map(f => f.filePath));
		}

		// Add current workspace path to beginning if set
		if (workspacePath) {
			folders.unshift(workspacePath);
		}

		// Clear those dupes
		files = arrays.distinct(files);
		folders = arrays.distinct(folders);

		return { files, folders };
	}

617
	private getWindowUserEnv(openConfig: IOpenConfiguration): platform.IProcessEnvironment {
618 619 620
		return assign({}, this.initialUserEnv, openConfig.userEnv || {});
	}

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

B
Benjamin Pasero 已提交
623
		// Reload an existing extension development host window on the same path
E
Erich Gamma 已提交
624
		// We currently do not allow more than one extension development window
B
Benjamin Pasero 已提交
625
		// on the same extension path.
626
		let res = WindowsManager.WINDOWS.filter(w => w.config && this.isPathEqual(w.config.extensionDevelopmentPath, openConfig.cli.extensionDevelopmentPath));
E
Erich Gamma 已提交
627 628
		if (res && res.length === 1) {
			this.reload(res[0], openConfig.cli);
B
Benjamin Pasero 已提交
629
			res[0].focus(); // make sure it gets focus and is restored
E
Erich Gamma 已提交
630 631 632 633

			return;
		}

634
		// Fill in previously opened workspace unless an explicit path is provided and we are not unit testing
B
Benjamin Pasero 已提交
635
		if (openConfig.cli._.length === 0 && !openConfig.cli.extensionTestsPath) {
B
Benjamin Pasero 已提交
636
			const workspaceToOpen = this.windowsState.lastPluginDevelopmentHostWindow && this.windowsState.lastPluginDevelopmentHostWindow.workspacePath;
E
Erich Gamma 已提交
637
			if (workspaceToOpen) {
B
Benjamin Pasero 已提交
638
				openConfig.cli._ = [workspaceToOpen];
E
Erich Gamma 已提交
639 640 641 642
			}
		}

		// Make sure we are not asked to open a path that is already opened
B
Benjamin Pasero 已提交
643 644
		if (openConfig.cli._.length > 0) {
			res = WindowsManager.WINDOWS.filter(w => w.openedWorkspacePath && openConfig.cli._.indexOf(w.openedWorkspacePath) >= 0);
E
Erich Gamma 已提交
645
			if (res.length) {
B
Benjamin Pasero 已提交
646
				openConfig.cli._ = [];
E
Erich Gamma 已提交
647 648 649 650
			}
		}

		// Open it
651
		this.open({ context: openConfig.context, cli: openConfig.cli, forceNewWindow: true, forceEmpty: openConfig.cli._.length === 0 });
E
Erich Gamma 已提交
652 653
	}

654
	private toConfiguration(config: IOpenConfiguration, workspacePath?: string, filesToOpen?: IPath[], filesToCreate?: IPath[], filesToDiff?: IPath[]): IWindowConfiguration {
655
		const configuration: IWindowConfiguration = mixin({}, config.cli); // inherit all properties from CLI
656
		configuration.appRoot = this.environmentService.appRoot;
B
Benjamin Pasero 已提交
657
		configuration.execPath = process.execPath;
658 659
		configuration.userEnv = this.getWindowUserEnv(config);
		configuration.isInitialStartup = config.initialStartup;
E
Erich Gamma 已提交
660 661 662
		configuration.workspacePath = workspacePath;
		configuration.filesToOpen = filesToOpen;
		configuration.filesToCreate = filesToCreate;
663
		configuration.filesToDiff = filesToDiff;
J
Johannes Rieken 已提交
664
		configuration.nodeCachedDataDir = this.environmentService.isBuilt && this.environmentService.nodeCachedDataDir;
E
Erich Gamma 已提交
665 666 667 668

		return configuration;
	}

J
Joao Moreno 已提交
669
	private toIPath(anyPath: string, ignoreFileNotFound?: boolean, gotoLineMode?: boolean): IPath {
E
Erich Gamma 已提交
670 671 672 673
		if (!anyPath) {
			return null;
		}

674
		let parsedPath: IPathWithLineAndColumn;
E
Erich Gamma 已提交
675
		if (gotoLineMode) {
J
Joao Moreno 已提交
676
			parsedPath = parseLineAndColumnAware(anyPath);
E
Erich Gamma 已提交
677 678 679
			anyPath = parsedPath.path;
		}

B
Benjamin Pasero 已提交
680
		const candidate = path.normalize(anyPath);
E
Erich Gamma 已提交
681
		try {
B
Benjamin Pasero 已提交
682
			const candidateStat = fs.statSync(candidate);
E
Erich Gamma 已提交
683 684 685 686 687
			if (candidateStat) {
				return candidateStat.isFile() ?
					{
						filePath: candidate,
						lineNumber: gotoLineMode ? parsedPath.line : void 0,
688
						columnNumber: gotoLineMode ? parsedPath.column : void 0
E
Erich Gamma 已提交
689 690 691 692
					} :
					{ workspacePath: candidate };
			}
		} catch (error) {
693 694
			this.removeFromRecentPathsList(candidate); // since file does not seem to exist anymore, remove from recent

E
Erich Gamma 已提交
695 696 697 698 699 700 701 702
			if (ignoreFileNotFound) {
				return { filePath: candidate, createFilePath: true }; // assume this is a file that does not yet exist
			}
		}

		return null;
	}

B
Benjamin Pasero 已提交
703
	private cliToPaths(cli: ParsedArgs, ignoreFileNotFound?: boolean): IPath[] {
E
Erich Gamma 已提交
704 705 706

		// Check for pass in candidate or last opened path
		let candidates: string[] = [];
B
Benjamin Pasero 已提交
707 708
		if (cli._.length > 0) {
			candidates = cli._;
E
Erich Gamma 已提交
709 710 711 712
		}

		// No path argument, check settings for what to do now
		else {
713 714 715 716
			let reopenFolders: string;
			if (this.lifecycleService.wasUpdated) {
				reopenFolders = ReopenFoldersSetting.ALL; // always reopen all folders when an update was applied
			} else {
717 718
				const windowConfig = this.configurationService.getConfiguration<IWindowSettings>('window');
				reopenFolders = (windowConfig && windowConfig.reopenFolders) || ReopenFoldersSetting.ONE;
719 720
			}

B
Benjamin Pasero 已提交
721
			const lastActiveFolder = this.windowsState.lastActiveWindow && this.windowsState.lastActiveWindow.workspacePath;
E
Erich Gamma 已提交
722 723

			// Restore all
724
			if (reopenFolders === ReopenFoldersSetting.ALL) {
B
Benjamin Pasero 已提交
725
				const lastOpenedFolders = this.windowsState.openedFolders.map(o => o.workspacePath);
E
Erich Gamma 已提交
726 727 728 729 730 731 732 733 734 735 736

				// If we have a last active folder, move it to the end
				if (lastActiveFolder) {
					lastOpenedFolders.splice(lastOpenedFolders.indexOf(lastActiveFolder), 1);
					lastOpenedFolders.push(lastActiveFolder);
				}

				candidates.push(...lastOpenedFolders);
			}

			// Restore last active
737
			else if (lastActiveFolder && (reopenFolders === ReopenFoldersSetting.ONE || reopenFolders !== ReopenFoldersSetting.NONE)) {
E
Erich Gamma 已提交
738 739 740 741
				candidates.push(lastActiveFolder);
			}
		}

742
		const iPaths = candidates.map(candidate => this.toIPath(candidate, ignoreFileNotFound, cli.goto)).filter(path => !!path);
E
Erich Gamma 已提交
743 744 745 746 747 748 749 750
		if (iPaths.length > 0) {
			return iPaths;
		}

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

751
	private openInBrowserWindow(configuration: IWindowConfiguration, forceNewWindow?: boolean, windowToUse?: VSCodeWindow, emptyWorkspaceBackupFolder?: string): VSCodeWindow {
J
Joao Moreno 已提交
752
		let vscodeWindow: VSCodeWindow;
E
Erich Gamma 已提交
753 754 755 756 757

		if (!forceNewWindow) {
			vscodeWindow = windowToUse || this.getLastActiveWindow();

			if (vscodeWindow) {
B
Benjamin Pasero 已提交
758
				vscodeWindow.focus();
E
Erich Gamma 已提交
759 760 761 762 763
			}
		}

		// New window
		if (!vscodeWindow) {
764
			const windowConfig = this.configurationService.getConfiguration<IWindowSettings>('window');
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
			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 {
				allowFullscreen = this.lifecycleService.wasUpdated || (windowConfig && windowConfig.restoreFullscreen);
			}

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

J
Johannes Rieken 已提交
782
			vscodeWindow = new VSCodeWindow({
783
				state,
784
				extensionDevelopmentPath: configuration.extensionDevelopmentPath,
785
				isExtensionTestHost: !!configuration.extensionTestsPath,
786
				titleBarStyle: windowConfig ? windowConfig.titleBarStyle : void 0
J
Johannes Rieken 已提交
787 788 789
			},
				this.logService,
				this.environmentService,
790 791
				this.configurationService,
				this.storageService
J
Johannes Rieken 已提交
792
			);
793

E
Erich Gamma 已提交
794 795 796
			WindowsManager.WINDOWS.push(vscodeWindow);

			// Window Events
797 798
			vscodeWindow.win.webContents.removeAllListeners('devtools-reload-page'); // remove built in listener so we can handle this on our own
			vscodeWindow.win.webContents.on('devtools-reload-page', () => this.reload(vscodeWindow));
799 800
			vscodeWindow.win.webContents.on('crashed', () => this.onWindowError(vscodeWindow, WindowError.CRASHED));
			vscodeWindow.win.on('unresponsive', () => this.onWindowError(vscodeWindow, WindowError.UNRESPONSIVE));
E
Erich Gamma 已提交
801 802 803 804
			vscodeWindow.win.on('close', () => this.onBeforeWindowClose(vscodeWindow));
			vscodeWindow.win.on('closed', () => this.onWindowClosed(vscodeWindow));

			// Lifecycle
J
Joao Moreno 已提交
805
			this.lifecycleService.registerWindow(vscodeWindow);
E
Erich Gamma 已提交
806 807 808 809 810 811
		}

		// Existing window
		else {

			// Some configuration things get inherited if the window is being reused and we are
B
Benjamin Pasero 已提交
812
			// in extension development host mode. These options are all development related.
B
Benjamin Pasero 已提交
813
			const currentWindowConfig = vscodeWindow.config;
A
Alex Dima 已提交
814 815
			if (!configuration.extensionDevelopmentPath && currentWindowConfig && !!currentWindowConfig.extensionDevelopmentPath) {
				configuration.extensionDevelopmentPath = currentWindowConfig.extensionDevelopmentPath;
B
Benjamin Pasero 已提交
816
				configuration.verbose = currentWindowConfig.verbose;
817
				configuration.debugBrkPluginHost = currentWindowConfig.debugBrkPluginHost;
818
				configuration.debugPluginHost = currentWindowConfig.debugPluginHost;
819
				configuration['extensions-dir'] = currentWindowConfig['extensions-dir'];
E
Erich Gamma 已提交
820 821 822 823
			}
		}

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

B
Benjamin Pasero 已提交
827 828 829 830 831
				// Register window for backups
				if (!configuration.extensionDevelopmentPath) {
					this.backupService.registerWindowForBackupsSync(vscodeWindow.id, !configuration.workspacePath, emptyWorkspaceBackupFolder, configuration.workspacePath);
				}

E
Erich Gamma 已提交
832 833 834 835
				// Load it
				vscodeWindow.load(configuration);
			}
		});
836 837

		return vscodeWindow;
E
Erich Gamma 已提交
838 839
	}

840
	private getNewWindowState(configuration: IWindowConfiguration): INewWindowState {
E
Erich Gamma 已提交
841

B
Benjamin Pasero 已提交
842
		// extension development host Window - load from stored settings if any
A
Alex Dima 已提交
843
		if (!!configuration.extensionDevelopmentPath && this.windowsState.lastPluginDevelopmentHostWindow) {
E
Erich Gamma 已提交
844 845 846 847 848
			return this.windowsState.lastPluginDevelopmentHostWindow.uiState;
		}

		// Known Folder - load from stored settings if any
		if (configuration.workspacePath) {
B
Benjamin Pasero 已提交
849
			const stateForWorkspace = this.windowsState.openedFolders.filter(o => this.isPathEqual(o.workspacePath, configuration.workspacePath)).map(o => o.uiState);
E
Erich Gamma 已提交
850 851 852 853 854 855
			if (stateForWorkspace.length) {
				return stateForWorkspace[0];
			}
		}

		// First Window
B
Benjamin Pasero 已提交
856
		const lastActive = this.getLastActiveWindow();
E
Erich Gamma 已提交
857 858 859 860 861 862 863 864 865
		if (!lastActive && this.windowsState.lastActiveWindow) {
			return this.windowsState.lastActiveWindow.uiState;
		}

		//
		// 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
866
		let displayToUse: Electron.Display;
B
Benjamin Pasero 已提交
867
		const displays = screen.getAllDisplays();
E
Erich Gamma 已提交
868 869 870 871 872 873 874 875 876 877 878

		// 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
			if (platform.isMacintosh) {
B
Benjamin Pasero 已提交
879
				const cursorPoint = screen.getCursorScreenPoint();
E
Erich Gamma 已提交
880 881 882 883 884 885 886 887 888 889 890 891 892 893
				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());
			}

			// fallback to first display
			if (!displayToUse) {
				displayToUse = displays[0];
			}
		}

894
		let state = defaultWindowState() as INewWindowState;
895 896
		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 已提交
897

898 899 900 901 902 903 904 905 906 907 908
		// 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 已提交
909 910 911 912 913 914 915
				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;
				}

916 917 918 919 920 921 922 923
				ensureNoOverlap = false;
			}
		}

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

924 925
		state.hasDefaultState = true; // flag as default state

926
		return state;
E
Erich Gamma 已提交
927 928
	}

J
Joao Moreno 已提交
929
	private ensureNoOverlap(state: ISingleWindowState): ISingleWindowState {
E
Erich Gamma 已提交
930 931 932 933
		if (WindowsManager.WINDOWS.length === 0) {
			return state;
		}

934 935
		const existingWindowBounds = WindowsManager.WINDOWS.map(win => win.getBounds());
		while (existingWindowBounds.some(b => b.x === state.x || b.y === state.y)) {
E
Erich Gamma 已提交
936 937 938 939 940 941 942
			state.x += 30;
			state.y += 30;
		}

		return state;
	}

943
	public openFileFolderPicker(forceNewWindow?: boolean): void {
944
		this.doPickAndOpen({ pickFolders: true, pickFiles: true, forceNewWindow });
945 946
	}

947 948
	public openFilePicker(forceNewWindow?: boolean, path?: string, window?: VSCodeWindow): void {
		this.doPickAndOpen({ pickFiles: true, forceNewWindow, path, window });
949 950
	}

951 952
	public openFolderPicker(forceNewWindow?: boolean, window?: VSCodeWindow): void {
		this.doPickAndOpen({ pickFolders: true, forceNewWindow, window });
E
Erich Gamma 已提交
953 954
	}

955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970
	public openAccessibilityOptions(): void {
		let win = new BrowserWindow({
			alwaysOnTop: true,
			skipTaskbar: true,
			resizable: false,
			width: 450,
			height: 300,
			show: true,
			title: nls.localize('accessibilityOptionsWindowTitle', "Accessibility Options")
		});

		win.setMenuBarVisibility(false);

		win.loadURL('chrome://accessibility');
	}

971
	private doPickAndOpen(options: INativeOpenDialogOptions): void {
972
		this.getFileOrFolderPaths(options, (paths: string[]) => {
E
Erich Gamma 已提交
973
			if (paths && paths.length) {
974
				this.open({ context: OpenContext.DIALOG, cli: this.environmentService.args, pathsToOpen: paths, forceNewWindow: options.forceNewWindow });
E
Erich Gamma 已提交
975 976 977 978
			}
		});
	}

979
	private getFileOrFolderPaths(options: INativeOpenDialogOptions, clb: (paths: string[]) => void): void {
B
Benjamin Pasero 已提交
980
		const workingDir = options.path || this.storageService.getItem<string>(WindowsManager.workingDirPickerStorageKey);
981
		const focussedWindow = options.window || this.getFocusedWindow();
E
Erich Gamma 已提交
982

B
Benjamin Pasero 已提交
983
		let pickerProperties: ('openFile' | 'openDirectory' | 'multiSelections' | 'createDirectory')[];
984
		if (options.pickFiles && options.pickFolders) {
E
Erich Gamma 已提交
985 986
			pickerProperties = ['multiSelections', 'openDirectory', 'openFile', 'createDirectory'];
		} else {
987
			pickerProperties = ['multiSelections', options.pickFolders ? 'openDirectory' : 'openFile', 'createDirectory'];
E
Erich Gamma 已提交
988 989
		}

990
		dialog.showOpenDialog(focussedWindow && focussedWindow.win, {
E
Erich Gamma 已提交
991 992
			defaultPath: workingDir,
			properties: pickerProperties
993
		}, paths => {
E
Erich Gamma 已提交
994 995 996
			if (paths && paths.length > 0) {

				// Remember path in storage for next time
J
Joao Moreno 已提交
997
				this.storageService.setItem(WindowsManager.workingDirPickerStorageKey, path.dirname(paths[0]));
E
Erich Gamma 已提交
998 999 1000 1001 1002 1003 1004 1005 1006

				// Return
				clb(paths);
			} else {
				clb(void (0));
			}
		});
	}

1007
	public focusLastActive(cli: ParsedArgs, context: OpenContext): VSCodeWindow {
B
Benjamin Pasero 已提交
1008
		const lastActive = this.getLastActiveWindow();
E
Erich Gamma 已提交
1009
		if (lastActive) {
B
Benjamin Pasero 已提交
1010
			lastActive.focus();
1011 1012

			return lastActive;
E
Erich Gamma 已提交
1013 1014 1015
		}

		// No window - open new one
1016
		this.windowsState.openedFolders = []; // make sure we do not open too much
1017
		const res = this.open({ context, cli });
1018 1019

		return res && res[0];
E
Erich Gamma 已提交
1020 1021
	}

J
Joao Moreno 已提交
1022
	public getLastActiveWindow(): VSCodeWindow {
1023
		return getLastActiveWindow(WindowsManager.WINDOWS);
E
Erich Gamma 已提交
1024 1025
	}

J
Joao Moreno 已提交
1026
	public findWindow(workspacePath: string, filePath?: string, extensionDevelopmentPath?: string): VSCodeWindow {
E
Erich Gamma 已提交
1027 1028 1029
		if (WindowsManager.WINDOWS.length) {

			// Sort the last active window to the front of the array of windows to test
B
Benjamin Pasero 已提交
1030 1031
			const windowsToTest = WindowsManager.WINDOWS.slice(0);
			const lastActiveWindow = this.getLastActiveWindow();
E
Erich Gamma 已提交
1032 1033 1034 1035 1036 1037
			if (lastActiveWindow) {
				windowsToTest.splice(windowsToTest.indexOf(lastActiveWindow), 1);
				windowsToTest.unshift(lastActiveWindow);
			}

			// Find it
1038
			const res = windowsToTest.filter(w => {
E
Erich Gamma 已提交
1039 1040

				// match on workspace
1041
				if (typeof w.openedWorkspacePath === 'string' && (this.isPathEqual(w.openedWorkspacePath, workspacePath))) {
E
Erich Gamma 已提交
1042 1043 1044 1045
					return true;
				}

				// match on file
B
Benjamin Pasero 已提交
1046
				if (typeof w.openedFilePath === 'string' && this.isPathEqual(w.openedFilePath, filePath)) {
E
Erich Gamma 已提交
1047 1048 1049 1050 1051 1052 1053 1054
					return true;
				}

				// match on file path
				if (typeof w.openedWorkspacePath === 'string' && filePath && paths.isEqualOrParent(filePath, w.openedWorkspacePath)) {
					return true;
				}

1055 1056 1057 1058 1059
				// match on extension development path
				if (typeof extensionDevelopmentPath === 'string' && w.extensionDevelopmentPath === extensionDevelopmentPath) {
					return true;
				}

E
Erich Gamma 已提交
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
				return false;
			});

			if (res && res.length) {
				return res[0];
			}
		}

		return null;
	}

1071 1072
	public openNewWindow(context: OpenContext): void {
		this.open({ context, cli: this.environmentService.args, forceNewWindow: true, forceEmpty: true });
E
Erich Gamma 已提交
1073 1074 1075 1076 1077 1078
	}

	public sendToFocused(channel: string, ...args: any[]): void {
		const focusedWindow = this.getFocusedWindow() || this.getLastActiveWindow();

		if (focusedWindow) {
1079
			focusedWindow.sendWhenReady(channel, ...args);
E
Erich Gamma 已提交
1080 1081 1082 1083
		}
	}

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

1089
			w.sendWhenReady(channel, payload);
E
Erich Gamma 已提交
1090 1091 1092
		});
	}

J
Joao Moreno 已提交
1093
	public getFocusedWindow(): VSCodeWindow {
B
Benjamin Pasero 已提交
1094
		const win = BrowserWindow.getFocusedWindow();
E
Erich Gamma 已提交
1095 1096 1097 1098 1099 1100 1101
		if (win) {
			return this.getWindowById(win.id);
		}

		return null;
	}

J
Joao Moreno 已提交
1102
	public getWindowById(windowId: number): VSCodeWindow {
1103
		const res = WindowsManager.WINDOWS.filter(w => w.id === windowId);
E
Erich Gamma 已提交
1104 1105 1106 1107 1108 1109 1110
		if (res && res.length === 1) {
			return res[0];
		}

		return null;
	}

J
Joao Moreno 已提交
1111
	public getWindows(): VSCodeWindow[] {
E
Erich Gamma 已提交
1112 1113 1114 1115 1116 1117 1118
		return WindowsManager.WINDOWS;
	}

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

J
Joao Moreno 已提交
1119
	private onWindowError(vscodeWindow: VSCodeWindow, error: WindowError): void {
E
Erich Gamma 已提交
1120 1121 1122 1123
		console.error(error === WindowError.CRASHED ? '[VS Code]: render process crashed!' : '[VS Code]: detected unresponsive');

		// Unresponsive
		if (error === WindowError.UNRESPONSIVE) {
1124
			dialog.showMessageBox(vscodeWindow.win, {
B
Benjamin Pasero 已提交
1125
				title: product.nameLong,
E
Erich Gamma 已提交
1126
				type: 'warning',
B
Benjamin Pasero 已提交
1127
				buttons: [nls.localize('reopen', "Reopen"), nls.localize('wait', "Keep Waiting"), nls.localize('close', "Close")],
1128
				message: nls.localize('appStalled', "The window is no longer responding"),
B
Benjamin Pasero 已提交
1129
				detail: nls.localize('appStalledDetail', "You can reopen or close the window or keep waiting."),
E
Erich Gamma 已提交
1130
				noLink: true
1131
			}, result => {
E
Erich Gamma 已提交
1132
				if (result === 0) {
1133 1134
					vscodeWindow.reload();
				} else if (result === 2) {
1135
					this.onBeforeWindowClose(vscodeWindow); // 'close' event will not be fired on destroy(), so run it manually
1136
					vscodeWindow.win.destroy(); // make sure to destroy the window as it is unresponsive
E
Erich Gamma 已提交
1137 1138 1139 1140 1141 1142
				}
			});
		}

		// Crashed
		else {
1143
			dialog.showMessageBox(vscodeWindow.win, {
B
Benjamin Pasero 已提交
1144
				title: product.nameLong,
E
Erich Gamma 已提交
1145
				type: 'warning',
B
Benjamin Pasero 已提交
1146
				buttons: [nls.localize('reopen', "Reopen"), nls.localize('close', "Close")],
1147
				message: nls.localize('appCrashed', "The window has crashed"),
B
Benjamin Pasero 已提交
1148
				detail: nls.localize('appCrashedDetail', "We are sorry for the inconvenience! You can reopen the window to continue where you left off."),
E
Erich Gamma 已提交
1149
				noLink: true
1150
			}, result => {
1151 1152 1153
				if (result === 0) {
					vscodeWindow.reload();
				} else if (result === 1) {
1154
					this.onBeforeWindowClose(vscodeWindow); // 'close' event will not be fired on destroy(), so run it manually
1155 1156
					vscodeWindow.win.destroy(); // make sure to destroy the window as it has crashed
				}
E
Erich Gamma 已提交
1157 1158 1159 1160
			});
		}
	}

J
Joao Moreno 已提交
1161 1162
	private onBeforeWindowClose(win: VSCodeWindow): void {
		if (win.readyState !== ReadyState.READY) {
E
Erich Gamma 已提交
1163 1164 1165 1166
			return; // only persist windows that are fully loaded
		}

		// On Window close, update our stored state of this window
B
Benjamin Pasero 已提交
1167
		const state: IWindowState = { workspacePath: win.openedWorkspacePath, uiState: win.serializeWindowState() };
1168 1169 1170 1171
		if (win.isExtensionDevelopmentHost) {
			if (!win.isExtensionTestHost) {
				this.windowsState.lastPluginDevelopmentHostWindow = state; // do not let test run window state overwrite our extension development state
			}
E
Erich Gamma 已提交
1172 1173 1174 1175
		} else {
			this.windowsState.lastActiveWindow = state;

			this.windowsState.openedFolders.forEach(o => {
B
Benjamin Pasero 已提交
1176
				if (this.isPathEqual(o.workspacePath, win.openedWorkspacePath)) {
E
Erich Gamma 已提交
1177 1178 1179 1180 1181 1182
					o.uiState = state.uiState;
				}
			});
		}
	}

J
Joao Moreno 已提交
1183
	private onWindowClosed(win: VSCodeWindow): void {
E
Erich Gamma 已提交
1184 1185 1186 1187 1188

		// Tell window
		win.dispose();

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

		// Emit
1193
		this._onWindowClose.fire(win.id);
E
Erich Gamma 已提交
1194
	}
B
Benjamin Pasero 已提交
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218

	private isPathEqual(pathA: string, pathB: string): boolean {
		if (pathA === pathB) {
			return true;
		}

		if (!pathA || !pathB) {
			return false;
		}

		pathA = path.normalize(pathA);
		pathB = path.normalize(pathB);

		if (pathA === pathB) {
			return true;
		}

		if (!platform.isLinux) {
			pathA = pathA.toLowerCase();
			pathB = pathB.toLowerCase();
		}

		return pathA === pathB;
	}
J
Joao Moreno 已提交
1219

B
Benjamin Pasero 已提交
1220
	private updateWindowsJumpList(): void {
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 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 1276 1277 1278 1279 1280
		if (!platform.isWindows) {
			return; // only on windows
		}

		const jumpList: Electron.JumpListCategory[] = [];

		// Tasks
		jumpList.push({
			type: 'tasks',
			items: [
				{
					type: 'task',
					title: nls.localize('newWindow', "New Window"),
					description: nls.localize('newWindowDesc', "Opens a new window"),
					program: process.execPath,
					args: '-n', // force new window
					iconPath: process.execPath,
					iconIndex: 0
				}
			]
		});

		// Recent Folders
		if (this.getRecentPathsList().folders.length > 0) {

			// The user might have meanwhile removed items from the jump list and we have to respect that
			// so we need to update our list of recent paths with the choice of the user to not add them again
			// Also: Windows will not show our custom category at all if there is any entry which was removed
			// by the user! See https://github.com/Microsoft/vscode/issues/15052
			this.removeFromRecentPathsList(app.getJumpListSettings().removedItems.map(r => trim(r.args, '"')));

			// Add entries
			jumpList.push({
				type: 'custom',
				name: nls.localize('recentFolders', "Recent Folders"),
				items: this.getRecentPathsList().folders.slice(0, 7 /* limit number of entries here */).map(folder => {
					return <Electron.JumpListItem>{
						type: 'task',
						title: path.basename(folder) || folder, // use the base name to show shorter entries in the list
						description: nls.localize('folderDesc', "{0} {1}", path.basename(folder), getPathLabel(path.dirname(folder))),
						program: process.execPath,
						args: `"${folder}"`, // open folder (use quotes to support paths with whitespaces)
						iconPath: 'explorer.exe', // simulate folder icon
						iconIndex: 0
					};
				}).filter(i => !!i)
			});
		}

		// Recent
		jumpList.push({
			type: 'recent' // this enables to show files in the "recent" category
		});

		try {
			app.setJumpList(jumpList);
		} catch (error) {
			this.logService.log('#setJumpList', error); // since setJumpList is relatively new API, make sure to guard for errors
		}
	}
1281 1282 1283 1284 1285 1286

	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.
		const vscodeWindow = this.getFocusedWindow();
1287
		if (vscodeWindow && vscodeWindow.isExtensionDevelopmentHost && this.getWindowCount() > 1) {
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
			vscodeWindow.win.close();
		}

		// Otherwise: normal quit
		else {
			setTimeout(() => {
				app.quit();
			}, 10 /* delay to unwind callback stack (IPC) */);
		}
	}
1298
}