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

'use strict';

8
import { app, ipcMain as ipc, BrowserWindow, dialog } from 'electron';
9
import * as platform from 'vs/base/common/platform';
10
import { WindowsManager } from 'vs/code/electron-main/windows';
11
import { IWindowsService, OpenContext } from 'vs/platform/windows/common/windows';
12 13
import { WindowsChannel } from 'vs/platform/windows/common/windowsIpc';
import { WindowsService } from 'vs/platform/windows/electron-main/windowsService';
14
import { ILifecycleService } from 'vs/platform/lifecycle/electron-main/lifecycleMain';
B
Benjamin Pasero 已提交
15
import { CodeMenu } from 'vs/code/electron-main/menus';
B
Benjamin Pasero 已提交
16
import { getShellEnvironment } from 'vs/code/node/shellEnv';
17 18 19 20 21 22 23 24 25 26 27
import { IUpdateService } from 'vs/platform/update/common/update';
import { UpdateChannel } from 'vs/platform/update/common/updateIpc';
import { UpdateService } from 'vs/platform/update/electron-main/updateService';
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';
import { Mutex } from 'windows-mutex';
import { LaunchService, LaunchChannel, ILaunchService } from './launch';
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';
28
import { ILogService } from 'vs/platform/log/common/log';
29
import { IStorageMainService } from 'vs/platform/storage2/common/storage';
30 31 32 33 34 35 36 37 38 39 40 41
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IURLService } from 'vs/platform/url/common/url';
import { URLChannel } from 'vs/platform/url/common/urlIpc';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { NullTelemetryService } from 'vs/platform/telemetry/common/telemetryUtils';
import { ITelemetryAppenderChannel, TelemetryAppenderClient } from 'vs/platform/telemetry/common/telemetryIpc';
import { TelemetryService, ITelemetryServiceConfig } from 'vs/platform/telemetry/common/telemetryService';
import { resolveCommonProperties, machineIdStorageKey, machineIdIpcChannel } from 'vs/platform/telemetry/node/commonProperties';
import { getDelayedChannel } from 'vs/base/parts/ipc/common/ipc';
import product from 'vs/platform/node/product';
import pkg from 'vs/platform/node/package';
J
Joao Moreno 已提交
42
import { ProxyAuthHandler } from './auth';
B
Benjamin Pasero 已提交
43 44
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
import { ConfigurationService } from 'vs/platform/configuration/node/configurationService';
45 46
import { TPromise } from 'vs/base/common/winjs.base';
import { IWindowsMainService } from 'vs/platform/windows/electron-main/windows';
B
Benjamin Pasero 已提交
47
import { IHistoryMainService } from 'vs/platform/history/common/history';
B
Benjamin Pasero 已提交
48
import { isUndefinedOrNull } from 'vs/base/common/types';
49 50
import { CodeWindow } from 'vs/code/electron-main/window';
import { KeyboardLayoutMonitor } from 'vs/code/electron-main/keyboard';
M
Matt Bierner 已提交
51
import URI from 'vs/base/common/uri';
B
Benjamin Pasero 已提交
52 53
import { WorkspacesChannel } from 'vs/platform/workspaces/common/workspacesIpc';
import { IWorkspacesMainService } from 'vs/platform/workspaces/common/workspaces';
B
Benjamin Pasero 已提交
54 55
import { dirname, join } from 'path';
import { touch } from 'vs/base/node/pfs';
56

B
Benjamin Pasero 已提交
57
export class CodeApplication {
B
Benjamin Pasero 已提交
58

59
	private static readonly APP_ICON_REFRESH_KEY = 'macOSAppIconRefresh3';
B
Benjamin Pasero 已提交
60

61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
	private toDispose: IDisposable[];
	private windowsMainService: IWindowsMainService;

	private electronIpcServer: ElectronIPCServer;

	private sharedProcess: SharedProcess;
	private sharedProcessClient: TPromise<Client>;

	constructor(
		private mainIpcServer: Server,
		private userEnv: platform.IProcessEnvironment,
		@IInstantiationService private instantiationService: IInstantiationService,
		@ILogService private logService: ILogService,
		@IEnvironmentService private environmentService: IEnvironmentService,
		@ILifecycleService private lifecycleService: ILifecycleService,
B
Benjamin Pasero 已提交
76
		@IConfigurationService configurationService: ConfigurationService,
B
Benjamin Pasero 已提交
77 78
		@IStorageMainService private storageMainService: IStorageMainService,
		@IHistoryMainService private historyMainService: IHistoryMainService
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
	) {
		this.toDispose = [mainIpcServer, configurationService];

		this.registerListeners();
	}

	private registerListeners(): void {

		// We handle uncaught exceptions here to prevent electron from opening a dialog to the user
		process.on('uncaughtException', (err: any) => {
			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));
				}
			}

B
Benjamin Pasero 已提交
103
			this.logService.error(`[uncaught exception in main]: ${err}`);
104
			if (err.stack) {
B
Benjamin Pasero 已提交
105
				this.logService.error(err.stack);
106 107 108
			}
		});

109 110 111 112 113 114
		app.on('will-quit', () => {
			this.logService.log('App#will-quit: disposing resources');

			this.dispose();
		});

115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
		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) => {
			this.logService.log('App#activate');

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

M
Matt Bierner 已提交
130
		const isValidWebviewSource = (source: string) =>
131
			!source || (URI.parse(source.toLowerCase()).toString() as any).startsWith(URI.file(this.environmentService.appRoot.toLowerCase()).toString());
M
Matt Bierner 已提交
132

M
Matt Bierner 已提交
133
		app.on('web-contents-created', (_event: any, contents) => {
134
			contents.on('will-attach-webview', (event: Electron.Event, webPreferences, params) => {
M
Matt Bierner 已提交
135 136 137 138 139 140 141
				delete webPreferences.preload;
				webPreferences.nodeIntegration = false;

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

M
Matt Bierner 已提交
143
				// Otherwise prevent loading
B
Benjamin Pasero 已提交
144
				this.logService.error('webContents#web-contents-created: Prevented webview attach');
M
Matt Bierner 已提交
145 146 147 148
				event.preventDefault();
			});

			contents.on('will-navigate', event => {
B
Benjamin Pasero 已提交
149
				this.logService.error('webContents#will-navigate: Prevented webcontent navigation');
M
Matt Bierner 已提交
150 151 152 153
				event.preventDefault();
			});
		});

154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
		let macOpenFiles: string[] = [];
		let runningTimeout: number = null;
		app.on('open-file', (event: Event, path: string) => {
			this.logService.log('App#open-file: ', path);
			event.preventDefault();

			// Keep in array because more might come!
			macOpenFiles.push(path);

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

			// Handle paths delayed in case more are coming!
			runningTimeout = setTimeout(() => {
				if (this.windowsMainService) {
					this.windowsMainService.open({
						context: OpenContext.DOCK /* can also be opening from finder while app is running */,
						cli: this.environmentService.args,
						pathsToOpen: macOpenFiles,
						preferNewWindow: true /* dropping on the dock or opening from finder prefers to open in a new window */
					});
					macOpenFiles = [];
					runningTimeout = null;
				}
			}, 100);
		});

184 185 186 187
		app.on('new-window-for-tab', () => {
			this.windowsMainService.openNewWindow(OpenContext.DESKTOP); //macOS native tab "+" button
		});

M
Matt Bierner 已提交
188
		ipc.on('vscode:exit', (_event: any, code: number) => {
189 190 191 192 193 194
			this.logService.log('IPC#vscode:exit', code);

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

M
Matt Bierner 已提交
195
		ipc.on(machineIdIpcChannel, (_event: any, machineId: string) => {
196
			this.logService.log('IPC#vscode-machineId');
B
Benjamin Pasero 已提交
197
			this.storageMainService.setItem(machineIdStorageKey, machineId);
198 199
		});

M
Matt Bierner 已提交
200
		ipc.on('vscode:fetchShellEnv', (_event: any, windowId: number) => {
J
Johannes Rieken 已提交
201
			const { webContents } = BrowserWindow.fromId(windowId);
202
			getShellEnvironment().then(shellEnv => {
J
Johannes Rieken 已提交
203 204 205
				if (!webContents.isDestroyed()) {
					webContents.send('vscode:acceptShellEnv', shellEnv);
				}
206
			}, err => {
J
Johannes Rieken 已提交
207 208 209
				if (!webContents.isDestroyed()) {
					webContents.send('vscode:acceptShellEnv', {});
				}
B
Benjamin Pasero 已提交
210 211

				this.logService.error('Error fetching shell env', err);
212 213
			});
		});
214

M
Matt Bierner 已提交
215
		ipc.on('vscode:broadcast', (_event: any, windowId: number, broadcast: { channel: string; payload: any; }) => {
216
			if (this.windowsMainService && broadcast.channel && !isUndefinedOrNull(broadcast.payload)) {
217
				this.logService.log('IPC#vscode:broadcast', broadcast.channel, broadcast.payload);
218 219 220 221

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

222 223
				// Send to all windows (except sender window)
				this.windowsMainService.sendToAll('vscode:broadcast', broadcast, [windowId]);
224 225 226 227
			}
		});

		// Keyboard layout changes
228
		KeyboardLayoutMonitor.INSTANCE.onDidChangeKeyboardLayout(() => {
229
			if (this.windowsMainService) {
230
				this.windowsMainService.sendToAll('vscode:keyboardLayoutChanged', false);
231 232 233 234 235 236 237 238 239 240
			}
		});
	}

	private onBroadcast(event: string, payload: any): void {

		// Theme changes
		if (event === 'vscode:changeColorTheme' && typeof payload === 'string') {
			let data = JSON.parse(payload);

B
Benjamin Pasero 已提交
241 242
			this.storageMainService.setItem(CodeWindow.themeStorageKey, data.id);
			this.storageMainService.setItem(CodeWindow.themeBackgroundStorageKey, data.background);
243
		}
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
	}

	public startup(): void {
		this.logService.log('Starting VS Code in verbose mode');
		this.logService.log(`from: ${this.environmentService.appRoot}`);
		this.logService.log('args:', this.environmentService.args);

		// 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.
		if (platform.isWindows && product.win32AppUserModelId) {
			app.setAppUserModelId(product.win32AppUserModelId);
		}

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

		// Spawn shared process
		this.sharedProcess = new SharedProcess(this.environmentService, this.userEnv);
		this.toDispose.push(this.sharedProcess);
B
Benjamin Pasero 已提交
265
		this.sharedProcessClient = this.sharedProcess.whenReady().then(() => connect(this.environmentService.sharedIPCHandle, 'main'));
266 267 268 269

		// Services
		const appInstantiationService = this.initServices();

270
		// Setup Auth Handler
J
Joao Moreno 已提交
271
		const authHandler = appInstantiationService.createInstance(ProxyAuthHandler);
272 273
		this.toDispose.push(authHandler);

274 275 276 277 278
		// Open Windows
		appInstantiationService.invokeFunction(accessor => this.openFirstWindow(accessor));

		// Post Open Windows Tasks
		appInstantiationService.invokeFunction(accessor => this.afterWindowOpen(accessor));
279 280 281 282 283 284 285 286 287 288 289
	}

	private initServices(): IInstantiationService {
		const services = new ServiceCollection();

		services.set(IUpdateService, new SyncDescriptor(UpdateService));
		services.set(IWindowsMainService, new SyncDescriptor(WindowsManager));
		services.set(IWindowsService, new SyncDescriptor(WindowsService, this.sharedProcess));
		services.set(ILaunchService, new SyncDescriptor(LaunchService));

		// Telemtry
290
		if (this.environmentService.isBuilt && !this.environmentService.isExtensionDevelopment && !this.environmentService.args['disable-telemetry'] && !!product.enableTelemetry) {
291 292
			const channel = getDelayedChannel<ITelemetryAppenderChannel>(this.sharedProcessClient.then(c => c.getChannel('telemetryAppender')));
			const appender = new TelemetryAppenderClient(channel);
293
			const commonProperties = resolveCommonProperties(product.commit, pkg.version, this.environmentService.installSource)
K
kieferrm 已提交
294
				// __GDPR__COMMON__ "common.machineId" : { "classification": "EndUserPseudonymizedInformation", "purpose": "FeatureInsight" }
295
				.then(result => Object.defineProperty(result, 'common.machineId', {
B
Benjamin Pasero 已提交
296
					get: () => this.storageMainService.getItem(machineIdStorageKey),
297 298 299 300 301 302 303 304 305 306 307 308
					enumerable: true
				}));
			const piiPaths = [this.environmentService.appRoot, this.environmentService.extensionsPath];
			const config: ITelemetryServiceConfig = { appender, commonProperties, piiPaths };
			services.set(ITelemetryService, new SyncDescriptor(TelemetryService, config));
		} else {
			services.set(ITelemetryService, NullTelemetryService);
		}

		return this.instantiationService.createChild(services);
	}

309
	private openFirstWindow(accessor: ServicesAccessor): void {
310 311 312 313 314 315
		const appInstantiationService = accessor.get(IInstantiationService);

		// TODO@Joao: unfold this
		this.windowsMainService = accessor.get(IWindowsMainService);

		// TODO@Joao: so ugly...
B
Benjamin Pasero 已提交
316 317
		this.windowsMainService.onWindowsCountChanged(e => {
			if (!platform.isMacintosh && e.newCount === 0) {
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
				this.sharedProcess.dispose();
			}
		});

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

		const urlService = accessor.get(IURLService);
		const urlChannel = appInstantiationService.createInstance(URLChannel, urlService);
		this.electronIpcServer.registerChannel('url', urlChannel);

B
Benjamin Pasero 已提交
336 337 338 339
		const workspacesService = accessor.get(IWorkspacesMainService);
		const workspacesChannel = appInstantiationService.createInstance(WorkspacesChannel, workspacesService);
		this.electronIpcServer.registerChannel('workspaces', workspacesChannel);

340 341 342 343 344
		const windowsService = accessor.get(IWindowsService);
		const windowsChannel = new WindowsChannel(windowsService);
		this.electronIpcServer.registerChannel('windows', windowsChannel);
		this.sharedProcessClient.done(client => client.registerChannel('windows', windowsChannel));

C
Christof Marti 已提交
345

346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
		// Lifecycle
		this.lifecycleService.ready();

		// Propagate to clients
		this.windowsMainService.ready(this.userEnv);

		// Open our first window
		const args = this.environmentService.args;
		const context = !!process.env['VSCODE_CLI'] ? OpenContext.CLI : OpenContext.DESKTOP;
		if (args['new-window'] && args._.length === 0) {
			this.windowsMainService.open({ context, cli: args, forceNewWindow: true, forceEmpty: true, initialStartup: true }); // new window if "-n" was used without paths
		} else if (global.macOpenFiles && global.macOpenFiles.length && (!args._ || !args._.length)) {
			this.windowsMainService.open({ context: OpenContext.DOCK, cli: args, pathsToOpen: global.macOpenFiles, initialStartup: true }); // mac: open-file event received on startup
		} else {
			this.windowsMainService.open({ context, cli: args, forceNewWindow: args['new-window'] || (!args._.length && args['unity-launch']), diffMode: args.diff, initialStartup: true }); // default: read paths from cli
		}
362 363 364 365 366 367 368
	}

	private afterWindowOpen(accessor: ServicesAccessor): void {
		const appInstantiationService = accessor.get(IInstantiationService);

		let windowsMutex: Mutex = null;
		if (platform.isWindows) {
369 370

			// Setup Windows mutex
371 372 373 374 375
			try {
				const Mutex = (require.__$__nodeRequire('windows-mutex') as any).Mutex;
				windowsMutex = new Mutex(product.win32MutexName);
				this.toDispose.push({ dispose: () => windowsMutex.release() });
			} catch (e) {
376 377
				if (!this.environmentService.isBuilt) {
					dialog.showMessageBox({
378 379 380 381 382
						title: product.nameLong,
						type: 'warning',
						message: 'Failed to load windows-mutex!',
						detail: e.toString(),
						noLink: true
383 384
					});
				}
385
			}
386

387
			// Ensure Windows foreground love module
388
			try {
389
				// tslint:disable-next-line:no-unused-expression
390 391 392 393
				<any>require.__$__nodeRequire('windows-foreground-love');
			} catch (e) {
				if (!this.environmentService.isBuilt) {
					dialog.showMessageBox({
394 395 396 397 398
						title: product.nameLong,
						type: 'warning',
						message: 'Failed to load windows-foreground-love!',
						detail: e.toString(),
						noLink: true
399 400 401
					});
				}
			}
402
		}
403 404

		// Install Menu
B
Benjamin Pasero 已提交
405
		appInstantiationService.createInstance(CodeMenu);
406 407

		// Jump List
B
Benjamin Pasero 已提交
408 409
		this.historyMainService.updateWindowsJumpList();
		this.historyMainService.onRecentlyOpenedChange(() => this.historyMainService.updateWindowsJumpList());
410 411 412

		// Start shared process here
		this.sharedProcess.spawn();
B
Benjamin Pasero 已提交
413 414 415 416

		// Helps application icon refresh after an update with new icon is installed (macOS)
		// TODO@Ben remove after a couple of releases
		if (platform.isMacintosh) {
B
Benjamin Pasero 已提交
417 418
			if (!this.storageMainService.getItem(CodeApplication.APP_ICON_REFRESH_KEY)) {
				this.storageMainService.setItem(CodeApplication.APP_ICON_REFRESH_KEY, true);
B
Benjamin Pasero 已提交
419 420 421 422 423 424 425 426

				// 'exe' => /Applications/Visual Studio Code - Insiders.app/Contents/MacOS/Electron
				const appPath = dirname(dirname(dirname(app.getPath('exe'))));
				const infoPlistPath = join(appPath, 'Contents', 'Info.plist');
				touch(appPath).done(null, error => { /* ignore */ });
				touch(infoPlistPath).done(null, error => { /* ignore */ });
			}
		}
427 428 429 430 431
	}

	private dispose(): void {
		this.toDispose = dispose(this.toDispose);
	}
J
Johannes Rieken 已提交
432
}