windows.ts 41.9 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';
B
Benjamin Pasero 已提交
20
import { IPath, VSCodeWindow, IWindowConfiguration, IWindowState as ISingleWindowState, defaultWindowState, ReadyState } 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';
29
import CommonEvent, { Emitter } from 'vs/base/common/event';
30
import product from 'vs/platform/node/product';
E
Erich Gamma 已提交
31 32 33 34 35 36 37

enum WindowError {
	UNRESPONSIVE,
	CRASHED
}

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

interface IWindowState {
	workspacePath?: string;
J
Joao Moreno 已提交
51
	uiState: ISingleWindowState;
E
Erich Gamma 已提交
52 53 54 55 56 57 58 59
}

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

60
export interface IRecentPathsList {
E
Erich Gamma 已提交
61 62 63 64
	folders: string[];
	files: string[];
}

65 66 67
interface INativeOpenDialogOptions {
	pickFolders?: boolean;
	pickFiles?: boolean;
68 69
	path?: string;
	forceNewWindow?: boolean;
70
	window?: VSCodeWindow;
71 72
}

73 74 75 76 77 78
const ReopenFoldersSetting = {
	ALL: 'all',
	ONE: 'one',
	NONE: 'none'
};

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

J
Joao Moreno 已提交
81
export interface IWindowsMainService {
82
	_serviceBrand: any;
J
Joao Moreno 已提交
83 84

	// events
85 86
	onWindowReady: CommonEvent<VSCodeWindow>;
	onWindowClose: CommonEvent<number>;
B
Benjamin Pasero 已提交
87
	onPathsOpen: CommonEvent<IPath[]>;
88
	onRecentPathsChange: CommonEvent<void>;
J
Joao Moreno 已提交
89 90

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

J
Joao Moreno 已提交
118
export class WindowsManager implements IWindowsMainService {
J
Joao Moreno 已提交
119

120
	_serviceBrand: any;
E
Erich Gamma 已提交
121

122
	private static MAX_TOTAL_RECENT_ENTRIES = 100;
123

124
	private static recentPathsListStorageKey = 'openedPathsList';
125
	private static workingDirPickerStorageKey = 'pickerWorkingDir';
E
Erich Gamma 已提交
126 127
	private static windowsStateStorageKey = 'windowsState';

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

130
	private initialUserEnv: platform.IProcessEnvironment;
E
Erich Gamma 已提交
131 132
	private windowsState: IWindowsState;

133 134 135 136 137 138 139 140 141
	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;

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

J
Joao Moreno 已提交
145 146
	constructor(
		@ILogService private logService: ILogService,
J
Joao Moreno 已提交
147
		@IStorageService private storageService: IStorageService,
148
		@IEnvironmentService private environmentService: IEnvironmentService,
B
Benjamin Pasero 已提交
149
		@ILifecycleService private lifecycleService: ILifecycleService,
150
		@IBackupMainService private backupService: IBackupMainService,
B
Benjamin Pasero 已提交
151
		@IConfigurationService private configurationService: IConfigurationService
152
	) { }
J
Joao Moreno 已提交
153

154
	public ready(initialUserEnv: platform.IProcessEnvironment): void {
E
Erich Gamma 已提交
155 156
		this.registerListeners();

157
		this.initialUserEnv = initialUserEnv;
J
Joao Moreno 已提交
158
		this.windowsState = this.storageService.getItem<IWindowsState>(WindowsManager.windowsStateStorageKey) || { openedFolders: [] };
159 160

		this.updateWindowsJumpList();
E
Erich Gamma 已提交
161 162 163
	}

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

G
Giorgos Retsinas 已提交
167
			// Mac only event: open new window when we get activated
E
Erich Gamma 已提交
168
			if (!hasVisibleWindows) {
G
Giorgos Retsinas 已提交
169
				this.openNewWindow();
E
Erich Gamma 已提交
170 171 172 173 174 175
			}
		});

		let macOpenFiles: string[] = [];
		let runningTimeout: number = null;
		app.on('open-file', (event: Event, path: string) => {
J
Joao Moreno 已提交
176
			this.logService.log('App#open-file: ', path);
E
Erich Gamma 已提交
177 178 179 180 181 182 183 184 185 186 187 188 189
			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(() => {
190
				this.open({ cli: this.environmentService.args, pathsToOpen: macOpenFiles, preferNewWindow: true /* dropping on the dock prefers to open in a new window */ });
E
Erich Gamma 已提交
191 192 193 194 195
				macOpenFiles = [];
				runningTimeout = null;
			}, 100);
		});

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

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

				// Event
204
				this._onWindowReady.fire(win);
E
Erich Gamma 已提交
205 206 207
			}
		});

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

212 213 214 215
				// Handle specific events on main side
				this.onBroadcast(broadcast.channel, broadcast.payload);

				// Send to windows
216
				if (target) {
B
Benjamin Pasero 已提交
217
					const otherWindowsWithTarget = WindowsManager.WINDOWS.filter(w => w.id !== windowId && typeof w.openedWorkspacePath === 'string');
218 219 220 221 222
					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) {
223 224 225 226 227
						targetWindow.send('vscode:broadcast', broadcast);
					}
				} else {
					this.sendToAll('vscode:broadcast', broadcast, [windowId]);
				}
E
Erich Gamma 已提交
228
			}
229 230
		});

J
Joao Moreno 已提交
231
		this.lifecycleService.onBeforeQuit(() => {
E
Erich Gamma 已提交
232 233 234 235 236 237 238 239

			// 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
240
			this.windowsState.openedFolders = WindowsManager.WINDOWS.filter(w => w.readyState === ReadyState.READY && !!w.openedWorkspacePath && !w.isExtensionDevelopmentHost).map(w => {
E
Erich Gamma 已提交
241 242 243
				return <IWindowState>{
					workspacePath: w.openedWorkspacePath,
					uiState: w.serializeWindowState()
B
Benjamin Pasero 已提交
244
				};
E
Erich Gamma 已提交
245 246 247 248
			});
		});

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

252 253
		// Update jump list when recent paths change
		this.onRecentPathsChange(() => this.updateWindowsJumpList());
E
Erich Gamma 已提交
254 255
	}

256 257 258
	private onBroadcast(event: string, payload: any): void {

		// Theme changes
259 260
		if (event === 'vscode:changeColorTheme' && typeof payload === 'string') {
			this.storageService.setItem(VSCodeWindow.colorThemeStorageKey, payload);
261 262 263
		}
	}

B
Benjamin Pasero 已提交
264
	public reload(win: VSCodeWindow, cli?: ParsedArgs): void {
E
Erich Gamma 已提交
265 266

		// Only reload when the window has not vetoed this
267
		this.lifecycleService.unload(win, UnloadReason.RELOAD).done(veto => {
E
Erich Gamma 已提交
268 269 270 271 272 273
			if (!veto) {
				win.reload(cli);
			}
		});
	}

J
Joao Moreno 已提交
274 275
	public open(openConfig: IOpenConfiguration): VSCodeWindow[] {
		let iPathsToOpen: IPath[];
B
Benjamin Pasero 已提交
276
		const usedWindows: VSCodeWindow[] = [];
E
Erich Gamma 已提交
277 278 279

		// Find paths from provided paths if any
		if (openConfig.pathsToOpen && openConfig.pathsToOpen.length > 0) {
280
			iPathsToOpen = openConfig.pathsToOpen.map(pathToOpen => {
B
Benjamin Pasero 已提交
281
				const iPath = this.toIPath(pathToOpen, false, openConfig.cli && openConfig.cli.goto);
E
Erich Gamma 已提交
282 283 284

				// Warn if the requested path to open does not exist
				if (!iPath) {
B
Benjamin Pasero 已提交
285
					const options: Electron.ShowMessageBoxOptions = {
B
Benjamin Pasero 已提交
286
						title: product.nameLong,
E
Erich Gamma 已提交
287 288 289 290 291 292 293
						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 已提交
294
					const activeWindow = BrowserWindow.getFocusedWindow();
E
Erich Gamma 已提交
295
					if (activeWindow) {
296
						dialog.showMessageBox(activeWindow, options);
E
Erich Gamma 已提交
297
					} else {
298
						dialog.showMessageBox(options);
E
Erich Gamma 已提交
299 300 301 302 303 304 305 306 307 308
					}
				}

				return iPath;
			});

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

			if (iPathsToOpen.length === 0) {
309
				return null; // indicate to outside that open failed
E
Erich Gamma 已提交
310 311 312 313 314 315 316 317 318 319
			}
		}

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

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

324
		let foldersToOpen = arrays.distinct(iPathsToOpen.filter(iPath => iPath.workspacePath && !iPath.filePath).map(iPath => iPath.workspacePath), folder => platform.isLinux ? folder : folder.toLowerCase()); // prevent duplicates
325
		let foldersToRestore = (openConfig.initialStartup && !openConfig.cli.extensionDevelopmentPath) ? this.backupService.getWorkspaceBackupPaths() : [];
326 327 328
		let filesToOpen: IPath[] = [];
		let filesToDiff: IPath[] = [];
		let emptyToOpen = iPathsToOpen.filter(iPath => !iPath.workspacePath && !iPath.filePath);
329
		let emptyToRestore = (openConfig.initialStartup && !openConfig.cli.extensionDevelopmentPath) ? this.backupService.getEmptyWorkspaceBackupPaths() : [];
330 331 332 333 334 335 336 337 338 339 340
		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
			}

341 342 343
			foldersToOpen = []; 	// diff is always in empty workspace
			foldersToRestore = [];	// diff is always in empty workspace
			filesToCreate = []; 	// diff ignores other files that do not exist
344 345 346 347
		} else {
			filesToOpen = candidates;
		}

348 349
		let openInNewWindow = openConfig.preferNewWindow || openConfig.forceNewWindow;

350
		// Handle files to open/diff or to create when we dont open a folder
351
		if (!foldersToOpen.length && (filesToOpen.length > 0 || filesToCreate.length > 0 || filesToDiff.length > 0)) {
E
Erich Gamma 已提交
352

B
Benjamin Pasero 已提交
353
			// const the user settings override how files are open in a new window or same window unless we are forced
354 355 356 357 358
			let openFilesInNewWindow: boolean;
			if (openConfig.forceNewWindow) {
				openFilesInNewWindow = true;
			} else {
				openFilesInNewWindow = openConfig.preferNewWindow;
359
				if (openFilesInNewWindow && !openConfig.cli.extensionDevelopmentPath) { // can be overriden via settings (not for PDE though!)
360 361 362 363
					const windowConfig = this.configurationService.getConfiguration<IWindowSettings>('window');
					if (windowConfig && !windowConfig.openFilesInNewWindow) {
						openFilesInNewWindow = false; // do not open in new window if user configured this explicitly
					}
364
				}
E
Erich Gamma 已提交
365 366 367
			}

			// Open Files in last instance if any and flag tells us so
B
Benjamin Pasero 已提交
368
			const lastActiveWindow = this.getLastActiveWindow();
E
Erich Gamma 已提交
369
			if (!openFilesInNewWindow && lastActiveWindow) {
B
Benjamin Pasero 已提交
370
				lastActiveWindow.focus();
371
				lastActiveWindow.ready().then(readyWindow => {
372
					readyWindow.send('vscode:openFiles', { filesToOpen, filesToCreate, filesToDiff });
E
Erich Gamma 已提交
373
				});
374 375

				usedWindows.push(lastActiveWindow);
E
Erich Gamma 已提交
376 377 378 379
			}

			// Otherwise open instance with files
			else {
380
				const configuration = this.toConfiguration(openConfig, null, filesToOpen, filesToCreate, filesToDiff);
B
Benjamin Pasero 已提交
381
				const browserWindow = this.openInBrowserWindow(configuration, true /* new window */);
382
				usedWindows.push(browserWindow);
E
Erich Gamma 已提交
383

384
				openInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
385
			}
386 387 388 389 390

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

393 394 395
		// 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 已提交
396 397

			// Check for existing instances
398
			const windowsOnWorkspacePath = arrays.coalesce(allFoldersToOpen.map(folderToOpen => this.findWindow(folderToOpen)));
E
Erich Gamma 已提交
399
			if (windowsOnWorkspacePath.length > 0) {
B
Benjamin Pasero 已提交
400
				const browserWindow = windowsOnWorkspacePath[0];
401
				browserWindow.focus(); // just focus one of them
402
				browserWindow.ready().then(readyWindow => {
403
					readyWindow.send('vscode:openFiles', { filesToOpen, filesToCreate, filesToDiff });
E
Erich Gamma 已提交
404 405
				});

406 407
				usedWindows.push(browserWindow);

E
Erich Gamma 已提交
408 409 410
				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
411
				filesToDiff = [];
E
Erich Gamma 已提交
412

413
				openInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
414 415 416
			}

			// Open remaining ones
417 418
			allFoldersToOpen.forEach(folderToOpen => {
				if (windowsOnWorkspacePath.some(win => this.isPathEqual(win.openedWorkspacePath, folderToOpen))) {
E
Erich Gamma 已提交
419 420 421
					return; // ignore folders that are already open
				}

422
				const configuration = this.toConfiguration(openConfig, folderToOpen, filesToOpen, filesToCreate, filesToDiff);
B
Benjamin Pasero 已提交
423
				const browserWindow = this.openInBrowserWindow(configuration, openInNewWindow, openInNewWindow ? void 0 : openConfig.windowToUse);
424
				usedWindows.push(browserWindow);
E
Erich Gamma 已提交
425 426 427 428

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

431
				openInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
432 433 434 435
			});
		}

		// Handle empty
436
		if (emptyToRestore.length > 0) {
437
			emptyToRestore.forEach(emptyWorkspaceBackupFolder => {
B
Benjamin Pasero 已提交
438
				const configuration = this.toConfiguration(openConfig);
439
				const browserWindow = this.openInBrowserWindow(configuration, true /* new window */, null, emptyWorkspaceBackupFolder);
440 441 442 443 444
				usedWindows.push(browserWindow);

				openInNewWindow = true; // any other folders to open must open in new window then
			});
		}
B
Benjamin Pasero 已提交
445

446 447
		// Only open empty if no empty workspaces were restored
		else if (emptyToOpen.length > 0) {
E
Erich Gamma 已提交
448
			emptyToOpen.forEach(() => {
449
				const configuration = this.toConfiguration(openConfig);
B
Benjamin Pasero 已提交
450
				const browserWindow = this.openInBrowserWindow(configuration, openInNewWindow, openInNewWindow ? void 0 : openConfig.windowToUse);
451
				usedWindows.push(browserWindow);
E
Erich Gamma 已提交
452

453
				openInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
454 455 456
			});
		}

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

462 463 464
			iPathsToOpen.forEach(iPath => {
				if (iPath.filePath || iPath.workspacePath) {
					app.addRecentDocument(iPath.filePath || iPath.workspacePath);
465
					recentPaths.push({ path: iPath.filePath || iPath.workspacePath, isFile: !!iPath.filePath });
466 467
				}
			});
E
Erich Gamma 已提交
468

469 470 471 472
			if (recentPaths.length) {
				this.addToRecentPathsList(recentPaths);
			}
		}
E
Erich Gamma 已提交
473

474
		// Emit events
B
Benjamin Pasero 已提交
475
		this._onPathsOpen.fire(iPathsToOpen);
476

477
		return arrays.distinct(usedWindows);
E
Erich Gamma 已提交
478 479
	}

480 481
	public addToRecentPathsList(paths: { path: string; isFile?: boolean; }[]): void {
		if (!paths || !paths.length) {
482 483 484 485
			return;
		}

		const mru = this.getRecentPathsList();
486 487
		paths.forEach(p => {
			const {path, isFile} = p;
488

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

		this.storageService.setItem(WindowsManager.recentPathsListStorageKey, mru);
503
		this._onRecentPathsChange.fire();
504 505
	}

506 507 508 509 510 511 512 513 514 515
	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];
		}

516
		const mru = this.getRecentPathsList();
517
		let update = false;
518

519 520 521 522 523 524
		paths.forEach(path => {
			let index = mru.files.indexOf(path);
			if (index >= 0) {
				mru.files.splice(index, 1);
				update = true;
			}
525

526 527 528 529 530 531
			index = mru.folders.indexOf(path);
			if (index >= 0) {
				mru.folders.splice(index, 1);
				update = true;
			}
		});
532

533 534
		if (update) {
			this.storageService.setItem(WindowsManager.recentPathsListStorageKey, mru);
535
			this._onRecentPathsChange.fire();
536
		}
537 538 539 540 541
	}

	public clearRecentPathsList(): void {
		this.storageService.setItem(WindowsManager.recentPathsListStorageKey, { folders: [], files: [] });
		app.clearRecentDocuments();
542 543 544

		// Event
		this._onRecentPathsChange.fire();
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
	}

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

578
	private getWindowUserEnv(openConfig: IOpenConfiguration): platform.IProcessEnvironment {
579 580 581
		return assign({}, this.initialUserEnv, openConfig.userEnv || {});
	}

E
Erich Gamma 已提交
582 583 584 585 586
	public openPluginDevelopmentHostWindow(openConfig: IOpenConfiguration): void {

		// Reload an existing plugin development host window on the same path
		// We currently do not allow more than one extension development window
		// on the same plugin path.
587
		let res = WindowsManager.WINDOWS.filter(w => w.config && this.isPathEqual(w.config.extensionDevelopmentPath, openConfig.cli.extensionDevelopmentPath));
E
Erich Gamma 已提交
588 589
		if (res && res.length === 1) {
			this.reload(res[0], openConfig.cli);
B
Benjamin Pasero 已提交
590
			res[0].focus(); // make sure it gets focus and is restored
E
Erich Gamma 已提交
591 592 593 594

			return;
		}

595
		// Fill in previously opened workspace unless an explicit path is provided and we are not unit testing
B
Benjamin Pasero 已提交
596
		if (openConfig.cli._.length === 0 && !openConfig.cli.extensionTestsPath) {
B
Benjamin Pasero 已提交
597
			const workspaceToOpen = this.windowsState.lastPluginDevelopmentHostWindow && this.windowsState.lastPluginDevelopmentHostWindow.workspacePath;
E
Erich Gamma 已提交
598
			if (workspaceToOpen) {
B
Benjamin Pasero 已提交
599
				openConfig.cli._ = [workspaceToOpen];
E
Erich Gamma 已提交
600 601 602 603
			}
		}

		// Make sure we are not asked to open a path that is already opened
B
Benjamin Pasero 已提交
604 605
		if (openConfig.cli._.length > 0) {
			res = WindowsManager.WINDOWS.filter(w => w.openedWorkspacePath && openConfig.cli._.indexOf(w.openedWorkspacePath) >= 0);
E
Erich Gamma 已提交
606
			if (res.length) {
B
Benjamin Pasero 已提交
607
				openConfig.cli._ = [];
E
Erich Gamma 已提交
608 609 610 611
			}
		}

		// Open it
B
Benjamin Pasero 已提交
612
		this.open({ cli: openConfig.cli, forceNewWindow: true, forceEmpty: openConfig.cli._.length === 0 });
E
Erich Gamma 已提交
613 614
	}

615
	private toConfiguration(config: IOpenConfiguration, workspacePath?: string, filesToOpen?: IPath[], filesToCreate?: IPath[], filesToDiff?: IPath[]): IWindowConfiguration {
616
		const configuration: IWindowConfiguration = mixin({}, config.cli); // inherit all properties from CLI
617
		configuration.appRoot = this.environmentService.appRoot;
B
Benjamin Pasero 已提交
618
		configuration.execPath = process.execPath;
619 620
		configuration.userEnv = this.getWindowUserEnv(config);
		configuration.isInitialStartup = config.initialStartup;
E
Erich Gamma 已提交
621 622 623
		configuration.workspacePath = workspacePath;
		configuration.filesToOpen = filesToOpen;
		configuration.filesToCreate = filesToCreate;
624
		configuration.filesToDiff = filesToDiff;
J
Johannes Rieken 已提交
625
		configuration.nodeCachedDataDir = this.environmentService.isBuilt && this.environmentService.nodeCachedDataDir;
E
Erich Gamma 已提交
626 627 628 629

		return configuration;
	}

J
Joao Moreno 已提交
630
	private toIPath(anyPath: string, ignoreFileNotFound?: boolean, gotoLineMode?: boolean): IPath {
E
Erich Gamma 已提交
631 632 633 634
		if (!anyPath) {
			return null;
		}

635
		let parsedPath: IPathWithLineAndColumn;
E
Erich Gamma 已提交
636
		if (gotoLineMode) {
J
Joao Moreno 已提交
637
			parsedPath = parseLineAndColumnAware(anyPath);
E
Erich Gamma 已提交
638 639 640
			anyPath = parsedPath.path;
		}

B
Benjamin Pasero 已提交
641
		const candidate = path.normalize(anyPath);
E
Erich Gamma 已提交
642
		try {
B
Benjamin Pasero 已提交
643
			const candidateStat = fs.statSync(candidate);
E
Erich Gamma 已提交
644 645 646 647 648
			if (candidateStat) {
				return candidateStat.isFile() ?
					{
						filePath: candidate,
						lineNumber: gotoLineMode ? parsedPath.line : void 0,
649
						columnNumber: gotoLineMode ? parsedPath.column : void 0
E
Erich Gamma 已提交
650 651 652 653
					} :
					{ workspacePath: candidate };
			}
		} catch (error) {
654 655
			this.removeFromRecentPathsList(candidate); // since file does not seem to exist anymore, remove from recent

E
Erich Gamma 已提交
656 657 658 659 660 661 662 663
			if (ignoreFileNotFound) {
				return { filePath: candidate, createFilePath: true }; // assume this is a file that does not yet exist
			}
		}

		return null;
	}

B
Benjamin Pasero 已提交
664
	private cliToPaths(cli: ParsedArgs, ignoreFileNotFound?: boolean): IPath[] {
E
Erich Gamma 已提交
665 666 667

		// Check for pass in candidate or last opened path
		let candidates: string[] = [];
B
Benjamin Pasero 已提交
668 669
		if (cli._.length > 0) {
			candidates = cli._;
E
Erich Gamma 已提交
670 671 672 673
		}

		// No path argument, check settings for what to do now
		else {
674 675 676 677
			let reopenFolders: string;
			if (this.lifecycleService.wasUpdated) {
				reopenFolders = ReopenFoldersSetting.ALL; // always reopen all folders when an update was applied
			} else {
678 679
				const windowConfig = this.configurationService.getConfiguration<IWindowSettings>('window');
				reopenFolders = (windowConfig && windowConfig.reopenFolders) || ReopenFoldersSetting.ONE;
680 681
			}

B
Benjamin Pasero 已提交
682
			const lastActiveFolder = this.windowsState.lastActiveWindow && this.windowsState.lastActiveWindow.workspacePath;
E
Erich Gamma 已提交
683 684

			// Restore all
685
			if (reopenFolders === ReopenFoldersSetting.ALL) {
B
Benjamin Pasero 已提交
686
				const lastOpenedFolders = this.windowsState.openedFolders.map(o => o.workspacePath);
E
Erich Gamma 已提交
687 688 689 690 691 692 693 694 695 696 697

				// 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
698
			else if (lastActiveFolder && (reopenFolders === ReopenFoldersSetting.ONE || reopenFolders !== ReopenFoldersSetting.NONE)) {
E
Erich Gamma 已提交
699 700 701 702
				candidates.push(lastActiveFolder);
			}
		}

703
		const iPaths = candidates.map(candidate => this.toIPath(candidate, ignoreFileNotFound, cli.goto)).filter(path => !!path);
E
Erich Gamma 已提交
704 705 706 707 708 709 710 711
		if (iPaths.length > 0) {
			return iPaths;
		}

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

712
	private openInBrowserWindow(configuration: IWindowConfiguration, forceNewWindow?: boolean, windowToUse?: VSCodeWindow, emptyWorkspaceBackupFolder?: string): VSCodeWindow {
J
Joao Moreno 已提交
713
		let vscodeWindow: VSCodeWindow;
E
Erich Gamma 已提交
714 715 716 717 718

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

			if (vscodeWindow) {
B
Benjamin Pasero 已提交
719
				vscodeWindow.focus();
E
Erich Gamma 已提交
720 721 722 723 724
			}
		}

		// New window
		if (!vscodeWindow) {
725 726
			const windowConfig = this.configurationService.getConfiguration<IWindowSettings>('window');

J
Johannes Rieken 已提交
727
			vscodeWindow = new VSCodeWindow({
728
				state: this.getNewWindowState(configuration),
729
				extensionDevelopmentPath: configuration.extensionDevelopmentPath,
730
				isExtensionTestHost: !!configuration.extensionTestsPath,
B
Benjamin Pasero 已提交
731
				allowFullscreen: this.lifecycleService.wasUpdated || (windowConfig && windowConfig.restoreFullscreen),
732
				titleBarStyle: windowConfig ? windowConfig.titleBarStyle : void 0
J
Johannes Rieken 已提交
733 734 735 736 737 738
			},
				this.logService,
				this.environmentService,
				this.configurationService,
				this.storageService
			);
739

E
Erich Gamma 已提交
740 741 742
			WindowsManager.WINDOWS.push(vscodeWindow);

			// Window Events
743 744
			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));
745 746
			vscodeWindow.win.webContents.on('crashed', () => this.onWindowError(vscodeWindow, WindowError.CRASHED));
			vscodeWindow.win.on('unresponsive', () => this.onWindowError(vscodeWindow, WindowError.UNRESPONSIVE));
E
Erich Gamma 已提交
747 748 749 750
			vscodeWindow.win.on('close', () => this.onBeforeWindowClose(vscodeWindow));
			vscodeWindow.win.on('closed', () => this.onWindowClosed(vscodeWindow));

			// Lifecycle
J
Joao Moreno 已提交
751
			this.lifecycleService.registerWindow(vscodeWindow);
E
Erich Gamma 已提交
752 753 754 755 756 757 758
		}

		// Existing window
		else {

			// Some configuration things get inherited if the window is being reused and we are
			// in plugin development host mode. These options are all development related.
B
Benjamin Pasero 已提交
759
			const currentWindowConfig = vscodeWindow.config;
A
Alex Dima 已提交
760 761
			if (!configuration.extensionDevelopmentPath && currentWindowConfig && !!currentWindowConfig.extensionDevelopmentPath) {
				configuration.extensionDevelopmentPath = currentWindowConfig.extensionDevelopmentPath;
B
Benjamin Pasero 已提交
762
				configuration.verbose = currentWindowConfig.verbose;
763
				configuration.debugBrkPluginHost = currentWindowConfig.debugBrkPluginHost;
764
				configuration.debugPluginHost = currentWindowConfig.debugPluginHost;
765
				configuration['extensions-dir'] = currentWindowConfig['extensions-dir'];
E
Erich Gamma 已提交
766 767 768 769
			}
		}

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

B
Benjamin Pasero 已提交
773 774 775 776 777
				// Register window for backups
				if (!configuration.extensionDevelopmentPath) {
					this.backupService.registerWindowForBackupsSync(vscodeWindow.id, !configuration.workspacePath, emptyWorkspaceBackupFolder, configuration.workspacePath);
				}

E
Erich Gamma 已提交
778 779 780 781
				// Load it
				vscodeWindow.load(configuration);
			}
		});
782 783

		return vscodeWindow;
E
Erich Gamma 已提交
784 785
	}

J
Joao Moreno 已提交
786
	private getNewWindowState(configuration: IWindowConfiguration): ISingleWindowState {
E
Erich Gamma 已提交
787 788

		// plugin development host Window - load from stored settings if any
A
Alex Dima 已提交
789
		if (!!configuration.extensionDevelopmentPath && this.windowsState.lastPluginDevelopmentHostWindow) {
E
Erich Gamma 已提交
790 791 792 793 794
			return this.windowsState.lastPluginDevelopmentHostWindow.uiState;
		}

		// Known Folder - load from stored settings if any
		if (configuration.workspacePath) {
B
Benjamin Pasero 已提交
795
			const stateForWorkspace = this.windowsState.openedFolders.filter(o => this.isPathEqual(o.workspacePath, configuration.workspacePath)).map(o => o.uiState);
E
Erich Gamma 已提交
796 797 798 799 800 801
			if (stateForWorkspace.length) {
				return stateForWorkspace[0];
			}
		}

		// First Window
B
Benjamin Pasero 已提交
802
		const lastActive = this.getLastActiveWindow();
E
Erich Gamma 已提交
803 804 805 806 807 808 809 810 811
		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
812
		let displayToUse: Electron.Display;
B
Benjamin Pasero 已提交
813
		const displays = screen.getAllDisplays();
E
Erich Gamma 已提交
814 815 816 817 818 819 820 821 822 823 824

		// 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 已提交
825
				const cursorPoint = screen.getCursorScreenPoint();
E
Erich Gamma 已提交
826 827 828 829 830 831 832 833 834 835 836 837 838 839
				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];
			}
		}

B
Benjamin Pasero 已提交
840
		const defaultState = defaultWindowState();
E
Erich Gamma 已提交
841 842 843 844 845 846
		defaultState.x = displayToUse.bounds.x + (displayToUse.bounds.width / 2) - (defaultState.width / 2);
		defaultState.y = displayToUse.bounds.y + (displayToUse.bounds.height / 2) - (defaultState.height / 2);

		return this.ensureNoOverlap(defaultState);
	}

J
Joao Moreno 已提交
847
	private ensureNoOverlap(state: ISingleWindowState): ISingleWindowState {
E
Erich Gamma 已提交
848 849 850 851
		if (WindowsManager.WINDOWS.length === 0) {
			return state;
		}

852 853
		const existingWindowBounds = WindowsManager.WINDOWS.map(win => win.getBounds());
		while (existingWindowBounds.some(b => b.x === state.x || b.y === state.y)) {
E
Erich Gamma 已提交
854 855 856 857 858 859 860
			state.x += 30;
			state.y += 30;
		}

		return state;
	}

861
	public openFileFolderPicker(forceNewWindow?: boolean): void {
862
		this.doPickAndOpen({ pickFolders: true, pickFiles: true, forceNewWindow });
863 864
	}

865 866
	public openFilePicker(forceNewWindow?: boolean, path?: string, window?: VSCodeWindow): void {
		this.doPickAndOpen({ pickFiles: true, forceNewWindow, path, window });
867 868
	}

869 870
	public openFolderPicker(forceNewWindow?: boolean, window?: VSCodeWindow): void {
		this.doPickAndOpen({ pickFolders: true, forceNewWindow, window });
E
Erich Gamma 已提交
871 872
	}

873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
	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');
	}

889
	private doPickAndOpen(options: INativeOpenDialogOptions): void {
890
		this.getFileOrFolderPaths(options, (paths: string[]) => {
E
Erich Gamma 已提交
891
			if (paths && paths.length) {
892
				this.open({ cli: this.environmentService.args, pathsToOpen: paths, forceNewWindow: options.forceNewWindow });
E
Erich Gamma 已提交
893 894 895 896
			}
		});
	}

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

B
Benjamin Pasero 已提交
901
		let pickerProperties: ('openFile' | 'openDirectory' | 'multiSelections' | 'createDirectory')[];
902
		if (options.pickFiles && options.pickFolders) {
E
Erich Gamma 已提交
903 904
			pickerProperties = ['multiSelections', 'openDirectory', 'openFile', 'createDirectory'];
		} else {
905
			pickerProperties = ['multiSelections', options.pickFolders ? 'openDirectory' : 'openFile', 'createDirectory'];
E
Erich Gamma 已提交
906 907
		}

908
		dialog.showOpenDialog(focussedWindow && focussedWindow.win, {
E
Erich Gamma 已提交
909 910
			defaultPath: workingDir,
			properties: pickerProperties
911
		}, paths => {
E
Erich Gamma 已提交
912 913 914
			if (paths && paths.length > 0) {

				// Remember path in storage for next time
J
Joao Moreno 已提交
915
				this.storageService.setItem(WindowsManager.workingDirPickerStorageKey, path.dirname(paths[0]));
E
Erich Gamma 已提交
916 917 918 919 920 921 922 923 924

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

B
Benjamin Pasero 已提交
925
	public focusLastActive(cli: ParsedArgs): VSCodeWindow {
B
Benjamin Pasero 已提交
926
		const lastActive = this.getLastActiveWindow();
E
Erich Gamma 已提交
927
		if (lastActive) {
B
Benjamin Pasero 已提交
928
			lastActive.focus();
929 930

			return lastActive;
E
Erich Gamma 已提交
931 932 933
		}

		// No window - open new one
934 935 936 937
		this.windowsState.openedFolders = []; // make sure we do not open too much
		const res = this.open({ cli: cli });

		return res && res[0];
E
Erich Gamma 已提交
938 939
	}

J
Joao Moreno 已提交
940
	public getLastActiveWindow(): VSCodeWindow {
E
Erich Gamma 已提交
941
		if (WindowsManager.WINDOWS.length) {
942 943
			const lastFocussedDate = Math.max.apply(Math, WindowsManager.WINDOWS.map(w => w.lastFocusTime));
			const res = WindowsManager.WINDOWS.filter(w => w.lastFocusTime === lastFocussedDate);
E
Erich Gamma 已提交
944 945 946 947 948 949 950 951
			if (res && res.length) {
				return res[0];
			}
		}

		return null;
	}

J
Joao Moreno 已提交
952
	public findWindow(workspacePath: string, filePath?: string, extensionDevelopmentPath?: string): VSCodeWindow {
E
Erich Gamma 已提交
953 954 955
		if (WindowsManager.WINDOWS.length) {

			// Sort the last active window to the front of the array of windows to test
B
Benjamin Pasero 已提交
956 957
			const windowsToTest = WindowsManager.WINDOWS.slice(0);
			const lastActiveWindow = this.getLastActiveWindow();
E
Erich Gamma 已提交
958 959 960 961 962 963
			if (lastActiveWindow) {
				windowsToTest.splice(windowsToTest.indexOf(lastActiveWindow), 1);
				windowsToTest.unshift(lastActiveWindow);
			}

			// Find it
964
			const res = windowsToTest.filter(w => {
E
Erich Gamma 已提交
965 966

				// match on workspace
967
				if (typeof w.openedWorkspacePath === 'string' && (this.isPathEqual(w.openedWorkspacePath, workspacePath))) {
E
Erich Gamma 已提交
968 969 970 971
					return true;
				}

				// match on file
B
Benjamin Pasero 已提交
972
				if (typeof w.openedFilePath === 'string' && this.isPathEqual(w.openedFilePath, filePath)) {
E
Erich Gamma 已提交
973 974 975 976 977 978 979 980
					return true;
				}

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

981 982 983 984 985
				// match on extension development path
				if (typeof extensionDevelopmentPath === 'string' && w.extensionDevelopmentPath === extensionDevelopmentPath) {
					return true;
				}

E
Erich Gamma 已提交
986 987 988 989 990 991 992 993 994 995 996 997
				return false;
			});

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

		return null;
	}

	public openNewWindow(): void {
998
		this.open({ cli: this.environmentService.args, forceNewWindow: true, forceEmpty: true });
E
Erich Gamma 已提交
999 1000 1001 1002 1003 1004
	}

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

		if (focusedWindow) {
1005
			focusedWindow.sendWhenReady(channel, ...args);
E
Erich Gamma 已提交
1006 1007 1008 1009
		}
	}

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

1015
			w.sendWhenReady(channel, payload);
E
Erich Gamma 已提交
1016 1017 1018
		});
	}

J
Joao Moreno 已提交
1019
	public getFocusedWindow(): VSCodeWindow {
B
Benjamin Pasero 已提交
1020
		const win = BrowserWindow.getFocusedWindow();
E
Erich Gamma 已提交
1021 1022 1023 1024 1025 1026 1027
		if (win) {
			return this.getWindowById(win.id);
		}

		return null;
	}

J
Joao Moreno 已提交
1028
	public getWindowById(windowId: number): VSCodeWindow {
1029
		const res = WindowsManager.WINDOWS.filter(w => w.id === windowId);
E
Erich Gamma 已提交
1030 1031 1032 1033 1034 1035 1036
		if (res && res.length === 1) {
			return res[0];
		}

		return null;
	}

J
Joao Moreno 已提交
1037
	public getWindows(): VSCodeWindow[] {
E
Erich Gamma 已提交
1038 1039 1040 1041 1042 1043 1044
		return WindowsManager.WINDOWS;
	}

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

J
Joao Moreno 已提交
1045
	private onWindowError(vscodeWindow: VSCodeWindow, error: WindowError): void {
E
Erich Gamma 已提交
1046 1047 1048 1049
		console.error(error === WindowError.CRASHED ? '[VS Code]: render process crashed!' : '[VS Code]: detected unresponsive');

		// Unresponsive
		if (error === WindowError.UNRESPONSIVE) {
1050
			dialog.showMessageBox(vscodeWindow.win, {
B
Benjamin Pasero 已提交
1051
				title: product.nameLong,
E
Erich Gamma 已提交
1052
				type: 'warning',
B
Benjamin Pasero 已提交
1053
				buttons: [nls.localize('reopen', "Reopen"), nls.localize('wait', "Keep Waiting"), nls.localize('close', "Close")],
1054
				message: nls.localize('appStalled', "The window is no longer responding"),
B
Benjamin Pasero 已提交
1055
				detail: nls.localize('appStalledDetail', "You can reopen or close the window or keep waiting."),
E
Erich Gamma 已提交
1056
				noLink: true
1057
			}, result => {
E
Erich Gamma 已提交
1058
				if (result === 0) {
1059 1060
					vscodeWindow.reload();
				} else if (result === 2) {
1061
					this.onBeforeWindowClose(vscodeWindow); // 'close' event will not be fired on destroy(), so run it manually
1062
					vscodeWindow.win.destroy(); // make sure to destroy the window as it is unresponsive
E
Erich Gamma 已提交
1063 1064 1065 1066 1067 1068
				}
			});
		}

		// Crashed
		else {
1069
			dialog.showMessageBox(vscodeWindow.win, {
B
Benjamin Pasero 已提交
1070
				title: product.nameLong,
E
Erich Gamma 已提交
1071
				type: 'warning',
B
Benjamin Pasero 已提交
1072
				buttons: [nls.localize('reopen', "Reopen"), nls.localize('close', "Close")],
1073
				message: nls.localize('appCrashed', "The window has crashed"),
B
Benjamin Pasero 已提交
1074
				detail: nls.localize('appCrashedDetail', "We are sorry for the inconvenience! You can reopen the window to continue where you left off."),
E
Erich Gamma 已提交
1075
				noLink: true
1076
			}, result => {
1077 1078 1079
				if (result === 0) {
					vscodeWindow.reload();
				} else if (result === 1) {
1080
					this.onBeforeWindowClose(vscodeWindow); // 'close' event will not be fired on destroy(), so run it manually
1081 1082
					vscodeWindow.win.destroy(); // make sure to destroy the window as it has crashed
				}
E
Erich Gamma 已提交
1083 1084 1085 1086
			});
		}
	}

J
Joao Moreno 已提交
1087 1088
	private onBeforeWindowClose(win: VSCodeWindow): void {
		if (win.readyState !== ReadyState.READY) {
E
Erich Gamma 已提交
1089 1090 1091 1092
			return; // only persist windows that are fully loaded
		}

		// On Window close, update our stored state of this window
B
Benjamin Pasero 已提交
1093
		const state: IWindowState = { workspacePath: win.openedWorkspacePath, uiState: win.serializeWindowState() };
1094 1095 1096 1097
		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 已提交
1098 1099 1100 1101
		} else {
			this.windowsState.lastActiveWindow = state;

			this.windowsState.openedFolders.forEach(o => {
B
Benjamin Pasero 已提交
1102
				if (this.isPathEqual(o.workspacePath, win.openedWorkspacePath)) {
E
Erich Gamma 已提交
1103 1104 1105 1106 1107 1108
					o.uiState = state.uiState;
				}
			});
		}
	}

J
Joao Moreno 已提交
1109
	private onWindowClosed(win: VSCodeWindow): void {
E
Erich Gamma 已提交
1110 1111 1112 1113 1114

		// Tell window
		win.dispose();

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

		// Emit
1119
		this._onWindowClose.fire(win.id);
E
Erich Gamma 已提交
1120
	}
B
Benjamin Pasero 已提交
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144

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

1146
	public toggleMenuBar(windowId: number): void {
J
Joao Moreno 已提交
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
		// Update in settings
		const menuBarHidden = this.storageService.getItem(VSCodeWindow.menuBarHiddenKey, false);
		const newMenuBarHidden = !menuBarHidden;
		this.storageService.setItem(VSCodeWindow.menuBarHiddenKey, newMenuBarHidden);

		// Update across windows
		WindowsManager.WINDOWS.forEach(w => w.setMenuBarVisibility(!newMenuBarHidden));

		// Inform user if menu bar is now hidden
		if (newMenuBarHidden) {
			const vscodeWindow = this.getWindowById(windowId);
			if (vscodeWindow) {
				vscodeWindow.send('vscode:showInfoMessage', nls.localize('hiddenMenuBar', "You can still access the menu bar by pressing the **Alt** key."));
			}
		}
	}
1163

B
Benjamin Pasero 已提交
1164
	private updateWindowsJumpList(): void {
1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
		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
		}
	}
1225 1226 1227 1228 1229 1230

	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();
1231
		if (vscodeWindow && vscodeWindow.isExtensionDevelopmentHost && this.getWindowCount() > 1) {
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
			vscodeWindow.win.close();
		}

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