windows.ts 39.8 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7 8 9 10 11 12
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


'use strict';

import events = require('events');
import path = require('path');
import fs = require('fs');

13
import {ipcMain as ipc, app, screen, crashReporter, BrowserWindow, dialog} from 'electron';
E
Erich Gamma 已提交
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46

import platform = require('vs/base/common/platform');
import env = require('vs/workbench/electron-main/env');
import window = require('vs/workbench/electron-main/window');
import lifecycle = require('vs/workbench/electron-main/lifecycle');
import nls = require('vs/nls');
import paths = require('vs/base/common/paths');
import arrays = require('vs/base/common/arrays');
import objects = require('vs/base/common/objects');
import storage = require('vs/workbench/electron-main/storage');
import settings = require('vs/workbench/electron-main/settings');
import {Instance as UpdateManager, IUpdate} from 'vs/workbench/electron-main/update-manager';

const eventEmitter = new events.EventEmitter();

const EventTypes = {
	OPEN: 'open',
	CLOSE: 'close',
	READY: 'ready'
};

export function onOpen<T>(clb: (path: window.IPath) => void): () => void {
	eventEmitter.addListener(EventTypes.OPEN, clb);

	return () => eventEmitter.removeListener(EventTypes.OPEN, clb);
}

export function onReady<T>(clb: (win: window.VSCodeWindow) => void): () => void {
	eventEmitter.addListener(EventTypes.READY, clb);

	return () => eventEmitter.removeListener(EventTypes.READY, clb);
}

47
export function onClose<T>(clb: (id: number) => void): () => void {
E
Erich Gamma 已提交
48 49 50 51 52 53 54 55 56 57 58 59
	eventEmitter.addListener(EventTypes.CLOSE, clb);

	return () => eventEmitter.removeListener(EventTypes.CLOSE, clb);
}

enum WindowError {
	UNRESPONSIVE,
	CRASHED
}

export interface IOpenConfiguration {
	cli: env.ICommandLineArguments;
60
	userEnv?: env.IProcessEnvironment;
E
Erich Gamma 已提交
61
	pathsToOpen?: string[];
62
	preferNewWindow?: boolean;
E
Erich Gamma 已提交
63 64 65
	forceNewWindow?: boolean;
	forceEmpty?: boolean;
	windowToUse?: window.VSCodeWindow;
66
	diffMode?: boolean;
E
Erich Gamma 已提交
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
}

interface IWindowState {
	workspacePath?: string;
	uiState: window.IWindowState;
}

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

export interface IOpenedPathsList {
	folders: string[];
	files: string[];
}

85 86 87 88 89
interface ILogEntry {
	severity: string;
	arguments: any;
}

90 91 92 93 94
interface INativeOpenDialogOptions {
	pickFolders?: boolean;
	pickFiles?: boolean;
}

E
Erich Gamma 已提交
95 96 97 98
export class WindowsManager {

	public static openedPathsListStorageKey = 'openedPathsList';

99
	private static workingDirPickerStorageKey = 'pickerWorkingDir';
E
Erich Gamma 已提交
100 101 102 103
	private static windowsStateStorageKey = 'windowsState';

	private static WINDOWS: window.VSCodeWindow[] = [];

104
	private initialUserEnv: env.IProcessEnvironment;
E
Erich Gamma 已提交
105 106
	private windowsState: IWindowsState;

107
	public ready(initialUserEnv: env.IProcessEnvironment): void {
E
Erich Gamma 已提交
108 109
		this.registerListeners();

110
		this.initialUserEnv = initialUserEnv;
E
Erich Gamma 已提交
111 112 113 114
		this.windowsState = storage.getItem<IWindowsState>(WindowsManager.windowsStateStorageKey) || { openedFolders: [] };
	}

	private registerListeners(): void {
115
		app.on('activate', (event: Event, hasVisibleWindows: boolean) => {
E
Erich Gamma 已提交
116 117 118 119 120 121 122 123 124 125
			env.log('App#activate');

			// Mac only event: reopen last window when we get activated
			if (!hasVisibleWindows) {

				// We want to open the previously opened folder, so we dont pass on the path argument
				let cliArgWithoutPath = objects.clone(env.cliArgs);
				cliArgWithoutPath.pathArguments = [];
				this.windowsState.openedFolders = []; // make sure we do not restore too much

B
Benjamin Pasero 已提交
126
				this.open({ cli: cliArgWithoutPath });
E
Erich Gamma 已提交
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
			}
		});

		let macOpenFiles: string[] = [];
		let runningTimeout: number = null;
		app.on('open-file', (event: Event, path: string) => {
			env.log('App#open-file: ', path);
			event.preventDefault();

			// Keep in array because more might come!
			macOpenFiles.push(path);

			// Clear previous handler if any
			if (runningTimeout !== null) {
				clearTimeout(runningTimeout);
				runningTimeout = null;
			}

			// Handle paths delayed in case more are coming!
			runningTimeout = setTimeout(() => {
147
				this.open({ cli: env.cliArgs, pathsToOpen: macOpenFiles, preferNewWindow: true /* dropping on the dock prefers to open in a new window */ });
E
Erich Gamma 已提交
148 149 150 151 152
				macOpenFiles = [];
				runningTimeout = null;
			}, 100);
		});

153
		settings.manager.onChange((newSettings) => {
E
Erich Gamma 已提交
154
			this.sendToAll('vscode:optionsChange', JSON.stringify({ globalSettings: newSettings }));
155
		}, this);
E
Erich Gamma 已提交
156 157

		ipc.on('vscode:startCrashReporter', (event: any, config: any) => {
B
Benjamin Pasero 已提交
158
			env.log('IPC#vscode:startCrashReporter');
159

E
Erich Gamma 已提交
160 161 162
			crashReporter.start(config);
		});

B
Benjamin Pasero 已提交
163
		ipc.on('vscode:windowOpen', (event, paths: string[], forceNewWindow?: boolean) => {
E
Erich Gamma 已提交
164 165 166
			env.log('IPC#vscode-windowOpen: ', paths);

			if (paths && paths.length) {
B
Benjamin Pasero 已提交
167
				this.open({ cli: env.cliArgs, pathsToOpen: paths, forceNewWindow: forceNewWindow });
E
Erich Gamma 已提交
168 169 170
			}
		});

B
Benjamin Pasero 已提交
171
		ipc.on('vscode:workbenchLoaded', (event, windowId: number) => {
E
Erich Gamma 已提交
172 173 174 175 176 177 178 179 180 181 182
			env.log('IPC#vscode-workbenchLoaded');

			let win = this.getWindowById(windowId);
			if (win) {
				win.setReady();

				// Event
				eventEmitter.emit(EventTypes.READY, win);
			}
		});

B
Benjamin Pasero 已提交
183
		ipc.on('vscode:openFilePicker', () => {
E
Erich Gamma 已提交
184 185
			env.log('IPC#vscode-openFilePicker');

B
Benjamin Pasero 已提交
186
			this.openFilePicker();
E
Erich Gamma 已提交
187 188
		});

189
		ipc.on('vscode:openFolderPicker', (event, forceNewWindow?: boolean) => {
E
Erich Gamma 已提交
190 191
			env.log('IPC#vscode-openFolderPicker');

192 193 194 195 196 197 198
			this.openFolderPicker(forceNewWindow);
		});

		ipc.on('vscode:openFileFolderPicker', (event, forceNewWindow?: boolean) => {
			env.log('IPC#vscode-openFileFolderPicker');

			this.openFileFolderPicker(forceNewWindow);
E
Erich Gamma 已提交
199 200
		});

B
Benjamin Pasero 已提交
201
		ipc.on('vscode:closeFolder', (event, windowId: number) => {
E
Erich Gamma 已提交
202 203 204 205
			env.log('IPC#vscode-closeFolder');

			let win = this.getWindowById(windowId);
			if (win) {
B
Benjamin Pasero 已提交
206
				this.open({ cli: env.cliArgs, forceEmpty: true, windowToUse: win });
E
Erich Gamma 已提交
207 208 209
			}
		});

B
Benjamin Pasero 已提交
210
		ipc.on('vscode:openNewWindow', () => {
E
Erich Gamma 已提交
211 212
			env.log('IPC#vscode-openNewWindow');

B
Benjamin Pasero 已提交
213
			this.openNewWindow();
E
Erich Gamma 已提交
214 215
		});

B
Benjamin Pasero 已提交
216
		ipc.on('vscode:reloadWindow', (event, windowId: number) => {
E
Erich Gamma 已提交
217 218 219 220 221 222 223 224
			env.log('IPC#vscode:reloadWindow');

			let vscodeWindow = this.getWindowById(windowId);
			if (vscodeWindow) {
				this.reload(vscodeWindow);
			}
		});

B
Benjamin Pasero 已提交
225
		ipc.on('vscode:toggleFullScreen', (event, windowId: number) => {
E
Erich Gamma 已提交
226 227 228 229 230 231 232 233
			env.log('IPC#vscode:toggleFullScreen');

			let vscodeWindow = this.getWindowById(windowId);
			if (vscodeWindow) {
				vscodeWindow.toggleFullScreen();
			}
		});

234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
		ipc.on('vscode:setFullScreen', (event, windowId: number, fullscreen: boolean) => {
			env.log('IPC#vscode:setFullScreen');

			let vscodeWindow = this.getWindowById(windowId);
			if (vscodeWindow) {
				vscodeWindow.win.setFullScreen(fullscreen);
			}
		});

		ipc.on('vscode:toggleDevTools', (event, windowId: number) => {
			env.log('IPC#vscode:toggleDevTools');

			let vscodeWindow = this.getWindowById(windowId);
			if (vscodeWindow) {
				vscodeWindow.win.webContents.toggleDevTools();
			}
		});

		ipc.on('vscode:openDevTools', (event, windowId: number) => {
			env.log('IPC#vscode:openDevTools');

			let vscodeWindow = this.getWindowById(windowId);
			if (vscodeWindow) {
				vscodeWindow.win.webContents.openDevTools();
				vscodeWindow.win.show();
			}
		});

		ipc.on('vscode:setRepresentedFilename', (event, windowId: number, fileName: string) => {
			env.log('IPC#vscode:setRepresentedFilename');

			let vscodeWindow = this.getWindowById(windowId);
			if (vscodeWindow) {
				vscodeWindow.win.setRepresentedFilename(fileName);
			}
		});

		ipc.on('vscode:setMenuBarVisibility', (event, windowId: number, visibility: boolean) => {
			env.log('IPC#vscode:setMenuBarVisibility');

			let vscodeWindow = this.getWindowById(windowId);
			if (vscodeWindow) {
				vscodeWindow.win.setMenuBarVisibility(visibility);
			}
		});

		ipc.on('vscode:flashFrame', (event, windowId: number) => {
			env.log('IPC#vscode:flashFrame');

			let vscodeWindow = this.getWindowById(windowId);
			if (vscodeWindow) {
				vscodeWindow.win.flashFrame(!vscodeWindow.win.isFocused());
			}
		});

		ipc.on('vscode:focusWindow', (event, windowId: number) => {
			env.log('IPC#vscode:focusWindow');

			let vscodeWindow = this.getWindowById(windowId);
			if (vscodeWindow) {
				vscodeWindow.win.focus();
			}
		});

		ipc.on('vscode:setDocumentEdited', (event, windowId: number, edited: boolean) => {
			env.log('IPC#vscode:setDocumentEdited');

			let vscodeWindow = this.getWindowById(windowId);
			if (vscodeWindow && vscodeWindow.win.isDocumentEdited() !== edited) {
				vscodeWindow.win.setDocumentEdited(edited);
			}
		});

B
Benjamin Pasero 已提交
307
		ipc.on('vscode:toggleMenuBar', (event, windowId: number) => {
308 309 310 311 312 313 314 315 316
			env.log('IPC#vscode:toggleMenuBar');

			// Update in settings
			let menuBarHidden = storage.getItem(window.VSCodeWindow.menuBarHiddenKey, false);
			let newMenuBarHidden = !menuBarHidden;
			storage.setItem(window.VSCodeWindow.menuBarHiddenKey, newMenuBarHidden);

			// Update across windows
			WindowsManager.WINDOWS.forEach(w => w.setMenuBarVisibility(!newMenuBarHidden));
317 318 319 320 321 322 323 324

			// Inform user if menu bar is now hidden
			if (newMenuBarHidden) {
				let vscodeWindow = this.getWindowById(windowId);
				if (vscodeWindow) {
					vscodeWindow.send('vscode:showInfoMessage', nls.localize('hiddenMenuBar', "You can still access the menu bar by pressing the **Alt** key."));
				}
			}
325 326
		});

B
Benjamin Pasero 已提交
327
		ipc.on('vscode:broadcast', (event, windowId: number, target: string, broadcast: { channel: string; payload: any; }) => {
E
Erich Gamma 已提交
328
			if (broadcast.channel && broadcast.payload) {
B
Benjamin Pasero 已提交
329 330
				env.log('IPC#vscode:broadcast', target, broadcast.channel, broadcast.payload);

331 332 333 334
				// Handle specific events on main side
				this.onBroadcast(broadcast.channel, broadcast.payload);

				// Send to windows
335
				if (target) {
B
Benjamin Pasero 已提交
336
					const otherWindowsWithTarget = WindowsManager.WINDOWS.filter(w => w.id !== windowId && typeof w.openedWorkspacePath === 'string');
337 338 339 340 341
					const directTargetMatch = otherWindowsWithTarget.filter(w => this.isPathEqual(target, w.openedWorkspacePath));
					const parentTargetMatch = otherWindowsWithTarget.filter(w => paths.isEqualOrParent(target, w.openedWorkspacePath));

					const targetWindow = directTargetMatch.length ? directTargetMatch[0] : parentTargetMatch[0]; // prefer direct match over parent match
					if (targetWindow) {
342 343 344 345 346
						targetWindow.send('vscode:broadcast', broadcast);
					}
				} else {
					this.sendToAll('vscode:broadcast', broadcast, [windowId]);
				}
E
Erich Gamma 已提交
347
			}
348 349
		});

B
Benjamin Pasero 已提交
350
		ipc.on('vscode:log', (event, logEntry: ILogEntry) => {
351 352 353 354 355 356 357 358 359 360
			let args = [];
			try {
				let parsed = JSON.parse(logEntry.arguments);
				args.push(...Object.getOwnPropertyNames(parsed).map(o => parsed[o]));
			} catch (error) {
				args.push(logEntry.arguments);
			}

			console[logEntry.severity].apply(console, args);
		});
E
Erich Gamma 已提交
361

362
		ipc.on('vscode:closeExtensionHostWindow', (event, extensionDevelopmentPath: string) => {
B
Benjamin Pasero 已提交
363 364
			env.log('IPC#vscode:closeExtensionHostWindow', extensionDevelopmentPath);

365 366 367 368 369 370
			const windowOnExtension = this.findWindow(null, null, extensionDevelopmentPath);
			if (windowOnExtension) {
				windowOnExtension.win.close();
			}
		});

E
Erich Gamma 已提交
371 372 373 374 375 376 377 378 379 380
		UpdateManager.on('update-downloaded', (update: IUpdate) => {
			this.sendToFocused('vscode:telemetry', { eventName: 'update:downloaded', data: { version: update.version } });

			this.sendToAll('vscode:update-downloaded', JSON.stringify({
				releaseNotes: update.releaseNotes,
				version: update.version,
				date: update.date
			}));
		});

B
Benjamin Pasero 已提交
381
		ipc.on('vscode:update-apply', () => {
E
Erich Gamma 已提交
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
			env.log('IPC#vscode:update-apply');

			if (UpdateManager.availableUpdate) {
				UpdateManager.availableUpdate.quitAndUpdate();
			}
		});

		UpdateManager.on('update-not-available', (explicit: boolean) => {
			this.sendToFocused('vscode:telemetry', { eventName: 'update:notAvailable', data: { explicit } });

			if (explicit) {
				this.sendToFocused('vscode:update-not-available', '');
			}
		});

J
Joao Moreno 已提交
397 398 399 400 401 402
		UpdateManager.on('update-available', (url: string) => {
			if (url) {
				this.sendToFocused('vscode:update-available', url);
			}
		});

E
Erich Gamma 已提交
403 404 405 406 407 408 409 410 411 412 413 414 415
		lifecycle.onBeforeQuit(() => {

			// 0-1 window open: Do not keep the list but just rely on the active window to be stored
			if (WindowsManager.WINDOWS.length < 2) {
				this.windowsState.openedFolders = [];
				return;
			}

			// 2-N windows open: Keep a list of windows that are opened on a specific folder to restore it in the next session as needed
			this.windowsState.openedFolders = WindowsManager.WINDOWS.filter(w => w.readyState === window.ReadyState.READY && !!w.openedWorkspacePath && !w.isPluginDevelopmentHost).map(w => {
				return <IWindowState>{
					workspacePath: w.openedWorkspacePath,
					uiState: w.serializeWindowState()
B
Benjamin Pasero 已提交
416
				};
E
Erich Gamma 已提交
417 418 419 420 421 422
			});
		});

		app.on('will-quit', () => {
			storage.setItem(WindowsManager.windowsStateStorageKey, this.windowsState);
		});
423 424 425 426 427 428 429 430 431 432 433

		let loggedStartupTimes = false;
		onReady(window => {
			if (loggedStartupTimes) {
				return; // only for the first window
			}

			loggedStartupTimes = true;

			window.send('vscode:telemetry', { eventName: 'startupTime', data: { ellapsed: Date.now() - global.vscodeStart } });
		});
E
Erich Gamma 已提交
434 435
	}

436 437 438 439 440 441 442 443
	private onBroadcast(event: string, payload: any): void {

		// Theme changes
		if (event === 'vscode:changeTheme' && typeof payload === 'string') {
			storage.setItem(window.VSCodeWindow.themeStorageKey, payload);
		}
	}

E
Erich Gamma 已提交
444 445 446 447 448 449 450 451 452 453
	public reload(win: window.VSCodeWindow, cli?: env.ICommandLineArguments): void {

		// Only reload when the window has not vetoed this
		lifecycle.manager.unload(win).done((veto) => {
			if (!veto) {
				win.reload(cli);
			}
		});
	}

454
	public open(openConfig: IOpenConfiguration): window.VSCodeWindow[] {
E
Erich Gamma 已提交
455
		let iPathsToOpen: window.IPath[];
456
		let usedWindows: window.VSCodeWindow[] = [];
E
Erich Gamma 已提交
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475

		// Find paths from provided paths if any
		if (openConfig.pathsToOpen && openConfig.pathsToOpen.length > 0) {
			iPathsToOpen = openConfig.pathsToOpen.map((pathToOpen) => {
				let iPath = this.toIPath(pathToOpen, false, openConfig.cli && openConfig.cli.gotoLineMode);

				// Warn if the requested path to open does not exist
				if (!iPath) {
					let options = {
						title: env.product.nameLong,
						type: 'info',
						buttons: [nls.localize('ok', "OK")],
						message: nls.localize('pathNotExistTitle', "Path does not exist"),
						detail: nls.localize('pathNotExistDetail', "The path '{0}' does not seem to exist anymore on disk.", pathToOpen),
						noLink: true
					};

					let activeWindow = BrowserWindow.getFocusedWindow();
					if (activeWindow) {
476
						dialog.showMessageBox(activeWindow, options);
E
Erich Gamma 已提交
477
					} else {
478
						dialog.showMessageBox(options);
E
Erich Gamma 已提交
479 480 481 482 483 484 485 486 487 488
					}
				}

				return iPath;
			});

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

			if (iPathsToOpen.length === 0) {
489
				return null; // indicate to outside that open failed
E
Erich Gamma 已提交
490 491 492 493 494 495 496 497 498 499 500 501 502 503
			}
		}

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

		// Otherwise infer from command line arguments
		else {
			let ignoreFileNotFound = openConfig.cli.pathArguments.length > 0; // we assume the user wants to create this file from command line
			iPathsToOpen = this.cliToPaths(openConfig.cli, ignoreFileNotFound);
		}

504 505
		let filesToOpen: window.IPath[] = [];
		let filesToDiff: window.IPath[] = [];
506 507 508 509 510 511
		let foldersToOpen = iPathsToOpen.filter((iPath) => iPath.workspacePath && !iPath.filePath && !iPath.installExtensionPath);
		let emptyToOpen = iPathsToOpen.filter((iPath) => !iPath.workspacePath && !iPath.filePath && !iPath.installExtensionPath);
		let extensionsToInstall = iPathsToOpen.filter((iPath) => iPath.installExtensionPath).map(ipath => ipath.filePath);
		let filesToCreate = iPathsToOpen.filter((iPath) => !!iPath.filePath && iPath.createFilePath && !iPath.installExtensionPath);

		// Diff mode needs special care
512
		let candidates = iPathsToOpen.filter((iPath) => !!iPath.filePath && !iPath.createFilePath && !iPath.installExtensionPath);
513 514 515 516 517 518 519
		if (openConfig.diffMode) {
			if (candidates.length === 2) {
				filesToDiff = candidates;
			} else {
				emptyToOpen = [Object.create(null)]; // improper use of diffMode, open empty
			}

520
			foldersToOpen = []; // diff is always in empty workspace
B
Benjamin Pasero 已提交
521
			filesToCreate = []; // diff ignores other files that do not exist
522 523 524 525
		} else {
			filesToOpen = candidates;
		}

E
Erich Gamma 已提交
526 527
		let configuration: window.IWindowConfiguration;

528 529
		// Handle files to open/diff or to create when we dont open a folder
		if (!foldersToOpen.length && (filesToOpen.length > 0 || filesToCreate.length > 0 || filesToDiff.length > 0 || extensionsToInstall.length > 0)) {
E
Erich Gamma 已提交
530

531 532 533 534 535 536 537 538 539
			// Let the user settings override how files are open in a new window or same window unless we are forced
			let openFilesInNewWindow: boolean;
			if (openConfig.forceNewWindow) {
				openFilesInNewWindow = true;
			} else {
				openFilesInNewWindow = openConfig.preferNewWindow;
				if (openFilesInNewWindow && !openConfig.cli.extensionDevelopmentPath) { // can be overriden via settings (not for PDE though!)
					openFilesInNewWindow = settings.manager.getValue('window.openFilesInNewWindow', openFilesInNewWindow);
				}
E
Erich Gamma 已提交
540 541 542 543 544
			}

			// Open Files in last instance if any and flag tells us so
			let lastActiveWindow = this.getLastActiveWindow();
			if (!openFilesInNewWindow && lastActiveWindow) {
B
Benjamin Pasero 已提交
545
				lastActiveWindow.focus();
E
Erich Gamma 已提交
546
				lastActiveWindow.ready().then((readyWindow) => {
547
					readyWindow.send('vscode:openFiles', {
E
Erich Gamma 已提交
548
						filesToOpen: filesToOpen,
549 550
						filesToCreate: filesToCreate,
						filesToDiff: filesToDiff
E
Erich Gamma 已提交
551 552 553
					});

					if (extensionsToInstall.length) {
554
						readyWindow.send('vscode:installExtensions', { extensionsToInstall });
E
Erich Gamma 已提交
555 556
					}
				});
557 558

				usedWindows.push(lastActiveWindow);
E
Erich Gamma 已提交
559 560 561 562
			}

			// Otherwise open instance with files
			else {
563
				configuration = this.toConfiguration(openConfig.userEnv || this.initialUserEnv, openConfig.cli, null, filesToOpen, filesToCreate, filesToDiff, extensionsToInstall);
564 565
				let browserWindow = this.openInBrowserWindow(configuration, true /* new window */);
				usedWindows.push(browserWindow);
E
Erich Gamma 已提交
566 567 568 569 570 571

				openConfig.forceNewWindow = true; // any other folders to open must open in new window then
			}
		}

		// Handle folders to open
572
		let openInNewWindow = openConfig.preferNewWindow || openConfig.forceNewWindow;
E
Erich Gamma 已提交
573 574 575 576 577
		if (foldersToOpen.length > 0) {

			// Check for existing instances
			let windowsOnWorkspacePath = arrays.coalesce(foldersToOpen.map((iPath) => this.findWindow(iPath.workspacePath)));
			if (windowsOnWorkspacePath.length > 0) {
578 579 580
				let browserWindow = windowsOnWorkspacePath[0];
				browserWindow.focus(); // just focus one of them
				browserWindow.ready().then((readyWindow) => {
581
					readyWindow.send('vscode:openFiles', {
E
Erich Gamma 已提交
582
						filesToOpen: filesToOpen,
583 584
						filesToCreate: filesToCreate,
						filesToDiff: filesToDiff
E
Erich Gamma 已提交
585 586 587
					});

					if (extensionsToInstall.length) {
588
						readyWindow.send('vscode:installExtensions', { extensionsToInstall });
E
Erich Gamma 已提交
589 590 591
					}
				});

592 593
				usedWindows.push(browserWindow);

E
Erich Gamma 已提交
594 595 596
				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
597
				filesToDiff = [];
E
Erich Gamma 已提交
598 599
				extensionsToInstall = [];

600
				openInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
601 602 603 604
			}

			// Open remaining ones
			foldersToOpen.forEach((folderToOpen) => {
B
Benjamin Pasero 已提交
605
				if (windowsOnWorkspacePath.some((win) => this.isPathEqual(win.openedWorkspacePath, folderToOpen.workspacePath))) {
E
Erich Gamma 已提交
606 607 608
					return; // ignore folders that are already open
				}

609
				configuration = this.toConfiguration(openConfig.userEnv || this.initialUserEnv, openConfig.cli, folderToOpen.workspacePath, filesToOpen, filesToCreate, filesToDiff, extensionsToInstall);
610
				let browserWindow = this.openInBrowserWindow(configuration, openInNewWindow, openInNewWindow ? void 0 : openConfig.windowToUse);
611
				usedWindows.push(browserWindow);
E
Erich Gamma 已提交
612 613 614 615

				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
616
				filesToDiff = [];
E
Erich Gamma 已提交
617 618
				extensionsToInstall = [];

619
				openInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
620 621 622 623 624 625
			});
		}

		// Handle empty
		if (emptyToOpen.length > 0) {
			emptyToOpen.forEach(() => {
626
				let configuration = this.toConfiguration(openConfig.userEnv || this.initialUserEnv, openConfig.cli);
627
				let browserWindow = this.openInBrowserWindow(configuration, openInNewWindow, openInNewWindow ? void 0 : openConfig.windowToUse);
628
				usedWindows.push(browserWindow);
E
Erich Gamma 已提交
629

630
				openInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
631 632 633 634 635 636 637 638 639 640 641 642 643
			});
		}

		// Remember in recent document list
		iPathsToOpen.forEach((iPath) => {
			if (iPath.filePath || iPath.workspacePath) {
				app.addRecentDocument(iPath.filePath || iPath.workspacePath);
			}
		});

		// Emit events
		iPathsToOpen.forEach((iPath) => eventEmitter.emit(EventTypes.OPEN, iPath));

644
		return arrays.distinct(usedWindows);
E
Erich Gamma 已提交
645 646 647 648 649 650 651
	}

	public openPluginDevelopmentHostWindow(openConfig: IOpenConfiguration): void {

		// Reload an existing plugin development host window on the same path
		// We currently do not allow more than one extension development window
		// on the same plugin path.
A
Alex Dima 已提交
652
		let res = WindowsManager.WINDOWS.filter((w) => w.config && this.isPathEqual(w.config.extensionDevelopmentPath, openConfig.cli.extensionDevelopmentPath));
E
Erich Gamma 已提交
653 654
		if (res && res.length === 1) {
			this.reload(res[0], openConfig.cli);
B
Benjamin Pasero 已提交
655
			res[0].focus(); // make sure it gets focus and is restored
E
Erich Gamma 已提交
656 657 658 659

			return;
		}

660 661
		// Fill in previously opened workspace unless an explicit path is provided and we are not unit testing
		if (openConfig.cli.pathArguments.length === 0 && !openConfig.cli.extensionTestsPath) {
E
Erich Gamma 已提交
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
			let workspaceToOpen = this.windowsState.lastPluginDevelopmentHostWindow && this.windowsState.lastPluginDevelopmentHostWindow.workspacePath;
			if (workspaceToOpen) {
				openConfig.cli.pathArguments = [workspaceToOpen];
			}
		}

		// Make sure we are not asked to open a path that is already opened
		if (openConfig.cli.pathArguments.length > 0) {
			res = WindowsManager.WINDOWS.filter((w) => w.openedWorkspacePath && openConfig.cli.pathArguments.indexOf(w.openedWorkspacePath) >= 0);
			if (res.length) {
				openConfig.cli.pathArguments = [];
			}
		}

		// Open it
		this.open({ cli: openConfig.cli, forceNewWindow: true, forceEmpty: openConfig.cli.pathArguments.length === 0 });
	}

680
	private toConfiguration(userEnv: env.IProcessEnvironment, cli: env.ICommandLineArguments, workspacePath?: string, filesToOpen?: window.IPath[], filesToCreate?: window.IPath[], filesToDiff?: window.IPath[], extensionsToInstall?: string[]): window.IWindowConfiguration {
E
Erich Gamma 已提交
681 682 683 684 685
		let configuration: window.IWindowConfiguration = objects.mixin({}, cli); // inherit all properties from CLI
		configuration.execPath = process.execPath;
		configuration.workspacePath = workspacePath;
		configuration.filesToOpen = filesToOpen;
		configuration.filesToCreate = filesToCreate;
686
		configuration.filesToDiff = filesToDiff;
E
Erich Gamma 已提交
687 688
		configuration.extensionsToInstall = extensionsToInstall;
		configuration.appName = env.product.nameLong;
J
Joao Moreno 已提交
689 690
		configuration.applicationName = env.product.applicationName;
		configuration.darwinBundleIdentifier = env.product.darwinBundleIdentifier;
E
Erich Gamma 已提交
691 692 693 694 695 696
		configuration.appRoot = env.appRoot;
		configuration.version = env.version;
		configuration.commitHash = env.product.commit;
		configuration.appSettingsHome = env.appSettingsHome;
		configuration.appSettingsPath = env.appSettingsPath;
		configuration.appKeybindingsPath = env.appKeybindingsPath;
A
Alex Dima 已提交
697
		configuration.userExtensionsHome = env.userExtensionsHome;
698
		configuration.extensionTips = env.product.extensionTips;
699
		configuration.mainIPCHandle = env.mainIPCHandle;
E
Erich Gamma 已提交
700 701 702 703 704 705 706
		configuration.sharedIPCHandle = env.sharedIPCHandle;
		configuration.isBuilt = env.isBuilt;
		configuration.crashReporter = env.product.crashReporter;
		configuration.extensionsGallery = env.product.extensionsGallery;
		configuration.welcomePage = env.product.welcomePage;
		configuration.productDownloadUrl = env.product.downloadUrl;
		configuration.releaseNotesUrl = env.product.releaseNotesUrl;
707
		configuration.licenseUrl = env.product.licenseUrl;
E
Erich Gamma 已提交
708 709 710
		configuration.updateFeedUrl = UpdateManager.feedUrl;
		configuration.updateChannel = UpdateManager.channel;
		configuration.aiConfig = env.product.aiConfig;
S
Sofian Hnaide 已提交
711
		configuration.sendASmile = env.product.sendASmile;
E
Erich Gamma 已提交
712
		configuration.enableTelemetry = env.product.enableTelemetry;
713
		configuration.userEnv = userEnv;
E
Erich Gamma 已提交
714

715 716 717 718
		const recents = this.getRecentlyOpenedPaths(workspacePath, filesToOpen);
		configuration.recentFiles = recents.files;
		configuration.recentFolders = recents.folders;

E
Erich Gamma 已提交
719 720 721
		return configuration;
	}

722 723 724
	private getRecentlyOpenedPaths(workspacePath?: string, filesToOpen?: window.IPath[]): IOpenedPathsList {
		let files: string[];
		let folders: string[];
E
Erich Gamma 已提交
725 726

		// Get from storage
727 728 729 730 731 732 733
		let storedRecents = storage.getItem<IOpenedPathsList>(WindowsManager.openedPathsListStorageKey);
		if (storedRecents) {
			files = storedRecents.files || [];
			folders = storedRecents.folders || [];
		} else {
			files = [];
			folders = [];
E
Erich Gamma 已提交
734 735 736 737
		}

		// Add currently files to open to the beginning if any
		if (filesToOpen) {
738
			files.unshift(...filesToOpen.map(f => f.filePath));
E
Erich Gamma 已提交
739 740 741 742
		}

		// Add current workspace path to beginning if set
		if (workspacePath) {
743
			folders.unshift(workspacePath);
E
Erich Gamma 已提交
744 745
		}

746
		// Clear those dupes
747 748 749 750 751 752
		files = arrays.distinct(files);
		folders = arrays.distinct(folders);

		if (platform.isMacintosh && files.length > 0) {
			files = files.filter(f => folders.indexOf(f) < 0); // TODO@Ben migration (remove in the future)
		}
E
Erich Gamma 已提交
753

754
		// Make sure it is bounded
755 756 757 758
		files = files.slice(0, 10);
		folders = folders.slice(0, 10);

		return { files, folders };
E
Erich Gamma 已提交
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
	}

	private toIPath(anyPath: string, ignoreFileNotFound?: boolean, gotoLineMode?: boolean): window.IPath {
		if (!anyPath) {
			return null;
		}

		let parsedPath: env.IParsedPath;
		if (gotoLineMode) {
			parsedPath = env.parseLineAndColumnAware(anyPath);
			anyPath = parsedPath.path;
		}

		let candidate = path.normalize(anyPath);
		try {
			let candidateStat = fs.statSync(candidate);
			if (candidateStat) {
				return candidateStat.isFile() ?
					{
						filePath: candidate,
						lineNumber: gotoLineMode ? parsedPath.line : void 0,
						columnNumber: gotoLineMode ? parsedPath.column : void 0,
						installExtensionPath: /\.vsix$/i.test(candidate)
					} :
					{ workspacePath: candidate };
			}
		} catch (error) {
			if (ignoreFileNotFound) {
				return { filePath: candidate, createFilePath: true }; // assume this is a file that does not yet exist
			}
		}

		return null;
	}

	private cliToPaths(cli: env.ICommandLineArguments, ignoreFileNotFound?: boolean): window.IPath[] {

		// Check for pass in candidate or last opened path
		let candidates: string[] = [];
		if (cli.pathArguments.length > 0) {
			candidates = cli.pathArguments;
		}

		// No path argument, check settings for what to do now
		else {
			let reopenFolders = settings.manager.getValue('window.reopenFolders', 'one');
			let lastActiveFolder = this.windowsState.lastActiveWindow && this.windowsState.lastActiveWindow.workspacePath;

			// Restore all
			if (reopenFolders === 'all') {
				let lastOpenedFolders = this.windowsState.openedFolders.map(o => o.workspacePath);

				// If we have a last active folder, move it to the end
				if (lastActiveFolder) {
					lastOpenedFolders.splice(lastOpenedFolders.indexOf(lastActiveFolder), 1);
					lastOpenedFolders.push(lastActiveFolder);
				}

				candidates.push(...lastOpenedFolders);
			}

			// Restore last active
			else if (lastActiveFolder && (reopenFolders === 'one' || reopenFolders !== 'none')) {
				candidates.push(lastActiveFolder);
			}
		}

		let iPaths = candidates.map((candidate) => this.toIPath(candidate, ignoreFileNotFound, cli.gotoLineMode)).filter((path) => !!path);
		if (iPaths.length > 0) {
			return iPaths;
		}

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

835
	private openInBrowserWindow(configuration: window.IWindowConfiguration, forceNewWindow?: boolean, windowToUse?: window.VSCodeWindow): window.VSCodeWindow {
E
Erich Gamma 已提交
836 837 838 839 840 841
		let vscodeWindow: window.VSCodeWindow;

		if (!forceNewWindow) {
			vscodeWindow = windowToUse || this.getLastActiveWindow();

			if (vscodeWindow) {
B
Benjamin Pasero 已提交
842
				vscodeWindow.focus();
E
Erich Gamma 已提交
843 844 845 846 847
			}
		}

		// New window
		if (!vscodeWindow) {
848 849
			vscodeWindow = new window.VSCodeWindow({
				state: this.getNewWindowState(configuration),
850
				extensionDevelopmentPath: configuration.extensionDevelopmentPath
851 852
			});

E
Erich Gamma 已提交
853 854 855
			WindowsManager.WINDOWS.push(vscodeWindow);

			// Window Events
856 857
			vscodeWindow.win.webContents.on('crashed', () => this.onWindowError(vscodeWindow, WindowError.CRASHED));
			vscodeWindow.win.on('unresponsive', () => this.onWindowError(vscodeWindow, WindowError.UNRESPONSIVE));
E
Erich Gamma 已提交
858 859 860 861 862 863 864 865 866 867 868 869 870
			vscodeWindow.win.on('close', () => this.onBeforeWindowClose(vscodeWindow));
			vscodeWindow.win.on('closed', () => this.onWindowClosed(vscodeWindow));

			// Lifecycle
			lifecycle.manager.registerWindow(vscodeWindow);
		}

		// Existing window
		else {

			// Some configuration things get inherited if the window is being reused and we are
			// in plugin development host mode. These options are all development related.
			let currentWindowConfig = vscodeWindow.config;
A
Alex Dima 已提交
871 872
			if (!configuration.extensionDevelopmentPath && currentWindowConfig && !!currentWindowConfig.extensionDevelopmentPath) {
				configuration.extensionDevelopmentPath = currentWindowConfig.extensionDevelopmentPath;
E
Erich Gamma 已提交
873
				configuration.verboseLogging = currentWindowConfig.verboseLogging;
874 875 876
				configuration.logExtensionHostCommunication = currentWindowConfig.logExtensionHostCommunication;
				configuration.debugBrkExtensionHost = currentWindowConfig.debugBrkExtensionHost;
				configuration.debugExtensionHostPort = currentWindowConfig.debugExtensionHostPort;
B
Benjamin Pasero 已提交
877
				configuration.extensionsHomePath = currentWindowConfig.extensionsHomePath;
E
Erich Gamma 已提交
878 879 880 881 882 883 884 885 886 887 888
			}
		}

		// Only load when the window has not vetoed this
		lifecycle.manager.unload(vscodeWindow).done((veto) => {
			if (!veto) {

				// Load it
				vscodeWindow.load(configuration);
			}
		});
889 890

		return vscodeWindow;
E
Erich Gamma 已提交
891 892 893 894 895
	}

	private getNewWindowState(configuration: window.IWindowConfiguration): window.IWindowState {

		// plugin development host Window - load from stored settings if any
A
Alex Dima 已提交
896
		if (!!configuration.extensionDevelopmentPath && this.windowsState.lastPluginDevelopmentHostWindow) {
E
Erich Gamma 已提交
897 898 899 900 901
			return this.windowsState.lastPluginDevelopmentHostWindow.uiState;
		}

		// Known Folder - load from stored settings if any
		if (configuration.workspacePath) {
B
Benjamin Pasero 已提交
902
			let stateForWorkspace = this.windowsState.openedFolders.filter(o => this.isPathEqual(o.workspacePath, configuration.workspacePath)).map(o => o.uiState);
E
Erich Gamma 已提交
903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
			if (stateForWorkspace.length) {
				return stateForWorkspace[0];
			}
		}

		// First Window
		let lastActive = this.getLastActiveWindow();
		if (!lastActive && this.windowsState.lastActiveWindow) {
			return this.windowsState.lastActiveWindow.uiState;
		}

		//
		// 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
919
		let displayToUse: Electron.Display;
E
Erich Gamma 已提交
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967
		let displays = screen.getAllDisplays();

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

		// Multi Display
		else {

			// on mac there is 1 menu per window so we need to use the monitor where the cursor currently is
			if (platform.isMacintosh) {
				let cursorPoint = screen.getCursorScreenPoint();
				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());
			}

			// fallback to first display
			if (!displayToUse) {
				displayToUse = displays[0];
			}
		}

		let defaultState = window.defaultWindowState();
		defaultState.x = displayToUse.bounds.x + (displayToUse.bounds.width / 2) - (defaultState.width / 2);
		defaultState.y = displayToUse.bounds.y + (displayToUse.bounds.height / 2) - (defaultState.height / 2);

		return this.ensureNoOverlap(defaultState);
	}

	private ensureNoOverlap(state: window.IWindowState): window.IWindowState {
		if (WindowsManager.WINDOWS.length === 0) {
			return state;
		}

		let existingWindowBounds = WindowsManager.WINDOWS.map((win) => win.getBounds());
		while (existingWindowBounds.some((b) => b.x === state.x || b.y === state.y)) {
			state.x += 30;
			state.y += 30;
		}

		return state;
	}

968 969 970 971 972 973 974 975 976 977
	public openFileFolderPicker(forceNewWindow?: boolean): void {
		this.doPickAndOpen({ pickFolders: true, pickFiles: true }, forceNewWindow);
	}

	public openFilePicker(forceNewWindow?: boolean): void {
		this.doPickAndOpen({ pickFiles: true }, forceNewWindow);
	}

	public openFolderPicker(forceNewWindow?: boolean): void {
		this.doPickAndOpen({ pickFolders: true }, forceNewWindow);
E
Erich Gamma 已提交
978 979
	}

980 981
	private doPickAndOpen(options: INativeOpenDialogOptions, forceNewWindow?: boolean): void {
		this.getFileOrFolderPaths(options, (paths: string[]) => {
E
Erich Gamma 已提交
982
			if (paths && paths.length) {
983
				this.open({ cli: env.cliArgs, pathsToOpen: paths, forceNewWindow });
E
Erich Gamma 已提交
984 985 986 987
			}
		});
	}

988
	private getFileOrFolderPaths(options: INativeOpenDialogOptions, clb: (paths: string[]) => void): void {
989
		let workingDir = storage.getItem<string>(WindowsManager.workingDirPickerStorageKey);
E
Erich Gamma 已提交
990 991 992
		let focussedWindow = this.getFocusedWindow();

		let pickerProperties: string[];
993
		if (options.pickFiles && options.pickFolders) {
E
Erich Gamma 已提交
994 995
			pickerProperties = ['multiSelections', 'openDirectory', 'openFile', 'createDirectory'];
		} else {
996
			pickerProperties = ['multiSelections', options.pickFolders ? 'openDirectory' : 'openFile', 'createDirectory'];
E
Erich Gamma 已提交
997 998
		}

999
		dialog.showOpenDialog(focussedWindow && focussedWindow.win, {
E
Erich Gamma 已提交
1000 1001 1002 1003 1004 1005
			defaultPath: workingDir,
			properties: pickerProperties
		}, (paths) => {
			if (paths && paths.length > 0) {

				// Remember path in storage for next time
1006
				storage.setItem(WindowsManager.workingDirPickerStorageKey, path.dirname(paths[0]));
E
Erich Gamma 已提交
1007 1008 1009 1010 1011 1012 1013 1014 1015

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

1016
	public focusLastActive(cli: env.ICommandLineArguments): window.VSCodeWindow {
E
Erich Gamma 已提交
1017 1018
		let lastActive = this.getLastActiveWindow();
		if (lastActive) {
B
Benjamin Pasero 已提交
1019
			lastActive.focus();
1020 1021

			return lastActive;
E
Erich Gamma 已提交
1022 1023 1024
		}

		// No window - open new one
1025 1026 1027 1028
		this.windowsState.openedFolders = []; // make sure we do not open too much
		const res = this.open({ cli: cli });

		return res && res[0];
E
Erich Gamma 已提交
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
	}

	public getLastActiveWindow(): window.VSCodeWindow {
		if (WindowsManager.WINDOWS.length) {
			let lastFocussedDate = Math.max.apply(Math, WindowsManager.WINDOWS.map((w) => w.lastFocusTime));
			let res = WindowsManager.WINDOWS.filter((w) => w.lastFocusTime === lastFocussedDate);
			if (res && res.length) {
				return res[0];
			}
		}

		return null;
	}

1043
	public findWindow(workspacePath: string, filePath?: string, extensionDevelopmentPath?: string): window.VSCodeWindow {
E
Erich Gamma 已提交
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
		if (WindowsManager.WINDOWS.length) {

			// Sort the last active window to the front of the array of windows to test
			let windowsToTest = WindowsManager.WINDOWS.slice(0);
			let lastActiveWindow = this.getLastActiveWindow();
			if (lastActiveWindow) {
				windowsToTest.splice(windowsToTest.indexOf(lastActiveWindow), 1);
				windowsToTest.unshift(lastActiveWindow);
			}

			// Find it
			let res = windowsToTest.filter((w) => {

				// match on workspace
1058
				if (typeof w.openedWorkspacePath === 'string' && (this.isPathEqual(w.openedWorkspacePath, workspacePath))) {
E
Erich Gamma 已提交
1059 1060 1061 1062
					return true;
				}

				// match on file
B
Benjamin Pasero 已提交
1063
				if (typeof w.openedFilePath === 'string' && this.isPathEqual(w.openedFilePath, filePath)) {
E
Erich Gamma 已提交
1064 1065 1066 1067 1068 1069 1070 1071
					return true;
				}

				// match on file path
				if (typeof w.openedWorkspacePath === 'string' && filePath && paths.isEqualOrParent(filePath, w.openedWorkspacePath)) {
					return true;
				}

1072 1073 1074 1075 1076
				// match on extension development path
				if (typeof extensionDevelopmentPath === 'string' && w.extensionDevelopmentPath === extensionDevelopmentPath) {
					return true;
				}

E
Erich Gamma 已提交
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
				return false;
			});

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

		return null;
	}

	public openNewWindow(): void {
		this.open({ cli: env.cliArgs, forceNewWindow: true, forceEmpty: true });
	}

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

		if (focusedWindow) {
1096
			focusedWindow.sendWhenReady(channel, ...args);
E
Erich Gamma 已提交
1097 1098 1099 1100 1101
		}
	}

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

1106
			w.sendWhenReady(channel, payload);
E
Erich Gamma 已提交
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
		});
	}

	public getFocusedWindow(): window.VSCodeWindow {
		let win = BrowserWindow.getFocusedWindow();
		if (win) {
			return this.getWindowById(win.id);
		}

		return null;
	}

	public getWindowById(windowId: number): window.VSCodeWindow {
B
Benjamin Pasero 已提交
1120
		let res = WindowsManager.WINDOWS.filter((w) => w.id === windowId);
E
Erich Gamma 已提交
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
		if (res && res.length === 1) {
			return res[0];
		}

		return null;
	}

	public getWindows(): window.VSCodeWindow[] {
		return WindowsManager.WINDOWS;
	}

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

1136
	private onWindowError(vscodeWindow: window.VSCodeWindow, error: WindowError): void {
E
Erich Gamma 已提交
1137 1138 1139 1140
		console.error(error === WindowError.CRASHED ? '[VS Code]: render process crashed!' : '[VS Code]: detected unresponsive');

		// Unresponsive
		if (error === WindowError.UNRESPONSIVE) {
1141
			dialog.showMessageBox(vscodeWindow.win, {
E
Erich Gamma 已提交
1142 1143
				title: env.product.nameLong,
				type: 'warning',
B
Benjamin Pasero 已提交
1144
				buttons: [nls.localize('reopen', "Reopen"), nls.localize('wait', "Keep Waiting"), nls.localize('close', "Close")],
1145
				message: nls.localize('appStalled', "The window is no longer responding"),
B
Benjamin Pasero 已提交
1146
				detail: nls.localize('appStalledDetail', "You can reopen or close the window or keep waiting."),
E
Erich Gamma 已提交
1147 1148 1149
				noLink: true
			}, (result) => {
				if (result === 0) {
1150 1151
					vscodeWindow.reload();
				} else if (result === 2) {
1152
					this.onBeforeWindowClose(vscodeWindow); // 'close' event will not be fired on destroy(), so run it manually
1153
					vscodeWindow.win.destroy(); // make sure to destroy the window as it is unresponsive
E
Erich Gamma 已提交
1154 1155 1156 1157 1158 1159
				}
			});
		}

		// Crashed
		else {
1160
			dialog.showMessageBox(vscodeWindow.win, {
E
Erich Gamma 已提交
1161 1162
				title: env.product.nameLong,
				type: 'warning',
B
Benjamin Pasero 已提交
1163
				buttons: [nls.localize('reopen', "Reopen"), nls.localize('close', "Close")],
1164
				message: nls.localize('appCrashed', "The window has crashed"),
B
Benjamin Pasero 已提交
1165
				detail: nls.localize('appCrashedDetail', "We are sorry for the inconvenience! You can reopen the window to continue where you left off."),
E
Erich Gamma 已提交
1166 1167
				noLink: true
			}, (result) => {
1168 1169 1170
				if (result === 0) {
					vscodeWindow.reload();
				} else if (result === 1) {
1171
					this.onBeforeWindowClose(vscodeWindow); // 'close' event will not be fired on destroy(), so run it manually
1172 1173
					vscodeWindow.win.destroy(); // make sure to destroy the window as it has crashed
				}
E
Erich Gamma 已提交
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
			});
		}
	}

	private onBeforeWindowClose(win: window.VSCodeWindow): void {
		if (win.readyState !== window.ReadyState.READY) {
			return; // only persist windows that are fully loaded
		}

		// On Window close, update our stored state of this window
		let state: IWindowState = { workspacePath: win.openedWorkspacePath, uiState: win.serializeWindowState() };
		if (win.isPluginDevelopmentHost) {
			this.windowsState.lastPluginDevelopmentHostWindow = state;
		} else {
			this.windowsState.lastActiveWindow = state;

			this.windowsState.openedFolders.forEach(o => {
B
Benjamin Pasero 已提交
1191
				if (this.isPathEqual(o.workspacePath, win.openedWorkspacePath)) {
E
Erich Gamma 已提交
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
					o.uiState = state.uiState;
				}
			});
		}
	}

	private onWindowClosed(win: window.VSCodeWindow): void {

		// Tell window
		win.dispose();

		// Remove from our list so that Electron can clean it up
		let index = WindowsManager.WINDOWS.indexOf(win);
		WindowsManager.WINDOWS.splice(index, 1);

		// Emit
1208
		eventEmitter.emit(EventTypes.CLOSE, win.id);
E
Erich Gamma 已提交
1209
	}
B
Benjamin Pasero 已提交
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233

	private isPathEqual(pathA: string, pathB: string): boolean {
		if (pathA === pathB) {
			return true;
		}

		if (!pathA || !pathB) {
			return false;
		}

		pathA = path.normalize(pathA);
		pathB = path.normalize(pathB);

		if (pathA === pathB) {
			return true;
		}

		if (!platform.isLinux) {
			pathA = pathA.toLowerCase();
			pathB = pathB.toLowerCase();
		}

		return pathA === pathB;
	}
E
Erich Gamma 已提交
1234 1235 1236
}

export const manager = new WindowsManager();