app.ts 31.1 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 17 18
import { Server as ElectronIPCServer } from 'vs/base/parts/ipc/electron-main/ipc.electron-main';
import { Server, connect, Client } from 'vs/base/parts/ipc/node/ipc.net';
import { SharedProcess } from 'vs/code/electron-main/sharedProcess';
B
Benjamin Pasero 已提交
19
import { LaunchService, LaunchChannel, ILaunchService } from 'vs/platform/launch/electron-main/launchService';
20 21 22
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';
23
import { ILogService } from 'vs/platform/log/common/log';
B
Benjamin Pasero 已提交
24
import { IStateService } from 'vs/platform/state/common/state';
25 26 27
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 已提交
28
import { URLHandlerChannelClient, URLServiceChannel } from 'vs/platform/url/node/urlIpc';
29
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
30
import { NullTelemetryService, combinedAppender, LogAppender } from 'vs/platform/telemetry/common/telemetryUtils';
J
Joao Moreno 已提交
31
import { TelemetryAppenderClient } from 'vs/platform/telemetry/node/telemetryIpc';
32
import { TelemetryService, ITelemetryServiceConfig } from 'vs/platform/telemetry/common/telemetryService';
33
import { resolveCommonProperties } from 'vs/platform/telemetry/node/commonProperties';
A
Alex Dima 已提交
34
import { getDelayedChannel, StaticRouter } from 'vs/base/parts/ipc/common/ipc';
35 36
import product from 'vs/platform/product/node/product';
import pkg from 'vs/platform/product/node/package';
37
import { ProxyAuthHandler } from 'vs/code/electron-main/auth';
38
import { Disposable, toDisposable } from 'vs/base/common/lifecycle';
B
Benjamin Pasero 已提交
39
import { ConfigurationService } from 'vs/platform/configuration/node/configurationService';
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';
M
Matt Bierner 已提交
42
import { isUndefinedOrNull, withUndefinedAsNull } from 'vs/base/common/types';
43
import { KeyboardLayoutMonitor } from 'vs/code/electron-main/keyboard';
44
import { URI } from 'vs/base/common/uri';
J
Joao Moreno 已提交
45
import { WorkspacesChannel } from 'vs/platform/workspaces/node/workspacesIpc';
B
Benjamin Pasero 已提交
46
import { IWorkspacesMainService } from 'vs/platform/workspaces/common/workspaces';
47
import { getMachineId } from 'vs/base/node/id';
48 49 50
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';
51
import { IIssueService } from 'vs/platform/issue/common/issue';
J
Joao Moreno 已提交
52
import { IssueChannel } from 'vs/platform/issue/node/issueIpc';
P
Pine Wu 已提交
53
import { IssueService } from 'vs/platform/issue/electron-main/issueService';
J
Joao Moreno 已提交
54
import { LogLevelSetterChannel } from 'vs/platform/log/node/logIpc';
A
Alex Dima 已提交
55
import * as errors from 'vs/base/common/errors';
J
Joao Moreno 已提交
56
import { ElectronURLListener } from 'vs/platform/url/electron-main/electronUrlListener';
J
Joao Moreno 已提交
57
import { serve as serveDriver } from 'vs/platform/driver/electron-main/driver';
A
Alex Dima 已提交
58
import { connectRemoteAgentManagement, ManagementPersistentConnection } from 'vs/platform/remote/node/remoteAgentConnection';
59 60
import { IMenubarService } from 'vs/platform/menubar/common/menubar';
import { MenubarService } from 'vs/platform/menubar/electron-main/menubarService';
J
Joao Moreno 已提交
61
import { MenubarChannel } from 'vs/platform/menubar/node/menubarIpc';
M
Martin Aeschlimann 已提交
62
import { hasArgs } from 'vs/platform/environment/node/argv';
63
import { RunOnceScheduler } from 'vs/base/common/async';
64
import { registerContextMenuListener } from 'vs/base/parts/contextmenu/electron-main/contextmenu';
65
import { storeBackgroundColor } from 'vs/code/electron-main/theme';
B
Benjamin Pasero 已提交
66
import { homedir } from 'os';
67
import { join, sep } from 'vs/base/common/path';
B
Benjamin Pasero 已提交
68
import { localize } from 'vs/nls';
A
Tweaks  
Alex Dima 已提交
69
import { REMOTE_HOST_SCHEME } from 'vs/platform/remote/common/remoteHosts';
J
Joao Moreno 已提交
70
import { REMOTE_FILE_SYSTEM_CHANNEL_NAME } from 'vs/platform/remote/node/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';
82

83
export class CodeApplication extends Disposable {
B
Benjamin Pasero 已提交
84

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

87 88 89 90 91
	private windowsMainService: IWindowsMainService;

	private electronIpcServer: ElectronIPCServer;

	private sharedProcess: SharedProcess;
J
Johannes Rieken 已提交
92
	private sharedProcessClient: Promise<Client>;
93 94

	constructor(
95 96
		private readonly mainIpcServer: Server,
		private readonly userEnv: IProcessEnvironment,
97 98 99 100 101 102
		@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
103
	) {
104 105 106 107
		super();

		this._register(mainIpcServer);
		this._register(configurationService);
108 109 110 111 112 113 114

		this.registerListeners();
	}

	private registerListeners(): void {

		// We handle uncaught exceptions here to prevent electron from opening a dialog to the user
A
Alex Dima 已提交
115
		errors.setUnexpectedErrorHandler(err => this.onUnexpectedError(err));
B
Benjamin Pasero 已提交
116
		process.on('uncaughtException', err => this.onUnexpectedError(err));
117
		process.on('unhandledRejection', (reason: any, promise: Promise<any>) => errors.onUnexpectedError(reason));
118

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

B
Benjamin Pasero 已提交
122 123
		// Dispose on shutdown
		this.lifecycleService.onWillShutdown(() => this.dispose());
124

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

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

140 141
		// Security related measures (https://electronjs.org/docs/tutorial/security)
		// DO NOT CHANGE without consulting the documentation
142
		app.on('web-contents-created', (event: any, contents) => {
143
			contents.on('will-attach-webview', (event: Electron.Event, webPreferences, params) => {
144

145 146 147 148 149 150 151 152 153
				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;
					}

154
					const srcUri = URI.parse(source).fsPath.toLowerCase();
155 156
					const rootUri = URI.file(this.environmentService.appRoot).fsPath.toLowerCase();

157
					return startsWith(srcUri, rootUri + sep);
158 159
				};

160
				// Ensure defaults
M
Matt Bierner 已提交
161 162 163 164
				delete webPreferences.preload;
				webPreferences.nodeIntegration = false;

				// Verify URLs being loaded
165
				if (isValidWebviewSource(params.src) && isValidWebviewSource(webPreferences.preloadURL)) {
M
Matt Bierner 已提交
166 167
					return;
				}
M
Matt Bierner 已提交
168

169 170
				delete webPreferences.preloadUrl;

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

M
Matt Bierner 已提交
174 175 176 177
				event.preventDefault();
			});

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

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

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

				shell.openExternal(url);
			});
M
Matt Bierner 已提交
188 189
		});

190
		let macOpenFileURIs: IURIToOpen[] = [];
191
		let runningTimeout: any = null;
192
		app.on('open-file', (event: Event, path: string) => {
J
Joao Moreno 已提交
193
			this.logService.trace('App#open-file: ', path);
194 195 196
			event.preventDefault();

			// Keep in array because more might come!
197
			macOpenFileURIs.push({ uri: URI.file(path) });
198 199 200 201 202 203 204 205 206 207 208 209 210

			// 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 已提交
211
						urisToOpen: macOpenFileURIs,
212 213
						preferNewWindow: true /* dropping on the dock or opening from finder prefers to open in a new window */
					});
214
					macOpenFileURIs = [];
215 216 217 218 219
					runningTimeout = null;
				}
			}, 100);
		});

220 221 222 223
		app.on('new-window-for-tab', () => {
			this.windowsMainService.openNewWindow(OpenContext.DESKTOP); //macOS native tab "+" button
		});

224
		ipc.on('vscode:exit', (event: Event, code: number) => {
J
Joao Moreno 已提交
225
			this.logService.trace('IPC#vscode:exit', code);
226 227 228 229 230

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

231 232
		ipc.on('vscode:fetchShellEnv', (event: Event) => {
			const webContents = event.sender;
233
			getShellEnvironment().then(shellEnv => {
J
Johannes Rieken 已提交
234 235 236
				if (!webContents.isDestroyed()) {
					webContents.send('vscode:acceptShellEnv', shellEnv);
				}
237
			}, err => {
J
Johannes Rieken 已提交
238 239 240
				if (!webContents.isDestroyed()) {
					webContents.send('vscode:acceptShellEnv', {});
				}
B
Benjamin Pasero 已提交
241 242

				this.logService.error('Error fetching shell env', err);
243 244
			});
		});
245

246
		ipc.on('vscode:broadcast', (event: Event, windowId: number, broadcast: { channel: string; payload: any; }) => {
247
			if (this.windowsMainService && broadcast.channel && !isUndefinedOrNull(broadcast.payload)) {
J
Joao Moreno 已提交
248
				this.logService.trace('IPC#vscode:broadcast', broadcast.channel, broadcast.payload);
249 250 251 252

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

253 254
				// Send to all windows (except sender window)
				this.windowsMainService.sendToAll('vscode:broadcast', broadcast, [windowId]);
255 256 257
			}
		});

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

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

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

B
Benjamin Pasero 已提交
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
	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);
		}
	}

291 292 293 294
	private onBroadcast(event: string, payload: any): void {

		// Theme changes
		if (event === 'vscode:changeColorTheme' && typeof payload === 'string') {
295
			storeBackgroundColor(this.stateService, JSON.parse(payload));
296
		}
297 298
	}

J
Johannes Rieken 已提交
299
	startup(): Promise<void> {
J
Joao Moreno 已提交
300 301 302
		this.logService.debug('Starting VS Code');
		this.logService.debug(`from: ${this.environmentService.appRoot}`);
		this.logService.debug('args:', this.environmentService.args);
303

304 305 306 307
		// 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.
308
		if (isWindows && product.win32AppUserModelId) {
309 310
			app.setAppUserModelId(product.win32AppUserModelId);
		}
311

312 313 314 315 316 317 318
		// 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 {
319
			if (isMacintosh && this.configurationService.getValue<boolean>('window.nativeTabs') === true && !systemPreferences.getUserDefault('NSUseImprovedLayoutPass', 'boolean')) {
320
				systemPreferences.setUserDefault('NSUseImprovedLayoutPass', 'boolean', true as any);
321 322 323 324 325
			}
		} catch (error) {
			this.logService.error(error);
		}

326 327
		// Create Electron IPC Server
		this.electronIpcServer = new ElectronIPCServer();
328

B
Benjamin Pasero 已提交
329
		const startupWithMachineId = (machineId: string) => {
330
			this.logService.trace(`Resolved machine identifier: ${machineId}`);
331

332
			// Spawn shared process
333
			this.sharedProcess = this.instantiationService.createInstance(SharedProcess, machineId, this.userEnv);
334
			this.sharedProcessClient = this.sharedProcess.whenReady().then(() => connect(this.environmentService.sharedIPCHandle, 'main'));
335

336
			// Services
337
			return this.initServices(machineId).then(appInstantiationService => {
338

339 340 341 342 343 344 345
				// Create driver
				if (this.environmentService.driverHandle) {
					serveDriver(this.electronIpcServer, this.environmentService.driverHandle, this.environmentService, appInstantiationService).then(server => {
						this.logService.info('Driver started at:', this.environmentService.driverHandle);
						this._register(server);
					});
				}
346

347 348
				// Setup Auth Handler
				const authHandler = appInstantiationService.createInstance(ProxyAuthHandler);
349
				this._register(authHandler);
350

351
				// Open Windows
B
Benjamin Pasero 已提交
352
				const windows = appInstantiationService.invokeFunction(accessor => this.openFirstWindow(accessor));
B
Benjamin Pasero 已提交
353

354 355
				// Post Open Windows Tasks
				appInstantiationService.invokeFunction(accessor => this.afterWindowOpen(accessor));
B
Benjamin Pasero 已提交
356 357 358

				// Tracing: Stop tracing after windows are ready if enabled
				if (this.environmentService.args.trace) {
359 360 361
					this.stopTracingEventually(windows);
				}
			});
B
Benjamin Pasero 已提交
362 363 364 365 366 367 368 369 370 371 372 373
		};

		// Resolve unique machine ID
		this.logService.trace('Resolving machine identifier...');
		const resolvedMachineId = this.resolveMachineId();
		if (typeof resolvedMachineId === 'string') {
			return startupWithMachineId(resolvedMachineId);
		} else {
			return resolvedMachineId.then(machineId => startupWithMachineId(machineId));
		}
	}

J
Johannes Rieken 已提交
374
	private resolveMachineId(): string | Promise<string> {
B
Benjamin Pasero 已提交
375 376 377 378 379 380 381 382 383
		const machineId = this.stateService.getItem<string>(CodeApplication.MACHINE_ID_KEY);
		if (machineId) {
			return machineId;
		}

		return getMachineId().then(machineId => {
			this.stateService.setItem(CodeApplication.MACHINE_ID_KEY, machineId);

			return machineId;
384 385 386 387 388 389 390
		});
	}

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

		let recordingStopped = false;
M
Matt Bierner 已提交
391
		const stopRecording = (timeout: boolean) => {
392 393 394 395 396 397
			if (recordingStopped) {
				return;
			}

			recordingStopped = true; // only once

398
			contentTracing.stopRecording(join(homedir(), `${product.applicationName}-${Math.random().toString(16).slice(-4)}.trace.txt`), path => {
399 400 401 402 403 404 405 406 407
				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 已提交
408
				}
409
			});
410 411 412 413 414 415
		};

		// 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 已提交
416
		Promise.all(windows.map(window => window.ready())).then(() => {
417 418
			clearTimeout(timeoutHandle);
			stopRecording(false);
419
		});
420 421
	}

J
Johannes Rieken 已提交
422
	private initServices(machineId: string): Promise<IInstantiationService> {
423 424
		const services = new ServiceCollection();

425 426 427
		if (process.platform === 'win32') {
			services.set(IUpdateService, new SyncDescriptor(Win32UpdateService));
		} else if (process.platform === 'linux') {
J
Joao Moreno 已提交
428
			if (process.env.SNAP && process.env.SNAP_REVISION) {
J
Joao Moreno 已提交
429
				services.set(IUpdateService, new SyncDescriptor(SnapUpdateService, [process.env.SNAP, process.env.SNAP_REVISION]));
J
Joao Moreno 已提交
430 431 432
			} else {
				services.set(IUpdateService, new SyncDescriptor(LinuxUpdateService));
			}
433 434 435 436
		} else if (process.platform === 'darwin') {
			services.set(IUpdateService, new SyncDescriptor(DarwinUpdateService));
		}

437 438
		services.set(IWindowsMainService, new SyncDescriptor(WindowsManager, [machineId]));
		services.set(IWindowsService, new SyncDescriptor(WindowsService, [this.sharedProcess]));
439
		services.set(ILaunchService, new SyncDescriptor(LaunchService));
440
		services.set(IIssueService, new SyncDescriptor(IssueService, [machineId, this.userEnv]));
441
		services.set(IMenubarService, new SyncDescriptor(MenubarService));
442
		services.set(IStorageMainService, new SyncDescriptor(StorageMainService));
443 444 445 446
		services.set(IBackupMainService, new SyncDescriptor(BackupMainService));
		services.set(IHistoryMainService, new SyncDescriptor(HistoryMainService));
		services.set(IURLService, new SyncDescriptor(URLService));
		services.set(IWorkspacesMainService, new SyncDescriptor(WorkspacesMainService));
447

448
		// Telemetry
449
		if (!this.environmentService.isExtensionDevelopment && !this.environmentService.args['disable-telemetry'] && !!product.enableTelemetry) {
J
Joao Moreno 已提交
450
			const channel = getDelayedChannel(this.sharedProcessClient.then(c => c.getChannel('telemetryAppender')));
451
			const appender = combinedAppender(new TelemetryAppenderClient(channel), new LogAppender(this.logService));
452
			const commonProperties = resolveCommonProperties(product.commit, pkg.version, machineId, this.environmentService.installSourcePath);
453 454
			const piiPaths = [this.environmentService.appRoot, this.environmentService.extensionsPath];
			const config: ITelemetryServiceConfig = { appender, commonProperties, piiPaths };
455

456
			services.set(ITelemetryService, new SyncDescriptor(TelemetryService, [config]));
457 458 459 460
		} else {
			services.set(ITelemetryService, NullTelemetryService);
		}

461 462
		const appInstantiationService = this.instantiationService.createChild(services);

463
		// Init services that require it
464 465 466 467
		return appInstantiationService.invokeFunction(accessor => Promise.all([
			this.initStorageService(accessor),
			this.initBackupService(accessor)
		])).then(() => appInstantiationService);
468 469
	}

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

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

476
		return Promise.resolve();
477

478 479
	}

480 481 482 483 484 485
	private initBackupService(accessor: ServicesAccessor): Promise<void> {
		const backupMainService = accessor.get(IBackupMainService) as BackupMainService;

		return backupMainService.initialize();
	}

B
Benjamin Pasero 已提交
486
	private openFirstWindow(accessor: ServicesAccessor): ICodeWindow[] {
487 488 489 490 491 492 493 494 495 496 497 498
		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);

499 500 501 502
		const issueService = accessor.get(IIssueService);
		const issueChannel = new IssueChannel(issueService);
		this.electronIpcServer.registerChannel('issue', issueChannel);

B
Benjamin Pasero 已提交
503 504 505 506
		const workspacesService = accessor.get(IWorkspacesMainService);
		const workspacesChannel = appInstantiationService.createInstance(WorkspacesChannel, workspacesService);
		this.electronIpcServer.registerChannel('workspaces', workspacesChannel);

507 508 509
		const windowsService = accessor.get(IWindowsService);
		const windowsChannel = new WindowsChannel(windowsService);
		this.electronIpcServer.registerChannel('windows', windowsChannel);
510
		this.sharedProcessClient.then(client => client.registerChannel('windows', windowsChannel));
511

512 513 514 515
		const menubarService = accessor.get(IMenubarService);
		const menubarChannel = new MenubarChannel(menubarService);
		this.electronIpcServer.registerChannel('menubar', menubarChannel);

J
Joao Moreno 已提交
516 517 518 519
		const urlService = accessor.get(IURLService);
		const urlChannel = new URLServiceChannel(urlService);
		this.electronIpcServer.registerChannel('url', urlChannel);

520
		const storageMainService = accessor.get(IStorageMainService);
521
		const storageChannel = this._register(new GlobalStorageDatabaseChannel(this.logService, storageMainService as StorageMainService));
B
wip  
Benjamin Pasero 已提交
522 523
		this.electronIpcServer.registerChannel('storage', storageChannel);

S
Sandeep Somavarapu 已提交
524
		// Log level management
525
		const logLevelChannel = new LogLevelSetterChannel(accessor.get(ILogService));
S
Sandeep Somavarapu 已提交
526
		this.electronIpcServer.registerChannel('loglevel', logLevelChannel);
527
		this.sharedProcessClient.then(client => client.registerChannel('loglevel', logLevelChannel));
S
Sandeep Somavarapu 已提交
528

529
		// Lifecycle
B
Benjamin Pasero 已提交
530
		(this.lifecycleService as LifecycleService).ready();
531 532

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

J
Joao Moreno 已提交
535
		// Create a URL handler which forwards to the last active window
J
Joao Moreno 已提交
536
		const activeWindowManager = new ActiveWindowManager(windowsService);
J
Joao Moreno 已提交
537 538
		const activeWindowRouter = new StaticRouter(ctx => activeWindowManager.getActiveClientId().then(id => ctx === id));
		const urlHandlerChannel = this.electronIpcServer.getChannel('urlHandler', activeWindowRouter);
J
Joao Moreno 已提交
539
		const multiplexURLHandler = new URLHandlerChannelClient(urlHandlerChannel);
J
Joao Moreno 已提交
540

541 542
		// On Mac, Code can be running without any open windows, so we must create a window to handle urls,
		// if there is none
543
		if (isMacintosh) {
544 545 546
			const environmentService = accessor.get(IEnvironmentService);

			urlService.registerHandler({
J
Johannes Rieken 已提交
547
				handleURL(uri: URI): Promise<boolean> {
548 549 550 551 552 553 554
					if (windowsMainService.getWindowCount() === 0) {
						const cli = { ...environmentService.args, goto: true };
						const [window] = windowsMainService.open({ context: OpenContext.API, cli, forceEmpty: true });

						return window.ready().then(() => urlService.open(uri));
					}

B
Benjamin Pasero 已提交
555
					return Promise.resolve(false);
556 557 558 559
				}
			});
		}

560
		// Register the multiple URL handler
J
Joao Moreno 已提交
561 562
		urlService.registerHandler(multiplexURLHandler);

J
Joao Moreno 已提交
563
		// Watch Electron URLs and forward them to the UrlService
564
		const args = this.environmentService.args;
J
Joao Moreno 已提交
565
		const urls = args['open-url'] ? args._urls : [];
566
		const urlListener = new ElectronURLListener(urls || [], urlService, this.windowsMainService);
567
		this._register(urlListener);
J
Joao Moreno 已提交
568

569 570 571
		this.windowsMainService.ready(this.userEnv);

		// Open our first window
572
		const macOpenFiles = (<any>global).macOpenFiles as string[];
573
		const context = !!process.env['VSCODE_CLI'] ? OpenContext.CLI : OpenContext.DESKTOP;
M
Martin Aeschlimann 已提交
574 575 576
		const hasCliArgs = hasArgs(args._);
		const hasFolderURIs = hasArgs(args['folder-uri']);
		const hasFileURIs = hasArgs(args['file-uri']);
577
		const noRecentEntry = args['skip-add-to-recently-opened'] === true;
M
Martin Aeschlimann 已提交
578
		const waitMarkerFileURI = args.wait && args.waitMarkerFilePath ? URI.file(args.waitMarkerFilePath) : undefined;
579

M
Martin Aeschlimann 已提交
580
		if (args['new-window'] && !hasCliArgs && !hasFolderURIs && !hasFileURIs) {
M
Martin Aeschlimann 已提交
581 582 583 584 585 586 587 588 589 590
			// new window if "-n" was used without paths
			return this.windowsMainService.open({
				context,
				cli: args,
				forceNewWindow: true,
				forceEmpty: true,
				noRecentEntry,
				waitMarkerFileURI,
				initialStartup: true
			});
591
		}
B
Benjamin Pasero 已提交
592 593

		if (macOpenFiles && macOpenFiles.length && !hasCliArgs && !hasFolderURIs && !hasFileURIs) {
M
Martin Aeschlimann 已提交
594 595 596 597 598 599 600 601 602
			// mac: open-file event received on startup
			return this.windowsMainService.open({
				context: OpenContext.DOCK,
				cli: args,
				urisToOpen: macOpenFiles.map(file => ({ uri: URI.file(file) })),
				noRecentEntry,
				waitMarkerFileURI,
				initialStartup: true
			});
B
Benjamin Pasero 已提交
603 604
		}

M
Martin Aeschlimann 已提交
605 606 607 608 609 610 611 612 613 614
		// 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
		});
615 616 617
	}

	private afterWindowOpen(accessor: ServicesAccessor): void {
618
		const windowsMainService = accessor.get(IWindowsMainService);
619
		const historyMainService = accessor.get(IHistoryMainService);
620

621
		if (isWindows) {
622 623

			// Setup Windows mutex
624 625
			try {
				const Mutex = (require.__$__nodeRequire('windows-mutex') as any).Mutex;
626
				const windowsMutex = new Mutex(product.win32MutexName);
627
				this._register(toDisposable(() => windowsMutex.release()));
628
			} catch (e) {
629
				if (!this.environmentService.isBuilt) {
630
					windowsMainService.showMessageBox({
631 632 633 634 635
						title: product.nameLong,
						type: 'warning',
						message: 'Failed to load windows-mutex!',
						detail: e.toString(),
						noLink: true
636 637
					});
				}
638
			}
639

640
			// Ensure Windows foreground love module
641
			try {
642
				// tslint:disable-next-line:no-unused-expression
643
				require.__$__nodeRequire('windows-foreground-love');
644 645
			} catch (e) {
				if (!this.environmentService.isBuilt) {
646
					windowsMainService.showMessageBox({
647 648 649 650 651
						title: product.nameLong,
						type: 'warning',
						message: 'Failed to load windows-foreground-love!',
						detail: e.toString(),
						noLink: true
652 653 654
					});
				}
			}
655
		}
656

657 658 659 660 661 662 663 664
		// Remote Authorities
		this.handleRemoteAuthorities();

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

665
		// Jump List
666 667
		historyMainService.updateWindowsJumpList();
		historyMainService.onRecentlyOpenedChange(() => historyMainService.updateWindowsJumpList());
668

B
Benjamin Pasero 已提交
669 670
		// Start shared process after a while
		const sharedProcessSpawn = this._register(new RunOnceScheduler(() => getShellEnvironment().then(userEnv => this.sharedProcess.spawn(userEnv)), 3000));
671
		sharedProcessSpawn.schedule();
672
	}
673 674 675 676

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

A
Alex Dima 已提交
677 678
		const isBuilt = this.environmentService.isBuilt;

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

			constructor(authority: string, host: string, port: number) {
				this._authority = authority;
A
Alex Dima 已提交
686
				this._connection = connectRemoteAgentManagement(authority, host, port, `main`, isBuilt);
687
				this._disposeRunner = new RunOnceScheduler(() => this.dispose(), 5000);
688 689
			}

690
			dispose(): void {
691 692
				this._disposeRunner.dispose();
				connectionPool.delete(this._authority);
A
Alex Dima 已提交
693
				this._connection.then((connection) => {
694 695 696 697
					connection.dispose();
				});
			}

A
Alex Dima 已提交
698
			async getClient(): Promise<Client<RemoteAgentConnectionContext>> {
699
				this._disposeRunner.schedule();
A
Alex Dima 已提交
700 701
				const connection = await this._connection;
				return connection.client;
702 703 704 705 706
			}
		}

		const resolvedAuthorities = new Map<string, ResolvedAuthority>();
		ipc.on('vscode:remoteAuthorityResolved', (event: any, data: ResolvedAuthority) => {
707
			this.logService.info('Received resolved authority', data.authority);
708
			resolvedAuthorities.set(data.authority, data);
709 710
			// Make sure to close and remove any existing connections
			if (connectionPool.has(data.authority)) {
A
Alex Dima 已提交
711
				connectionPool.get(data.authority)!.dispose();
712
			}
713 714 715
		});

		const resolveAuthority = (authority: string): ResolvedAuthority | null => {
716
			this.logService.info('Resolving authority', authority);
717 718
			if (authority.indexOf('+') >= 0) {
				if (resolvedAuthorities.has(authority)) {
M
Matt Bierner 已提交
719
					return withUndefinedAsNull(resolvedAuthorities.get(authority));
720
				}
721
				this.logService.info('Didnot find resolved authority for', authority);
722 723 724 725
				return null;
			} else {
				const [host, strPort] = authority.split(':');
				const port = parseInt(strPort, 10);
726
				return { authority, host, port };
727 728 729 730 731
			}
		};

		protocol.registerBufferProtocol(REMOTE_HOST_SCHEME, async (request, callback) => {
			if (request.method !== 'GET') {
732
				return callback(undefined);
733 734 735
			}
			const uri = URI.parse(request.url);

736
			let activeConnection: ActiveConnection | undefined;
737 738 739
			if (connectionPool.has(uri.authority)) {
				activeConnection = connectionPool.get(uri.authority);
			} else {
740
				const resolvedAuthority = resolveAuthority(uri.authority);
741
				if (!resolvedAuthority) {
742
					callback(undefined);
743 744 745 746 747 748
					return;
				}
				activeConnection = new ActiveConnection(uri.authority, resolvedAuthority.host, resolvedAuthority.port);
				connectionPool.set(uri.authority, activeConnection);
			}
			try {
749
				const rawClient = await activeConnection!.getClient();
750 751 752 753 754 755 756
				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`
					const fileContents = await channel.call<Uint8Array>('readFile', [uri]);
					callback(Buffer.from(fileContents));
				} else {
757
					callback(undefined);
758 759 760
				}
			} catch (err) {
				errors.onUnexpectedError(err);
761
				callback(undefined);
762 763 764
			}
		});
	}
765
}
766