windowsMainService.ts 62.6 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 15
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { ParsedArgs } from 'vs/platform/environment/node/argv';
import { INativeEnvironmentService } from 'vs/platform/environment/node/environmentService';
16
import { IStateService } from 'vs/platform/state/node/state';
17
import { CodeWindow, defaultWindowState } from 'vs/code/electron-main/window';
R
Robo 已提交
18
import { ipcMain as ipc, screen, BrowserWindow, MessageBoxOptions, Display, app, nativeTheme } from 'electron';
19
import { parseLineAndColumnAware } from 'vs/code/node/paths';
20
import { ILifecycleMainService, UnloadReason, LifecycleMainService, LifecycleMainPhase } from 'vs/platform/lifecycle/electron-main/lifecycleMainService';
21
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
22
import { ILogService } from 'vs/platform/log/common/log';
23 24
import { IWindowSettings, IPath, isFileToOpen, isWorkspaceToOpen, isFolderToOpen, IWindowOpenable, IOpenEmptyWindowOptions } from 'vs/platform/windows/common/windows';
import { getLastActiveWindow, findBestWindowOrFolderForFile, findWindowOnWorkspace, findWindowOnExtensionDevelopmentPath, findWindowOnWorkspaceOrFolderUri, INativeWindowConfiguration, OpenContext, IAddFoldersRequest, IPathsToWaitFor } from 'vs/platform/windows/node/window';
25
import { Emitter } from 'vs/base/common/event';
26
import product from 'vs/platform/product/common/product';
27
import { IWindowsMainService, IOpenConfiguration, IWindowsCountChangedEvent, ICodeWindow, IWindowState as ISingleWindowState, WindowMode } from 'vs/platform/windows/electron-main/windows';
28
import { IWorkspacesHistoryMainService } from 'vs/platform/workspaces/electron-main/workspacesHistoryMainService';
29
import { IProcessEnvironment, isMacintosh, isWindows } from 'vs/base/common/platform';
30
import { IWorkspaceIdentifier, isSingleFolderWorkspaceIdentifier, hasWorkspaceFileExtension, IRecent } from 'vs/platform/workspaces/common/workspaces';
B
Benjamin Pasero 已提交
31
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
J
Johannes Rieken 已提交
32
import { Schemas } from 'vs/base/common/network';
33
import { URI } from 'vs/base/common/uri';
34
import { getComparisonKey, isEqual, normalizePath, originalFSPath, removeTrailingPathSeparator } from 'vs/base/common/resources';
M
Martin Aeschlimann 已提交
35
import { getRemoteAuthority } from 'vs/platform/remote/common/remoteHosts';
36
import { restoreWindowsState, WindowsStateStorageData, getWindowsStateStoreData } from 'vs/platform/windows/electron-main/windowsStateStorage';
B
Benjamin Pasero 已提交
37
import { getWorkspaceIdentifier, IWorkspacesMainService } from 'vs/platform/workspaces/electron-main/workspacesMainService';
38
import { once } from 'vs/base/common/functional';
M
Matt Bierner 已提交
39
import { Disposable } from 'vs/base/common/lifecycle';
40 41
import { IDialogMainService } from 'vs/platform/dialogs/electron-main/dialogs';
import { withNullAsUndefined } from 'vs/base/common/types';
42 43
import { isWindowsDriveLetter, toSlashes } from 'vs/base/common/extpath';
import { CharCode } from 'vs/base/common/charCode';
E
Erich Gamma 已提交
44

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

116 117 118 119 120 121 122 123 124 125 126 127 128 129
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 已提交
130 131 132

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

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 已提交
149 150 151

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

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

156
	_serviceBrand: undefined;
E
Erich Gamma 已提交
157

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

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

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

165 166
	private shuttingDown = false;

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

M
Matt Bierner 已提交
170
	private readonly _onWindowClose = this._register(new Emitter<number>());
171
	readonly onWindowClose = this._onWindowClose.event;
172

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

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

192
		this.windowsState = restoreWindowsState(this.stateService.getItem<WindowsStateStorageData>(WindowsMainService.windowsStateStorageKey));
193 194 195
		if (!Array.isArray(this.windowsState.openedWindows)) {
			this.windowsState.openedWindows = [];
		}
196

197 198
		this.lifecycleMainService.when(LifecycleMainPhase.Ready).then(() => this.registerListeners());
		this.lifecycleMainService.when(LifecycleMainPhase.AfterWindowOpen).then(() => this.installWindowsMutex());
199
	}
J
Joao Moreno 已提交
200

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

	private registerListeners(): void {
215

B
Benjamin Pasero 已提交
216
		// React to workbench ready events from windows
217
		ipc.on('vscode:workbenchReady', (event: Event, windowId: number) => {
B
Benjamin Pasero 已提交
218
			this.logService.trace('IPC#vscode-workbenchReady');
E
Erich Gamma 已提交
219

B
Benjamin Pasero 已提交
220
			const win = this.getWindowById(windowId);
E
Erich Gamma 已提交
221 222 223 224
			if (win) {
				win.setReady();

				// Event
225
				this._onWindowReady.fire(win);
E
Erich Gamma 已提交
226 227 228
			}
		});

229 230
		// React to HC color scheme changes (Windows)
		if (isWindows) {
R
Robo 已提交
231 232
			nativeTheme.on('updated', () => {
				if (nativeTheme.shouldUseInvertedColorScheme || nativeTheme.shouldUseHighContrastColors) {
233 234 235 236
					this.sendToAll('vscode:enterHighContrast');
				} else {
					this.sendToAll('vscode:leaveHighContrast');
				}
R
Robo 已提交
237
			});
238 239
		}

240 241 242 243 244 245 246 247 248
		// 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();
			}
		});

249
		// Handle various lifecycle events around windows
250 251
		this.lifecycleMainService.onBeforeWindowClose(window => this.onBeforeWindowClose(window));
		this.lifecycleMainService.onBeforeShutdown(() => this.onBeforeShutdown());
252 253 254 255 256
		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 已提交
257
				this.lastClosedWindowState = undefined;
258 259
			}
		});
260 261 262 263 264

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

267
	// Note that onBeforeShutdown() and onBeforeWindowClose() are fired in different order depending on the OS:
268
	// - macOS: since the app will not quit when closing the last window, you will always first get
269
	//          the onBeforeShutdown() event followed by N onbeforeWindowClose() events for each window
270 271
	// - 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()
272
	//          and then onBeforeShutdown(). Using the quit action however will first issue onBeforeShutdown()
273
	//          and then onBeforeWindowClose().
274 275 276 277 278 279 280
	//
	// Here is the behaviour on different OS dependig on action taken (Electron 1.7.x):
	//
	// 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
281
	// - onBeforeShutdown(N): number of windows reported in this event handler
282 283 284
	// - onBeforeWindowClose(N, M): number of windows reported and quitRequested boolean in this event handler
	//
	// macOS
285 286 287
	// 	-     quit(1): onBeforeShutdown(1), onBeforeWindowClose(1, true)
	// 	-     quit(2): onBeforeShutdown(2), onBeforeWindowClose(2, true), onBeforeWindowClose(2, true)
	// 	-     quit(0): onBeforeShutdown(0)
288 289 290
	// 	-    close(1): onBeforeWindowClose(1, false)
	//
	// Windows
291 292
	// 	-     quit(1): onBeforeShutdown(1), onBeforeWindowClose(1, true)
	// 	-     quit(2): onBeforeShutdown(2), onBeforeWindowClose(2, true), onBeforeWindowClose(2, true)
293
	// 	-    close(1): onBeforeWindowClose(2, false)[not last window]
294 295
	// 	-    close(1): onBeforeWindowClose(1, false), onBeforeShutdown(0)[last window]
	// 	- closeAll(2): onBeforeWindowClose(2, false), onBeforeWindowClose(2, false), onBeforeShutdown(0)
296 297
	//
	// Linux
298 299
	// 	-     quit(1): onBeforeShutdown(1), onBeforeWindowClose(1, true)
	// 	-     quit(2): onBeforeShutdown(2), onBeforeWindowClose(2, true), onBeforeWindowClose(2, true)
300
	// 	-    close(1): onBeforeWindowClose(2, false)[not last window]
301 302
	// 	-    close(1): onBeforeWindowClose(1, false), onBeforeShutdown(0)[last window]
	// 	- closeAll(2): onBeforeWindowClose(2, false), onBeforeWindowClose(2, false), onBeforeShutdown(0)
303
	//
304
	private onBeforeShutdown(): void {
305 306 307 308 309 310
		this.shuttingDown = true;

		this.saveWindowsState();
	}

	private saveWindowsState(): void {
311
		const currentWindowsState: IWindowsState = {
312
			openedWindows: [],
313
			lastPluginDevelopmentHostWindow: this.windowsState.lastPluginDevelopmentHostWindow,
314
			lastActiveWindow: this.lastClosedWindowState
315 316 317 318 319 320
		};

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

324
			if (activeWindow) {
325
				currentWindowsState.lastActiveWindow = this.toWindowState(activeWindow);
E
Erich Gamma 已提交
326
			}
327 328 329
		}

		// 2.) Find extension host window
330
		const extensionHostWindow = WindowsMainService.WINDOWS.find(window => window.isExtensionDevelopmentHost && !window.isExtensionTestHost);
331
		if (extensionHostWindow) {
332
			currentWindowsState.lastPluginDevelopmentHostWindow = this.toWindowState(extensionHostWindow);
333
		}
E
Erich Gamma 已提交
334

335
		// 3.) All windows (except extension host) for N >= 2 to support restoreWindows: all or for auto update
336 337 338 339 340
		//
		// 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) {
341
			currentWindowsState.openedWindows = WindowsMainService.WINDOWS.filter(window => !window.isExtensionDevelopmentHost).map(window => this.toWindowState(window));
342
		}
E
Erich Gamma 已提交
343

344
		// Persist
B
Benjamin Pasero 已提交
345 346
		const state = getWindowsStateStoreData(currentWindowsState);
		this.stateService.setItem(WindowsMainService.windowsStateStorageKey, state);
347 348 349 350

		if (this.shuttingDown) {
			this.logService.trace('onBeforeShutdown', state);
		}
351
	}
352

353
	// See note on #onBeforeShutdown() for details how these events are flowing
354
	private onBeforeWindowClose(win: ICodeWindow): void {
355
		if (this.lifecycleMainService.quitRequested) {
356 357 358 359
			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
360
		const state: IWindowState = this.toWindowState(win);
361 362 363 364
		if (win.isExtensionDevelopmentHost && !win.isExtensionTestHost) {
			this.windowsState.lastPluginDevelopmentHostWindow = state; // do not let test run window state overwrite our extension development state
		}

365
		// Any non extension host window with same workspace or folder
366
		else if (!win.isExtensionDevelopmentHost && (!!win.openedWorkspace || !!win.openedFolderUri)) {
367
			this.windowsState.openedWindows.forEach(o => {
B
fix npe  
Benjamin Pasero 已提交
368
				const sameWorkspace = win.openedWorkspace && o.workspace && o.workspace.id === win.openedWorkspace.id;
369
				const sameFolder = win.openedFolderUri && o.folderUri && isEqual(o.folderUri, win.openedFolderUri);
370 371

				if (sameWorkspace || sameFolder) {
372 373 374 375 376 377 378
					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.
379 380 381
		// 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) {
382 383
			this.lastClosedWindowState = state;
		}
E
Erich Gamma 已提交
384 385
	}

386
	private toWindowState(win: ICodeWindow): IWindowState {
387
		return {
388
			workspace: win.openedWorkspace,
389
			folderUri: win.openedFolderUri,
390
			backupPath: win.backupPath,
M
Martin Aeschlimann 已提交
391
			remoteAuthority: win.remoteAuthority,
392 393 394 395
			uiState: win.serializeWindowState()
		};
	}

396 397
	openEmptyWindow(context: OpenContext, options?: IOpenEmptyWindowOptions): ICodeWindow[] {
		let cli = this.environmentService.args;
B
Benjamin Pasero 已提交
398
		const remote = options?.remoteAuthority;
399 400 401 402
		if (cli && (cli.remote !== remote)) {
			cli = { ...cli, remote };
		}

B
Benjamin Pasero 已提交
403
		const forceReuseWindow = options?.forceReuseWindow;
404 405 406 407 408
		const forceNewWindow = !forceReuseWindow;

		return this.open({ context, cli, forceEmpty: true, forceNewWindow, forceReuseWindow });
	}

B
Benjamin Pasero 已提交
409
	open(openConfig: IOpenConfiguration): ICodeWindow[] {
410
		this.logService.trace('windowsManager#open');
411
		openConfig = this.validateOpenConfig(openConfig);
412

413
		const pathsToOpen = this.getPathsToOpen(openConfig);
414

415 416 417 418 419 420
		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
421
		for (const path of pathsToOpen) {
422 423 424 425 426 427 428 429 430 431 432
			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) {
433
				if (!fileInputs) {
434
					fileInputs = { filesToOpenOrCreate: [], filesToDiff: [], remoteAuthority: path.remoteAuthority };
435
				}
436
				fileInputs.filesToOpenOrCreate.push(path);
437 438 439 440
			} else if (path.backupPath) {
				emptyToRestore.push({ backupFolder: basename(path.backupPath), remoteAuthority: path.remoteAuthority });
			} else {
				emptyToOpen++;
441 442
			}
		}
443 444 445

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

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

456
		//
457
		// These are windows to restore because of hot-exit or from previous session (only performed once on startup!)
458
		//
459
		let workspacesToRestore: IWorkspacePathToOpen[] = [];
B
Benjamin Pasero 已提交
460
		if (openConfig.initialStartup && !openConfig.cli.extensionDevelopmentPath && !openConfig.cli['disable-restore-windows']) {
461 462

			// Untitled workspaces are always restored
463
			workspacesToRestore = this.workspacesMainService.getUntitledWorkspacesSync();
464
			workspacesToOpen.push(...workspacesToRestore);
465

466
			// Empty windows with backups are always restored
467 468 469
			emptyToRestore.push(...this.backupMainService.getEmptyWindowBackupPaths());
		} else {
			emptyToRestore.length = 0;
470
		}
471 472

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

475
		// Make sure to pass focus to the most relevant of the windows if we open multiple
476
		if (usedWindows.length > 1) {
477

478
			const focusLastActive = this.windowsState.lastActiveWindow && !openConfig.forceEmpty && openConfig.cli._.length && !openConfig.cli['file-uri'] && !openConfig.cli['folder-uri'] && !(openConfig.urisToOpen && openConfig.urisToOpen.length);
479 480
			let focusLastOpened = true;
			let focusLastWindow = true;
481

482 483
			// 1.) focus last active window if we are not instructed to open any paths
			if (focusLastActive) {
484
				const lastActiveWindow = usedWindows.filter(window => this.windowsState.lastActiveWindow && window.backupPath === this.windowsState.lastActiveWindow.backupPath);
485 486
				if (lastActiveWindow.length) {
					lastActiveWindow[0].focus();
487 488
					focusLastOpened = false;
					focusLastWindow = false;
489 490 491
				}
			}

492 493 494 495 496
			// 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 (
497 498
						(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
499 500 501 502 503 504 505 506 507 508 509 510
					) {
						continue;
					}

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

			// 3.) finally, always ensure to have at least last used window focused
			if (focusLastWindow) {
511
				usedWindows[usedWindows.length - 1].focus();
512 513
			}
		}
514

515 516
		// 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
517 518
		const isDiff = fileInputs && fileInputs.filesToDiff.length > 0;
		if (!usedWindows.some(window => window.isExtensionDevelopmentHost) && !isDiff && !openConfig.noRecentEntry) {
M
Martin Aeschlimann 已提交
519 520 521 522 523 524 525 526
			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 });
527
				}
528
			}
529
			this.workspacesHistoryMainService.addRecentlyOpened(recents);
530
		}
531

532
		// If we got started with --wait from the CLI, we need to signal to the outside when the window
533 534
		// 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 已提交
535 536
		const waitMarkerFileURI = openConfig.waitMarkerFileURI;
		if (openConfig.context === OpenContext.CLI && waitMarkerFileURI && usedWindows.length === 1 && usedWindows[0]) {
537
			usedWindows[0].whenClosedOrLoaded.then(() => fs.unlink(waitMarkerFileURI.fsPath, _error => undefined));
538 539
		}

540 541 542
		return usedWindows;
	}

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

553 554
	private doOpen(
		openConfig: IOpenConfiguration,
555 556
		workspacesToOpen: IWorkspacePathToOpen[],
		foldersToOpen: IFolderPathToOpen[],
557
		emptyToRestore: IEmptyWindowBackupInfo[],
558
		emptyToOpen: number,
559
		fileInputs: IFileInputs | undefined,
560
		foldersToAdd: IFolderPathToOpen[]
561
	) {
562
		const usedWindows: ICodeWindow[] = [];
563

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

567 568
		// Handle folders to add by looking for the last active workspace (not on initial startup)
		if (!openConfig.initialStartup && foldersToAdd.length > 0) {
569
			const authority = foldersToAdd[0].remoteAuthority;
570
			const lastActiveWindow = this.getLastActiveWindowForAuthority(authority);
571
			if (lastActiveWindow) {
572
				usedWindows.push(this.doAddFoldersToExistingWindow(lastActiveWindow, foldersToAdd.map(f => f.folderUri)));
573 574 575
			}
		}

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

580
			// Find suitable window or folder path to open files in
581
			const fileToCheck = fileInputs.filesToOpenOrCreate[0] || fileInputs.filesToDiff[0];
582

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

586
			const bestWindowOrFolder = findBestWindowOrFolderForFile({
587
				windows,
588 589
				newWindow: openFilesInNewWindow,
				context: openConfig.context,
B
Benjamin Pasero 已提交
590
				fileUri: fileToCheck?.fileUri,
591
				localWorkspaceResolver: workspace => workspace.configPath.scheme === Schemas.file ? this.workspacesMainService.resolveLocalWorkspaceSync(workspace.configPath) : null
592
			});
B
Benjamin Pasero 已提交
593

594 595 596 597 598
			// We found a window to open the files in
			if (bestWindowOrFolder instanceof CodeWindow) {

				// Window is workspace
				if (bestWindowOrFolder.openedWorkspace) {
599
					workspacesToOpen.push({ workspace: bestWindowOrFolder.openedWorkspace, remoteAuthority: bestWindowOrFolder.remoteAuthority });
600 601 602
				}

				// Window is single folder
603
				else if (bestWindowOrFolder.openedFolderUri) {
604
					foldersToOpen.push({ folderUri: bestWindowOrFolder.openedFolderUri, remoteAuthority: bestWindowOrFolder.remoteAuthority });
605 606 607 608 609 610
				}

				// Window is empty
				else {

					// Do open files
611
					usedWindows.push(this.doOpenFilesInExistingWindow(openConfig, bestWindowOrFolder, fileInputs));
612 613

					// Reset these because we handled them
R
Rob Lourens 已提交
614
					fileInputs = undefined;
615
				}
616 617 618
			}

			// Finally, if no window or folder is found, just open the files in an empty window
E
Erich Gamma 已提交
619
			else {
B
Benjamin Pasero 已提交
620
				usedWindows.push(this.openInBrowserWindow({
B
Benjamin Pasero 已提交
621 622 623
					userEnv: openConfig.userEnv,
					cli: openConfig.cli,
					initialStartup: openConfig.initialStartup,
624
					fileInputs,
625
					forceNewWindow: true,
M
Martin Aeschlimann 已提交
626
					remoteAuthority: fileInputs.remoteAuthority,
627
					forceNewTabbedWindow: openConfig.forceNewTabbedWindow
B
Benjamin Pasero 已提交
628
				}));
E
Erich Gamma 已提交
629

630
				// Reset these because we handled them
R
Rob Lourens 已提交
631
				fileInputs = undefined;
E
Erich Gamma 已提交
632 633 634
			}
		}

635
		// Handle workspaces to open (instructed and to restore)
636
		const allWorkspacesToOpen = arrays.distinct(workspacesToOpen, workspace => workspace.workspace.id); // prevent duplicates
637 638 639
		if (allWorkspacesToOpen.length > 0) {

			// Check for existing instances
640
			const windowsOnWorkspace = arrays.coalesce(allWorkspacesToOpen.map(workspaceToOpen => findWindowOnWorkspace(WindowsMainService.WINDOWS, workspaceToOpen.workspace)));
641 642
			if (windowsOnWorkspace.length > 0) {
				const windowOnWorkspace = windowsOnWorkspace[0];
B
Benjamin Pasero 已提交
643
				const fileInputsForWindow = (fileInputs?.remoteAuthority === windowOnWorkspace.remoteAuthority) ? fileInputs : undefined;
644 645

				// Do open files
646
				usedWindows.push(this.doOpenFilesInExistingWindow(openConfig, windowOnWorkspace, fileInputsForWindow));
647 648

				// Reset these because we handled them
649
				if (fileInputsForWindow) {
R
Rob Lourens 已提交
650
					fileInputs = undefined;
651
				}
652 653 654 655 656 657

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

			// Open remaining ones
			allWorkspacesToOpen.forEach(workspaceToOpen => {
658
				if (windowsOnWorkspace.some(win => win.openedWorkspace && win.openedWorkspace.id === workspaceToOpen.workspace.id)) {
659 660 661
					return; // ignore folders that are already open
				}

662
				const remoteAuthority = workspaceToOpen.remoteAuthority;
B
Benjamin Pasero 已提交
663
				const fileInputsForWindow = (fileInputs?.remoteAuthority === remoteAuthority) ? fileInputs : undefined;
664

665
				// Do open folder
666
				usedWindows.push(this.doOpenFolderOrWorkspace(openConfig, workspaceToOpen, openFolderInNewWindow, fileInputsForWindow));
667 668

				// Reset these because we handled them
669
				if (fileInputsForWindow) {
R
Rob Lourens 已提交
670
					fileInputs = undefined;
671
				}
672 673 674 675 676

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

677
		// Handle folders to open (instructed and to restore)
678
		const allFoldersToOpen = arrays.distinct(foldersToOpen, folder => getComparisonKey(folder.folderUri)); // prevent duplicates
679
		if (allFoldersToOpen.length > 0) {
E
Erich Gamma 已提交
680 681

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

687
				// Do open files
688
				usedWindows.push(this.doOpenFilesInExistingWindow(openConfig, windowOnFolderPath, fileInputsForWindow));
689

E
Erich Gamma 已提交
690
				// Reset these because we handled them
691
				if (fileInputsForWindow) {
R
Rob Lourens 已提交
692
					fileInputs = undefined;
693
				}
E
Erich Gamma 已提交
694

B
Benjamin Pasero 已提交
695
				openFolderInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
696 697 698
			}

			// Open remaining ones
699
			allFoldersToOpen.forEach(folderToOpen => {
700

701
				if (windowsOnFolderPath.some(win => isEqual(win.openedFolderUri, folderToOpen.folderUri))) {
E
Erich Gamma 已提交
702 703 704
					return; // ignore folders that are already open
				}

705
				const remoteAuthority = folderToOpen.remoteAuthority;
B
Benjamin Pasero 已提交
706
				const fileInputsForWindow = (fileInputs?.remoteAuthority === remoteAuthority) ? fileInputs : undefined;
707

708
				// Do open folder
709
				usedWindows.push(this.doOpenFolderOrWorkspace(openConfig, folderToOpen, openFolderInNewWindow, fileInputsForWindow));
E
Erich Gamma 已提交
710 711

				// Reset these because we handled them
712
				if (fileInputsForWindow) {
R
Rob Lourens 已提交
713
					fileInputs = undefined;
714
				}
E
Erich Gamma 已提交
715

B
Benjamin Pasero 已提交
716
				openFolderInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
717 718 719
			});
		}

720
		// Handle empty to restore
721
		const allEmptyToRestore = arrays.distinct(emptyToRestore, info => info.backupFolder); // prevent duplicates
722 723
		if (allEmptyToRestore.length > 0) {
			allEmptyToRestore.forEach(emptyWindowBackupInfo => {
M
Martin Aeschlimann 已提交
724
				const remoteAuthority = emptyWindowBackupInfo.remoteAuthority;
B
Benjamin Pasero 已提交
725
				const fileInputsForWindow = (fileInputs?.remoteAuthority === remoteAuthority) ? fileInputs : undefined;
726

B
Benjamin Pasero 已提交
727
				usedWindows.push(this.openInBrowserWindow({
B
Benjamin Pasero 已提交
728 729 730
					userEnv: openConfig.userEnv,
					cli: openConfig.cli,
					initialStartup: openConfig.initialStartup,
731
					fileInputs: fileInputsForWindow,
M
Martin Aeschlimann 已提交
732
					remoteAuthority,
B
Benjamin Pasero 已提交
733
					forceNewWindow: true,
734
					forceNewTabbedWindow: openConfig.forceNewTabbedWindow,
735
					emptyWindowBackupInfo
B
Benjamin Pasero 已提交
736
				}));
737

B
wip  
Benjamin Pasero 已提交
738
				// Reset these because we handled them
739
				if (fileInputsForWindow) {
R
Rob Lourens 已提交
740
					fileInputs = undefined;
741
				}
B
wip  
Benjamin Pasero 已提交
742

B
Benjamin Pasero 已提交
743
				openFolderInNewWindow = true; // any other folders to open must open in new window then
744 745
			});
		}
B
Benjamin Pasero 已提交
746

747
		// Handle empty to open (only if no other window opened)
748 749 750 751
		if (usedWindows.length === 0 || fileInputs) {
			if (fileInputs && !emptyToOpen) {
				emptyToOpen++;
			}
752

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

755
			for (let i = 0; i < emptyToOpen; i++) {
B
Benjamin Pasero 已提交
756
				usedWindows.push(this.openInBrowserWindow({
B
Benjamin Pasero 已提交
757 758 759
					userEnv: openConfig.userEnv,
					cli: openConfig.cli,
					initialStartup: openConfig.initialStartup,
M
Martin Aeschlimann 已提交
760
					remoteAuthority,
761
					forceNewWindow: openFolderInNewWindow,
762 763
					forceNewTabbedWindow: openConfig.forceNewTabbedWindow,
					fileInputs
B
Benjamin Pasero 已提交
764
				}));
E
Erich Gamma 已提交
765

766
				// Reset these because we handled them
R
Rob Lourens 已提交
767
				fileInputs = undefined;
768
				openFolderInNewWindow = true; // any other window to open must open in new window then
769 770
			}
		}
E
Erich Gamma 已提交
771

772
		return arrays.distinct(usedWindows);
E
Erich Gamma 已提交
773 774
	}

775
	private doOpenFilesInExistingWindow(configuration: IOpenConfiguration, window: ICodeWindow, fileInputs?: IFileInputs): ICodeWindow {
776 777
		window.focus(); // make sure window has focus

778
		const params: { filesToOpenOrCreate?: IPath[], filesToDiff?: IPath[], filesToWait?: IPathsToWaitFor, termProgram?: string } = {};
B
Benjamin Pasero 已提交
779
		if (fileInputs) {
780
			params.filesToOpenOrCreate = fileInputs.filesToOpenOrCreate;
B
Benjamin Pasero 已提交
781 782 783 784 785 786 787 788 789
			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 已提交
790 791

		return window;
792 793
	}

794
	private doAddFoldersToExistingWindow(window: ICodeWindow, foldersToAdd: URI[]): ICodeWindow {
795 796
		window.focus(); // make sure window has focus

B
Benjamin Pasero 已提交
797 798 799
		const request: IAddFoldersRequest = { foldersToAdd };

		window.sendWhenReady('vscode:addFolders', request);
800 801 802 803

		return window;
	}

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

809 810 811 812
		const browserWindow = this.openInBrowserWindow({
			userEnv: openConfig.userEnv,
			cli: openConfig.cli,
			initialStartup: openConfig.initialStartup,
813
			workspace: folderOrWorkspace.workspace,
814
			folderUri: folderOrWorkspace.folderUri,
815
			fileInputs,
M
Martin Aeschlimann 已提交
816
			remoteAuthority: folderOrWorkspace.remoteAuthority,
B
Benjamin Pasero 已提交
817
			forceNewWindow,
818
			forceNewTabbedWindow: openConfig.forceNewTabbedWindow,
819
			windowToUse
820 821 822 823 824
		});

		return browserWindow;
	}

B
Benjamin Pasero 已提交
825 826
	private getPathsToOpen(openConfig: IOpenConfiguration): IPathToOpen[] {
		let windowsToOpen: IPathToOpen[];
827
		let isCommandLineOrAPICall = false;
E
Erich Gamma 已提交
828

829
		// Extract paths: from API
S
Sandeep Somavarapu 已提交
830
		if (openConfig.urisToOpen && openConfig.urisToOpen.length > 0) {
831
			windowsToOpen = this.doExtractPathsFromAPI(openConfig);
832
			isCommandLineOrAPICall = true;
E
Erich Gamma 已提交
833 834
		}

B
Benjamin Pasero 已提交
835 836
		// Check for force empty
		else if (openConfig.forceEmpty) {
837
			windowsToOpen = [Object.create(null)];
E
Erich Gamma 已提交
838 839
		}

840
		// Extract paths: from CLI
841
		else if (openConfig.cli._.length || openConfig.cli['folder-uri'] || openConfig.cli['file-uri']) {
842
			windowsToOpen = this.doExtractPathsFromCLI(openConfig.cli);
843
			isCommandLineOrAPICall = true;
B
Benjamin Pasero 已提交
844 845
		}

846
		// Extract windows: from previous session
B
Benjamin Pasero 已提交
847
		else {
848
			windowsToOpen = this.doGetWindowsFromLastSession();
B
Benjamin Pasero 已提交
849 850
		}

851 852
		// Convert multiple folders into workspace (if opened via API or CLI)
		// This will ensure to open these folders in one window instead of multiple
853 854
		// If we are in addMode, we should not do this because in that case all
		// folders should be added to the existing window.
855
		if (!openConfig.addMode && isCommandLineOrAPICall) {
856
			const foldersToOpen = windowsToOpen.filter(path => !!path.folderUri);
857
			if (foldersToOpen.length > 1) {
858
				const remoteAuthority = foldersToOpen[0].remoteAuthority;
859 860 861 862 863 864 865
				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);
				}
866 867 868
			}
		}

869
		return windowsToOpen;
E
Erich Gamma 已提交
870 871
	}

872
	private doExtractPathsFromAPI(openConfig: IOpenConfiguration): IPathToOpen[] {
M
Matt Bierner 已提交
873
		const pathsToOpen: IPathToOpen[] = [];
874
		const parseOptions: IPathParseOptions = { gotoLineMode: openConfig.gotoLineMode };
M
Matt Bierner 已提交
875
		for (const pathToOpen of openConfig.urisToOpen || []) {
M
Martin Aeschlimann 已提交
876 877 878 879
			if (!pathToOpen) {
				continue;
			}

M
Martin Aeschlimann 已提交
880
			const path = this.parseUri(pathToOpen, parseOptions);
M
Martin Aeschlimann 已提交
881
			if (path) {
M
Martin Aeschlimann 已提交
882
				path.label = pathToOpen.label;
M
Martin Aeschlimann 已提交
883 884
				pathsToOpen.push(path);
			} else {
885 886
				const uri = this.resourceFromURIToOpen(pathToOpen);

B
Benjamin Pasero 已提交
887
				// Warn about the invalid URI or path
M
Martin Aeschlimann 已提交
888
				let message, detail;
M
Martin Aeschlimann 已提交
889
				if (uri.scheme === Schemas.file) {
M
Martin Aeschlimann 已提交
890
					message = localize('pathNotExistTitle', "Path does not exist");
M
Martin Aeschlimann 已提交
891
					detail = localize('pathNotExistDetail', "The path '{0}' does not seem to exist anymore on disk.", uri.fsPath);
M
Martin Aeschlimann 已提交
892 893
				} else {
					message = localize('uriInvalidTitle', "URI can not be opened");
M
Martin Aeschlimann 已提交
894
					detail = localize('uriInvalidDetail', "The URI '{0}' is not valid and can not be opened.", uri.toString());
M
Martin Aeschlimann 已提交
895
				}
896
				const options: MessageBoxOptions = {
897 898
					title: product.nameLong,
					type: 'info',
899
					buttons: [localize('ok', "OK")],
M
Martin Aeschlimann 已提交
900 901
					message,
					detail,
902 903 904
					noLink: true
				};

905
				this.dialogMainService.showMessageBox(options, withNullAsUndefined(BrowserWindow.getFocusedWindow()));
906
			}
M
Martin Aeschlimann 已提交
907
		}
908 909 910 911
		return pathsToOpen;
	}

	private doExtractPathsFromCLI(cli: ParsedArgs): IPath[] {
M
Matt Bierner 已提交
912
		const pathsToOpen: IPathToOpen[] = [];
R
Rob Lourens 已提交
913
		const parseOptions: IPathParseOptions = { ignoreFileNotFound: true, gotoLineMode: cli.goto, remoteAuthority: cli.remote || undefined };
914 915

		// folder uris
916 917 918 919 920 921 922 923 924
		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 已提交
925
				}
M
Martin Aeschlimann 已提交
926
			}
927 928
		}

929

930
		// file uris
931 932 933 934 935 936 937 938 939
		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 已提交
940
				}
M
Martin Aeschlimann 已提交
941
			}
942 943 944
		}

		// folder or file paths
945
		const cliArgs = cli._;
M
Martin Aeschlimann 已提交
946 947 948 949 950
		for (let cliArg of cliArgs) {
			const path = this.parsePath(cliArg, parseOptions);
			if (path) {
				pathsToOpen.push(path);
			}
951 952
		}

M
Martin Aeschlimann 已提交
953
		if (pathsToOpen.length) {
954
			return pathsToOpen;
B
Benjamin Pasero 已提交
955 956 957 958 959 960
		}

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

B
Benjamin Pasero 已提交
961
	private doGetWindowsFromLastSession(): IPathToOpen[] {
962
		const restoreWindows = this.getRestoreWindowsSetting();
B
Benjamin Pasero 已提交
963

964
		switch (restoreWindows) {
B
Benjamin Pasero 已提交
965

966
			// none: we always open an empty window
967 968
			case 'none':
				return [Object.create(null)];
B
Benjamin Pasero 已提交
969

970
			// one: restore last opened workspace/folder or empty window
971 972
			// all: restore all windows
			// folders: restore last opened folders only
973
			case 'one':
974 975
			case 'all':
			case 'folders':
976 977 978
				const openedWindows: IWindowState[] = [];
				if (restoreWindows !== 'one') {
					openedWindows.push(...this.windowsState.openedWindows);
979
				}
980 981
				if (this.windowsState.lastActiveWindow) {
					openedWindows.push(this.windowsState.lastActiveWindow);
982
				}
983

984 985 986
				const windowsToOpen: IPathToOpen[] = [];
				for (const openedWindow of openedWindows) {
					if (openedWindow.workspace) { // Workspaces
M
Martin Aeschlimann 已提交
987
						const pathToOpen = this.parseUri({ workspaceUri: openedWindow.workspace.configPath }, { remoteAuthority: openedWindow.remoteAuthority });
B
Benjamin Pasero 已提交
988
						if (pathToOpen?.workspace) {
989 990 991
							windowsToOpen.push(pathToOpen);
						}
					} else if (openedWindow.folderUri) { // Folders
M
Martin Aeschlimann 已提交
992
						const pathToOpen = this.parseUri({ folderUri: openedWindow.folderUri }, { remoteAuthority: openedWindow.remoteAuthority });
B
Benjamin Pasero 已提交
993
						if (pathToOpen?.folderUri) {
994 995
							windowsToOpen.push(pathToOpen);
						}
996
					} 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 已提交
997
						windowsToOpen.push({ backupPath: openedWindow.backupPath, remoteAuthority: openedWindow.remoteAuthority });
998
					}
999 1000 1001 1002 1003 1004 1005
				}

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

				break;
B
Benjamin Pasero 已提交
1006
		}
E
Erich Gamma 已提交
1007

1008
		// Always fallback to empty window
B
Benjamin Pasero 已提交
1009
		return [Object.create(null)];
E
Erich Gamma 已提交
1010 1011
	}

1012 1013
	private getRestoreWindowsSetting(): RestoreWindowsSetting {
		let restoreWindows: RestoreWindowsSetting;
1014
		if (this.lifecycleMainService.wasRestarted) {
1015 1016
			restoreWindows = 'all'; // always reopen all windows when an update was applied
		} else {
1017
			const windowConfig = this.configurationService.getValue<IWindowSettings>('window');
B
Benjamin Pasero 已提交
1018
			restoreWindows = windowConfig?.restoreWindows || 'all'; // by default restore all windows
1019 1020

			if (['all', 'folders', 'one', 'none'].indexOf(restoreWindows) === -1) {
B
Benjamin Pasero 已提交
1021
				restoreWindows = 'all'; // by default restore all windows
1022 1023 1024 1025 1026 1027
			}
		}

		return restoreWindows;
	}

1028
	private argToUri(arg: string): URI | undefined {
M
Martin Aeschlimann 已提交
1029
		try {
1030
			const uri = URI.parse(arg);
M
Martin Aeschlimann 已提交
1031
			if (!uri.scheme) {
M
Martin Aeschlimann 已提交
1032
				this.logService.error(`Invalid URI input string, scheme missing: ${arg}`);
1033
				return undefined;
M
Martin Aeschlimann 已提交
1034
			}
1035

M
Martin Aeschlimann 已提交
1036 1037
			return uri;
		} catch (e) {
M
Martin Aeschlimann 已提交
1038
			this.logService.error(`Invalid URI input string: ${arg}, ${e.message}`);
1039
		}
1040

1041
		return undefined;
1042 1043
	}

1044 1045
	private parseUri(toOpen: IWindowOpenable, options: IPathParseOptions = {}): IPathToOpen | undefined {
		if (!toOpen) {
1046
			return undefined;
1047
		}
1048

1049
		let uri = this.resourceFromURIToOpen(toOpen);
M
Martin Aeschlimann 已提交
1050
		if (uri.scheme === Schemas.file) {
1051
			return this.parsePath(uri.fsPath, options, isFileToOpen(toOpen));
1052
		}
M
Martin Aeschlimann 已提交
1053 1054

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

1057 1058
		// normalize URI
		uri = normalizePath(uri);
1059 1060

		// remove trailing slash
1061
		uri = removeTrailingPathSeparator(uri);
1062

1063 1064
		// File
		if (isFileToOpen(toOpen)) {
1065
			if (options.gotoLineMode) {
1066 1067 1068 1069
				const parsedPath = parseLineAndColumnAware(uri.path);
				return {
					fileUri: uri.with({ path: parsedPath.path }),
					lineNumber: parsedPath.line,
M
Martin Aeschlimann 已提交
1070 1071
					columnNumber: parsedPath.column,
					remoteAuthority
1072 1073
				};
			}
1074

1075
			return {
M
Martin Aeschlimann 已提交
1076 1077
				fileUri: uri,
				remoteAuthority
1078
			};
1079 1080 1081 1082
		}

		// Workspace
		else if (isWorkspaceToOpen(toOpen)) {
M
Martin Aeschlimann 已提交
1083 1084 1085 1086
			return {
				workspace: getWorkspaceIdentifier(uri),
				remoteAuthority
			};
1087
		}
1088 1089

		// Folder
1090
		return {
M
Martin Aeschlimann 已提交
1091 1092
			folderUri: uri,
			remoteAuthority
1093 1094 1095
		};
	}

1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
	private resourceFromURIToOpen(openable: IWindowOpenable): URI {
		if (isWorkspaceToOpen(openable)) {
			return openable.workspaceUri;
		}

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

		return openable.fileUri;
	}

M
Martin Aeschlimann 已提交
1108
	private parsePath(anyPath: string, options: IPathParseOptions, forceOpenWorkspaceAsFile?: boolean): IPathToOpen | undefined {
E
Erich Gamma 已提交
1109
		if (!anyPath) {
1110
			return undefined;
E
Erich Gamma 已提交
1111 1112
		}

1113
		let lineNumber, columnNumber: number | undefined;
1114

1115
		if (options.gotoLineMode) {
1116 1117 1118
			const parsedPath = parseLineAndColumnAware(anyPath);
			lineNumber = parsedPath.line;
			columnNumber = parsedPath.column;
1119

E
Erich Gamma 已提交
1120 1121 1122
			anyPath = parsedPath.path;
		}

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

1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
		if (remoteAuthority) {
			const first = anyPath.charCodeAt(0);
			// 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 });

1138 1139 1140 1141 1142 1143 1144
			// 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 };
					}
				} else if (posix.extname(anyPath).length > 0) {
1145 1146 1147 1148 1149 1150 1151 1152
					return { fileUri: uri, remoteAuthority };
				}
			}
			return { folderUri: uri, remoteAuthority };
		}

		let candidate = normalize(anyPath);

E
Erich Gamma 已提交
1153
		try {
1154

B
Benjamin Pasero 已提交
1155
			const candidateStat = fs.statSync(candidate);
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
			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
						};
1167
					}
1168 1169
				}

1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
				// 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 已提交
1189 1190
			}
		} catch (error) {
S
Sandeep Somavarapu 已提交
1191
			const fileUri = URI.file(candidate);
B
Benjamin Pasero 已提交
1192
			this.workspacesHistoryMainService.removeRecentlyOpened([fileUri]); // since file does not seem to exist anymore, remove from recent
1193 1194

			// assume this is a file that does not yet exist
B
Benjamin Pasero 已提交
1195
			if (options?.ignoreFileNotFound) {
1196 1197 1198 1199 1200
				return {
					fileUri,
					remoteAuthority,
					exists: false
				};
E
Erich Gamma 已提交
1201 1202 1203
			}
		}

1204
		return undefined;
E
Erich Gamma 已提交
1205 1206
	}

B
Benjamin Pasero 已提交
1207 1208 1209
	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
1210
		const windowConfig = this.configurationService.getValue<IWindowSettings>('window');
B
Benjamin Pasero 已提交
1211 1212
		const openFolderInNewWindowConfig = windowConfig?.openFoldersInNewWindow || 'default' /* default */;
		const openFilesInNewWindowConfig = windowConfig?.openFilesInNewWindow || 'off' /* default */;
1213

B
Benjamin Pasero 已提交
1214
		let openFolderInNewWindow = (openConfig.preferNewWindow || openConfig.forceNewWindow) && !openConfig.forceReuseWindow;
1215 1216
		if (!openConfig.forceNewWindow && !openConfig.forceReuseWindow && (openFolderInNewWindowConfig === 'on' || openFolderInNewWindowConfig === 'off')) {
			openFolderInNewWindow = (openFolderInNewWindowConfig === 'on');
B
Benjamin Pasero 已提交
1217 1218 1219
		}

		// 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 已提交
1220
		let openFilesInNewWindow: boolean = false;
B
Benjamin Pasero 已提交
1221
		if (openConfig.forceNewWindow || openConfig.forceReuseWindow) {
M
Matt Bierner 已提交
1222
			openFilesInNewWindow = !!openConfig.forceNewWindow && !openConfig.forceReuseWindow;
B
Benjamin Pasero 已提交
1223
		} else {
1224 1225 1226 1227 1228 1229 1230 1231

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

1232 1233
			// 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
1234
			else {
1235
				if (openConfig.context !== OpenContext.DIALOG && openConfig.context !== OpenContext.MENU && !(openConfig.userEnv && openConfig.userEnv['TERM_PROGRAM'] === 'vscode')) {
1236 1237
					openFilesInNewWindow = true;
				}
B
Benjamin Pasero 已提交
1238 1239
			}

1240
			// finally check for overrides of default
1241 1242
			if (!openConfig.cli.extensionDevelopmentPath && (openFilesInNewWindowConfig === 'on' || openFilesInNewWindowConfig === 'off')) {
				openFilesInNewWindow = (openFilesInNewWindowConfig === 'on');
B
Benjamin Pasero 已提交
1243 1244 1245
			}
		}

M
Matt Bierner 已提交
1246
		return { openFolderInNewWindow: !!openFolderInNewWindow, openFilesInNewWindow };
B
Benjamin Pasero 已提交
1247 1248
	}

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

B
Benjamin Pasero 已提交
1251 1252 1253
		// 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.
1254
		const existingWindow = findWindowOnExtensionDevelopmentPath(WindowsMainService.WINDOWS, extensionDevelopmentPath);
1255
		if (existingWindow) {
1256
			this.lifecycleMainService.reload(existingWindow, openConfig.cli);
1257
			existingWindow.focus(); // make sure it gets focus and is restored
E
Erich Gamma 已提交
1258

1259
			return [existingWindow];
B
Benjamin Pasero 已提交
1260
		}
1261 1262
		let folderUris = openConfig.cli['folder-uri'] || [];
		let fileUris = openConfig.cli['file-uri'] || [];
1263
		let cliArgs = openConfig.cli._;
E
Erich Gamma 已提交
1264

1265
		// Fill in previously opened workspace unless an explicit path is provided and we are not unit testing
1266
		if (!cliArgs.length && !folderUris.length && !fileUris.length && !openConfig.cli.extensionTestsPath) {
1267
			const extensionDevelopmentWindowState = this.windowsState.lastPluginDevelopmentHostWindow;
1268
			const workspaceToOpen = extensionDevelopmentWindowState && (extensionDevelopmentWindowState.workspace || extensionDevelopmentWindowState.folderUri);
1269
			if (workspaceToOpen) {
1270
				if (isSingleFolderWorkspaceIdentifier(workspaceToOpen)) {
1271
					if (workspaceToOpen.scheme === Schemas.file) {
1272
						cliArgs = [workspaceToOpen.fsPath];
1273
					} else {
1274
						folderUris = [workspaceToOpen.toString()];
1275 1276
					}
				} else {
M
Martin Aeschlimann 已提交
1277
					if (workspaceToOpen.configPath.scheme === Schemas.file) {
1278
						cliArgs = [originalFSPath(workspaceToOpen.configPath)];
M
Martin Aeschlimann 已提交
1279
					} else {
1280
						fileUris = [workspaceToOpen.configPath.toString()];
M
Martin Aeschlimann 已提交
1281
					}
1282
				}
E
Erich Gamma 已提交
1283 1284 1285
			}
		}

1286 1287 1288 1289 1290
		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) {
1291
					if (authority) {
1292 1293
						if (url.authority !== authority) {
							this.logService.error('more than one extension development path authority');
1294 1295
						}
					} else {
1296
						authority = url.authority;
1297 1298 1299
					}
				}
			}
1300 1301 1302 1303 1304 1305 1306 1307
		}

		// 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);
1308
			if (!!findWindowOnWorkspaceOrFolderUri(WindowsMainService.WINDOWS, uri)) {
1309
				return false;
1310
			}
1311 1312
			return uri.authority === authority;
		});
1313

1314 1315
		folderUris = folderUris.filter(uri => {
			const u = this.argToUri(uri);
1316
			if (!!findWindowOnWorkspaceOrFolderUri(WindowsMainService.WINDOWS, u)) {
1317 1318 1319 1320 1321 1322 1323
				return false;
			}
			return u ? u.authority === authority : false;
		});

		fileUris = fileUris.filter(uri => {
			const u = this.argToUri(uri);
1324
			if (!!findWindowOnWorkspaceOrFolderUri(WindowsMainService.WINDOWS, u)) {
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
				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
1335 1336 1337
		const noFilesOrFolders = !cliArgs.length && !folderUris.length && !fileUris.length;
		if (noFilesOrFolders && authority) {
			openConfig.cli.remote = authority;
1338 1339
		}

B
Benjamin Pasero 已提交
1340
		// Open it
M
Martin Aeschlimann 已提交
1341 1342 1343 1344
		const openArgs: IOpenConfiguration = {
			context: openConfig.context,
			cli: openConfig.cli,
			forceNewWindow: true,
1345
			forceEmpty: noFilesOrFolders,
M
Martin Aeschlimann 已提交
1346 1347 1348 1349
			userEnv: openConfig.userEnv,
			noRecentEntry: true,
			waitMarkerFileURI: openConfig.waitMarkerFileURI
		};
1350 1351

		return this.open(openArgs);
E
Erich Gamma 已提交
1352 1353
	}

1354
	private openInBrowserWindow(options: IOpenBrowserWindowOptions): ICodeWindow {
1355

1356 1357
		// Build INativeWindowConfiguration from config and options
		const configuration: INativeWindowConfiguration = mixin({}, options.cli); // inherit all properties from CLI
B
Benjamin Pasero 已提交
1358
		configuration.appRoot = this.environmentService.appRoot;
1359
		configuration.machineId = this.machineId;
1360
		configuration.nodeCachedDataDir = this.environmentService.nodeCachedDataDir;
1361
		configuration.mainPid = process.pid;
B
Benjamin Pasero 已提交
1362
		configuration.execPath = process.execPath;
1363
		configuration.userEnv = { ...this.initialUserEnv, ...options.userEnv };
B
Benjamin Pasero 已提交
1364
		configuration.isInitialStartup = options.initialStartup;
1365
		configuration.workspace = options.workspace;
1366
		configuration.folderUri = options.folderUri;
M
Martin Aeschlimann 已提交
1367
		configuration.remoteAuthority = options.remoteAuthority;
1368 1369 1370

		const fileInputs = options.fileInputs;
		if (fileInputs) {
1371
			configuration.filesToOpenOrCreate = fileInputs.filesToOpenOrCreate;
1372 1373 1374
			configuration.filesToDiff = fileInputs.filesToDiff;
			configuration.filesToWait = fileInputs.filesToWait;
		}
B
Benjamin Pasero 已提交
1375

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

1384
		let window: ICodeWindow | undefined;
1385
		if (!options.forceNewWindow && !options.forceNewTabbedWindow) {
1386 1387 1388
			window = options.windowToUse || this.getLastActiveWindow();
			if (window) {
				window.focus();
E
Erich Gamma 已提交
1389 1390 1391 1392
			}
		}

		// New window
1393
		if (!window) {
1394
			const windowConfig = this.configurationService.getValue<IWindowSettings>('window');
1395 1396 1397 1398 1399
			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 已提交
1400
				allowFullscreen = (windowConfig?.newWindowDimensions && ['fullscreen', 'inherit', 'offset'].indexOf(windowConfig.newWindowDimensions) >= 0);
1401 1402 1403 1404
			}

			// Window state is from a previous session: only allow fullscreen when we got updated or user wants to restore
			else {
B
Benjamin Pasero 已提交
1405
				allowFullscreen = this.lifecycleMainService.wasRestarted || windowConfig?.restoreFullscreen;
B
Benjamin Pasero 已提交
1406 1407 1408 1409 1410 1411 1412 1413 1414

				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;
				}
1415 1416 1417 1418 1419
			}

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

1421
			// Create the window
1422
			const createdWindow = window = this.instantiationService.createInstance(CodeWindow, {
1423
				state,
1424
				extensionDevelopmentPath: configuration.extensionDevelopmentPath,
1425
				isExtensionTestHost: !!configuration.extensionTestsPath
1426
			});
1427

1428 1429 1430 1431 1432 1433 1434 1435
			// Add as window tab if configured (macOS only)
			if (options.forceNewTabbedWindow) {
				const activeWindow = this.getLastActiveWindow();
				if (activeWindow) {
					activeWindow.addTabbedWindow(window);
				}
			}

B
Benjamin Pasero 已提交
1436
			// Add to our list of windows
1437
			WindowsMainService.WINDOWS.push(window);
E
Erich Gamma 已提交
1438

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

E
Erich Gamma 已提交
1442
			// Window Events
1443 1444
			once(window.onClose)(() => this.onWindowClosed(createdWindow));
			once(window.onDestroy)(() => this.onBeforeWindowClose(createdWindow)); // try to save state before destroy because close will not fire
1445
			window.win.webContents.removeAllListeners('devtools-reload-page'); // remove built in listener so we can handle this on our own
1446
			window.win.webContents.on('devtools-reload-page', () => this.lifecycleMainService.reload(createdWindow));
E
Erich Gamma 已提交
1447 1448

			// Lifecycle
1449
			(this.lifecycleMainService as LifecycleMainService).registerWindow(window);
E
Erich Gamma 已提交
1450 1451 1452 1453 1454 1455
		}

		// Existing window
		else {

			// Some configuration things get inherited if the window is being reused and we are
B
Benjamin Pasero 已提交
1456
			// in extension development host mode. These options are all development related.
1457
			const currentWindowConfig = window.config;
A
Alex Dima 已提交
1458 1459
			if (!configuration.extensionDevelopmentPath && currentWindowConfig && !!currentWindowConfig.extensionDevelopmentPath) {
				configuration.extensionDevelopmentPath = currentWindowConfig.extensionDevelopmentPath;
B
Benjamin Pasero 已提交
1460
				configuration.verbose = currentWindowConfig.verbose;
1461
				configuration['inspect-brk-extensions'] = currentWindowConfig['inspect-brk-extensions'];
1462
				configuration.debugId = currentWindowConfig.debugId;
1463
				configuration['inspect-extensions'] = currentWindowConfig['inspect-extensions'];
1464
				configuration['extensions-dir'] = currentWindowConfig['extensions-dir'];
E
Erich Gamma 已提交
1465 1466 1467
			}
		}

1468 1469 1470 1471
		// 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) {
1472
			this.lifecycleMainService.unload(window, UnloadReason.LOAD).then(veto => {
1473
				if (!veto) {
M
Matt Bierner 已提交
1474
					this.doOpenInBrowserWindow(window!, configuration, options);
B
Benjamin Pasero 已提交
1475
				}
1476 1477 1478 1479 1480 1481 1482
			});
		} else {
			this.doOpenInBrowserWindow(window, configuration, options);
		}

		return window;
	}
B
Benjamin Pasero 已提交
1483

1484
	private doOpenInBrowserWindow(window: ICodeWindow, configuration: INativeWindowConfiguration, options: IOpenBrowserWindowOptions): void {
1485

1486 1487 1488
		// Register window for backups
		if (!configuration.extensionDevelopmentPath) {
			if (configuration.workspace) {
1489
				configuration.backupPath = this.backupMainService.registerWorkspaceBackupSync({ workspace: configuration.workspace, remoteAuthority: configuration.remoteAuthority });
1490 1491 1492 1493
			} else if (configuration.folderUri) {
				configuration.backupPath = this.backupMainService.registerFolderBackupSync(configuration.folderUri);
			} else {
				const backupFolder = options.emptyWindowBackupInfo && options.emptyWindowBackupInfo.backupFolder;
1494
				configuration.backupPath = this.backupMainService.registerEmptyWindowBackupSync(backupFolder, configuration.remoteAuthority);
E
Erich Gamma 已提交
1495
			}
1496
		}
1497

1498 1499
		// Load it
		window.load(configuration);
E
Erich Gamma 已提交
1500 1501
	}

1502
	private getNewWindowState(configuration: INativeWindowConfiguration): INewWindowState {
1503
		const lastActive = this.getLastActiveWindow();
E
Erich Gamma 已提交
1504

1505 1506
		// Restore state unless we are running extension tests
		if (!configuration.extensionTestsPath) {
E
Erich Gamma 已提交
1507

1508 1509 1510
			// extension development host Window - load from stored settings if any
			if (!!configuration.extensionDevelopmentPath && this.windowsState.lastPluginDevelopmentHostWindow) {
				return this.windowsState.lastPluginDevelopmentHostWindow.uiState;
1511 1512
			}

1513
			// Known Workspace - load from stored settings
M
Matt Bierner 已提交
1514 1515 1516
			const workspace = configuration.workspace;
			if (workspace) {
				const stateForWorkspace = this.windowsState.openedWindows.filter(o => o.workspace && o.workspace.id === workspace.id).map(o => o.uiState);
1517 1518 1519 1520 1521 1522
				if (stateForWorkspace.length) {
					return stateForWorkspace[0];
				}
			}

			// Known Folder - load from stored settings
1523
			if (configuration.folderUri) {
1524
				const stateForFolder = this.windowsState.openedWindows.filter(o => o.folderUri && isEqual(o.folderUri, configuration.folderUri)).map(o => o.uiState);
1525 1526 1527
				if (stateForFolder.length) {
					return stateForFolder[0];
				}
1528 1529
			}

1530 1531 1532 1533 1534 1535
			// 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 已提交
1536 1537
			}

1538 1539 1540 1541 1542
			// First Window
			const lastActiveState = this.lastClosedWindowState || this.windowsState.lastActiveWindow;
			if (!lastActive && lastActiveState) {
				return lastActiveState.uiState;
			}
E
Erich Gamma 已提交
1543 1544 1545 1546 1547 1548 1549
		}

		//
		// 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
1550
		let displayToUse: Display | undefined;
B
Benjamin Pasero 已提交
1551
		const displays = screen.getAllDisplays();
E
Erich Gamma 已提交
1552 1553 1554 1555 1556 1557 1558 1559 1560 1561

		// 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 已提交
1562
			if (isMacintosh) {
B
Benjamin Pasero 已提交
1563
				const cursorPoint = screen.getCursorScreenPoint();
E
Erich Gamma 已提交
1564 1565 1566 1567 1568 1569 1570 1571
				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());
			}

1572
			// fallback to primary display or first display
E
Erich Gamma 已提交
1573
			if (!displayToUse) {
1574
				displayToUse = screen.getPrimaryDisplay() || displays[0];
E
Erich Gamma 已提交
1575 1576 1577
			}
		}

1578 1579 1580
		// 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.
1581
		let state = defaultWindowState();
M
Matt Bierner 已提交
1582 1583
		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 已提交
1584

1585
		// Check for newWindowDimensions setting and adjust accordingly
1586
		const windowConfig = this.configurationService.getValue<IWindowSettings>('window');
1587
		let ensureNoOverlap = true;
B
Benjamin Pasero 已提交
1588
		if (windowConfig?.newWindowDimensions) {
1589 1590 1591 1592 1593 1594
			if (windowConfig.newWindowDimensions === 'maximized') {
				state.mode = WindowMode.Maximized;
				ensureNoOverlap = false;
			} else if (windowConfig.newWindowDimensions === 'fullscreen') {
				state.mode = WindowMode.Fullscreen;
				ensureNoOverlap = false;
S
SteVen Batten 已提交
1595
			} else if ((windowConfig.newWindowDimensions === 'inherit' || windowConfig.newWindowDimensions === 'offset') && lastActive) {
B
Benjamin Pasero 已提交
1596 1597 1598 1599 1600 1601 1602
				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 已提交
1603
				ensureNoOverlap = state.mode !== WindowMode.Fullscreen && windowConfig.newWindowDimensions === 'offset';
1604 1605 1606 1607 1608 1609 1610
			}
		}

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

1611
		(state as INewWindowState).hasDefaultState = true; // flag as default state
1612

1613
		return state;
E
Erich Gamma 已提交
1614 1615
	}

J
Joao Moreno 已提交
1616
	private ensureNoOverlap(state: ISingleWindowState): ISingleWindowState {
1617
		if (WindowsMainService.WINDOWS.length === 0) {
E
Erich Gamma 已提交
1618 1619 1620
			return state;
		}

M
Matt Bierner 已提交
1621 1622 1623
		state.x = typeof state.x === 'number' ? state.x : 0;
		state.y = typeof state.y === 'number' ? state.y : 0;

1624
		const existingWindowBounds = WindowsMainService.WINDOWS.map(win => win.getBounds());
1625
		while (existingWindowBounds.some(b => b.x === state.x || b.y === state.y)) {
E
Erich Gamma 已提交
1626 1627 1628 1629 1630 1631 1632
			state.x += 30;
			state.y += 30;
		}

		return state;
	}

B
Benjamin Pasero 已提交
1633
	focusLastActive(cli: ParsedArgs, context: OpenContext): ICodeWindow {
B
Benjamin Pasero 已提交
1634
		const lastActive = this.getLastActiveWindow();
E
Erich Gamma 已提交
1635
		if (lastActive) {
B
Benjamin Pasero 已提交
1636
			lastActive.focus();
1637 1638

			return lastActive;
E
Erich Gamma 已提交
1639 1640
		}

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

M
Matt Bierner 已提交
1645
	getLastActiveWindow(): ICodeWindow | undefined {
1646
		return getLastActiveWindow(WindowsMainService.WINDOWS);
E
Erich Gamma 已提交
1647 1648
	}

1649
	private getLastActiveWindowForAuthority(remoteAuthority: string | undefined): ICodeWindow | undefined {
1650
		return getLastActiveWindow(WindowsMainService.WINDOWS.filter(window => window.remoteAuthority === remoteAuthority));
M
Martin Aeschlimann 已提交
1651 1652
	}

B
Benjamin Pasero 已提交
1653
	sendToFocused(channel: string, ...args: any[]): void {
E
Erich Gamma 已提交
1654 1655 1656
		const focusedWindow = this.getFocusedWindow() || this.getLastActiveWindow();

		if (focusedWindow) {
1657
			focusedWindow.sendWhenReady(channel, ...args);
E
Erich Gamma 已提交
1658 1659 1660
		}
	}

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

B
Benjamin Pasero 已提交
1667 1668
			window.sendWhenReady(channel, payload);
		}
E
Erich Gamma 已提交
1669 1670
	}

1671
	private getFocusedWindow(): ICodeWindow | undefined {
B
Benjamin Pasero 已提交
1672
		const win = BrowserWindow.getFocusedWindow();
E
Erich Gamma 已提交
1673 1674 1675 1676
		if (win) {
			return this.getWindowById(win.id);
		}

M
Matt Bierner 已提交
1677
		return undefined;
E
Erich Gamma 已提交
1678 1679
	}

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

M
Matt Bierner 已提交
1683
		return arrays.firstOrDefault(res);
E
Erich Gamma 已提交
1684 1685
	}

B
Benjamin Pasero 已提交
1686
	getWindows(): ICodeWindow[] {
1687
		return WindowsMainService.WINDOWS;
E
Erich Gamma 已提交
1688 1689
	}

B
Benjamin Pasero 已提交
1690
	getWindowCount(): number {
1691
		return WindowsMainService.WINDOWS.length;
E
Erich Gamma 已提交
1692 1693
	}

1694
	private onWindowClosed(win: ICodeWindow): void {
E
Erich Gamma 已提交
1695 1696

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

		// Emit
1701
		this._onWindowsCountChanged.fire({ oldCount: WindowsMainService.WINDOWS.length + 1, newCount: WindowsMainService.WINDOWS.length });
1702
		this._onWindowClose.fire(win.id);
E
Erich Gamma 已提交
1703
	}
B
Benjamin Pasero 已提交
1704
}