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

6
import * as fs from 'fs';
7
import { basename, normalize, join, posix } from 'vs/base/common/path';
B
Benjamin Pasero 已提交
8
import { localize } from 'vs/nls';
J
Joao Moreno 已提交
9
import * as arrays from 'vs/base/common/arrays';
10
import { mixin } from 'vs/base/common/objects';
11 12
import { IBackupMainService } from 'vs/platform/backup/electron-main/backup';
import { IEmptyWindowBackupInfo } from 'vs/platform/backup/node/backup';
13 14
import { IEnvironmentService, INativeEnvironmentService } from 'vs/platform/environment/common/environment';
import { NativeParsedArgs } from 'vs/platform/environment/common/argv';
15
import { IStateService } from 'vs/platform/state/node/state';
16
import { CodeWindow, defaultWindowState } from 'vs/code/electron-main/window';
17
import { screen, BrowserWindow, MessageBoxOptions, Display, app } from 'electron';
18
import { ILifecycleMainService, UnloadReason, LifecycleMainService, LifecycleMainPhase } from 'vs/platform/lifecycle/electron-main/lifecycleMainService';
19
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
20
import { ILogService } from 'vs/platform/log/common/log';
21 22
import { IWindowSettings, IPath, isFileToOpen, isWorkspaceToOpen, isFolderToOpen, IWindowOpenable, IOpenEmptyWindowOptions, IAddFoldersRequest, IPathsToWaitFor, INativeWindowConfiguration } from 'vs/platform/windows/common/windows';
import { getLastActiveWindow, findBestWindowOrFolderForFile, findWindowOnWorkspace, findWindowOnExtensionDevelopmentPath, findWindowOnWorkspaceOrFolderUri, OpenContext } from 'vs/platform/windows/node/window';
23
import { Emitter } from 'vs/base/common/event';
24
import product from 'vs/platform/product/common/product';
25
import { IWindowsMainService, IOpenConfiguration, IWindowsCountChangedEvent, ICodeWindow, IWindowState as ISingleWindowState, WindowMode, IOpenEmptyConfiguration } from 'vs/platform/windows/electron-main/windows';
26
import { IWorkspacesHistoryMainService } from 'vs/platform/workspaces/electron-main/workspacesHistoryMainService';
27
import { IProcessEnvironment, isMacintosh, isWindows } from 'vs/base/common/platform';
28
import { IWorkspaceIdentifier, isSingleFolderWorkspaceIdentifier, hasWorkspaceFileExtension, IRecent } from 'vs/platform/workspaces/common/workspaces';
B
Benjamin Pasero 已提交
29
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
J
Johannes Rieken 已提交
30
import { Schemas } from 'vs/base/common/network';
31
import { URI } from 'vs/base/common/uri';
32
import { normalizePath, originalFSPath, removeTrailingPathSeparator, extUriBiasedIgnorePathCase } from 'vs/base/common/resources';
M
Martin Aeschlimann 已提交
33
import { getRemoteAuthority } from 'vs/platform/remote/common/remoteHosts';
34
import { restoreWindowsState, WindowsStateStorageData, getWindowsStateStoreData } from 'vs/platform/windows/electron-main/windowsStateStorage';
B
Benjamin Pasero 已提交
35
import { getWorkspaceIdentifier, IWorkspacesMainService } from 'vs/platform/workspaces/electron-main/workspacesMainService';
36
import { once } from 'vs/base/common/functional';
M
Matt Bierner 已提交
37
import { Disposable } from 'vs/base/common/lifecycle';
38 39
import { IDialogMainService } from 'vs/platform/dialogs/electron-main/dialogs';
import { withNullAsUndefined } from 'vs/base/common/types';
40
import { isWindowsDriveLetter, toSlashes, parseLineAndColumnAware } from 'vs/base/common/extpath';
41
import { CharCode } from 'vs/base/common/charCode';
42
import { getPathLabel } from 'vs/base/common/labels';
E
Erich Gamma 已提交
43

M
Martin Aeschlimann 已提交
44 45 46 47 48 49 50 51 52 53 54 55 56 57
export interface IWindowState {
	workspace?: IWorkspaceIdentifier;
	folderUri?: URI;
	backupPath?: string;
	remoteAuthority?: string;
	uiState: ISingleWindowState;
}

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

58 59 60 61
interface INewWindowState extends ISingleWindowState {
	hasDefaultState?: boolean;
}

62
type RestoreWindowsSetting = 'all' | 'folders' | 'one' | 'none';
63

B
Benjamin Pasero 已提交
64 65
interface IOpenBrowserWindowOptions {
	userEnv?: IProcessEnvironment;
66
	cli?: NativeParsedArgs;
67

68
	workspace?: IWorkspaceIdentifier;
69
	folderUri?: URI;
B
Benjamin Pasero 已提交
70

M
Matt Bierner 已提交
71
	remoteAuthority?: string;
M
Martin Aeschlimann 已提交
72

B
Benjamin Pasero 已提交
73 74
	initialStartup?: boolean;

75
	fileInputs?: IFileInputs;
B
Benjamin Pasero 已提交
76 77

	forceNewWindow?: boolean;
78
	forceNewTabbedWindow?: boolean;
79
	windowToUse?: ICodeWindow;
B
Benjamin Pasero 已提交
80

81 82 83 84 85 86
	emptyWindowBackupInfo?: IEmptyWindowBackupInfo;
}

interface IPathParseOptions {
	ignoreFileNotFound?: boolean;
	gotoLineMode?: boolean;
M
Martin Aeschlimann 已提交
87
	remoteAuthority?: string;
88 89 90
}

interface IFileInputs {
91
	filesToOpenOrCreate: IPath[];
92 93
	filesToDiff: IPath[];
	filesToWait?: IPathsToWaitFor;
M
Martin Aeschlimann 已提交
94
	remoteAuthority?: string;
B
Benjamin Pasero 已提交
95 96
}

B
Benjamin Pasero 已提交
97
interface IPathToOpen extends IPath {
98

99
	// the workspace for a Code instance to open
100
	workspace?: IWorkspaceIdentifier;
101

102
	// the folder path for a Code instance to open
103
	folderUri?: URI;
104

105
	// the backup path for a Code instance to use
106 107
	backupPath?: string;

M
Martin Aeschlimann 已提交
108 109 110
	// the remote authority for the Code instance to open. Undefined if not remote.
	remoteAuthority?: string;

M
Martin Aeschlimann 已提交
111 112
	// optional label for the recent history
	label?: string;
113 114
}

115 116 117 118 119 120 121 122 123 124 125 126 127 128
function isFolderPathToOpen(path: IPathToOpen): path is IFolderPathToOpen {
	return !!path.folderUri;
}

interface IFolderPathToOpen {

	// the folder path for a Code instance to open
	folderUri: URI;

	// the backup path for a Code instance to use
	backupPath?: string;

	// the remote authority for the Code instance to open. Undefined if not remote.
	remoteAuthority?: string;
M
Martin Aeschlimann 已提交
129 130 131

	// optional label for the recent history
	label?: string;
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
}

function isWorkspacePathToOpen(path: IPathToOpen): path is IWorkspacePathToOpen {
	return !!path.workspace;
}

interface IWorkspacePathToOpen {

	// the workspace for a Code instance to open
	workspace: IWorkspaceIdentifier;

	// the backup path for a Code instance to use
	backupPath?: string;

	// the remote authority for the Code instance to open. Undefined if not remote.
	remoteAuthority?: string;
M
Martin Aeschlimann 已提交
148 149 150

	// optional label for the recent history
	label?: string;
151 152
}

153
export class WindowsMainService extends Disposable implements IWindowsMainService {
J
Joao Moreno 已提交
154

155
	declare readonly _serviceBrand: undefined;
E
Erich Gamma 已提交
156

157
	private static readonly windowsStateStorageKey = 'windowsState';
E
Erich Gamma 已提交
158

159
	private static readonly WINDOWS: ICodeWindow[] = [];
160

161
	private readonly windowsState: IWindowsState;
162
	private lastClosedWindowState?: IWindowState;
E
Erich Gamma 已提交
163

164 165
	private shuttingDown = false;

M
Matt Bierner 已提交
166
	private readonly _onWindowReady = this._register(new Emitter<ICodeWindow>());
167
	readonly onWindowReady = this._onWindowReady.event;
168

M
Matt Bierner 已提交
169
	private readonly _onWindowsCountChanged = this._register(new Emitter<IWindowsCountChangedEvent>());
170
	readonly onWindowsCountChanged = this._onWindowsCountChanged.event;
B
Benjamin Pasero 已提交
171

J
Joao Moreno 已提交
172
	constructor(
B
Benjamin Pasero 已提交
173
		private readonly machineId: string,
174
		private readonly initialUserEnv: IProcessEnvironment,
175 176
		@ILogService private readonly logService: ILogService,
		@IStateService private readonly stateService: IStateService,
177
		@IEnvironmentService private readonly environmentService: INativeEnvironmentService,
178
		@ILifecycleMainService private readonly lifecycleMainService: ILifecycleMainService,
179 180
		@IBackupMainService private readonly backupMainService: IBackupMainService,
		@IConfigurationService private readonly configurationService: IConfigurationService,
181
		@IWorkspacesHistoryMainService private readonly workspacesHistoryMainService: IWorkspacesHistoryMainService,
182
		@IWorkspacesMainService private readonly workspacesMainService: IWorkspacesMainService,
183 184
		@IInstantiationService private readonly instantiationService: IInstantiationService,
		@IDialogMainService private readonly dialogMainService: IDialogMainService
185
	) {
M
Matt Bierner 已提交
186
		super();
187

188
		this.windowsState = restoreWindowsState(this.stateService.getItem<WindowsStateStorageData>(WindowsMainService.windowsStateStorageKey));
189 190 191
		if (!Array.isArray(this.windowsState.openedWindows)) {
			this.windowsState.openedWindows = [];
		}
192

193 194
		this.lifecycleMainService.when(LifecycleMainPhase.Ready).then(() => this.registerListeners());
		this.lifecycleMainService.when(LifecycleMainPhase.AfterWindowOpen).then(() => this.installWindowsMutex());
195
	}
J
Joao Moreno 已提交
196

197
	private installWindowsMutex(): void {
198 199
		const win32MutexName = product.win32MutexName;
		if (isWindows && win32MutexName) {
200 201
			try {
				const WindowsMutex = (require.__$__nodeRequire('windows-mutex') as typeof import('windows-mutex')).Mutex;
202
				const mutex = new WindowsMutex(win32MutexName);
203
				once(this.lifecycleMainService.onWillShutdown)(() => mutex.release());
204 205 206 207
			} catch (e) {
				this.logService.error(e);
			}
		}
E
Erich Gamma 已提交
208 209 210
	}

	private registerListeners(): void {
211

212 213 214 215 216 217 218 219 220
		// When a window looses focus, save all windows state. This allows to
		// prevent loss of window-state data when OS is restarted without properly
		// shutting down the application (https://github.com/microsoft/vscode/issues/87171)
		app.on('browser-window-blur', () => {
			if (!this.shuttingDown) {
				this.saveWindowsState();
			}
		});

221
		// Handle various lifecycle events around windows
222 223
		this.lifecycleMainService.onBeforeWindowClose(window => this.onBeforeWindowClose(window));
		this.lifecycleMainService.onBeforeShutdown(() => this.onBeforeShutdown());
224 225 226 227 228
		this.onWindowsCountChanged(e => {
			if (e.newCount - e.oldCount > 0) {
				// clear last closed window state when a new window opens. this helps on macOS where
				// otherwise closing the last window, opening a new window and then quitting would
				// use the state of the previously closed window when restarting.
R
Rob Lourens 已提交
229
				this.lastClosedWindowState = undefined;
230 231
			}
		});
232 233 234 235 236

		// Signal a window is ready after having entered a workspace
		this._register(this.workspacesMainService.onWorkspaceEntered(event => {
			this._onWindowReady.fire(event.window);
		}));
237 238
	}

239
	// Note that onBeforeShutdown() and onBeforeWindowClose() are fired in different order depending on the OS:
240
	// - macOS: since the app will not quit when closing the last window, you will always first get
K
Keshav Bohra 已提交
241
	//          the onBeforeShutdown() event followed by N onBeforeWindowClose() events for each window
242 243
	// - 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()
244
	//          and then onBeforeShutdown(). Using the quit action however will first issue onBeforeShutdown()
245
	//          and then onBeforeWindowClose().
246
	//
K
Keshav Bohra 已提交
247
	// Here is the behavior on different OS depending on action taken (Electron 1.7.x):
248 249 250 251 252
	//
	// Legend
	// -  quit(N): quit application with N windows opened
	// - close(1): close one window via the window close button
	// - closeAll: close all windows via the taskbar command
253
	// - onBeforeShutdown(N): number of windows reported in this event handler
254 255 256
	// - onBeforeWindowClose(N, M): number of windows reported and quitRequested boolean in this event handler
	//
	// macOS
257 258 259
	// 	-     quit(1): onBeforeShutdown(1), onBeforeWindowClose(1, true)
	// 	-     quit(2): onBeforeShutdown(2), onBeforeWindowClose(2, true), onBeforeWindowClose(2, true)
	// 	-     quit(0): onBeforeShutdown(0)
260 261 262
	// 	-    close(1): onBeforeWindowClose(1, false)
	//
	// Windows
263 264
	// 	-     quit(1): onBeforeShutdown(1), onBeforeWindowClose(1, true)
	// 	-     quit(2): onBeforeShutdown(2), onBeforeWindowClose(2, true), onBeforeWindowClose(2, true)
265
	// 	-    close(1): onBeforeWindowClose(2, false)[not last window]
266 267
	// 	-    close(1): onBeforeWindowClose(1, false), onBeforeShutdown(0)[last window]
	// 	- closeAll(2): onBeforeWindowClose(2, false), onBeforeWindowClose(2, false), onBeforeShutdown(0)
268 269
	//
	// Linux
270 271
	// 	-     quit(1): onBeforeShutdown(1), onBeforeWindowClose(1, true)
	// 	-     quit(2): onBeforeShutdown(2), onBeforeWindowClose(2, true), onBeforeWindowClose(2, true)
272
	// 	-    close(1): onBeforeWindowClose(2, false)[not last window]
273 274
	// 	-    close(1): onBeforeWindowClose(1, false), onBeforeShutdown(0)[last window]
	// 	- closeAll(2): onBeforeWindowClose(2, false), onBeforeWindowClose(2, false), onBeforeShutdown(0)
275
	//
276
	private onBeforeShutdown(): void {
277 278 279 280 281 282
		this.shuttingDown = true;

		this.saveWindowsState();
	}

	private saveWindowsState(): void {
283
		const currentWindowsState: IWindowsState = {
284
			openedWindows: [],
285
			lastPluginDevelopmentHostWindow: this.windowsState.lastPluginDevelopmentHostWindow,
286
			lastActiveWindow: this.lastClosedWindowState
287 288 289 290 291 292
		};

		// 1.) Find a last active window (pick any other first window otherwise)
		if (!currentWindowsState.lastActiveWindow) {
			let activeWindow = this.getLastActiveWindow();
			if (!activeWindow || activeWindow.isExtensionDevelopmentHost) {
293
				activeWindow = WindowsMainService.WINDOWS.find(window => !window.isExtensionDevelopmentHost);
294
			}
E
Erich Gamma 已提交
295

296
			if (activeWindow) {
297
				currentWindowsState.lastActiveWindow = this.toWindowState(activeWindow);
E
Erich Gamma 已提交
298
			}
299 300 301
		}

		// 2.) Find extension host window
302
		const extensionHostWindow = WindowsMainService.WINDOWS.find(window => window.isExtensionDevelopmentHost && !window.isExtensionTestHost);
303
		if (extensionHostWindow) {
304
			currentWindowsState.lastPluginDevelopmentHostWindow = this.toWindowState(extensionHostWindow);
305
		}
E
Erich Gamma 已提交
306

307
		// 3.) All windows (except extension host) for N >= 2 to support restoreWindows: all or for auto update
308
		//
K
Keshav Bohra 已提交
309
		// Careful here: asking a window for its window state after it has been closed returns bogus values (width: 0, height: 0)
310 311 312
		// 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) {
313
			currentWindowsState.openedWindows = WindowsMainService.WINDOWS.filter(window => !window.isExtensionDevelopmentHost).map(window => this.toWindowState(window));
314
		}
E
Erich Gamma 已提交
315

316
		// Persist
B
Benjamin Pasero 已提交
317 318
		const state = getWindowsStateStoreData(currentWindowsState);
		this.stateService.setItem(WindowsMainService.windowsStateStorageKey, state);
319 320 321 322

		if (this.shuttingDown) {
			this.logService.trace('onBeforeShutdown', state);
		}
323
	}
324

325
	// See note on #onBeforeShutdown() for details how these events are flowing
326
	private onBeforeWindowClose(win: ICodeWindow): void {
327
		if (this.lifecycleMainService.quitRequested) {
328 329 330 331
			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
332
		const state: IWindowState = this.toWindowState(win);
333 334 335 336
		if (win.isExtensionDevelopmentHost && !win.isExtensionTestHost) {
			this.windowsState.lastPluginDevelopmentHostWindow = state; // do not let test run window state overwrite our extension development state
		}

337
		// Any non extension host window with same workspace or folder
338
		else if (!win.isExtensionDevelopmentHost && (!!win.openedWorkspace || !!win.openedFolderUri)) {
339
			this.windowsState.openedWindows.forEach(o => {
B
fix npe  
Benjamin Pasero 已提交
340
				const sameWorkspace = win.openedWorkspace && o.workspace && o.workspace.id === win.openedWorkspace.id;
341
				const sameFolder = win.openedFolderUri && o.folderUri && extUriBiasedIgnorePathCase.isEqual(o.folderUri, win.openedFolderUri);
342 343

				if (sameWorkspace || sameFolder) {
344 345 346 347 348 349 350
					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.
351 352 353
		// 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) {
354 355
			this.lastClosedWindowState = state;
		}
E
Erich Gamma 已提交
356 357
	}

358
	private toWindowState(win: ICodeWindow): IWindowState {
359
		return {
360
			workspace: win.openedWorkspace,
361
			folderUri: win.openedFolderUri,
362
			backupPath: win.backupPath,
M
Martin Aeschlimann 已提交
363
			remoteAuthority: win.remoteAuthority,
364 365 366 367
			uiState: win.serializeWindowState()
		};
	}

368
	openEmptyWindow(openConfig: IOpenEmptyConfiguration, options?: IOpenEmptyWindowOptions): ICodeWindow[] {
369
		let cli = this.environmentService.args;
B
Benjamin Pasero 已提交
370
		const remote = options?.remoteAuthority;
371 372 373 374
		if (cli && (cli.remote !== remote)) {
			cli = { ...cli, remote };
		}

B
Benjamin Pasero 已提交
375
		const forceReuseWindow = options?.forceReuseWindow;
376 377
		const forceNewWindow = !forceReuseWindow;

378
		return this.open({ ...openConfig, cli, forceEmpty: true, forceNewWindow, forceReuseWindow });
379 380
	}

B
Benjamin Pasero 已提交
381
	open(openConfig: IOpenConfiguration): ICodeWindow[] {
382
		this.logService.trace('windowsManager#open');
383
		openConfig = this.validateOpenConfig(openConfig);
384

385
		const pathsToOpen = this.getPathsToOpen(openConfig);
386

387 388 389 390 391 392
		const foldersToAdd: IFolderPathToOpen[] = [];
		const foldersToOpen: IFolderPathToOpen[] = [];
		const workspacesToOpen: IWorkspacePathToOpen[] = [];
		const emptyToRestore: IEmptyWindowBackupInfo[] = []; // empty windows with backupPath
		let emptyToOpen: number = 0;
		let fileInputs: IFileInputs | undefined; 		// collect all file inputs
393
		for (const path of pathsToOpen) {
394 395 396 397 398 399 400 401 402 403 404
			if (isFolderPathToOpen(path)) {
				if (openConfig.addMode) {
					// When run with --add, take the folders that are to be opened as
					// folders that should be added to the currently active window.
					foldersToAdd.push(path);
				} else {
					foldersToOpen.push(path);
				}
			} else if (isWorkspacePathToOpen(path)) {
				workspacesToOpen.push(path);
			} else if (path.fileUri) {
405
				if (!fileInputs) {
406
					fileInputs = { filesToOpenOrCreate: [], filesToDiff: [], remoteAuthority: path.remoteAuthority };
407
				}
408
				fileInputs.filesToOpenOrCreate.push(path);
409 410 411 412
			} else if (path.backupPath) {
				emptyToRestore.push({ backupFolder: basename(path.backupPath), remoteAuthority: path.remoteAuthority });
			} else {
				emptyToOpen++;
413 414
			}
		}
415 416 417

		// When run with --diff, take the files to open as files to diff
		// if there are exactly two files provided.
418 419 420
		if (fileInputs && openConfig.diffMode && fileInputs.filesToOpenOrCreate.length === 2) {
			fileInputs.filesToDiff = fileInputs.filesToOpenOrCreate;
			fileInputs.filesToOpenOrCreate = [];
E
Erich Gamma 已提交
421 422
		}

423
		// When run with --wait, make sure we keep the paths to wait for
M
Martin Aeschlimann 已提交
424
		if (fileInputs && openConfig.waitMarkerFileURI) {
425
			fileInputs.filesToWait = { paths: [...fileInputs.filesToDiff, ...fileInputs.filesToOpenOrCreate], waitMarkerFileUri: openConfig.waitMarkerFileURI };
426 427
		}

428
		//
429
		// These are windows to restore because of hot-exit or from previous session (only performed once on startup!)
430
		//
431
		let workspacesToRestore: IWorkspacePathToOpen[] = [];
B
Benjamin Pasero 已提交
432
		if (openConfig.initialStartup && !openConfig.cli.extensionDevelopmentPath && !openConfig.cli['disable-restore-windows']) {
433 434

			// Untitled workspaces are always restored
435
			workspacesToRestore = this.workspacesMainService.getUntitledWorkspacesSync();
436
			workspacesToOpen.push(...workspacesToRestore);
437

438
			// Empty windows with backups are always restored
439 440 441
			emptyToRestore.push(...this.backupMainService.getEmptyWindowBackupPaths());
		} else {
			emptyToRestore.length = 0;
442
		}
443 444

		// Open based on config
445
		const usedWindows = this.doOpen(openConfig, workspacesToOpen, foldersToOpen, emptyToRestore, emptyToOpen, fileInputs, foldersToAdd);
446

447
		// Make sure to pass focus to the most relevant of the windows if we open multiple
448
		if (usedWindows.length > 1) {
449
			const focusLastActive = this.windowsState.lastActiveWindow && !openConfig.forceEmpty && openConfig.cli._.length && !openConfig.cli['file-uri'] && !openConfig.cli['folder-uri'] && !(openConfig.urisToOpen && openConfig.urisToOpen.length);
450 451
			let focusLastOpened = true;
			let focusLastWindow = true;
452

453 454
			// 1.) focus last active window if we are not instructed to open any paths
			if (focusLastActive) {
455
				const lastActiveWindow = usedWindows.filter(window => this.windowsState.lastActiveWindow && window.backupPath === this.windowsState.lastActiveWindow.backupPath);
456 457
				if (lastActiveWindow.length) {
					lastActiveWindow[0].focus();
458 459
					focusLastOpened = false;
					focusLastWindow = false;
460 461 462
				}
			}

463 464 465 466 467
			// 2.) if instructed to open paths, focus last window which is not restored
			if (focusLastOpened) {
				for (let i = usedWindows.length - 1; i >= 0; i--) {
					const usedWindow = usedWindows[i];
					if (
468 469
						(usedWindow.openedWorkspace && workspacesToRestore.some(workspace => usedWindow.openedWorkspace && workspace.workspace.id === usedWindow.openedWorkspace.id)) ||	// skip over restored workspace
						(usedWindow.backupPath && emptyToRestore.some(empty => usedWindow.backupPath && empty.backupFolder === basename(usedWindow.backupPath)))							// skip over restored empty window
470 471 472 473 474 475 476 477 478 479 480 481
					) {
						continue;
					}

					usedWindow.focus();
					focusLastWindow = false;
					break;
				}
			}

			// 3.) finally, always ensure to have at least last used window focused
			if (focusLastWindow) {
482
				usedWindows[usedWindows.length - 1].focus();
483 484
			}
		}
485

486 487
		// Remember in recent document list (unless this opens for extension development)
		// Also do not add paths when files are opened for diffing, only if opened individually
488 489
		const isDiff = fileInputs && fileInputs.filesToDiff.length > 0;
		if (!usedWindows.some(window => window.isExtensionDevelopmentHost) && !isDiff && !openConfig.noRecentEntry) {
M
Martin Aeschlimann 已提交
490 491 492 493 494 495 496 497
			const recents: IRecent[] = [];
			for (let pathToOpen of pathsToOpen) {
				if (pathToOpen.workspace) {
					recents.push({ label: pathToOpen.label, workspace: pathToOpen.workspace });
				} else if (pathToOpen.folderUri) {
					recents.push({ label: pathToOpen.label, folderUri: pathToOpen.folderUri });
				} else if (pathToOpen.fileUri) {
					recents.push({ label: pathToOpen.label, fileUri: pathToOpen.fileUri });
498
				}
499
			}
500
			this.workspacesHistoryMainService.addRecentlyOpened(recents);
501
		}
502

503
		// If we got started with --wait from the CLI, we need to signal to the outside when the window
504 505
		// used for the edit operation is closed or loaded to a different folder so that the waiting
		// process can continue. We do this by deleting the waitMarkerFilePath.
M
Martin Aeschlimann 已提交
506 507
		const waitMarkerFileURI = openConfig.waitMarkerFileURI;
		if (openConfig.context === OpenContext.CLI && waitMarkerFileURI && usedWindows.length === 1 && usedWindows[0]) {
508
			usedWindows[0].whenClosedOrLoaded.then(() => fs.unlink(waitMarkerFileURI.fsPath, _error => undefined));
509 510
		}

511 512 513
		return usedWindows;
	}

514 515 516 517 518 519 520 521 522 523
	private validateOpenConfig(config: IOpenConfiguration): IOpenConfiguration {

		// Make sure addMode is only enabled if we have an active window
		if (config.addMode && (config.initialStartup || !this.getLastActiveWindow())) {
			config.addMode = false;
		}

		return config;
	}

524 525
	private doOpen(
		openConfig: IOpenConfiguration,
526 527
		workspacesToOpen: IWorkspacePathToOpen[],
		foldersToOpen: IFolderPathToOpen[],
528
		emptyToRestore: IEmptyWindowBackupInfo[],
529
		emptyToOpen: number,
530
		fileInputs: IFileInputs | undefined,
531
		foldersToAdd: IFolderPathToOpen[]
532
	) {
533
		const usedWindows: ICodeWindow[] = [];
534

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

538 539
		// Handle folders to add by looking for the last active workspace (not on initial startup)
		if (!openConfig.initialStartup && foldersToAdd.length > 0) {
540
			const authority = foldersToAdd[0].remoteAuthority;
541
			const lastActiveWindow = this.getLastActiveWindowForAuthority(authority);
542
			if (lastActiveWindow) {
543
				usedWindows.push(this.doAddFoldersToExistingWindow(lastActiveWindow, foldersToAdd.map(f => f.folderUri)));
544 545 546
			}
		}

B
Benjamin Pasero 已提交
547
		// 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
548
		const potentialWindowsCount = foldersToOpen.length + workspacesToOpen.length + emptyToRestore.length;
549
		if (potentialWindowsCount === 0 && fileInputs) {
E
Erich Gamma 已提交
550

551
			// Find suitable window or folder path to open files in
552
			const fileToCheck = fileInputs.filesToOpenOrCreate[0] || fileInputs.filesToDiff[0];
553

M
Martin Aeschlimann 已提交
554
			// only look at the windows with correct authority
555
			const windows = WindowsMainService.WINDOWS.filter(window => fileInputs && window.remoteAuthority === fileInputs.remoteAuthority);
556

557
			const bestWindowOrFolder = findBestWindowOrFolderForFile({
558
				windows,
559 560
				newWindow: openFilesInNewWindow,
				context: openConfig.context,
B
Benjamin Pasero 已提交
561
				fileUri: fileToCheck?.fileUri,
562
				localWorkspaceResolver: workspace => workspace.configPath.scheme === Schemas.file ? this.workspacesMainService.resolveLocalWorkspaceSync(workspace.configPath) : null
563
			});
B
Benjamin Pasero 已提交
564

565 566 567 568 569
			// We found a window to open the files in
			if (bestWindowOrFolder instanceof CodeWindow) {

				// Window is workspace
				if (bestWindowOrFolder.openedWorkspace) {
570
					workspacesToOpen.push({ workspace: bestWindowOrFolder.openedWorkspace, remoteAuthority: bestWindowOrFolder.remoteAuthority });
571 572 573
				}

				// Window is single folder
574
				else if (bestWindowOrFolder.openedFolderUri) {
575
					foldersToOpen.push({ folderUri: bestWindowOrFolder.openedFolderUri, remoteAuthority: bestWindowOrFolder.remoteAuthority });
576 577 578 579 580 581
				}

				// Window is empty
				else {

					// Do open files
582
					usedWindows.push(this.doOpenFilesInExistingWindow(openConfig, bestWindowOrFolder, fileInputs));
583 584

					// Reset these because we handled them
R
Rob Lourens 已提交
585
					fileInputs = undefined;
586
				}
587 588 589
			}

			// Finally, if no window or folder is found, just open the files in an empty window
E
Erich Gamma 已提交
590
			else {
B
Benjamin Pasero 已提交
591
				usedWindows.push(this.openInBrowserWindow({
B
Benjamin Pasero 已提交
592 593 594
					userEnv: openConfig.userEnv,
					cli: openConfig.cli,
					initialStartup: openConfig.initialStartup,
595
					fileInputs,
596
					forceNewWindow: true,
M
Martin Aeschlimann 已提交
597
					remoteAuthority: fileInputs.remoteAuthority,
598
					forceNewTabbedWindow: openConfig.forceNewTabbedWindow
B
Benjamin Pasero 已提交
599
				}));
E
Erich Gamma 已提交
600

601
				// Reset these because we handled them
R
Rob Lourens 已提交
602
				fileInputs = undefined;
E
Erich Gamma 已提交
603 604 605
			}
		}

606
		// Handle workspaces to open (instructed and to restore)
607
		const allWorkspacesToOpen = arrays.distinct(workspacesToOpen, workspace => workspace.workspace.id); // prevent duplicates
608 609 610
		if (allWorkspacesToOpen.length > 0) {

			// Check for existing instances
611
			const windowsOnWorkspace = arrays.coalesce(allWorkspacesToOpen.map(workspaceToOpen => findWindowOnWorkspace(WindowsMainService.WINDOWS, workspaceToOpen.workspace)));
612 613
			if (windowsOnWorkspace.length > 0) {
				const windowOnWorkspace = windowsOnWorkspace[0];
B
Benjamin Pasero 已提交
614
				const fileInputsForWindow = (fileInputs?.remoteAuthority === windowOnWorkspace.remoteAuthority) ? fileInputs : undefined;
615 616

				// Do open files
617
				usedWindows.push(this.doOpenFilesInExistingWindow(openConfig, windowOnWorkspace, fileInputsForWindow));
618 619

				// Reset these because we handled them
620
				if (fileInputsForWindow) {
R
Rob Lourens 已提交
621
					fileInputs = undefined;
622
				}
623 624 625 626 627 628

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

			// Open remaining ones
			allWorkspacesToOpen.forEach(workspaceToOpen => {
629
				if (windowsOnWorkspace.some(win => win.openedWorkspace && win.openedWorkspace.id === workspaceToOpen.workspace.id)) {
630 631 632
					return; // ignore folders that are already open
				}

633
				const remoteAuthority = workspaceToOpen.remoteAuthority;
B
Benjamin Pasero 已提交
634
				const fileInputsForWindow = (fileInputs?.remoteAuthority === remoteAuthority) ? fileInputs : undefined;
635

636
				// Do open folder
637
				usedWindows.push(this.doOpenFolderOrWorkspace(openConfig, workspaceToOpen, openFolderInNewWindow, fileInputsForWindow));
638 639

				// Reset these because we handled them
640
				if (fileInputsForWindow) {
R
Rob Lourens 已提交
641
					fileInputs = undefined;
642
				}
643 644 645 646 647

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

648
		// Handle folders to open (instructed and to restore)
649
		const allFoldersToOpen = arrays.distinct(foldersToOpen, folder => extUriBiasedIgnorePathCase.getComparisonKey(folder.folderUri)); // prevent duplicates
650
		if (allFoldersToOpen.length > 0) {
E
Erich Gamma 已提交
651 652

			// Check for existing instances
653
			const windowsOnFolderPath = arrays.coalesce(allFoldersToOpen.map(folderToOpen => findWindowOnWorkspace(WindowsMainService.WINDOWS, folderToOpen.folderUri)));
654
			if (windowsOnFolderPath.length > 0) {
655
				const windowOnFolderPath = windowsOnFolderPath[0];
B
Benjamin Pasero 已提交
656
				const fileInputsForWindow = fileInputs?.remoteAuthority === windowOnFolderPath.remoteAuthority ? fileInputs : undefined;
E
Erich Gamma 已提交
657

658
				// Do open files
659
				usedWindows.push(this.doOpenFilesInExistingWindow(openConfig, windowOnFolderPath, fileInputsForWindow));
660

E
Erich Gamma 已提交
661
				// Reset these because we handled them
662
				if (fileInputsForWindow) {
R
Rob Lourens 已提交
663
					fileInputs = undefined;
664
				}
E
Erich Gamma 已提交
665

B
Benjamin Pasero 已提交
666
				openFolderInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
667 668 669
			}

			// Open remaining ones
670
			allFoldersToOpen.forEach(folderToOpen => {
671

672
				if (windowsOnFolderPath.some(win => extUriBiasedIgnorePathCase.isEqual(win.openedFolderUri, folderToOpen.folderUri))) {
E
Erich Gamma 已提交
673 674 675
					return; // ignore folders that are already open
				}

676
				const remoteAuthority = folderToOpen.remoteAuthority;
B
Benjamin Pasero 已提交
677
				const fileInputsForWindow = (fileInputs?.remoteAuthority === remoteAuthority) ? fileInputs : undefined;
678

679
				// Do open folder
680
				usedWindows.push(this.doOpenFolderOrWorkspace(openConfig, folderToOpen, openFolderInNewWindow, fileInputsForWindow));
E
Erich Gamma 已提交
681 682

				// Reset these because we handled them
683
				if (fileInputsForWindow) {
R
Rob Lourens 已提交
684
					fileInputs = undefined;
685
				}
E
Erich Gamma 已提交
686

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

691
		// Handle empty to restore
692
		const allEmptyToRestore = arrays.distinct(emptyToRestore, info => info.backupFolder); // prevent duplicates
693 694
		if (allEmptyToRestore.length > 0) {
			allEmptyToRestore.forEach(emptyWindowBackupInfo => {
M
Martin Aeschlimann 已提交
695
				const remoteAuthority = emptyWindowBackupInfo.remoteAuthority;
B
Benjamin Pasero 已提交
696
				const fileInputsForWindow = (fileInputs?.remoteAuthority === remoteAuthority) ? fileInputs : undefined;
697

B
Benjamin Pasero 已提交
698
				usedWindows.push(this.openInBrowserWindow({
B
Benjamin Pasero 已提交
699 700 701
					userEnv: openConfig.userEnv,
					cli: openConfig.cli,
					initialStartup: openConfig.initialStartup,
702
					fileInputs: fileInputsForWindow,
M
Martin Aeschlimann 已提交
703
					remoteAuthority,
B
Benjamin Pasero 已提交
704
					forceNewWindow: true,
705
					forceNewTabbedWindow: openConfig.forceNewTabbedWindow,
706
					emptyWindowBackupInfo
B
Benjamin Pasero 已提交
707
				}));
708

B
wip  
Benjamin Pasero 已提交
709
				// Reset these because we handled them
710
				if (fileInputsForWindow) {
R
Rob Lourens 已提交
711
					fileInputs = undefined;
712
				}
B
wip  
Benjamin Pasero 已提交
713

B
Benjamin Pasero 已提交
714
				openFolderInNewWindow = true; // any other folders to open must open in new window then
715 716
			});
		}
B
Benjamin Pasero 已提交
717

718
		// Handle empty to open (only if no other window opened)
719 720 721 722
		if (usedWindows.length === 0 || fileInputs) {
			if (fileInputs && !emptyToOpen) {
				emptyToOpen++;
			}
723

R
Rob Lourens 已提交
724
			const remoteAuthority = fileInputs ? fileInputs.remoteAuthority : (openConfig.cli && openConfig.cli.remote || undefined);
725

726
			for (let i = 0; i < emptyToOpen; i++) {
727
				usedWindows.push(this.doOpenEmpty(openConfig, openFolderInNewWindow, remoteAuthority, fileInputs));
E
Erich Gamma 已提交
728

729
				// Reset these because we handled them
R
Rob Lourens 已提交
730
				fileInputs = undefined;
731
				openFolderInNewWindow = true; // any other window to open must open in new window then
732 733
			}
		}
E
Erich Gamma 已提交
734

735
		return arrays.distinct(usedWindows);
E
Erich Gamma 已提交
736 737
	}

738
	private doOpenFilesInExistingWindow(configuration: IOpenConfiguration, window: ICodeWindow, fileInputs?: IFileInputs): ICodeWindow {
739 740
		window.focus(); // make sure window has focus

741
		const params: { filesToOpenOrCreate?: IPath[], filesToDiff?: IPath[], filesToWait?: IPathsToWaitFor, termProgram?: string } = {};
B
Benjamin Pasero 已提交
742
		if (fileInputs) {
743
			params.filesToOpenOrCreate = fileInputs.filesToOpenOrCreate;
B
Benjamin Pasero 已提交
744 745 746 747 748 749 750 751 752
			params.filesToDiff = fileInputs.filesToDiff;
			params.filesToWait = fileInputs.filesToWait;
		}

		if (configuration.userEnv) {
			params.termProgram = configuration.userEnv['TERM_PROGRAM'];
		}

		window.sendWhenReady('vscode:openFiles', params);
B
Benjamin Pasero 已提交
753 754

		return window;
755 756
	}

757
	private doAddFoldersToExistingWindow(window: ICodeWindow, foldersToAdd: URI[]): ICodeWindow {
758 759
		window.focus(); // make sure window has focus

B
Benjamin Pasero 已提交
760 761 762
		const request: IAddFoldersRequest = { foldersToAdd };

		window.sendWhenReady('vscode:addFolders', request);
763 764 765 766

		return window;
	}

767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
	private doOpenEmpty(openConfig: IOpenConfiguration, forceNewWindow: boolean, remoteAuthority: string | undefined, fileInputs: IFileInputs | undefined, windowToUse?: ICodeWindow): ICodeWindow {
		if (!forceNewWindow && !windowToUse && typeof openConfig.contextWindowId === 'number') {
			windowToUse = this.getWindowById(openConfig.contextWindowId); // fix for https://github.com/microsoft/vscode/issues/97172
		}

		return this.openInBrowserWindow({
			userEnv: openConfig.userEnv,
			cli: openConfig.cli,
			initialStartup: openConfig.initialStartup,
			remoteAuthority,
			forceNewWindow,
			forceNewTabbedWindow: openConfig.forceNewTabbedWindow,
			fileInputs,
			windowToUse
		});
	}

M
Matt Bierner 已提交
784
	private doOpenFolderOrWorkspace(openConfig: IOpenConfiguration, folderOrWorkspace: IPathToOpen, forceNewWindow: boolean, fileInputs: IFileInputs | undefined, windowToUse?: ICodeWindow): ICodeWindow {
B
Benjamin Pasero 已提交
785 786 787 788
		if (!forceNewWindow && !windowToUse && typeof openConfig.contextWindowId === 'number') {
			windowToUse = this.getWindowById(openConfig.contextWindowId); // fix for https://github.com/Microsoft/vscode/issues/49587
		}

789
		return this.openInBrowserWindow({
790 791 792
			userEnv: openConfig.userEnv,
			cli: openConfig.cli,
			initialStartup: openConfig.initialStartup,
793
			workspace: folderOrWorkspace.workspace,
794
			folderUri: folderOrWorkspace.folderUri,
795
			fileInputs,
M
Martin Aeschlimann 已提交
796
			remoteAuthority: folderOrWorkspace.remoteAuthority,
B
Benjamin Pasero 已提交
797
			forceNewWindow,
798
			forceNewTabbedWindow: openConfig.forceNewTabbedWindow,
799
			windowToUse
800 801 802
		});
	}

B
Benjamin Pasero 已提交
803 804
	private getPathsToOpen(openConfig: IOpenConfiguration): IPathToOpen[] {
		let windowsToOpen: IPathToOpen[];
805
		let isCommandLineOrAPICall = false;
E
Erich Gamma 已提交
806

807
		// Extract paths: from API
S
Sandeep Somavarapu 已提交
808
		if (openConfig.urisToOpen && openConfig.urisToOpen.length > 0) {
809
			windowsToOpen = this.doExtractPathsFromAPI(openConfig);
810
			isCommandLineOrAPICall = true;
E
Erich Gamma 已提交
811 812
		}

B
Benjamin Pasero 已提交
813 814
		// Check for force empty
		else if (openConfig.forceEmpty) {
815
			windowsToOpen = [Object.create(null)];
E
Erich Gamma 已提交
816 817
		}

818
		// Extract paths: from CLI
819
		else if (openConfig.cli._.length || openConfig.cli['folder-uri'] || openConfig.cli['file-uri']) {
820
			windowsToOpen = this.doExtractPathsFromCLI(openConfig.cli);
821
			isCommandLineOrAPICall = true;
B
Benjamin Pasero 已提交
822 823
		}

824
		// Extract windows: from previous session
B
Benjamin Pasero 已提交
825
		else {
826
			windowsToOpen = this.doGetWindowsFromLastSession();
B
Benjamin Pasero 已提交
827 828
		}

829 830
		// Convert multiple folders into workspace (if opened via API or CLI)
		// This will ensure to open these folders in one window instead of multiple
831 832
		// If we are in addMode, we should not do this because in that case all
		// folders should be added to the existing window.
833
		if (!openConfig.addMode && isCommandLineOrAPICall) {
834
			const foldersToOpen = windowsToOpen.filter(path => !!path.folderUri);
835
			if (foldersToOpen.length > 1) {
836
				const remoteAuthority = foldersToOpen[0].remoteAuthority;
837 838 839 840 841 842 843
				if (foldersToOpen.every(f => f.remoteAuthority === remoteAuthority)) { // only if all folder have the same authority
					const workspace = this.workspacesMainService.createUntitledWorkspaceSync(foldersToOpen.map(folder => ({ uri: folder.folderUri! })));

					// Add workspace and remove folders thereby
					windowsToOpen.push({ workspace, remoteAuthority });
					windowsToOpen = windowsToOpen.filter(path => !path.folderUri);
				}
844 845 846
			}
		}

847
		return windowsToOpen;
E
Erich Gamma 已提交
848 849
	}

850
	private doExtractPathsFromAPI(openConfig: IOpenConfiguration): IPathToOpen[] {
M
Matt Bierner 已提交
851
		const pathsToOpen: IPathToOpen[] = [];
852
		const parseOptions: IPathParseOptions = { gotoLineMode: openConfig.gotoLineMode };
M
Matt Bierner 已提交
853
		for (const pathToOpen of openConfig.urisToOpen || []) {
M
Martin Aeschlimann 已提交
854 855 856 857
			if (!pathToOpen) {
				continue;
			}

M
Martin Aeschlimann 已提交
858
			const path = this.parseUri(pathToOpen, parseOptions);
M
Martin Aeschlimann 已提交
859
			if (path) {
M
Martin Aeschlimann 已提交
860
				path.label = pathToOpen.label;
M
Martin Aeschlimann 已提交
861 862
				pathsToOpen.push(path);
			} else {
863 864
				const uri = this.resourceFromURIToOpen(pathToOpen);

B
Benjamin Pasero 已提交
865
				// Warn about the invalid URI or path
M
Martin Aeschlimann 已提交
866
				let message, detail;
M
Martin Aeschlimann 已提交
867
				if (uri.scheme === Schemas.file) {
M
Martin Aeschlimann 已提交
868
					message = localize('pathNotExistTitle', "Path does not exist");
869
					detail = localize('pathNotExistDetail', "The path '{0}' does not seem to exist anymore on disk.", getPathLabel(uri.fsPath, this.environmentService));
M
Martin Aeschlimann 已提交
870 871
				} else {
					message = localize('uriInvalidTitle', "URI can not be opened");
M
Martin Aeschlimann 已提交
872
					detail = localize('uriInvalidDetail', "The URI '{0}' is not valid and can not be opened.", uri.toString());
M
Martin Aeschlimann 已提交
873
				}
874

875
				const options: MessageBoxOptions = {
876 877
					title: product.nameLong,
					type: 'info',
878
					buttons: [localize('ok', "OK")],
M
Martin Aeschlimann 已提交
879 880
					message,
					detail,
881 882 883
					noLink: true
				};

884
				this.dialogMainService.showMessageBox(options, withNullAsUndefined(BrowserWindow.getFocusedWindow()));
885
			}
M
Martin Aeschlimann 已提交
886
		}
887 888 889
		return pathsToOpen;
	}

890
	private doExtractPathsFromCLI(cli: NativeParsedArgs): IPath[] {
M
Matt Bierner 已提交
891
		const pathsToOpen: IPathToOpen[] = [];
R
Rob Lourens 已提交
892
		const parseOptions: IPathParseOptions = { ignoreFileNotFound: true, gotoLineMode: cli.goto, remoteAuthority: cli.remote || undefined };
893 894

		// folder uris
895 896 897 898 899 900 901 902 903
		const folderUris = cli['folder-uri'];
		if (folderUris) {
			for (let f of folderUris) {
				const folderUri = this.argToUri(f);
				if (folderUri) {
					const path = this.parseUri({ folderUri }, parseOptions);
					if (path) {
						pathsToOpen.push(path);
					}
M
Martin Aeschlimann 已提交
904
				}
M
Martin Aeschlimann 已提交
905
			}
906 907
		}

908

909
		// file uris
910 911 912 913 914 915 916 917 918
		const fileUris = cli['file-uri'];
		if (fileUris) {
			for (let f of fileUris) {
				const fileUri = this.argToUri(f);
				if (fileUri) {
					const path = this.parseUri(hasWorkspaceFileExtension(f) ? { workspaceUri: fileUri } : { fileUri }, parseOptions);
					if (path) {
						pathsToOpen.push(path);
					}
M
Martin Aeschlimann 已提交
919
				}
M
Martin Aeschlimann 已提交
920
			}
921 922 923
		}

		// folder or file paths
924
		const cliArgs = cli._;
M
Martin Aeschlimann 已提交
925 926 927 928 929
		for (let cliArg of cliArgs) {
			const path = this.parsePath(cliArg, parseOptions);
			if (path) {
				pathsToOpen.push(path);
			}
930 931
		}

M
Martin Aeschlimann 已提交
932
		if (pathsToOpen.length) {
933
			return pathsToOpen;
B
Benjamin Pasero 已提交
934 935 936 937 938 939
		}

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

B
Benjamin Pasero 已提交
940
	private doGetWindowsFromLastSession(): IPathToOpen[] {
941
		const restoreWindows = this.getRestoreWindowsSetting();
B
Benjamin Pasero 已提交
942

943
		switch (restoreWindows) {
B
Benjamin Pasero 已提交
944

945
			// none: we always open an empty window
946 947
			case 'none':
				return [Object.create(null)];
B
Benjamin Pasero 已提交
948

949
			// one: restore last opened workspace/folder or empty window
950 951
			// all: restore all windows
			// folders: restore last opened folders only
952
			case 'one':
953 954
			case 'all':
			case 'folders':
955 956 957
				const openedWindows: IWindowState[] = [];
				if (restoreWindows !== 'one') {
					openedWindows.push(...this.windowsState.openedWindows);
958
				}
959 960
				if (this.windowsState.lastActiveWindow) {
					openedWindows.push(this.windowsState.lastActiveWindow);
961
				}
962

963 964 965
				const windowsToOpen: IPathToOpen[] = [];
				for (const openedWindow of openedWindows) {
					if (openedWindow.workspace) { // Workspaces
M
Martin Aeschlimann 已提交
966
						const pathToOpen = this.parseUri({ workspaceUri: openedWindow.workspace.configPath }, { remoteAuthority: openedWindow.remoteAuthority });
B
Benjamin Pasero 已提交
967
						if (pathToOpen?.workspace) {
968 969 970
							windowsToOpen.push(pathToOpen);
						}
					} else if (openedWindow.folderUri) { // Folders
M
Martin Aeschlimann 已提交
971
						const pathToOpen = this.parseUri({ folderUri: openedWindow.folderUri }, { remoteAuthority: openedWindow.remoteAuthority });
B
Benjamin Pasero 已提交
972
						if (pathToOpen?.folderUri) {
973 974
							windowsToOpen.push(pathToOpen);
						}
975
					} else if (restoreWindows !== 'folders' && openedWindow.backupPath && !openedWindow.remoteAuthority) { // Local windows that were empty. Empty windows with backups will always be restored in open()
M
Martin Aeschlimann 已提交
976
						windowsToOpen.push({ backupPath: openedWindow.backupPath, remoteAuthority: openedWindow.remoteAuthority });
977
					}
978 979 980 981 982 983 984
				}

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

				break;
B
Benjamin Pasero 已提交
985
		}
E
Erich Gamma 已提交
986

987
		// Always fallback to empty window
B
Benjamin Pasero 已提交
988
		return [Object.create(null)];
E
Erich Gamma 已提交
989 990
	}

991 992
	private getRestoreWindowsSetting(): RestoreWindowsSetting {
		let restoreWindows: RestoreWindowsSetting;
993
		if (this.lifecycleMainService.wasRestarted) {
994 995
			restoreWindows = 'all'; // always reopen all windows when an update was applied
		} else {
996
			const windowConfig = this.configurationService.getValue<IWindowSettings>('window');
B
Benjamin Pasero 已提交
997
			restoreWindows = windowConfig?.restoreWindows || 'all'; // by default restore all windows
998

999
			if (!['all', 'folders', 'one', 'none'].includes(restoreWindows)) {
B
Benjamin Pasero 已提交
1000
				restoreWindows = 'all'; // by default restore all windows
1001 1002 1003 1004 1005 1006
			}
		}

		return restoreWindows;
	}

1007
	private argToUri(arg: string): URI | undefined {
M
Martin Aeschlimann 已提交
1008
		try {
1009
			const uri = URI.parse(arg);
M
Martin Aeschlimann 已提交
1010
			if (!uri.scheme) {
M
Martin Aeschlimann 已提交
1011
				this.logService.error(`Invalid URI input string, scheme missing: ${arg}`);
1012
				return undefined;
M
Martin Aeschlimann 已提交
1013
			}
1014

M
Martin Aeschlimann 已提交
1015 1016
			return uri;
		} catch (e) {
M
Martin Aeschlimann 已提交
1017
			this.logService.error(`Invalid URI input string: ${arg}, ${e.message}`);
1018
		}
1019

1020
		return undefined;
1021 1022
	}

1023 1024
	private parseUri(toOpen: IWindowOpenable, options: IPathParseOptions = {}): IPathToOpen | undefined {
		if (!toOpen) {
1025
			return undefined;
1026
		}
1027

1028
		let uri = this.resourceFromURIToOpen(toOpen);
M
Martin Aeschlimann 已提交
1029
		if (uri.scheme === Schemas.file) {
1030
			return this.parsePath(uri.fsPath, options, isFileToOpen(toOpen));
1031
		}
M
Martin Aeschlimann 已提交
1032 1033

		// open remote if either specified in the cli or if it's a remotehost URI
1034
		const remoteAuthority = options.remoteAuthority || getRemoteAuthority(uri);
M
Martin Aeschlimann 已提交
1035

1036 1037
		// normalize URI
		uri = normalizePath(uri);
1038 1039

		// remove trailing slash
1040
		uri = removeTrailingPathSeparator(uri);
1041

1042 1043
		// File
		if (isFileToOpen(toOpen)) {
1044
			if (options.gotoLineMode) {
1045 1046 1047 1048
				const parsedPath = parseLineAndColumnAware(uri.path);
				return {
					fileUri: uri.with({ path: parsedPath.path }),
					lineNumber: parsedPath.line,
M
Martin Aeschlimann 已提交
1049 1050
					columnNumber: parsedPath.column,
					remoteAuthority
1051 1052
				};
			}
1053

1054
			return {
M
Martin Aeschlimann 已提交
1055 1056
				fileUri: uri,
				remoteAuthority
1057
			};
1058 1059 1060 1061
		}

		// Workspace
		else if (isWorkspaceToOpen(toOpen)) {
M
Martin Aeschlimann 已提交
1062 1063 1064 1065
			return {
				workspace: getWorkspaceIdentifier(uri),
				remoteAuthority
			};
1066
		}
1067 1068

		// Folder
1069
		return {
M
Martin Aeschlimann 已提交
1070 1071
			folderUri: uri,
			remoteAuthority
1072 1073 1074
		};
	}

1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
	private resourceFromURIToOpen(openable: IWindowOpenable): URI {
		if (isWorkspaceToOpen(openable)) {
			return openable.workspaceUri;
		}

		if (isFolderToOpen(openable)) {
			return openable.folderUri;
		}

		return openable.fileUri;
	}

M
Martin Aeschlimann 已提交
1087
	private parsePath(anyPath: string, options: IPathParseOptions, forceOpenWorkspaceAsFile?: boolean): IPathToOpen | undefined {
E
Erich Gamma 已提交
1088
		if (!anyPath) {
1089
			return undefined;
E
Erich Gamma 已提交
1090 1091
		}

1092
		let lineNumber, columnNumber: number | undefined;
1093

1094
		if (options.gotoLineMode) {
1095 1096 1097
			const parsedPath = parseLineAndColumnAware(anyPath);
			lineNumber = parsedPath.line;
			columnNumber = parsedPath.column;
1098

E
Erich Gamma 已提交
1099 1100 1101
			anyPath = parsedPath.path;
		}

1102
		// open remote if either specified in the cli even if it is a local file.
1103
		const remoteAuthority = options.remoteAuthority;
M
Martin Aeschlimann 已提交
1104

1105 1106
		if (remoteAuthority) {
			const first = anyPath.charCodeAt(0);
1107

1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
			// make absolute
			if (first !== CharCode.Slash) {
				if (isWindowsDriveLetter(first) && anyPath.charCodeAt(anyPath.charCodeAt(1)) === CharCode.Colon) {
					anyPath = toSlashes(anyPath);
				}
				anyPath = '/' + anyPath;
			}

			const uri = URI.from({ scheme: Schemas.vscodeRemote, authority: remoteAuthority, path: anyPath });

1118 1119 1120 1121 1122 1123
			// guess the file type: If it ends with a slash it's a folder. If it has a file extension, it's a file or a workspace. By defaults it's a folder.
			if (anyPath.charCodeAt(anyPath.length - 1) !== CharCode.Slash) {
				if (hasWorkspaceFileExtension(anyPath)) {
					if (forceOpenWorkspaceAsFile) {
						return { fileUri: uri, remoteAuthority };
					}
1124
				} else if (posix.basename(anyPath).indexOf('.') !== -1) { // file name starts with a dot or has an file extension
1125 1126 1127 1128 1129 1130 1131 1132
					return { fileUri: uri, remoteAuthority };
				}
			}
			return { folderUri: uri, remoteAuthority };
		}

		let candidate = normalize(anyPath);

E
Erich Gamma 已提交
1133
		try {
1134

B
Benjamin Pasero 已提交
1135
			const candidateStat = fs.statSync(candidate);
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
			if (candidateStat.isFile()) {

				// Workspace (unless disabled via flag)
				if (!forceOpenWorkspaceAsFile) {
					const workspace = this.workspacesMainService.resolveLocalWorkspaceSync(URI.file(candidate));
					if (workspace) {
						return {
							workspace: { id: workspace.id, configPath: workspace.configPath },
							remoteAuthority: workspace.remoteAuthority,
							exists: true
						};
1147
					}
1148 1149
				}

1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
				// File
				return {
					fileUri: URI.file(candidate),
					lineNumber,
					columnNumber,
					remoteAuthority,
					exists: true
				};
			}

			// Folder (we check for isDirectory() because e.g. paths like /dev/null
			// are neither file nor folder but some external tools might pass them
			// over to us)
			else if (candidateStat.isDirectory()) {
				return {
					folderUri: URI.file(candidate),
					remoteAuthority,
					exists: true
				};
E
Erich Gamma 已提交
1169 1170
			}
		} catch (error) {
S
Sandeep Somavarapu 已提交
1171
			const fileUri = URI.file(candidate);
B
Benjamin Pasero 已提交
1172
			this.workspacesHistoryMainService.removeRecentlyOpened([fileUri]); // since file does not seem to exist anymore, remove from recent
1173 1174

			// assume this is a file that does not yet exist
B
Benjamin Pasero 已提交
1175
			if (options?.ignoreFileNotFound) {
1176 1177 1178 1179 1180
				return {
					fileUri,
					remoteAuthority,
					exists: false
				};
E
Erich Gamma 已提交
1181 1182 1183
			}
		}

1184
		return undefined;
E
Erich Gamma 已提交
1185 1186
	}

B
Benjamin Pasero 已提交
1187 1188 1189
	private shouldOpenNewWindow(openConfig: IOpenConfiguration): { openFolderInNewWindow: boolean; openFilesInNewWindow: boolean; } {

		// let the user settings override how folders are open in a new window or same window unless we are forced
1190
		const windowConfig = this.configurationService.getValue<IWindowSettings>('window');
B
Benjamin Pasero 已提交
1191 1192
		const openFolderInNewWindowConfig = windowConfig?.openFoldersInNewWindow || 'default' /* default */;
		const openFilesInNewWindowConfig = windowConfig?.openFilesInNewWindow || 'off' /* default */;
1193

B
Benjamin Pasero 已提交
1194
		let openFolderInNewWindow = (openConfig.preferNewWindow || openConfig.forceNewWindow) && !openConfig.forceReuseWindow;
1195 1196
		if (!openConfig.forceNewWindow && !openConfig.forceReuseWindow && (openFolderInNewWindowConfig === 'on' || openFolderInNewWindowConfig === 'off')) {
			openFolderInNewWindow = (openFolderInNewWindowConfig === 'on');
B
Benjamin Pasero 已提交
1197 1198 1199
		}

		// 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)
M
Matt Bierner 已提交
1200
		let openFilesInNewWindow: boolean = false;
B
Benjamin Pasero 已提交
1201
		if (openConfig.forceNewWindow || openConfig.forceReuseWindow) {
M
Matt Bierner 已提交
1202
			openFilesInNewWindow = !!openConfig.forceNewWindow && !openConfig.forceReuseWindow;
B
Benjamin Pasero 已提交
1203
		} else {
1204 1205 1206 1207 1208 1209 1210 1211

			// macOS: by default we open files in a new window if this is triggered via DOCK context
			if (isMacintosh) {
				if (openConfig.context === OpenContext.DOCK) {
					openFilesInNewWindow = true;
				}
			}

1212 1213
			// Linux/Windows: by default we open files in the new window unless triggered via DIALOG / MENU context
			// or from the integrated terminal where we assume the user prefers to open in the current window
1214
			else {
1215
				if (openConfig.context !== OpenContext.DIALOG && openConfig.context !== OpenContext.MENU && !(openConfig.userEnv && openConfig.userEnv['TERM_PROGRAM'] === 'vscode')) {
1216 1217
					openFilesInNewWindow = true;
				}
B
Benjamin Pasero 已提交
1218 1219
			}

1220
			// finally check for overrides of default
1221 1222
			if (!openConfig.cli.extensionDevelopmentPath && (openFilesInNewWindowConfig === 'on' || openFilesInNewWindowConfig === 'off')) {
				openFilesInNewWindow = (openFilesInNewWindowConfig === 'on');
B
Benjamin Pasero 已提交
1223 1224 1225
			}
		}

M
Matt Bierner 已提交
1226
		return { openFolderInNewWindow: !!openFolderInNewWindow, openFilesInNewWindow };
B
Benjamin Pasero 已提交
1227 1228
	}

1229
	openExtensionDevelopmentHostWindow(extensionDevelopmentPath: string[], openConfig: IOpenConfiguration): ICodeWindow[] {
E
Erich Gamma 已提交
1230

B
Benjamin Pasero 已提交
1231 1232 1233
		// Reload an existing extension development host window on the same path
		// We currently do not allow more than one extension development window
		// on the same extension path.
1234
		const existingWindow = findWindowOnExtensionDevelopmentPath(WindowsMainService.WINDOWS, extensionDevelopmentPath);
1235
		if (existingWindow) {
1236
			this.lifecycleMainService.reload(existingWindow, openConfig.cli);
1237
			existingWindow.focus(); // make sure it gets focus and is restored
E
Erich Gamma 已提交
1238

1239
			return [existingWindow];
B
Benjamin Pasero 已提交
1240
		}
1241 1242
		let folderUris = openConfig.cli['folder-uri'] || [];
		let fileUris = openConfig.cli['file-uri'] || [];
1243
		let cliArgs = openConfig.cli._;
E
Erich Gamma 已提交
1244

1245
		// Fill in previously opened workspace unless an explicit path is provided and we are not unit testing
1246
		if (!cliArgs.length && !folderUris.length && !fileUris.length && !openConfig.cli.extensionTestsPath) {
1247
			const extensionDevelopmentWindowState = this.windowsState.lastPluginDevelopmentHostWindow;
1248
			const workspaceToOpen = extensionDevelopmentWindowState && (extensionDevelopmentWindowState.workspace || extensionDevelopmentWindowState.folderUri);
1249
			if (workspaceToOpen) {
1250
				if (isSingleFolderWorkspaceIdentifier(workspaceToOpen)) {
1251
					if (workspaceToOpen.scheme === Schemas.file) {
1252
						cliArgs = [workspaceToOpen.fsPath];
1253
					} else {
1254
						folderUris = [workspaceToOpen.toString()];
1255 1256
					}
				} else {
M
Martin Aeschlimann 已提交
1257
					if (workspaceToOpen.configPath.scheme === Schemas.file) {
1258
						cliArgs = [originalFSPath(workspaceToOpen.configPath)];
M
Martin Aeschlimann 已提交
1259
					} else {
1260
						fileUris = [workspaceToOpen.configPath.toString()];
M
Martin Aeschlimann 已提交
1261
					}
1262
				}
E
Erich Gamma 已提交
1263 1264 1265
			}
		}

1266 1267 1268 1269 1270
		let authority = '';
		for (let p of extensionDevelopmentPath) {
			if (p.match(/^[a-zA-Z][a-zA-Z0-9\+\-\.]+:/)) {
				const url = URI.parse(p);
				if (url.scheme === Schemas.vscodeRemote) {
1271
					if (authority) {
1272 1273
						if (url.authority !== authority) {
							this.logService.error('more than one extension development path authority');
1274 1275
						}
					} else {
1276
						authority = url.authority;
1277 1278 1279
					}
				}
			}
1280 1281 1282 1283 1284 1285 1286 1287
		}

		// Make sure that we do not try to open:
		// - a workspace or folder that is already opened
		// - a workspace or file that has a different authority as the extension development.

		cliArgs = cliArgs.filter(path => {
			const uri = URI.file(path);
1288
			if (!!findWindowOnWorkspaceOrFolderUri(WindowsMainService.WINDOWS, uri)) {
1289
				return false;
1290
			}
1291 1292
			return uri.authority === authority;
		});
1293

1294 1295
		folderUris = folderUris.filter(uri => {
			const u = this.argToUri(uri);
1296
			if (!!findWindowOnWorkspaceOrFolderUri(WindowsMainService.WINDOWS, u)) {
1297 1298 1299 1300 1301 1302 1303
				return false;
			}
			return u ? u.authority === authority : false;
		});

		fileUris = fileUris.filter(uri => {
			const u = this.argToUri(uri);
1304
			if (!!findWindowOnWorkspaceOrFolderUri(WindowsMainService.WINDOWS, u)) {
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
				return false;
			}
			return u ? u.authority === authority : false;
		});

		openConfig.cli._ = cliArgs;
		openConfig.cli['folder-uri'] = folderUris;
		openConfig.cli['file-uri'] = fileUris;

		// if there are no files or folders cli args left, use the "remote" cli argument
1315 1316 1317
		const noFilesOrFolders = !cliArgs.length && !folderUris.length && !fileUris.length;
		if (noFilesOrFolders && authority) {
			openConfig.cli.remote = authority;
1318 1319
		}

B
Benjamin Pasero 已提交
1320
		// Open it
M
Martin Aeschlimann 已提交
1321 1322 1323 1324
		const openArgs: IOpenConfiguration = {
			context: openConfig.context,
			cli: openConfig.cli,
			forceNewWindow: true,
1325
			forceEmpty: noFilesOrFolders,
M
Martin Aeschlimann 已提交
1326 1327 1328 1329
			userEnv: openConfig.userEnv,
			noRecentEntry: true,
			waitMarkerFileURI: openConfig.waitMarkerFileURI
		};
1330 1331

		return this.open(openArgs);
E
Erich Gamma 已提交
1332 1333
	}

1334
	private openInBrowserWindow(options: IOpenBrowserWindowOptions): ICodeWindow {
1335

1336 1337
		// Build INativeWindowConfiguration from config and options
		const configuration: INativeWindowConfiguration = mixin({}, options.cli); // inherit all properties from CLI
B
Benjamin Pasero 已提交
1338
		configuration.appRoot = this.environmentService.appRoot;
1339
		configuration.machineId = this.machineId;
1340
		configuration.nodeCachedDataDir = this.environmentService.nodeCachedDataDir;
1341
		configuration.mainPid = process.pid;
B
Benjamin Pasero 已提交
1342
		configuration.execPath = process.execPath;
1343
		configuration.userEnv = { ...this.initialUserEnv, ...options.userEnv };
B
Benjamin Pasero 已提交
1344
		configuration.isInitialStartup = options.initialStartup;
1345
		configuration.workspace = options.workspace;
1346
		configuration.folderUri = options.folderUri;
M
Martin Aeschlimann 已提交
1347
		configuration.remoteAuthority = options.remoteAuthority;
1348 1349 1350

		const fileInputs = options.fileInputs;
		if (fileInputs) {
1351
			configuration.filesToOpenOrCreate = fileInputs.filesToOpenOrCreate;
1352 1353 1354
			configuration.filesToDiff = fileInputs.filesToDiff;
			configuration.filesToWait = fileInputs.filesToWait;
		}
B
Benjamin Pasero 已提交
1355

1356
		// if we know the backup folder upfront (for empty windows to restore), we can set it
1357
		// directly here which helps for restoring UI state associated with that window.
B
Benjamin Pasero 已提交
1358
		// For all other cases we first call into registerEmptyWindowBackupSync() to set it before
1359
		// loading the window.
1360
		if (options.emptyWindowBackupInfo) {
S
Sandeep Somavarapu 已提交
1361
			configuration.backupPath = join(this.environmentService.backupHome.fsPath, options.emptyWindowBackupInfo.backupFolder);
1362 1363
		}

1364
		let window: ICodeWindow | undefined;
1365
		if (!options.forceNewWindow && !options.forceNewTabbedWindow) {
1366 1367 1368
			window = options.windowToUse || this.getLastActiveWindow();
			if (window) {
				window.focus();
E
Erich Gamma 已提交
1369 1370 1371 1372
			}
		}

		// New window
1373
		if (!window) {
1374
			const windowConfig = this.configurationService.getValue<IWindowSettings>('window');
1375 1376 1377 1378 1379
			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) {
S
SteVen Batten 已提交
1380
				allowFullscreen = (windowConfig?.newWindowDimensions && ['fullscreen', 'inherit', 'offset'].indexOf(windowConfig.newWindowDimensions) >= 0);
1381 1382 1383 1384
			}

			// Window state is from a previous session: only allow fullscreen when we got updated or user wants to restore
			else {
B
Benjamin Pasero 已提交
1385
				allowFullscreen = this.lifecycleMainService.wasRestarted || windowConfig?.restoreFullscreen;
B
Benjamin Pasero 已提交
1386 1387 1388 1389 1390 1391 1392 1393 1394

				if (allowFullscreen && isMacintosh && WindowsMainService.WINDOWS.some(win => win.isFullScreen)) {
					// macOS: Electron does not allow to restore multiple windows in
					// fullscreen. As such, if we already restored a window in that
					// state, we cannot allow more fullscreen windows. See
					// https://github.com/microsoft/vscode/issues/41691 and
					// https://github.com/electron/electron/issues/13077
					allowFullscreen = false;
				}
1395 1396 1397 1398 1399
			}

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

1401
			// Create the window
1402
			const createdWindow = window = this.instantiationService.createInstance(CodeWindow, {
1403
				state,
1404
				extensionDevelopmentPath: configuration.extensionDevelopmentPath,
1405
				isExtensionTestHost: !!configuration.extensionTestsPath
1406
			});
1407

1408 1409 1410 1411
			// Add as window tab if configured (macOS only)
			if (options.forceNewTabbedWindow) {
				const activeWindow = this.getLastActiveWindow();
				if (activeWindow) {
1412
					activeWindow.addTabbedWindow(createdWindow);
1413 1414 1415
				}
			}

B
Benjamin Pasero 已提交
1416
			// Add to our list of windows
1417
			WindowsMainService.WINDOWS.push(createdWindow);
E
Erich Gamma 已提交
1418

B
Benjamin Pasero 已提交
1419
			// Indicate number change via event
1420
			this._onWindowsCountChanged.fire({ oldCount: WindowsMainService.WINDOWS.length - 1, newCount: WindowsMainService.WINDOWS.length });
B
Benjamin Pasero 已提交
1421

E
Erich Gamma 已提交
1422
			// Window Events
1423 1424 1425 1426 1427
			once(createdWindow.onReady)(() => this._onWindowReady.fire(createdWindow));
			once(createdWindow.onClose)(() => this.onWindowClosed(createdWindow));
			once(createdWindow.onDestroy)(() => this.onBeforeWindowClose(createdWindow)); // try to save state before destroy because close will not fire
			createdWindow.win.webContents.removeAllListeners('devtools-reload-page'); // remove built in listener so we can handle this on our own
			createdWindow.win.webContents.on('devtools-reload-page', () => this.lifecycleMainService.reload(createdWindow));
E
Erich Gamma 已提交
1428 1429

			// Lifecycle
1430
			(this.lifecycleMainService as LifecycleMainService).registerWindow(createdWindow);
E
Erich Gamma 已提交
1431 1432 1433 1434 1435 1436
		}

		// Existing window
		else {

			// Some configuration things get inherited if the window is being reused and we are
B
Benjamin Pasero 已提交
1437
			// in extension development host mode. These options are all development related.
1438
			const currentWindowConfig = window.config;
A
Alex Dima 已提交
1439 1440
			if (!configuration.extensionDevelopmentPath && currentWindowConfig && !!currentWindowConfig.extensionDevelopmentPath) {
				configuration.extensionDevelopmentPath = currentWindowConfig.extensionDevelopmentPath;
B
Benjamin Pasero 已提交
1441
				configuration.verbose = currentWindowConfig.verbose;
1442
				configuration['inspect-brk-extensions'] = currentWindowConfig['inspect-brk-extensions'];
1443
				configuration.debugId = currentWindowConfig.debugId;
1444
				configuration['inspect-extensions'] = currentWindowConfig['inspect-extensions'];
1445
				configuration['extensions-dir'] = currentWindowConfig['extensions-dir'];
E
Erich Gamma 已提交
1446 1447 1448
			}
		}

1449 1450 1451 1452
		// If the window was already loaded, make sure to unload it
		// first and only load the new configuration if that was
		// not vetoed
		if (window.isReady) {
1453
			this.lifecycleMainService.unload(window, UnloadReason.LOAD).then(veto => {
1454
				if (!veto) {
M
Matt Bierner 已提交
1455
					this.doOpenInBrowserWindow(window!, configuration, options);
B
Benjamin Pasero 已提交
1456
				}
1457 1458 1459 1460 1461 1462 1463
			});
		} else {
			this.doOpenInBrowserWindow(window, configuration, options);
		}

		return window;
	}
B
Benjamin Pasero 已提交
1464

1465
	private doOpenInBrowserWindow(window: ICodeWindow, configuration: INativeWindowConfiguration, options: IOpenBrowserWindowOptions): void {
1466

1467 1468 1469
		// Register window for backups
		if (!configuration.extensionDevelopmentPath) {
			if (configuration.workspace) {
1470
				configuration.backupPath = this.backupMainService.registerWorkspaceBackupSync({ workspace: configuration.workspace, remoteAuthority: configuration.remoteAuthority });
1471 1472 1473 1474
			} else if (configuration.folderUri) {
				configuration.backupPath = this.backupMainService.registerFolderBackupSync(configuration.folderUri);
			} else {
				const backupFolder = options.emptyWindowBackupInfo && options.emptyWindowBackupInfo.backupFolder;
1475
				configuration.backupPath = this.backupMainService.registerEmptyWindowBackupSync(backupFolder, configuration.remoteAuthority);
E
Erich Gamma 已提交
1476
			}
1477
		}
1478

1479 1480
		// Load it
		window.load(configuration);
E
Erich Gamma 已提交
1481 1482
	}

1483
	private getNewWindowState(configuration: INativeWindowConfiguration): INewWindowState {
1484
		const lastActive = this.getLastActiveWindow();
E
Erich Gamma 已提交
1485

1486 1487
		// Restore state unless we are running extension tests
		if (!configuration.extensionTestsPath) {
E
Erich Gamma 已提交
1488

1489 1490 1491
			// extension development host Window - load from stored settings if any
			if (!!configuration.extensionDevelopmentPath && this.windowsState.lastPluginDevelopmentHostWindow) {
				return this.windowsState.lastPluginDevelopmentHostWindow.uiState;
1492 1493
			}

1494
			// Known Workspace - load from stored settings
M
Matt Bierner 已提交
1495 1496 1497
			const workspace = configuration.workspace;
			if (workspace) {
				const stateForWorkspace = this.windowsState.openedWindows.filter(o => o.workspace && o.workspace.id === workspace.id).map(o => o.uiState);
1498 1499 1500 1501 1502 1503
				if (stateForWorkspace.length) {
					return stateForWorkspace[0];
				}
			}

			// Known Folder - load from stored settings
1504
			if (configuration.folderUri) {
1505
				const stateForFolder = this.windowsState.openedWindows.filter(o => o.folderUri && extUriBiasedIgnorePathCase.isEqual(o.folderUri, configuration.folderUri)).map(o => o.uiState);
1506 1507 1508
				if (stateForFolder.length) {
					return stateForFolder[0];
				}
1509 1510
			}

1511 1512 1513 1514 1515 1516
			// Empty windows with backups
			else if (configuration.backupPath) {
				const stateForEmptyWindow = this.windowsState.openedWindows.filter(o => o.backupPath === configuration.backupPath).map(o => o.uiState);
				if (stateForEmptyWindow.length) {
					return stateForEmptyWindow[0];
				}
E
Erich Gamma 已提交
1517 1518
			}

1519 1520 1521 1522 1523
			// First Window
			const lastActiveState = this.lastClosedWindowState || this.windowsState.lastActiveWindow;
			if (!lastActive && lastActiveState) {
				return lastActiveState.uiState;
			}
E
Erich Gamma 已提交
1524 1525 1526 1527 1528 1529 1530
		}

		//
		// 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
1531
		let displayToUse: Display | undefined;
B
Benjamin Pasero 已提交
1532
		const displays = screen.getAllDisplays();
E
Erich Gamma 已提交
1533 1534 1535 1536 1537 1538 1539 1540 1541 1542

		// Single Display
		if (displays.length === 1) {
			displayToUse = displays[0];
		}

		// Multi Display
		else {

			// on mac there is 1 menu per window so we need to use the monitor where the cursor currently is
B
Benjamin Pasero 已提交
1543
			if (isMacintosh) {
B
Benjamin Pasero 已提交
1544
				const cursorPoint = screen.getCursorScreenPoint();
E
Erich Gamma 已提交
1545 1546 1547 1548 1549 1550 1551 1552
				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());
			}

1553
			// fallback to primary display or first display
E
Erich Gamma 已提交
1554
			if (!displayToUse) {
1555
				displayToUse = screen.getPrimaryDisplay() || displays[0];
E
Erich Gamma 已提交
1556 1557 1558
			}
		}

1559 1560 1561
		// Compute x/y based on display bounds
		// Note: important to use Math.round() because Electron does not seem to be too happy about
		// display coordinates that are not absolute numbers.
1562
		let state = defaultWindowState();
M
Matt Bierner 已提交
1563 1564
		state.x = Math.round(displayToUse.bounds.x + (displayToUse.bounds.width / 2) - (state.width! / 2));
		state.y = Math.round(displayToUse.bounds.y + (displayToUse.bounds.height / 2) - (state.height! / 2));
E
Erich Gamma 已提交
1565

1566
		// Check for newWindowDimensions setting and adjust accordingly
1567
		const windowConfig = this.configurationService.getValue<IWindowSettings>('window');
1568
		let ensureNoOverlap = true;
B
Benjamin Pasero 已提交
1569
		if (windowConfig?.newWindowDimensions) {
1570 1571 1572 1573 1574 1575
			if (windowConfig.newWindowDimensions === 'maximized') {
				state.mode = WindowMode.Maximized;
				ensureNoOverlap = false;
			} else if (windowConfig.newWindowDimensions === 'fullscreen') {
				state.mode = WindowMode.Fullscreen;
				ensureNoOverlap = false;
S
SteVen Batten 已提交
1576
			} else if ((windowConfig.newWindowDimensions === 'inherit' || windowConfig.newWindowDimensions === 'offset') && lastActive) {
B
Benjamin Pasero 已提交
1577 1578 1579 1580 1581 1582 1583
				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;
				}

S
SteVen Batten 已提交
1584
				ensureNoOverlap = state.mode !== WindowMode.Fullscreen && windowConfig.newWindowDimensions === 'offset';
1585 1586 1587 1588 1589 1590 1591
			}
		}

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

1592
		(state as INewWindowState).hasDefaultState = true; // flag as default state
1593

1594
		return state;
E
Erich Gamma 已提交
1595 1596
	}

J
Joao Moreno 已提交
1597
	private ensureNoOverlap(state: ISingleWindowState): ISingleWindowState {
1598
		if (WindowsMainService.WINDOWS.length === 0) {
E
Erich Gamma 已提交
1599 1600 1601
			return state;
		}

M
Matt Bierner 已提交
1602 1603 1604
		state.x = typeof state.x === 'number' ? state.x : 0;
		state.y = typeof state.y === 'number' ? state.y : 0;

1605
		const existingWindowBounds = WindowsMainService.WINDOWS.map(win => win.getBounds());
1606
		while (existingWindowBounds.some(b => b.x === state.x || b.y === state.y)) {
E
Erich Gamma 已提交
1607 1608 1609 1610 1611 1612 1613
			state.x += 30;
			state.y += 30;
		}

		return state;
	}

M
Matt Bierner 已提交
1614
	getLastActiveWindow(): ICodeWindow | undefined {
1615
		return getLastActiveWindow(WindowsMainService.WINDOWS);
E
Erich Gamma 已提交
1616 1617
	}

1618
	private getLastActiveWindowForAuthority(remoteAuthority: string | undefined): ICodeWindow | undefined {
1619
		return getLastActiveWindow(WindowsMainService.WINDOWS.filter(window => window.remoteAuthority === remoteAuthority));
M
Martin Aeschlimann 已提交
1620 1621
	}

B
Benjamin Pasero 已提交
1622
	sendToFocused(channel: string, ...args: any[]): void {
E
Erich Gamma 已提交
1623 1624 1625
		const focusedWindow = this.getFocusedWindow() || this.getLastActiveWindow();

		if (focusedWindow) {
1626
			focusedWindow.sendWhenReady(channel, ...args);
E
Erich Gamma 已提交
1627 1628 1629
		}
	}

B
Benjamin Pasero 已提交
1630
	sendToAll(channel: string, payload?: any, windowIdsToIgnore?: number[]): void {
1631
		for (const window of WindowsMainService.WINDOWS) {
B
Benjamin Pasero 已提交
1632 1633
			if (windowIdsToIgnore && windowIdsToIgnore.indexOf(window.id) >= 0) {
				continue; // do not send if we are instructed to ignore it
E
Erich Gamma 已提交
1634 1635
			}

B
Benjamin Pasero 已提交
1636 1637
			window.sendWhenReady(channel, payload);
		}
E
Erich Gamma 已提交
1638 1639
	}

1640
	private getFocusedWindow(): ICodeWindow | undefined {
B
Benjamin Pasero 已提交
1641
		const win = BrowserWindow.getFocusedWindow();
E
Erich Gamma 已提交
1642 1643 1644 1645
		if (win) {
			return this.getWindowById(win.id);
		}

M
Matt Bierner 已提交
1646
		return undefined;
E
Erich Gamma 已提交
1647 1648
	}

M
Matt Bierner 已提交
1649
	getWindowById(windowId: number): ICodeWindow | undefined {
1650
		const res = WindowsMainService.WINDOWS.filter(window => window.id === windowId);
1651

M
Matt Bierner 已提交
1652
		return arrays.firstOrDefault(res);
E
Erich Gamma 已提交
1653 1654
	}

B
Benjamin Pasero 已提交
1655
	getWindows(): ICodeWindow[] {
1656
		return WindowsMainService.WINDOWS;
E
Erich Gamma 已提交
1657 1658
	}

B
Benjamin Pasero 已提交
1659
	getWindowCount(): number {
1660
		return WindowsMainService.WINDOWS.length;
E
Erich Gamma 已提交
1661 1662
	}

1663
	private onWindowClosed(win: ICodeWindow): void {
E
Erich Gamma 已提交
1664 1665

		// Remove from our list so that Electron can clean it up
1666 1667
		const index = WindowsMainService.WINDOWS.indexOf(win);
		WindowsMainService.WINDOWS.splice(index, 1);
E
Erich Gamma 已提交
1668 1669

		// Emit
1670
		this._onWindowsCountChanged.fire({ oldCount: WindowsMainService.WINDOWS.length + 1, newCount: WindowsMainService.WINDOWS.length });
E
Erich Gamma 已提交
1671
	}
B
Benjamin Pasero 已提交
1672
}