extHost.api.impl.ts 33.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 42
import URI from 'vs/base/common/uri';
import Severity from 'vs/base/common/severity';
import EditorCommon = require('vs/editor/common/editorCommon');
J
Johannes Rieken 已提交
43 44 45 46
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';
47
import * as vscode from 'vscode';
E
Erich Gamma 已提交
48
import * as paths from 'vs/base/common/paths';
49
import { MainContext, ExtHostContext, IInitData } from './extHost.protocol';
50
import * as languageConfiguration from 'vs/editor/common/modes/languageConfiguration';
51
import { TextEditorCursorStyle } from 'vs/editor/common/config/editorOptions';
B
Benjamin Pasero 已提交
52 53 54
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';
55 56
import { ExtHostFileSystem } from 'vs/workbench/api/node/extHostFileSystem';
import { FileChangeType, FileType } from 'vs/platform/files/common/files';
57
import { ExtHostDecorations } from 'vs/workbench/api/node/extHostDecorations';
58
import { toGlobPattern, toLanguageSelector } from 'vs/workbench/api/node/extHostTypeConverters';
A
Alex Dima 已提交
59
import { ExtensionActivatedByAPI } from 'vs/workbench/api/node/extHostExtensionActivator';
60
import { isFalsyOrEmpty } from 'vs/base/common/arrays';
E
Erich Gamma 已提交
61

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

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

E
Erich Gamma 已提交
76
/**
77
 * This method instantiates and returns the extension API surface
E
Erich Gamma 已提交
78
 */
79 80
export function createApiFactory(
	initData: IInitData,
81
	threadService: ExtHostThreadService,
82 83
	extHostWorkspace: ExtHostWorkspace,
	extHostConfiguration: ExtHostConfiguration,
J
Joao Moreno 已提交
84
	extensionService: ExtHostExtensionService
85
): IExtensionApiFactory {
86

87
	// Addressable instances
88
	const extHostHeapService = threadService.set(ExtHostContext.ExtHostHeapService, new ExtHostHeapService());
89
	const extHostDecorations = threadService.set(ExtHostContext.ExtHostDecorations, new ExtHostDecorations(threadService));
90
	const extHostDocumentsAndEditors = threadService.set(ExtHostContext.ExtHostDocumentsAndEditors, new ExtHostDocumentsAndEditors(threadService));
91 92
	const extHostDocuments = threadService.set(ExtHostContext.ExtHostDocuments, new ExtHostDocuments(threadService, extHostDocumentsAndEditors));
	const extHostDocumentContentProviders = threadService.set(ExtHostContext.ExtHostDocumentContentProviders, new ExtHostDocumentContentProvider(threadService, extHostDocumentsAndEditors));
93
	const extHostDocumentSaveParticipant = threadService.set(ExtHostContext.ExtHostDocumentSaveParticipant, new ExtHostDocumentSaveParticipant(extHostDocuments, threadService.get(MainContext.MainThreadEditors)));
94
	const extHostEditors = threadService.set(ExtHostContext.ExtHostEditors, new ExtHostEditors(threadService, extHostDocumentsAndEditors));
J
Joao Moreno 已提交
95
	const extHostCommands = threadService.set(ExtHostContext.ExtHostCommands, new ExtHostCommands(threadService, extHostHeapService));
96
	const extHostTreeViews = threadService.set(ExtHostContext.ExtHostTreeViews, new ExtHostTreeViews(threadService.get(MainContext.MainThreadTreeViews), extHostCommands));
97
	threadService.set(ExtHostContext.ExtHostWorkspace, extHostWorkspace);
98
	const extHostDebugService = threadService.set(ExtHostContext.ExtHostDebugService, new ExtHostDebugService(threadService, extHostWorkspace));
99
	threadService.set(ExtHostContext.ExtHostConfiguration, extHostConfiguration);
100 101
	const extHostDiagnostics = threadService.set(ExtHostContext.ExtHostDiagnostics, new ExtHostDiagnostics(threadService));
	const languageFeatures = threadService.set(ExtHostContext.ExtHostLanguageFeatures, new ExtHostLanguageFeatures(threadService, extHostDocuments, extHostCommands, extHostHeapService, extHostDiagnostics));
102
	const extHostFileSystem = threadService.set(ExtHostContext.ExtHostFileSystem, new ExtHostFileSystem(threadService));
103
	const extHostFileSystemEvent = threadService.set(ExtHostContext.ExtHostFileSystemEventService, new ExtHostFileSystemEventService());
104
	const extHostQuickOpen = threadService.set(ExtHostContext.ExtHostQuickOpen, new ExtHostQuickOpen(threadService, extHostWorkspace, extHostCommands));
105
	const extHostTerminalService = threadService.set(ExtHostContext.ExtHostTerminalService, new ExtHostTerminalService(threadService));
J
Joao Moreno 已提交
106
	const extHostSCM = threadService.set(ExtHostContext.ExtHostSCM, new ExtHostSCM(threadService, extHostCommands));
D
Dirk Baeumer 已提交
107
	const extHostTask = threadService.set(ExtHostContext.ExtHostTask, new ExtHostTask(threadService, extHostWorkspace));
108
	const extHostWindow = threadService.set(ExtHostContext.ExtHostWindow, new ExtHostWindow(threadService));
109 110 111 112 113
	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);
114

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

123 124
	// Register API-ish commands
	ExtHostApiCommands.register(extHostCommands);
125

126
	return function (extension: IExtensionDescription): typeof vscode {
127

A
Alex Dima 已提交
128 129
		const EXTENSION_ID = extension.id;

130 131 132 133 134 135
		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;
136

137
		} else if (extension.enableProposedApi && !extension.isBuiltin) {
138 139 140 141
			if (
				!initData.environment.enableProposedApiForAll &&
				initData.environment.enableProposedApiFor.indexOf(extension.id) < 0
			) {
142
				extension.enableProposedApi = false;
143
				console.error(`Extension '${extension.id} cannot use PROPOSED API (must started out of dev or enabled via --enable-proposed-api)`);
144 145

			} else {
146 147 148
				// 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.`);
149
			}
150 151
		}

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

					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) => {
174
						console.warn('An error occurred while running command ' + id, err);
175
					});
176
				});
177 178
			},
			registerDiffInformationCommand: proposedApiFunction(extension, (id: string, callback: (diff: vscode.LineChange[], ...args: any[]) => any, thisArg?: any): vscode.Disposable => {
179 180 181 182 183 184 185 186 187 188
				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]);
				});
189
			}),
190
			executeCommand<T>(id: string, ...args: any[]): Thenable<T> {
191
				return extHostCommands.executeCommand<T>(id, ...args);
192
			},
193 194 195
			getCommands(filterInternal: boolean = false): Thenable<string[]> {
				return extHostCommands.getCommands(filterInternal);
			}
196
		};
197

198 199
		// namespace: env
		const env: typeof vscode.env = Object.freeze({
200 201
			get machineId() { return initData.telemetryInfo.machineId; },
			get sessionId() { return initData.telemetryInfo.sessionId; },
202
			get language() { return Platform.language; },
J
Johannes Rieken 已提交
203 204
			get appName() { return product.nameLong; },
			get appRoot() { return initData.environment.appRoot; },
205
		});
E
Erich Gamma 已提交
206

207 208 209
		// namespace: extensions
		const extensions: typeof vscode.extensions = {
			getExtension(extensionId: string): Extension<any> {
210
				let desc = extensionService.getExtensionDescription(extensionId);
211 212 213
				if (desc) {
					return new Extension(extensionService, desc);
				}
214
				return undefined;
215 216
			},
			get all(): Extension<any>[] {
217
				return extensionService.getAllExtensionDescriptions().map((desc) => new Extension(extensionService, desc));
E
Erich Gamma 已提交
218
			}
219
		};
E
Erich Gamma 已提交
220

221 222 223 224 225 226 227 228 229
		// 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 {
230
				return score(toLanguageSelector(selector), document.uri, document.languageId);
231 232 233 234 235 236 237 238 239 240
			},
			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 已提交
241 242
			registerImplementationProvider(selector: vscode.DocumentSelector, provider: vscode.ImplementationProvider): vscode.Disposable {
				return languageFeatures.registerImplementationProvider(selector, provider);
243
			},
244 245 246
			registerTypeDefinitionProvider(selector: vscode.DocumentSelector, provider: vscode.TypeDefinitionProvider): vscode.Disposable {
				return languageFeatures.registerTypeDefinitionProvider(selector, provider);
			},
247
			registerHoverProvider(selector: vscode.DocumentSelector, provider: vscode.HoverProvider): vscode.Disposable {
248
				return languageFeatures.registerHoverProvider(selector, provider, extension.id);
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
			},
			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 {
278
				return languageFeatures.registerCompletionItemProvider(selector, provider, triggerCharacters);
279 280 281 282
			},
			registerDocumentLinkProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentLinkProvider): vscode.Disposable {
				return languageFeatures.registerDocumentLinkProvider(selector, provider);
			},
283 284 285
			registerColorProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentColorProvider): vscode.Disposable {
				return languageFeatures.registerColorProvider(selector, provider);
			},
286 287
			setLanguageConfiguration: (language: string, configuration: vscode.LanguageConfiguration): vscode.Disposable => {
				return languageFeatures.setLanguageConfiguration(language, configuration);
288
			}
289
		};
E
Erich Gamma 已提交
290

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

395
		// namespace: workspace
396
		let warnedRootPath = false;
397 398
		const workspace: typeof vscode.workspace = {
			get rootPath() {
399 400 401 402
				if (!warnedRootPath) {
					warnedRootPath = true;
					extensionService.addMessage(EXTENSION_ID, Severity.Warning, 'workspace.rootPath is deprecated');
				}
403 404 405 406 407
				return extHostWorkspace.getPath();
			},
			set rootPath(value) {
				throw errors.readonly();
			},
408 409
			getWorkspaceFolder(resource) {
				return extHostWorkspace.getWorkspaceFolder(resource);
410
			},
411
			get workspaceFolders() {
412
				return extHostWorkspace.getWorkspaceFolders();
413
			},
414 415 416 417 418 419
			get name() {
				return extHostWorkspace.workspace ? extHostWorkspace.workspace.name : undefined;
			},
			set name(value) {
				throw errors.readonly();
			},
420
			onDidChangeWorkspaceFolders: function (listener, thisArgs?, disposables?) {
421
				return extHostWorkspace.onDidChangeWorkspace(listener, thisArgs, disposables);
422
			},
J
Johannes Rieken 已提交
423 424
			asRelativePath: (pathOrUri, includeWorkspace) => {
				return extHostWorkspace.getRelativePath(pathOrUri, includeWorkspace);
425 426
			},
			findFiles: (include, exclude, maxResults?, token?) => {
427
				return extHostWorkspace.findFiles(toGlobPattern(include), toGlobPattern(exclude), maxResults, token);
428 429 430 431 432
			},
			saveAll: (includeUntitled?) => {
				return extHostWorkspace.saveAll(includeUntitled);
			},
			applyEdit(edit: vscode.WorkspaceEdit): TPromise<boolean> {
433
				return extHostEditors.applyWorkspaceEdit(edit);
434 435
			},
			createFileSystemWatcher: (pattern, ignoreCreate, ignoreChange, ignoreDelete): vscode.FileSystemWatcher => {
436
				return extHostFileSystemEvent.createFileSystemWatcher(toGlobPattern(pattern), ignoreCreate, ignoreChange, ignoreDelete);
437 438 439 440 441 442 443
			},
			get textDocuments() {
				return extHostDocuments.getAllDocumentData().map(data => data.document);
			},
			set textDocuments(value) {
				throw errors.readonly();
			},
444
			openTextDocument(uriOrFileNameOrOptions?: vscode.Uri | string | { language?: string; content?: string; }) {
B
Benjamin Pasero 已提交
445 446
				let uriPromise: TPromise<URI>;

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

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

498 499
		// namespace: scm
		const scm: typeof vscode.scm = {
500
			get inputBox() {
J
Joao Moreno 已提交
501
				return extHostSCM.getLastInputBox(extension);
502
			},
J
Joao Moreno 已提交
503 504
			createSourceControl(id: string, label: string, rootUri?: vscode.Uri) {
				return extHostSCM.createSourceControl(extension, id, label, rootUri);
J
Joao Moreno 已提交
505
			}
506
		};
J
Joao Moreno 已提交
507

508 509
		// namespace: debug
		const debug: typeof vscode.debug = {
510 511 512
			get activeDebugSession() {
				return extHostDebugService.activeDebugSession;
			},
513 514
			get activeDebugConsole() {
				return extHostDebugService.activeDebugConsole;
515
			},
516 517
			get breakpoints() {
				return extHostDebugService.breakpoints;
518
			},
519 520 521
			onDidStartDebugSession(listener, thisArg?, disposables?) {
				return extHostDebugService.onDidStartDebugSession(listener, thisArg, disposables);
			},
522
			onDidTerminateDebugSession(listener, thisArg?, disposables?) {
523
				return extHostDebugService.onDidTerminateDebugSession(listener, thisArg, disposables);
524
			},
A
Andre Weinand 已提交
525
			onDidChangeActiveDebugSession(listener, thisArg?, disposables?) {
526
				return extHostDebugService.onDidChangeActiveDebugSession(listener, thisArg, disposables);
A
Andre Weinand 已提交
527 528
			},
			onDidReceiveDebugSessionCustomEvent(listener, thisArg?, disposables?) {
A
Andre Weinand 已提交
529
				return extHostDebugService.onDidReceiveDebugSessionCustomEvent(listener, thisArg, disposables);
530
			},
531 532 533 534 535 536
			onDidChangeBreakpoints: proposedApiFunction(extension, (listener, thisArgs?, disposables?) => {
				return extHostDebugService.onDidChangeBreakpoints(listener, thisArgs, disposables);
			}),
			startDebugging(folder: vscode.WorkspaceFolder | undefined, nameOrConfig: string | vscode.DebugConfiguration) {
				return extHostDebugService.startDebugging(folder, nameOrConfig);
			},
A
Andre Weinand 已提交
537
			registerDebugConfigurationProvider(debugType: string, provider: vscode.DebugConfigurationProvider) {
538
				return extHostDebugService.registerDebugConfigurationProvider(debugType, provider);
539
			}
540 541 542
		};


543
		return <typeof vscode>{
544 545 546 547 548 549 550 551
			version: pkg.version,
			// namespaces
			commands,
			env,
			extensions,
			languages,
			window,
			workspace,
J
Joao Moreno 已提交
552
			scm,
553
			debug,
554 555
			// types
			CancellationTokenSource: CancellationTokenSource,
556
			CodeAction: extHostTypes.CodeAction,
557
			CodeLens: extHostTypes.CodeLens,
558
			Color: extHostTypes.Color,
559 560
			ColorPresentation: extHostTypes.ColorPresentation,
			ColorInformation: extHostTypes.ColorInformation,
561
			EndOfLine: extHostTypes.EndOfLine,
562 563 564
			CompletionItem: extHostTypes.CompletionItem,
			CompletionItemKind: extHostTypes.CompletionItemKind,
			CompletionList: extHostTypes.CompletionList,
M
Matt Bierner 已提交
565
			CompletionTriggerKind: extHostTypes.CompletionTriggerKind,
566 567 568 569 570
			Diagnostic: extHostTypes.Diagnostic,
			DiagnosticSeverity: extHostTypes.DiagnosticSeverity,
			Disposable: extHostTypes.Disposable,
			DocumentHighlight: extHostTypes.DocumentHighlight,
			DocumentHighlightKind: extHostTypes.DocumentHighlightKind,
571
			DocumentLink: extHostTypes.DocumentLink,
572 573
			EventEmitter: Emitter,
			Hover: extHostTypes.Hover,
574
			IndentAction: languageConfiguration.IndentAction,
575
			Location: extHostTypes.Location,
576
			MarkdownString: extHostTypes.MarkdownString,
577
			OverviewRulerLane: EditorCommon.OverviewRulerLane,
578 579 580 581 582 583 584 585 586 587 588 589
			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,
590
			TextEditorCursorStyle: TextEditorCursorStyle,
591
			TextEditorLineNumbersStyle: extHostTypes.TextEditorLineNumbersStyle,
592
			TextEditorRevealType: extHostTypes.TextEditorRevealType,
593
			TextEditorSelectionChangeKind: extHostTypes.TextEditorSelectionChangeKind,
594
			DecorationRangeBehavior: extHostTypes.DecorationRangeBehavior,
595
			Uri: URI,
596 597
			ViewColumn: extHostTypes.ViewColumn,
			WorkspaceEdit: extHostTypes.WorkspaceEdit,
J
Johannes Rieken 已提交
598
			ProgressLocation: extHostTypes.ProgressLocation,
S
Sandeep Somavarapu 已提交
599
			TreeItemCollapsibleState: extHostTypes.TreeItemCollapsibleState,
S
Sandeep Somavarapu 已提交
600
			TreeItem: extHostTypes.TreeItem,
601
			ThemeColor: extHostTypes.ThemeColor,
J
Joao Moreno 已提交
602
			// functions
603
			TaskRevealKind: extHostTypes.TaskRevealKind,
604
			TaskPanelKind: extHostTypes.TaskPanelKind,
605
			TaskGroup: extHostTypes.TaskGroup,
D
Dirk Baeumer 已提交
606 607
			ProcessExecution: extHostTypes.ProcessExecution,
			ShellExecution: extHostTypes.ShellExecution,
D
Dirk Baeumer 已提交
608
			TaskScope: extHostTypes.TaskScope,
S
Sandeep Somavarapu 已提交
609
			Task: extHostTypes.Task,
610
			ConfigurationTarget: extHostTypes.ConfigurationTarget,
611
			RelativePattern: extHostTypes.RelativePattern,
612

613
			// TODO@JOH,remote
614 615
			FileChangeType: <any>FileChangeType,
			FileType: <any>FileType
616
		};
617
	};
E
Erich Gamma 已提交
618 619 620 621
}

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

A
Alex Dima 已提交
622
	private _extensionService: ExtHostExtensionService;
E
Erich Gamma 已提交
623 624 625 626 627

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

J
Johannes Rieken 已提交
628
	constructor(extensionService: ExtHostExtensionService, description: IExtensionDescription) {
A
Alex Dima 已提交
629
		this._extensionService = extensionService;
E
Erich Gamma 已提交
630 631 632 633 634 635
		this.id = description.id;
		this.extensionPath = paths.normalize(description.extensionFolderPath, true);
		this.packageJSON = description;
	}

	get isActive(): boolean {
A
Alex Dima 已提交
636
		return this._extensionService.isActivated(this.id);
E
Erich Gamma 已提交
637 638 639
	}

	get exports(): T {
A
Alex Dima 已提交
640
		return <T>this._extensionService.getExtensionExports(this.id);
E
Erich Gamma 已提交
641 642 643
	}

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

J
Johannes Rieken 已提交
648
export function initializeExtensionApi(extensionService: ExtHostExtensionService, apiFactory: IExtensionApiFactory): TPromise<void> {
649
	return extensionService.getExtensionPathIndex().then(trie => defineAPI(apiFactory, trie));
J
Johannes Rieken 已提交
650 651
}

652
function defineAPI(factory: IExtensionApiFactory, extensionPaths: TernarySearchTree<IExtensionDescription>): void {
J
Johannes Rieken 已提交
653 654

	// each extension is meant to get its own api implementation
J
Johannes Rieken 已提交
655
	const extApiImpl = new Map<string, typeof vscode>();
J
Johannes Rieken 已提交
656
	let defaultApiImpl: typeof vscode;
657 658 659

	const node_module = <any>require.__$__nodeRequire('module');
	const original = node_module._load;
E
Erich Gamma 已提交
660
	node_module._load = function load(request, parent, isMain) {
661 662 663 664 665
		if (request !== 'vscode') {
			return original.apply(this, arguments);
		}

		// get extension id from filename and api for extension
J
Johannes Rieken 已提交
666
		const ext = extensionPaths.findSubstr(parent.filename);
667
		if (ext) {
J
Johannes Rieken 已提交
668
			let apiImpl = extApiImpl.get(ext.id);
669
			if (!apiImpl) {
J
Johannes Rieken 已提交
670 671
				apiImpl = factory(ext);
				extApiImpl.set(ext.id, apiImpl);
672 673 674 675 676 677
			}
			return apiImpl;
		}

		// fall back to a default implementation
		if (!defaultApiImpl) {
678
			defaultApiImpl = factory(nullExtensionDescription);
E
Erich Gamma 已提交
679
		}
680
		return defaultApiImpl;
E
Erich Gamma 已提交
681 682
	};
}
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697

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