windowsMainService.ts 63.2 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 { ILifecycleMainService, UnloadReason, LifecycleMainService, LifecycleMainPhase } from 'vs/platform/lifecycle/electron-main/lifecycleMainService';
20
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
21
import { ILogService } from 'vs/platform/log/common/log';
22
import { IWindowSettings, IPath, isFileToOpen, isWorkspaceToOpen, isFolderToOpen, IWindowOpenable, IOpenEmptyWindowOptions, IAddFoldersRequest } from 'vs/platform/windows/common/windows';
23
import { getLastActiveWindow, findBestWindowOrFolderForFile, findWindowOnWorkspace, findWindowOnExtensionDevelopmentPath, findWindowOnWorkspaceOrFolderUri, INativeWindowConfiguration, OpenContext, IPathsToWaitFor } from 'vs/platform/windows/node/window';
24
import { Emitter } from 'vs/base/common/event';
25
import product from 'vs/platform/product/common/product';
26
import { IWindowsMainService, IOpenConfiguration, IWindowsCountChangedEvent, ICodeWindow, IWindowState as ISingleWindowState, WindowMode, IOpenEmptyConfiguration } from 'vs/platform/windows/electron-main/windows';
27
import { IWorkspacesHistoryMainService } from 'vs/platform/workspaces/electron-main/workspacesHistoryMainService';
28
import { IProcessEnvironment, isMacintosh, isWindows } from 'vs/base/common/platform';
29
import { IWorkspaceIdentifier, isSingleFolderWorkspaceIdentifier, hasWorkspaceFileExtension, IRecent } from 'vs/platform/workspaces/common/workspaces';
B
Benjamin Pasero 已提交
30
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
J
Johannes Rieken 已提交
31
import { Schemas } from 'vs/base/common/network';
32
import { URI } from 'vs/base/common/uri';
33
import { normalizePath, originalFSPath, removeTrailingPathSeparator, extUriBiasedIgnorePathCase } from 'vs/base/common/resources';
M
Martin Aeschlimann 已提交
34
import { getRemoteAuthority } from 'vs/platform/remote/common/remoteHosts';
35
import { restoreWindowsState, WindowsStateStorageData, getWindowsStateStoreData } from 'vs/platform/windows/electron-main/windowsStateStorage';
B
Benjamin Pasero 已提交
36
import { getWorkspaceIdentifier, IWorkspacesMainService } from 'vs/platform/workspaces/electron-main/workspacesMainService';
37
import { once } from 'vs/base/common/functional';
M
Matt Bierner 已提交
38
import { Disposable } from 'vs/base/common/lifecycle';
39 40
import { IDialogMainService } from 'vs/platform/dialogs/electron-main/dialogs';
import { withNullAsUndefined } from 'vs/base/common/types';
41
import { isWindowsDriveLetter, toSlashes, parseLineAndColumnAware } from 'vs/base/common/extpath';
42
import { CharCode } from 'vs/base/common/charCode';
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 66
interface IOpenBrowserWindowOptions {
	userEnv?: IProcessEnvironment;
	cli?: ParsedArgs;
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 _onWindowClose = this._register(new Emitter<number>());
170
	readonly onWindowClose = this._onWindowClose.event;
171

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

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

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

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

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

	private registerListeners(): void {
214

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

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

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

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

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

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

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

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

		this.saveWindowsState();
	}

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

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

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

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

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

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

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

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

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

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

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

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

B
Benjamin Pasero 已提交
402
		const forceReuseWindow = options?.forceReuseWindow;
403 404
		const forceNewWindow = !forceReuseWindow;

405
		return this.open({ ...openConfig, cli, forceEmpty: true, forceNewWindow, forceReuseWindow });
406 407
	}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

538 539 540
		return usedWindows;
	}

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

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

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

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

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

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

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

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

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

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

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

				// Window is empty
				else {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

			// Open remaining ones
697
			allFoldersToOpen.forEach(folderToOpen => {
698

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

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

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

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

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

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

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

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

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

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

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

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

756
				// Reset these because we handled them
R
Rob Lourens 已提交
757
				fileInputs = undefined;
758
				openFolderInNewWindow = true; // any other window to open must open in new window then
759 760
			}
		}
E
Erich Gamma 已提交
761

762
		return arrays.distinct(usedWindows);
E
Erich Gamma 已提交
763 764
	}

765
	private doOpenFilesInExistingWindow(configuration: IOpenConfiguration, window: ICodeWindow, fileInputs?: IFileInputs): ICodeWindow {
766 767
		window.focus(); // make sure window has focus

768
		const params: { filesToOpenOrCreate?: IPath[], filesToDiff?: IPath[], filesToWait?: IPathsToWaitFor, termProgram?: string } = {};
B
Benjamin Pasero 已提交
769
		if (fileInputs) {
770
			params.filesToOpenOrCreate = fileInputs.filesToOpenOrCreate;
B
Benjamin Pasero 已提交
771 772 773 774 775 776 777 778 779
			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 已提交
780 781

		return window;
782 783
	}

784
	private doAddFoldersToExistingWindow(window: ICodeWindow, foldersToAdd: URI[]): ICodeWindow {
785 786
		window.focus(); // make sure window has focus

B
Benjamin Pasero 已提交
787 788 789
		const request: IAddFoldersRequest = { foldersToAdd };

		window.sendWhenReady('vscode:addFolders', request);
790 791 792 793

		return window;
	}

794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
	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 已提交
811
	private doOpenFolderOrWorkspace(openConfig: IOpenConfiguration, folderOrWorkspace: IPathToOpen, forceNewWindow: boolean, fileInputs: IFileInputs | undefined, windowToUse?: ICodeWindow): ICodeWindow {
B
Benjamin Pasero 已提交
812 813 814 815
		if (!forceNewWindow && !windowToUse && typeof openConfig.contextWindowId === 'number') {
			windowToUse = this.getWindowById(openConfig.contextWindowId); // fix for https://github.com/Microsoft/vscode/issues/49587
		}

816
		return this.openInBrowserWindow({
817 818 819
			userEnv: openConfig.userEnv,
			cli: openConfig.cli,
			initialStartup: openConfig.initialStartup,
820
			workspace: folderOrWorkspace.workspace,
821
			folderUri: folderOrWorkspace.folderUri,
822
			fileInputs,
M
Martin Aeschlimann 已提交
823
			remoteAuthority: folderOrWorkspace.remoteAuthority,
B
Benjamin Pasero 已提交
824
			forceNewWindow,
825
			forceNewTabbedWindow: openConfig.forceNewTabbedWindow,
826
			windowToUse
827 828 829
		});
	}

B
Benjamin Pasero 已提交
830 831
	private getPathsToOpen(openConfig: IOpenConfiguration): IPathToOpen[] {
		let windowsToOpen: IPathToOpen[];
832
		let isCommandLineOrAPICall = false;
E
Erich Gamma 已提交
833

834
		// Extract paths: from API
S
Sandeep Somavarapu 已提交
835
		if (openConfig.urisToOpen && openConfig.urisToOpen.length > 0) {
836
			windowsToOpen = this.doExtractPathsFromAPI(openConfig);
837
			isCommandLineOrAPICall = true;
E
Erich Gamma 已提交
838 839
		}

B
Benjamin Pasero 已提交
840 841
		// Check for force empty
		else if (openConfig.forceEmpty) {
842
			windowsToOpen = [Object.create(null)];
E
Erich Gamma 已提交
843 844
		}

845
		// Extract paths: from CLI
846
		else if (openConfig.cli._.length || openConfig.cli['folder-uri'] || openConfig.cli['file-uri']) {
847
			windowsToOpen = this.doExtractPathsFromCLI(openConfig.cli);
848
			isCommandLineOrAPICall = true;
B
Benjamin Pasero 已提交
849 850
		}

851
		// Extract windows: from previous session
B
Benjamin Pasero 已提交
852
		else {
853
			windowsToOpen = this.doGetWindowsFromLastSession();
B
Benjamin Pasero 已提交
854 855
		}

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

874
		return windowsToOpen;
E
Erich Gamma 已提交
875 876
	}

877
	private doExtractPathsFromAPI(openConfig: IOpenConfiguration): IPathToOpen[] {
M
Matt Bierner 已提交
878
		const pathsToOpen: IPathToOpen[] = [];
879
		const parseOptions: IPathParseOptions = { gotoLineMode: openConfig.gotoLineMode };
M
Matt Bierner 已提交
880
		for (const pathToOpen of openConfig.urisToOpen || []) {
M
Martin Aeschlimann 已提交
881 882 883 884
			if (!pathToOpen) {
				continue;
			}

M
Martin Aeschlimann 已提交
885
			const path = this.parseUri(pathToOpen, parseOptions);
M
Martin Aeschlimann 已提交
886
			if (path) {
M
Martin Aeschlimann 已提交
887
				path.label = pathToOpen.label;
M
Martin Aeschlimann 已提交
888 889
				pathsToOpen.push(path);
			} else {
890 891
				const uri = this.resourceFromURIToOpen(pathToOpen);

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

910
				this.dialogMainService.showMessageBox(options, withNullAsUndefined(BrowserWindow.getFocusedWindow()));
911
			}
M
Martin Aeschlimann 已提交
912
		}
913 914 915 916
		return pathsToOpen;
	}

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

		// folder uris
921 922 923 924 925 926 927 928 929
		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 已提交
930
				}
M
Martin Aeschlimann 已提交
931
			}
932 933
		}

934

935
		// file uris
936 937 938 939 940 941 942 943 944
		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 已提交
945
				}
M
Martin Aeschlimann 已提交
946
			}
947 948 949
		}

		// folder or file paths
950
		const cliArgs = cli._;
M
Martin Aeschlimann 已提交
951 952 953 954 955
		for (let cliArg of cliArgs) {
			const path = this.parsePath(cliArg, parseOptions);
			if (path) {
				pathsToOpen.push(path);
			}
956 957
		}

M
Martin Aeschlimann 已提交
958
		if (pathsToOpen.length) {
959
			return pathsToOpen;
B
Benjamin Pasero 已提交
960 961 962 963 964 965
		}

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

B
Benjamin Pasero 已提交
966
	private doGetWindowsFromLastSession(): IPathToOpen[] {
967
		const restoreWindows = this.getRestoreWindowsSetting();
B
Benjamin Pasero 已提交
968

969
		switch (restoreWindows) {
B
Benjamin Pasero 已提交
970

971
			// none: we always open an empty window
972 973
			case 'none':
				return [Object.create(null)];
B
Benjamin Pasero 已提交
974

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

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

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

				break;
B
Benjamin Pasero 已提交
1011
		}
E
Erich Gamma 已提交
1012

1013
		// Always fallback to empty window
B
Benjamin Pasero 已提交
1014
		return [Object.create(null)];
E
Erich Gamma 已提交
1015 1016
	}

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

			if (['all', 'folders', 'one', 'none'].indexOf(restoreWindows) === -1) {
B
Benjamin Pasero 已提交
1026
				restoreWindows = 'all'; // by default restore all windows
1027 1028 1029 1030 1031 1032
			}
		}

		return restoreWindows;
	}

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

M
Martin Aeschlimann 已提交
1041 1042
			return uri;
		} catch (e) {
M
Martin Aeschlimann 已提交
1043
			this.logService.error(`Invalid URI input string: ${arg}, ${e.message}`);
1044
		}
1045

1046
		return undefined;
1047 1048
	}

1049 1050
	private parseUri(toOpen: IWindowOpenable, options: IPathParseOptions = {}): IPathToOpen | undefined {
		if (!toOpen) {
1051
			return undefined;
1052
		}
1053

1054
		let uri = this.resourceFromURIToOpen(toOpen);
M
Martin Aeschlimann 已提交
1055
		if (uri.scheme === Schemas.file) {
1056
			return this.parsePath(uri.fsPath, options, isFileToOpen(toOpen));
1057
		}
M
Martin Aeschlimann 已提交
1058 1059

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

1062 1063
		// normalize URI
		uri = normalizePath(uri);
1064 1065

		// remove trailing slash
1066
		uri = removeTrailingPathSeparator(uri);
1067

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

1080
			return {
M
Martin Aeschlimann 已提交
1081 1082
				fileUri: uri,
				remoteAuthority
1083
			};
1084 1085 1086 1087
		}

		// Workspace
		else if (isWorkspaceToOpen(toOpen)) {
M
Martin Aeschlimann 已提交
1088 1089 1090 1091
			return {
				workspace: getWorkspaceIdentifier(uri),
				remoteAuthority
			};
1092
		}
1093 1094

		// Folder
1095
		return {
M
Martin Aeschlimann 已提交
1096 1097
			folderUri: uri,
			remoteAuthority
1098 1099 1100
		};
	}

1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
	private resourceFromURIToOpen(openable: IWindowOpenable): URI {
		if (isWorkspaceToOpen(openable)) {
			return openable.workspaceUri;
		}

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

		return openable.fileUri;
	}

M
Martin Aeschlimann 已提交
1113
	private parsePath(anyPath: string, options: IPathParseOptions, forceOpenWorkspaceAsFile?: boolean): IPathToOpen | undefined {
E
Erich Gamma 已提交
1114
		if (!anyPath) {
1115
			return undefined;
E
Erich Gamma 已提交
1116 1117
		}

1118
		let lineNumber, columnNumber: number | undefined;
1119

1120
		if (options.gotoLineMode) {
1121 1122 1123
			const parsedPath = parseLineAndColumnAware(anyPath);
			lineNumber = parsedPath.line;
			columnNumber = parsedPath.column;
1124

E
Erich Gamma 已提交
1125 1126 1127
			anyPath = parsedPath.path;
		}

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

1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
		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 });

1143 1144 1145 1146 1147 1148 1149
			// 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) {
1150 1151 1152 1153 1154 1155 1156 1157
					return { fileUri: uri, remoteAuthority };
				}
			}
			return { folderUri: uri, remoteAuthority };
		}

		let candidate = normalize(anyPath);

E
Erich Gamma 已提交
1158
		try {
1159

B
Benjamin Pasero 已提交
1160
			const candidateStat = fs.statSync(candidate);
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
			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
						};
1172
					}
1173 1174
				}

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

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

1209
		return undefined;
E
Erich Gamma 已提交
1210 1211
	}

B
Benjamin Pasero 已提交
1212 1213 1214
	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
1215
		const windowConfig = this.configurationService.getValue<IWindowSettings>('window');
B
Benjamin Pasero 已提交
1216 1217
		const openFolderInNewWindowConfig = windowConfig?.openFoldersInNewWindow || 'default' /* default */;
		const openFilesInNewWindowConfig = windowConfig?.openFilesInNewWindow || 'off' /* default */;
1218

B
Benjamin Pasero 已提交
1219
		let openFolderInNewWindow = (openConfig.preferNewWindow || openConfig.forceNewWindow) && !openConfig.forceReuseWindow;
1220 1221
		if (!openConfig.forceNewWindow && !openConfig.forceReuseWindow && (openFolderInNewWindowConfig === 'on' || openFolderInNewWindowConfig === 'off')) {
			openFolderInNewWindow = (openFolderInNewWindowConfig === 'on');
B
Benjamin Pasero 已提交
1222 1223 1224
		}

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

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

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

1245
			// finally check for overrides of default
1246 1247
			if (!openConfig.cli.extensionDevelopmentPath && (openFilesInNewWindowConfig === 'on' || openFilesInNewWindowConfig === 'off')) {
				openFilesInNewWindow = (openFilesInNewWindowConfig === 'on');
B
Benjamin Pasero 已提交
1248 1249 1250
			}
		}

M
Matt Bierner 已提交
1251
		return { openFolderInNewWindow: !!openFolderInNewWindow, openFilesInNewWindow };
B
Benjamin Pasero 已提交
1252 1253
	}

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

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

1264
			return [existingWindow];
B
Benjamin Pasero 已提交
1265
		}
1266 1267
		let folderUris = openConfig.cli['folder-uri'] || [];
		let fileUris = openConfig.cli['file-uri'] || [];
1268
		let cliArgs = openConfig.cli._;
E
Erich Gamma 已提交
1269

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

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

		// 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);
1313
			if (!!findWindowOnWorkspaceOrFolderUri(WindowsMainService.WINDOWS, uri)) {
1314
				return false;
1315
			}
1316 1317
			return uri.authority === authority;
		});
1318

1319 1320
		folderUris = folderUris.filter(uri => {
			const u = this.argToUri(uri);
1321
			if (!!findWindowOnWorkspaceOrFolderUri(WindowsMainService.WINDOWS, u)) {
1322 1323 1324 1325 1326 1327 1328
				return false;
			}
			return u ? u.authority === authority : false;
		});

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

B
Benjamin Pasero 已提交
1345
		// Open it
M
Martin Aeschlimann 已提交
1346 1347 1348 1349
		const openArgs: IOpenConfiguration = {
			context: openConfig.context,
			cli: openConfig.cli,
			forceNewWindow: true,
1350
			forceEmpty: noFilesOrFolders,
M
Martin Aeschlimann 已提交
1351 1352 1353 1354
			userEnv: openConfig.userEnv,
			noRecentEntry: true,
			waitMarkerFileURI: openConfig.waitMarkerFileURI
		};
1355 1356

		return this.open(openArgs);
E
Erich Gamma 已提交
1357 1358
	}

1359
	private openInBrowserWindow(options: IOpenBrowserWindowOptions): ICodeWindow {
1360

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

		const fileInputs = options.fileInputs;
		if (fileInputs) {
1376
			configuration.filesToOpenOrCreate = fileInputs.filesToOpenOrCreate;
1377 1378 1379
			configuration.filesToDiff = fileInputs.filesToDiff;
			configuration.filesToWait = fileInputs.filesToWait;
		}
B
Benjamin Pasero 已提交
1380

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

1389
		let window: ICodeWindow | undefined;
1390
		if (!options.forceNewWindow && !options.forceNewTabbedWindow) {
1391 1392 1393
			window = options.windowToUse || this.getLastActiveWindow();
			if (window) {
				window.focus();
E
Erich Gamma 已提交
1394 1395 1396 1397
			}
		}

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

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

				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;
				}
1420 1421 1422 1423 1424
			}

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

1426
			// Create the window
1427
			const createdWindow = window = this.instantiationService.createInstance(CodeWindow, {
1428
				state,
1429
				extensionDevelopmentPath: configuration.extensionDevelopmentPath,
1430
				isExtensionTestHost: !!configuration.extensionTestsPath
1431
			});
1432

1433 1434 1435 1436 1437 1438 1439 1440
			// Add as window tab if configured (macOS only)
			if (options.forceNewTabbedWindow) {
				const activeWindow = this.getLastActiveWindow();
				if (activeWindow) {
					activeWindow.addTabbedWindow(window);
				}
			}

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

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

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

			// Lifecycle
1454
			(this.lifecycleMainService as LifecycleMainService).registerWindow(window);
E
Erich Gamma 已提交
1455 1456 1457 1458 1459 1460
		}

		// Existing window
		else {

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

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

		return window;
	}
B
Benjamin Pasero 已提交
1488

1489
	private doOpenInBrowserWindow(window: ICodeWindow, configuration: INativeWindowConfiguration, options: IOpenBrowserWindowOptions): void {
1490

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

1503 1504
		// Load it
		window.load(configuration);
E
Erich Gamma 已提交
1505 1506
	}

1507
	private getNewWindowState(configuration: INativeWindowConfiguration): INewWindowState {
1508
		const lastActive = this.getLastActiveWindow();
E
Erich Gamma 已提交
1509

1510 1511
		// Restore state unless we are running extension tests
		if (!configuration.extensionTestsPath) {
E
Erich Gamma 已提交
1512

1513 1514 1515
			// extension development host Window - load from stored settings if any
			if (!!configuration.extensionDevelopmentPath && this.windowsState.lastPluginDevelopmentHostWindow) {
				return this.windowsState.lastPluginDevelopmentHostWindow.uiState;
1516 1517
			}

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

			// Known Folder - load from stored settings
1528
			if (configuration.folderUri) {
1529
				const stateForFolder = this.windowsState.openedWindows.filter(o => o.folderUri && extUriBiasedIgnorePathCase.isEqual(o.folderUri, configuration.folderUri)).map(o => o.uiState);
1530 1531 1532
				if (stateForFolder.length) {
					return stateForFolder[0];
				}
1533 1534
			}

1535 1536 1537 1538 1539 1540
			// 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 已提交
1541 1542
			}

1543 1544 1545 1546 1547
			// First Window
			const lastActiveState = this.lastClosedWindowState || this.windowsState.lastActiveWindow;
			if (!lastActive && lastActiveState) {
				return lastActiveState.uiState;
			}
E
Erich Gamma 已提交
1548 1549 1550 1551 1552 1553 1554
		}

		//
		// 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
1555
		let displayToUse: Display | undefined;
B
Benjamin Pasero 已提交
1556
		const displays = screen.getAllDisplays();
E
Erich Gamma 已提交
1557 1558 1559 1560 1561 1562 1563 1564 1565 1566

		// 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 已提交
1567
			if (isMacintosh) {
B
Benjamin Pasero 已提交
1568
				const cursorPoint = screen.getCursorScreenPoint();
E
Erich Gamma 已提交
1569 1570 1571 1572 1573 1574 1575 1576
				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());
			}

1577
			// fallback to primary display or first display
E
Erich Gamma 已提交
1578
			if (!displayToUse) {
1579
				displayToUse = screen.getPrimaryDisplay() || displays[0];
E
Erich Gamma 已提交
1580 1581 1582
			}
		}

1583 1584 1585
		// 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.
1586
		let state = defaultWindowState();
M
Matt Bierner 已提交
1587 1588
		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 已提交
1589

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

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

1616
		(state as INewWindowState).hasDefaultState = true; // flag as default state
1617

1618
		return state;
E
Erich Gamma 已提交
1619 1620
	}

J
Joao Moreno 已提交
1621
	private ensureNoOverlap(state: ISingleWindowState): ISingleWindowState {
1622
		if (WindowsMainService.WINDOWS.length === 0) {
E
Erich Gamma 已提交
1623 1624 1625
			return state;
		}

M
Matt Bierner 已提交
1626 1627 1628
		state.x = typeof state.x === 'number' ? state.x : 0;
		state.y = typeof state.y === 'number' ? state.y : 0;

1629
		const existingWindowBounds = WindowsMainService.WINDOWS.map(win => win.getBounds());
1630
		while (existingWindowBounds.some(b => b.x === state.x || b.y === state.y)) {
E
Erich Gamma 已提交
1631 1632 1633 1634 1635 1636 1637
			state.x += 30;
			state.y += 30;
		}

		return state;
	}

B
Benjamin Pasero 已提交
1638
	focusLastActive(cli: ParsedArgs, context: OpenContext): ICodeWindow {
B
Benjamin Pasero 已提交
1639
		const lastActive = this.getLastActiveWindow();
E
Erich Gamma 已提交
1640
		if (lastActive) {
B
Benjamin Pasero 已提交
1641
			lastActive.focus();
1642 1643

			return lastActive;
E
Erich Gamma 已提交
1644 1645
		}

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

M
Matt Bierner 已提交
1650
	getLastActiveWindow(): ICodeWindow | undefined {
1651
		return getLastActiveWindow(WindowsMainService.WINDOWS);
E
Erich Gamma 已提交
1652 1653
	}

1654
	private getLastActiveWindowForAuthority(remoteAuthority: string | undefined): ICodeWindow | undefined {
1655
		return getLastActiveWindow(WindowsMainService.WINDOWS.filter(window => window.remoteAuthority === remoteAuthority));
M
Martin Aeschlimann 已提交
1656 1657
	}

B
Benjamin Pasero 已提交
1658
	sendToFocused(channel: string, ...args: any[]): void {
E
Erich Gamma 已提交
1659 1660 1661
		const focusedWindow = this.getFocusedWindow() || this.getLastActiveWindow();

		if (focusedWindow) {
1662
			focusedWindow.sendWhenReady(channel, ...args);
E
Erich Gamma 已提交
1663 1664 1665
		}
	}

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

B
Benjamin Pasero 已提交
1672 1673
			window.sendWhenReady(channel, payload);
		}
E
Erich Gamma 已提交
1674 1675
	}

1676
	private getFocusedWindow(): ICodeWindow | undefined {
B
Benjamin Pasero 已提交
1677
		const win = BrowserWindow.getFocusedWindow();
E
Erich Gamma 已提交
1678 1679 1680 1681
		if (win) {
			return this.getWindowById(win.id);
		}

M
Matt Bierner 已提交
1682
		return undefined;
E
Erich Gamma 已提交
1683 1684
	}

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

M
Matt Bierner 已提交
1688
		return arrays.firstOrDefault(res);
E
Erich Gamma 已提交
1689 1690
	}

B
Benjamin Pasero 已提交
1691
	getWindows(): ICodeWindow[] {
1692
		return WindowsMainService.WINDOWS;
E
Erich Gamma 已提交
1693 1694
	}

B
Benjamin Pasero 已提交
1695
	getWindowCount(): number {
1696
		return WindowsMainService.WINDOWS.length;
E
Erich Gamma 已提交
1697 1698
	}

1699
	private onWindowClosed(win: ICodeWindow): void {
E
Erich Gamma 已提交
1700 1701

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

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