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

'use strict';

J
Joao Moreno 已提交
8
import * as path from 'path';
B
Benjamin Pasero 已提交
9
import * as fs from 'original-fs';
J
Joao Moreno 已提交
10 11 12 13 14
import * as platform from 'vs/base/common/platform';
import * as nls from 'vs/nls';
import * as paths from 'vs/base/common/paths';
import * as arrays from 'vs/base/common/arrays';
import * as objects from 'vs/base/common/objects';
J
Joao Moreno 已提交
15
import pkg from 'vs/platform/package';
J
Joao Moreno 已提交
16 17 18 19
import { EventEmitter } from 'events';
import { IStorageService } from 'vs/code/electron-main/storage';
import { IPath, VSCodeWindow, ReadyState, IWindowConfiguration, IWindowState as ISingleWindowState, defaultWindowState } from 'vs/code/electron-main/window';
import { ipcMain as ipc, app, screen, crashReporter, BrowserWindow, dialog } from 'electron';
20 21
import { ICommandLineArguments, IProcessEnvironment, IEnvironmentService, IParsedPath, parseLineAndColumnAware } from 'vs/code/electron-main/env';
import { ILifecycleService } from 'vs/code/electron-main/lifecycle';
J
Joao Moreno 已提交
22 23
import { ISettingsService } from 'vs/code/electron-main/settings';
import { IUpdateService, IUpdate } from 'vs/code/electron-main/update-manager';
B
Benjamin Pasero 已提交
24
import { ILogService } from 'vs/code/electron-main/log';
J
Joao Moreno 已提交
25
import { ServiceIdentifier, createDecorator, IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
E
Erich Gamma 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38

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

enum WindowError {
	UNRESPONSIVE,
	CRASHED
}

export interface IOpenConfiguration {
J
Joao Moreno 已提交
39 40
	cli: ICommandLineArguments;
	userEnv?: IProcessEnvironment;
E
Erich Gamma 已提交
41
	pathsToOpen?: string[];
42
	preferNewWindow?: boolean;
E
Erich Gamma 已提交
43 44
	forceNewWindow?: boolean;
	forceEmpty?: boolean;
J
Joao Moreno 已提交
45
	windowToUse?: VSCodeWindow;
46
	diffMode?: boolean;
E
Erich Gamma 已提交
47 48 49 50
}

interface IWindowState {
	workspacePath?: string;
J
Joao Moreno 已提交
51
	uiState: ISingleWindowState;
E
Erich Gamma 已提交
52 53 54 55 56 57 58 59 60 61 62 63 64
}

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

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

65 66 67 68 69
interface ILogEntry {
	severity: string;
	arguments: any;
}

70 71 72
interface INativeOpenDialogOptions {
	pickFolders?: boolean;
	pickFiles?: boolean;
73 74
	path?: string;
	forceNewWindow?: boolean;
75 76
}

77 78 79 80 81 82
const ReopenFoldersSetting = {
	ALL: 'all',
	ONE: 'one',
	NONE: 'none'
};

J
renames  
Joao Moreno 已提交
83
export const IWindowsService = createDecorator<IWindowsService>('windowsService');
J
Joao Moreno 已提交
84

J
renames  
Joao Moreno 已提交
85
export interface IWindowsService {
J
Joao Moreno 已提交
86 87 88 89
	serviceId: ServiceIdentifier<any>;

	// TODO make proper events
	// events
J
Joao Moreno 已提交
90 91
	onOpen(clb: (path: IPath) => void): () => void;
	onReady(clb: (win: VSCodeWindow) => void): () => void;
J
Joao Moreno 已提交
92 93 94
	onClose(clb: (id: number) => void): () => void;

	// methods
J
Joao Moreno 已提交
95
	ready(initialUserEnv: IProcessEnvironment): void;
J
Joao Moreno 已提交
96 97
	reload(win: VSCodeWindow, cli?: ICommandLineArguments): void;
	open(openConfig: IOpenConfiguration): VSCodeWindow[];
J
Joao Moreno 已提交
98 99 100 101
	openPluginDevelopmentHostWindow(openConfig: IOpenConfiguration): void;
	openFileFolderPicker(forceNewWindow?: boolean): void;
	openFilePicker(forceNewWindow?: boolean): void;
	openFolderPicker(forceNewWindow?: boolean): void;
J
Joao Moreno 已提交
102 103 104
	focusLastActive(cli: ICommandLineArguments): VSCodeWindow;
	getLastActiveWindow(): VSCodeWindow;
	findWindow(workspacePath: string, filePath?: string, extensionDevelopmentPath?: string): VSCodeWindow;
J
Joao Moreno 已提交
105 106 107
	openNewWindow(): void;
	sendToFocused(channel: string, ...args: any[]): void;
	sendToAll(channel: string, payload: any, windowIdsToIgnore?: number[]): void;
J
Joao Moreno 已提交
108 109 110
	getFocusedWindow(): VSCodeWindow;
	getWindowById(windowId: number): VSCodeWindow;
	getWindows(): VSCodeWindow[];
J
Joao Moreno 已提交
111 112 113
	getWindowCount(): number;
}

J
renames  
Joao Moreno 已提交
114
export class WindowsManager implements IWindowsService {
J
Joao Moreno 已提交
115

J
renames  
Joao Moreno 已提交
116
	serviceId = IWindowsService;
E
Erich Gamma 已提交
117 118 119

	public static openedPathsListStorageKey = 'openedPathsList';

120
	private static workingDirPickerStorageKey = 'pickerWorkingDir';
E
Erich Gamma 已提交
121 122
	private static windowsStateStorageKey = 'windowsState';

J
Joao Moreno 已提交
123
	private static WINDOWS: VSCodeWindow[] = [];
E
Erich Gamma 已提交
124

J
Joao Moreno 已提交
125
	private eventEmitter = new EventEmitter();
J
Joao Moreno 已提交
126
	private initialUserEnv: IProcessEnvironment;
E
Erich Gamma 已提交
127 128
	private windowsState: IWindowsState;

J
Joao Moreno 已提交
129 130 131
	constructor(
		@IInstantiationService private instantiationService: IInstantiationService,
		@ILogService private logService: ILogService,
J
Joao Moreno 已提交
132
		@IStorageService private storageService: IStorageService,
J
renames  
Joao Moreno 已提交
133
		@IEnvironmentService private envService: IEnvironmentService,
J
Joao Moreno 已提交
134
		@ILifecycleService private lifecycleService: ILifecycleService,
B
Benjamin Pasero 已提交
135 136
		@IUpdateService private updateService: IUpdateService,
		@ISettingsService private settingsService: ISettingsService
J
Joao Moreno 已提交
137 138
	) {	}

J
Joao Moreno 已提交
139
	onOpen(clb: (path: IPath) => void): () => void {
J
Joao Moreno 已提交
140 141 142 143 144
		this.eventEmitter.addListener(EventTypes.OPEN, clb);

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

J
Joao Moreno 已提交
145
	onReady(clb: (win: VSCodeWindow) => void): () => void {
J
Joao Moreno 已提交
146 147 148 149 150 151 152 153 154 155 156
		this.eventEmitter.addListener(EventTypes.READY, clb);

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

	onClose(clb: (id: number) => void): () => void {
		this.eventEmitter.addListener(EventTypes.CLOSE, clb);

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

J
Joao Moreno 已提交
157
	public ready(initialUserEnv: IProcessEnvironment): void {
E
Erich Gamma 已提交
158 159
		this.registerListeners();

160
		this.initialUserEnv = initialUserEnv;
J
Joao Moreno 已提交
161
		this.windowsState = this.storageService.getItem<IWindowsState>(WindowsManager.windowsStateStorageKey) || { openedFolders: [] };
E
Erich Gamma 已提交
162 163 164
	}

	private registerListeners(): void {
165
		app.on('activate', (event: Event, hasVisibleWindows: boolean) => {
J
Joao Moreno 已提交
166
			this.logService.log('App#activate');
E
Erich Gamma 已提交
167

G
Giorgos Retsinas 已提交
168
			// Mac only event: open new window when we get activated
E
Erich Gamma 已提交
169
			if (!hasVisibleWindows) {
G
Giorgos Retsinas 已提交
170
				this.openNewWindow();
E
Erich Gamma 已提交
171 172 173 174 175 176
			}
		});

		let macOpenFiles: string[] = [];
		let runningTimeout: number = null;
		app.on('open-file', (event: Event, path: string) => {
J
Joao Moreno 已提交
177
			this.logService.log('App#open-file: ', path);
E
Erich Gamma 已提交
178 179 180 181 182 183 184 185 186 187 188 189 190
			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(() => {
J
Joao Moreno 已提交
191
				this.open({ cli: this.envService.cliArgs, pathsToOpen: macOpenFiles, preferNewWindow: true /* dropping on the dock prefers to open in a new window */ });
E
Erich Gamma 已提交
192 193 194 195 196
				macOpenFiles = [];
				runningTimeout = null;
			}, 100);
		});

B
Benjamin Pasero 已提交
197
		this.settingsService.onChange((newSettings) => {
E
Erich Gamma 已提交
198
			this.sendToAll('vscode:optionsChange', JSON.stringify({ globalSettings: newSettings }));
199
		}, this);
E
Erich Gamma 已提交
200 201

		ipc.on('vscode:startCrashReporter', (event: any, config: any) => {
J
Joao Moreno 已提交
202
			this.logService.log('IPC#vscode:startCrashReporter');
203

E
Erich Gamma 已提交
204 205 206
			crashReporter.start(config);
		});

B
Benjamin Pasero 已提交
207
		ipc.on('vscode:windowOpen', (event, paths: string[], forceNewWindow?: boolean) => {
J
Joao Moreno 已提交
208
			this.logService.log('IPC#vscode-windowOpen: ', paths);
E
Erich Gamma 已提交
209 210

			if (paths && paths.length) {
J
Joao Moreno 已提交
211
				this.open({ cli: this.envService.cliArgs, pathsToOpen: paths, forceNewWindow: forceNewWindow });
E
Erich Gamma 已提交
212 213 214
			}
		});

B
Benjamin Pasero 已提交
215
		ipc.on('vscode:workbenchLoaded', (event, windowId: number) => {
J
Joao Moreno 已提交
216
			this.logService.log('IPC#vscode-workbenchLoaded');
E
Erich Gamma 已提交
217 218 219 220 221 222

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

				// Event
J
Joao Moreno 已提交
223
				this.eventEmitter.emit(EventTypes.READY, win);
E
Erich Gamma 已提交
224 225 226
			}
		});

227
		ipc.on('vscode:openFilePicker', (event, forceNewWindow?: boolean, path?: string) => {
J
Joao Moreno 已提交
228
			this.logService.log('IPC#vscode-openFilePicker');
E
Erich Gamma 已提交
229

230
			this.openFilePicker(forceNewWindow, path);
E
Erich Gamma 已提交
231 232
		});

233
		ipc.on('vscode:openFolderPicker', (event, forceNewWindow?: boolean) => {
J
Joao Moreno 已提交
234
			this.logService.log('IPC#vscode-openFolderPicker');
E
Erich Gamma 已提交
235

236 237 238 239
			this.openFolderPicker(forceNewWindow);
		});

		ipc.on('vscode:openFileFolderPicker', (event, forceNewWindow?: boolean) => {
J
Joao Moreno 已提交
240
			this.logService.log('IPC#vscode-openFileFolderPicker');
241 242

			this.openFileFolderPicker(forceNewWindow);
E
Erich Gamma 已提交
243 244
		});

B
Benjamin Pasero 已提交
245
		ipc.on('vscode:closeFolder', (event, windowId: number) => {
J
Joao Moreno 已提交
246
			this.logService.log('IPC#vscode-closeFolder');
E
Erich Gamma 已提交
247 248 249

			let win = this.getWindowById(windowId);
			if (win) {
J
Joao Moreno 已提交
250
				this.open({ cli: this.envService.cliArgs, forceEmpty: true, windowToUse: win });
E
Erich Gamma 已提交
251 252 253
			}
		});

B
Benjamin Pasero 已提交
254
		ipc.on('vscode:openNewWindow', () => {
J
Joao Moreno 已提交
255
			this.logService.log('IPC#vscode-openNewWindow');
E
Erich Gamma 已提交
256

B
Benjamin Pasero 已提交
257
			this.openNewWindow();
E
Erich Gamma 已提交
258 259
		});

B
Benjamin Pasero 已提交
260
		ipc.on('vscode:reloadWindow', (event, windowId: number) => {
J
Joao Moreno 已提交
261
			this.logService.log('IPC#vscode:reloadWindow');
E
Erich Gamma 已提交
262 263 264 265 266 267 268

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

B
Benjamin Pasero 已提交
269
		ipc.on('vscode:toggleFullScreen', (event, windowId: number) => {
J
Joao Moreno 已提交
270
			this.logService.log('IPC#vscode:toggleFullScreen');
E
Erich Gamma 已提交
271 272 273 274 275 276 277

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

278
		ipc.on('vscode:setFullScreen', (event, windowId: number, fullscreen: boolean) => {
J
Joao Moreno 已提交
279
			this.logService.log('IPC#vscode:setFullScreen');
280 281 282 283 284 285 286 287

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

		ipc.on('vscode:toggleDevTools', (event, windowId: number) => {
J
Joao Moreno 已提交
288
			this.logService.log('IPC#vscode:toggleDevTools');
289 290 291 292 293 294 295 296

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

		ipc.on('vscode:openDevTools', (event, windowId: number) => {
J
Joao Moreno 已提交
297
			this.logService.log('IPC#vscode:openDevTools');
298 299 300 301 302 303 304 305 306

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

		ipc.on('vscode:setRepresentedFilename', (event, windowId: number, fileName: string) => {
J
Joao Moreno 已提交
307
			this.logService.log('IPC#vscode:setRepresentedFilename');
308 309 310 311 312 313 314 315

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

		ipc.on('vscode:setMenuBarVisibility', (event, windowId: number, visibility: boolean) => {
J
Joao Moreno 已提交
316
			this.logService.log('IPC#vscode:setMenuBarVisibility');
317 318 319 320 321 322 323 324

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

		ipc.on('vscode:flashFrame', (event, windowId: number) => {
J
Joao Moreno 已提交
325
			this.logService.log('IPC#vscode:flashFrame');
326 327 328 329 330 331 332 333

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

		ipc.on('vscode:focusWindow', (event, windowId: number) => {
J
Joao Moreno 已提交
334
			this.logService.log('IPC#vscode:focusWindow');
335 336 337 338 339 340 341 342

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

		ipc.on('vscode:setDocumentEdited', (event, windowId: number, edited: boolean) => {
J
Joao Moreno 已提交
343
			this.logService.log('IPC#vscode:setDocumentEdited');
344 345 346 347 348 349 350

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

B
Benjamin Pasero 已提交
351
		ipc.on('vscode:toggleMenuBar', (event, windowId: number) => {
J
Joao Moreno 已提交
352
			this.logService.log('IPC#vscode:toggleMenuBar');
353 354

			// Update in settings
J
Joao Moreno 已提交
355
			let menuBarHidden = this.storageService.getItem(VSCodeWindow.menuBarHiddenKey, false);
356
			let newMenuBarHidden = !menuBarHidden;
J
Joao Moreno 已提交
357
			this.storageService.setItem(VSCodeWindow.menuBarHiddenKey, newMenuBarHidden);
358 359 360

			// Update across windows
			WindowsManager.WINDOWS.forEach(w => w.setMenuBarVisibility(!newMenuBarHidden));
361 362 363 364 365 366 367 368

			// 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."));
				}
			}
369 370
		});

B
Benjamin Pasero 已提交
371
		ipc.on('vscode:broadcast', (event, windowId: number, target: string, broadcast: { channel: string; payload: any; }) => {
E
Erich Gamma 已提交
372
			if (broadcast.channel && broadcast.payload) {
J
Joao Moreno 已提交
373
				this.logService.log('IPC#vscode:broadcast', target, broadcast.channel, broadcast.payload);
B
Benjamin Pasero 已提交
374

375 376 377 378
				// Handle specific events on main side
				this.onBroadcast(broadcast.channel, broadcast.payload);

				// Send to windows
379
				if (target) {
B
Benjamin Pasero 已提交
380
					const otherWindowsWithTarget = WindowsManager.WINDOWS.filter(w => w.id !== windowId && typeof w.openedWorkspacePath === 'string');
381 382 383 384 385
					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) {
386 387 388 389 390
						targetWindow.send('vscode:broadcast', broadcast);
					}
				} else {
					this.sendToAll('vscode:broadcast', broadcast, [windowId]);
				}
E
Erich Gamma 已提交
391
			}
392 393
		});

B
Benjamin Pasero 已提交
394
		ipc.on('vscode:log', (event, logEntry: ILogEntry) => {
395 396 397 398 399 400 401 402 403 404
			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 已提交
405

406
		ipc.on('vscode:closeExtensionHostWindow', (event, extensionDevelopmentPath: string) => {
J
Joao Moreno 已提交
407
			this.logService.log('IPC#vscode:closeExtensionHostWindow', extensionDevelopmentPath);
B
Benjamin Pasero 已提交
408

409 410 411 412 413 414
			const windowOnExtension = this.findWindow(null, null, extensionDevelopmentPath);
			if (windowOnExtension) {
				windowOnExtension.win.close();
			}
		});

B
Benjamin Pasero 已提交
415
		this.updateService.on('update-downloaded', (update: IUpdate) => {
E
Erich Gamma 已提交
416 417 418 419 420 421 422 423 424
			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 已提交
425
		ipc.on('vscode:update-apply', () => {
J
Joao Moreno 已提交
426
			this.logService.log('IPC#vscode:update-apply');
E
Erich Gamma 已提交
427

B
Benjamin Pasero 已提交
428 429
			if (this.updateService.availableUpdate) {
				this.updateService.availableUpdate.quitAndUpdate();
E
Erich Gamma 已提交
430 431 432
			}
		});

B
Benjamin Pasero 已提交
433
		this.updateService.on('update-not-available', (explicit: boolean) => {
E
Erich Gamma 已提交
434 435 436 437 438 439 440
			this.sendToFocused('vscode:telemetry', { eventName: 'update:notAvailable', data: { explicit } });

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

B
Benjamin Pasero 已提交
441
		this.updateService.on('update-available', (url: string) => {
J
Joao Moreno 已提交
442 443 444 445 446
			if (url) {
				this.sendToFocused('vscode:update-available', url);
			}
		});

J
Joao Moreno 已提交
447
		this.lifecycleService.onBeforeQuit(() => {
E
Erich Gamma 已提交
448 449 450 451 452 453 454 455

			// 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
J
Joao Moreno 已提交
456
			this.windowsState.openedFolders = WindowsManager.WINDOWS.filter(w => w.readyState === ReadyState.READY && !!w.openedWorkspacePath && !w.isPluginDevelopmentHost).map(w => {
E
Erich Gamma 已提交
457 458 459
				return <IWindowState>{
					workspacePath: w.openedWorkspacePath,
					uiState: w.serializeWindowState()
B
Benjamin Pasero 已提交
460
				};
E
Erich Gamma 已提交
461 462 463 464
			});
		});

		app.on('will-quit', () => {
J
Joao Moreno 已提交
465
			this.storageService.setItem(WindowsManager.windowsStateStorageKey, this.windowsState);
E
Erich Gamma 已提交
466
		});
467 468

		let loggedStartupTimes = false;
J
Joao Moreno 已提交
469
		this.onReady(window => {
470 471 472 473 474 475 476 477
			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 已提交
478 479
	}

480 481 482 483
	private onBroadcast(event: string, payload: any): void {

		// Theme changes
		if (event === 'vscode:changeTheme' && typeof payload === 'string') {
J
Joao Moreno 已提交
484
			this.storageService.setItem(VSCodeWindow.themeStorageKey, payload);
485 486 487
		}
	}

J
Joao Moreno 已提交
488
	public reload(win: VSCodeWindow, cli?: ICommandLineArguments): void {
E
Erich Gamma 已提交
489 490

		// Only reload when the window has not vetoed this
J
Joao Moreno 已提交
491
		this.lifecycleService.unload(win).done((veto) => {
E
Erich Gamma 已提交
492 493 494 495 496 497
			if (!veto) {
				win.reload(cli);
			}
		});
	}

J
Joao Moreno 已提交
498 499 500
	public open(openConfig: IOpenConfiguration): VSCodeWindow[] {
		let iPathsToOpen: IPath[];
		let usedWindows: VSCodeWindow[] = [];
E
Erich Gamma 已提交
501 502 503 504 505 506 507 508

		// 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) {
B
Benjamin Pasero 已提交
509
					let options:Electron.ShowMessageBoxOptions = {
J
Joao Moreno 已提交
510
						title: this.envService.product.nameLong,
E
Erich Gamma 已提交
511 512 513 514 515 516 517 518 519
						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) {
520
						dialog.showMessageBox(activeWindow, options);
E
Erich Gamma 已提交
521
					} else {
522
						dialog.showMessageBox(options);
E
Erich Gamma 已提交
523 524 525 526 527 528 529 530 531 532
					}
				}

				return iPath;
			});

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

			if (iPathsToOpen.length === 0) {
533
				return null; // indicate to outside that open failed
E
Erich Gamma 已提交
534 535 536 537 538 539 540 541 542 543 544 545 546 547
			}
		}

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

J
Joao Moreno 已提交
548 549
		let filesToOpen: IPath[] = [];
		let filesToDiff: IPath[] = [];
550 551 552 553 554 555
		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
556
		let candidates = iPathsToOpen.filter((iPath) => !!iPath.filePath && !iPath.createFilePath && !iPath.installExtensionPath);
557 558 559 560 561 562 563
		if (openConfig.diffMode) {
			if (candidates.length === 2) {
				filesToDiff = candidates;
			} else {
				emptyToOpen = [Object.create(null)]; // improper use of diffMode, open empty
			}

564
			foldersToOpen = []; // diff is always in empty workspace
B
Benjamin Pasero 已提交
565
			filesToCreate = []; // diff ignores other files that do not exist
566 567 568 569
		} else {
			filesToOpen = candidates;
		}

J
Joao Moreno 已提交
570
		let configuration: IWindowConfiguration;
E
Erich Gamma 已提交
571

572 573
		// 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 已提交
574

575 576 577 578 579 580 581
			// 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!)
B
Benjamin Pasero 已提交
582
					openFilesInNewWindow = this.settingsService.getValue('window.openFilesInNewWindow', openFilesInNewWindow);
583
				}
E
Erich Gamma 已提交
584 585 586 587 588
			}

			// Open Files in last instance if any and flag tells us so
			let lastActiveWindow = this.getLastActiveWindow();
			if (!openFilesInNewWindow && lastActiveWindow) {
B
Benjamin Pasero 已提交
589
				lastActiveWindow.focus();
E
Erich Gamma 已提交
590
				lastActiveWindow.ready().then((readyWindow) => {
591
					readyWindow.send('vscode:openFiles', {
E
Erich Gamma 已提交
592
						filesToOpen: filesToOpen,
593 594
						filesToCreate: filesToCreate,
						filesToDiff: filesToDiff
E
Erich Gamma 已提交
595 596 597
					});

					if (extensionsToInstall.length) {
598
						readyWindow.send('vscode:installExtensions', { extensionsToInstall });
E
Erich Gamma 已提交
599 600
					}
				});
601 602

				usedWindows.push(lastActiveWindow);
E
Erich Gamma 已提交
603 604 605 606
			}

			// Otherwise open instance with files
			else {
607
				configuration = this.toConfiguration(openConfig.userEnv || this.initialUserEnv, openConfig.cli, null, filesToOpen, filesToCreate, filesToDiff, extensionsToInstall);
608 609
				let browserWindow = this.openInBrowserWindow(configuration, true /* new window */);
				usedWindows.push(browserWindow);
E
Erich Gamma 已提交
610 611 612 613 614 615

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

		// Handle folders to open
616
		let openInNewWindow = openConfig.preferNewWindow || openConfig.forceNewWindow;
E
Erich Gamma 已提交
617 618 619 620 621
		if (foldersToOpen.length > 0) {

			// Check for existing instances
			let windowsOnWorkspacePath = arrays.coalesce(foldersToOpen.map((iPath) => this.findWindow(iPath.workspacePath)));
			if (windowsOnWorkspacePath.length > 0) {
622 623 624
				let browserWindow = windowsOnWorkspacePath[0];
				browserWindow.focus(); // just focus one of them
				browserWindow.ready().then((readyWindow) => {
625
					readyWindow.send('vscode:openFiles', {
E
Erich Gamma 已提交
626
						filesToOpen: filesToOpen,
627 628
						filesToCreate: filesToCreate,
						filesToDiff: filesToDiff
E
Erich Gamma 已提交
629 630 631
					});

					if (extensionsToInstall.length) {
632
						readyWindow.send('vscode:installExtensions', { extensionsToInstall });
E
Erich Gamma 已提交
633 634 635
					}
				});

636 637
				usedWindows.push(browserWindow);

E
Erich Gamma 已提交
638 639 640
				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
641
				filesToDiff = [];
E
Erich Gamma 已提交
642 643
				extensionsToInstall = [];

644
				openInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
645 646 647 648
			}

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

653
				configuration = this.toConfiguration(openConfig.userEnv || this.initialUserEnv, openConfig.cli, folderToOpen.workspacePath, filesToOpen, filesToCreate, filesToDiff, extensionsToInstall);
654
				let browserWindow = this.openInBrowserWindow(configuration, openInNewWindow, openInNewWindow ? void 0 : openConfig.windowToUse);
655
				usedWindows.push(browserWindow);
E
Erich Gamma 已提交
656 657 658 659

				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
660
				filesToDiff = [];
E
Erich Gamma 已提交
661 662
				extensionsToInstall = [];

663
				openInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
664 665 666 667 668 669
			});
		}

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

674
				openInNewWindow = true; // any other folders to open must open in new window then
E
Erich Gamma 已提交
675 676 677 678 679 680 681 682 683 684 685
			});
		}

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

		// Emit events
J
Joao Moreno 已提交
686
		iPathsToOpen.forEach((iPath) => this.eventEmitter.emit(EventTypes.OPEN, iPath));
E
Erich Gamma 已提交
687

688
		return arrays.distinct(usedWindows);
E
Erich Gamma 已提交
689 690 691 692 693 694 695
	}

	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 已提交
696
		let res = WindowsManager.WINDOWS.filter((w) => w.config && this.isPathEqual(w.config.extensionDevelopmentPath, openConfig.cli.extensionDevelopmentPath));
E
Erich Gamma 已提交
697 698
		if (res && res.length === 1) {
			this.reload(res[0], openConfig.cli);
B
Benjamin Pasero 已提交
699
			res[0].focus(); // make sure it gets focus and is restored
E
Erich Gamma 已提交
700 701 702 703

			return;
		}

704 705
		// 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 已提交
706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
			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 });
	}

J
Joao Moreno 已提交
724 725
	private toConfiguration(userEnv: IProcessEnvironment, cli: ICommandLineArguments, workspacePath?: string, filesToOpen?: IPath[], filesToCreate?: IPath[], filesToDiff?: IPath[], extensionsToInstall?: string[]): IWindowConfiguration {
		let configuration: IWindowConfiguration = objects.mixin({}, cli); // inherit all properties from CLI
E
Erich Gamma 已提交
726 727 728 729
		configuration.execPath = process.execPath;
		configuration.workspacePath = workspacePath;
		configuration.filesToOpen = filesToOpen;
		configuration.filesToCreate = filesToCreate;
730
		configuration.filesToDiff = filesToDiff;
E
Erich Gamma 已提交
731
		configuration.extensionsToInstall = extensionsToInstall;
J
Joao Moreno 已提交
732 733 734
		configuration.appName = this.envService.product.nameLong;
		configuration.applicationName = this.envService.product.applicationName;
		configuration.darwinBundleIdentifier = this.envService.product.darwinBundleIdentifier;
J
Joao Moreno 已提交
735
		configuration.appRoot = this.envService.appRoot;
736
		configuration.version = pkg.version;
J
Joao Moreno 已提交
737
		configuration.commitHash = this.envService.product.commit;
J
Joao Moreno 已提交
738 739 740
		configuration.appSettingsHome = this.envService.appSettingsHome;
		configuration.appSettingsPath = this.envService.appSettingsPath;
		configuration.appKeybindingsPath = this.envService.appKeybindingsPath;
J
Joao Moreno 已提交
741
		configuration.userExtensionsHome = this.envService.userExtensionsHome;
J
Joao Moreno 已提交
742 743 744 745 746 747 748 749 750 751
		configuration.extensionTips = this.envService.product.extensionTips;
		configuration.mainIPCHandle = this.envService.mainIPCHandle;
		configuration.sharedIPCHandle = this.envService.sharedIPCHandle;
		configuration.isBuilt = this.envService.isBuilt;
		configuration.crashReporter = this.envService.product.crashReporter;
		configuration.extensionsGallery = this.envService.product.extensionsGallery;
		configuration.welcomePage = this.envService.product.welcomePage;
		configuration.productDownloadUrl = this.envService.product.downloadUrl;
		configuration.releaseNotesUrl = this.envService.product.releaseNotesUrl;
		configuration.licenseUrl = this.envService.product.licenseUrl;
B
Benjamin Pasero 已提交
752 753
		configuration.updateFeedUrl = this.updateService.feedUrl;
		configuration.updateChannel = this.updateService.channel;
J
Joao Moreno 已提交
754 755 756
		configuration.aiConfig = this.envService.product.aiConfig;
		configuration.sendASmile = this.envService.product.sendASmile;
		configuration.enableTelemetry = this.envService.product.enableTelemetry;
757
		configuration.userEnv = userEnv;
E
Erich Gamma 已提交
758

759 760 761 762
		const recents = this.getRecentlyOpenedPaths(workspacePath, filesToOpen);
		configuration.recentFiles = recents.files;
		configuration.recentFolders = recents.folders;

E
Erich Gamma 已提交
763 764 765
		return configuration;
	}

J
Joao Moreno 已提交
766
	private getRecentlyOpenedPaths(workspacePath?: string, filesToOpen?: IPath[]): IOpenedPathsList {
767 768
		let files: string[];
		let folders: string[];
E
Erich Gamma 已提交
769 770

		// Get from storage
J
Joao Moreno 已提交
771
		let storedRecents = this.storageService.getItem<IOpenedPathsList>(WindowsManager.openedPathsListStorageKey);
772 773 774 775 776 777
		if (storedRecents) {
			files = storedRecents.files || [];
			folders = storedRecents.folders || [];
		} else {
			files = [];
			folders = [];
E
Erich Gamma 已提交
778 779 780 781
		}

		// Add currently files to open to the beginning if any
		if (filesToOpen) {
782
			files.unshift(...filesToOpen.map(f => f.filePath));
E
Erich Gamma 已提交
783 784 785 786
		}

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

790
		// Clear those dupes
791 792 793
		files = arrays.distinct(files);
		folders = arrays.distinct(folders);

794
		// Make sure it is bounded
795 796 797 798
		files = files.slice(0, 10);
		folders = folders.slice(0, 10);

		return { files, folders };
E
Erich Gamma 已提交
799 800
	}

J
Joao Moreno 已提交
801
	private toIPath(anyPath: string, ignoreFileNotFound?: boolean, gotoLineMode?: boolean): IPath {
E
Erich Gamma 已提交
802 803 804 805
		if (!anyPath) {
			return null;
		}

J
Joao Moreno 已提交
806
		let parsedPath: IParsedPath;
E
Erich Gamma 已提交
807
		if (gotoLineMode) {
J
Joao Moreno 已提交
808
			parsedPath = parseLineAndColumnAware(anyPath);
E
Erich Gamma 已提交
809 810 811 812 813
			anyPath = parsedPath.path;
		}

		let candidate = path.normalize(anyPath);
		try {
814
			let candidateStat = fs.statSync(candidate);
E
Erich Gamma 已提交
815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
			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;
	}

J
Joao Moreno 已提交
834
	private cliToPaths(cli: ICommandLineArguments, ignoreFileNotFound?: boolean): IPath[] {
E
Erich Gamma 已提交
835 836 837 838 839 840 841 842 843

		// 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 {
844 845 846 847 848 849 850
			let reopenFolders: string;
			if (this.lifecycleService.wasUpdated) {
				reopenFolders = ReopenFoldersSetting.ALL; // always reopen all folders when an update was applied
			} else {
				reopenFolders = this.settingsService.getValue('window.reopenFolders', ReopenFoldersSetting.ONE);
			}

E
Erich Gamma 已提交
851 852 853
			let lastActiveFolder = this.windowsState.lastActiveWindow && this.windowsState.lastActiveWindow.workspacePath;

			// Restore all
854
			if (reopenFolders === ReopenFoldersSetting.ALL) {
E
Erich Gamma 已提交
855 856 857 858 859 860 861 862 863 864 865 866
				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
867
			else if (lastActiveFolder && (reopenFolders === ReopenFoldersSetting.ONE || reopenFolders !== ReopenFoldersSetting.NONE)) {
E
Erich Gamma 已提交
868 869 870 871 872 873 874 875 876 877 878 879 880
				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)];
	}

J
Joao Moreno 已提交
881 882
	private openInBrowserWindow(configuration: IWindowConfiguration, forceNewWindow?: boolean, windowToUse?: VSCodeWindow): VSCodeWindow {
		let vscodeWindow: VSCodeWindow;
E
Erich Gamma 已提交
883 884 885 886 887

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

			if (vscodeWindow) {
B
Benjamin Pasero 已提交
888
				vscodeWindow.focus();
E
Erich Gamma 已提交
889 890 891 892 893
			}
		}

		// New window
		if (!vscodeWindow) {
J
Joao Moreno 已提交
894
			vscodeWindow = this.instantiationService.createInstance(VSCodeWindow, {
895
				state: this.getNewWindowState(configuration),
896 897
				extensionDevelopmentPath: configuration.extensionDevelopmentPath,
				allowFullscreen: this.lifecycleService.wasUpdated || this.settingsService.getValue('window.restoreFullscreen', false)
898 899
			});

E
Erich Gamma 已提交
900 901 902
			WindowsManager.WINDOWS.push(vscodeWindow);

			// Window Events
903 904
			vscodeWindow.win.webContents.removeAllListeners('devtools-reload-page'); // remove built in listener so we can handle this on our own
			vscodeWindow.win.webContents.on('devtools-reload-page', () => this.reload(vscodeWindow));
905 906
			vscodeWindow.win.webContents.on('crashed', () => this.onWindowError(vscodeWindow, WindowError.CRASHED));
			vscodeWindow.win.on('unresponsive', () => this.onWindowError(vscodeWindow, WindowError.UNRESPONSIVE));
E
Erich Gamma 已提交
907 908 909 910
			vscodeWindow.win.on('close', () => this.onBeforeWindowClose(vscodeWindow));
			vscodeWindow.win.on('closed', () => this.onWindowClosed(vscodeWindow));

			// Lifecycle
J
Joao Moreno 已提交
911
			this.lifecycleService.registerWindow(vscodeWindow);
E
Erich Gamma 已提交
912 913 914 915 916 917 918 919
		}

		// 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 已提交
920 921
			if (!configuration.extensionDevelopmentPath && currentWindowConfig && !!currentWindowConfig.extensionDevelopmentPath) {
				configuration.extensionDevelopmentPath = currentWindowConfig.extensionDevelopmentPath;
E
Erich Gamma 已提交
922
				configuration.verboseLogging = currentWindowConfig.verboseLogging;
923
				configuration.logExtensionHostCommunication = currentWindowConfig.logExtensionHostCommunication;
924
				configuration.debugBrkFileWatcherPort = currentWindowConfig.debugBrkFileWatcherPort;
925 926
				configuration.debugBrkExtensionHost = currentWindowConfig.debugBrkExtensionHost;
				configuration.debugExtensionHostPort = currentWindowConfig.debugExtensionHostPort;
B
Benjamin Pasero 已提交
927
				configuration.extensionsHomePath = currentWindowConfig.extensionsHomePath;
E
Erich Gamma 已提交
928 929 930 931
			}
		}

		// Only load when the window has not vetoed this
J
Joao Moreno 已提交
932
		this.lifecycleService.unload(vscodeWindow).done((veto) => {
E
Erich Gamma 已提交
933 934 935 936 937 938
			if (!veto) {

				// Load it
				vscodeWindow.load(configuration);
			}
		});
939 940

		return vscodeWindow;
E
Erich Gamma 已提交
941 942
	}

J
Joao Moreno 已提交
943
	private getNewWindowState(configuration: IWindowConfiguration): ISingleWindowState {
E
Erich Gamma 已提交
944 945

		// plugin development host Window - load from stored settings if any
A
Alex Dima 已提交
946
		if (!!configuration.extensionDevelopmentPath && this.windowsState.lastPluginDevelopmentHostWindow) {
E
Erich Gamma 已提交
947 948 949 950 951
			return this.windowsState.lastPluginDevelopmentHostWindow.uiState;
		}

		// Known Folder - load from stored settings if any
		if (configuration.workspacePath) {
B
Benjamin Pasero 已提交
952
			let stateForWorkspace = this.windowsState.openedFolders.filter(o => this.isPathEqual(o.workspacePath, configuration.workspacePath)).map(o => o.uiState);
E
Erich Gamma 已提交
953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968
			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
969
		let displayToUse: Electron.Display;
E
Erich Gamma 已提交
970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996
		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];
			}
		}

J
Joao Moreno 已提交
997
		let defaultState = defaultWindowState();
E
Erich Gamma 已提交
998 999 1000 1001 1002 1003
		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);
	}

J
Joao Moreno 已提交
1004
	private ensureNoOverlap(state: ISingleWindowState): ISingleWindowState {
E
Erich Gamma 已提交
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
		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;
	}

1018
	public openFileFolderPicker(forceNewWindow?: boolean): void {
1019
		this.doPickAndOpen({ pickFolders: true, pickFiles: true , forceNewWindow});
1020 1021
	}

1022 1023
	public openFilePicker(forceNewWindow?: boolean, path?: string): void {
		this.doPickAndOpen({ pickFiles: true, forceNewWindow, path });
1024 1025 1026
	}

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

1030
	private doPickAndOpen(options: INativeOpenDialogOptions): void {
1031
		this.getFileOrFolderPaths(options, (paths: string[]) => {
E
Erich Gamma 已提交
1032
			if (paths && paths.length) {
1033
				this.open({ cli: this.envService.cliArgs, pathsToOpen: paths, forceNewWindow: options.forceNewWindow });
E
Erich Gamma 已提交
1034 1035 1036 1037
			}
		});
	}

1038
	private getFileOrFolderPaths(options: INativeOpenDialogOptions, clb: (paths: string[]) => void): void {
1039
		let workingDir = options.path || this.storageService.getItem<string>(WindowsManager.workingDirPickerStorageKey);
E
Erich Gamma 已提交
1040 1041
		let focussedWindow = this.getFocusedWindow();

B
Benjamin Pasero 已提交
1042
		let pickerProperties: ('openFile' | 'openDirectory' | 'multiSelections' | 'createDirectory')[];
1043
		if (options.pickFiles && options.pickFolders) {
E
Erich Gamma 已提交
1044 1045
			pickerProperties = ['multiSelections', 'openDirectory', 'openFile', 'createDirectory'];
		} else {
1046
			pickerProperties = ['multiSelections', options.pickFolders ? 'openDirectory' : 'openFile', 'createDirectory'];
E
Erich Gamma 已提交
1047 1048
		}

1049
		dialog.showOpenDialog(focussedWindow && focussedWindow.win, {
E
Erich Gamma 已提交
1050 1051 1052 1053 1054 1055
			defaultPath: workingDir,
			properties: pickerProperties
		}, (paths) => {
			if (paths && paths.length > 0) {

				// Remember path in storage for next time
J
Joao Moreno 已提交
1056
				this.storageService.setItem(WindowsManager.workingDirPickerStorageKey, path.dirname(paths[0]));
E
Erich Gamma 已提交
1057 1058 1059 1060 1061 1062 1063 1064 1065

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

J
Joao Moreno 已提交
1066
	public focusLastActive(cli: ICommandLineArguments): VSCodeWindow {
E
Erich Gamma 已提交
1067 1068
		let lastActive = this.getLastActiveWindow();
		if (lastActive) {
B
Benjamin Pasero 已提交
1069
			lastActive.focus();
1070 1071

			return lastActive;
E
Erich Gamma 已提交
1072 1073 1074
		}

		// No window - open new one
1075 1076 1077 1078
		this.windowsState.openedFolders = []; // make sure we do not open too much
		const res = this.open({ cli: cli });

		return res && res[0];
E
Erich Gamma 已提交
1079 1080
	}

J
Joao Moreno 已提交
1081
	public getLastActiveWindow(): VSCodeWindow {
E
Erich Gamma 已提交
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
		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;
	}

J
Joao Moreno 已提交
1093
	public findWindow(workspacePath: string, filePath?: string, extensionDevelopmentPath?: string): VSCodeWindow {
E
Erich Gamma 已提交
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
		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
1108
				if (typeof w.openedWorkspacePath === 'string' && (this.isPathEqual(w.openedWorkspacePath, workspacePath))) {
E
Erich Gamma 已提交
1109 1110 1111 1112
					return true;
				}

				// match on file
B
Benjamin Pasero 已提交
1113
				if (typeof w.openedFilePath === 'string' && this.isPathEqual(w.openedFilePath, filePath)) {
E
Erich Gamma 已提交
1114 1115 1116 1117 1118 1119 1120 1121
					return true;
				}

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

1122 1123 1124 1125 1126
				// match on extension development path
				if (typeof extensionDevelopmentPath === 'string' && w.extensionDevelopmentPath === extensionDevelopmentPath) {
					return true;
				}

E
Erich Gamma 已提交
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
				return false;
			});

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

		return null;
	}

	public openNewWindow(): void {
J
Joao Moreno 已提交
1139
		this.open({ cli: this.envService.cliArgs, forceNewWindow: true, forceEmpty: true });
E
Erich Gamma 已提交
1140 1141 1142 1143 1144 1145
	}

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

		if (focusedWindow) {
1146
			focusedWindow.sendWhenReady(channel, ...args);
E
Erich Gamma 已提交
1147 1148 1149 1150 1151
		}
	}

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

1156
			w.sendWhenReady(channel, payload);
E
Erich Gamma 已提交
1157 1158 1159
		});
	}

J
Joao Moreno 已提交
1160
	public getFocusedWindow(): VSCodeWindow {
E
Erich Gamma 已提交
1161 1162 1163 1164 1165 1166 1167 1168
		let win = BrowserWindow.getFocusedWindow();
		if (win) {
			return this.getWindowById(win.id);
		}

		return null;
	}

J
Joao Moreno 已提交
1169
	public getWindowById(windowId: number): VSCodeWindow {
B
Benjamin Pasero 已提交
1170
		let res = WindowsManager.WINDOWS.filter((w) => w.id === windowId);
E
Erich Gamma 已提交
1171 1172 1173 1174 1175 1176 1177
		if (res && res.length === 1) {
			return res[0];
		}

		return null;
	}

J
Joao Moreno 已提交
1178
	public getWindows(): VSCodeWindow[] {
E
Erich Gamma 已提交
1179 1180 1181 1182 1183 1184 1185
		return WindowsManager.WINDOWS;
	}

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

J
Joao Moreno 已提交
1186
	private onWindowError(vscodeWindow: VSCodeWindow, error: WindowError): void {
E
Erich Gamma 已提交
1187 1188 1189 1190
		console.error(error === WindowError.CRASHED ? '[VS Code]: render process crashed!' : '[VS Code]: detected unresponsive');

		// Unresponsive
		if (error === WindowError.UNRESPONSIVE) {
1191
			dialog.showMessageBox(vscodeWindow.win, {
J
Joao Moreno 已提交
1192
				title: this.envService.product.nameLong,
E
Erich Gamma 已提交
1193
				type: 'warning',
B
Benjamin Pasero 已提交
1194
				buttons: [nls.localize('reopen', "Reopen"), nls.localize('wait', "Keep Waiting"), nls.localize('close', "Close")],
1195
				message: nls.localize('appStalled', "The window is no longer responding"),
B
Benjamin Pasero 已提交
1196
				detail: nls.localize('appStalledDetail', "You can reopen or close the window or keep waiting."),
E
Erich Gamma 已提交
1197 1198 1199
				noLink: true
			}, (result) => {
				if (result === 0) {
1200 1201
					vscodeWindow.reload();
				} else if (result === 2) {
1202
					this.onBeforeWindowClose(vscodeWindow); // 'close' event will not be fired on destroy(), so run it manually
1203
					vscodeWindow.win.destroy(); // make sure to destroy the window as it is unresponsive
E
Erich Gamma 已提交
1204 1205 1206 1207 1208 1209
				}
			});
		}

		// Crashed
		else {
1210
			dialog.showMessageBox(vscodeWindow.win, {
J
Joao Moreno 已提交
1211
				title: this.envService.product.nameLong,
E
Erich Gamma 已提交
1212
				type: 'warning',
B
Benjamin Pasero 已提交
1213
				buttons: [nls.localize('reopen', "Reopen"), nls.localize('close', "Close")],
1214
				message: nls.localize('appCrashed', "The window has crashed"),
B
Benjamin Pasero 已提交
1215
				detail: nls.localize('appCrashedDetail', "We are sorry for the inconvenience! You can reopen the window to continue where you left off."),
E
Erich Gamma 已提交
1216 1217
				noLink: true
			}, (result) => {
1218 1219 1220
				if (result === 0) {
					vscodeWindow.reload();
				} else if (result === 1) {
1221
					this.onBeforeWindowClose(vscodeWindow); // 'close' event will not be fired on destroy(), so run it manually
1222 1223
					vscodeWindow.win.destroy(); // make sure to destroy the window as it has crashed
				}
E
Erich Gamma 已提交
1224 1225 1226 1227
			});
		}
	}

J
Joao Moreno 已提交
1228 1229
	private onBeforeWindowClose(win: VSCodeWindow): void {
		if (win.readyState !== ReadyState.READY) {
E
Erich Gamma 已提交
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
			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 已提交
1241
				if (this.isPathEqual(o.workspacePath, win.openedWorkspacePath)) {
E
Erich Gamma 已提交
1242 1243 1244 1245 1246 1247
					o.uiState = state.uiState;
				}
			});
		}
	}

J
Joao Moreno 已提交
1248
	private onWindowClosed(win: VSCodeWindow): void {
E
Erich Gamma 已提交
1249 1250 1251 1252 1253 1254 1255 1256 1257

		// 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
J
Joao Moreno 已提交
1258
		this.eventEmitter.emit(EventTypes.CLOSE, win.id);
E
Erich Gamma 已提交
1259
	}
B
Benjamin Pasero 已提交
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283

	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;
	}
J
Joao Moreno 已提交
1284
}