extHost.api.impl.ts 37.6 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 109 110 111
	const extHostTreeViews = rpcProtocol.set(ExtHostContext.ExtHostTreeViews, new ExtHostTreeViews(rpcProtocol.getProxy(MainContext.MainThreadTreeViews), extHostCommands));
	rpcProtocol.set(ExtHostContext.ExtHostWorkspace, extHostWorkspace);
	const extHostDebugService = rpcProtocol.set(ExtHostContext.ExtHostDebugService, new ExtHostDebugService(rpcProtocol, extHostWorkspace));
	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
			getDiagnostics: <any>proposedApiFunction(extension, (resource?) => {
241 242
				return 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
		};
E
Erich Gamma 已提交
423

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

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

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

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

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


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

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

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

A
Alex Dima 已提交
688
	private _extensionService: ExtHostExtensionService;
E
Erich Gamma 已提交
689 690 691 692 693

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

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

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

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

	activate(): Thenable<T> {
A
Alex Dima 已提交
710
		return this._extensionService.activateById(this.id, new ExtensionActivatedByAPI(false)).then(() => this.exports);
E
Erich Gamma 已提交
711 712 713
	}
}

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

718
function defineAPI(factory: IExtensionApiFactory, extensionPaths: TernarySearchTree<IExtensionDescription>): void {
J
Johannes Rieken 已提交
719 720

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

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

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

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

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