app.ts 16.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';
46 47 48
import { IDisposable, dispose } from "vs/base/common/lifecycle";
import { ConfigurationService } from "vs/platform/configuration/node/configurationService";
import { TPromise } from "vs/base/common/winjs.base";
B
Benjamin Pasero 已提交
49
import { IWindowsMainService } from "vs/platform/windows/electron-main/windows";
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
import { WorkspacesChannel } from "vs/platform/workspaces/common/workspacesIpc";
56
import { IWorkspacesMainService } from "vs/platform/workspaces/common/workspaces";
57

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

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

			this.dispose();
		});

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

		app.on('web-contents-created', (event, contents) => {
			contents.on('will-attach-webview', (event, webPreferences, params) => {
				delete webPreferences.preload;
				webPreferences.nodeIntegration = false;

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

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

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

152 153 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
		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);
		});

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

186 187 188 189 190 191 192
		ipc.on('vscode:exit', (event, code: number) => {
			this.logService.log('IPC#vscode:exit', code);

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

193 194 195 196 197 198
		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 已提交
199
			const { webContents } = BrowserWindow.fromId(windowId);
200
			getShellEnvironment().then(shellEnv => {
J
Johannes Rieken 已提交
201 202 203
				if (!webContents.isDestroyed()) {
					webContents.send('vscode:acceptShellEnv', shellEnv);
				}
204
			}, err => {
J
Johannes Rieken 已提交
205 206 207
				if (!webContents.isDestroyed()) {
					webContents.send('vscode:acceptShellEnv', {});
				}
B
Benjamin Pasero 已提交
208 209

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

213
		ipc.on('vscode:broadcast', (event, windowId: number, broadcast: { channel: string; payload: any; }) => {
214
			if (this.windowsMainService && broadcast.channel && !isUndefinedOrNull(broadcast.payload)) {
215
				this.logService.log('IPC#vscode:broadcast', broadcast.channel, broadcast.payload);
216 217 218 219

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

220 221
				// Send to all windows (except sender window)
				this.windowsMainService.sendToAll('vscode:broadcast', broadcast, [windowId]);
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
			}
		});

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

	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);
		}
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
	}

	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 已提交
263
		this.sharedProcessClient = this.sharedProcess.whenReady().then(() => connect(this.environmentService.sharedIPCHandle, 'main'));
264 265 266 267

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

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

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

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

	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 已提交
286
		services.set(ICredentialsService, new SyncDescriptor(CredentialsService));
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306

		// 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);
			const commonProperties = resolveCommonProperties(product.commit, pkg.version)
				.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);
	}

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

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

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

338 339 340 341 342
		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 已提交
343 344 345 346
		const credentialsService = accessor.get(ICredentialsService);
		const credentialsChannel = new CredentialsChannel(credentialsService);
		this.electronIpcServer.registerChannel('credentials', credentialsChannel);

347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
		// 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
		}
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
	}

	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
			}
		}
379 380

		// Install Menu
B
Benjamin Pasero 已提交
381
		appInstantiationService.createInstance(CodeMenu);
382 383

		// Jump List
384
		this.historyService.updateWindowsJumpList();
B
Benjamin Pasero 已提交
385
		this.historyService.onRecentlyOpenedChange(() => this.historyService.updateWindowsJumpList());
386 387 388 389 390 391 392 393

		// Start shared process here
		this.sharedProcess.spawn();
	}

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