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

enum WindowError {
	UNRESPONSIVE,
	CRASHED
}

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

E
Erich Gamma 已提交
44 45
interface IWindowState {
	workspacePath?: string;
J
Joao Moreno 已提交
46
	uiState: ISingleWindowState;
E
Erich Gamma 已提交
47 48 49 50 51 52 53 54
}

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

55 56 57
interface INativeOpenDialogOptions {
	pickFolders?: boolean;
	pickFiles?: boolean;
58 59
	path?: string;
	forceNewWindow?: boolean;
B
Benjamin Pasero 已提交
60
	window?: CodeWindow;
61 62
}

63 64 65 66 67 68
const ReopenFoldersSetting = {
	ALL: 'all',
	ONE: 'one',
	NONE: 'none'
};

J
Joao Moreno 已提交
69
export class WindowsManager implements IWindowsMainService {
J
Joao Moreno 已提交
70

71
	_serviceBrand: any;
E
Erich Gamma 已提交
72

73
	private static MAX_TOTAL_RECENT_ENTRIES = 100;
74

75
	private static recentPathsListStorageKey = 'openedPathsList';
76
	private static workingDirPickerStorageKey = 'pickerWorkingDir';
E
Erich Gamma 已提交
77 78
	private static windowsStateStorageKey = 'windowsState';

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

81
	private initialUserEnv: platform.IProcessEnvironment;
82

E
Erich Gamma 已提交
83
	private windowsState: IWindowsState;
84
	private lastClosedWindowState: IWindowState;
E
Erich Gamma 已提交
85

86 87 88
	private _onRecentPathsChange = new Emitter<void>();
	onRecentPathsChange: CommonEvent<void> = this._onRecentPathsChange.event;

B
Benjamin Pasero 已提交
89 90
	private _onWindowReady = new Emitter<CodeWindow>();
	onWindowReady: CommonEvent<CodeWindow> = this._onWindowReady.event;
91 92 93 94

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

95 96 97
	private _onWindowReload = new Emitter<number>();
	onWindowReload: CommonEvent<number> = this._onWindowReload.event;

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

J
Joao Moreno 已提交
101 102
	constructor(
		@ILogService private logService: ILogService,
J
Joao Moreno 已提交
103
		@IStorageService private storageService: IStorageService,
104
		@IEnvironmentService private environmentService: IEnvironmentService,
B
Benjamin Pasero 已提交
105
		@ILifecycleService private lifecycleService: ILifecycleService,
106
		@IBackupMainService private backupService: IBackupMainService,
107
		@ITelemetryService private telemetryService: ITelemetryService,
108
		@IConfigurationService private configurationService: IConfigurationService
109
	) { }
J
Joao Moreno 已提交
110

111
	public ready(initialUserEnv: platform.IProcessEnvironment): void {
E
Erich Gamma 已提交
112 113
		this.registerListeners();

114
		this.initialUserEnv = initialUserEnv;
J
Joao Moreno 已提交
115
		this.windowsState = this.storageService.getItem<IWindowsState>(WindowsManager.windowsStateStorageKey) || { openedFolders: [] };
E
Erich Gamma 已提交
116 117 118
	}

	private registerListeners(): void {
119 120 121 122 123

		app.on('accessibility-support-changed', (event: Event, accessibilitySupportEnabled: boolean) => {
			this.sendToAll('vscode:accessibilitySupportChanged', accessibilitySupportEnabled);
		});

124
		app.on('activate', (event: Event, hasVisibleWindows: boolean) => {
J
Joao Moreno 已提交
125
			this.logService.log('App#activate');
E
Erich Gamma 已提交
126

G
Giorgos Retsinas 已提交
127
			// Mac only event: open new window when we get activated
E
Erich Gamma 已提交
128
			if (!hasVisibleWindows) {
129
				this.openNewWindow(OpenContext.DOCK);
E
Erich Gamma 已提交
130 131 132 133 134 135
			}
		});

		let macOpenFiles: string[] = [];
		let runningTimeout: number = null;
		app.on('open-file', (event: Event, path: string) => {
J
Joao Moreno 已提交
136
			this.logService.log('App#open-file: ', path);
E
Erich Gamma 已提交
137 138 139 140 141 142 143 144 145 146 147 148 149
			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 已提交
150 151 152 153 154 155
				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 已提交
156 157 158 159 160
				macOpenFiles = [];
				runningTimeout = null;
			}, 100);
		});

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

B
Benjamin Pasero 已提交
164
			const win = this.getWindowById(windowId);
E
Erich Gamma 已提交
165 166 167 168
			if (win) {
				win.setReady();

				// Event
169
				this._onWindowReady.fire(win);
E
Erich Gamma 已提交
170 171 172
			}
		});

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

177 178 179 180
				// Handle specific events on main side
				this.onBroadcast(broadcast.channel, broadcast.payload);

				// Send to windows
181
				if (target) {
B
Benjamin Pasero 已提交
182
					const otherWindowsWithTarget = WindowsManager.WINDOWS.filter(w => w.id !== windowId && typeof w.openedWorkspacePath === 'string');
183 184
					const directTargetMatch = otherWindowsWithTarget.filter(w => isEqual(target, w.openedWorkspacePath, !platform.isLinux /* ignorecase */));
					const parentTargetMatch = otherWindowsWithTarget.filter(w => isParent(target, w.openedWorkspacePath, !platform.isLinux /* ignorecase */));
185 186 187

					const targetWindow = directTargetMatch.length ? directTargetMatch[0] : parentTargetMatch[0]; // prefer direct match over parent match
					if (targetWindow) {
188 189 190 191 192
						targetWindow.send('vscode:broadcast', broadcast);
					}
				} else {
					this.sendToAll('vscode:broadcast', broadcast, [windowId]);
				}
E
Erich Gamma 已提交
193
			}
194 195
		});

196
		// Update our windows state before quitting and before closing windows
B
Benjamin Pasero 已提交
197
		this.lifecycleService.onBeforeWindowClose(win => this.onBeforeWindowClose(win as CodeWindow));
198
		this.lifecycleService.onBeforeQuit(() => this.onBeforeQuit());
A
Alex Dima 已提交
199

B
Benjamin Pasero 已提交
200 201
		// Keyboard layout changes
		KeyboardLayoutMonitor.INSTANCE.onDidChangeKeyboardLayout(isISOKeyboard => this.sendToAll('vscode:keyboardLayoutChanged', isISOKeyboard));
202 203 204 205 206 207 208 209 210 211 212 213 214
	}

	// Note that onBeforeQuit() and onBeforeWindowClose() are fired in different order depending on the OS:
	// - macOS: since the app will not quit when closing the last window, you will always first get
	//          the onBeforeQuit() event followed by N onbeforeWindowClose() events for each window
	// - other: on other OS, closing the last window will quit the app so the order depends on the
	//          user interaction: closing the last window will first trigger onBeforeWindowClose()
	//          and then onBeforeQuit(). Using the quit action however will first issue onBeforeQuit()
	//          and then onBeforeWindowClose().
	private onBeforeQuit(): void {
		const currentWindowsState: IWindowsState = {
			openedFolders: [],
			lastPluginDevelopmentHostWindow: this.windowsState.lastPluginDevelopmentHostWindow,
215
			lastActiveWindow: this.lastClosedWindowState
216 217 218 219 220 221 222 223
		};

		// 1.) Find a last active window (pick any other first window otherwise)
		if (!currentWindowsState.lastActiveWindow) {
			let activeWindow = this.getLastActiveWindow();
			if (!activeWindow || activeWindow.isExtensionDevelopmentHost) {
				activeWindow = WindowsManager.WINDOWS.filter(w => !w.isExtensionDevelopmentHost)[0];
			}
E
Erich Gamma 已提交
224

225 226
			if (activeWindow) {
				currentWindowsState.lastActiveWindow = { workspacePath: activeWindow.openedWorkspacePath, uiState: activeWindow.serializeWindowState() };
E
Erich Gamma 已提交
227
			}
228 229 230 231 232 233 234
		}

		// 2.) Find extension host window
		const extensionHostWindow = WindowsManager.WINDOWS.filter(w => w.isExtensionDevelopmentHost && !w.isExtensionTestHost)[0];
		if (extensionHostWindow) {
			currentWindowsState.lastPluginDevelopmentHostWindow = { workspacePath: extensionHostWindow.openedWorkspacePath, uiState: extensionHostWindow.serializeWindowState() };
		}
E
Erich Gamma 已提交
235

236 237 238 239 240 241 242
		// 3.) All windows with opened folders for N >= 2 to support reopenFolders: all or for auto update
		//
		// Carefull here: asking a window for its window state after it has been closed returns bogus values (width: 0, height: 0)
		// so if we ever want to persist the UI state of the last closed window (window count === 1), it has
		// to come from the stored lastClosedWindowState on Win/Linux at least
		if (this.getWindowCount() > 1) {
			currentWindowsState.openedFolders = WindowsManager.WINDOWS.filter(w => !!w.openedWorkspacePath && !w.isExtensionDevelopmentHost).map(w => {
E
Erich Gamma 已提交
243 244 245
				return <IWindowState>{
					workspacePath: w.openedWorkspacePath,
					uiState: w.serializeWindowState()
B
Benjamin Pasero 已提交
246
				};
E
Erich Gamma 已提交
247
			});
248
		}
E
Erich Gamma 已提交
249

250 251 252
		// Persist
		this.storageService.setItem(WindowsManager.windowsStateStorageKey, currentWindowsState);
	}
253

254
	// See note on #onBeforeQuit() for details how these events are flowing
B
Benjamin Pasero 已提交
255
	private onBeforeWindowClose(win: CodeWindow): void {
256 257 258 259 260 261 262 263 264 265 266 267 268
		if (this.lifecycleService.isQuitRequested()) {
			return; // during quit, many windows close in parallel so let it be handled in the before-quit handler
		}

		// On Window close, update our stored UI state of this window
		const state: IWindowState = { workspacePath: win.openedWorkspacePath, uiState: win.serializeWindowState() };
		if (win.isExtensionDevelopmentHost && !win.isExtensionTestHost) {
			this.windowsState.lastPluginDevelopmentHostWindow = state; // do not let test run window state overwrite our extension development state
		}

		// Any non extension host window with same workspace
		else if (!win.isExtensionDevelopmentHost && !!win.openedWorkspacePath) {
			this.windowsState.openedFolders.forEach(o => {
269
				if (isEqual(o.workspacePath, win.openedWorkspacePath, !platform.isLinux /* ignorecase */)) {
270 271 272 273 274 275 276
					o.uiState = state.uiState;
				}
			});
		}

		// On Windows and Linux closing the last window will trigger quit. Since we are storing all UI state
		// before quitting, we need to remember the UI state of this window to be able to persist it.
277 278 279
		// On macOS we keep the last closed window state ready in case the user wants to quit right after or
		// wants to open another window, in which case we use this state over the persisted one.
		if (this.getWindowCount() === 1) {
280 281
			this.lastClosedWindowState = state;
		}
E
Erich Gamma 已提交
282 283
	}

284
	private onBroadcast(event: string, payload: any): void {
285

286
		// Theme changes
287
		if (event === 'vscode:changeColorTheme' && typeof payload === 'string') {
288 289

			let data = JSON.parse(payload);
B
Benjamin Pasero 已提交
290 291
			this.storageService.setItem(CodeWindow.themeStorageKey, data.id);
			this.storageService.setItem(CodeWindow.themeBackgroundStorageKey, data.background);
292
		}
293
	}
B
Benjamin Pasero 已提交
294
	public reload(win: CodeWindow, cli?: ParsedArgs): void {
E
Erich Gamma 已提交
295 296

		// Only reload when the window has not vetoed this
297
		this.lifecycleService.unload(win, UnloadReason.RELOAD).done(veto => {
E
Erich Gamma 已提交
298 299
			if (!veto) {
				win.reload(cli);
300 301 302

				// Emit
				this._onWindowReload.fire(win.id);
E
Erich Gamma 已提交
303 304 305 306
			}
		});
	}

B
Benjamin Pasero 已提交
307
	public open(openConfig: IOpenConfiguration): CodeWindow[] {
308 309
		const windowConfig = this.configurationService.getConfiguration<IWindowSettings>('window');

J
Joao Moreno 已提交
310
		let iPathsToOpen: IPath[];
B
Benjamin Pasero 已提交
311
		const usedWindows: CodeWindow[] = [];
E
Erich Gamma 已提交
312 313 314

		// Find paths from provided paths if any
		if (openConfig.pathsToOpen && openConfig.pathsToOpen.length > 0) {
315
			iPathsToOpen = openConfig.pathsToOpen.map(pathToOpen => {
B
Benjamin Pasero 已提交
316
				const iPath = this.toIPath(pathToOpen, false, openConfig.cli && openConfig.cli.goto);
E
Erich Gamma 已提交
317 318 319

				// Warn if the requested path to open does not exist
				if (!iPath) {
B
Benjamin Pasero 已提交
320
					const options: Electron.ShowMessageBoxOptions = {
B
Benjamin Pasero 已提交
321
						title: product.nameLong,
E
Erich Gamma 已提交
322 323 324 325 326 327 328
						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 已提交
329
					const activeWindow = BrowserWindow.getFocusedWindow();
E
Erich Gamma 已提交
330
					if (activeWindow) {
331
						dialog.showMessageBox(activeWindow, options);
E
Erich Gamma 已提交
332
					} else {
333
						dialog.showMessageBox(options);
E
Erich Gamma 已提交
334 335 336 337 338 339 340 341 342 343
					}
				}

				return iPath;
			});

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

			if (iPathsToOpen.length === 0) {
344
				return null; // indicate to outside that open failed
E
Erich Gamma 已提交
345 346 347 348 349 350 351 352 353 354
			}
		}

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

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

359
		let foldersToOpen = arrays.distinct(iPathsToOpen.filter(iPath => iPath.workspacePath && !iPath.filePath).map(iPath => iPath.workspacePath), folder => platform.isLinux ? folder : folder.toLowerCase()); // prevent duplicates
360
		let foldersToRestore = (openConfig.initialStartup && !openConfig.cli.extensionDevelopmentPath) ? this.backupService.getWorkspaceBackupPaths() : [];
361 362 363
		let filesToOpen: IPath[] = [];
		let filesToDiff: IPath[] = [];
		let emptyToOpen = iPathsToOpen.filter(iPath => !iPath.workspacePath && !iPath.filePath);
364
		let emptyToRestore = (openConfig.initialStartup && !openConfig.cli.extensionDevelopmentPath) ? this.backupService.getEmptyWorkspaceBackupPaths() : [];
365 366 367 368 369 370 371 372 373 374 375
		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
			}

376 377 378
			foldersToOpen = []; 	// diff is always in empty workspace
			foldersToRestore = [];	// diff is always in empty workspace
			filesToCreate = []; 	// diff ignores other files that do not exist
379 380 381 382
		} else {
			filesToOpen = candidates;
		}

383
		// let the user settings override how folders are open in a new window or same window unless we are forced
384
		let openFolderInNewWindow = (openConfig.preferNewWindow || openConfig.forceNewWindow) && !openConfig.forceReuseWindow;
385 386
		if (!openConfig.forceNewWindow && !openConfig.forceReuseWindow && windowConfig && (windowConfig.openFoldersInNewWindow === 'on' || windowConfig.openFoldersInNewWindow === 'off')) {
			openFolderInNewWindow = (windowConfig.openFoldersInNewWindow === 'on');
387
		}
388

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

392
			// 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)
393
			let openFilesInNewWindow: boolean;
394 395
			if (openConfig.forceNewWindow || openConfig.forceReuseWindow) {
				openFilesInNewWindow = openConfig.forceNewWindow && !openConfig.forceReuseWindow;
396
			} else {
B
Benjamin Pasero 已提交
397
				if (openConfig.context === OpenContext.DOCK) {
398 399 400
					openFilesInNewWindow = true; // only on macOS do we allow to open files in a new window if this is triggered via DOCK context
				}

B
Benjamin Pasero 已提交
401
				if (!openConfig.cli.extensionDevelopmentPath && windowConfig && (windowConfig.openFilesInNewWindow === 'on' || windowConfig.openFilesInNewWindow === 'off')) {
402
					openFilesInNewWindow = (windowConfig.openFilesInNewWindow === 'on');
403
				}
E
Erich Gamma 已提交
404 405 406
			}

			// Open Files in last instance if any and flag tells us so
407 408 409 410 411 412 413 414 415
			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
			});
B
Benjamin Pasero 已提交
416
			if (windowOrFolder instanceof CodeWindow) {
417
				windowOrFolder.focus();
418
				const files = { filesToOpen, filesToCreate, filesToDiff }; // copy to object because they get reset shortly after
419
				windowOrFolder.ready().then(readyWindow => {
420
					readyWindow.send('vscode:openFiles', files);
E
Erich Gamma 已提交
421
				});
422

423
				usedWindows.push(windowOrFolder);
E
Erich Gamma 已提交
424 425 426 427
			}

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

B
Benjamin Pasero 已提交
432
				openFolderInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
433
			}
434 435 436 437 438

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

441 442 443
		// 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 已提交
444 445

			// Check for existing instances
446
			const windowsOnWorkspacePath = arrays.coalesce(allFoldersToOpen.map(folderToOpen => this.findWindow(folderToOpen)));
E
Erich Gamma 已提交
447
			if (windowsOnWorkspacePath.length > 0) {
B
Benjamin Pasero 已提交
448
				const browserWindow = windowsOnWorkspacePath[0];
449
				browserWindow.focus(); // just focus one of them
450
				const files = { filesToOpen, filesToCreate, filesToDiff }; // copy to object because they get reset shortly after
451
				browserWindow.ready().then(readyWindow => {
452
					readyWindow.send('vscode:openFiles', files);
E
Erich Gamma 已提交
453 454
				});

455 456
				usedWindows.push(browserWindow);

E
Erich Gamma 已提交
457 458 459
				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
460
				filesToDiff = [];
E
Erich Gamma 已提交
461

B
Benjamin Pasero 已提交
462
				openFolderInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
463 464 465
			}

			// Open remaining ones
466
			allFoldersToOpen.forEach(folderToOpen => {
467
				if (windowsOnWorkspacePath.some(win => isEqual(win.openedWorkspacePath, folderToOpen, !platform.isLinux /* ignorecase */))) {
E
Erich Gamma 已提交
468 469 470
					return; // ignore folders that are already open
				}

471
				const configuration = this.toConfiguration(openConfig, folderToOpen, filesToOpen, filesToCreate, filesToDiff);
472
				const browserWindow = this.openInBrowserWindow(configuration, openFolderInNewWindow, openFolderInNewWindow ? void 0 : openConfig.windowToUse as CodeWindow);
473
				usedWindows.push(browserWindow);
E
Erich Gamma 已提交
474 475 476 477

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

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

		// Handle empty
485
		if (emptyToRestore.length > 0) {
486
			emptyToRestore.forEach(emptyWorkspaceBackupFolder => {
B
wip  
Benjamin Pasero 已提交
487
				const configuration = this.toConfiguration(openConfig, void 0, filesToOpen, filesToCreate, filesToDiff);
488
				const browserWindow = this.openInBrowserWindow(configuration, true /* new window */, null, emptyWorkspaceBackupFolder);
489 490
				usedWindows.push(browserWindow);

B
wip  
Benjamin Pasero 已提交
491 492 493 494 495
				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
				filesToDiff = [];

B
Benjamin Pasero 已提交
496
				openFolderInNewWindow = true; // any other folders to open must open in new window then
497 498
			});
		}
B
Benjamin Pasero 已提交
499

500 501
		// Only open empty if no empty workspaces were restored
		else if (emptyToOpen.length > 0) {
E
Erich Gamma 已提交
502
			emptyToOpen.forEach(() => {
503
				const configuration = this.toConfiguration(openConfig);
504
				const browserWindow = this.openInBrowserWindow(configuration, openFolderInNewWindow, openFolderInNewWindow ? void 0 : openConfig.windowToUse as CodeWindow);
505
				usedWindows.push(browserWindow);
E
Erich Gamma 已提交
506

B
Benjamin Pasero 已提交
507
				openFolderInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
508 509 510
			});
		}

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

516 517 518
			iPathsToOpen.forEach(iPath => {
				if (iPath.filePath || iPath.workspacePath) {
					app.addRecentDocument(iPath.filePath || iPath.workspacePath);
519
					recentPaths.push({ path: iPath.filePath || iPath.workspacePath, isFile: !!iPath.filePath });
520 521
				}
			});
E
Erich Gamma 已提交
522

523 524 525 526
			if (recentPaths.length) {
				this.addToRecentPathsList(recentPaths);
			}
		}
E
Erich Gamma 已提交
527

528
		// Emit events
B
Benjamin Pasero 已提交
529
		this._onPathsOpen.fire(iPathsToOpen);
530

531
		return arrays.distinct(usedWindows);
E
Erich Gamma 已提交
532 533
	}

534 535
	public addToRecentPathsList(paths: { path: string; isFile?: boolean; }[]): void {
		if (!paths || !paths.length) {
536 537 538 539
			return;
		}

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

543 544 545 546 547 548 549 550 551 552 553 554
			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);
		});
555 556

		this.storageService.setItem(WindowsManager.recentPathsListStorageKey, mru);
557
		this._onRecentPathsChange.fire();
558 559
	}

560 561 562 563 564 565 566 567 568 569
	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];
		}

570
		const mru = this.getRecentPathsList();
571
		let update = false;
572

573 574 575 576 577 578
		paths.forEach(path => {
			let index = mru.files.indexOf(path);
			if (index >= 0) {
				mru.files.splice(index, 1);
				update = true;
			}
579

580 581 582 583 584 585
			index = mru.folders.indexOf(path);
			if (index >= 0) {
				mru.folders.splice(index, 1);
				update = true;
			}
		});
586

587 588
		if (update) {
			this.storageService.setItem(WindowsManager.recentPathsListStorageKey, mru);
589
			this._onRecentPathsChange.fire();
590
		}
591 592 593 594 595
	}

	public clearRecentPathsList(): void {
		this.storageService.setItem(WindowsManager.recentPathsListStorageKey, { folders: [], files: [] });
		app.clearRecentDocuments();
596 597 598

		// Event
		this._onRecentPathsChange.fire();
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
	}

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

632
	private getWindowUserEnv(openConfig: IOpenConfiguration): platform.IProcessEnvironment {
633 634 635
		return assign({}, this.initialUserEnv, openConfig.userEnv || {});
	}

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

B
Benjamin Pasero 已提交
638
		// Reload an existing extension development host window on the same path
E
Erich Gamma 已提交
639
		// We currently do not allow more than one extension development window
B
Benjamin Pasero 已提交
640
		// on the same extension path.
641
		let res = WindowsManager.WINDOWS.filter(w => w.config && isEqual(w.config.extensionDevelopmentPath, openConfig.cli.extensionDevelopmentPath, !platform.isLinux /* ignorecase */));
E
Erich Gamma 已提交
642 643
		if (res && res.length === 1) {
			this.reload(res[0], openConfig.cli);
B
Benjamin Pasero 已提交
644
			res[0].focus(); // make sure it gets focus and is restored
E
Erich Gamma 已提交
645 646 647 648

			return;
		}

649
		// Fill in previously opened workspace unless an explicit path is provided and we are not unit testing
B
Benjamin Pasero 已提交
650
		if (openConfig.cli._.length === 0 && !openConfig.cli.extensionTestsPath) {
B
Benjamin Pasero 已提交
651
			const workspaceToOpen = this.windowsState.lastPluginDevelopmentHostWindow && this.windowsState.lastPluginDevelopmentHostWindow.workspacePath;
E
Erich Gamma 已提交
652
			if (workspaceToOpen) {
B
Benjamin Pasero 已提交
653
				openConfig.cli._ = [workspaceToOpen];
E
Erich Gamma 已提交
654 655 656 657
			}
		}

		// Make sure we are not asked to open a path that is already opened
B
Benjamin Pasero 已提交
658 659
		if (openConfig.cli._.length > 0) {
			res = WindowsManager.WINDOWS.filter(w => w.openedWorkspacePath && openConfig.cli._.indexOf(w.openedWorkspacePath) >= 0);
E
Erich Gamma 已提交
660
			if (res.length) {
B
Benjamin Pasero 已提交
661
				openConfig.cli._ = [];
E
Erich Gamma 已提交
662 663 664 665
			}
		}

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

669
	private toConfiguration(config: IOpenConfiguration, workspacePath?: string, filesToOpen?: IPath[], filesToCreate?: IPath[], filesToDiff?: IPath[]): IWindowConfiguration {
670
		const configuration: IWindowConfiguration = mixin({}, config.cli); // inherit all properties from CLI
671
		configuration.appRoot = this.environmentService.appRoot;
B
Benjamin Pasero 已提交
672
		configuration.execPath = process.execPath;
673 674
		configuration.userEnv = this.getWindowUserEnv(config);
		configuration.isInitialStartup = config.initialStartup;
E
Erich Gamma 已提交
675 676 677
		configuration.workspacePath = workspacePath;
		configuration.filesToOpen = filesToOpen;
		configuration.filesToCreate = filesToCreate;
678
		configuration.filesToDiff = filesToDiff;
679
		configuration.nodeCachedDataDir = this.environmentService.nodeCachedDataDir;
E
Erich Gamma 已提交
680 681 682 683

		return configuration;
	}

J
Joao Moreno 已提交
684
	private toIPath(anyPath: string, ignoreFileNotFound?: boolean, gotoLineMode?: boolean): IPath {
E
Erich Gamma 已提交
685 686 687 688
		if (!anyPath) {
			return null;
		}

689
		let parsedPath: IPathWithLineAndColumn;
E
Erich Gamma 已提交
690
		if (gotoLineMode) {
J
Joao Moreno 已提交
691
			parsedPath = parseLineAndColumnAware(anyPath);
E
Erich Gamma 已提交
692 693 694
			anyPath = parsedPath.path;
		}

B
Benjamin Pasero 已提交
695
		const candidate = path.normalize(anyPath);
E
Erich Gamma 已提交
696
		try {
B
Benjamin Pasero 已提交
697
			const candidateStat = fs.statSync(candidate);
E
Erich Gamma 已提交
698 699 700 701 702
			if (candidateStat) {
				return candidateStat.isFile() ?
					{
						filePath: candidate,
						lineNumber: gotoLineMode ? parsedPath.line : void 0,
703
						columnNumber: gotoLineMode ? parsedPath.column : void 0
E
Erich Gamma 已提交
704 705 706 707
					} :
					{ workspacePath: candidate };
			}
		} catch (error) {
708 709
			this.removeFromRecentPathsList(candidate); // since file does not seem to exist anymore, remove from recent

E
Erich Gamma 已提交
710 711 712 713 714 715 716 717
			if (ignoreFileNotFound) {
				return { filePath: candidate, createFilePath: true }; // assume this is a file that does not yet exist
			}
		}

		return null;
	}

B
Benjamin Pasero 已提交
718
	private cliToPaths(cli: ParsedArgs, ignoreFileNotFound?: boolean): IPath[] {
E
Erich Gamma 已提交
719 720 721

		// Check for pass in candidate or last opened path
		let candidates: string[] = [];
B
Benjamin Pasero 已提交
722 723
		if (cli._.length > 0) {
			candidates = cli._;
E
Erich Gamma 已提交
724 725 726 727
		}

		// No path argument, check settings for what to do now
		else {
728
			let reopenFolders: string;
729
			if (this.lifecycleService.wasRestarted) {
730 731
				reopenFolders = ReopenFoldersSetting.ALL; // always reopen all folders when an update was applied
			} else {
732 733
				const windowConfig = this.configurationService.getConfiguration<IWindowSettings>('window');
				reopenFolders = (windowConfig && windowConfig.reopenFolders) || ReopenFoldersSetting.ONE;
734 735
			}

B
Benjamin Pasero 已提交
736
			const lastActiveFolder = this.windowsState.lastActiveWindow && this.windowsState.lastActiveWindow.workspacePath;
E
Erich Gamma 已提交
737 738

			// Restore all
739
			if (reopenFolders === ReopenFoldersSetting.ALL) {
B
Benjamin Pasero 已提交
740
				const lastOpenedFolders = this.windowsState.openedFolders.map(o => o.workspacePath);
E
Erich Gamma 已提交
741 742 743 744 745 746 747 748 749 750 751

				// 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
752
			else if (lastActiveFolder && (reopenFolders === ReopenFoldersSetting.ONE || reopenFolders !== ReopenFoldersSetting.NONE)) {
E
Erich Gamma 已提交
753 754 755 756
				candidates.push(lastActiveFolder);
			}
		}

757
		const iPaths = candidates.map(candidate => this.toIPath(candidate, ignoreFileNotFound, cli.goto)).filter(path => !!path);
E
Erich Gamma 已提交
758 759 760 761 762 763 764 765
		if (iPaths.length > 0) {
			return iPaths;
		}

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

B
Benjamin Pasero 已提交
766 767
	private openInBrowserWindow(configuration: IWindowConfiguration, forceNewWindow?: boolean, windowToUse?: CodeWindow, emptyWorkspaceBackupFolder?: string): CodeWindow {
		let codeWindow: CodeWindow;
E
Erich Gamma 已提交
768 769

		if (!forceNewWindow) {
B
Benjamin Pasero 已提交
770
			codeWindow = windowToUse || this.getLastActiveWindow();
E
Erich Gamma 已提交
771

B
Benjamin Pasero 已提交
772 773
			if (codeWindow) {
				codeWindow.focus();
E
Erich Gamma 已提交
774 775 776 777
			}
		}

		// New window
B
Benjamin Pasero 已提交
778
		if (!codeWindow) {
779
			const windowConfig = this.configurationService.getConfiguration<IWindowSettings>('window');
780 781 782 783 784 785 786 787 788 789
			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 {
790
				allowFullscreen = this.lifecycleService.wasRestarted || (windowConfig && windowConfig.restoreFullscreen);
791 792 793 794 795
			}

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

B
Benjamin Pasero 已提交
797
			codeWindow = new CodeWindow({
798
				state,
799
				extensionDevelopmentPath: configuration.extensionDevelopmentPath,
800
				isExtensionTestHost: !!configuration.extensionTestsPath
J
Johannes Rieken 已提交
801 802 803
			},
				this.logService,
				this.environmentService,
804 805
				this.configurationService,
				this.storageService
J
Johannes Rieken 已提交
806
			);
807

B
Benjamin Pasero 已提交
808
			WindowsManager.WINDOWS.push(codeWindow);
E
Erich Gamma 已提交
809 810

			// Window Events
B
Benjamin Pasero 已提交
811 812 813 814 815
			codeWindow.win.webContents.removeAllListeners('devtools-reload-page'); // remove built in listener so we can handle this on our own
			codeWindow.win.webContents.on('devtools-reload-page', () => this.reload(codeWindow));
			codeWindow.win.webContents.on('crashed', () => this.onWindowError(codeWindow, WindowError.CRASHED));
			codeWindow.win.on('unresponsive', () => this.onWindowError(codeWindow, WindowError.UNRESPONSIVE));
			codeWindow.win.on('closed', () => this.onWindowClosed(codeWindow));
E
Erich Gamma 已提交
816 817

			// Lifecycle
B
Benjamin Pasero 已提交
818
			this.lifecycleService.registerWindow(codeWindow);
E
Erich Gamma 已提交
819 820 821 822 823 824
		}

		// Existing window
		else {

			// Some configuration things get inherited if the window is being reused and we are
B
Benjamin Pasero 已提交
825
			// in extension development host mode. These options are all development related.
B
Benjamin Pasero 已提交
826
			const currentWindowConfig = codeWindow.config;
A
Alex Dima 已提交
827 828
			if (!configuration.extensionDevelopmentPath && currentWindowConfig && !!currentWindowConfig.extensionDevelopmentPath) {
				configuration.extensionDevelopmentPath = currentWindowConfig.extensionDevelopmentPath;
B
Benjamin Pasero 已提交
829
				configuration.verbose = currentWindowConfig.verbose;
830
				configuration.debugBrkPluginHost = currentWindowConfig.debugBrkPluginHost;
831
				configuration.debugPluginHost = currentWindowConfig.debugPluginHost;
832
				configuration['extensions-dir'] = currentWindowConfig['extensions-dir'];
E
Erich Gamma 已提交
833 834 835 836
			}
		}

		// Only load when the window has not vetoed this
B
Benjamin Pasero 已提交
837
		this.lifecycleService.unload(codeWindow, UnloadReason.LOAD).done(veto => {
E
Erich Gamma 已提交
838 839
			if (!veto) {

B
Benjamin Pasero 已提交
840 841
				// Register window for backups
				if (!configuration.extensionDevelopmentPath) {
B
Benjamin Pasero 已提交
842
					this.backupService.registerWindowForBackupsSync(codeWindow.id, !configuration.workspacePath, emptyWorkspaceBackupFolder, configuration.workspacePath);
B
Benjamin Pasero 已提交
843 844
				}

E
Erich Gamma 已提交
845
				// Load it
B
Benjamin Pasero 已提交
846
				codeWindow.load(configuration);
E
Erich Gamma 已提交
847 848
			}
		});
849

B
Benjamin Pasero 已提交
850
		return codeWindow;
E
Erich Gamma 已提交
851 852
	}

853
	private getNewWindowState(configuration: IWindowConfiguration): INewWindowState {
E
Erich Gamma 已提交
854

B
Benjamin Pasero 已提交
855
		// extension development host Window - load from stored settings if any
A
Alex Dima 已提交
856
		if (!!configuration.extensionDevelopmentPath && this.windowsState.lastPluginDevelopmentHostWindow) {
E
Erich Gamma 已提交
857 858 859 860 861
			return this.windowsState.lastPluginDevelopmentHostWindow.uiState;
		}

		// Known Folder - load from stored settings if any
		if (configuration.workspacePath) {
862
			const stateForWorkspace = this.windowsState.openedFolders.filter(o => isEqual(o.workspacePath, configuration.workspacePath, !platform.isLinux /* ignorecase */)).map(o => o.uiState);
E
Erich Gamma 已提交
863 864 865 866 867 868
			if (stateForWorkspace.length) {
				return stateForWorkspace[0];
			}
		}

		// First Window
B
Benjamin Pasero 已提交
869
		const lastActive = this.getLastActiveWindow();
870 871 872
		const lastActiveState = this.lastClosedWindowState || this.windowsState.lastActiveWindow;
		if (!lastActive && lastActiveState) {
			return lastActiveState.uiState;
E
Erich Gamma 已提交
873 874 875 876 877 878 879
		}

		//
		// 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
880
		let displayToUse: Electron.Display;
B
Benjamin Pasero 已提交
881
		const displays = screen.getAllDisplays();
E
Erich Gamma 已提交
882 883 884 885 886 887 888 889 890 891 892

		// 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 已提交
893
				const cursorPoint = screen.getCursorScreenPoint();
E
Erich Gamma 已提交
894 895 896 897 898 899 900 901
				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());
			}

902
			// fallback to primary display or first display
E
Erich Gamma 已提交
903
			if (!displayToUse) {
904
				displayToUse = screen.getPrimaryDisplay() || displays[0];
E
Erich Gamma 已提交
905 906 907
			}
		}

908
		let state = defaultWindowState() as INewWindowState;
909 910
		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 已提交
911

912 913 914 915 916 917 918 919 920 921 922
		// 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 已提交
923 924 925 926 927 928 929
				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;
				}

930 931 932 933 934 935 936 937
				ensureNoOverlap = false;
			}
		}

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

938 939
		state.hasDefaultState = true; // flag as default state

940
		return state;
E
Erich Gamma 已提交
941 942
	}

J
Joao Moreno 已提交
943
	private ensureNoOverlap(state: ISingleWindowState): ISingleWindowState {
E
Erich Gamma 已提交
944 945 946 947
		if (WindowsManager.WINDOWS.length === 0) {
			return state;
		}

948 949
		const existingWindowBounds = WindowsManager.WINDOWS.map(win => win.getBounds());
		while (existingWindowBounds.some(b => b.x === state.x || b.y === state.y)) {
E
Erich Gamma 已提交
950 951 952 953 954 955 956
			state.x += 30;
			state.y += 30;
		}

		return state;
	}

957 958
	public openFileFolderPicker(forceNewWindow?: boolean, data?: ITelemetryData): void {
		this.doPickAndOpen({ pickFolders: true, pickFiles: true, forceNewWindow }, 'openFileFolder', data);
959 960
	}

B
Benjamin Pasero 已提交
961
	public openFilePicker(forceNewWindow?: boolean, path?: string, window?: CodeWindow, data?: ITelemetryData): void {
962
		this.doPickAndOpen({ pickFiles: true, forceNewWindow, path, window }, 'openFile', data);
963 964
	}

B
Benjamin Pasero 已提交
965
	public openFolderPicker(forceNewWindow?: boolean, window?: CodeWindow, data?: ITelemetryData): void {
966
		this.doPickAndOpen({ pickFolders: true, forceNewWindow, window }, 'openFolder', data);
E
Erich Gamma 已提交
967 968
	}

969
	private doPickAndOpen(options: INativeOpenDialogOptions, eventName: string, data?: ITelemetryData): void {
970
		this.getFileOrFolderPaths(options, (paths: string[]) => {
971 972
			const nOfPaths = paths ? paths.length : 0;
			if (nOfPaths) {
973
				this.open({ context: OpenContext.DIALOG, cli: this.environmentService.args, pathsToOpen: paths, forceNewWindow: options.forceNewWindow });
E
Erich Gamma 已提交
974
			}
975 976 977 978 979
			this.telemetryService.publicLog(eventName, {
				...data,
				outcome: nOfPaths ? 'success' : 'canceled',
				nOfPaths
			});
E
Erich Gamma 已提交
980 981 982
		});
	}

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

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

994
		dialog.showOpenDialog(focussedWindow && focussedWindow.win, {
E
Erich Gamma 已提交
995 996
			defaultPath: workingDir,
			properties: pickerProperties
997
		}, paths => {
E
Erich Gamma 已提交
998 999 1000
			if (paths && paths.length > 0) {

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

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

B
Benjamin Pasero 已提交
1011
	public focusLastActive(cli: ParsedArgs, context: OpenContext): CodeWindow {
B
Benjamin Pasero 已提交
1012
		const lastActive = this.getLastActiveWindow();
E
Erich Gamma 已提交
1013
		if (lastActive) {
B
Benjamin Pasero 已提交
1014
			lastActive.focus();
1015 1016

			return lastActive;
E
Erich Gamma 已提交
1017 1018
		}

B
Benjamin Pasero 已提交
1019 1020
		// No window - open new empty one
		const res = this.open({ context, cli, forceEmpty: true });
1021 1022

		return res && res[0];
E
Erich Gamma 已提交
1023 1024
	}

B
Benjamin Pasero 已提交
1025
	public getLastActiveWindow(): CodeWindow {
1026
		return getLastActiveWindow(WindowsManager.WINDOWS);
E
Erich Gamma 已提交
1027 1028
	}

B
Benjamin Pasero 已提交
1029
	public findWindow(workspacePath: string, filePath?: string, extensionDevelopmentPath?: string): CodeWindow {
E
Erich Gamma 已提交
1030 1031 1032
		if (WindowsManager.WINDOWS.length) {

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

			// Find it
1041
			const res = windowsToTest.filter(w => {
E
Erich Gamma 已提交
1042 1043

				// match on workspace
1044
				if (typeof w.openedWorkspacePath === 'string' && (isEqual(w.openedWorkspacePath, workspacePath, !platform.isLinux /* ignorecase */))) {
E
Erich Gamma 已提交
1045 1046 1047 1048
					return true;
				}

				// match on file
1049
				if (typeof w.openedFilePath === 'string' && isEqual(w.openedFilePath, filePath, !platform.isLinux /* ignorecase */)) {
E
Erich Gamma 已提交
1050 1051 1052 1053
					return true;
				}

				// match on file path
1054
				if (typeof w.openedWorkspacePath === 'string' && filePath && isEqualOrParent(filePath, w.openedWorkspacePath, !platform.isLinux /* ignorecase */)) {
E
Erich Gamma 已提交
1055 1056 1057
					return true;
				}

1058
				// match on extension development path
1059
				if (typeof extensionDevelopmentPath === 'string' && isEqual(w.extensionDevelopmentPath, extensionDevelopmentPath, !platform.isLinux /* ignorecase */)) {
1060 1061 1062
					return true;
				}

E
Erich Gamma 已提交
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
				return false;
			});

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

		return null;
	}

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

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

		if (focusedWindow) {
1082
			focusedWindow.sendWhenReady(channel, ...args);
E
Erich Gamma 已提交
1083 1084 1085 1086
		}
	}

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

1092
			w.sendWhenReady(channel, payload);
E
Erich Gamma 已提交
1093 1094 1095
		});
	}

B
Benjamin Pasero 已提交
1096
	public getFocusedWindow(): CodeWindow {
B
Benjamin Pasero 已提交
1097
		const win = BrowserWindow.getFocusedWindow();
E
Erich Gamma 已提交
1098 1099 1100 1101 1102 1103 1104
		if (win) {
			return this.getWindowById(win.id);
		}

		return null;
	}

B
Benjamin Pasero 已提交
1105
	public getWindowById(windowId: number): CodeWindow {
1106
		const res = WindowsManager.WINDOWS.filter(w => w.id === windowId);
E
Erich Gamma 已提交
1107 1108 1109 1110 1111 1112 1113
		if (res && res.length === 1) {
			return res[0];
		}

		return null;
	}

B
Benjamin Pasero 已提交
1114
	public getWindows(): CodeWindow[] {
E
Erich Gamma 已提交
1115 1116 1117 1118 1119 1120 1121
		return WindowsManager.WINDOWS;
	}

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

B
Benjamin Pasero 已提交
1122
	private onWindowError(codeWindow: CodeWindow, error: WindowError): void {
E
Erich Gamma 已提交
1123 1124 1125 1126
		console.error(error === WindowError.CRASHED ? '[VS Code]: render process crashed!' : '[VS Code]: detected unresponsive');

		// Unresponsive
		if (error === WindowError.UNRESPONSIVE) {
B
Benjamin Pasero 已提交
1127
			dialog.showMessageBox(codeWindow.win, {
B
Benjamin Pasero 已提交
1128
				title: product.nameLong,
E
Erich Gamma 已提交
1129
				type: 'warning',
B
Benjamin Pasero 已提交
1130
				buttons: [nls.localize('reopen', "Reopen"), nls.localize('wait', "Keep Waiting"), nls.localize('close', "Close")],
1131
				message: nls.localize('appStalled', "The window is no longer responding"),
B
Benjamin Pasero 已提交
1132
				detail: nls.localize('appStalledDetail', "You can reopen or close the window or keep waiting."),
E
Erich Gamma 已提交
1133
				noLink: true
1134
			}, result => {
B
Benjamin Pasero 已提交
1135
				if (!codeWindow.win) {
1136 1137 1138
					return; // Return early if the window has been going down already
				}

E
Erich Gamma 已提交
1139
				if (result === 0) {
B
Benjamin Pasero 已提交
1140
					codeWindow.reload();
1141
				} else if (result === 2) {
B
Benjamin Pasero 已提交
1142 1143
					this.onBeforeWindowClose(codeWindow); // 'close' event will not be fired on destroy(), so run it manually
					codeWindow.win.destroy(); // make sure to destroy the window as it is unresponsive
E
Erich Gamma 已提交
1144 1145 1146 1147 1148 1149
				}
			});
		}

		// Crashed
		else {
B
Benjamin Pasero 已提交
1150
			dialog.showMessageBox(codeWindow.win, {
B
Benjamin Pasero 已提交
1151
				title: product.nameLong,
E
Erich Gamma 已提交
1152
				type: 'warning',
B
Benjamin Pasero 已提交
1153
				buttons: [nls.localize('reopen', "Reopen"), nls.localize('close', "Close")],
1154
				message: nls.localize('appCrashed', "The window has crashed"),
B
Benjamin Pasero 已提交
1155
				detail: nls.localize('appCrashedDetail', "We are sorry for the inconvenience! You can reopen the window to continue where you left off."),
E
Erich Gamma 已提交
1156
				noLink: true
1157
			}, result => {
B
Benjamin Pasero 已提交
1158
				if (!codeWindow.win) {
1159 1160 1161
					return; // Return early if the window has been going down already
				}

1162
				if (result === 0) {
B
Benjamin Pasero 已提交
1163
					codeWindow.reload();
1164
				} else if (result === 1) {
B
Benjamin Pasero 已提交
1165 1166
					this.onBeforeWindowClose(codeWindow); // 'close' event will not be fired on destroy(), so run it manually
					codeWindow.win.destroy(); // make sure to destroy the window as it has crashed
1167
				}
E
Erich Gamma 已提交
1168 1169 1170 1171
			});
		}
	}

B
Benjamin Pasero 已提交
1172
	private onWindowClosed(win: CodeWindow): void {
E
Erich Gamma 已提交
1173 1174 1175 1176 1177

		// Tell window
		win.dispose();

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

		// Emit
1182
		this._onWindowClose.fire(win.id);
E
Erich Gamma 已提交
1183
	}
B
Benjamin Pasero 已提交
1184

B
Benjamin Pasero 已提交
1185
	public updateWindowsJumpList(): void {
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 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245
		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
		}
	}
1246 1247 1248 1249 1250

	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.
B
Benjamin Pasero 已提交
1251 1252 1253
		const codeWindow = this.getFocusedWindow();
		if (codeWindow && codeWindow.isExtensionDevelopmentHost && this.getWindowCount() > 1) {
			codeWindow.win.close();
1254 1255 1256 1257 1258
		}

		// Otherwise: normal quit
		else {
			setTimeout(() => {
1259
				this.lifecycleService.quit();
1260 1261 1262
			}, 10 /* delay to unwind callback stack (IPC) */);
		}
	}
1263
}