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

'use strict';

import { app, ipcMain as ipc, BrowserWindow } from 'electron';
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 29
import { ILogService } from 'vs/platform/log/common/log';
import { IStorageService } from 'vs/platform/storage/node/storage';
30 31 32 33 34 35 36 37
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';
C
Christof Marti 已提交
38 39 40
import { ICredentialsService } from 'vs/platform/credentials/common/credentials';
import { CredentialsService } from 'vs/platform/credentials/node/credentialsService';
import { CredentialsChannel } from 'vs/platform/credentials/node/credentialsIpc';
41 42 43 44
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 已提交
45
import { ProxyAuthHandler } from './auth';
B
Benjamin Pasero 已提交
46 47
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
import { ConfigurationService } from 'vs/platform/configuration/node/configurationService';
48 49
import { TPromise } from 'vs/base/common/winjs.base';
import { IWindowsMainService } from 'vs/platform/windows/electron-main/windows';
B
Benjamin Pasero 已提交
50
import { IHistoryMainService } from 'vs/platform/history/common/history';
B
Benjamin Pasero 已提交
51
import { isUndefinedOrNull } from 'vs/base/common/types';
52 53
import { CodeWindow } from 'vs/code/electron-main/window';
import { KeyboardLayoutMonitor } from 'vs/code/electron-main/keyboard';
M
Matt Bierner 已提交
54
import URI from 'vs/base/common/uri';
B
Benjamin Pasero 已提交
55 56
import { WorkspacesChannel } from 'vs/platform/workspaces/common/workspacesIpc';
import { IWorkspacesMainService } from 'vs/platform/workspaces/common/workspaces';
B
Benjamin Pasero 已提交
57 58
import { dirname, join } from 'path';
import { touch } from 'vs/base/node/pfs';
59

B
Benjamin Pasero 已提交
60
export class CodeApplication {
B
Benjamin Pasero 已提交
61 62 63

	private static APP_ICON_REFRESH_KEY = 'macOSAppIconRefresh';

64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
	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,
		@IConfigurationService private configurationService: ConfigurationService<any>,
80 81
		@IStorageService private storageService: IStorageService,
		@IHistoryMainService private historyService: IHistoryMainService
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
	) {
		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 已提交
106
			this.logService.error(`[uncaught exception in main]: ${err}`);
107
			if (err.stack) {
B
Benjamin Pasero 已提交
108
				this.logService.error(err.stack);
109 110 111
			}
		});

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

			this.dispose();
		});

118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
		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 已提交
133
		const isValidWebviewSource = (source: string) =>
134
			!source || (URI.parse(source.toLowerCase()).toString() as any).startsWith(URI.file(this.environmentService.appRoot.toLowerCase()).toString());
M
Matt Bierner 已提交
135 136

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

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

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

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

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 184 185 186
		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);
		});

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

191 192 193 194 195 196 197
		ipc.on('vscode:exit', (event, code: number) => {
			this.logService.log('IPC#vscode:exit', code);

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

198 199 200 201 202 203
		ipc.on(machineIdIpcChannel, (event, machineId: string) => {
			this.logService.log('IPC#vscode-machineId');
			this.storageService.setItem(machineIdStorageKey, machineId);
		});

		ipc.on('vscode:fetchShellEnv', (event, windowId) => {
J
Johannes Rieken 已提交
204
			const { webContents } = BrowserWindow.fromId(windowId);
205
			getShellEnvironment().then(shellEnv => {
J
Johannes Rieken 已提交
206 207 208
				if (!webContents.isDestroyed()) {
					webContents.send('vscode:acceptShellEnv', shellEnv);
				}
209
			}, err => {
J
Johannes Rieken 已提交
210 211 212
				if (!webContents.isDestroyed()) {
					webContents.send('vscode:acceptShellEnv', {});
				}
B
Benjamin Pasero 已提交
213 214

				this.logService.error('Error fetching shell env', err);
215 216
			});
		});
217

218
		ipc.on('vscode:broadcast', (event, windowId: number, broadcast: { channel: string; payload: any; }) => {
219
			if (this.windowsMainService && broadcast.channel && !isUndefinedOrNull(broadcast.payload)) {
220
				this.logService.log('IPC#vscode:broadcast', broadcast.channel, broadcast.payload);
221 222 223 224

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

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

		// Keyboard layout changes
231
		KeyboardLayoutMonitor.INSTANCE.onDidChangeKeyboardLayout(() => {
232
			if (this.windowsMainService) {
233
				this.windowsMainService.sendToAll('vscode:keyboardLayoutChanged', false);
234 235 236 237 238 239 240 241 242 243 244 245 246
			}
		});
	}

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

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

			this.storageService.setItem(CodeWindow.themeStorageKey, data.id);
			this.storageService.setItem(CodeWindow.themeBackgroundStorageKey, data.background);
		}
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
	}

	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 已提交
268
		this.sharedProcessClient = this.sharedProcess.whenReady().then(() => connect(this.environmentService.sharedIPCHandle, 'main'));
269 270 271 272

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

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

277 278 279 280 281
		// Open Windows
		appInstantiationService.invokeFunction(accessor => this.openFirstWindow(accessor));

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

	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));
C
Christof Marti 已提交
291
		services.set(ICredentialsService, new SyncDescriptor(CredentialsService));
292 293 294 295 296

		// Telemtry
		if (this.environmentService.isBuilt && !this.environmentService.isExtensionDevelopment && !!product.enableTelemetry) {
			const channel = getDelayedChannel<ITelemetryAppenderChannel>(this.sharedProcessClient.then(c => c.getChannel('telemetryAppender')));
			const appender = new TelemetryAppenderClient(channel);
297
			const commonProperties = resolveCommonProperties(product.commit, pkg.version, this.environmentService.installSource)
298
				// __GDPR__COMMON__ "common.machineId" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
299 300 301 302 303 304 305 306 307 308 309 310 311 312
				.then(result => Object.defineProperty(result, 'common.machineId', {
					get: () => this.storageService.getItem(machineIdStorageKey),
					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);
	}

313
	private openFirstWindow(accessor: ServicesAccessor): void {
314 315 316 317 318 319
		const appInstantiationService = accessor.get(IInstantiationService);

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

		// TODO@Joao: so ugly...
B
Benjamin Pasero 已提交
320 321
		this.windowsMainService.onWindowsCountChanged(e => {
			if (!platform.isMacintosh && e.newCount === 0) {
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
				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 已提交
340 341 342 343
		const workspacesService = accessor.get(IWorkspacesMainService);
		const workspacesChannel = appInstantiationService.createInstance(WorkspacesChannel, workspacesService);
		this.electronIpcServer.registerChannel('workspaces', workspacesChannel);

344 345 346 347 348
		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 已提交
349 350 351 352
		const credentialsService = accessor.get(ICredentialsService);
		const credentialsChannel = new CredentialsChannel(credentialsService);
		this.electronIpcServer.registerChannel('credentials', credentialsChannel);

353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
		// 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
		}
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
	}

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

		// Setup Windows mutex
		let windowsMutex: Mutex = null;
		if (platform.isWindows) {
			try {
				const Mutex = (require.__$__nodeRequire('windows-mutex') as any).Mutex;
				windowsMutex = new Mutex(product.win32MutexName);
				this.toDispose.push({ dispose: () => windowsMutex.release() });
			} catch (e) {
				// noop
			}
		}
385 386

		// Install Menu
B
Benjamin Pasero 已提交
387
		appInstantiationService.createInstance(CodeMenu);
388 389

		// Jump List
390
		this.historyService.updateWindowsJumpList();
B
Benjamin Pasero 已提交
391
		this.historyService.onRecentlyOpenedChange(() => this.historyService.updateWindowsJumpList());
392 393 394

		// Start shared process here
		this.sharedProcess.spawn();
B
Benjamin Pasero 已提交
395 396 397 398 399 400 401 402 403 404 405 406 407 408

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

				// 'exe' => /Applications/Visual Studio Code - Insiders.app/Contents/MacOS/Electron
				const appPath = dirname(dirname(dirname(app.getPath('exe'))));
				const infoPlistPath = join(appPath, 'Contents', 'Info.plist');
				touch(appPath).done(null, error => { /* ignore */ });
				touch(infoPlistPath).done(null, error => { /* ignore */ });
			}
		}
409 410 411 412 413
	}

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