extHostExtensionService.ts 12.2 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';

J
Joao Moreno 已提交
7
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
8
import { join } from 'path';
9
import { mkdirp, dirExists } from 'vs/base/node/pfs';
E
Erich Gamma 已提交
10
import Severity from 'vs/base/common/severity';
J
Johannes Rieken 已提交
11 12
import { TPromise } from 'vs/base/common/winjs.base';
import { AbstractExtensionService, ActivatedExtension } from 'vs/platform/extensions/common/abstractExtensionService';
A
Alex Dima 已提交
13
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
J
Johannes Rieken 已提交
14 15
import { ExtHostStorage } from 'vs/workbench/api/node/extHostStorage';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
16
import { createApiFactory, initializeExtensionApi } from 'vs/workbench/api/node/extHost.api.impl';
J
Johannes Rieken 已提交
17
import { IThreadService } from 'vs/workbench/services/thread/common/threadService';
18
import { MainContext, MainProcessExtensionServiceShape, IWorkspaceData, IEnvironment, IInitData } from './extHost.protocol';
B
Benjamin Pasero 已提交
19

A
Alex Dima 已提交
20 21 22 23 24
/**
 * Represents the source code (module) of an extension.
 */
export interface IExtensionModule {
	activate(ctx: IExtensionContext): TPromise<IExtensionAPI>;
25 26 27
	deactivate(): void;
}

A
Alex Dima 已提交
28 29 30 31 32
/**
 * Represents the API of an extension (return value of `activate`).
 */
export interface IExtensionAPI {
	// _extensionAPIBrand: any;
33 34
}

A
Alex Dima 已提交
35
export class ExtHostExtension extends ActivatedExtension {
36

A
Alex Dima 已提交
37 38
	module: IExtensionModule;
	exports: IExtensionAPI;
39 40
	subscriptions: IDisposable[];

A
Alex Dima 已提交
41
	constructor(activationFailed: boolean, module: IExtensionModule, exports: IExtensionAPI, subscriptions: IDisposable[]) {
42 43 44 45
		super(activationFailed);
		this.module = module;
		this.exports = exports;
		this.subscriptions = subscriptions;
E
Erich Gamma 已提交
46
	}
47
}
E
Erich Gamma 已提交
48

A
Alex Dima 已提交
49
export class ExtHostEmptyExtension extends ExtHostExtension {
50 51
	constructor() {
		super(false, { activate: undefined, deactivate: undefined }, undefined, []);
E
Erich Gamma 已提交
52 53 54
	}
}

A
Alex Dima 已提交
55
export interface IExtensionMemento {
A
Alex Dima 已提交
56 57 58 59
	get<T>(key: string, defaultValue: T): T;
	update(key: string, value: any): Thenable<boolean>;
}

A
Alex Dima 已提交
60
class ExtensionMemento implements IExtensionMemento {
A
Alex Dima 已提交
61 62 63

	private _id: string;
	private _shared: boolean;
A
Alex Dima 已提交
64
	private _storage: ExtHostStorage;
A
Alex Dima 已提交
65

A
Alex Dima 已提交
66
	private _init: TPromise<ExtensionMemento>;
A
Alex Dima 已提交
67 68
	private _value: { [n: string]: any; };

A
Alex Dima 已提交
69
	constructor(id: string, global: boolean, storage: ExtHostStorage) {
A
Alex Dima 已提交
70 71 72 73 74 75 76 77 78 79
		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;
		});
	}

A
Alex Dima 已提交
80
	get whenReady(): TPromise<ExtensionMemento> {
A
Alex Dima 已提交
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
		return this._init;
	}

	get<T>(key: string, defaultValue: T): T {
		let value = this._value[key];
		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);
	}
}

100 101
class ExtensionStoragePath {

102
	private readonly _workspace: IWorkspaceData;
103 104 105 106 107
	private readonly _environment: IEnvironment;

	private readonly _ready: TPromise<string>;
	private _value: string;

108
	constructor(workspace: IWorkspaceData, environment: IEnvironment) {
109
		this._workspace = workspace;
110 111 112 113 114 115 116 117
		this._environment = environment;
		this._ready = this._getOrCreateWorkspaceStoragePath().then(value => this._value = value);
	}

	get whenReady(): TPromise<any> {
		return this._ready;
	}

118 119
	value(extension: IExtensionDescription): string {
		if (this._value) {
120
			return join(this._value, extension.id);
121
		}
M
Matt Bierner 已提交
122
		return undefined;
123 124 125
	}

	private _getOrCreateWorkspaceStoragePath(): TPromise<string> {
126
		if (!this._workspace) {
127 128
			return TPromise.as(undefined);
		}
129
		const storageName = this._workspace.id;
130
		const storagePath = join(this._environment.appSettingsHome, 'workspaceStorage', storageName);
131 132 133 134 135 136

		return dirExists(storagePath).then(exists => {
			if (exists) {
				return storagePath;
			}

J
Johannes Rieken 已提交
137
			return mkdirp(storagePath).then(success => {
138 139 140 141 142 143 144 145
				return storagePath;
			}, err => {
				return undefined;
			});
		});
	}
}

A
Alex Dima 已提交
146 147
export interface IExtensionContext {
	subscriptions: IDisposable[];
A
Alex Dima 已提交
148 149
	workspaceState: IExtensionMemento;
	globalState: IExtensionMemento;
A
Alex Dima 已提交
150
	extensionPath: string;
D
Dirk Baeumer 已提交
151
	storagePath: string;
A
Alex Dima 已提交
152 153 154
	asAbsolutePath(relativePath: string): string;
}

A
Alex Dima 已提交
155
export class ExtHostExtensionService extends AbstractExtensionService<ExtHostExtension> {
E
Erich Gamma 已提交
156 157

	private _threadService: IThreadService;
A
Alex Dima 已提交
158
	private _storage: ExtHostStorage;
159
	private _storagePath: ExtensionStoragePath;
160
	private _proxy: MainProcessExtensionServiceShape;
161
	private _telemetryService: ITelemetryService;
E
Erich Gamma 已提交
162 163 164 165

	/**
	 * This class is constructed manually because it is a service, so it doesn't use any ctor injection
	 */
166
	constructor(initData: IInitData, threadService: IThreadService, telemetryService: ITelemetryService) {
167 168
		super(false);
		this._registry.registerExtensions(initData.extensions);
E
Erich Gamma 已提交
169
		this._threadService = threadService;
A
Alex Dima 已提交
170
		this._storage = new ExtHostStorage(threadService);
171
		this._storagePath = new ExtensionStoragePath(initData.workspace, initData.environment);
172
		this._proxy = this._threadService.get(MainContext.MainProcessExtensionService);
173
		this._telemetryService = telemetryService;
174 175

		// initialize API first
176
		const apiFactory = createApiFactory(initData, threadService, this, this._telemetryService);
177
		initializeExtensionApi(this, apiFactory).then(() => this._triggerOnReady());
E
Erich Gamma 已提交
178 179
	}

180 181 182 183 184 185 186 187
	public getAllExtensionDescriptions(): IExtensionDescription[] {
		return this._registry.getAllExtensionDescriptions();
	}

	public getExtensionDescription(extensionId: string): IExtensionDescription {
		return this._registry.getExtensionDescription(extensionId);
	}

A
Alex Dima 已提交
188
	public $localShowMessage(severity: Severity, msg: string): void {
E
Erich Gamma 已提交
189 190 191 192 193 194 195 196 197 198 199 200
		switch (severity) {
			case Severity.Error:
				console.error(msg);
				break;
			case Severity.Warning:
				console.warn(msg);
				break;
			default:
				console.log(msg);
		}
	}

A
Alex Dima 已提交
201
	public get(extensionId: string): IExtensionAPI {
A
Alex Dima 已提交
202
		return this._manager.getActivatedExtension(extensionId).exports;
203 204
	}

205
	public deactivate(extensionId: string): TPromise<void> {
J
Johannes Rieken 已提交
206
		let result: TPromise<void> = TPromise.as(void 0);
207

A
Alex Dima 已提交
208 209 210 211 212
		if (!this._manager.isActivated(extensionId)) {
			return result;
		}

		let extension = this._manager.getActivatedExtension(extensionId);
A
Alex Dima 已提交
213
		if (!extension) {
214
			return result;
215 216 217 218
		}

		// call deactivate if available
		try {
A
Alex Dima 已提交
219
			if (typeof extension.module.deactivate === 'function') {
220 221 222 223
				result = TPromise.wrap(extension.module.deactivate()).then(null, (err) => {
					// TODO: Do something with err if this is not the shutdown case
					return TPromise.as(void 0);
				});
224
			}
B
Benjamin Pasero 已提交
225
		} catch (err) {
226 227 228 229 230
			// TODO: Do something with err if this is not the shutdown case
		}

		// clean up subscriptions
		try {
J
Joao Moreno 已提交
231
			dispose(extension.subscriptions);
B
Benjamin Pasero 已提交
232
		} catch (err) {
233 234
			// TODO: Do something with err if this is not the shutdown case
		}
235 236

		return result;
237
	}
E
Erich Gamma 已提交
238

A
Alex Dima 已提交
239 240 241 242 243
	// -- overwriting AbstractExtensionService

	protected _showMessage(severity: Severity, msg: string): void {
		this._proxy.$localShowMessage(severity, msg);
		this.$localShowMessage(severity, msg);
E
Erich Gamma 已提交
244 245
	}

A
Alex Dima 已提交
246 247
	protected _createFailedExtension() {
		return new ExtHostExtension(true, { activate: undefined, deactivate: undefined }, undefined, []);
E
Erich Gamma 已提交
248 249
	}

A
Alex Dima 已提交
250
	private _loadExtensionContext(extensionDescription: IExtensionDescription): TPromise<IExtensionContext> {
E
Erich Gamma 已提交
251

A
Alex Dima 已提交
252 253
		let globalState = new ExtensionMemento(extensionDescription.id, true, this._storage);
		let workspaceState = new ExtensionMemento(extensionDescription.id, false, this._storage);
E
Erich Gamma 已提交
254

255 256 257 258 259
		return TPromise.join([
			globalState.whenReady,
			workspaceState.whenReady,
			this._storagePath.whenReady
		]).then(() => {
A
Alex Dima 已提交
260
			return Object.freeze(<IExtensionContext>{
E
Erich Gamma 已提交
261 262 263
				globalState,
				workspaceState,
				subscriptions: [],
A
Alex Dima 已提交
264
				get extensionPath() { return extensionDescription.extensionFolderPath; },
265
				storagePath: this._storagePath.value(extensionDescription),
266
				asAbsolutePath: (relativePath: string) => { return join(extensionDescription.extensionFolderPath, relativePath); }
E
Erich Gamma 已提交
267 268 269 270
			});
		});
	}

271
	protected _actualActivateExtension(extensionDescription: IExtensionDescription): TPromise<ExtHostExtension> {
A
Alex Dima 已提交
272 273 274
		return this._doActualActivateExtension(extensionDescription).then((activatedExtension) => {
			this._proxy.$onExtensionActivated(extensionDescription.id);
			return activatedExtension;
E
Erich Gamma 已提交
275
		}, (err) => {
A
Alex Dima 已提交
276
			this._proxy.$onExtensionActivationFailed(extensionDescription.id);
E
Erich Gamma 已提交
277 278 279 280
			throw err;
		});
	}

A
Alex Dima 已提交
281
	private _doActualActivateExtension(extensionDescription: IExtensionDescription): TPromise<ExtHostExtension> {
282 283
		let event = getTelemetryActivationEvent(extensionDescription);
		this._telemetryService.publicLog('activatePlugin', event);
A
Alex Dima 已提交
284
		if (!extensionDescription.main) {
A
Alex Dima 已提交
285 286
			// Treat the extension as being empty => NOT AN ERROR CASE
			return TPromise.as(new ExtHostEmptyExtension());
287
		}
288 289 290 291 292 293
		return this.onReady().then(() => {
			return TPromise.join<any>([
				loadCommonJSModule(extensionDescription.main),
				this._loadExtensionContext(extensionDescription)
			]).then(values => {
				return ExtHostExtensionService._callActivate(<IExtensionModule>values[0], <IExtensionContext>values[1]);
294 295 296
			}, (errors: any[]) => {
				// Avoid failing with an array of errors, fail with a single error
				if (errors[0]) {
297
					return TPromise.wrapError<ExtHostExtension>(errors[0]);
298 299
				}
				if (errors[1]) {
300
					return TPromise.wrapError<ExtHostExtension>(errors[1]);
301
				}
M
Matt Bierner 已提交
302
				return undefined;
303 304 305 306
			});
		});
	}

A
Alex Dima 已提交
307 308 309
	private static _callActivate(extensionModule: IExtensionModule, context: IExtensionContext): TPromise<ExtHostExtension> {
		// Make sure the extension's surface is not undefined
		extensionModule = extensionModule || {
310 311 312 313
			activate: undefined,
			deactivate: undefined
		};

A
Alex Dima 已提交
314 315
		return this._callActivateOptional(extensionModule, context).then((extensionExports) => {
			return new ExtHostExtension(false, extensionModule, extensionExports, context.subscriptions);
316 317 318
		});
	}

A
Alex Dima 已提交
319 320
	private static _callActivateOptional(extensionModule: IExtensionModule, context: IExtensionContext): TPromise<IExtensionAPI> {
		if (typeof extensionModule.activate === 'function') {
321
			try {
A
Alex Dima 已提交
322
				return TPromise.as(extensionModule.activate.apply(global, [context]));
323
			} catch (err) {
A
Alex Dima 已提交
324
				return TPromise.wrapError(err);
325 326
			}
		} else {
A
Alex Dima 已提交
327 328
			// No activate found => the module is the extension's exports
			return TPromise.as<IExtensionAPI>(extensionModule);
329 330 331
		}
	}

E
Erich Gamma 已提交
332 333
	// -- called by main thread

334 335
	public $activateByEvent(activationEvent: string): TPromise<void> {
		return this._manager.activateByEvent(activationEvent);
E
Erich Gamma 已提交
336 337 338
	}
}

A
Alex Dima 已提交
339
function loadCommonJSModule<T>(modulePath: string): TPromise<T> {
B
Benjamin Pasero 已提交
340
	let r: T = null;
E
Erich Gamma 已提交
341 342
	try {
		r = require.__$__nodeRequire<T>(modulePath);
B
Benjamin Pasero 已提交
343
	} catch (e) {
344
		return TPromise.wrapError<T>(e);
E
Erich Gamma 已提交
345
	}
A
Alex Dima 已提交
346
	return TPromise.as(r);
E
Erich Gamma 已提交
347
}
A
Alex Dima 已提交
348 349 350 351 352 353

function getTelemetryActivationEvent(extensionDescription: IExtensionDescription): any {
	let event = {
		id: extensionDescription.id,
		name: extensionDescription.name,
		publisherDisplayName: extensionDescription.publisher,
354 355
		activationEvents: extensionDescription.activationEvents ? extensionDescription.activationEvents.join(',') : null,
		isBuiltin: extensionDescription.isBuiltin
A
Alex Dima 已提交
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
	};

	for (let contribution in extensionDescription.contributes) {
		let contributionDetails = extensionDescription.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;
388
}