extHost.api.impl.ts 34.4 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';

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';
C
Christof Marti 已提交
38
import { ExtHostCredentials } from 'vs/workbench/api/node/extHostCredentials';
39
import { ExtHostWindow } from 'vs/workbench/api/node/extHostWindow';
J
Johannes Rieken 已提交
40
import * as extHostTypes from 'vs/workbench/api/node/extHostTypes';
E
Erich Gamma 已提交
41 42 43
import URI from 'vs/base/common/uri';
import Severity from 'vs/base/common/severity';
import EditorCommon = require('vs/editor/common/editorCommon');
J
Johannes Rieken 已提交
44 45 46 47
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { ExtHostExtensionService } from 'vs/workbench/api/node/extHostExtensionService';
import { TPromise } from 'vs/base/common/winjs.base';
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';
50
import { MainContext, ExtHostContext, IInitData } from './extHost.protocol';
51
import * as languageConfiguration from 'vs/editor/common/modes/languageConfiguration';
52
import { TextEditorCursorStyle } from 'vs/editor/common/config/editorOptions';
B
Benjamin Pasero 已提交
53 54 55
import { ExtHostThreadService } from 'vs/workbench/services/thread/node/extHostThreadService';
import { ProxyIdentifier } from 'vs/workbench/services/thread/common/threadService';
import { ExtHostDialogs } from 'vs/workbench/api/node/extHostDialogs';
56 57
import { ExtHostFileSystem } from 'vs/workbench/api/node/extHostFileSystem';
import { FileChangeType, FileType } from 'vs/platform/files/common/files';
E
Erich Gamma 已提交
58

59
export interface IExtensionApiFactory {
60
	(extension: IExtensionDescription): typeof vscode;
61 62
}

63
function proposedApiFunction<T>(extension: IExtensionDescription, fn: T): T {
64
	if (extension.enableProposedApi) {
65 66 67
		return fn;
	} else {
		return <any>(() => {
68
			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}`);
69 70 71 72
		});
	}
}

E
Erich Gamma 已提交
73
/**
74
 * This method instantiates and returns the extension API surface
E
Erich Gamma 已提交
75
 */
76 77
export function createApiFactory(
	initData: IInitData,
78
	threadService: ExtHostThreadService,
79
	extensionService: ExtHostExtensionService
80
): IExtensionApiFactory {
81

82 83
	const mainThreadTelemetry = threadService.get(MainContext.MainThreadTelemetry);

84
	// Addressable instances
85
	const extHostHeapService = threadService.set(ExtHostContext.ExtHostHeapService, new ExtHostHeapService());
86
	const extHostDocumentsAndEditors = threadService.set(ExtHostContext.ExtHostDocumentsAndEditors, new ExtHostDocumentsAndEditors(threadService, extensionService));
87 88
	const extHostDocuments = threadService.set(ExtHostContext.ExtHostDocuments, new ExtHostDocuments(threadService, extHostDocumentsAndEditors));
	const extHostDocumentContentProviders = threadService.set(ExtHostContext.ExtHostDocumentContentProviders, new ExtHostDocumentContentProvider(threadService, extHostDocumentsAndEditors));
89
	const extHostDocumentSaveParticipant = threadService.set(ExtHostContext.ExtHostDocumentSaveParticipant, new ExtHostDocumentSaveParticipant(extHostDocuments, threadService.get(MainContext.MainThreadEditors)));
90 91 92 93
	const extHostEditors = threadService.set(ExtHostContext.ExtHostEditors, new ExtHostEditors(threadService, extHostDocumentsAndEditors));
	const extHostCommands = threadService.set(ExtHostContext.ExtHostCommands, new ExtHostCommands(threadService, extHostHeapService));
	const extHostTreeViews = threadService.set(ExtHostContext.ExtHostTreeViews, new ExtHostTreeViews(threadService.get(MainContext.MainThreadTreeViews), extHostCommands));
	const extHostWorkspace = threadService.set(ExtHostContext.ExtHostWorkspace, new ExtHostWorkspace(threadService, initData.workspace));
94
	const extHostDebugService = threadService.set(ExtHostContext.ExtHostDebugService, new ExtHostDebugService(threadService, extHostWorkspace));
95 96 97
	const extHostConfiguration = threadService.set(ExtHostContext.ExtHostConfiguration, new ExtHostConfiguration(threadService.get(MainContext.MainThreadConfiguration), extHostWorkspace, initData.configuration));
	const extHostDiagnostics = threadService.set(ExtHostContext.ExtHostDiagnostics, new ExtHostDiagnostics(threadService));
	const languageFeatures = threadService.set(ExtHostContext.ExtHostLanguageFeatures, new ExtHostLanguageFeatures(threadService, extHostDocuments, extHostCommands, extHostHeapService, extHostDiagnostics));
98
	const extHostFileSystem = threadService.set(ExtHostContext.ExtHostFileSystem, new ExtHostFileSystem(threadService));
99
	const extHostFileSystemEvent = threadService.set(ExtHostContext.ExtHostFileSystemEventService, new ExtHostFileSystemEventService());
100
	const extHostQuickOpen = threadService.set(ExtHostContext.ExtHostQuickOpen, new ExtHostQuickOpen(threadService, extHostWorkspace, extHostCommands));
101 102
	const extHostTerminalService = threadService.set(ExtHostContext.ExtHostTerminalService, new ExtHostTerminalService(threadService));
	const extHostSCM = threadService.set(ExtHostContext.ExtHostSCM, new ExtHostSCM(threadService, extHostCommands));
D
Dirk Baeumer 已提交
103
	const extHostTask = threadService.set(ExtHostContext.ExtHostTask, new ExtHostTask(threadService, extHostWorkspace));
104
	const extHostCredentials = threadService.set(ExtHostContext.ExtHostCredentials, new ExtHostCredentials(threadService));
105
	const extHostWindow = threadService.set(ExtHostContext.ExtHostWindow, new ExtHostWindow(threadService));
106 107 108 109 110
	threadService.set(ExtHostContext.ExtHostExtensionService, extensionService);

	// Check that no named customers are missing
	const expected: ProxyIdentifier<any>[] = Object.keys(ExtHostContext).map((key) => ExtHostContext[key]);
	threadService.assertRegistered(expected);
111

112 113
	// Other instances
	const extHostMessageService = new ExtHostMessageService(threadService);
114
	const extHostDialogs = new ExtHostDialogs(threadService);
115
	const extHostStatusBar = new ExtHostStatusBar(threadService);
116
	const extHostProgress = new ExtHostProgress(threadService.get(MainContext.MainThreadProgress));
117 118
	const extHostOutputService = new ExtHostOutputService(threadService);
	const extHostLanguages = new ExtHostLanguages(threadService);
119

120 121
	// Register API-ish commands
	ExtHostApiCommands.register(extHostCommands);
122

123
	return function (extension: IExtensionDescription): typeof vscode {
124

125
		if (extension.enableProposedApi && !extension.isBuiltin) {
126

127 128 129 130
			if (
				!initData.environment.enableProposedApiForAll &&
				initData.environment.enableProposedApiFor.indexOf(extension.id) < 0
			) {
131
				extension.enableProposedApi = false;
132
				console.error(`Extension '${extension.id} cannot use PROPOSED API (must started out of dev or enabled via --enable-proposed-api)`);
133 134

			} else {
135 136 137
				// 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.`);
138
			}
139 140
		}

141 142 143 144 145 146 147
		const apiUsage = new class {
			private _seen = new Set<string>();
			publicLog(apiName: string) {
				if (this._seen.has(apiName)) {
					return undefined;
				}
				this._seen.add(apiName);
K
kieferrm 已提交
148
				/* __GDPR__
K
kieferrm 已提交
149 150 151 152 153 154 155 156
					"apiUsage" : {
						"name" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
						"extension": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
						"${include}": [
							"${MainThreadData}"
						]
					}
				*/
157
				return mainThreadTelemetry.$publicLog('apiUsage', {
158 159 160 161 162 163
					name: apiName,
					extension: extension.id
				});
			}
		};

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

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

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

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

233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
		// 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 已提交
253 254
			registerImplementationProvider(selector: vscode.DocumentSelector, provider: vscode.ImplementationProvider): vscode.Disposable {
				return languageFeatures.registerImplementationProvider(selector, provider);
255
			},
256 257 258
			registerTypeDefinitionProvider(selector: vscode.DocumentSelector, provider: vscode.TypeDefinitionProvider): vscode.Disposable {
				return languageFeatures.registerTypeDefinitionProvider(selector, provider);
			},
259
			registerHoverProvider(selector: vscode.DocumentSelector, provider: vscode.HoverProvider): vscode.Disposable {
260
				return languageFeatures.registerHoverProvider(selector, provider, extension.id);
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
			},
			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 {
290
				return languageFeatures.registerCompletionItemProvider(selector, provider, triggerCharacters);
291 292 293 294 295 296
			},
			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);
297 298 299 300 301
			},
			// proposed API
			registerColorProvider: proposedApiFunction(extension, (selector: vscode.DocumentSelector, provider: vscode.DocumentColorProvider) => {
				return languageFeatures.registerColorProvider(selector, provider);
			})
302
		};
E
Erich Gamma 已提交
303

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

405 406 407
		// namespace: workspace
		const workspace: typeof vscode.workspace = {
			get rootPath() {
408
				apiUsage.publicLog('workspace#rootPath');
409 410 411 412 413
				return extHostWorkspace.getPath();
			},
			set rootPath(value) {
				throw errors.readonly();
			},
414
			getWorkspaceFolder(resource) {
415
				apiUsage.publicLog('workspace#getWorkspaceFolder');
416
				return extHostWorkspace.getWorkspaceFolder(resource);
417
			},
418
			get workspaceFolders() {
419
				apiUsage.publicLog('workspace#workspaceFolders');
420
				return extHostWorkspace.getWorkspaceFolders();
421
			},
422
			onDidChangeWorkspaceFolders: function (listener, thisArgs?, disposables?) {
423
				apiUsage.publicLog('workspace#onDidChangeWorkspaceFolders');
424
				return extHostWorkspace.onDidChangeWorkspace(listener, thisArgs, disposables);
425
			},
J
Johannes Rieken 已提交
426 427
			asRelativePath: (pathOrUri, includeWorkspace) => {
				return extHostWorkspace.getRelativePath(pathOrUri, includeWorkspace);
428 429 430 431 432 433 434 435
			},
			findFiles: (include, exclude, maxResults?, token?) => {
				return extHostWorkspace.findFiles(include, exclude, maxResults, token);
			},
			saveAll: (includeUntitled?) => {
				return extHostWorkspace.saveAll(includeUntitled);
			},
			applyEdit(edit: vscode.WorkspaceEdit): TPromise<boolean> {
436
				return extHostEditors.applyWorkspaceEdit(edit);
437 438 439 440 441 442 443 444 445 446
			},
			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();
			},
447
			openTextDocument(uriOrFileNameOrOptions?: vscode.Uri | string | { language?: string; content?: string; }) {
B
Benjamin Pasero 已提交
448 449
				let uriPromise: TPromise<URI>;

450
				let options = uriOrFileNameOrOptions as { language?: string; content?: string; };
B
Benjamin Pasero 已提交
451
				if (typeof uriOrFileNameOrOptions === 'string') {
B
Benjamin Pasero 已提交
452 453 454
					uriPromise = TPromise.as(URI.file(uriOrFileNameOrOptions));
				} else if (uriOrFileNameOrOptions instanceof URI) {
					uriPromise = TPromise.as(<URI>uriOrFileNameOrOptions);
B
Benjamin Pasero 已提交
455 456
				} else if (!options || typeof options === 'object') {
					uriPromise = extHostDocuments.createDocumentData(options);
457
				} else {
B
Benjamin Pasero 已提交
458
					throw new Error('illegal argument - uriOrFileNameOrOptions');
459
				}
B
Benjamin Pasero 已提交
460 461 462 463 464 465

				return uriPromise.then(uri => {
					return extHostDocuments.ensureDocumentData(uri).then(() => {
						const data = extHostDocuments.getDocumentData(uri);
						return data && data.document;
					});
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
				});
			},
			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);
482
			},
483
			onDidChangeConfiguration: (listener: (_: any) => any, thisArgs?: any, disposables?: extHostTypes.Disposable[]) => {
484 485
				return extHostConfiguration.onDidChangeConfiguration(listener, thisArgs, disposables);
			},
S
Sandeep Somavarapu 已提交
486 487
			getConfiguration: (section?: string, resource?: vscode.Uri): vscode.WorkspaceConfiguration => {
				return extHostConfiguration.getConfiguration(section, <URI>resource);
488
			},
489 490
			registerTextDocumentContentProvider(scheme: string, provider: vscode.TextDocumentContentProvider) {
				return extHostDocumentContentProviders.registerTextDocumentContentProvider(scheme, provider);
491
			},
492
			registerTaskProvider: (type: string, provider: vscode.TaskProvider) => {
493
				return extHostTask.registerTaskProvider(extension, provider);
J
Johannes Rieken 已提交
494 495
			},
			registerFileSystemProvider: proposedApiFunction(extension, (authority, provider) => {
496
				return extHostFileSystem.registerFileSystemProvider(authority, provider);
J
Johannes Rieken 已提交
497
			})
498
		};
499

500 501
		// namespace: scm
		const scm: typeof vscode.scm = {
502
			get inputBox() {
J
Joao Moreno 已提交
503
				return extHostSCM.getLastInputBox(extension);
504
			},
J
Joao Moreno 已提交
505
			createSourceControl(id: string, label: string, rootUri?: vscode.Uri) {
K
kieferrm 已提交
506
				/* __GDPR__
K
kieferrm 已提交
507 508 509 510 511 512 513 514 515
					"registerSCMProvider" : {
						"extensionId" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
						"providerId": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" },
						"providerLabel": { "classification": "PublicPersonalData", "purpose": "FeatureInsight" },
						"${include}": [
							"${MainThreadData}"
						]
					}
				*/
516
				mainThreadTelemetry.$publicLog('registerSCMProvider', {
517
					extensionId: extension.id,
J
Joao Moreno 已提交
518 519
					providerId: id,
					providerLabel: label
520 521
				});

J
Joao Moreno 已提交
522
				return extHostSCM.createSourceControl(extension, id, label, rootUri);
J
Joao Moreno 已提交
523
			}
524
		};
J
Joao Moreno 已提交
525

526 527
		// namespace: debug
		const debug: typeof vscode.debug = {
528 529 530
			get activeDebugSession() {
				return extHostDebugService.activeDebugSession;
			},
531
			startDebugging(folder: vscode.WorkspaceFolder | undefined, nameOrConfig: string | vscode.DebugConfiguration) {
532
				return extHostDebugService.startDebugging(folder, nameOrConfig);
533
			},
534 535 536
			onDidStartDebugSession(listener, thisArg?, disposables?) {
				return extHostDebugService.onDidStartDebugSession(listener, thisArg, disposables);
			},
537
			onDidTerminateDebugSession(listener, thisArg?, disposables?) {
538
				return extHostDebugService.onDidTerminateDebugSession(listener, thisArg, disposables);
539
			},
A
Andre Weinand 已提交
540
			onDidChangeActiveDebugSession(listener, thisArg?, disposables?) {
541
				return extHostDebugService.onDidChangeActiveDebugSession(listener, thisArg, disposables);
A
Andre Weinand 已提交
542 543
			},
			onDidReceiveDebugSessionCustomEvent(listener, thisArg?, disposables?) {
A
Andre Weinand 已提交
544
				return extHostDebugService.onDidReceiveDebugSessionCustomEvent(listener, thisArg, disposables);
545
			},
A
Andre Weinand 已提交
546
			registerDebugConfigurationProvider(debugType: string, provider: vscode.DebugConfigurationProvider) {
547
				return extHostDebugService.registerDebugConfigurationProvider(debugType, provider);
A
Andre Weinand 已提交
548
			},
549 550
		};

C
Christof Marti 已提交
551
		// namespace: credentials
552
		const credentials = {
C
Christof Marti 已提交
553 554 555 556 557 558 559 560 561 562 563
			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);
			}
		};

564

565
		const api: typeof vscode = {
566 567 568 569 570 571 572 573
			version: pkg.version,
			// namespaces
			commands,
			env,
			extensions,
			languages,
			window,
			workspace,
J
Joao Moreno 已提交
574
			scm,
575
			debug,
576 577 578
			// types
			CancellationTokenSource: CancellationTokenSource,
			CodeLens: extHostTypes.CodeLens,
579
			Color: extHostTypes.Color,
580 581
			ColorPresentation: extHostTypes.ColorPresentation,
			ColorInformation: extHostTypes.ColorInformation,
582
			EndOfLine: extHostTypes.EndOfLine,
583 584 585
			CompletionItem: extHostTypes.CompletionItem,
			CompletionItemKind: extHostTypes.CompletionItemKind,
			CompletionList: extHostTypes.CompletionList,
M
Matt Bierner 已提交
586
			CompletionTriggerKind: extHostTypes.CompletionTriggerKind,
587 588 589 590 591
			Diagnostic: extHostTypes.Diagnostic,
			DiagnosticSeverity: extHostTypes.DiagnosticSeverity,
			Disposable: extHostTypes.Disposable,
			DocumentHighlight: extHostTypes.DocumentHighlight,
			DocumentHighlightKind: extHostTypes.DocumentHighlightKind,
592
			DocumentLink: extHostTypes.DocumentLink,
593 594
			EventEmitter: Emitter,
			Hover: extHostTypes.Hover,
595
			IndentAction: languageConfiguration.IndentAction,
596
			Location: extHostTypes.Location,
597
			MarkdownString: extHostTypes.MarkdownString,
598
			OverviewRulerLane: EditorCommon.OverviewRulerLane,
599 600 601 602 603 604 605 606 607 608 609 610
			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,
611
			TextEditorCursorStyle: TextEditorCursorStyle,
612
			TextEditorLineNumbersStyle: extHostTypes.TextEditorLineNumbersStyle,
613
			TextEditorRevealType: extHostTypes.TextEditorRevealType,
614
			TextEditorSelectionChangeKind: extHostTypes.TextEditorSelectionChangeKind,
615
			DecorationRangeBehavior: extHostTypes.DecorationRangeBehavior,
616
			Uri: URI,
617 618
			ViewColumn: extHostTypes.ViewColumn,
			WorkspaceEdit: extHostTypes.WorkspaceEdit,
J
Johannes Rieken 已提交
619
			ProgressLocation: extHostTypes.ProgressLocation,
S
Sandeep Somavarapu 已提交
620
			TreeItemCollapsibleState: extHostTypes.TreeItemCollapsibleState,
S
Sandeep Somavarapu 已提交
621
			TreeItem: extHostTypes.TreeItem,
622
			ThemeColor: extHostTypes.ThemeColor,
J
Joao Moreno 已提交
623
			// functions
624
			TaskRevealKind: extHostTypes.TaskRevealKind,
625
			TaskPanelKind: extHostTypes.TaskPanelKind,
626
			TaskGroup: extHostTypes.TaskGroup,
D
Dirk Baeumer 已提交
627 628
			ProcessExecution: extHostTypes.ProcessExecution,
			ShellExecution: extHostTypes.ShellExecution,
D
Dirk Baeumer 已提交
629
			TaskScope: extHostTypes.TaskScope,
S
Sandeep Somavarapu 已提交
630
			Task: extHostTypes.Task,
631
			ConfigurationTarget: extHostTypes.ConfigurationTarget,
632
			RelativePattern: extHostTypes.RelativePattern,
633

634
			// TODO@JOH,remote
635 636
			FileChangeType: <any>FileChangeType,
			FileType: <any>FileType
637
		};
638 639
		if (extension.enableProposedApi && extension.isBuiltin) {
			api['credentials'] = credentials;
640 641
		}
		return api;
642
	};
E
Erich Gamma 已提交
643 644 645 646
}

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

A
Alex Dima 已提交
647
	private _extensionService: ExtHostExtensionService;
E
Erich Gamma 已提交
648 649 650 651 652

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

J
Johannes Rieken 已提交
653
	constructor(extensionService: ExtHostExtensionService, description: IExtensionDescription) {
A
Alex Dima 已提交
654
		this._extensionService = extensionService;
E
Erich Gamma 已提交
655 656 657 658 659 660
		this.id = description.id;
		this.extensionPath = paths.normalize(description.extensionFolderPath, true);
		this.packageJSON = description;
	}

	get isActive(): boolean {
A
Alex Dima 已提交
661
		return this._extensionService.isActivated(this.id);
E
Erich Gamma 已提交
662 663 664
	}

	get exports(): T {
A
Alex Dima 已提交
665
		return <T>this._extensionService.getExtensionExports(this.id);
E
Erich Gamma 已提交
666 667 668
	}

	activate(): Thenable<T> {
669
		return this._extensionService.activateById(this.id, false).then(() => this.exports);
E
Erich Gamma 已提交
670 671 672
	}
}

J
Johannes Rieken 已提交
673
export function initializeExtensionApi(extensionService: ExtHostExtensionService, apiFactory: IExtensionApiFactory): TPromise<void> {
674
	return extensionService.getExtensionPathIndex().then(trie => defineAPI(apiFactory, trie));
J
Johannes Rieken 已提交
675 676
}

677
function defineAPI(factory: IExtensionApiFactory, extensionPaths: TernarySearchTree<IExtensionDescription>): void {
J
Johannes Rieken 已提交
678 679

	// each extension is meant to get its own api implementation
J
Johannes Rieken 已提交
680
	const extApiImpl = new Map<string, typeof vscode>();
J
Johannes Rieken 已提交
681
	let defaultApiImpl: typeof vscode;
682 683 684

	const node_module = <any>require.__$__nodeRequire('module');
	const original = node_module._load;
E
Erich Gamma 已提交
685
	node_module._load = function load(request, parent, isMain) {
686 687 688 689 690
		if (request !== 'vscode') {
			return original.apply(this, arguments);
		}

		// get extension id from filename and api for extension
J
Johannes Rieken 已提交
691
		const ext = extensionPaths.findSubstr(parent.filename);
692
		if (ext) {
J
Johannes Rieken 已提交
693
			let apiImpl = extApiImpl.get(ext.id);
694
			if (!apiImpl) {
J
Johannes Rieken 已提交
695 696
				apiImpl = factory(ext);
				extApiImpl.set(ext.id, apiImpl);
697 698 699 700 701 702
			}
			return apiImpl;
		}

		// fall back to a default implementation
		if (!defaultApiImpl) {
703
			defaultApiImpl = factory(nullExtensionDescription);
E
Erich Gamma 已提交
704
		}
705
		return defaultApiImpl;
E
Erich Gamma 已提交
706 707
	};
}
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722

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