app.ts 31.3 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';
12
import { ILifecycleService, LifecycleMainPhase } 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 } from 'vs/base/common/lifecycle';
B
Benjamin Pasero 已提交
40
import { IWindowsMainService, ICodeWindow } from 'vs/platform/windows/electron-main/windows';
B
Benjamin Pasero 已提交
41
import { IHistoryMainService } from 'vs/platform/history/common/history';
42
import { withUndefinedAsNull } from 'vs/base/common/types';
43
import { URI } from 'vs/base/common/uri';
J
Joao Moreno 已提交
44
import { WorkspacesChannel } from 'vs/platform/workspaces/node/workspacesIpc';
M
Martin Aeschlimann 已提交
45
import { IWorkspacesMainService, hasWorkspaceFileExtension } from 'vs/platform/workspaces/common/workspaces';
46
import { getMachineId } from 'vs/base/node/id';
47 48 49
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';
50
import { IIssueService } from 'vs/platform/issue/common/issue';
J
Joao Moreno 已提交
51
import { IssueChannel } from 'vs/platform/issue/node/issueIpc';
P
Pine Wu 已提交
52
import { IssueService } from 'vs/platform/issue/electron-main/issueService';
53
import { LogLevelSetterChannel } from 'vs/platform/log/common/logIpc';
54
import { setUnexpectedErrorHandler, onUnexpectedError } from 'vs/base/common/errors';
J
Joao Moreno 已提交
55
import { ElectronURLListener } from 'vs/platform/url/electron-main/electronUrlListener';
J
Joao Moreno 已提交
56
import { serve as serveDriver } from 'vs/platform/driver/electron-main/driver';
A
Alex Dima 已提交
57
import { connectRemoteAgentManagement, ManagementPersistentConnection, IConnectionOptions } from 'vs/platform/remote/common/remoteAgentConnection';
58 59
import { IMenubarService } from 'vs/platform/menubar/common/menubar';
import { MenubarService } from 'vs/platform/menubar/electron-main/menubarService';
J
Joao Moreno 已提交
60
import { MenubarChannel } from 'vs/platform/menubar/node/menubarIpc';
M
Martin Aeschlimann 已提交
61
import { hasArgs } from 'vs/platform/environment/node/argv';
62
import { RunOnceScheduler } from 'vs/base/common/async';
63
import { registerContextMenuListener } from 'vs/base/parts/contextmenu/electron-main/contextmenu';
B
Benjamin Pasero 已提交
64
import { homedir } from 'os';
B
Benjamin Pasero 已提交
65
import { join, sep } from 'vs/base/common/path';
B
Benjamin Pasero 已提交
66
import { localize } from 'vs/nls';
B
Benjamin Pasero 已提交
67
import { Schemas } from 'vs/base/common/network';
A
Alex Dima 已提交
68
import { REMOTE_FILE_SYSTEM_CHANNEL_NAME } from 'vs/platform/remote/common/remoteAgentFileSystemChannel';
A
Tweaks  
Alex Dima 已提交
69
import { ResolvedAuthority } from 'vs/platform/remote/common/remoteAuthorityResolver';
J
Joao Moreno 已提交
70
import { SnapUpdateService } from 'vs/platform/update/electron-main/updateService.snap';
B
wip  
Benjamin Pasero 已提交
71 72
import { IStorageMainService, StorageMainService } from 'vs/platform/storage/node/storageMainService';
import { GlobalStorageDatabaseChannel } from 'vs/platform/storage/node/storageIpc';
73
import { startsWith } from 'vs/base/common/strings';
74 75 76 77 78
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';
79
import { RemoteAgentConnectionContext } from 'vs/platform/remote/common/remoteAgentEnvironment';
A
Alex Dima 已提交
80
import { nodeWebSocketFactory } from 'vs/platform/remote/node/nodeWebSocketFactory';
A
Alex Dima 已提交
81
import { VSBuffer } from 'vs/base/common/buffer';
B
Benjamin Pasero 已提交
82
import { statSync } from 'fs';
I
isidor 已提交
83
import { ISignService } from 'vs/platform/sign/common/sign';
84 85
import { IDiagnosticsService } from 'vs/platform/diagnostics/common/diagnosticsService';
import { DiagnosticsService } from 'vs/platform/diagnostics/node/diagnosticsIpc';
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
	private windowsMainService: IWindowsMainService | undefined;
92 93

	constructor(
94 95
		private readonly mainIpcServer: Server,
		private readonly userEnv: IProcessEnvironment,
96 97 98 99
		@IInstantiationService private readonly instantiationService: IInstantiationService,
		@ILogService private readonly logService: ILogService,
		@IEnvironmentService private readonly environmentService: IEnvironmentService,
		@ILifecycleService private readonly lifecycleService: ILifecycleService,
S
Sandeep Somavarapu 已提交
100
		@IConfigurationService private readonly configurationService: IConfigurationService,
I
isidor 已提交
101 102
		@IStateService private readonly stateService: IStateService,
		@ISignService private readonly signService: ISignService
103
	) {
104 105
		super();

106 107 108 109 110 111
		this.registerListeners();
	}

	private registerListeners(): void {

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

B
Benjamin Pasero 已提交
116 117
		// Dispose on shutdown
		this.lifecycleService.onWillShutdown(() => this.dispose());
118

119 120 121
		// Contextmenu via IPC support
		registerContextMenuListener();

122 123 124 125 126 127 128
		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 已提交
129
			this.logService.trace('App#activate');
130 131 132 133 134 135 136

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

137
		// Security related measures (https://electronjs.org/docs/tutorial/security)
138 139 140 141
		//
		// !!! DO NOT CHANGE without consulting the documentation !!!
		//
		// app.on('remote-get-guest-web-contents', event => event.preventDefault()); // TODO@Ben TODO@Matt revisit this need for <webview>
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
		app.on('remote-require', (event, sender, module) => {
			this.logService.trace('App#on(remote-require): prevented');

			event.preventDefault();
		});
		app.on('remote-get-global', (event, sender, module) => {
			this.logService.trace(`App#on(remote-get-global): prevented on ${module}`);

			event.preventDefault();
		});
		app.on('remote-get-builtin', (event, sender, module) => {
			this.logService.trace(`App#on(remote-get-builtin): prevented on ${module}`);

			if (module !== 'clipboard') {
				event.preventDefault();
			}
		});
		app.on('remote-get-current-window', event => {
			this.logService.trace(`App#on(remote-get-current-window): prevented`);

			event.preventDefault();
		});
		app.on('remote-get-current-web-contents', event => {
			this.logService.trace(`App#on(remote-get-current-web-contents): prevented`);

			event.preventDefault();
		});
169
		app.on('web-contents-created', (_event: Electron.Event, contents) => {
170
			contents.on('will-attach-webview', (event: Electron.Event, webPreferences, params) => {
171

172 173 174 175 176 177 178 179 180
				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;
					}

181
					const srcUri = URI.parse(source).fsPath.toLowerCase();
182 183
					const rootUri = URI.file(this.environmentService.appRoot).fsPath.toLowerCase();

184
					return startsWith(srcUri, rootUri + sep);
185 186
				};

187
				// Ensure defaults
M
Matt Bierner 已提交
188 189 190 191
				delete webPreferences.preload;
				webPreferences.nodeIntegration = false;

				// Verify URLs being loaded
192
				if (isValidWebviewSource(params.src) && isValidWebviewSource(webPreferences.preloadURL)) {
M
Matt Bierner 已提交
193 194
					return;
				}
M
Matt Bierner 已提交
195

196 197
				delete webPreferences.preloadUrl;

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

M
Matt Bierner 已提交
201 202 203 204
				event.preventDefault();
			});

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

M
Matt Bierner 已提交
207 208
				event.preventDefault();
			});
209 210 211 212 213 214

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

				shell.openExternal(url);
			});
M
Matt Bierner 已提交
215 216
		});

217
		let macOpenFileURIs: IURIToOpen[] = [];
218
		let runningTimeout: NodeJS.Timeout | null = null;
219
		app.on('open-file', (event: Event, path: string) => {
J
Joao Moreno 已提交
220
			this.logService.trace('App#open-file: ', path);
221 222 223
			event.preventDefault();

			// Keep in array because more might come!
224
			macOpenFileURIs.push(this.getURIToOpenFromPathSync(path));
225 226 227 228 229 230 231 232 233 234 235 236 237

			// 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 已提交
238
						urisToOpen: macOpenFileURIs,
239 240
						preferNewWindow: true /* dropping on the dock or opening from finder prefers to open in a new window */
					});
241

242
					macOpenFileURIs = [];
243 244 245 246 247
					runningTimeout = null;
				}
			}, 100);
		});

248
		app.on('new-window-for-tab', () => {
249 250 251
			if (this.windowsMainService) {
				this.windowsMainService.openNewWindow(OpenContext.DESKTOP); //macOS native tab "+" button
			}
252 253
		});

254
		ipc.on('vscode:exit', (event: Event, code: number) => {
J
Joao Moreno 已提交
255
			this.logService.trace('IPC#vscode:exit', code);
256 257 258 259 260

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

261
		ipc.on('vscode:fetchShellEnv', async (event: Event) => {
262
			const webContents = event.sender;
263 264

			try {
265
				const shellEnv = await getShellEnvironment(this.logService, this.environmentService);
J
Johannes Rieken 已提交
266 267 268
				if (!webContents.isDestroyed()) {
					webContents.send('vscode:acceptShellEnv', shellEnv);
				}
269
			} catch (error) {
J
Johannes Rieken 已提交
270 271 272
				if (!webContents.isDestroyed()) {
					webContents.send('vscode:acceptShellEnv', {});
				}
B
Benjamin Pasero 已提交
273

274 275
				this.logService.error('Error fetching shell env', error);
			}
276
		});
277

278 279
		ipc.on('vscode:extensionHostDebug', (_: Event, windowId: number, broadcast: any) => {
			if (this.windowsMainService) {
280
				this.windowsMainService.sendToAll('vscode:extensionHostDebug', broadcast, [windowId]); // Send to all windows (except sender window)
281 282 283
			}
		});

284 285
		ipc.on('vscode:toggleDevTools', (event: Event) => event.sender.toggleDevTools());
		ipc.on('vscode:openDevTools', (event: Event) => event.sender.openDevTools());
B
Benjamin Pasero 已提交
286

287
		ipc.on('vscode:reloadWindow', (event: Event) => event.sender.reload());
288

B
Benjamin Pasero 已提交
289
		// Some listeners after window opened
290 291 292
		(async () => {
			await this.lifecycleService.when(LifecycleMainPhase.AfterWindowOpen);

B
Benjamin Pasero 已提交
293
			// After waking up from sleep  (after window opened)
294 295 296 297 298 299
			powerMonitor.on('resume', () => {
				if (this.windowsMainService) {
					this.windowsMainService.sendToAll('vscode:osResume', undefined);
				}
			});

B
Benjamin Pasero 已提交
300
			// Keyboard layout changes (after window opened)
301 302 303 304 305 306 307
			const nativeKeymap = await import('native-keymap');
			nativeKeymap.onDidChangeKeyboardLayout(() => {
				if (this.windowsMainService) {
					this.windowsMainService.sendToAll('vscode:keyboardLayoutChanged', false);
				}
			});
		})();
308 309
	}

B
Benjamin Pasero 已提交
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
	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);
		}
	}

331
	async startup(): Promise<void> {
J
Joao Moreno 已提交
332 333 334
		this.logService.debug('Starting VS Code');
		this.logService.debug(`from: ${this.environmentService.appRoot}`);
		this.logService.debug('args:', this.environmentService.args);
335

336 337 338 339
		// 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.
340
		if (isWindows && product.win32AppUserModelId) {
341 342
			app.setAppUserModelId(product.win32AppUserModelId);
		}
343

344 345 346 347 348 349 350
		// 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 {
351
			if (isMacintosh && this.configurationService.getValue<boolean>('window.nativeTabs') === true && !systemPreferences.getUserDefault('NSUseImprovedLayoutPass', 'boolean')) {
352
				systemPreferences.setUserDefault('NSUseImprovedLayoutPass', 'boolean', true as any);
353 354 355 356 357
			}
		} catch (error) {
			this.logService.error(error);
		}

358
		// Create Electron IPC Server
359
		const electronIpcServer = new ElectronIPCServer();
360

361 362 363 364
		// Resolve unique machine ID
		this.logService.trace('Resolving machine identifier...');
		const machineId = await this.resolveMachineId();
		this.logService.trace(`Resolved machine identifier: ${machineId}`);
365

366 367 368 369 370
		// Spawn shared process after the first window has opened and 3s have passed
		const sharedProcess = this.instantiationService.createInstance(SharedProcess, machineId, this.userEnv);
		const sharedProcessClient = sharedProcess.whenReady().then(() => connect(this.environmentService.sharedIPCHandle, 'main'));
		this.lifecycleService.when(LifecycleMainPhase.AfterWindowOpen).then(() => {
			this._register(new RunOnceScheduler(async () => {
371
				const userEnv = await getShellEnvironment(this.logService, this.environmentService);
372 373 374 375

				sharedProcess.spawn(userEnv);
			}, 3000)).schedule();
		});
376

377
		// Services
378
		const appInstantiationService = await this.createServices(machineId, sharedProcess, sharedProcessClient);
379

380 381
		// Create driver
		if (this.environmentService.driverHandle) {
B
Benjamin Pasero 已提交
382
			const server = await serveDriver(electronIpcServer, this.environmentService.driverHandle!, this.environmentService, appInstantiationService);
383

B
Benjamin Pasero 已提交
384 385
			this.logService.info('Driver started at:', this.environmentService.driverHandle);
			this._register(server);
386
		}
387

388 389 390
		// Setup Auth Handler
		const authHandler = appInstantiationService.createInstance(ProxyAuthHandler);
		this._register(authHandler);
B
Benjamin Pasero 已提交
391

392
		// Open Windows
393
		const windows = appInstantiationService.invokeFunction(accessor => this.openFirstWindow(accessor, electronIpcServer, sharedProcessClient));
B
Benjamin Pasero 已提交
394

395
		// Post Open Windows Tasks
396
		this.afterWindowOpen();
B
Benjamin Pasero 已提交
397

398 399 400
		// Tracing: Stop tracing after windows are ready if enabled
		if (this.environmentService.args.trace) {
			this.stopTracingEventually(windows);
B
Benjamin Pasero 已提交
401 402 403
		}
	}

404
	private async resolveMachineId(): Promise<string> {
B
Benjamin Pasero 已提交
405

406 407 408 409 410
		// We cache the machineId for faster lookups on startup
		// and resolve it only once initially if not cached
		let machineId = this.stateService.getItem<string>(CodeApplication.MACHINE_ID_KEY);
		if (!machineId) {
			machineId = await getMachineId();
B
Benjamin Pasero 已提交
411

412 413
			this.stateService.setItem(CodeApplication.MACHINE_ID_KEY, machineId);
		}
414 415

		return machineId;
416 417
	}

418 419
	private async createServices(machineId: string, sharedProcess: SharedProcess, sharedProcessClient: Promise<Client<string>>): Promise<IInstantiationService> {
		const services = new ServiceCollection();
420

421 422 423 424
		switch (process.platform) {
			case 'win32':
				services.set(IUpdateService, new SyncDescriptor(Win32UpdateService));
				break;
425

426 427 428
			case 'linux':
				if (process.env.SNAP && process.env.SNAP_REVISION) {
					services.set(IUpdateService, new SyncDescriptor(SnapUpdateService, [process.env.SNAP, process.env.SNAP_REVISION]));
429
				} else {
430
					services.set(IUpdateService, new SyncDescriptor(LinuxUpdateService));
B
Benjamin Pasero 已提交
431
				}
432
				break;
433

434 435 436
			case 'darwin':
				services.set(IUpdateService, new SyncDescriptor(DarwinUpdateService));
				break;
437 438
		}

439 440
		services.set(IWindowsMainService, new SyncDescriptor(WindowsManager, [machineId, this.userEnv]));
		services.set(IWindowsService, new SyncDescriptor(WindowsService, [sharedProcess]));
441
		services.set(ILaunchService, new SyncDescriptor(LaunchService));
442 443 444 445

		const diagnosticsChannel = getDelayedChannel(sharedProcessClient.then(client => client.getChannel('diagnostics')));
		services.set(IDiagnosticsService, new SyncDescriptor(DiagnosticsService, [diagnosticsChannel]));

446
		services.set(IIssueService, new SyncDescriptor(IssueService, [machineId, this.userEnv]));
447
		services.set(IMenubarService, new SyncDescriptor(MenubarService));
448 449 450 451 452 453 454 455

		const storageMainService = new StorageMainService(this.logService, this.environmentService);
		services.set(IStorageMainService, storageMainService);
		this.lifecycleService.onWillShutdown(e => e.join(storageMainService.close()));

		const backupMainService = new BackupMainService(this.environmentService, this.configurationService, this.logService);
		services.set(IBackupMainService, backupMainService);

456 457 458
		services.set(IHistoryMainService, new SyncDescriptor(HistoryMainService));
		services.set(IURLService, new SyncDescriptor(URLService));
		services.set(IWorkspacesMainService, new SyncDescriptor(WorkspacesMainService));
459

460
		// Telemetry
461
		if (!this.environmentService.isExtensionDevelopment && !this.environmentService.args['disable-telemetry'] && !!product.enableTelemetry) {
462
			const channel = getDelayedChannel(sharedProcessClient.then(client => client.getChannel('telemetryAppender')));
463
			const appender = combinedAppender(new TelemetryAppenderClient(channel), new LogAppender(this.logService));
464
			const commonProperties = resolveCommonProperties(product.commit, pkg.version, machineId, this.environmentService.installSourcePath);
465 466
			const piiPaths = [this.environmentService.appRoot, this.environmentService.extensionsPath];
			const config: ITelemetryServiceConfig = { appender, commonProperties, piiPaths };
467

468
			services.set(ITelemetryService, new SyncDescriptor(TelemetryService, [config]));
469 470 471 472
		} else {
			services.set(ITelemetryService, NullTelemetryService);
		}

473
		// Init services that require it
474
		await backupMainService.initialize();
475

476
		return this.instantiationService.createChild(services);
477 478
	}

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

482 483 484 485 486
		let recordingStopped = false;
		const stopRecording = (timeout: boolean) => {
			if (recordingStopped) {
				return;
			}
B
wip  
Benjamin Pasero 已提交
487

488
			recordingStopped = true; // only once
489

490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
			contentTracing.stopRecording(join(homedir(), `${product.applicationName}-${Math.random().toString(16).slice(-4)}.trace.txt`), path => {
				if (!timeout) {
					if (this.windowsMainService) {
						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}`);
				}
			});
		};
505

506 507 508 509 510 511 512 513
		// 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
		Promise.all(windows.map(window => window.ready())).then(() => {
			clearTimeout(timeoutHandle);
			stopRecording(false);
		});
514 515
	}

516
	private openFirstWindow(accessor: ServicesAccessor, electronIpcServer: ElectronIPCServer, sharedProcessClient: Promise<Client<string>>): ICodeWindow[] {
517 518 519 520 521 522 523 524 525

		// 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);
526
		electronIpcServer.registerChannel('update', updateChannel);
527

528 529
		const issueService = accessor.get(IIssueService);
		const issueChannel = new IssueChannel(issueService);
530
		electronIpcServer.registerChannel('issue', issueChannel);
531

B
Benjamin Pasero 已提交
532
		const workspacesService = accessor.get(IWorkspacesMainService);
533 534
		const workspacesChannel = new WorkspacesChannel(workspacesService);
		electronIpcServer.registerChannel('workspaces', workspacesChannel);
B
Benjamin Pasero 已提交
535

536 537
		const windowsService = accessor.get(IWindowsService);
		const windowsChannel = new WindowsChannel(windowsService);
538 539
		electronIpcServer.registerChannel('windows', windowsChannel);
		sharedProcessClient.then(client => client.registerChannel('windows', windowsChannel));
540

541 542
		const menubarService = accessor.get(IMenubarService);
		const menubarChannel = new MenubarChannel(menubarService);
543
		electronIpcServer.registerChannel('menubar', menubarChannel);
544

J
Joao Moreno 已提交
545 546
		const urlService = accessor.get(IURLService);
		const urlChannel = new URLServiceChannel(urlService);
547
		electronIpcServer.registerChannel('url', urlChannel);
J
Joao Moreno 已提交
548

549
		const storageMainService = accessor.get(IStorageMainService);
550
		const storageChannel = this._register(new GlobalStorageDatabaseChannel(this.logService, storageMainService as StorageMainService));
551
		electronIpcServer.registerChannel('storage', storageChannel);
B
wip  
Benjamin Pasero 已提交
552

S
Sandeep Somavarapu 已提交
553
		// Log level management
554
		const logLevelChannel = new LogLevelSetterChannel(accessor.get(ILogService));
555 556
		electronIpcServer.registerChannel('loglevel', logLevelChannel);
		sharedProcessClient.then(client => client.registerChannel('loglevel', logLevelChannel));
S
Sandeep Somavarapu 已提交
557

558 559
		// Signal phase: ready (services set)
		this.lifecycleService.phase = LifecycleMainPhase.Ready;
560 561

		// Propagate to clients
J
Joao Moreno 已提交
562
		const windowsMainService = this.windowsMainService = accessor.get(IWindowsMainService);
J
Joao Moreno 已提交
563

J
Joao Moreno 已提交
564
		// Create a URL handler which forwards to the last active window
J
Joao Moreno 已提交
565
		const activeWindowManager = new ActiveWindowManager(windowsService);
J
Joao Moreno 已提交
566
		const activeWindowRouter = new StaticRouter(ctx => activeWindowManager.getActiveClientId().then(id => ctx === id));
567
		const urlHandlerChannel = electronIpcServer.getChannel('urlHandler', activeWindowRouter);
J
Joao Moreno 已提交
568
		const multiplexURLHandler = new URLHandlerChannelClient(urlHandlerChannel);
J
Joao Moreno 已提交
569

570 571
		// On Mac, Code can be running without any open windows, so we must create a window to handle urls,
		// if there is none
572
		if (isMacintosh) {
573 574 575
			const environmentService = accessor.get(IEnvironmentService);

			urlService.registerHandler({
576
				async handleURL(uri: URI): Promise<boolean> {
577 578 579 580
					if (windowsMainService.getWindowCount() === 0) {
						const cli = { ...environmentService.args, goto: true };
						const [window] = windowsMainService.open({ context: OpenContext.API, cli, forceEmpty: true });

581 582 583
						await window.ready();

						return urlService.open(uri);
584 585
					}

586
					return false;
587 588 589 590
				}
			});
		}

591
		// Register the multiple URL handler
J
Joao Moreno 已提交
592 593
		urlService.registerHandler(multiplexURLHandler);

J
Joao Moreno 已提交
594
		// Watch Electron URLs and forward them to the UrlService
595
		const args = this.environmentService.args;
J
Joao Moreno 已提交
596
		const urls = args['open-url'] ? args._urls : [];
597
		const urlListener = new ElectronURLListener(urls || [], urlService, windowsMainService);
598
		this._register(urlListener);
J
Joao Moreno 已提交
599

600
		// Open our first window
601
		const macOpenFiles: string[] = (<any>global).macOpenFiles;
602
		const context = !!process.env['VSCODE_CLI'] ? OpenContext.CLI : OpenContext.DESKTOP;
M
Martin Aeschlimann 已提交
603 604 605
		const hasCliArgs = hasArgs(args._);
		const hasFolderURIs = hasArgs(args['folder-uri']);
		const hasFileURIs = hasArgs(args['file-uri']);
606
		const noRecentEntry = args['skip-add-to-recently-opened'] === true;
M
Martin Aeschlimann 已提交
607
		const waitMarkerFileURI = args.wait && args.waitMarkerFilePath ? URI.file(args.waitMarkerFilePath) : undefined;
608

609
		// new window if "-n" was used without paths
M
Martin Aeschlimann 已提交
610
		if (args['new-window'] && !hasCliArgs && !hasFolderURIs && !hasFileURIs) {
611
			return windowsMainService.open({
M
Martin Aeschlimann 已提交
612 613 614 615 616 617 618 619
				context,
				cli: args,
				forceNewWindow: true,
				forceEmpty: true,
				noRecentEntry,
				waitMarkerFileURI,
				initialStartup: true
			});
620
		}
B
Benjamin Pasero 已提交
621

622
		// mac: open-file event received on startup
B
Benjamin Pasero 已提交
623
		if (macOpenFiles && macOpenFiles.length && !hasCliArgs && !hasFolderURIs && !hasFileURIs) {
624
			return windowsMainService.open({
M
Martin Aeschlimann 已提交
625 626
				context: OpenContext.DOCK,
				cli: args,
627
				urisToOpen: macOpenFiles.map(file => this.getURIToOpenFromPathSync(file)),
M
Martin Aeschlimann 已提交
628 629 630 631
				noRecentEntry,
				waitMarkerFileURI,
				initialStartup: true
			});
B
Benjamin Pasero 已提交
632 633
		}

M
Martin Aeschlimann 已提交
634
		// default: read paths from cli
635
		return windowsMainService.open({
M
Martin Aeschlimann 已提交
636 637 638 639 640 641 642 643
			context,
			cli: args,
			forceNewWindow: args['new-window'] || (!hasCliArgs && args['unity-launch']),
			diffMode: args.diff,
			noRecentEntry,
			waitMarkerFileURI,
			initialStartup: true
		});
644 645
	}

646 647 648 649 650
	private getURIToOpenFromPathSync(path: string): IURIToOpen {
		try {
			const fileStat = statSync(path);
			if (fileStat.isDirectory()) {
				return { folderUri: URI.file(path) };
651
			}
652

653 654
			if (hasWorkspaceFileExtension(path)) {
				return { workspaceUri: URI.file(path) };
655
			}
656 657
		} catch (error) {
			// ignore errors
658
		}
659

660 661
		return { fileUri: URI.file(path) };
	}
662

663
	private afterWindowOpen(): void {
664

665 666
		// Signal phase: after window open
		this.lifecycleService.phase = LifecycleMainPhase.AfterWindowOpen;
667

668 669
		// Remote Authorities
		this.handleRemoteAuthorities();
670
	}
671 672 673 674

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

A
Alex Dima 已提交
675 676
		const isBuilt = this.environmentService.isBuilt;

677
		class ActiveConnection {
678
			private readonly _authority: string;
A
Alex Dima 已提交
679
			private readonly _connection: Promise<ManagementPersistentConnection>;
680
			private readonly _disposeRunner: RunOnceScheduler;
681

I
isidor 已提交
682
			constructor(authority: string, host: string, port: number, signService: ISignService) {
683
				this._authority = authority;
684

A
Alex Dima 已提交
685
				const options: IConnectionOptions = {
686
					isBuilt,
A
Alex Dima 已提交
687
					commit: product.commit,
A
Alex Dima 已提交
688
					webSocketFactory: nodeWebSocketFactory,
A
Alex Dima 已提交
689 690 691 692
					addressProvider: {
						getAddress: () => {
							return Promise.resolve({ host, port });
						}
I
isidor 已提交
693
					},
I
Isidor Nikolic 已提交
694
					signService
A
Alex Dima 已提交
695
				};
696

A
Alex Dima 已提交
697
				this._connection = connectRemoteAgentManagement(options, authority, `main`);
698
				this._disposeRunner = new RunOnceScheduler(() => this.dispose(), 5000);
699 700
			}

701
			dispose(): void {
702 703
				this._disposeRunner.dispose();
				connectionPool.delete(this._authority);
704
				this._connection.then(connection => connection.dispose());
705 706
			}

A
Alex Dima 已提交
707
			async getClient(): Promise<Client<RemoteAgentConnectionContext>> {
708
				this._disposeRunner.schedule();
A
Alex Dima 已提交
709
				const connection = await this._connection;
710

A
Alex Dima 已提交
711
				return connection.client;
712 713 714 715
			}
		}

		const resolvedAuthorities = new Map<string, ResolvedAuthority>();
716
		ipc.on('vscode:remoteAuthorityResolved', (event: Electron.Event, data: ResolvedAuthority) => {
717
			this.logService.info('Received resolved authority', data.authority);
718

719
			resolvedAuthorities.set(data.authority, data);
720

721 722
			// Make sure to close and remove any existing connections
			if (connectionPool.has(data.authority)) {
A
Alex Dima 已提交
723
				connectionPool.get(data.authority)!.dispose();
724
			}
725 726 727
		});

		const resolveAuthority = (authority: string): ResolvedAuthority | null => {
728
			this.logService.info('Resolving authority', authority);
729

730 731
			if (authority.indexOf('+') >= 0) {
				if (resolvedAuthorities.has(authority)) {
M
Matt Bierner 已提交
732
					return withUndefinedAsNull(resolvedAuthorities.get(authority));
733
				}
734

735
				this.logService.info('Didnot find resolved authority for', authority);
736

737 738 739 740
				return null;
			} else {
				const [host, strPort] = authority.split(':');
				const port = parseInt(strPort, 10);
741

742
				return { authority, host, port };
743 744 745
			}
		};

B
Benjamin Pasero 已提交
746
		protocol.registerBufferProtocol(Schemas.vscodeRemote, async (request, callback) => {
747
			if (request.method !== 'GET') {
748
				return callback(undefined);
749
			}
750

751 752
			const uri = URI.parse(request.url);

753
			let activeConnection: ActiveConnection | undefined;
754 755 756
			if (connectionPool.has(uri.authority)) {
				activeConnection = connectionPool.get(uri.authority);
			} else {
757
				const resolvedAuthority = resolveAuthority(uri.authority);
758
				if (!resolvedAuthority) {
759
					callback(undefined);
760 761
					return;
				}
762

I
isidor 已提交
763
				activeConnection = new ActiveConnection(uri.authority, resolvedAuthority.host, resolvedAuthority.port, this.signService);
764 765
				connectionPool.set(uri.authority, activeConnection);
			}
766

767
			try {
768
				const rawClient = await activeConnection!.getClient();
769 770 771 772
				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 已提交
773 774
					const fileContents = await channel.call<VSBuffer>('readFile', [uri]);
					callback(<Buffer>fileContents.buffer);
775
				} else {
776
					callback(undefined);
777 778
				}
			} catch (err) {
779
				onUnexpectedError(err);
780
				callback(undefined);
781 782 783
			}
		});
	}
784
}