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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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 已提交
147 148 149

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

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

154
	_serviceBrand: undefined;
E
Erich Gamma 已提交
155

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

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

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

163 164
	private shuttingDown = false;

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

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

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

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

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

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

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

	private registerListeners(): void {
213

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

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

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

227 228
		// React to HC color scheme changes (Windows)
		if (isWindows) {
229 230
			const onHighContrastChange = () => {
				if (systemPreferences.isInvertedColorScheme() || systemPreferences.isHighContrastColorScheme()) {
231 232 233 234
					this.sendToAll('vscode:enterHighContrast');
				} else {
					this.sendToAll('vscode:leaveHighContrast');
				}
235 236 237 238
			};

			systemPreferences.on('inverted-color-scheme-changed', () => onHighContrastChange());
			systemPreferences.on('high-contrast-color-scheme-changed', () => onHighContrastChange());
239 240
		}

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

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

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

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

		this.saveWindowsState();
	}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

457
		//
458
		// These are windows to restore because of hot-exit or from previous session (only performed once on startup!)
459
		//
460 461
		let foldersToRestore: URI[] = [];
		let workspacesToRestore: IWorkspacePathToOpen[] = [];
B
Benjamin Pasero 已提交
462
		if (openConfig.initialStartup && !openConfig.cli.extensionDevelopmentPath && !openConfig.cli['disable-restore-windows']) {
463
			let foldersToRestore = this.backupMainService.getFolderBackupPaths();
464
			foldersToAdd.push(...foldersToRestore.map(f => ({ folderUri: f, remoteAuhority: getRemoteAuthority(f), isRestored: true })));
465

466 467 468
			// collect from workspaces with hot-exit backups and from previous window session
			workspacesToRestore = [...this.backupMainService.getWorkspaceBackups(), ...this.workspacesMainService.getUntitledWorkspacesSync()];
			workspacesToOpen.push(...workspacesToRestore);
469

470 471 472
			emptyToRestore.push(...this.backupMainService.getEmptyWindowBackupPaths());
		} else {
			emptyToRestore.length = 0;
473
		}
474 475

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

478
		// Make sure to pass focus to the most relevant of the windows if we open multiple
479
		if (usedWindows.length > 1) {
480

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

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

495 496 497 498 499
			// 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 (
500 501 502
						(usedWindow.openedWorkspace && workspacesToRestore.some(workspace => usedWindow.openedWorkspace && workspace.workspace.id === usedWindow.openedWorkspace.id)) ||	// skip over restored workspace
						(usedWindow.openedFolderUri && foldersToRestore.some(uri => isEqual(uri, usedWindow.openedFolderUri))) ||															// skip over restored folder
						(usedWindow.backupPath && emptyToRestore.some(empty => usedWindow.backupPath && empty.backupFolder === basename(usedWindow.backupPath)))							// skip over restored empty window
503 504 505 506 507 508 509 510 511 512 513 514
					) {
						continue;
					}

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

			// 3.) finally, always ensure to have at least last used window focused
			if (focusLastWindow) {
515
				usedWindows[usedWindows.length - 1].focus();
516 517
			}
		}
518

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

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

544 545 546
		return usedWindows;
	}

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

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

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

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

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

584
			// Find suitable window or folder path to open files in
585
			const fileToCheck = fileInputs.filesToOpenOrCreate[0] || fileInputs.filesToDiff[0];
586

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

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

598 599 600 601 602
			// We found a window to open the files in
			if (bestWindowOrFolder instanceof CodeWindow) {

				// Window is workspace
				if (bestWindowOrFolder.openedWorkspace) {
603
					workspacesToOpen.push({ workspace: bestWindowOrFolder.openedWorkspace, remoteAuthority: bestWindowOrFolder.remoteAuthority });
604 605 606
				}

				// Window is single folder
607
				else if (bestWindowOrFolder.openedFolderUri) {
608
					foldersToOpen.push({ folderUri: bestWindowOrFolder.openedFolderUri, remoteAuthority: bestWindowOrFolder.remoteAuthority });
609 610 611 612 613 614
				}

				// Window is empty
				else {

					// Do open files
615
					usedWindows.push(this.doOpenFilesInExistingWindow(openConfig, bestWindowOrFolder, fileInputs));
616 617

					// Reset these because we handled them
R
Rob Lourens 已提交
618
					fileInputs = undefined;
619
				}
620 621 622
			}

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

634
				// Reset these because we handled them
R
Rob Lourens 已提交
635
				fileInputs = undefined;
E
Erich Gamma 已提交
636 637 638
			}
		}

639
		// Handle workspaces to open (instructed and to restore)
640
		const allWorkspacesToOpen = arrays.distinct(workspacesToOpen, workspace => workspace.workspace.id); // prevent duplicates
641 642 643
		if (allWorkspacesToOpen.length > 0) {

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

				// Do open files
650
				usedWindows.push(this.doOpenFilesInExistingWindow(openConfig, windowOnWorkspace, fileInputsForWindow));
651 652

				// Reset these because we handled them
653
				if (fileInputsForWindow) {
R
Rob Lourens 已提交
654
					fileInputs = undefined;
655
				}
656 657 658 659 660 661

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

			// Open remaining ones
			allWorkspacesToOpen.forEach(workspaceToOpen => {
662
				if (windowsOnWorkspace.some(win => win.openedWorkspace && win.openedWorkspace.id === workspaceToOpen.workspace.id)) {
663 664 665
					return; // ignore folders that are already open
				}

666
				const remoteAuthority = workspaceToOpen.remoteAuthority;
B
Benjamin Pasero 已提交
667
				const fileInputsForWindow = (fileInputs?.remoteAuthority === remoteAuthority) ? fileInputs : undefined;
668

669
				// Do open folder
670
				usedWindows.push(this.doOpenFolderOrWorkspace(openConfig, workspaceToOpen, openFolderInNewWindow, fileInputsForWindow));
671 672

				// Reset these because we handled them
673
				if (fileInputsForWindow) {
R
Rob Lourens 已提交
674
					fileInputs = undefined;
675
				}
676 677 678 679 680

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

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

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

691
				// Do open files
692
				usedWindows.push(this.doOpenFilesInExistingWindow(openConfig, windowOnFolderPath, fileInputsForWindow));
693

E
Erich Gamma 已提交
694
				// Reset these because we handled them
695
				if (fileInputsForWindow) {
R
Rob Lourens 已提交
696
					fileInputs = undefined;
697
				}
E
Erich Gamma 已提交
698

B
Benjamin Pasero 已提交
699
				openFolderInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
700 701 702
			}

			// Open remaining ones
703
			allFoldersToOpen.forEach(folderToOpen => {
704

705
				if (windowsOnFolderPath.some(win => isEqual(win.openedFolderUri, folderToOpen.folderUri))) {
E
Erich Gamma 已提交
706 707 708
					return; // ignore folders that are already open
				}

709
				const remoteAuthority = folderToOpen.remoteAuthority;
B
Benjamin Pasero 已提交
710
				const fileInputsForWindow = (fileInputs?.remoteAuthority === remoteAuthority) ? fileInputs : undefined;
711

712
				// Do open folder
713
				usedWindows.push(this.doOpenFolderOrWorkspace(openConfig, folderToOpen, openFolderInNewWindow, fileInputsForWindow));
E
Erich Gamma 已提交
714 715

				// Reset these because we handled them
716
				if (fileInputsForWindow) {
R
Rob Lourens 已提交
717
					fileInputs = undefined;
718
				}
E
Erich Gamma 已提交
719

B
Benjamin Pasero 已提交
720
				openFolderInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
721 722 723
			});
		}

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

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

B
wip  
Benjamin Pasero 已提交
742
				// Reset these because we handled them
743
				if (fileInputsForWindow) {
R
Rob Lourens 已提交
744
					fileInputs = undefined;
745
				}
B
wip  
Benjamin Pasero 已提交
746

B
Benjamin Pasero 已提交
747
				openFolderInNewWindow = true; // any other folders to open must open in new window then
748 749
			});
		}
B
Benjamin Pasero 已提交
750

751
		// Handle empty to open (only if no other window opened)
752 753 754 755
		if (usedWindows.length === 0 || fileInputs) {
			if (fileInputs && !emptyToOpen) {
				emptyToOpen++;
			}
756

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

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

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

776
		return arrays.distinct(usedWindows);
E
Erich Gamma 已提交
777 778
	}

779
	private doOpenFilesInExistingWindow(configuration: IOpenConfiguration, window: ICodeWindow, fileInputs?: IFileInputs): ICodeWindow {
780 781
		window.focus(); // make sure window has focus

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

		return window;
796 797
	}

798
	private doAddFoldersToExistingWindow(window: ICodeWindow, foldersToAdd: URI[]): ICodeWindow {
799 800
		window.focus(); // make sure window has focus

B
Benjamin Pasero 已提交
801 802 803
		const request: IAddFoldersRequest = { foldersToAdd };

		window.sendWhenReady('vscode:addFolders', request);
804 805 806 807

		return window;
	}

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

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

		return browserWindow;
	}

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

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

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

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

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

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

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

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

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

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

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

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

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

933

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		return restoreWindows;
	}

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

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

1045
		return undefined;
1046 1047
	}

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

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

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

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

		// remove trailing slash
1065 1066
		if (hasTrailingPathSeparator(uri)) {
			uri = removeTrailingPathSeparator(uri);
1067
		}
1068

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

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

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

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

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

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

		return openable.fileUri;
	}

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

1119
		let lineNumber, columnNumber: number | undefined;
1120

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

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

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

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

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

		let candidate = normalize(anyPath);

E
Erich Gamma 已提交
1159
		try {
1160

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		// Existing window
		else {

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

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

		return window;
	}
B
Benjamin Pasero 已提交
1489

1490
	private doOpenInBrowserWindow(window: ICodeWindow, configuration: IWindowConfiguration, options: IOpenBrowserWindowOptions): void {
1491

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		return state;
	}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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