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

7
import { Emitter } from 'vs/base/common/event';
8
import { TernarySearchTree } 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';
E
Erich Gamma 已提交
11
import * as errors from 'vs/base/common/errors';
12 13
import product from 'vs/platform/node/product';
import pkg from 'vs/platform/node/package';
J
Johannes Rieken 已提交
14
import { ExtHostFileSystemEventService } from 'vs/workbench/api/node/extHostFileSystemEventService';
J
Johannes Rieken 已提交
15
import { ExtHostDocumentsAndEditors } from 'vs/workbench/api/node/extHostDocumentsAndEditors';
J
Johannes Rieken 已提交
16
import { ExtHostDocuments } from 'vs/workbench/api/node/extHostDocuments';
17
import { ExtHostDocumentContentProvider } from 'vs/workbench/api/node/extHostDocumentContentProviders';
J
Johannes Rieken 已提交
18 19 20
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';
38
import { ExtHostWindow } from 'vs/workbench/api/node/extHostWindow';
J
Johannes Rieken 已提交
39
import * as extHostTypes from 'vs/workbench/api/node/extHostTypes';
E
Erich Gamma 已提交
40 41
import URI from 'vs/base/common/uri';
import Severity from 'vs/base/common/severity';
42
import { IExtensionDescription } from 'vs/workbench/services/extensions/common/extensions';
J
Johannes Rieken 已提交
43 44 45
import { ExtHostExtensionService } from 'vs/workbench/api/node/extHostExtensionService';
import { TPromise } from 'vs/base/common/winjs.base';
import { CancellationTokenSource } from 'vs/base/common/cancellation';
46
import * as vscode from 'vscode';
E
Erich Gamma 已提交
47
import * as paths from 'vs/base/common/paths';
48
import { MainContext, ExtHostContext, IInitData, IExtHostContext } from './extHost.protocol';
49
import * as languageConfiguration from 'vs/editor/common/modes/languageConfiguration';
50
import { TextEditorCursorStyle } from 'vs/editor/common/config/editorOptions';
A
Alex Dima 已提交
51
import { ProxyIdentifier } from 'vs/workbench/services/extensions/node/proxyIdentifier';
B
Benjamin Pasero 已提交
52
import { ExtHostDialogs } from 'vs/workbench/api/node/extHostDialogs';
53
import { ExtHostFileSystem } from 'vs/workbench/api/node/extHostFileSystem';
54
import { ExtHostDecorations } from 'vs/workbench/api/node/extHostDecorations';
55
import { toGlobPattern, toLanguageSelector } from 'vs/workbench/api/node/extHostTypeConverters';
A
Alex Dima 已提交
56
import { ExtensionActivatedByAPI } from 'vs/workbench/api/node/extHostExtensionActivator';
57
import { isFalsyOrEmpty } from 'vs/base/common/arrays';
A
Alex Dima 已提交
58
import { OverviewRulerLane } from 'vs/editor/common/model';
59
import { ExtHostLogService } from 'vs/workbench/api/node/extHostLogService';
M
Matt Bierner 已提交
60
import { ExtHostWebviews } from 'vs/workbench/api/node/extHostWebview';
E
Erich Gamma 已提交
61

62
export interface IExtensionApiFactory {
63
	(extension: IExtensionDescription): typeof vscode;
64 65
}

66 67 68 69 70 71 72 73 74 75
export function checkProposedApiEnabled(extension: IExtensionDescription): void {
	if (!extension.enableProposedApi) {
		throwProposedApiError(extension);
	}
}

function throwProposedApiError(extension: IExtensionDescription): never {
	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}`);
}

76
function proposedApiFunction<T>(extension: IExtensionDescription, fn: T): T {
77
	if (extension.enableProposedApi) {
78 79
		return fn;
	} else {
80
		return <any>throwProposedApiError;
81 82 83
	}
}

E
Erich Gamma 已提交
84
/**
85
 * This method instantiates and returns the extension API surface
E
Erich Gamma 已提交
86
 */
87 88
export function createApiFactory(
	initData: IInitData,
A
Alex Dima 已提交
89
	rpcProtocol: IExtHostContext,
90 91
	extHostWorkspace: ExtHostWorkspace,
	extHostConfiguration: ExtHostConfiguration,
J
Joao Moreno 已提交
92
	extensionService: ExtHostExtensionService,
93
	extHostLogService: ExtHostLogService
94
): IExtensionApiFactory {
95

96
	// Addressable instances
97
	rpcProtocol.set(ExtHostContext.ExtHostLogService, extHostLogService);
A
Alex Dima 已提交
98 99
	const extHostHeapService = rpcProtocol.set(ExtHostContext.ExtHostHeapService, new ExtHostHeapService());
	const extHostDecorations = rpcProtocol.set(ExtHostContext.ExtHostDecorations, new ExtHostDecorations(rpcProtocol));
M
Matt Bierner 已提交
100
	const extHostWebviews = rpcProtocol.set(ExtHostContext.ExtHostWebviews, new ExtHostWebviews(rpcProtocol));
101
	const extHostDocumentsAndEditors = rpcProtocol.set(ExtHostContext.ExtHostDocumentsAndEditors, new ExtHostDocumentsAndEditors(rpcProtocol));
A
Alex Dima 已提交
102
	const extHostDocuments = rpcProtocol.set(ExtHostContext.ExtHostDocuments, new ExtHostDocuments(rpcProtocol, extHostDocumentsAndEditors));
103
	const extHostDocumentContentProviders = rpcProtocol.set(ExtHostContext.ExtHostDocumentContentProviders, new ExtHostDocumentContentProvider(rpcProtocol, extHostDocumentsAndEditors, extHostLogService));
104
	const extHostDocumentSaveParticipant = rpcProtocol.set(ExtHostContext.ExtHostDocumentSaveParticipant, new ExtHostDocumentSaveParticipant(extHostLogService, extHostDocuments, rpcProtocol.getProxy(MainContext.MainThreadTextEditors)));
A
Alex Dima 已提交
105
	const extHostEditors = rpcProtocol.set(ExtHostContext.ExtHostEditors, new ExtHostEditors(rpcProtocol, extHostDocumentsAndEditors));
106
	const extHostCommands = rpcProtocol.set(ExtHostContext.ExtHostCommands, new ExtHostCommands(rpcProtocol, extHostHeapService, extHostLogService));
A
Alex Dima 已提交
107 108
	const extHostTreeViews = rpcProtocol.set(ExtHostContext.ExtHostTreeViews, new ExtHostTreeViews(rpcProtocol.getProxy(MainContext.MainThreadTreeViews), extHostCommands));
	rpcProtocol.set(ExtHostContext.ExtHostWorkspace, extHostWorkspace);
109
	const extHostDebugService = rpcProtocol.set(ExtHostContext.ExtHostDebugService, new ExtHostDebugService(rpcProtocol, extHostWorkspace, extensionService));
A
Alex Dima 已提交
110 111
	rpcProtocol.set(ExtHostContext.ExtHostConfiguration, extHostConfiguration);
	const extHostDiagnostics = rpcProtocol.set(ExtHostContext.ExtHostDiagnostics, new ExtHostDiagnostics(rpcProtocol));
112 113
	const extHostLanguageFeatures = rpcProtocol.set(ExtHostContext.ExtHostLanguageFeatures, new ExtHostLanguageFeatures(rpcProtocol, extHostDocuments, extHostCommands, extHostHeapService, extHostDiagnostics));
	const extHostFileSystem = rpcProtocol.set(ExtHostContext.ExtHostFileSystem, new ExtHostFileSystem(rpcProtocol, extHostLanguageFeatures));
A
Alex Dima 已提交
114 115 116
	const extHostFileSystemEvent = rpcProtocol.set(ExtHostContext.ExtHostFileSystemEventService, new ExtHostFileSystemEventService());
	const extHostQuickOpen = rpcProtocol.set(ExtHostContext.ExtHostQuickOpen, new ExtHostQuickOpen(rpcProtocol, extHostWorkspace, extHostCommands));
	const extHostTerminalService = rpcProtocol.set(ExtHostContext.ExtHostTerminalService, new ExtHostTerminalService(rpcProtocol));
117
	const extHostSCM = rpcProtocol.set(ExtHostContext.ExtHostSCM, new ExtHostSCM(rpcProtocol, extHostCommands, extHostLogService));
A
Alex Dima 已提交
118 119 120
	const extHostTask = rpcProtocol.set(ExtHostContext.ExtHostTask, new ExtHostTask(rpcProtocol, extHostWorkspace));
	const extHostWindow = rpcProtocol.set(ExtHostContext.ExtHostWindow, new ExtHostWindow(rpcProtocol));
	rpcProtocol.set(ExtHostContext.ExtHostExtensionService, extensionService);
121
	const extHostProgress = rpcProtocol.set(ExtHostContext.ExtHostProgress, new ExtHostProgress(rpcProtocol.getProxy(MainContext.MainThreadProgress)));
122 123 124

	// Check that no named customers are missing
	const expected: ProxyIdentifier<any>[] = Object.keys(ExtHostContext).map((key) => ExtHostContext[key]);
A
Alex Dima 已提交
125
	rpcProtocol.assertRegistered(expected);
126

127
	// Other instances
A
Alex Dima 已提交
128 129 130 131 132
	const extHostMessageService = new ExtHostMessageService(rpcProtocol);
	const extHostDialogs = new ExtHostDialogs(rpcProtocol);
	const extHostStatusBar = new ExtHostStatusBar(rpcProtocol);
	const extHostOutputService = new ExtHostOutputService(rpcProtocol);
	const extHostLanguages = new ExtHostLanguages(rpcProtocol);
133

134
	// Register API-ish commands
135
	ExtHostApiCommands.register(extHostCommands, extHostTask);
136

137
	return function (extension: IExtensionDescription): typeof vscode {
138

139 140 141 142 143 144
		if (!isFalsyOrEmpty(product.extensionAllowedProposedApi)
			&& product.extensionAllowedProposedApi.indexOf(extension.id) >= 0
		) {
			// fast lane -> proposed api is available to all extensions
			// that are listed in product.json-files
			extension.enableProposedApi = true;
145

146
		} else if (extension.enableProposedApi && !extension.isBuiltin) {
147 148 149 150
			if (
				!initData.environment.enableProposedApiForAll &&
				initData.environment.enableProposedApiFor.indexOf(extension.id) < 0
			) {
151
				extension.enableProposedApi = false;
152
				console.error(`Extension '${extension.id} cannot use PROPOSED API (must started out of dev or enabled via --enable-proposed-api)`);
153 154

			} else {
155 156 157
				// 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.`);
158
			}
159 160
		}

161 162
		// namespace: commands
		const commands: typeof vscode.commands = {
M
Matt Bierner 已提交
163
			registerCommand(id: string, command: <T>(...args: any[]) => T | Thenable<T>, thisArgs?: any): vscode.Disposable {
164
				return extHostCommands.registerCommand(true, id, command, thisArgs);
165
			},
166
			registerTextEditorCommand(id: string, callback: (textEditor: vscode.TextEditor, edit: vscode.TextEditorEdit, ...args: any[]) => void, thisArg?: any): vscode.Disposable {
167
				return extHostCommands.registerCommand(true, id, (...args: any[]): any => {
168 169 170
					let activeTextEditor = extHostEditors.getActiveTextEditor();
					if (!activeTextEditor) {
						console.warn('Cannot execute ' + id + ' because there is no active text editor.');
171
						return undefined;
172
					}
173 174 175 176 177 178 179 180 181 182

					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) => {
183
						console.warn('An error occurred while running command ' + id, err);
184
					});
185
				});
186 187
			},
			registerDiffInformationCommand: proposedApiFunction(extension, (id: string, callback: (diff: vscode.LineChange[], ...args: any[]) => any, thisArg?: any): vscode.Disposable => {
188
				return extHostCommands.registerCommand(true, id, async (...args: any[]) => {
189 190 191 192 193 194 195 196 197
					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]);
				});
198
			}),
199
			executeCommand<T>(id: string, ...args: any[]): Thenable<T> {
200
				return extHostCommands.executeCommand<T>(id, ...args);
201
			},
202 203 204
			getCommands(filterInternal: boolean = false): Thenable<string[]> {
				return extHostCommands.getCommands(filterInternal);
			}
205
		};
206

207 208
		// namespace: env
		const env: typeof vscode.env = Object.freeze({
209 210
			get machineId() { return initData.telemetryInfo.machineId; },
			get sessionId() { return initData.telemetryInfo.sessionId; },
211
			get language() { return Platform.language; },
J
Johannes Rieken 已提交
212 213
			get appName() { return product.nameLong; },
			get appRoot() { return initData.environment.appRoot; },
M
Matt Bierner 已提交
214
			get logLevel() { return extHostLogService.getLevel(); }
215
		});
E
Erich Gamma 已提交
216

217 218 219
		// namespace: extensions
		const extensions: typeof vscode.extensions = {
			getExtension(extensionId: string): Extension<any> {
220
				let desc = extensionService.getExtensionDescription(extensionId);
221 222 223
				if (desc) {
					return new Extension(extensionService, desc);
				}
224
				return undefined;
225 226
			},
			get all(): Extension<any>[] {
227
				return extensionService.getAllExtensionDescriptions().map((desc) => new Extension(extensionService, desc));
E
Erich Gamma 已提交
228
			}
229
		};
E
Erich Gamma 已提交
230

231 232 233 234 235
		// namespace: languages
		const languages: typeof vscode.languages = {
			createDiagnosticCollection(name?: string): vscode.DiagnosticCollection {
				return extHostDiagnostics.createDiagnosticCollection(name);
			},
236 237 238 239
			get onDidChangeDiagnostics() {
				checkProposedApiEnabled(extension);
				return extHostDiagnostics.onDidChangeDiagnostics;
			},
240 241 242
			getDiagnostics: (resource?) => {
				return <any>extHostDiagnostics.getDiagnostics(resource);
			},
243 244 245 246
			getLanguages(): TPromise<string[]> {
				return extHostLanguages.getLanguages();
			},
			match(selector: vscode.DocumentSelector, document: vscode.TextDocument): number {
247
				return score(toLanguageSelector(selector), document.uri, document.languageId, true);
248 249
			},
			registerCodeActionsProvider(selector: vscode.DocumentSelector, provider: vscode.CodeActionProvider): vscode.Disposable {
250
				return extHostLanguageFeatures.registerCodeActionProvider(selector, provider);
251 252
			},
			registerCodeLensProvider(selector: vscode.DocumentSelector, provider: vscode.CodeLensProvider): vscode.Disposable {
253
				return extHostLanguageFeatures.registerCodeLensProvider(selector, provider);
254 255
			},
			registerDefinitionProvider(selector: vscode.DocumentSelector, provider: vscode.DefinitionProvider): vscode.Disposable {
256
				return extHostLanguageFeatures.registerDefinitionProvider(selector, provider);
257
			},
M
Matt Bierner 已提交
258
			registerImplementationProvider(selector: vscode.DocumentSelector, provider: vscode.ImplementationProvider): vscode.Disposable {
259
				return extHostLanguageFeatures.registerImplementationProvider(selector, provider);
260
			},
261
			registerTypeDefinitionProvider(selector: vscode.DocumentSelector, provider: vscode.TypeDefinitionProvider): vscode.Disposable {
262
				return extHostLanguageFeatures.registerTypeDefinitionProvider(selector, provider);
263
			},
264
			registerHoverProvider(selector: vscode.DocumentSelector, provider: vscode.HoverProvider): vscode.Disposable {
265
				return extHostLanguageFeatures.registerHoverProvider(selector, provider, extension.id);
266 267
			},
			registerDocumentHighlightProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentHighlightProvider): vscode.Disposable {
268
				return extHostLanguageFeatures.registerDocumentHighlightProvider(selector, provider);
269 270
			},
			registerReferenceProvider(selector: vscode.DocumentSelector, provider: vscode.ReferenceProvider): vscode.Disposable {
271
				return extHostLanguageFeatures.registerReferenceProvider(selector, provider);
272 273
			},
			registerRenameProvider(selector: vscode.DocumentSelector, provider: vscode.RenameProvider): vscode.Disposable {
274
				return extHostLanguageFeatures.registerRenameProvider(selector, provider, extension.enableProposedApi);
275 276
			},
			registerDocumentSymbolProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentSymbolProvider): vscode.Disposable {
277
				return extHostLanguageFeatures.registerDocumentSymbolProvider(selector, provider);
278 279
			},
			registerWorkspaceSymbolProvider(provider: vscode.WorkspaceSymbolProvider): vscode.Disposable {
280
				return extHostLanguageFeatures.registerWorkspaceSymbolProvider(provider);
281 282
			},
			registerDocumentFormattingEditProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentFormattingEditProvider): vscode.Disposable {
283
				return extHostLanguageFeatures.registerDocumentFormattingEditProvider(selector, provider);
284 285
			},
			registerDocumentRangeFormattingEditProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentRangeFormattingEditProvider): vscode.Disposable {
286
				return extHostLanguageFeatures.registerDocumentRangeFormattingEditProvider(selector, provider);
287 288
			},
			registerOnTypeFormattingEditProvider(selector: vscode.DocumentSelector, provider: vscode.OnTypeFormattingEditProvider, firstTriggerCharacter: string, ...moreTriggerCharacters: string[]): vscode.Disposable {
289
				return extHostLanguageFeatures.registerOnTypeFormattingEditProvider(selector, provider, [firstTriggerCharacter].concat(moreTriggerCharacters));
290 291
			},
			registerSignatureHelpProvider(selector: vscode.DocumentSelector, provider: vscode.SignatureHelpProvider, ...triggerCharacters: string[]): vscode.Disposable {
292
				return extHostLanguageFeatures.registerSignatureHelpProvider(selector, provider, triggerCharacters);
293 294
			},
			registerCompletionItemProvider(selector: vscode.DocumentSelector, provider: vscode.CompletionItemProvider, ...triggerCharacters: string[]): vscode.Disposable {
295
				return extHostLanguageFeatures.registerCompletionItemProvider(selector, provider, triggerCharacters);
296 297
			},
			registerDocumentLinkProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentLinkProvider): vscode.Disposable {
298
				return extHostLanguageFeatures.registerDocumentLinkProvider(selector, provider);
299
			},
300
			registerColorProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentColorProvider): vscode.Disposable {
301
				return extHostLanguageFeatures.registerColorProvider(selector, provider);
302
			},
303 304 305
			registerFoldingProvider: proposedApiFunction(extension, (selector: vscode.DocumentSelector, provider: vscode.FoldingProvider): vscode.Disposable => {
				return extHostLanguageFeatures.registerFoldingProvider(selector, provider);
			}),
306
			setLanguageConfiguration: (language: string, configuration: vscode.LanguageConfiguration): vscode.Disposable => {
307
				return extHostLanguageFeatures.setLanguageConfiguration(language, configuration);
308
			}
309
		};
E
Erich Gamma 已提交
310

311 312 313 314 315 316 317 318
		// namespace: window
		const window: typeof vscode.window = {
			get activeTextEditor() {
				return extHostEditors.getActiveTextEditor();
			},
			get visibleTextEditors() {
				return extHostEditors.getVisibleTextEditors();
			},
J
Johannes Rieken 已提交
319
			showTextDocument(documentOrUri: vscode.TextDocument | vscode.Uri, columnOrOptions?: vscode.ViewColumn | vscode.TextDocumentShowOptions, preserveFocus?: boolean): TPromise<vscode.TextEditor> {
B
Benjamin Pasero 已提交
320
				let documentPromise: TPromise<vscode.TextDocument>;
J
Johannes Rieken 已提交
321 322
				if (URI.isUri(documentOrUri)) {
					documentPromise = TPromise.wrap(workspace.openTextDocument(documentOrUri));
B
Benjamin Pasero 已提交
323
				} else {
J
Johannes Rieken 已提交
324
					documentPromise = TPromise.wrap(<vscode.TextDocument>documentOrUri);
B
Benjamin Pasero 已提交
325 326 327 328
				}
				return documentPromise.then(document => {
					return extHostEditors.showTextDocument(document, columnOrOptions, preserveFocus);
				});
329 330 331 332
			},
			createTextEditorDecorationType(options: vscode.DecorationRenderOptions): vscode.TextEditorDecorationType {
				return extHostEditors.createTextEditorDecorationType(options);
			},
333 334 335
			onDidChangeActiveTextEditor(listener, thisArg?, disposables?) {
				return extHostEditors.onDidChangeActiveTextEditor(listener, thisArg, disposables);
			},
336 337 338
			onDidChangeVisibleTextEditors(listener, thisArg, disposables) {
				return extHostEditors.onDidChangeVisibleTextEditors(listener, thisArg, disposables);
			},
339
			onDidChangeTextEditorSelection(listener: (e: vscode.TextEditorSelectionChangeEvent) => any, thisArgs?: any, disposables?: extHostTypes.Disposable[]) {
340 341
				return extHostEditors.onDidChangeTextEditorSelection(listener, thisArgs, disposables);
			},
342
			onDidChangeTextEditorOptions(listener: (e: vscode.TextEditorOptionsChangeEvent) => any, thisArgs?: any, disposables?: extHostTypes.Disposable[]) {
343 344
				return extHostEditors.onDidChangeTextEditorOptions(listener, thisArgs, disposables);
			},
345
			onDidChangeTextEditorVisibleRanges(listener: (e: vscode.TextEditorVisibleRangesChangeEvent) => any, thisArgs?: any, disposables?: extHostTypes.Disposable[]) {
346
				return extHostEditors.onDidChangeTextEditorVisibleRanges(listener, thisArgs, disposables);
347
			},
348 349 350
			onDidChangeTextEditorViewColumn(listener, thisArg?, disposables?) {
				return extHostEditors.onDidChangeTextEditorViewColumn(listener, thisArg, disposables);
			},
351 352 353
			onDidCloseTerminal(listener, thisArg?, disposables?) {
				return extHostTerminalService.onDidCloseTerminal(listener, thisArg, disposables);
			},
J
Joao Moreno 已提交
354 355
			get state() {
				return extHostWindow.state;
356
			},
J
Joao Moreno 已提交
357
			onDidChangeWindowState(listener, thisArg?, disposables?) {
J
Joao Moreno 已提交
358
				return extHostWindow.onDidChangeWindowState(listener, thisArg, disposables);
J
Joao Moreno 已提交
359
			},
J
Joao Moreno 已提交
360
			showInformationMessage(message, first, ...rest) {
361
				return extHostMessageService.showMessage(extension, Severity.Info, message, first, rest);
362
			},
J
Joao Moreno 已提交
363
			showWarningMessage(message, first, ...rest) {
364
				return extHostMessageService.showMessage(extension, Severity.Warning, message, first, rest);
365
			},
J
Joao Moreno 已提交
366
			showErrorMessage(message, first, ...rest) {
367
				return extHostMessageService.showMessage(extension, Severity.Error, message, first, rest);
368
			},
C
Christof Marti 已提交
369
			showQuickPick(items: any, options: vscode.QuickPickOptions, token?: vscode.CancellationToken): any {
370 371
				return extHostQuickOpen.showQuickPick(items, options, token);
			},
372
			showWorkspaceFolderPick(options: vscode.WorkspaceFolderPickOptions) {
373
				return extHostQuickOpen.showWorkspaceFolderPick(options);
374
			},
375 376 377
			showInputBox(options?: vscode.InputBoxOptions, token?: vscode.CancellationToken) {
				return extHostQuickOpen.showInput(options, token);
			},
378 379 380 381 382 383
			showOpenDialog(options) {
				return extHostDialogs.showOpenDialog(options);
			},
			showSaveDialog(options) {
				return extHostDialogs.showSaveDialog(options);
			},
384
			createStatusBarItem(position?: vscode.StatusBarAlignment, priority?: number): vscode.StatusBarItem {
385
				return extHostStatusBar.createStatusBarEntry(extension.id, <number>position, priority);
386 387 388 389
			},
			setStatusBarMessage(text: string, timeoutOrThenable?: number | Thenable<any>): vscode.Disposable {
				return extHostStatusBar.setStatusBarMessage(text, timeoutOrThenable);
			},
390
			withScmProgress<R>(task: (progress: vscode.Progress<number>) => Thenable<R>) {
391
				console.warn(`[Deprecation Warning] function 'withScmProgress' is deprecated and should no longer be used. Use 'withProgress' instead.`);
392
				return extHostProgress.withProgress(extension, { location: extHostTypes.ProgressLocation.SourceControl }, (progress, token) => task({ report(n: number) { /*noop*/ } }));
J
Johannes Rieken 已提交
393
			},
394
			withProgress<R>(options: vscode.ProgressOptions, task: (progress: vscode.Progress<{ message?: string; worked?: number }>, token: vscode.CancellationToken) => Thenable<R>) {
J
Johannes Rieken 已提交
395
				return extHostProgress.withProgress(extension, options, task);
396
			},
397 398 399
			createOutputChannel(name: string): vscode.OutputChannel {
				return extHostOutputService.createOutputChannel(name);
			},
400 401 402 403
			createTerminal(nameOrOptions: vscode.TerminalOptions | string, shellPath?: string, shellArgs?: string[]): vscode.Terminal {
				if (typeof nameOrOptions === 'object') {
					return extHostTerminalService.createTerminalFromOptions(<vscode.TerminalOptions>nameOrOptions);
				}
D
Daniel Imms 已提交
404
				return extHostTerminalService.createTerminal(<string>nameOrOptions, shellPath, shellArgs);
405
			},
406 407 408 409 410
			registerTreeDataProvider(viewId: string, treeDataProvider: vscode.TreeDataProvider<any>): vscode.Disposable {
				return extHostTreeViews.registerTreeDataProvider(viewId, treeDataProvider);
			},
			createTreeView(viewId: string, options: { treeDataProvider: vscode.TreeDataProvider<any> }): vscode.TreeView<any> {
				return extHostTreeViews.createTreeView(viewId, options);
S
Sandeep Somavarapu 已提交
411
			},
412 413
			// proposed API
			sampleFunction: proposedApiFunction(extension, () => {
414
				return extHostMessageService.showMessage(extension, Severity.Info, 'Hello Proposed Api!', {}, []);
415
			}),
416 417
			registerDecorationProvider: proposedApiFunction(extension, (provider: vscode.DecorationProvider) => {
				return extHostDecorations.registerDecorationProvider(provider, extension.id);
M
Matt Bierner 已提交
418
			}),
419 420
			createWebview: proposedApiFunction(extension, (viewType: string, title: string, column: vscode.ViewColumn, options: vscode.WebviewOptions) => {
				return extHostWebviews.createWebview(viewType, title, column, options, extension.extensionFolderPath);
421 422 423
			}),
			registerWebviewSerializer: proposedApiFunction(extension, (viewType: string, serializer: vscode.WebviewSerializer) => {
				return extHostWebviews.registerWebviewSerializer(viewType, serializer);
424
			})
425
		};
E
Erich Gamma 已提交
426

427 428 429 430 431 432 433 434
		// namespace: workspace
		const workspace: typeof vscode.workspace = {
			get rootPath() {
				return extHostWorkspace.getPath();
			},
			set rootPath(value) {
				throw errors.readonly();
			},
435 436
			getWorkspaceFolder(resource) {
				return extHostWorkspace.getWorkspaceFolder(resource);
437
			},
438
			get workspaceFolders() {
439
				return extHostWorkspace.getWorkspaceFolders();
440
			},
441 442 443 444 445 446
			get name() {
				return extHostWorkspace.workspace ? extHostWorkspace.workspace.name : undefined;
			},
			set name(value) {
				throw errors.readonly();
			},
447 448 449
			updateWorkspaceFolders: (index, deleteCount, ...workspaceFoldersToAdd) => {
				return extHostWorkspace.updateWorkspaceFolders(extension, index, deleteCount || 0, ...workspaceFoldersToAdd);
			},
450
			onDidChangeWorkspaceFolders: function (listener, thisArgs?, disposables?) {
451
				return extHostWorkspace.onDidChangeWorkspace(listener, thisArgs, disposables);
452
			},
J
Johannes Rieken 已提交
453 454
			asRelativePath: (pathOrUri, includeWorkspace) => {
				return extHostWorkspace.getRelativePath(pathOrUri, includeWorkspace);
455 456
			},
			findFiles: (include, exclude, maxResults?, token?) => {
457
				return extHostWorkspace.findFiles(toGlobPattern(include), toGlobPattern(exclude), maxResults, extension.id, token);
458 459 460 461 462
			},
			saveAll: (includeUntitled?) => {
				return extHostWorkspace.saveAll(includeUntitled);
			},
			applyEdit(edit: vscode.WorkspaceEdit): TPromise<boolean> {
463
				return extHostEditors.applyWorkspaceEdit(edit);
464 465
			},
			createFileSystemWatcher: (pattern, ignoreCreate, ignoreChange, ignoreDelete): vscode.FileSystemWatcher => {
466
				return extHostFileSystemEvent.createFileSystemWatcher(toGlobPattern(pattern), ignoreCreate, ignoreChange, ignoreDelete);
467 468 469 470 471 472 473
			},
			get textDocuments() {
				return extHostDocuments.getAllDocumentData().map(data => data.document);
			},
			set textDocuments(value) {
				throw errors.readonly();
			},
474
			openTextDocument(uriOrFileNameOrOptions?: vscode.Uri | string | { language?: string; content?: string; }) {
B
Benjamin Pasero 已提交
475 476
				let uriPromise: TPromise<URI>;

477
				let options = uriOrFileNameOrOptions as { language?: string; content?: string; };
B
Benjamin Pasero 已提交
478
				if (typeof uriOrFileNameOrOptions === 'string') {
B
Benjamin Pasero 已提交
479 480
					uriPromise = TPromise.as(URI.file(uriOrFileNameOrOptions));
				} else if (uriOrFileNameOrOptions instanceof URI) {
J
Johannes Rieken 已提交
481
					uriPromise = TPromise.as(uriOrFileNameOrOptions);
B
Benjamin Pasero 已提交
482 483
				} else if (!options || typeof options === 'object') {
					uriPromise = extHostDocuments.createDocumentData(options);
484
				} else {
B
Benjamin Pasero 已提交
485
					throw new Error('illegal argument - uriOrFileNameOrOptions');
486
				}
B
Benjamin Pasero 已提交
487 488 489 490 491 492

				return uriPromise.then(uri => {
					return extHostDocuments.ensureDocumentData(uri).then(() => {
						const data = extHostDocuments.getDocumentData(uri);
						return data && data.document;
					});
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
				});
			},
			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?) => {
508
				return extHostDocumentSaveParticipant.getOnWillSaveTextDocumentEvent(extension)(listener, thisArgs, disposables);
509
			},
510
			onDidChangeConfiguration: (listener: (_: any) => any, thisArgs?: any, disposables?: extHostTypes.Disposable[]) => {
511 512
				return extHostConfiguration.onDidChangeConfiguration(listener, thisArgs, disposables);
			},
513 514
			getConfiguration(section?: string, resource?: vscode.Uri): vscode.WorkspaceConfiguration {
				resource = arguments.length === 1 ? void 0 : resource;
S
Sandeep Somavarapu 已提交
515
				return extHostConfiguration.getConfiguration(section, resource, extension.id);
516
			},
517 518
			registerTextDocumentContentProvider(scheme: string, provider: vscode.TextDocumentContentProvider) {
				return extHostDocumentContentProviders.registerTextDocumentContentProvider(scheme, provider);
519
			},
520
			registerTaskProvider: (type: string, provider: vscode.TaskProvider) => {
521
				return extHostTask.registerTaskProvider(extension, provider);
J
Johannes Rieken 已提交
522
			},
D
Dirk Baeumer 已提交
523 524 525 526 527 528 529
			// fetchTasks: proposedApiFunction(extension, (): Thenable<vscode.Task[]> => {
			// 	return extHostTask.executeTaskProvider();
			// }),
			// executeTask: proposedApiFunction(extension, (task: vscode.Task): Thenable<vscode.TaskExecution> => {
			// 	return extHostTask.executeTask(extension, task);
			// }),
			fetchTasks: (): Thenable<vscode.Task[]> => {
530
				return extHostTask.executeTaskProvider();
D
Dirk Baeumer 已提交
531 532
			},
			executeTask: (task: vscode.Task): Thenable<vscode.TaskExecution> => {
533
				return extHostTask.executeTask(extension, task);
D
Dirk Baeumer 已提交
534
			},
535 536 537 538 539 540
			onDidStartTask: (listeners, thisArgs?, disposables?) => {
				return extHostTask.onDidStartTask(listeners, thisArgs, disposables);
			},
			onDidEndTask: (listeners, thisArgs?, disposables?) => {
				return extHostTask.onDidEndTask(listeners, thisArgs, disposables);
			},
541 542
			registerFileSystemProvider: proposedApiFunction(extension, (scheme, provider, newProvider?) => {
				return extHostFileSystem.registerFileSystemProvider(scheme, provider, newProvider);
543 544 545
			}),
			registerSearchProvider: proposedApiFunction(extension, (scheme, provider) => {
				return extHostFileSystem.registerSearchProvider(scheme, provider);
J
Johannes Rieken 已提交
546
			})
547
		};
548

549 550
		// namespace: scm
		const scm: typeof vscode.scm = {
551
			get inputBox() {
J
Joao Moreno 已提交
552
				return extHostSCM.getLastInputBox(extension);
553
			},
J
Joao Moreno 已提交
554 555
			createSourceControl(id: string, label: string, rootUri?: vscode.Uri) {
				return extHostSCM.createSourceControl(extension, id, label, rootUri);
J
Joao Moreno 已提交
556
			}
557
		};
J
Joao Moreno 已提交
558

559 560
		// namespace: debug
		const debug: typeof vscode.debug = {
561 562 563
			get activeDebugSession() {
				return extHostDebugService.activeDebugSession;
			},
564 565
			get activeDebugConsole() {
				return extHostDebugService.activeDebugConsole;
566
			},
567 568
			get breakpoints() {
				return extHostDebugService.breakpoints;
569
			},
570 571 572
			onDidStartDebugSession(listener, thisArg?, disposables?) {
				return extHostDebugService.onDidStartDebugSession(listener, thisArg, disposables);
			},
573
			onDidTerminateDebugSession(listener, thisArg?, disposables?) {
574
				return extHostDebugService.onDidTerminateDebugSession(listener, thisArg, disposables);
575
			},
A
Andre Weinand 已提交
576
			onDidChangeActiveDebugSession(listener, thisArg?, disposables?) {
577
				return extHostDebugService.onDidChangeActiveDebugSession(listener, thisArg, disposables);
A
Andre Weinand 已提交
578 579
			},
			onDidReceiveDebugSessionCustomEvent(listener, thisArg?, disposables?) {
A
Andre Weinand 已提交
580
				return extHostDebugService.onDidReceiveDebugSessionCustomEvent(listener, thisArg, disposables);
581
			},
582
			onDidChangeBreakpoints(listener, thisArgs?, disposables?) {
583 584
				return extHostDebugService.onDidChangeBreakpoints(listener, thisArgs, disposables);
			},
A
Andre Weinand 已提交
585
			registerDebugConfigurationProvider(debugType: string, provider: vscode.DebugConfigurationProvider) {
586
				return extHostDebugService.registerDebugConfigurationProvider(debugType, provider);
587
			},
588 589 590 591
			startDebugging(folder: vscode.WorkspaceFolder | undefined, nameOrConfig: string | vscode.DebugConfiguration) {
				return extHostDebugService.startDebugging(folder, nameOrConfig);
			},
			addBreakpoints(breakpoints: vscode.Breakpoint[]) {
592
				return extHostDebugService.addBreakpoints(breakpoints);
593 594
			},
			removeBreakpoints(breakpoints: vscode.Breakpoint[]) {
595
				return extHostDebugService.removeBreakpoints(breakpoints);
596
			}
597 598 599
		};


600
		return <typeof vscode>{
601 602 603 604 605 606 607 608
			version: pkg.version,
			// namespaces
			commands,
			env,
			extensions,
			languages,
			window,
			workspace,
J
Joao Moreno 已提交
609
			scm,
610
			debug,
611
			// types
612
			Breakpoint: extHostTypes.Breakpoint,
613
			CancellationTokenSource: CancellationTokenSource,
614
			CodeAction: extHostTypes.CodeAction,
M
Matt Bierner 已提交
615
			CodeActionKind: extHostTypes.CodeActionKind,
616
			CodeLens: extHostTypes.CodeLens,
617
			Color: extHostTypes.Color,
618 619
			ColorPresentation: extHostTypes.ColorPresentation,
			ColorInformation: extHostTypes.ColorInformation,
620
			EndOfLine: extHostTypes.EndOfLine,
621 622 623
			CompletionItem: extHostTypes.CompletionItem,
			CompletionItemKind: extHostTypes.CompletionItemKind,
			CompletionList: extHostTypes.CompletionList,
M
Matt Bierner 已提交
624
			CompletionTriggerKind: extHostTypes.CompletionTriggerKind,
625
			DebugAdapterExecutable: extHostTypes.DebugAdapterExecutable,
626
			Diagnostic: extHostTypes.Diagnostic,
627
			DiagnosticRelatedInformation: extHostTypes.DiagnosticRelatedInformation,
628 629 630 631
			DiagnosticSeverity: extHostTypes.DiagnosticSeverity,
			Disposable: extHostTypes.Disposable,
			DocumentHighlight: extHostTypes.DocumentHighlight,
			DocumentHighlightKind: extHostTypes.DocumentHighlightKind,
632
			DocumentLink: extHostTypes.DocumentLink,
633
			EventEmitter: Emitter,
634
			FunctionBreakpoint: extHostTypes.FunctionBreakpoint,
635
			Hover: extHostTypes.Hover,
636
			IndentAction: languageConfiguration.IndentAction,
637
			Location: extHostTypes.Location,
638
			LogLevel: extHostTypes.LogLevel,
639
			MarkdownString: extHostTypes.MarkdownString,
640
			OverviewRulerLane: OverviewRulerLane,
641 642 643 644 645 646 647
			ParameterInformation: extHostTypes.ParameterInformation,
			Position: extHostTypes.Position,
			Range: extHostTypes.Range,
			Selection: extHostTypes.Selection,
			SignatureHelp: extHostTypes.SignatureHelp,
			SignatureInformation: extHostTypes.SignatureInformation,
			SnippetString: extHostTypes.SnippetString,
648
			SourceBreakpoint: extHostTypes.SourceBreakpoint,
649 650 651
			StatusBarAlignment: extHostTypes.StatusBarAlignment,
			SymbolInformation: extHostTypes.SymbolInformation,
			SymbolKind: extHostTypes.SymbolKind,
652
			SourceControlInputBoxValidationType: extHostTypes.SourceControlInputBoxValidationType,
653 654
			TextDocumentSaveReason: extHostTypes.TextDocumentSaveReason,
			TextEdit: extHostTypes.TextEdit,
655
			TextEditorCursorStyle: TextEditorCursorStyle,
656
			TextEditorLineNumbersStyle: extHostTypes.TextEditorLineNumbersStyle,
657
			TextEditorRevealType: extHostTypes.TextEditorRevealType,
658
			TextEditorSelectionChangeKind: extHostTypes.TextEditorSelectionChangeKind,
659
			DecorationRangeBehavior: extHostTypes.DecorationRangeBehavior,
660
			Uri: URI,
661 662
			ViewColumn: extHostTypes.ViewColumn,
			WorkspaceEdit: extHostTypes.WorkspaceEdit,
J
Johannes Rieken 已提交
663
			ProgressLocation: extHostTypes.ProgressLocation,
S
Sandeep Somavarapu 已提交
664
			TreeItemCollapsibleState: extHostTypes.TreeItemCollapsibleState,
665
			ThemeIcon: extHostTypes.ThemeIcon,
S
Sandeep Somavarapu 已提交
666
			TreeItem: extHostTypes.TreeItem,
667
			ThemeColor: extHostTypes.ThemeColor,
J
Joao Moreno 已提交
668
			// functions
669
			TaskRevealKind: extHostTypes.TaskRevealKind,
670
			TaskPanelKind: extHostTypes.TaskPanelKind,
671
			TaskGroup: extHostTypes.TaskGroup,
D
Dirk Baeumer 已提交
672 673
			ProcessExecution: extHostTypes.ProcessExecution,
			ShellExecution: extHostTypes.ShellExecution,
674
			ShellQuoting: extHostTypes.ShellQuoting,
D
Dirk Baeumer 已提交
675
			TaskScope: extHostTypes.TaskScope,
S
Sandeep Somavarapu 已提交
676
			Task: extHostTypes.Task,
677
			ConfigurationTarget: extHostTypes.ConfigurationTarget,
678
			RelativePattern: extHostTypes.RelativePattern,
679

J
Johannes Rieken 已提交
680
			FileChangeType: extHostTypes.FileChangeType,
681 682 683 684
			FileType: extHostTypes.FileType,
			FoldingRangeList: extHostTypes.FoldingRangeList,
			FoldingRange: extHostTypes.FoldingRange,
			FoldingRangeType: extHostTypes.FoldingRangeType
685
		};
686
	};
E
Erich Gamma 已提交
687 688 689 690
}

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

A
Alex Dima 已提交
691
	private _extensionService: ExtHostExtensionService;
E
Erich Gamma 已提交
692 693 694 695 696

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

J
Johannes Rieken 已提交
697
	constructor(extensionService: ExtHostExtensionService, description: IExtensionDescription) {
A
Alex Dima 已提交
698
		this._extensionService = extensionService;
E
Erich Gamma 已提交
699 700 701 702 703 704
		this.id = description.id;
		this.extensionPath = paths.normalize(description.extensionFolderPath, true);
		this.packageJSON = description;
	}

	get isActive(): boolean {
A
Alex Dima 已提交
705
		return this._extensionService.isActivated(this.id);
E
Erich Gamma 已提交
706 707 708
	}

	get exports(): T {
A
Alex Dima 已提交
709
		return <T>this._extensionService.getExtensionExports(this.id);
E
Erich Gamma 已提交
710 711 712
	}

	activate(): Thenable<T> {
713
		return this._extensionService.activateByIdWithErrors(this.id, new ExtensionActivatedByAPI(false)).then(() => this.exports);
E
Erich Gamma 已提交
714 715 716
	}
}

J
Johannes Rieken 已提交
717
export function initializeExtensionApi(extensionService: ExtHostExtensionService, apiFactory: IExtensionApiFactory): TPromise<void> {
718
	return extensionService.getExtensionPathIndex().then(trie => defineAPI(apiFactory, trie));
J
Johannes Rieken 已提交
719 720
}

721
function defineAPI(factory: IExtensionApiFactory, extensionPaths: TernarySearchTree<IExtensionDescription>): void {
J
Johannes Rieken 已提交
722 723

	// each extension is meant to get its own api implementation
J
Johannes Rieken 已提交
724
	const extApiImpl = new Map<string, typeof vscode>();
J
Johannes Rieken 已提交
725
	let defaultApiImpl: typeof vscode;
726 727 728

	const node_module = <any>require.__$__nodeRequire('module');
	const original = node_module._load;
E
Erich Gamma 已提交
729
	node_module._load = function load(request, parent, isMain) {
730 731 732 733 734
		if (request !== 'vscode') {
			return original.apply(this, arguments);
		}

		// get extension id from filename and api for extension
J
Johannes Rieken 已提交
735
		const ext = extensionPaths.findSubstr(parent.filename);
736
		if (ext) {
J
Johannes Rieken 已提交
737
			let apiImpl = extApiImpl.get(ext.id);
738
			if (!apiImpl) {
J
Johannes Rieken 已提交
739 740
				apiImpl = factory(ext);
				extApiImpl.set(ext.id, apiImpl);
741 742 743 744 745 746
			}
			return apiImpl;
		}

		// fall back to a default implementation
		if (!defaultApiImpl) {
747
			defaultApiImpl = factory(nullExtensionDescription);
E
Erich Gamma 已提交
748
		}
749
		return defaultApiImpl;
E
Erich Gamma 已提交
750 751
	};
}
752 753 754 755 756 757 758 759 760 761 762 763 764 765 766

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