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

A
Alex Dima 已提交
7
import { 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
import { TPromise } from 'vs/base/common/winjs.base';
A
Alex Dima 已提交
12
import { ExtensionDescriptionRegistry } from "vs/workbench/services/extensions/node/extensionDescriptionRegistry";
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';
A
Alex Dima 已提交
17
import { MainContext, MainThreadExtensionServiceShape, IWorkspaceData, IEnvironment, IInitData, ExtHostExtensionServiceShape } from './extHost.protocol';
A
Alex Dima 已提交
18 19
import { IExtensionMemento, ExtensionsActivator, ActivatedExtension, IExtensionAPI, IExtensionContext, EmptyExtension, IExtensionModule } from "vs/workbench/api/node/extHostExtensionActivator";
import { Barrier } from "vs/workbench/services/extensions/node/barrier";
20
import { ExtHostThreadService } from "vs/workbench/services/thread/node/extHostThreadService";
A
Alex Dima 已提交
21

A
Alex Dima 已提交
22
class ExtensionMemento implements IExtensionMemento {
A
Alex Dima 已提交
23 24 25

	private _id: string;
	private _shared: boolean;
A
Alex Dima 已提交
26
	private _storage: ExtHostStorage;
A
Alex Dima 已提交
27

A
Alex Dima 已提交
28
	private _init: TPromise<ExtensionMemento>;
A
Alex Dima 已提交
29 30
	private _value: { [n: string]: any; };

A
Alex Dima 已提交
31
	constructor(id: string, global: boolean, storage: ExtHostStorage) {
A
Alex Dima 已提交
32 33 34 35 36 37 38 39 40 41
		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 已提交
42
	get whenReady(): TPromise<ExtensionMemento> {
A
Alex Dima 已提交
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
		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);
	}
}

62 63
class ExtensionStoragePath {

64
	private readonly _workspace: IWorkspaceData;
65 66 67 68 69
	private readonly _environment: IEnvironment;

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

70
	constructor(workspace: IWorkspaceData, environment: IEnvironment) {
71
		this._workspace = workspace;
72 73 74 75 76 77 78 79
		this._environment = environment;
		this._ready = this._getOrCreateWorkspaceStoragePath().then(value => this._value = value);
	}

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

80 81
	value(extension: IExtensionDescription): string {
		if (this._value) {
82
			return join(this._value, extension.id);
83
		}
M
Matt Bierner 已提交
84
		return undefined;
85 86 87
	}

	private _getOrCreateWorkspaceStoragePath(): TPromise<string> {
88
		if (!this._workspace) {
89 90
			return TPromise.as(undefined);
		}
91
		const storageName = this._workspace.id;
92
		const storagePath = join(this._environment.appSettingsHome, 'workspaceStorage', storageName);
93 94 95 96 97 98

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

J
Johannes Rieken 已提交
99
			return mkdirp(storagePath).then(success => {
100 101 102 103 104 105 106 107
				return storagePath;
			}, err => {
				return undefined;
			});
		});
	}
}

A
Alex Dima 已提交
108
export class ExtHostExtensionService implements ExtHostExtensionServiceShape {
A
Alex Dima 已提交
109 110 111

	private readonly _barrier: Barrier;
	private readonly _registry: ExtensionDescriptionRegistry;
112
	private readonly _threadService: ExtHostThreadService;
A
Alex Dima 已提交
113 114 115
	private readonly _telemetryService: ITelemetryService;
	private readonly _storage: ExtHostStorage;
	private readonly _storagePath: ExtensionStoragePath;
116
	private readonly _proxy: MainThreadExtensionServiceShape;
A
Alex Dima 已提交
117
	private _activator: ExtensionsActivator;
A
Alex Dima 已提交
118

A
Alex Dima 已提交
119 120 121
	/**
	 * This class is constructed manually because it is a service, so it doesn't use any ctor injection
	 */
122
	constructor(initData: IInitData, threadService: ExtHostThreadService, telemetryService: ITelemetryService) {
A
Alex Dima 已提交
123 124 125 126 127 128
		this._barrier = new Barrier();
		this._registry = new ExtensionDescriptionRegistry(initData.extensions);
		this._threadService = threadService;
		this._telemetryService = telemetryService;
		this._storage = new ExtHostStorage(threadService);
		this._storagePath = new ExtensionStoragePath(initData.workspace, initData.environment);
129
		this._proxy = this._threadService.get(MainContext.MainThreadExtensionService);
A
Alex Dima 已提交
130
		this._activator = null;
131

A
Alex Dima 已提交
132 133
		// initialize API first (i.e. do not release barrier until the API is initialized)
		const apiFactory = createApiFactory(initData, threadService, this, this._telemetryService);
134

A
Alex Dima 已提交
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
		initializeExtensionApi(this, apiFactory).then(() => {

			this._activator = new ExtensionsActivator(this._registry, {
				showMessage: (severity: Severity, message: string): void => {
					this._proxy.$localShowMessage(severity, message);

					switch (severity) {
						case Severity.Error:
							console.error(message);
							break;
						case Severity.Warning:
							console.warn(message);
							break;
						default:
							console.log(message);
					}
				},

				actualActivateExtension: (extensionDescription: IExtensionDescription): TPromise<ActivatedExtension> => {
					return this._activateExtension(extensionDescription);
				}
156 157
			});

A
Alex Dima 已提交
158 159
			this._barrier.open();
		});
160 161
	}

A
Alex Dima 已提交
162 163
	public onExtensionAPIReady(): TPromise<boolean> {
		return this._barrier.wait();
164 165 166
	}

	public isActivated(extensionId: string): boolean {
A
Alex Dima 已提交
167 168 169 170
		if (this._barrier.isOpen()) {
			return this._activator.isActivated(extensionId);
		}
		return false;
171 172 173
	}

	public activateByEvent(activationEvent: string): TPromise<void> {
A
Alex Dima 已提交
174 175
		if (this._barrier.isOpen()) {
			return this._activator.activateByEvent(activationEvent);
176
		} else {
A
Alex Dima 已提交
177
			return this._barrier.wait().then(() => this._activator.activateByEvent(activationEvent));
178 179 180 181
		}
	}

	public activateById(extensionId: string): TPromise<void> {
A
Alex Dima 已提交
182 183
		if (this._barrier.isOpen()) {
			return this._activator.activateById(extensionId);
184
		} else {
A
Alex Dima 已提交
185
			return this._barrier.wait().then(() => this._activator.activateById(extensionId));
186 187 188
		}
	}

189 190 191 192 193 194 195 196
	public getAllExtensionDescriptions(): IExtensionDescription[] {
		return this._registry.getAllExtensionDescriptions();
	}

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

A
Alex Dima 已提交
197 198 199 200 201
	public getExtensionExports(extensionId: string): IExtensionAPI {
		if (this._barrier.isOpen()) {
			return this._activator.getActivatedExtension(extensionId).exports;
		} else {
			return null;
E
Erich Gamma 已提交
202 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._barrier.isOpen()) {
			return result;
		}

		if (!this._activator.isActivated(extensionId)) {
A
Alex Dima 已提交
213 214 215
			return result;
		}

A
Alex Dima 已提交
216
		let extension = this._activator.getActivatedExtension(extensionId);
A
Alex Dima 已提交
217
		if (!extension) {
218
			return result;
219 220 221 222
		}

		// call deactivate if available
		try {
A
Alex Dima 已提交
223
			if (typeof extension.module.deactivate === 'function') {
224 225 226 227
				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);
				});
228
			}
B
Benjamin Pasero 已提交
229
		} catch (err) {
230 231 232 233 234
			// TODO: Do something with err if this is not the shutdown case
		}

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

		return result;
241
	}
E
Erich Gamma 已提交
242

A
Alex Dima 已提交
243
	// --- impl
A
Alex Dima 已提交
244

A
Alex Dima 已提交
245 246 247 248 249 250 251 252
	private _activateExtension(extensionDescription: IExtensionDescription): TPromise<ActivatedExtension> {
		return this._doActivateExtension(extensionDescription).then((activatedExtension) => {
			this._proxy.$onExtensionActivated(extensionDescription.id);
			return activatedExtension;
		}, (err) => {
			this._proxy.$onExtensionActivationFailed(extensionDescription.id);
			throw err;
		});
E
Erich Gamma 已提交
253 254
	}

A
Alex Dima 已提交
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
	private _doActivateExtension(extensionDescription: IExtensionDescription): TPromise<ActivatedExtension> {
		let event = getTelemetryActivationEvent(extensionDescription);
		this._telemetryService.publicLog('activatePlugin', event);
		if (!extensionDescription.main) {
			// Treat the extension as being empty => NOT AN ERROR CASE
			return TPromise.as(new EmptyExtension());
		}
		return TPromise.join<any>([
			loadCommonJSModule(extensionDescription.main),
			this._loadExtensionContext(extensionDescription)
		]).then(values => {
			return ExtHostExtensionService._callActivate(<IExtensionModule>values[0], <IExtensionContext>values[1]);
		}, (errors: any[]) => {
			// Avoid failing with an array of errors, fail with a single error
			if (errors[0]) {
				return TPromise.wrapError<ActivatedExtension>(errors[0]);
			}
			if (errors[1]) {
				return TPromise.wrapError<ActivatedExtension>(errors[1]);
			}
			return undefined;
		});
E
Erich Gamma 已提交
277 278
	}

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

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

284 285 286 287 288
		return TPromise.join([
			globalState.whenReady,
			workspaceState.whenReady,
			this._storagePath.whenReady
		]).then(() => {
A
Alex Dima 已提交
289
			return Object.freeze(<IExtensionContext>{
E
Erich Gamma 已提交
290 291 292
				globalState,
				workspaceState,
				subscriptions: [],
A
Alex Dima 已提交
293
				get extensionPath() { return extensionDescription.extensionFolderPath; },
294
				storagePath: this._storagePath.value(extensionDescription),
295
				asAbsolutePath: (relativePath: string) => { return join(extensionDescription.extensionFolderPath, relativePath); }
E
Erich Gamma 已提交
296 297 298 299
			});
		});
	}

A
Alex Dima 已提交
300
	private static _callActivate(extensionModule: IExtensionModule, context: IExtensionContext): TPromise<ActivatedExtension> {
A
Alex Dima 已提交
301 302
		// Make sure the extension's surface is not undefined
		extensionModule = extensionModule || {
303 304 305 306
			activate: undefined,
			deactivate: undefined
		};

A
Alex Dima 已提交
307
		return this._callActivateOptional(extensionModule, context).then((extensionExports) => {
A
Alex Dima 已提交
308
			return new ActivatedExtension(false, extensionModule, extensionExports, context.subscriptions);
309 310 311
		});
	}

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

E
Erich Gamma 已提交
325 326
	// -- called by main thread

327
	public $activateByEvent(activationEvent: string): TPromise<void> {
A
Alex Dima 已提交
328
		return this.activateByEvent(activationEvent);
329 330 331
	}
}

A
Alex Dima 已提交
332
function loadCommonJSModule<T>(modulePath: string): TPromise<T> {
B
Benjamin Pasero 已提交
333
	let r: T = null;
E
Erich Gamma 已提交
334 335
	try {
		r = require.__$__nodeRequire<T>(modulePath);
B
Benjamin Pasero 已提交
336
	} catch (e) {
337
		return TPromise.wrapError<T>(e);
E
Erich Gamma 已提交
338
	}
A
Alex Dima 已提交
339
	return TPromise.as(r);
E
Erich Gamma 已提交
340
}
A
Alex Dima 已提交
341 342 343 344 345 346

function getTelemetryActivationEvent(extensionDescription: IExtensionDescription): any {
	let event = {
		id: extensionDescription.id,
		name: extensionDescription.name,
		publisherDisplayName: extensionDescription.publisher,
347 348
		activationEvents: extensionDescription.activationEvents ? extensionDescription.activationEvents.join(',') : null,
		isBuiltin: extensionDescription.isBuiltin
A
Alex Dima 已提交
349 350 351 352 353 354 355 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
	};

	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;
381
}