nativePluginService.ts 13.8 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';

I
isidor 已提交
7
import {IPluginDescription, IMessage, IPluginStatus} from 'vs/platform/plugins/common/plugins';
E
Erich Gamma 已提交
8 9
import {PluginsRegistry} from 'vs/platform/plugins/common/pluginsRegistry';
import WinJS = require('vs/base/common/winjs.base');
10
import {IDisposable} from 'vs/base/common/lifecycle';
E
Erich Gamma 已提交
11
import {Remotable, IThreadService} from 'vs/platform/thread/common/thread';
12
import {ActivatedPlugin, AbstractPluginService, IPluginContext, IPluginMemento, loadAMDModule} from 'vs/platform/plugins/common/abstractPluginService';
E
Erich Gamma 已提交
13 14 15 16 17
import Severity from 'vs/base/common/severity';
import {IMessageService} from 'vs/platform/message/common/message';
import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry';
import {PluginHostStorage} from 'vs/platform/storage/common/remotable.storage';
import * as paths from 'vs/base/common/paths';
A
tslint  
Alex Dima 已提交
18
import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace';
19
import {disposeAll} from 'vs/base/common/lifecycle';
20
var hasOwnProperty = Object.hasOwnProperty;
E
Erich Gamma 已提交
21 22 23 24 25 26 27

class PluginMemento implements IPluginMemento {

	private _id: string;
	private _shared: boolean;
	private _storage: PluginHostStorage;

A
tslint  
Alex Dima 已提交
28 29
	private _init:WinJS.TPromise<PluginMemento>;
	private _value: { [n: string]: any;};
E
Erich Gamma 已提交
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46

	constructor(id: string, global:boolean, storage: PluginHostStorage) {
		this._id = id;
		this._shared = global;
		this._storage = storage;

		this._init = this._storage.getValue(this._shared, this._id, Object.create(null)).then(value => {
			this._value = value;
			return this;
		});
	}

	get whenReady(): WinJS.TPromise<PluginMemento> {
		return this._init;
	}

	get<T>(key: string, defaultValue: T): T {
A
tslint  
Alex Dima 已提交
47
		let value = this._value[key];
E
Erich Gamma 已提交
48 49 50 51 52 53 54 55 56 57 58 59 60 61
		if (typeof value === 'undefined') {
			value = defaultValue;
		}
		return value;
	}

	update(key: string, value: any): Thenable<boolean> {
		this._value[key] = value;
		return this._storage
			.setValue(this._shared, this._id, this._value)
			.then(() => true);
	}
}

62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
/**
 * Represents a failed extension in the ext host.
 */
export class MainProcessFailedPlugin extends ActivatedPlugin {
	constructor() {
		super(true);
	}
}

/**
 * Represents an extension that was successfully loaded or an
 * empty extension in the ext host.
 */
export class MainProcessSuccessPlugin extends ActivatedPlugin {
	constructor() {
		super(false);
	}
}


E
Erich Gamma 已提交
82
@Remotable.MainContext('MainProcessPluginService')
83
export class MainProcessPluginService extends AbstractPluginService<ActivatedPlugin> {
E
Erich Gamma 已提交
84 85 86 87 88 89

	private _threadService: IThreadService;
	private _messageService: IMessageService;
	private _telemetryService: ITelemetryService;
	private _proxy: PluginHostPluginService;
	private _isDev: boolean;
I
isidor 已提交
90
	private _pluginsStatus: { [id: string]: IPluginStatus };
E
Erich Gamma 已提交
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109

	/**
	 * This class is constructed manually because it is a service, so it doesn't use any ctor injection
	 */
	constructor(
		contextService: IWorkspaceContextService,
		threadService: IThreadService,
		messageService:IMessageService,
		telemetryService:ITelemetryService
	) {
		let config = contextService.getConfiguration();
		this._isDev = !config.env.isBuilt || !!config.env.pluginDevelopmentPath;

		this._messageService = messageService;
		threadService.registerRemotableInstance(MainProcessPluginService, this);
		super(false);
		this._threadService = threadService;
		this._telemetryService = telemetryService;
		this._proxy = this._threadService.getRemotable(PluginHostPluginService);
I
isidor 已提交
110
		this._pluginsStatus = {};
E
Erich Gamma 已提交
111 112 113 114 115 116

		PluginsRegistry.handleExtensionPoints((severity, source, message) => {
			this.showMessage(severity, source, message);
		});
	}

117 118 119 120
	protected _createFailedPlugin() {
		return new MainProcessFailedPlugin();
	}

E
Erich Gamma 已提交
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
	private getTelemetryActivationEvent(pluginDescription: IPluginDescription): any {
		var event = {
			id: pluginDescription.id,
			name: pluginDescription.name,
			publisherDisplayName: pluginDescription.publisher,
			activationEvents: pluginDescription.activationEvents ? pluginDescription.activationEvents.join(',') : null
		};

		for (let contribution in pluginDescription.contributes) {
			let contributionDetails = pluginDescription.contributes[contribution];

			if (!contributionDetails) {
				continue;
			}

			switch (contribution) {
				case 'debuggers':
					let types = contributionDetails.reduce((p,c)=> p ? p + ',' + c['type']: c['type'], '');
					event['contribution.debuggers'] = types;
					break;
				case 'grammars':
					let grammers = contributionDetails.reduce((p,c)=> p ? p + ',' + c['language']: c['language'], '');
					event['contribution.grammars'] = grammers;
					break;
				case 'languages':
					let languages = contributionDetails.reduce((p,c)=> p ? p + ',' + c['id']: c['id'], '');
					event['contribution.languages'] = languages;
					break;
				case 'tmSnippets':
					let tmSnippets = contributionDetails.reduce((p,c)=> p ? p + ',' + c['languageId']: c['languageId'], '');
					event['contribution.tmSnippets'] = tmSnippets;
					break;
				default:
					event[`contribution.${contribution}`] = true;
			}
		}

		return event;
	}

	protected _showMessage(severity:Severity, msg:string): void {
		this._proxy.$doShowMessage(severity, msg);
		this.$doShowMessage(severity, msg);
	}

166 167 168 169 170 171 172 173
	public showMessage(severity:Severity, source: string, message:string) {
		super.showMessage(severity, source, message);
		if (!this._pluginsStatus[source]) {
			this._pluginsStatus[source] = { messages: [] };
		}
		this._pluginsStatus[source].messages.push({ type: severity, source, message });
	}

E
Erich Gamma 已提交
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
	public $doShowMessage(severity:Severity, msg:string): void {
		let messageShown = false;
		if (severity === Severity.Error || severity === Severity.Warning) {
			if (this._isDev) {
				// Only show nasty intrusive messages if doing extension development.
				this._messageService.show(severity, msg);
				messageShown = true;
			}
		}

		if (!messageShown) {
			switch (severity) {
				case Severity.Error:
					console.error(msg);
					break;
				case Severity.Warning:
					console.warn(msg);
					break;
				default:
					console.log(msg);
			}
		}
	}

I
isidor 已提交
198 199 200 201
	public getPluginsStatus(): { [id: string]: IPluginStatus } {
		return this._pluginsStatus;
	}

202 203 204 205
	public deactivate(pluginId:string): void {
		this._proxy.deactivate(pluginId);
	}

E
Erich Gamma 已提交
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
	// -- overwriting AbstractPluginService

	protected _actualActivatePlugin(pluginDescription: IPluginDescription): WinJS.TPromise<ActivatedPlugin> {
		let event = this.getTelemetryActivationEvent(pluginDescription);
		this._telemetryService.publicLog('activatePlugin', event);
		// redirect plugin activation to the plugin host
		return this._proxy.$activatePluginInPluginHost(pluginDescription).then(_ => {
			// the plugin host calls $onPluginActivatedInPluginHost, where we write to `activatedPlugins`
			return this.activatedPlugins[pluginDescription.id];
		});
	}

	// -- called by plugin host

	public $onPluginHostReady(pluginDescriptions: IPluginDescription[], messages:IMessage[]): void {
		PluginsRegistry.registerPlugins(pluginDescriptions);
		this.registrationDone(messages);
	}

225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
	public $onPluginActivatedInPluginHost(pluginId:string): void {
		this.activatedPlugins[pluginId] = new MainProcessSuccessPlugin();
	}

	public $onPluginActivationFailedInPluginHost(pluginId:string): void {
		this.activatedPlugins[pluginId] = new MainProcessFailedPlugin();
	}
}

export interface IPluginModule {
	activate(ctx: IPluginContext): WinJS.TPromise<IPluginExports>;
	deactivate(): void;
}

export interface IPluginExports {
	// _pluginExportsBrand: any;
}

export class ExtHostPlugin extends ActivatedPlugin {

	module: IPluginModule;
	exports: IPluginExports;
	subscriptions: IDisposable[];

	constructor(activationFailed: boolean, module: IPluginModule, exports: IPluginExports, subscriptions: IDisposable[]) {
		super(activationFailed);
		this.module = module;
		this.exports = exports;
		this.subscriptions = subscriptions;
E
Erich Gamma 已提交
254
	}
255
}
E
Erich Gamma 已提交
256

257 258 259
export class EmptyPlugin extends ExtHostPlugin {
	constructor() {
		super(false, { activate: undefined, deactivate: undefined }, undefined, []);
E
Erich Gamma 已提交
260 261 262 263
	}
}

@Remotable.PluginHostContext('PluginHostPluginService')
264
export class PluginHostPluginService extends AbstractPluginService<ExtHostPlugin> {
E
Erich Gamma 已提交
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298

	private _threadService: IThreadService;
	private _storage: PluginHostStorage;
	private _proxy: MainProcessPluginService;

	/**
	 * This class is constructed manually because it is a service, so it doesn't use any ctor injection
	 */
	constructor(threadService: IThreadService) {
		threadService.registerRemotableInstance(PluginHostPluginService, this);
		super(true);
		this._threadService = threadService;
		this._storage = new PluginHostStorage(threadService);
		this._proxy = this._threadService.getRemotable(MainProcessPluginService);
	}

	protected _showMessage(severity:Severity, msg:string): void {
		this._proxy.$doShowMessage(severity, msg);
		this.$doShowMessage(severity, msg);
	}

	public $doShowMessage(severity:Severity, msg:string): void {
		switch (severity) {
			case Severity.Error:
				console.error(msg);
				break;
			case Severity.Warning:
				console.warn(msg);
				break;
			default:
				console.log(msg);
		}
	}

299 300 301 302 303 304 305
	public get(pluginId: string): IPluginExports {
		if (!hasOwnProperty.call(this.activatedPlugins, pluginId)) {
			throw new Error('Plugin `' + pluginId + '` is not known or not activated');
		}
		return this.activatedPlugins[pluginId].exports;
	}

306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
	public deactivate(pluginId:string): void {
		let plugin = this.activatedPlugins[pluginId];
		if (!plugin) {
			return;
		}

		// call deactivate if available
		try {
			if (typeof plugin.module.deactivate === 'function') {
				plugin.module.deactivate();
			}
		} catch(err) {
			// TODO: Do something with err if this is not the shutdown case
		}

		// clean up subscriptions
		try {
A
tslint  
Alex Dima 已提交
323
			disposeAll(plugin.subscriptions);
324 325 326 327
		} catch(err) {
			// TODO: Do something with err if this is not the shutdown case
		}
	}
E
Erich Gamma 已提交
328

329 330 331 332
	protected _createFailedPlugin() {
		return new ExtHostPlugin(true, { activate: undefined, deactivate: undefined }, undefined, []);
	}

E
Erich Gamma 已提交
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
	// -- overwriting AbstractPluginService

	public registrationDone(messages:IMessage[]): void {
		super.registrationDone([]);
		this._proxy.$onPluginHostReady(PluginsRegistry.getAllPluginDescriptions(), messages);
	}

	protected _loadPluginModule(pluginDescription: IPluginDescription): WinJS.TPromise<IPluginModule> {
		if (pluginDescription.isAMD) {
			return loadAMDModule(uriFromPath(pluginDescription.main));
		}

		return loadCommonJSModule(pluginDescription.main);
	}

	protected _loadPluginContext(pluginDescription: IPluginDescription): WinJS.TPromise<IPluginContext> {

		let globalState = new PluginMemento(pluginDescription.id, true, this._storage);
		let workspaceState = new PluginMemento(pluginDescription.id, false, this._storage);

		return WinJS.TPromise.join([globalState.whenReady, workspaceState.whenReady]).then(() => {
			return Object.freeze(<IPluginContext>{
				globalState,
				workspaceState,
				subscriptions: [],
A
tslint  
Alex Dima 已提交
358
				get extensionPath() { return pluginDescription.extensionFolderPath; },
E
Erich Gamma 已提交
359 360 361 362 363 364 365
				asAbsolutePath: (relativePath:string) => { return paths.normalize(paths.join(pluginDescription.extensionFolderPath, relativePath), true); }
			});
		});
	}

	protected _actualActivatePlugin(pluginDescription: IPluginDescription): WinJS.TPromise<ActivatedPlugin> {

366 367
		return this._superActualActivatePlugin(pluginDescription).then((activatedPlugin) => {
			this._proxy.$onPluginActivatedInPluginHost(pluginDescription.id);
E
Erich Gamma 已提交
368 369
			return activatedPlugin;
		}, (err) => {
370
			this._proxy.$onPluginActivationFailedInPluginHost(pluginDescription.id);
E
Erich Gamma 已提交
371 372 373 374
			throw err;
		});
	}

375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
	private _superActualActivatePlugin(pluginDescription: IPluginDescription): WinJS.TPromise<ExtHostPlugin> {

		if (!pluginDescription.main) {
			// Treat the plugin as being empty => NOT AN ERROR CASE
			return WinJS.TPromise.as(new EmptyPlugin());
		}
		return this._loadPluginModule(pluginDescription).then((pluginModule) => {
			return this._loadPluginContext(pluginDescription).then(context => {
				return PluginHostPluginService._callActivate(pluginModule, context);
			});
		});
	}

	private static _callActivate(pluginModule: IPluginModule, context: IPluginContext): WinJS.TPromise<ExtHostPlugin> {
		// Make sure the plugin's surface is not undefined
		pluginModule = pluginModule || {
			activate: undefined,
			deactivate: undefined
		};

		// let subscriptions:IDisposable[] = [];
		return this._callActivateOptional(pluginModule, context).then((pluginExports) => {
			return new ExtHostPlugin(false, pluginModule, pluginExports, context.subscriptions);
		});
	}

	private static _callActivateOptional(pluginModule: IPluginModule, context: IPluginContext): WinJS.TPromise<IPluginExports> {
		if (typeof pluginModule.activate === 'function') {
			try {
				return WinJS.TPromise.as(pluginModule.activate.apply(global, [context]));
			} catch (err) {
				return WinJS.TPromise.wrapError(err);
			}
		} else {
			// No activate found => the module is the plugin's exports
			return WinJS.TPromise.as<IPluginExports>(pluginModule);
		}
	}

E
Erich Gamma 已提交
414 415 416
	// -- called by main thread

	public $activatePluginInPluginHost(pluginDescription: IPluginDescription): WinJS.TPromise<void> {
417
		return this._activatePlugin(pluginDescription);
E
Erich Gamma 已提交
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
	}

}

function loadCommonJSModule<T>(modulePath: string): WinJS.TPromise<T> {
	var r: T = null;
	try {
		r = require.__$__nodeRequire<T>(modulePath);
	} catch(e) {
		return WinJS.TPromise.wrapError(e);
	}
	return WinJS.TPromise.as(r);
}


// TODO@Alex: Duplicated in:
// * src\bootstrap.js
// * src\vs\workbench\electron-main\bootstrap.js
// * src\vs\platform\plugins\common\nativePluginService.ts
function uriFromPath(_path) {
	var pathName = _path.replace(/\\/g, '/');

	if (pathName.length > 0 && pathName.charAt(0) !== '/') {
		pathName = '/' + pathName;
	}

	return encodeURI('file://' + pathName);
}