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, IpcMainEvent, BrowserWindow } from 'electron';
7
import { IProcessEnvironment, isWindows, isMacintosh } from 'vs/base/common/platform';
8
import { WindowsMainService } from 'vs/platform/windows/electron-main/windowsMainService';
9
import { OpenContext, IWindowOpenable } from 'vs/platform/windows/common/windows';
10
import { ActiveWindowManager } from 'vs/code/node/activeWindowTracker';
11
import { ILifecycleMainService, LifecycleMainPhase } from 'vs/platform/lifecycle/electron-main/lifecycleMainService';
B
Benjamin Pasero 已提交
12
import { getShellEnvironment } from 'vs/code/node/shellEnv';
13
import { IUpdateService } from 'vs/platform/update/common/update';
14
import { UpdateChannel } from 'vs/platform/update/electron-main/updateIpc';
15
import { Server as ElectronIPCServer } from 'vs/base/parts/ipc/electron-main/ipc.electron-main';
A
Alex Dima 已提交
16 17
import { Client } from 'vs/base/parts/ipc/common/ipc.net';
import { Server, connect } from 'vs/base/parts/ipc/node/ipc.net';
18
import { SharedProcess } from 'vs/code/electron-main/sharedProcess';
19
import { LaunchMainService, ILaunchMainService } from 'vs/platform/launch/electron-main/launchMainService';
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';
24
import { IStateService } from 'vs/platform/state/node/state';
25 26
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
27
import { IURLService, IOpenURLOptions } from 'vs/platform/url/common/url';
28
import { URLHandlerChannelClient, URLHandlerRouter } from 'vs/platform/url/common/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';
B
Benjamin Pasero 已提交
34 35
import { getDelayedChannel, StaticRouter } from 'vs/base/parts/ipc/common/ipc';
import { createChannelReceiver } from 'vs/base/parts/ipc/node/ipc';
36
import product from 'vs/platform/product/common/product';
37
import { ProxyAuthHandler } from 'vs/code/electron-main/auth';
38
import { Disposable } from 'vs/base/common/lifecycle';
B
Benjamin Pasero 已提交
39
import { IWindowsMainService, ICodeWindow } from 'vs/platform/windows/electron-main/windows';
40
import { URI } from 'vs/base/common/uri';
41 42
import { hasWorkspaceFileExtension, IWorkspacesService } from 'vs/platform/workspaces/common/workspaces';
import { WorkspacesService } from 'vs/platform/workspaces/electron-main/workspacesService';
43
import { getMachineId } from 'vs/base/node/id';
44 45 46
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';
47
import { IIssueService } from 'vs/platform/issue/node/issue';
48
import { IssueMainService } from 'vs/platform/issue/electron-main/issueMainService';
49
import { LoggerChannel } from 'vs/platform/log/common/logIpc';
50
import { setUnexpectedErrorHandler, onUnexpectedError } from 'vs/base/common/errors';
J
Joao Moreno 已提交
51
import { ElectronURLListener } from 'vs/platform/url/electron-main/electronUrlListener';
J
Joao Moreno 已提交
52
import { serve as serveDriver } from 'vs/platform/driver/electron-main/driver';
53
import { IMenubarService } from 'vs/platform/menubar/node/menubar';
54
import { MenubarMainService } from 'vs/platform/menubar/electron-main/menubarMainService';
55
import { RunOnceScheduler } from 'vs/base/common/async';
56
import { registerContextMenuListener } from 'vs/base/parts/contextmenu/electron-main/contextmenu';
B
Benjamin Pasero 已提交
57
import { homedir } from 'os';
B
Benjamin Pasero 已提交
58
import { join, sep } from 'vs/base/common/path';
B
Benjamin Pasero 已提交
59
import { localize } from 'vs/nls';
B
Benjamin Pasero 已提交
60
import { Schemas } from 'vs/base/common/network';
J
Joao Moreno 已提交
61
import { SnapUpdateService } from 'vs/platform/update/electron-main/updateService.snap';
B
wip  
Benjamin Pasero 已提交
62 63
import { IStorageMainService, StorageMainService } from 'vs/platform/storage/node/storageMainService';
import { GlobalStorageDatabaseChannel } from 'vs/platform/storage/node/storageIpc';
64
import { startsWith } from 'vs/base/common/strings';
65
import { BackupMainService } from 'vs/platform/backup/electron-main/backupMainService';
66
import { IBackupMainService } from 'vs/platform/backup/electron-main/backup';
67
import { WorkspacesHistoryMainService, IWorkspacesHistoryMainService } from 'vs/platform/workspaces/electron-main/workspacesHistoryMainService';
68
import { URLService } from 'vs/platform/url/node/urlService';
B
Benjamin Pasero 已提交
69
import { WorkspacesMainService, IWorkspacesMainService } from 'vs/platform/workspaces/electron-main/workspacesMainService';
B
Benjamin Pasero 已提交
70
import { statSync } from 'fs';
71
import { DiagnosticsService } from 'vs/platform/diagnostics/node/diagnosticsIpc';
72
import { IDiagnosticsService } from 'vs/platform/diagnostics/node/diagnosticsService';
73 74 75
import { FileService } from 'vs/platform/files/common/fileService';
import { IFileService } from 'vs/platform/files/common/files';
import { DiskFileSystemProvider } from 'vs/platform/files/node/diskFileSystemProvider';
76
import { ExtensionHostDebugBroadcastChannel } from 'vs/platform/debug/common/extensionHostDebugIpc';
77
import { IElectronMainService, ElectronMainService } from 'vs/platform/electron/electron-main/electronMainService';
78
import { ISharedProcessMainService, SharedProcessMainService } from 'vs/platform/ipc/electron-main/sharedProcessMainService';
79
import { assign } from 'vs/base/common/objects';
80 81
import { IDialogMainService, DialogMainService } from 'vs/platform/dialogs/electron-main/dialogs';
import { withNullAsUndefined } from 'vs/base/common/types';
82
import { parseArgs, OPTIONS } from 'vs/platform/environment/node/argv';
83

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

86
	private static readonly MACHINE_ID_KEY = 'telemetry.machineId';
87
	private static readonly TRUE_MACHINE_ID_KEY = 'telemetry.trueMachineId';
B
Benjamin Pasero 已提交
88

89
	private windowsMainService: IWindowsMainService | undefined;
90
	private dialogMainService: IDialogMainService | undefined;
91 92

	constructor(
93 94
		private readonly mainIpcServer: Server,
		private readonly userEnv: IProcessEnvironment,
95 96 97
		@IInstantiationService private readonly instantiationService: IInstantiationService,
		@ILogService private readonly logService: ILogService,
		@IEnvironmentService private readonly environmentService: IEnvironmentService,
98
		@ILifecycleMainService private readonly lifecycleMainService: ILifecycleMainService,
S
Sandeep Somavarapu 已提交
99
		@IConfigurationService private readonly configurationService: IConfigurationService,
100
		@IStateService private readonly stateService: IStateService
101
	) {
102 103
		super();

104 105 106 107 108 109
		this.registerListeners();
	}

	private registerListeners(): void {

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

B
Benjamin Pasero 已提交
114
		// Dispose on shutdown
115
		this.lifecycleMainService.onWillShutdown(() => this.dispose());
116

117 118 119
		// Contextmenu via IPC support
		registerContextMenuListener();

120 121 122 123 124 125 126
		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 已提交
127
			this.logService.trace('App#activate');
128 129 130

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

135
		// Security related measures (https://electronjs.org/docs/tutorial/security)
136 137 138 139
		//
		// !!! 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>
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
		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 => {
B
Benjamin Pasero 已提交
163 164
			if (this.environmentService.args.driver) {
				return; // the driver needs access to web contents
D
Daniel Imms 已提交
165
			}
B
Benjamin Pasero 已提交
166 167 168 169

			this.logService.trace(`App#on(remote-get-current-web-contents): prevented`);

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

174
				const isValidWebviewSource = (source: string): boolean => {
175 176 177 178 179 180 181 182
					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;
					}

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

186
					return startsWith(srcUri, rootUri + sep);
187 188
				};

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

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

198
				delete webPreferences.preloadUrl;
199

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

M
Matt Bierner 已提交
203 204 205 206
				event.preventDefault();
			});

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

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

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

				shell.openExternal(url);
			});
M
Matt Bierner 已提交
217 218
		});

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

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

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

245
					macOpenFileURIs = [];
246 247 248 249 250
					runningTimeout = null;
				}
			}, 100);
		});

251
		app.on('new-window-for-tab', () => {
252
			if (this.windowsMainService) {
253
				this.windowsMainService.openEmptyWindow(OpenContext.DESKTOP); //macOS native tab "+" button
254
			}
255 256
		});

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

			this.dispose();
261
			this.lifecycleMainService.kill(code);
262 263
		});

264
		ipc.on('vscode:fetchShellEnv', async (event: IpcMainEvent) => {
265
			const webContents = event.sender;
266 267

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

277 278
				this.logService.error('Error fetching shell env', error);
			}
279
		});
280

281 282
		ipc.on('vscode:toggleDevTools', (event: IpcMainEvent) => event.sender.toggleDevTools());
		ipc.on('vscode:openDevTools', (event: IpcMainEvent) => event.sender.openDevTools());
B
Benjamin Pasero 已提交
283

284
		ipc.on('vscode:reloadWindow', (event: IpcMainEvent) => event.sender.reload());
285

B
Benjamin Pasero 已提交
286
		// Some listeners after window opened
287
		(async () => {
288
			await this.lifecycleMainService.when(LifecycleMainPhase.AfterWindowOpen);
289

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

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

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

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

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

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

356
		// Create Electron IPC Server
357
		const electronIpcServer = new ElectronIPCServer();
358

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

364 365 366
		// 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'));
367
		this.lifecycleMainService.when(LifecycleMainPhase.AfterWindowOpen).then(() => {
368
			this._register(new RunOnceScheduler(async () => {
369
				const userEnv = await getShellEnvironment(this.logService, this.environmentService);
370 371 372 373

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

375
		// Services
376
		const appInstantiationService = await this.createServices(machineId, trueMachineId, sharedProcess, sharedProcessClient);
377

378 379
		// Create driver
		if (this.environmentService.driverHandle) {
380
			const server = await serveDriver(electronIpcServer, this.environmentService.driverHandle, this.environmentService, appInstantiationService);
381

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

386
		// Setup Auth Handler
387
		this._register(new ProxyAuthHandler());
B
Benjamin Pasero 已提交
388

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

392
		// Post Open Windows Tasks
393
		this.afterWindowOpen();
B
Benjamin Pasero 已提交
394

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

401
	private async resolveMachineId(): Promise<{ machineId: string, trueMachineId?: string }> {
B
Benjamin Pasero 已提交
402

403 404 405 406 407
		// 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 已提交
408

409 410
			this.stateService.setItem(CodeApplication.MACHINE_ID_KEY, machineId);
		}
411

412 413 414 415 416 417 418 419 420 421 422 423
		// Check if machineId is hashed iBridge Device
		let trueMachineId: string | undefined;
		if (isMacintosh && machineId === '6c9d2bc8f91b89624add29c0abeae7fb42bf539fa1cdb2e3e57cd668fa9bcead') {
			trueMachineId = this.stateService.getItem<string>(CodeApplication.TRUE_MACHINE_ID_KEY);
			if (!trueMachineId) {
				trueMachineId = await getMachineId();

				this.stateService.setItem(CodeApplication.TRUE_MACHINE_ID_KEY, trueMachineId);
			}
		}

		return { machineId, trueMachineId };
424 425
	}

426
	private async createServices(machineId: string, trueMachineId: string | undefined, sharedProcess: SharedProcess, sharedProcessClient: Promise<Client<string>>): Promise<IInstantiationService> {
427
		const services = new ServiceCollection();
428

429 430 431 432 433 434
		const fileService = this._register(new FileService(this.logService));
		services.set(IFileService, fileService);

		const diskFileSystemProvider = this._register(new DiskFileSystemProvider(this.logService));
		fileService.registerProvider(Schemas.file, diskFileSystemProvider);

435 436 437 438
		switch (process.platform) {
			case 'win32':
				services.set(IUpdateService, new SyncDescriptor(Win32UpdateService));
				break;
439

440 441 442
			case 'linux':
				if (process.env.SNAP && process.env.SNAP_REVISION) {
					services.set(IUpdateService, new SyncDescriptor(SnapUpdateService, [process.env.SNAP, process.env.SNAP_REVISION]));
443
				} else {
444
					services.set(IUpdateService, new SyncDescriptor(LinuxUpdateService));
B
Benjamin Pasero 已提交
445
				}
446
				break;
447

448 449 450
			case 'darwin':
				services.set(IUpdateService, new SyncDescriptor(DarwinUpdateService));
				break;
451 452
		}

453
		services.set(IWindowsMainService, new SyncDescriptor(WindowsMainService, [machineId, this.userEnv]));
454
		services.set(IDialogMainService, new SyncDescriptor(DialogMainService));
455
		services.set(ISharedProcessMainService, new SyncDescriptor(SharedProcessMainService, [sharedProcess]));
456
		services.set(ILaunchMainService, new SyncDescriptor(LaunchMainService));
457 458 459 460

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

461
		services.set(IIssueService, new SyncDescriptor(IssueMainService, [machineId, this.userEnv]));
462
		services.set(IElectronMainService, new SyncDescriptor(ElectronMainService));
463
		services.set(IWorkspacesService, new SyncDescriptor(WorkspacesService));
464
		services.set(IMenubarService, new SyncDescriptor(MenubarMainService));
465 466 467

		const storageMainService = new StorageMainService(this.logService, this.environmentService);
		services.set(IStorageMainService, storageMainService);
468
		this.lifecycleMainService.onWillShutdown(e => e.join(storageMainService.close()));
469 470 471 472

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

473
		services.set(IWorkspacesHistoryMainService, new SyncDescriptor(WorkspacesHistoryMainService));
474 475
		services.set(IURLService, new SyncDescriptor(URLService));
		services.set(IWorkspacesMainService, new SyncDescriptor(WorkspacesMainService));
476

477
		// Telemetry
478
		if (!this.environmentService.isExtensionDevelopment && !this.environmentService.args['disable-telemetry'] && !!product.enableTelemetry) {
479
			const channel = getDelayedChannel(sharedProcessClient.then(client => client.getChannel('telemetryAppender')));
480
			const appender = combinedAppender(new TelemetryAppenderClient(channel), new LogAppender(this.logService));
481
			const commonProperties = resolveCommonProperties(product.commit, product.version, machineId, product.msftInternalDomains, this.environmentService.installSourcePath);
482
			const piiPaths = this.environmentService.extensionsPath ? [this.environmentService.appRoot, this.environmentService.extensionsPath] : [this.environmentService.appRoot];
483
			const config: ITelemetryServiceConfig = { appender, commonProperties, piiPaths, trueMachineId };
484

485
			services.set(ITelemetryService, new SyncDescriptor(TelemetryService, [config]));
486 487 488 489
		} else {
			services.set(ITelemetryService, NullTelemetryService);
		}

490
		// Init services that require it
491
		await backupMainService.initialize();
492

493
		return this.instantiationService.createChild(services);
494 495
	}

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

499
		let recordingStopped = false;
500
		const stopRecording = (timeout: boolean) => {
501 502 503
			if (recordingStopped) {
				return;
			}
B
wip  
Benjamin Pasero 已提交
504

505
			recordingStopped = true; // only once
506

507 508 509 510 511 512 513 514 515 516 517 518
			contentTracing.stopRecording(join(homedir(), `${product.applicationName}-${Math.random().toString(16).slice(-4)}.trace.txt`), path => {
				if (!timeout) {
					if (this.dialogMainService) {
						this.dialogMainService.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")]
						}, withNullAsUndefined(BrowserWindow.getFocusedWindow()));
					}
				} else {
					this.logService.info(`Tracing: data recorded (after 30s timeout) to ${path}`);
519
				}
520
			});
521
		};
522

523 524 525 526 527 528 529 530
		// 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);
		});
531 532
	}

533
	private openFirstWindow(accessor: ServicesAccessor, electronIpcServer: ElectronIPCServer, sharedProcessClient: Promise<Client<string>>): ICodeWindow[] {
534 535

		// Register more Main IPC services
536
		const launchMainService = accessor.get(ILaunchMainService);
537
		const launchChannel = createChannelReceiver(launchMainService, { disableMarshalling: true });
538 539 540 541 542
		this.mainIpcServer.registerChannel('launch', launchChannel);

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

545
		const issueService = accessor.get(IIssueService);
546
		const issueChannel = createChannelReceiver(issueService);
547
		electronIpcServer.registerChannel('issue', issueChannel);
548

549 550
		const electronMainService = accessor.get(IElectronMainService);
		const electronChannel = createChannelReceiver(electronMainService);
551
		electronIpcServer.registerChannel('electron', electronChannel);
552
		sharedProcessClient.then(client => client.registerChannel('electron', electronChannel));
553

554
		const sharedProcessMainService = accessor.get(ISharedProcessMainService);
555
		const sharedProcessChannel = createChannelReceiver(sharedProcessMainService);
556 557
		electronIpcServer.registerChannel('sharedProcess', sharedProcessChannel);

558 559
		const workspacesService = accessor.get(IWorkspacesService);
		const workspacesChannel = createChannelReceiver(workspacesService);
560
		electronIpcServer.registerChannel('workspaces', workspacesChannel);
B
Benjamin Pasero 已提交
561

562
		const menubarService = accessor.get(IMenubarService);
563
		const menubarChannel = createChannelReceiver(menubarService);
564
		electronIpcServer.registerChannel('menubar', menubarChannel);
565

J
Joao Moreno 已提交
566
		const urlService = accessor.get(IURLService);
567
		const urlChannel = createChannelReceiver(urlService);
568
		electronIpcServer.registerChannel('url', urlChannel);
J
Joao Moreno 已提交
569

570
		const storageMainService = accessor.get(IStorageMainService);
571
		const storageChannel = this._register(new GlobalStorageDatabaseChannel(this.logService, storageMainService));
572
		electronIpcServer.registerChannel('storage', storageChannel);
B
wip  
Benjamin Pasero 已提交
573

574 575 576
		const loggerChannel = new LoggerChannel(accessor.get(ILogService));
		electronIpcServer.registerChannel('logger', loggerChannel);
		sharedProcessClient.then(client => client.registerChannel('logger', loggerChannel));
S
Sandeep Somavarapu 已提交
577

578 579
		const windowsMainService = this.windowsMainService = accessor.get(IWindowsMainService);

580
		// ExtensionHost Debug broadcast service
581
		electronIpcServer.registerChannel(ExtensionHostDebugBroadcastChannel.ChannelName, new ElectronExtensionHostDebugBroadcastChannel(windowsMainService));
582

583
		// Signal phase: ready (services set)
584
		this.lifecycleMainService.phase = LifecycleMainPhase.Ready;
585 586

		// Propagate to clients
587
		this.dialogMainService = accessor.get(IDialogMainService);
J
Joao Moreno 已提交
588

589 590 591
		// Create a URL handler to open file URIs in the active window
		const environmentService = accessor.get(IEnvironmentService);
		urlService.registerHandler({
592
			async handleURL(uri: URI, options?: IOpenURLOptions): Promise<boolean> {
593 594 595 596

				// Catch file URLs
				if (uri.authority === Schemas.file && !!uri.path) {
					const cli = assign(Object.create(null), environmentService.args);
J
comment  
Joao Moreno 已提交
597 598

					// hey Ben, we need to convert this `code://file` URI into a `file://` URI
J
Joao Moreno 已提交
599
					const urisToOpen = [{ fileUri: URI.file(uri.fsPath) }];
600 601 602 603 604 605 606 607 608 609

					windowsMainService.open({ context: OpenContext.API, cli, urisToOpen, gotoLineMode: true });

					return true;
				}

				return false;
			}
		});

J
Joao Moreno 已提交
610
		// Create a URL handler which forwards to the last active window
611
		const activeWindowManager = new ActiveWindowManager(electronMainService);
J
Joao Moreno 已提交
612
		const activeWindowRouter = new StaticRouter(ctx => activeWindowManager.getActiveClientId().then(id => ctx === id));
613 614
		const urlHandlerRouter = new URLHandlerRouter(activeWindowRouter);
		const urlHandlerChannel = electronIpcServer.getChannel('urlHandler', urlHandlerRouter);
J
Joao Moreno 已提交
615
		const multiplexURLHandler = new URLHandlerChannelClient(urlHandlerChannel);
J
Joao Moreno 已提交
616

617 618
		// On Mac, Code can be running without any open windows, so we must create a window to handle urls,
		// if there is none
619
		if (isMacintosh) {
620
			urlService.registerHandler({
621
				async handleURL(uri: URI, options?: IOpenURLOptions): Promise<boolean> {
622
					if (windowsMainService.getWindowCount() === 0) {
623 624
						const cli = { ...environmentService.args };
						const [window] = windowsMainService.open({ context: OpenContext.API, cli, forceEmpty: true, gotoLineMode: true });
625

626 627 628
						await window.ready();

						return urlService.open(uri);
629 630
					}

631
					return false;
632 633 634 635
				}
			});
		}

636
		// Register the multiple URL handler
J
Joao Moreno 已提交
637 638
		urlService.registerHandler(multiplexURLHandler);

J
Joao Moreno 已提交
639
		// Watch Electron URLs and forward them to the UrlService
640
		const args = this.environmentService.args;
J
Joao Moreno 已提交
641
		const urls = args['open-url'] ? args._urls : [];
R
rzj17 已提交
642
		const urlListener = new ElectronURLListener(urls || [], urlService, windowsMainService, this.environmentService);
643
		this._register(urlListener);
J
Joao Moreno 已提交
644

645
		// Open our first window
646
		const macOpenFiles: string[] = (<any>global).macOpenFiles;
647
		const context = !!process.env['VSCODE_CLI'] ? OpenContext.CLI : OpenContext.DESKTOP;
648 649 650
		const hasCliArgs = args._.length;
		const hasFolderURIs = !!args['folder-uri'];
		const hasFileURIs = !!args['file-uri'];
651
		const noRecentEntry = args['skip-add-to-recently-opened'] === true;
M
Martin Aeschlimann 已提交
652
		const waitMarkerFileURI = args.wait && args.waitMarkerFilePath ? URI.file(args.waitMarkerFilePath) : undefined;
653

654
		// new window if "-n" was used without paths
M
Martin Aeschlimann 已提交
655
		if (args['new-window'] && !hasCliArgs && !hasFolderURIs && !hasFileURIs) {
656
			return windowsMainService.open({
M
Martin Aeschlimann 已提交
657 658 659 660 661 662 663 664
				context,
				cli: args,
				forceNewWindow: true,
				forceEmpty: true,
				noRecentEntry,
				waitMarkerFileURI,
				initialStartup: true
			});
665
		}
B
Benjamin Pasero 已提交
666

667
		// mac: open-file event received on startup
B
Benjamin Pasero 已提交
668
		if (macOpenFiles.length && !hasCliArgs && !hasFolderURIs && !hasFileURIs) {
669
			return windowsMainService.open({
M
Martin Aeschlimann 已提交
670 671
				context: OpenContext.DOCK,
				cli: args,
672
				urisToOpen: macOpenFiles.map(file => this.getWindowOpenableFromPathSync(file)),
M
Martin Aeschlimann 已提交
673 674
				noRecentEntry,
				waitMarkerFileURI,
675
				gotoLineMode: false,
M
Martin Aeschlimann 已提交
676 677
				initialStartup: true
			});
B
Benjamin Pasero 已提交
678 679
		}

M
Martin Aeschlimann 已提交
680
		// default: read paths from cli
681
		return windowsMainService.open({
M
Martin Aeschlimann 已提交
682 683 684 685 686 687
			context,
			cli: args,
			forceNewWindow: args['new-window'] || (!hasCliArgs && args['unity-launch']),
			diffMode: args.diff,
			noRecentEntry,
			waitMarkerFileURI,
688
			gotoLineMode: args.goto,
M
Martin Aeschlimann 已提交
689 690
			initialStartup: true
		});
691 692
	}

693
	private getWindowOpenableFromPathSync(path: string): IWindowOpenable {
694 695 696 697
		try {
			const fileStat = statSync(path);
			if (fileStat.isDirectory()) {
				return { folderUri: URI.file(path) };
698
			}
699

700 701
			if (hasWorkspaceFileExtension(path)) {
				return { workspaceUri: URI.file(path) };
702
			}
703 704
		} catch (error) {
			// ignore errors
705
		}
706

707 708
		return { fileUri: URI.file(path) };
	}
709

710
	private afterWindowOpen(): void {
711

712
		// Signal phase: after window open
713
		this.lifecycleMainService.phase = LifecycleMainPhase.AfterWindowOpen;
714

715 716
		// Remote Authorities
		this.handleRemoteAuthorities();
717
	}
718 719

	private handleRemoteAuthorities(): void {
720
		protocol.registerHttpProtocol(Schemas.vscodeRemoteResource, (request, callback) => {
721
			callback({
722
				url: request.url.replace(/^vscode-remote-resource:/, 'http:'),
723 724
				method: request.method
			});
725 726
		});
	}
727
}
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752

class ElectronExtensionHostDebugBroadcastChannel<TContext> extends ExtensionHostDebugBroadcastChannel<TContext> {

	constructor(private windowsMainService: IWindowsMainService) {
		super();
	}

	call(ctx: TContext, command: string, arg?: any): Promise<any> {
		if (command === 'openExtensionDevelopmentHostWindow') {
			const env = arg[1];
			const pargs = parseArgs(arg[0], OPTIONS);
			const extDevPaths = pargs.extensionDevelopmentPath;
			if (extDevPaths) {
				this.windowsMainService.openExtensionDevelopmentHostWindow(extDevPaths, {
					context: OpenContext.API,
					cli: pargs,
					userEnv: Object.keys(env).length > 0 ? env : undefined
				});
			}
			return Promise.resolve();
		} else {
			return super.call(ctx, command, arg);
		}
	}
}