extHost.api.impl.ts 32.3 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';

7
import { Emitter } from 'vs/base/common/event';
8
import { TrieMap } from 'vs/base/common/map';
J
Johannes Rieken 已提交
9
import { score } from 'vs/editor/common/modes/languageSelector';
10
import * as Platform from 'vs/base/common/platform';
J
Johannes Rieken 已提交
11
import { IThreadService } from 'vs/workbench/services/thread/common/threadService';
E
Erich Gamma 已提交
12
import * as errors from 'vs/base/common/errors';
13 14
import product from 'vs/platform/node/product';
import pkg from 'vs/platform/node/package';
J
Johannes Rieken 已提交
15
import { ExtHostFileSystemEventService } from 'vs/workbench/api/node/extHostFileSystemEventService';
J
Johannes Rieken 已提交
16
import { ExtHostDocumentsAndEditors } from 'vs/workbench/api/node/extHostDocumentsAndEditors';
J
Johannes Rieken 已提交
17 18 19 20
import { ExtHostDocuments } from 'vs/workbench/api/node/extHostDocuments';
import { ExtHostDocumentSaveParticipant } from 'vs/workbench/api/node/extHostDocumentSaveParticipant';
import { ExtHostConfiguration } from 'vs/workbench/api/node/extHostConfiguration';
import { ExtHostDiagnostics } from 'vs/workbench/api/node/extHostDiagnostics';
S
Sandeep Somavarapu 已提交
21
import { ExtHostTreeViews } from 'vs/workbench/api/node/extHostTreeViews';
J
Johannes Rieken 已提交
22 23
import { ExtHostWorkspace } from 'vs/workbench/api/node/extHostWorkspace';
import { ExtHostQuickOpen } from 'vs/workbench/api/node/extHostQuickOpen';
24
import { ExtHostProgress } from 'vs/workbench/api/node/extHostProgress';
J
Joao Moreno 已提交
25
import { ExtHostSCM } from 'vs/workbench/api/node/extHostSCM';
J
Johannes Rieken 已提交
26 27 28 29 30 31
import { ExtHostHeapService } from 'vs/workbench/api/node/extHostHeapService';
import { ExtHostStatusBar } from 'vs/workbench/api/node/extHostStatusBar';
import { ExtHostCommands } from 'vs/workbench/api/node/extHostCommands';
import { ExtHostOutputService } from 'vs/workbench/api/node/extHostOutputService';
import { ExtHostTerminalService } from 'vs/workbench/api/node/extHostTerminalService';
import { ExtHostMessageService } from 'vs/workbench/api/node/extHostMessageService';
J
Johannes Rieken 已提交
32
import { ExtHostEditors } from 'vs/workbench/api/node/extHostTextEditors';
J
Johannes Rieken 已提交
33 34
import { ExtHostLanguages } from 'vs/workbench/api/node/extHostLanguages';
import { ExtHostLanguageFeatures } from 'vs/workbench/api/node/extHostLanguageFeatures';
35
import { ExtHostApiCommands } from 'vs/workbench/api/node/extHostApiCommands';
36
import { ExtHostTask } from 'vs/workbench/api/node/extHostTask';
37
import { ExtHostDebugService } from 'vs/workbench/api/node/extHostDebugService';
C
Christof Marti 已提交
38
import { ExtHostCredentials } from 'vs/workbench/api/node/extHostCredentials';
J
Johannes Rieken 已提交
39
import * as extHostTypes from 'vs/workbench/api/node/extHostTypes';
E
Erich Gamma 已提交
40 41 42
import URI from 'vs/base/common/uri';
import Severity from 'vs/base/common/severity';
import EditorCommon = require('vs/editor/common/editorCommon');
J
Johannes Rieken 已提交
43 44 45
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { ExtHostExtensionService } from 'vs/workbench/api/node/extHostExtensionService';
import { TPromise } from 'vs/base/common/winjs.base';
46
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
J
Johannes Rieken 已提交
47
import { CancellationTokenSource } from 'vs/base/common/cancellation';
48
import * as vscode from 'vscode';
E
Erich Gamma 已提交
49
import * as paths from 'vs/base/common/paths';
J
Johannes Rieken 已提交
50
import { realpath } from 'fs';
51
import { MainContext, ExtHostContext, InstanceCollection, IInitData } from './extHost.protocol';
52
import * as languageConfiguration from 'vs/editor/common/modes/languageConfiguration';
53
import { TextEditorCursorStyle } from 'vs/editor/common/config/editorOptions';
E
Erich Gamma 已提交
54

55
export interface IExtensionApiFactory {
56
	(extension: IExtensionDescription): typeof vscode;
57 58
}

59
function proposedApiFunction<T>(extension: IExtensionDescription, fn: T): T {
60
	if (extension.enableProposedApi) {
61 62 63
		return fn;
	} else {
		return <any>(() => {
64
			throw new Error(`[${extension.id}]: Proposed API is only available when running out of dev or with the following command line switch: --enable-proposed-api ${extension.id}`);
65 66 67 68
		});
	}
}

E
Erich Gamma 已提交
69
/**
70
 * This method instantiates and returns the extension API surface
E
Erich Gamma 已提交
71
 */
72 73 74 75 76 77
export function createApiFactory(
	initData: IInitData,
	threadService: IThreadService,
	extensionService: ExtHostExtensionService,
	telemetryService: ITelemetryService
): IExtensionApiFactory {
78

79 80
	// Addressable instances
	const col = new InstanceCollection();
81
	const extHostHeapService = col.define(ExtHostContext.ExtHostHeapService).set<ExtHostHeapService>(new ExtHostHeapService());
82
	const extHostDebugService = col.define(ExtHostContext.ExtHostDebugService).set<ExtHostDebugService>(new ExtHostDebugService(threadService));
J
Johannes Rieken 已提交
83 84
	const extHostDocumentsAndEditors = col.define(ExtHostContext.ExtHostDocumentsAndEditors).set<ExtHostDocumentsAndEditors>(new ExtHostDocumentsAndEditors(threadService));
	const extHostDocuments = col.define(ExtHostContext.ExtHostDocuments).set<ExtHostDocuments>(new ExtHostDocuments(threadService, extHostDocumentsAndEditors));
85
	const extHostDocumentSaveParticipant = col.define(ExtHostContext.ExtHostDocumentSaveParticipant).set<ExtHostDocumentSaveParticipant>(new ExtHostDocumentSaveParticipant(extHostDocuments, threadService.get(MainContext.MainThreadWorkspace)));
J
Johannes Rieken 已提交
86
	const extHostEditors = col.define(ExtHostContext.ExtHostEditors).set<ExtHostEditors>(new ExtHostEditors(threadService, extHostDocumentsAndEditors));
87
	const extHostCommands = col.define(ExtHostContext.ExtHostCommands).set<ExtHostCommands>(new ExtHostCommands(threadService, extHostHeapService));
S
Sandeep Somavarapu 已提交
88
	const extHostTreeViews = col.define(ExtHostContext.ExtHostTreeViews).set<ExtHostTreeViews>(new ExtHostTreeViews(threadService.get(MainContext.MainThreadTreeViews), extHostCommands));
89
	const extHostWorkspace = col.define(ExtHostContext.ExtHostWorkspace).set<ExtHostWorkspace>(new ExtHostWorkspace(threadService, initData.workspace));
J
Johannes Rieken 已提交
90
	const extHostConfiguration = col.define(ExtHostContext.ExtHostConfiguration).set<ExtHostConfiguration>(new ExtHostConfiguration(threadService.get(MainContext.MainThreadConfiguration), extHostWorkspace, initData.configuration));
91
	const extHostDiagnostics = col.define(ExtHostContext.ExtHostDiagnostics).set<ExtHostDiagnostics>(new ExtHostDiagnostics(threadService));
92
	const languageFeatures = col.define(ExtHostContext.ExtHostLanguageFeatures).set<ExtHostLanguageFeatures>(new ExtHostLanguageFeatures(threadService, extHostDocuments, extHostCommands, extHostHeapService, extHostDiagnostics));
93 94 95
	const extHostFileSystemEvent = col.define(ExtHostContext.ExtHostFileSystemEventService).set<ExtHostFileSystemEventService>(new ExtHostFileSystemEventService());
	const extHostQuickOpen = col.define(ExtHostContext.ExtHostQuickOpen).set<ExtHostQuickOpen>(new ExtHostQuickOpen(threadService));
	const extHostTerminalService = col.define(ExtHostContext.ExtHostTerminalService).set<ExtHostTerminalService>(new ExtHostTerminalService(threadService));
J
Joao Moreno 已提交
96
	const extHostSCM = col.define(ExtHostContext.ExtHostSCM).set<ExtHostSCM>(new ExtHostSCM(threadService, extHostCommands));
97
	const extHostTask = col.define(ExtHostContext.ExtHostTask).set<ExtHostTask>(new ExtHostTask(threadService));
C
Christof Marti 已提交
98
	const extHostCredentials = col.define(ExtHostContext.ExtHostCredentials).set<ExtHostCredentials>(new ExtHostCredentials(threadService));
99 100
	col.define(ExtHostContext.ExtHostExtensionService).set(extensionService);
	col.finish(false, threadService);
101

102 103 104
	// Other instances
	const extHostMessageService = new ExtHostMessageService(threadService);
	const extHostStatusBar = new ExtHostStatusBar(threadService);
105
	const extHostProgress = new ExtHostProgress(threadService.get(MainContext.MainThreadProgress));
106 107
	const extHostOutputService = new ExtHostOutputService(threadService);
	const extHostLanguages = new ExtHostLanguages(threadService);
108

109 110
	// Register API-ish commands
	ExtHostApiCommands.register(extHostCommands);
111

112
	return function (extension: IExtensionDescription): typeof vscode {
113

114
		if (extension.enableProposedApi && !extension.isBuiltin) {
115

116 117 118 119
			if (
				!initData.environment.enableProposedApiForAll &&
				initData.environment.enableProposedApiFor.indexOf(extension.id) < 0
			) {
120
				extension.enableProposedApi = false;
121
				console.error(`Extension '${extension.id} cannot use PROPOSED API (must started out of dev or enabled via --enable-proposed-api)`);
122 123

			} else {
124 125 126
				// proposed api is available when developing or when an extension was explicitly
				// spelled out via a command line argument
				console.warn(`Extension '${extension.id}' uses PROPOSED API which is subject to change and removal without notice.`);
127
			}
128 129
		}

130 131 132 133 134 135 136 137 138 139 140 141 142 143
		const apiUsage = new class {
			private _seen = new Set<string>();
			publicLog(apiName: string) {
				if (this._seen.has(apiName)) {
					return undefined;
				}
				this._seen.add(apiName);
				return telemetryService.publicLog('apiUsage', {
					name: apiName,
					extension: extension.id
				});
			}
		};

144 145
		// namespace: commands
		const commands: typeof vscode.commands = {
146 147
			registerCommand<T>(id: string, command: <T>(...args: any[]) => T | Thenable<T>, thisArgs?: any): vscode.Disposable {
				return extHostCommands.registerCommand(id, command, thisArgs);
148
			},
149
			registerTextEditorCommand(id: string, callback: (textEditor: vscode.TextEditor, edit: vscode.TextEditorEdit, ...args: any[]) => void, thisArg?: any): vscode.Disposable {
150
				return extHostCommands.registerCommand(id, (...args: any[]): any => {
151 152 153
					let activeTextEditor = extHostEditors.getActiveTextEditor();
					if (!activeTextEditor) {
						console.warn('Cannot execute ' + id + ' because there is no active text editor.');
154
						return undefined;
155
					}
156 157 158 159 160 161 162 163 164 165

					return activeTextEditor.edit((edit: vscode.TextEditorEdit) => {
						args.unshift(activeTextEditor, edit);
						callback.apply(thisArg, args);

					}).then((result) => {
						if (!result) {
							console.warn('Edits from command ' + id + ' were not applied.');
						}
					}, (err) => {
166
						console.warn('An error occurred while running command ' + id, err);
167
					});
168
				});
169 170
			},
			registerDiffInformationCommand: proposedApiFunction(extension, (id: string, callback: (diff: vscode.LineChange[], ...args: any[]) => any, thisArg?: any): vscode.Disposable => {
171 172 173 174 175 176 177 178 179 180
				return extHostCommands.registerCommand(id, async (...args: any[]) => {
					let activeTextEditor = extHostEditors.getActiveTextEditor();
					if (!activeTextEditor) {
						console.warn('Cannot execute ' + id + ' because there is no active text editor.');
						return undefined;
					}

					const diff = await extHostEditors.getDiffInformation(activeTextEditor.id);
					callback.apply(thisArg, [diff, ...args]);
				});
181
			}),
182
			executeCommand<T>(id: string, ...args: any[]): Thenable<T> {
183
				return extHostCommands.executeCommand<T>(id, ...args);
184
			},
185 186 187
			getCommands(filterInternal: boolean = false): Thenable<string[]> {
				return extHostCommands.getCommands(filterInternal);
			}
188
		};
189

190 191
		// namespace: env
		const env: typeof vscode.env = Object.freeze({
192 193
			get machineId() { return initData.telemetryInfo.machineId; },
			get sessionId() { return initData.telemetryInfo.sessionId; },
194 195 196
			get language() { return Platform.language; },
			get appName() { return product.nameLong; }
		});
E
Erich Gamma 已提交
197

198 199 200
		// namespace: extensions
		const extensions: typeof vscode.extensions = {
			getExtension(extensionId: string): Extension<any> {
201
				let desc = extensionService.getExtensionDescription(extensionId);
202 203 204
				if (desc) {
					return new Extension(extensionService, desc);
				}
205
				return undefined;
206 207
			},
			get all(): Extension<any>[] {
208
				return extensionService.getAllExtensionDescriptions().map((desc) => new Extension(extensionService, desc));
E
Erich Gamma 已提交
209
			}
210
		};
E
Erich Gamma 已提交
211

212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
		// namespace: languages
		const languages: typeof vscode.languages = {
			createDiagnosticCollection(name?: string): vscode.DiagnosticCollection {
				return extHostDiagnostics.createDiagnosticCollection(name);
			},
			getLanguages(): TPromise<string[]> {
				return extHostLanguages.getLanguages();
			},
			match(selector: vscode.DocumentSelector, document: vscode.TextDocument): number {
				return score(selector, <any>document.uri, document.languageId);
			},
			registerCodeActionsProvider(selector: vscode.DocumentSelector, provider: vscode.CodeActionProvider): vscode.Disposable {
				return languageFeatures.registerCodeActionProvider(selector, provider);
			},
			registerCodeLensProvider(selector: vscode.DocumentSelector, provider: vscode.CodeLensProvider): vscode.Disposable {
				return languageFeatures.registerCodeLensProvider(selector, provider);
			},
			registerDefinitionProvider(selector: vscode.DocumentSelector, provider: vscode.DefinitionProvider): vscode.Disposable {
				return languageFeatures.registerDefinitionProvider(selector, provider);
			},
M
Matt Bierner 已提交
232 233
			registerImplementationProvider(selector: vscode.DocumentSelector, provider: vscode.ImplementationProvider): vscode.Disposable {
				return languageFeatures.registerImplementationProvider(selector, provider);
234
			},
235 236 237
			registerTypeDefinitionProvider(selector: vscode.DocumentSelector, provider: vscode.TypeDefinitionProvider): vscode.Disposable {
				return languageFeatures.registerTypeDefinitionProvider(selector, provider);
			},
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
			registerHoverProvider(selector: vscode.DocumentSelector, provider: vscode.HoverProvider): vscode.Disposable {
				return languageFeatures.registerHoverProvider(selector, provider);
			},
			registerDocumentHighlightProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentHighlightProvider): vscode.Disposable {
				return languageFeatures.registerDocumentHighlightProvider(selector, provider);
			},
			registerReferenceProvider(selector: vscode.DocumentSelector, provider: vscode.ReferenceProvider): vscode.Disposable {
				return languageFeatures.registerReferenceProvider(selector, provider);
			},
			registerRenameProvider(selector: vscode.DocumentSelector, provider: vscode.RenameProvider): vscode.Disposable {
				return languageFeatures.registerRenameProvider(selector, provider);
			},
			registerDocumentSymbolProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentSymbolProvider): vscode.Disposable {
				return languageFeatures.registerDocumentSymbolProvider(selector, provider);
			},
			registerWorkspaceSymbolProvider(provider: vscode.WorkspaceSymbolProvider): vscode.Disposable {
				return languageFeatures.registerWorkspaceSymbolProvider(provider);
			},
			registerDocumentFormattingEditProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentFormattingEditProvider): vscode.Disposable {
				return languageFeatures.registerDocumentFormattingEditProvider(selector, provider);
			},
			registerDocumentRangeFormattingEditProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentRangeFormattingEditProvider): vscode.Disposable {
				return languageFeatures.registerDocumentRangeFormattingEditProvider(selector, provider);
			},
			registerOnTypeFormattingEditProvider(selector: vscode.DocumentSelector, provider: vscode.OnTypeFormattingEditProvider, firstTriggerCharacter: string, ...moreTriggerCharacters: string[]): vscode.Disposable {
				return languageFeatures.registerOnTypeFormattingEditProvider(selector, provider, [firstTriggerCharacter].concat(moreTriggerCharacters));
			},
			registerSignatureHelpProvider(selector: vscode.DocumentSelector, provider: vscode.SignatureHelpProvider, ...triggerCharacters: string[]): vscode.Disposable {
				return languageFeatures.registerSignatureHelpProvider(selector, provider, triggerCharacters);
			},
			registerCompletionItemProvider(selector: vscode.DocumentSelector, provider: vscode.CompletionItemProvider, ...triggerCharacters: string[]): vscode.Disposable {
269
				return languageFeatures.registerCompletionItemProvider(selector, provider, triggerCharacters);
270 271 272 273 274 275
			},
			registerDocumentLinkProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentLinkProvider): vscode.Disposable {
				return languageFeatures.registerDocumentLinkProvider(selector, provider);
			},
			setLanguageConfiguration: (language: string, configuration: vscode.LanguageConfiguration): vscode.Disposable => {
				return languageFeatures.setLanguageConfiguration(language, configuration);
276 277 278 279 280
			},
			// proposed API
			registerColorProvider: proposedApiFunction(extension, (selector: vscode.DocumentSelector, provider: vscode.DocumentColorProvider) => {
				return languageFeatures.registerColorProvider(selector, provider);
			})
281
		};
E
Erich Gamma 已提交
282

283 284 285 286 287 288 289 290
		// namespace: window
		const window: typeof vscode.window = {
			get activeTextEditor() {
				return extHostEditors.getActiveTextEditor();
			},
			get visibleTextEditors() {
				return extHostEditors.getVisibleTextEditors();
			},
J
Johannes Rieken 已提交
291
			showTextDocument(documentOrUri: vscode.TextDocument | vscode.Uri, columnOrOptions?: vscode.ViewColumn | vscode.TextDocumentShowOptions, preserveFocus?: boolean): TPromise<vscode.TextEditor> {
B
Benjamin Pasero 已提交
292
				let documentPromise: TPromise<vscode.TextDocument>;
J
Johannes Rieken 已提交
293 294
				if (URI.isUri(documentOrUri)) {
					documentPromise = TPromise.wrap(workspace.openTextDocument(documentOrUri));
B
Benjamin Pasero 已提交
295
				} else {
J
Johannes Rieken 已提交
296
					documentPromise = TPromise.wrap(<vscode.TextDocument>documentOrUri);
B
Benjamin Pasero 已提交
297 298 299 300
				}
				return documentPromise.then(document => {
					return extHostEditors.showTextDocument(document, columnOrOptions, preserveFocus);
				});
301 302 303 304
			},
			createTextEditorDecorationType(options: vscode.DecorationRenderOptions): vscode.TextEditorDecorationType {
				return extHostEditors.createTextEditorDecorationType(options);
			},
305 306 307
			onDidChangeActiveTextEditor(listener, thisArg?, disposables?) {
				return extHostEditors.onDidChangeActiveTextEditor(listener, thisArg, disposables);
			},
308 309 310
			onDidChangeVisibleTextEditors(listener, thisArg, disposables) {
				return extHostEditors.onDidChangeVisibleTextEditors(listener, thisArg, disposables);
			},
311
			onDidChangeTextEditorSelection(listener: (e: vscode.TextEditorSelectionChangeEvent) => any, thisArgs?: any, disposables?: extHostTypes.Disposable[]) {
312 313
				return extHostEditors.onDidChangeTextEditorSelection(listener, thisArgs, disposables);
			},
314
			onDidChangeTextEditorOptions(listener: (e: vscode.TextEditorOptionsChangeEvent) => any, thisArgs?: any, disposables?: extHostTypes.Disposable[]) {
315 316 317 318 319
				return extHostEditors.onDidChangeTextEditorOptions(listener, thisArgs, disposables);
			},
			onDidChangeTextEditorViewColumn(listener, thisArg?, disposables?) {
				return extHostEditors.onDidChangeTextEditorViewColumn(listener, thisArg, disposables);
			},
320 321 322
			onDidCloseTerminal(listener, thisArg?, disposables?) {
				return extHostTerminalService.onDidCloseTerminal(listener, thisArg, disposables);
			},
J
Joao Moreno 已提交
323 324
			showInformationMessage(message, first, ...rest) {
				return extHostMessageService.showMessage(Severity.Info, message, first, rest);
325
			},
J
Joao Moreno 已提交
326 327
			showWarningMessage(message, first, ...rest) {
				return extHostMessageService.showMessage(Severity.Warning, message, first, rest);
328
			},
J
Joao Moreno 已提交
329 330
			showErrorMessage(message, first, ...rest) {
				return extHostMessageService.showMessage(Severity.Error, message, first, rest);
331
			},
332
			showQuickPick(items: any, options: vscode.QuickPickOptions, token?: vscode.CancellationToken) {
333 334 335 336 337 338
				return extHostQuickOpen.showQuickPick(items, options, token);
			},
			showInputBox(options?: vscode.InputBoxOptions, token?: vscode.CancellationToken) {
				return extHostQuickOpen.showInput(options, token);
			},
			createStatusBarItem(position?: vscode.StatusBarAlignment, priority?: number): vscode.StatusBarItem {
339
				return extHostStatusBar.createStatusBarEntry(extension.id, <number>position, priority);
340 341 342 343
			},
			setStatusBarMessage(text: string, timeoutOrThenable?: number | Thenable<any>): vscode.Disposable {
				return extHostStatusBar.setStatusBarMessage(text, timeoutOrThenable);
			},
344
			withScmProgress<R>(task: (progress: vscode.Progress<number>) => Thenable<R>) {
345
				console.warn(`[Deprecation Warning] function 'withScmProgress' is deprecated and should no longer be used. Use 'withProgress' instead.`);
346
				return extHostProgress.withProgress(extension, { location: extHostTypes.ProgressLocation.SourceControl }, (progress, token) => task({ report(n: number) { /*noop*/ } }));
J
Johannes Rieken 已提交
347 348 349
			},
			withProgress<R>(options: vscode.ProgressOptions, task: (progress: vscode.Progress<{ message?: string; percentage?: number }>) => Thenable<R>) {
				return extHostProgress.withProgress(extension, options, task);
350
			},
351 352 353
			createOutputChannel(name: string): vscode.OutputChannel {
				return extHostOutputService.createOutputChannel(name);
			},
354 355 356 357
			createTerminal(nameOrOptions: vscode.TerminalOptions | string, shellPath?: string, shellArgs?: string[]): vscode.Terminal {
				if (typeof nameOrOptions === 'object') {
					return extHostTerminalService.createTerminalFromOptions(<vscode.TerminalOptions>nameOrOptions);
				}
D
Daniel Imms 已提交
358
				return extHostTerminalService.createTerminal(<string>nameOrOptions, shellPath, shellArgs);
359
			},
S
Sandeep Somavarapu 已提交
360 361 362
			registerTreeDataProvider(viewId: string, treeDataProvider: vscode.TreeDataProvider<any>): vscode.Disposable {
				return extHostTreeViews.registerTreeDataProvider(viewId, treeDataProvider);
			},
363 364
			// proposed API
			sampleFunction: proposedApiFunction(extension, () => {
J
Joao Moreno 已提交
365
				return extHostMessageService.showMessage(Severity.Info, 'Hello Proposed Api!', {}, []);
366
			}),
367
		};
E
Erich Gamma 已提交
368

369 370 371
		// namespace: workspace
		const workspace: typeof vscode.workspace = {
			get rootPath() {
372
				apiUsage.publicLog('workspace#rootPath');
373 374 375 376 377
				return extHostWorkspace.getPath();
			},
			set rootPath(value) {
				throw errors.readonly();
			},
378 379
			getWorkspaceFolder(resource) {
				return extHostWorkspace.getWorkspaceFolder(resource);
380
			},
381
			get workspaceFolders() {
382
				apiUsage.publicLog('workspace#workspaceFolders');
383
				return extHostWorkspace.getWorkspaceFolders();
384
			},
385
			onDidChangeWorkspaceFolders: function (listener, thisArgs?, disposables?) {
386
				apiUsage.publicLog('workspace#onDidChangeWorkspaceFolders');
387
				return extHostWorkspace.onDidChangeWorkspace(listener, thisArgs, disposables);
388
			},
J
Johannes Rieken 已提交
389 390
			asRelativePath: (pathOrUri, includeWorkspace) => {
				return extHostWorkspace.getRelativePath(pathOrUri, includeWorkspace);
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
			},
			findFiles: (include, exclude, maxResults?, token?) => {
				return extHostWorkspace.findFiles(include, exclude, maxResults, token);
			},
			saveAll: (includeUntitled?) => {
				return extHostWorkspace.saveAll(includeUntitled);
			},
			applyEdit(edit: vscode.WorkspaceEdit): TPromise<boolean> {
				return extHostWorkspace.appyEdit(edit);
			},
			createFileSystemWatcher: (pattern, ignoreCreate, ignoreChange, ignoreDelete): vscode.FileSystemWatcher => {
				return extHostFileSystemEvent.createFileSystemWatcher(pattern, ignoreCreate, ignoreChange, ignoreDelete);
			},
			get textDocuments() {
				return extHostDocuments.getAllDocumentData().map(data => data.document);
			},
			set textDocuments(value) {
				throw errors.readonly();
			},
410
			openTextDocument(uriOrFileNameOrOptions?: vscode.Uri | string | { language?: string; content?: string; }) {
B
Benjamin Pasero 已提交
411 412
				let uriPromise: TPromise<URI>;

413
				let options = uriOrFileNameOrOptions as { language?: string; content?: string; };
B
Benjamin Pasero 已提交
414 415 416 417 418 419
				if (!options || typeof options.language === 'string') {
					uriPromise = extHostDocuments.createDocumentData(options);
				} else if (typeof uriOrFileNameOrOptions === 'string') {
					uriPromise = TPromise.as(URI.file(uriOrFileNameOrOptions));
				} else if (uriOrFileNameOrOptions instanceof URI) {
					uriPromise = TPromise.as(<URI>uriOrFileNameOrOptions);
420
				} else {
B
Benjamin Pasero 已提交
421
					throw new Error('illegal argument - uriOrFileNameOrOptions');
422
				}
B
Benjamin Pasero 已提交
423 424 425 426 427 428

				return uriPromise.then(uri => {
					return extHostDocuments.ensureDocumentData(uri).then(() => {
						const data = extHostDocuments.getDocumentData(uri);
						return data && data.document;
					});
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
				});
			},
			registerTextDocumentContentProvider(scheme: string, provider: vscode.TextDocumentContentProvider) {
				return extHostDocuments.registerTextDocumentContentProvider(scheme, provider);
			},
			onDidOpenTextDocument: (listener, thisArgs?, disposables?) => {
				return extHostDocuments.onDidAddDocument(listener, thisArgs, disposables);
			},
			onDidCloseTextDocument: (listener, thisArgs?, disposables?) => {
				return extHostDocuments.onDidRemoveDocument(listener, thisArgs, disposables);
			},
			onDidChangeTextDocument: (listener, thisArgs?, disposables?) => {
				return extHostDocuments.onDidChangeDocument(listener, thisArgs, disposables);
			},
			onDidSaveTextDocument: (listener, thisArgs?, disposables?) => {
				return extHostDocuments.onDidSaveDocument(listener, thisArgs, disposables);
			},
			onWillSaveTextDocument: (listener, thisArgs?, disposables?) => {
				return extHostDocumentSaveParticipant.onWillSaveTextDocumentEvent(listener, thisArgs, disposables);
448
			},
449
			onDidChangeConfiguration: (listener: (_: any) => any, thisArgs?: any, disposables?: extHostTypes.Disposable[]) => {
450 451
				return extHostConfiguration.onDidChangeConfiguration(listener, thisArgs, disposables);
			},
S
Sandeep Somavarapu 已提交
452 453
			getConfiguration: (section?: string, resource?: vscode.Uri): vscode.WorkspaceConfiguration => {
				return extHostConfiguration.getConfiguration(section, <URI>resource);
454
			},
455
			registerTaskProvider: (type: string, provider: vscode.TaskProvider) => {
456
				return extHostTask.registerTaskProvider(extension, provider);
J
Johannes Rieken 已提交
457 458 459 460
			},
			registerFileSystemProvider: proposedApiFunction(extension, (authority, provider) => {
				return extHostWorkspace.registerFileSystemProvider(authority, provider);
			})
461
		};
462

463 464
		// namespace: scm
		const scm: typeof vscode.scm = {
465 466
			get inputBox() {
				return extHostSCM.inputBox;
467
			},
J
Joao Moreno 已提交
468
			createSourceControl(id: string, label: string) {
469 470
				telemetryService.publicLog('registerSCMProvider', {
					extensionId: extension.id,
J
Joao Moreno 已提交
471 472
					providerId: id,
					providerLabel: label
473 474
				});

J
Joao Moreno 已提交
475
				return extHostSCM.createSourceControl(id, label);
J
Joao Moreno 已提交
476
			}
477
		};
J
Joao Moreno 已提交
478

479 480
		// namespace: debug
		const debug: typeof vscode.debug = {
481 482 483
			get activeDebugSession() {
				return extHostDebugService.activeDebugSession;
			},
484
			startDebugging(folder: vscode.WorkspaceFolder | undefined, nameOrConfig: string | vscode.DebugConfiguration) {
485
				return extHostDebugService.startDebugging(folder, nameOrConfig);
486
			},
487 488
			onDidStartDebugSession(listener, thisArg?, disposables?) {
				return extHostDebugService.onDidStartDebugSession(listener, thisArg, disposables);
489 490
			},
			onDidTerminateDebugSession(listener, thisArg?, disposables?) {
491
				return extHostDebugService.onDidTerminateDebugSession(listener, thisArg, disposables);
492
			},
A
Andre Weinand 已提交
493
			onDidChangeActiveDebugSession(listener, thisArg?, disposables?) {
494
				return extHostDebugService.onDidChangeActiveDebugSession(listener, thisArg, disposables);
A
Andre Weinand 已提交
495 496
			},
			onDidReceiveDebugSessionCustomEvent(listener, thisArg?, disposables?) {
A
Andre Weinand 已提交
497
				return extHostDebugService.onDidReceiveDebugSessionCustomEvent(listener, thisArg, disposables);
A
Andre Weinand 已提交
498
			}
499 500
		};

C
Christof Marti 已提交
501 502 503 504 505 506 507 508 509 510 511
		// namespace: credentials
		const credentials: typeof vscode.credentials = {
			readSecret(service: string, account: string): Thenable<string | undefined> {
				return extHostCredentials.readSecret(service, account);
			},
			writeSecret(service: string, account: string, secret: string): Thenable<void> {
				return extHostCredentials.writeSecret(service, account, secret);
			},
			deleteSecret(service: string, account: string): Thenable<boolean> {
				return extHostCredentials.deleteSecret(service, account);
			}
512 513 514
		};


515
		const api: typeof vscode = {
516 517 518 519 520 521 522 523
			version: pkg.version,
			// namespaces
			commands,
			env,
			extensions,
			languages,
			window,
			workspace,
J
Joao Moreno 已提交
524
			scm,
525
			debug,
526
			credentials,
527 528 529
			// types
			CancellationTokenSource: CancellationTokenSource,
			CodeLens: extHostTypes.CodeLens,
530 531 532
			Color: extHostTypes.Color,
			ColorInfo: extHostTypes.ColorInfo,
			EndOfLine: extHostTypes.EndOfLine,
533 534 535
			CompletionItem: extHostTypes.CompletionItem,
			CompletionItemKind: extHostTypes.CompletionItemKind,
			CompletionList: extHostTypes.CompletionList,
536 537 538 539 540
			Diagnostic: extHostTypes.Diagnostic,
			DiagnosticSeverity: extHostTypes.DiagnosticSeverity,
			Disposable: extHostTypes.Disposable,
			DocumentHighlight: extHostTypes.DocumentHighlight,
			DocumentHighlightKind: extHostTypes.DocumentHighlightKind,
541
			DocumentLink: extHostTypes.DocumentLink,
542 543
			EventEmitter: Emitter,
			Hover: extHostTypes.Hover,
544
			IndentAction: languageConfiguration.IndentAction,
545
			Location: extHostTypes.Location,
546
			OverviewRulerLane: EditorCommon.OverviewRulerLane,
547 548 549 550 551 552 553 554 555 556 557 558
			ParameterInformation: extHostTypes.ParameterInformation,
			Position: extHostTypes.Position,
			Range: extHostTypes.Range,
			Selection: extHostTypes.Selection,
			SignatureHelp: extHostTypes.SignatureHelp,
			SignatureInformation: extHostTypes.SignatureInformation,
			SnippetString: extHostTypes.SnippetString,
			StatusBarAlignment: extHostTypes.StatusBarAlignment,
			SymbolInformation: extHostTypes.SymbolInformation,
			SymbolKind: extHostTypes.SymbolKind,
			TextDocumentSaveReason: extHostTypes.TextDocumentSaveReason,
			TextEdit: extHostTypes.TextEdit,
559
			TextEditorCursorStyle: TextEditorCursorStyle,
560
			TextEditorLineNumbersStyle: extHostTypes.TextEditorLineNumbersStyle,
561
			TextEditorRevealType: extHostTypes.TextEditorRevealType,
562
			TextEditorSelectionChangeKind: extHostTypes.TextEditorSelectionChangeKind,
563
			DecorationRangeBehavior: extHostTypes.DecorationRangeBehavior,
564
			Uri: <any>URI,
565 566
			ViewColumn: extHostTypes.ViewColumn,
			WorkspaceEdit: extHostTypes.WorkspaceEdit,
J
Johannes Rieken 已提交
567
			ProgressLocation: extHostTypes.ProgressLocation,
S
Sandeep Somavarapu 已提交
568
			TreeItemCollapsibleState: extHostTypes.TreeItemCollapsibleState,
S
Sandeep Somavarapu 已提交
569
			TreeItem: extHostTypes.TreeItem,
570
			ThemeColor: extHostTypes.ThemeColor,
J
Joao Moreno 已提交
571
			// functions
572
			TaskRevealKind: extHostTypes.TaskRevealKind,
573
			TaskPanelKind: extHostTypes.TaskPanelKind,
574
			TaskGroup: extHostTypes.TaskGroup,
D
Dirk Baeumer 已提交
575 576
			ProcessExecution: extHostTypes.ProcessExecution,
			ShellExecution: extHostTypes.ShellExecution,
S
Sandeep Somavarapu 已提交
577 578
			Task: extHostTypes.Task,
			ConfigurationTarget: extHostTypes.ConfigurationTarget
579
		};
580 581 582 583
		if (!extension.enableProposedApi) {
			delete api.credentials; // Instead of error to avoid #31854
		}
		return api;
584
	};
E
Erich Gamma 已提交
585 586 587 588
}

class Extension<T> implements vscode.Extension<T> {

A
Alex Dima 已提交
589
	private _extensionService: ExtHostExtensionService;
E
Erich Gamma 已提交
590 591 592 593 594

	public id: string;
	public extensionPath: string;
	public packageJSON: any;

J
Johannes Rieken 已提交
595
	constructor(extensionService: ExtHostExtensionService, description: IExtensionDescription) {
A
Alex Dima 已提交
596
		this._extensionService = extensionService;
E
Erich Gamma 已提交
597 598 599 600 601 602
		this.id = description.id;
		this.extensionPath = paths.normalize(description.extensionFolderPath, true);
		this.packageJSON = description;
	}

	get isActive(): boolean {
A
Alex Dima 已提交
603
		return this._extensionService.isActivated(this.id);
E
Erich Gamma 已提交
604 605 606
	}

	get exports(): T {
A
Alex Dima 已提交
607
		return <T>this._extensionService.get(this.id);
E
Erich Gamma 已提交
608 609 610
	}

	activate(): Thenable<T> {
A
Alex Dima 已提交
611
		return this._extensionService.activateById(this.id).then(() => this.exports);
E
Erich Gamma 已提交
612 613 614
	}
}

J
Johannes Rieken 已提交
615 616 617
export function initializeExtensionApi(extensionService: ExtHostExtensionService, apiFactory: IExtensionApiFactory): TPromise<void> {
	return createExtensionPathIndex(extensionService).then(trie => defineAPI(apiFactory, trie));
}
618

J
Johannes Rieken 已提交
619
function createExtensionPathIndex(extensionService: ExtHostExtensionService): TPromise<TrieMap<IExtensionDescription>> {
620 621

	// create trie to enable fast 'filename -> extension id' look up
622
	const trie = new TrieMap<IExtensionDescription>(TrieMap.PathSplitter);
J
Johannes Rieken 已提交
623 624
	const extensions = extensionService.getAllExtensionDescriptions().map(ext => {
		if (!ext.main) {
625
			return undefined;
626
		}
J
Johannes Rieken 已提交
627 628 629 630 631
		return new TPromise((resolve, reject) => {
			realpath(ext.extensionFolderPath, (err, path) => {
				if (err) {
					reject(err);
				} else {
J
Johannes Rieken 已提交
632
					trie.insert(path, ext);
J
Johannes Rieken 已提交
633 634 635 636 637 638 639 640 641 642 643 644
					resolve(void 0);
				}
			});
		});
	});

	return TPromise.join(extensions).then(() => trie);
}

function defineAPI(factory: IExtensionApiFactory, extensionPaths: TrieMap<IExtensionDescription>): void {

	// each extension is meant to get its own api implementation
J
Johannes Rieken 已提交
645
	const extApiImpl = new Map<string, typeof vscode>();
J
Johannes Rieken 已提交
646
	let defaultApiImpl: typeof vscode;
647 648 649

	const node_module = <any>require.__$__nodeRequire('module');
	const original = node_module._load;
E
Erich Gamma 已提交
650
	node_module._load = function load(request, parent, isMain) {
651 652 653 654 655
		if (request !== 'vscode') {
			return original.apply(this, arguments);
		}

		// get extension id from filename and api for extension
J
Johannes Rieken 已提交
656
		const ext = extensionPaths.findSubstr(parent.filename);
657
		if (ext) {
J
Johannes Rieken 已提交
658
			let apiImpl = extApiImpl.get(ext.id);
659
			if (!apiImpl) {
J
Johannes Rieken 已提交
660 661
				apiImpl = factory(ext);
				extApiImpl.set(ext.id, apiImpl);
662 663 664 665 666 667
			}
			return apiImpl;
		}

		// fall back to a default implementation
		if (!defaultApiImpl) {
668
			defaultApiImpl = factory(nullExtensionDescription);
E
Erich Gamma 已提交
669
		}
670
		return defaultApiImpl;
E
Erich Gamma 已提交
671 672
	};
}
673 674 675 676 677 678 679 680 681 682 683 684 685 686 687

const nullExtensionDescription: IExtensionDescription = {
	id: 'nullExtensionDescription',
	name: 'Null Extension Description',
	publisher: 'vscode',
	activationEvents: undefined,
	contributes: undefined,
	enableProposedApi: false,
	engines: undefined,
	extensionDependencies: undefined,
	extensionFolderPath: undefined,
	isBuiltin: false,
	main: undefined,
	version: undefined
};