app.ts 32.0 KB
Newer Older
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

6
import { app, ipcMain as ipc, systemPreferences, shell, Event, contentTracing, protocol, powerMonitor } from 'electron';
7
import { IProcessEnvironment, isWindows, isMacintosh } from 'vs/base/common/platform';
8
import { WindowsManager } from 'vs/code/electron-main/windows';
9
import { IWindowsService, OpenContext, ActiveWindowManager, IURIToOpen } from 'vs/platform/windows/common/windows';
J
Joao Moreno 已提交
10
import { WindowsChannel } from 'vs/platform/windows/node/windowsIpc';
11
import { WindowsService } from 'vs/platform/windows/electron-main/windowsService';
B
Benjamin Pasero 已提交
12
import { ILifecycleService, LifecycleService } from 'vs/platform/lifecycle/electron-main/lifecycleMain';
B
Benjamin Pasero 已提交
13
import { getShellEnvironment } from 'vs/code/node/shellEnv';
14
import { IUpdateService } from 'vs/platform/update/common/update';
J
Joao Moreno 已提交
15
import { UpdateChannel } from 'vs/platform/update/node/updateIpc';
16
import { Server as ElectronIPCServer } from 'vs/base/parts/ipc/electron-main/ipc.electron-main';
A
Alex Dima 已提交
17 18
import { Client } from 'vs/base/parts/ipc/common/ipc.net';
import { Server, connect } from 'vs/base/parts/ipc/node/ipc.net';
19
import { SharedProcess } from 'vs/code/electron-main/sharedProcess';
B
Benjamin Pasero 已提交
20
import { LaunchService, LaunchChannel, ILaunchService } from 'vs/platform/launch/electron-main/launchService';
21 22 23
import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors';
24
import { ILogService } from 'vs/platform/log/common/log';
B
Benjamin Pasero 已提交
25
import { IStateService } from 'vs/platform/state/common/state';
26 27 28
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IURLService } from 'vs/platform/url/common/url';
J
Joao Moreno 已提交
29
import { URLHandlerChannelClient, URLServiceChannel } from 'vs/platform/url/node/urlIpc';
30
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
31
import { NullTelemetryService, combinedAppender, LogAppender } from 'vs/platform/telemetry/common/telemetryUtils';
J
Joao Moreno 已提交
32
import { TelemetryAppenderClient } from 'vs/platform/telemetry/node/telemetryIpc';
33
import { TelemetryService, ITelemetryServiceConfig } from 'vs/platform/telemetry/common/telemetryService';
34
import { resolveCommonProperties } from 'vs/platform/telemetry/node/commonProperties';
A
Alex Dima 已提交
35
import { getDelayedChannel, StaticRouter } from 'vs/base/parts/ipc/common/ipc';
36 37
import product from 'vs/platform/product/node/product';
import pkg from 'vs/platform/product/node/package';
38
import { ProxyAuthHandler } from 'vs/code/electron-main/auth';
39
import { Disposable, toDisposable } from 'vs/base/common/lifecycle';
B
Benjamin Pasero 已提交
40
import { ConfigurationService } from 'vs/platform/configuration/node/configurationService';
B
Benjamin Pasero 已提交
41
import { IWindowsMainService, ICodeWindow } from 'vs/platform/windows/electron-main/windows';
B
Benjamin Pasero 已提交
42
import { IHistoryMainService } from 'vs/platform/history/common/history';
43
import { withUndefinedAsNull } from 'vs/base/common/types';
44
import { KeyboardLayoutMonitor } from 'vs/code/electron-main/keyboard';
45
import { URI } from 'vs/base/common/uri';
J
Joao Moreno 已提交
46
import { WorkspacesChannel } from 'vs/platform/workspaces/node/workspacesIpc';
M
Martin Aeschlimann 已提交
47
import { IWorkspacesMainService, hasWorkspaceFileExtension } from 'vs/platform/workspaces/common/workspaces';
48
import { getMachineId } from 'vs/base/node/id';
49 50 51
import { Win32UpdateService } from 'vs/platform/update/electron-main/updateService.win32';
import { LinuxUpdateService } from 'vs/platform/update/electron-main/updateService.linux';
import { DarwinUpdateService } from 'vs/platform/update/electron-main/updateService.darwin';
52
import { IIssueService } from 'vs/platform/issue/common/issue';
J
Joao Moreno 已提交
53
import { IssueChannel } from 'vs/platform/issue/node/issueIpc';
P
Pine Wu 已提交
54
import { IssueService } from 'vs/platform/issue/electron-main/issueService';
J
Joao Moreno 已提交
55
import { LogLevelSetterChannel } from 'vs/platform/log/node/logIpc';
56
import { setUnexpectedErrorHandler, onUnexpectedError } from 'vs/base/common/errors';
J
Joao Moreno 已提交
57
import { ElectronURLListener } from 'vs/platform/url/electron-main/electronUrlListener';
J
Joao Moreno 已提交
58
import { serve as serveDriver } from 'vs/platform/driver/electron-main/driver';
A
Alex Dima 已提交
59
import { connectRemoteAgentManagement, ManagementPersistentConnection, IConnectionOptions } from 'vs/platform/remote/common/remoteAgentConnection';
60 61
import { IMenubarService } from 'vs/platform/menubar/common/menubar';
import { MenubarService } from 'vs/platform/menubar/electron-main/menubarService';
J
Joao Moreno 已提交
62
import { MenubarChannel } from 'vs/platform/menubar/node/menubarIpc';
M
Martin Aeschlimann 已提交
63
import { hasArgs } from 'vs/platform/environment/node/argv';
64
import { RunOnceScheduler } from 'vs/base/common/async';
65
import { registerContextMenuListener } from 'vs/base/parts/contextmenu/electron-main/contextmenu';
B
Benjamin Pasero 已提交
66
import { homedir } from 'os';
67
import { join, sep, dirname } from 'vs/base/common/path';
B
Benjamin Pasero 已提交
68
import { localize } from 'vs/nls';
B
Benjamin Pasero 已提交
69
import { Schemas } from 'vs/base/common/network';
A
Alex Dima 已提交
70
import { REMOTE_FILE_SYSTEM_CHANNEL_NAME } from 'vs/platform/remote/common/remoteAgentFileSystemChannel';
A
Tweaks  
Alex Dima 已提交
71
import { ResolvedAuthority } from 'vs/platform/remote/common/remoteAuthorityResolver';
J
Joao Moreno 已提交
72
import { SnapUpdateService } from 'vs/platform/update/electron-main/updateService.snap';
B
wip  
Benjamin Pasero 已提交
73 74
import { IStorageMainService, StorageMainService } from 'vs/platform/storage/node/storageMainService';
import { GlobalStorageDatabaseChannel } from 'vs/platform/storage/node/storageIpc';
75
import { startsWith } from 'vs/base/common/strings';
76 77 78 79 80
import { BackupMainService } from 'vs/platform/backup/electron-main/backupMainService';
import { IBackupMainService } from 'vs/platform/backup/common/backup';
import { HistoryMainService } from 'vs/platform/history/electron-main/historyMainService';
import { URLService } from 'vs/platform/url/common/urlService';
import { WorkspacesMainService } from 'vs/platform/workspaces/electron-main/workspacesMainService';
81
import { RemoteAgentConnectionContext } from 'vs/platform/remote/common/remoteAgentEnvironment';
A
Alex Dima 已提交
82
import { nodeWebSocketFactory } from 'vs/platform/remote/node/nodeWebSocketFactory';
A
Alex Dima 已提交
83
import { VSBuffer } from 'vs/base/common/buffer';
84 85
import { statSync, utimes } from 'fs';
import { promisify } from 'util';
86

87
export class CodeApplication extends Disposable {
B
Benjamin Pasero 已提交
88

89
	private static readonly MACHINE_ID_KEY = 'telemetry.machineId';
B
Benjamin Pasero 已提交
90

91 92
	private static APP_ICON_REFRESH_KEY = 'macOSAppIconRefresh7';

93 94 95 96 97
	private windowsMainService: IWindowsMainService;

	private electronIpcServer: ElectronIPCServer;

	private sharedProcess: SharedProcess;
J
Johannes Rieken 已提交
98
	private sharedProcessClient: Promise<Client>;
99 100

	constructor(
101 102
		private readonly mainIpcServer: Server,
		private readonly userEnv: IProcessEnvironment,
103 104 105 106 107 108
		@IInstantiationService private readonly instantiationService: IInstantiationService,
		@ILogService private readonly logService: ILogService,
		@IEnvironmentService private readonly environmentService: IEnvironmentService,
		@ILifecycleService private readonly lifecycleService: ILifecycleService,
		@IConfigurationService private readonly configurationService: ConfigurationService,
		@IStateService private readonly stateService: IStateService
109
	) {
110 111 112 113
		super();

		this._register(mainIpcServer);
		this._register(configurationService);
114 115 116 117 118 119 120

		this.registerListeners();
	}

	private registerListeners(): void {

		// We handle uncaught exceptions here to prevent electron from opening a dialog to the user
121
		setUnexpectedErrorHandler(err => this.onUnexpectedError(err));
B
Benjamin Pasero 已提交
122
		process.on('uncaughtException', err => this.onUnexpectedError(err));
123
		process.on('unhandledRejection', (reason: unknown) => onUnexpectedError(reason));
124

125 126 127
		// Contextmenu via IPC support
		registerContextMenuListener();

B
Benjamin Pasero 已提交
128 129
		// Dispose on shutdown
		this.lifecycleService.onWillShutdown(() => this.dispose());
130

131 132 133 134 135 136 137
		app.on('accessibility-support-changed', (event: Event, accessibilitySupportEnabled: boolean) => {
			if (this.windowsMainService) {
				this.windowsMainService.sendToAll('vscode:accessibilitySupportChanged', accessibilitySupportEnabled);
			}
		});

		app.on('activate', (event: Event, hasVisibleWindows: boolean) => {
J
Joao Moreno 已提交
138
			this.logService.trace('App#activate');
139 140 141 142 143 144 145

			// Mac only event: open new window when we get activated
			if (!hasVisibleWindows && this.windowsMainService) {
				this.windowsMainService.openNewWindow(OpenContext.DOCK);
			}
		});

146 147
		// Security related measures (https://electronjs.org/docs/tutorial/security)
		// DO NOT CHANGE without consulting the documentation
148
		app.on('web-contents-created', (event: Electron.Event, contents) => {
149
			contents.on('will-attach-webview', (event: Electron.Event, webPreferences, params) => {
150

151 152 153 154 155 156 157 158 159
				const isValidWebviewSource = (source: string): boolean => {
					if (!source) {
						return false;
					}

					if (source === 'data:text/html;charset=utf-8,%3C%21DOCTYPE%20html%3E%0D%0A%3Chtml%20lang%3D%22en%22%20style%3D%22width%3A%20100%25%3B%20height%3A%20100%25%22%3E%0D%0A%3Chead%3E%0D%0A%09%3Ctitle%3EVirtual%20Document%3C%2Ftitle%3E%0D%0A%3C%2Fhead%3E%0D%0A%3Cbody%20style%3D%22margin%3A%200%3B%20overflow%3A%20hidden%3B%20width%3A%20100%25%3B%20height%3A%20100%25%22%3E%0D%0A%3C%2Fbody%3E%0D%0A%3C%2Fhtml%3E') {
						return true;
					}

160
					const srcUri = URI.parse(source).fsPath.toLowerCase();
161 162
					const rootUri = URI.file(this.environmentService.appRoot).fsPath.toLowerCase();

163
					return startsWith(srcUri, rootUri + sep);
164 165
				};

166
				// Ensure defaults
M
Matt Bierner 已提交
167 168 169 170
				delete webPreferences.preload;
				webPreferences.nodeIntegration = false;

				// Verify URLs being loaded
171
				if (isValidWebviewSource(params.src) && isValidWebviewSource(webPreferences.preloadURL)) {
M
Matt Bierner 已提交
172 173
					return;
				}
M
Matt Bierner 已提交
174

175 176
				delete webPreferences.preloadUrl;

M
Matt Bierner 已提交
177
				// Otherwise prevent loading
B
Benjamin Pasero 已提交
178
				this.logService.error('webContents#web-contents-created: Prevented webview attach');
179

M
Matt Bierner 已提交
180 181 182 183
				event.preventDefault();
			});

			contents.on('will-navigate', event => {
B
Benjamin Pasero 已提交
184
				this.logService.error('webContents#will-navigate: Prevented webcontent navigation');
185

M
Matt Bierner 已提交
186 187
				event.preventDefault();
			});
188 189 190 191 192 193

			contents.on('new-window', (event: Event, url: string) => {
				event.preventDefault(); // prevent code that wants to open links

				shell.openExternal(url);
			});
M
Matt Bierner 已提交
194 195
		});

196
		let macOpenFileURIs: IURIToOpen[] = [];
197
		let runningTimeout: NodeJS.Timeout | null = null;
198
		app.on('open-file', (event: Event, path: string) => {
J
Joao Moreno 已提交
199
			this.logService.trace('App#open-file: ', path);
200 201 202
			event.preventDefault();

			// Keep in array because more might come!
M
Martin Aeschlimann 已提交
203
			macOpenFileURIs.push(getURIToOpenFromPathSync(path));
204 205 206 207 208 209 210 211 212 213 214 215 216

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

			// Handle paths delayed in case more are coming!
			runningTimeout = setTimeout(() => {
				if (this.windowsMainService) {
					this.windowsMainService.open({
						context: OpenContext.DOCK /* can also be opening from finder while app is running */,
						cli: this.environmentService.args,
S
Sandeep Somavarapu 已提交
217
						urisToOpen: macOpenFileURIs,
218 219
						preferNewWindow: true /* dropping on the dock or opening from finder prefers to open in a new window */
					});
220
					macOpenFileURIs = [];
221 222 223 224 225
					runningTimeout = null;
				}
			}, 100);
		});

226 227 228 229
		app.on('new-window-for-tab', () => {
			this.windowsMainService.openNewWindow(OpenContext.DESKTOP); //macOS native tab "+" button
		});

230
		ipc.on('vscode:exit', (event: Event, code: number) => {
J
Joao Moreno 已提交
231
			this.logService.trace('IPC#vscode:exit', code);
232 233 234 235 236

			this.dispose();
			this.lifecycleService.kill(code);
		});

237 238
		ipc.on('vscode:fetchShellEnv', (event: Event) => {
			const webContents = event.sender;
J
Joao Moreno 已提交
239
			getShellEnvironment(this.logService).then(shellEnv => {
J
Johannes Rieken 已提交
240 241 242
				if (!webContents.isDestroyed()) {
					webContents.send('vscode:acceptShellEnv', shellEnv);
				}
243
			}, err => {
J
Johannes Rieken 已提交
244 245 246
				if (!webContents.isDestroyed()) {
					webContents.send('vscode:acceptShellEnv', {});
				}
B
Benjamin Pasero 已提交
247 248

				this.logService.error('Error fetching shell env', err);
249 250
			});
		});
251

252 253 254 255 256 257 258
		ipc.on('vscode:extensionHostDebug', (_: Event, windowId: number, broadcast: any) => {
			if (this.windowsMainService) {
				// Send to all windows (except sender window)
				this.windowsMainService.sendToAll('vscode:extensionHostDebug', broadcast, [windowId]);
			}
		});

259 260
		ipc.on('vscode:toggleDevTools', (event: Event) => event.sender.toggleDevTools());
		ipc.on('vscode:openDevTools', (event: Event) => event.sender.openDevTools());
B
Benjamin Pasero 已提交
261

262
		ipc.on('vscode:reloadWindow', (event: Event) => event.sender.reload());
263 264 265 266 267 268

		powerMonitor.on('resume', () => { // After waking up from sleep
			if (this.windowsMainService) {
				this.windowsMainService.sendToAll('vscode:osResume', undefined);
			}
		});
269 270
	}

B
Benjamin Pasero 已提交
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
	private onUnexpectedError(err: Error): void {
		if (err) {

			// take only the message and stack property
			const friendlyError = {
				message: err.message,
				stack: err.stack
			};

			// handle on client side
			if (this.windowsMainService) {
				this.windowsMainService.sendToFocused('vscode:reportError', JSON.stringify(friendlyError));
			}
		}

		this.logService.error(`[uncaught exception in main]: ${err}`);
		if (err.stack) {
			this.logService.error(err.stack);
		}
	}

292
	async startup(): Promise<void> {
J
Joao Moreno 已提交
293 294 295
		this.logService.debug('Starting VS Code');
		this.logService.debug(`from: ${this.environmentService.appRoot}`);
		this.logService.debug('args:', this.environmentService.args);
296

297 298 299 300
		// Make sure we associate the program with the app user model id
		// This will help Windows to associate the running program with
		// any shortcut that is pinned to the taskbar and prevent showing
		// two icons in the taskbar for the same app.
301
		if (isWindows && product.win32AppUserModelId) {
302 303
			app.setAppUserModelId(product.win32AppUserModelId);
		}
304

305 306 307 308 309 310 311
		// Fix native tabs on macOS 10.13
		// macOS enables a compatibility patch for any bundle ID beginning with
		// "com.microsoft.", which breaks native tabs for VS Code when using this
		// identifier (from the official build).
		// Explicitly opt out of the patch here before creating any windows.
		// See: https://github.com/Microsoft/vscode/issues/35361#issuecomment-399794085
		try {
312
			if (isMacintosh && this.configurationService.getValue<boolean>('window.nativeTabs') === true && !systemPreferences.getUserDefault('NSUseImprovedLayoutPass', 'boolean')) {
313
				systemPreferences.setUserDefault('NSUseImprovedLayoutPass', 'boolean', true as any);
314 315 316 317 318
			}
		} catch (error) {
			this.logService.error(error);
		}

319 320
		// Create Electron IPC Server
		this.electronIpcServer = new ElectronIPCServer();
321

322 323 324 325
		// Resolve unique machine ID
		this.logService.trace('Resolving machine identifier...');
		const machineId = await this.resolveMachineId();
		this.logService.trace(`Resolved machine identifier: ${machineId}`);
326

327 328 329
		// Spawn shared process
		this.sharedProcess = this.instantiationService.createInstance(SharedProcess, machineId, this.userEnv);
		this.sharedProcessClient = this.sharedProcess.whenReady().then(() => connect(this.environmentService.sharedIPCHandle, 'main'));
330

331 332
		// Services
		const appInstantiationService = await this.initServices(machineId);
333

334 335 336 337
		// Create driver
		if (this.environmentService.driverHandle) {
			(async () => {
				const server = await serveDriver(this.electronIpcServer, this.environmentService.driverHandle!, this.environmentService, appInstantiationService);
338

339 340 341 342
				this.logService.info('Driver started at:', this.environmentService.driverHandle);
				this._register(server);
			})();
		}
343

344 345 346
		// Setup Auth Handler
		const authHandler = appInstantiationService.createInstance(ProxyAuthHandler);
		this._register(authHandler);
B
Benjamin Pasero 已提交
347

348 349
		// Open Windows
		const windows = appInstantiationService.invokeFunction(accessor => this.openFirstWindow(accessor));
B
Benjamin Pasero 已提交
350

351 352
		// Post Open Windows Tasks
		appInstantiationService.invokeFunction(accessor => this.afterWindowOpen(accessor));
B
Benjamin Pasero 已提交
353

354 355 356
		// Tracing: Stop tracing after windows are ready if enabled
		if (this.environmentService.args.trace) {
			this.stopTracingEventually(windows);
B
Benjamin Pasero 已提交
357 358 359
		}
	}

360 361
	private async resolveMachineId(): Promise<string> {
		let machineId = this.stateService.getItem<string>(CodeApplication.MACHINE_ID_KEY);
B
Benjamin Pasero 已提交
362 363 364 365
		if (machineId) {
			return machineId;
		}

366
		machineId = await getMachineId();
B
Benjamin Pasero 已提交
367

368 369 370
		this.stateService.setItem(CodeApplication.MACHINE_ID_KEY, machineId);

		return machineId;
371 372 373 374 375 376
	}

	private stopTracingEventually(windows: ICodeWindow[]): void {
		this.logService.info(`Tracing: waiting for windows to get ready...`);

		let recordingStopped = false;
M
Matt Bierner 已提交
377
		const stopRecording = (timeout: boolean) => {
378 379 380 381 382 383
			if (recordingStopped) {
				return;
			}

			recordingStopped = true; // only once

384
			contentTracing.stopRecording(join(homedir(), `${product.applicationName}-${Math.random().toString(16).slice(-4)}.trace.txt`), path => {
385 386 387 388 389 390 391 392 393
				if (!timeout) {
					this.windowsMainService.showMessageBox({
						type: 'info',
						message: localize('trace.message', "Successfully created trace."),
						detail: localize('trace.detail', "Please create an issue and manually attach the following file:\n{0}", path),
						buttons: [localize('trace.ok', "Ok")]
					}, this.windowsMainService.getLastActiveWindow());
				} else {
					this.logService.info(`Tracing: data recorded (after 30s timeout) to ${path}`);
B
Benjamin Pasero 已提交
394
				}
395
			});
396 397 398 399 400 401
		};

		// Wait up to 30s before creating the trace anyways
		const timeoutHandle = setTimeout(() => stopRecording(true), 30000);

		// Wait for all windows to get ready and stop tracing then
B
Benjamin Pasero 已提交
402
		Promise.all(windows.map(window => window.ready())).then(() => {
403 404
			clearTimeout(timeoutHandle);
			stopRecording(false);
405
		});
406 407
	}

408
	private async initServices(machineId: string): Promise<IInstantiationService> {
409 410
		const services = new ServiceCollection();

411 412 413
		if (process.platform === 'win32') {
			services.set(IUpdateService, new SyncDescriptor(Win32UpdateService));
		} else if (process.platform === 'linux') {
J
Joao Moreno 已提交
414
			if (process.env.SNAP && process.env.SNAP_REVISION) {
J
Joao Moreno 已提交
415
				services.set(IUpdateService, new SyncDescriptor(SnapUpdateService, [process.env.SNAP, process.env.SNAP_REVISION]));
J
Joao Moreno 已提交
416 417 418
			} else {
				services.set(IUpdateService, new SyncDescriptor(LinuxUpdateService));
			}
419 420 421 422
		} else if (process.platform === 'darwin') {
			services.set(IUpdateService, new SyncDescriptor(DarwinUpdateService));
		}

423 424
		services.set(IWindowsMainService, new SyncDescriptor(WindowsManager, [machineId]));
		services.set(IWindowsService, new SyncDescriptor(WindowsService, [this.sharedProcess]));
425
		services.set(ILaunchService, new SyncDescriptor(LaunchService));
426
		services.set(IIssueService, new SyncDescriptor(IssueService, [machineId, this.userEnv]));
427
		services.set(IMenubarService, new SyncDescriptor(MenubarService));
428
		services.set(IStorageMainService, new SyncDescriptor(StorageMainService));
429 430 431 432
		services.set(IBackupMainService, new SyncDescriptor(BackupMainService));
		services.set(IHistoryMainService, new SyncDescriptor(HistoryMainService));
		services.set(IURLService, new SyncDescriptor(URLService));
		services.set(IWorkspacesMainService, new SyncDescriptor(WorkspacesMainService));
433

434
		// Telemetry
435
		if (!this.environmentService.isExtensionDevelopment && !this.environmentService.args['disable-telemetry'] && !!product.enableTelemetry) {
J
Joao Moreno 已提交
436
			const channel = getDelayedChannel(this.sharedProcessClient.then(c => c.getChannel('telemetryAppender')));
437
			const appender = combinedAppender(new TelemetryAppenderClient(channel), new LogAppender(this.logService));
438
			const commonProperties = resolveCommonProperties(product.commit, pkg.version, machineId, this.environmentService.installSourcePath);
439 440
			const piiPaths = [this.environmentService.appRoot, this.environmentService.extensionsPath];
			const config: ITelemetryServiceConfig = { appender, commonProperties, piiPaths };
441

442
			services.set(ITelemetryService, new SyncDescriptor(TelemetryService, [config]));
443 444 445 446
		} else {
			services.set(ITelemetryService, NullTelemetryService);
		}

447 448
		const appInstantiationService = this.instantiationService.createChild(services);

449
		// Init services that require it
450
		await appInstantiationService.invokeFunction(accessor => Promise.all([
451 452
			this.initStorageService(accessor),
			this.initBackupService(accessor)
453 454 455
		]));

		return appInstantiationService;
456 457
	}

J
Johannes Rieken 已提交
458
	private initStorageService(accessor: ServicesAccessor): Promise<void> {
459
		const storageMainService = accessor.get(IStorageMainService) as StorageMainService;
460

B
wip  
Benjamin Pasero 已提交
461
		// Ensure to close storage on shutdown
462
		this.lifecycleService.onWillShutdown(e => e.join(storageMainService.close()));
B
wip  
Benjamin Pasero 已提交
463

464
		return Promise.resolve();
465

466 467
	}

468 469 470 471 472 473
	private initBackupService(accessor: ServicesAccessor): Promise<void> {
		const backupMainService = accessor.get(IBackupMainService) as BackupMainService;

		return backupMainService.initialize();
	}

B
Benjamin Pasero 已提交
474
	private openFirstWindow(accessor: ServicesAccessor): ICodeWindow[] {
475 476 477 478 479 480 481 482 483 484 485 486
		const appInstantiationService = accessor.get(IInstantiationService);

		// Register more Main IPC services
		const launchService = accessor.get(ILaunchService);
		const launchChannel = new LaunchChannel(launchService);
		this.mainIpcServer.registerChannel('launch', launchChannel);

		// Register more Electron IPC services
		const updateService = accessor.get(IUpdateService);
		const updateChannel = new UpdateChannel(updateService);
		this.electronIpcServer.registerChannel('update', updateChannel);

487 488 489 490
		const issueService = accessor.get(IIssueService);
		const issueChannel = new IssueChannel(issueService);
		this.electronIpcServer.registerChannel('issue', issueChannel);

B
Benjamin Pasero 已提交
491 492 493 494
		const workspacesService = accessor.get(IWorkspacesMainService);
		const workspacesChannel = appInstantiationService.createInstance(WorkspacesChannel, workspacesService);
		this.electronIpcServer.registerChannel('workspaces', workspacesChannel);

495 496 497
		const windowsService = accessor.get(IWindowsService);
		const windowsChannel = new WindowsChannel(windowsService);
		this.electronIpcServer.registerChannel('windows', windowsChannel);
498
		this.sharedProcessClient.then(client => client.registerChannel('windows', windowsChannel));
499

500 501 502 503
		const menubarService = accessor.get(IMenubarService);
		const menubarChannel = new MenubarChannel(menubarService);
		this.electronIpcServer.registerChannel('menubar', menubarChannel);

J
Joao Moreno 已提交
504 505 506 507
		const urlService = accessor.get(IURLService);
		const urlChannel = new URLServiceChannel(urlService);
		this.electronIpcServer.registerChannel('url', urlChannel);

508
		const storageMainService = accessor.get(IStorageMainService);
509
		const storageChannel = this._register(new GlobalStorageDatabaseChannel(this.logService, storageMainService as StorageMainService));
B
wip  
Benjamin Pasero 已提交
510 511
		this.electronIpcServer.registerChannel('storage', storageChannel);

S
Sandeep Somavarapu 已提交
512
		// Log level management
513
		const logLevelChannel = new LogLevelSetterChannel(accessor.get(ILogService));
S
Sandeep Somavarapu 已提交
514
		this.electronIpcServer.registerChannel('loglevel', logLevelChannel);
515
		this.sharedProcessClient.then(client => client.registerChannel('loglevel', logLevelChannel));
S
Sandeep Somavarapu 已提交
516

517
		// Lifecycle
B
Benjamin Pasero 已提交
518
		(this.lifecycleService as LifecycleService).ready();
519 520

		// Propagate to clients
521
		const windowsMainService = this.windowsMainService = accessor.get(IWindowsMainService); // TODO@Joao: unfold this
J
Joao Moreno 已提交
522

J
Joao Moreno 已提交
523
		// Create a URL handler which forwards to the last active window
J
Joao Moreno 已提交
524
		const activeWindowManager = new ActiveWindowManager(windowsService);
J
Joao Moreno 已提交
525 526
		const activeWindowRouter = new StaticRouter(ctx => activeWindowManager.getActiveClientId().then(id => ctx === id));
		const urlHandlerChannel = this.electronIpcServer.getChannel('urlHandler', activeWindowRouter);
J
Joao Moreno 已提交
527
		const multiplexURLHandler = new URLHandlerChannelClient(urlHandlerChannel);
J
Joao Moreno 已提交
528

529 530
		// On Mac, Code can be running without any open windows, so we must create a window to handle urls,
		// if there is none
531
		if (isMacintosh) {
532 533 534
			const environmentService = accessor.get(IEnvironmentService);

			urlService.registerHandler({
535
				async handleURL(uri: URI): Promise<boolean> {
536 537 538 539
					if (windowsMainService.getWindowCount() === 0) {
						const cli = { ...environmentService.args, goto: true };
						const [window] = windowsMainService.open({ context: OpenContext.API, cli, forceEmpty: true });

540 541 542
						await window.ready();

						return urlService.open(uri);
543 544
					}

545
					return false;
546 547 548 549
				}
			});
		}

550
		// Register the multiple URL handler
J
Joao Moreno 已提交
551 552
		urlService.registerHandler(multiplexURLHandler);

J
Joao Moreno 已提交
553
		// Watch Electron URLs and forward them to the UrlService
554
		const args = this.environmentService.args;
J
Joao Moreno 已提交
555
		const urls = args['open-url'] ? args._urls : [];
556
		const urlListener = new ElectronURLListener(urls || [], urlService, this.windowsMainService);
557
		this._register(urlListener);
J
Joao Moreno 已提交
558

559 560 561
		this.windowsMainService.ready(this.userEnv);

		// Open our first window
562
		const macOpenFiles: string[] = (<any>global).macOpenFiles;
563
		const context = !!process.env['VSCODE_CLI'] ? OpenContext.CLI : OpenContext.DESKTOP;
M
Martin Aeschlimann 已提交
564 565 566
		const hasCliArgs = hasArgs(args._);
		const hasFolderURIs = hasArgs(args['folder-uri']);
		const hasFileURIs = hasArgs(args['file-uri']);
567
		const noRecentEntry = args['skip-add-to-recently-opened'] === true;
M
Martin Aeschlimann 已提交
568
		const waitMarkerFileURI = args.wait && args.waitMarkerFilePath ? URI.file(args.waitMarkerFilePath) : undefined;
569

M
Martin Aeschlimann 已提交
570
		if (args['new-window'] && !hasCliArgs && !hasFolderURIs && !hasFileURIs) {
M
Martin Aeschlimann 已提交
571 572 573 574 575 576 577 578 579 580
			// new window if "-n" was used without paths
			return this.windowsMainService.open({
				context,
				cli: args,
				forceNewWindow: true,
				forceEmpty: true,
				noRecentEntry,
				waitMarkerFileURI,
				initialStartup: true
			});
581
		}
B
Benjamin Pasero 已提交
582 583

		if (macOpenFiles && macOpenFiles.length && !hasCliArgs && !hasFolderURIs && !hasFileURIs) {
M
Martin Aeschlimann 已提交
584 585 586 587
			// mac: open-file event received on startup
			return this.windowsMainService.open({
				context: OpenContext.DOCK,
				cli: args,
M
Martin Aeschlimann 已提交
588
				urisToOpen: macOpenFiles.map(getURIToOpenFromPathSync),
M
Martin Aeschlimann 已提交
589 590 591 592
				noRecentEntry,
				waitMarkerFileURI,
				initialStartup: true
			});
B
Benjamin Pasero 已提交
593 594
		}

M
Martin Aeschlimann 已提交
595 596 597 598 599 600 601 602 603 604
		// default: read paths from cli
		return this.windowsMainService.open({
			context,
			cli: args,
			forceNewWindow: args['new-window'] || (!hasCliArgs && args['unity-launch']),
			diffMode: args.diff,
			noRecentEntry,
			waitMarkerFileURI,
			initialStartup: true
		});
605 606 607
	}

	private afterWindowOpen(accessor: ServicesAccessor): void {
608
		const windowsMainService = accessor.get(IWindowsMainService);
609
		const historyMainService = accessor.get(IHistoryMainService);
610

611
		if (isWindows) {
612 613

			// Setup Windows mutex
614 615
			try {
				const Mutex = (require.__$__nodeRequire('windows-mutex') as any).Mutex;
616
				const windowsMutex = new Mutex(product.win32MutexName);
617
				this._register(toDisposable(() => windowsMutex.release()));
618
			} catch (e) {
619
				if (!this.environmentService.isBuilt) {
620
					windowsMainService.showMessageBox({
621 622 623 624 625
						title: product.nameLong,
						type: 'warning',
						message: 'Failed to load windows-mutex!',
						detail: e.toString(),
						noLink: true
626 627
					});
				}
628
			}
629

630
			// Ensure Windows foreground love module
631
			try {
632
				// tslint:disable-next-line:no-unused-expression
633
				require.__$__nodeRequire('windows-foreground-love');
634 635
			} catch (e) {
				if (!this.environmentService.isBuilt) {
636
					windowsMainService.showMessageBox({
637 638 639 640 641
						title: product.nameLong,
						type: 'warning',
						message: 'Failed to load windows-foreground-love!',
						detail: e.toString(),
						noLink: true
642 643 644
					});
				}
			}
645
		}
646

647 648 649 650 651 652 653 654
		// Remote Authorities
		this.handleRemoteAuthorities();

		// Keyboard layout changes
		KeyboardLayoutMonitor.INSTANCE.onDidChangeKeyboardLayout(() => {
			this.windowsMainService.sendToAll('vscode:keyboardLayoutChanged', false);
		});

655
		// Jump List
656 657
		historyMainService.updateWindowsJumpList();
		historyMainService.onRecentlyOpenedChange(() => historyMainService.updateWindowsJumpList());
658

B
Benjamin Pasero 已提交
659
		// Start shared process after a while
J
Joao Moreno 已提交
660
		const sharedProcessSpawn = this._register(new RunOnceScheduler(() => getShellEnvironment(this.logService).then(userEnv => this.sharedProcess.spawn(userEnv)), 3000));
661
		sharedProcessSpawn.schedule();
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685

		// Helps application icon refresh after an update with new icon is installed (macOS)
		// TODO@Ben remove after a couple of releases
		if (isMacintosh) {
			if (!this.stateService.getItem(CodeApplication.APP_ICON_REFRESH_KEY)) {
				this.stateService.setItem(CodeApplication.APP_ICON_REFRESH_KEY, true);

				// 'exe' => /Applications/Visual Studio Code - Insiders.app/Contents/MacOS/Electron
				const appPath = dirname(dirname(dirname(app.getPath('exe'))));
				const infoPlistPath = join(appPath, 'Contents', 'Info.plist');
				this.touch(appPath);
				this.touch(infoPlistPath);
			}
		}
	}

	private async touch(path: string): Promise<void> {
		const now = Date.now() / 1000; // the value should be a Unix timestamp in seconds

		try {
			await promisify(utimes)(path, now, now);
		} catch (error) {
			// ignore
		}
686
	}
687 688 689 690

	private handleRemoteAuthorities(): void {
		const connectionPool: Map<string, ActiveConnection> = new Map<string, ActiveConnection>();

A
Alex Dima 已提交
691 692
		const isBuilt = this.environmentService.isBuilt;

693
		class ActiveConnection {
694
			private readonly _authority: string;
A
Alex Dima 已提交
695
			private readonly _connection: Promise<ManagementPersistentConnection>;
696
			private readonly _disposeRunner: RunOnceScheduler;
697 698 699

			constructor(authority: string, host: string, port: number) {
				this._authority = authority;
A
Alex Dima 已提交
700 701 702
				const options: IConnectionOptions = {
					isBuilt: isBuilt,
					commit: product.commit,
A
Alex Dima 已提交
703
					webSocketFactory: nodeWebSocketFactory,
A
Alex Dima 已提交
704 705 706 707 708 709 710
					addressProvider: {
						getAddress: () => {
							return Promise.resolve({ host, port });
						}
					}
				};
				this._connection = connectRemoteAgentManagement(options, authority, `main`);
711
				this._disposeRunner = new RunOnceScheduler(() => this.dispose(), 5000);
712 713
			}

714
			dispose(): void {
715 716
				this._disposeRunner.dispose();
				connectionPool.delete(this._authority);
717
				this._connection.then(connection => connection.dispose());
718 719
			}

A
Alex Dima 已提交
720
			async getClient(): Promise<Client<RemoteAgentConnectionContext>> {
721
				this._disposeRunner.schedule();
A
Alex Dima 已提交
722 723
				const connection = await this._connection;
				return connection.client;
724 725 726 727
			}
		}

		const resolvedAuthorities = new Map<string, ResolvedAuthority>();
728
		ipc.on('vscode:remoteAuthorityResolved', (event: Electron.Event, data: ResolvedAuthority) => {
729
			this.logService.info('Received resolved authority', data.authority);
730
			resolvedAuthorities.set(data.authority, data);
731 732
			// Make sure to close and remove any existing connections
			if (connectionPool.has(data.authority)) {
A
Alex Dima 已提交
733
				connectionPool.get(data.authority)!.dispose();
734
			}
735 736 737
		});

		const resolveAuthority = (authority: string): ResolvedAuthority | null => {
738
			this.logService.info('Resolving authority', authority);
739 740
			if (authority.indexOf('+') >= 0) {
				if (resolvedAuthorities.has(authority)) {
M
Matt Bierner 已提交
741
					return withUndefinedAsNull(resolvedAuthorities.get(authority));
742
				}
743
				this.logService.info('Didnot find resolved authority for', authority);
744 745 746 747
				return null;
			} else {
				const [host, strPort] = authority.split(':');
				const port = parseInt(strPort, 10);
748
				return { authority, host, port };
749 750 751
			}
		};

B
Benjamin Pasero 已提交
752
		protocol.registerBufferProtocol(Schemas.vscodeRemote, async (request, callback) => {
753
			if (request.method !== 'GET') {
754
				return callback(undefined);
755 756 757
			}
			const uri = URI.parse(request.url);

758
			let activeConnection: ActiveConnection | undefined;
759 760 761
			if (connectionPool.has(uri.authority)) {
				activeConnection = connectionPool.get(uri.authority);
			} else {
762
				const resolvedAuthority = resolveAuthority(uri.authority);
763
				if (!resolvedAuthority) {
764
					callback(undefined);
765 766 767 768 769 770
					return;
				}
				activeConnection = new ActiveConnection(uri.authority, resolvedAuthority.host, resolvedAuthority.port);
				connectionPool.set(uri.authority, activeConnection);
			}
			try {
771
				const rawClient = await activeConnection!.getClient();
772 773 774 775
				if (connectionPool.has(uri.authority)) { // not disposed in the meantime
					const channel = rawClient.getChannel(REMOTE_FILE_SYSTEM_CHANNEL_NAME);

					// TODO@alex don't use call directly, wrap it around a `RemoteExtensionsFileSystemProvider`
A
Alex Dima 已提交
776 777
					const fileContents = await channel.call<VSBuffer>('readFile', [uri]);
					callback(<Buffer>fileContents.buffer);
778
				} else {
779
					callback(undefined);
780 781
				}
			} catch (err) {
782
				onUnexpectedError(err);
783
				callback(undefined);
784 785 786
			}
		});
	}
787
}
788

M
Martin Aeschlimann 已提交
789 790 791 792 793 794 795 796 797 798 799 800
function getURIToOpenFromPathSync(path: string): IURIToOpen {
	try {
		const fileStat = statSync(path);
		if (fileStat.isDirectory()) {
			return { folderUri: URI.file(path) };
		} else if (hasWorkspaceFileExtension(path)) {
			return { workspaceUri: URI.file(path) };
		}
	} catch (error) {
	}
	return { fileUri: URI.file(path) };
}