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

6
import * as nls from 'vs/nls';
A
Alex Dima 已提交
7 8
import { CancellationTokenSource } from 'vs/base/common/cancellation';
import * as errors from 'vs/base/common/errors';
J
Joao Moreno 已提交
9
import { Emitter, Event } from 'vs/base/common/event';
10
import * as path from 'vs/base/common/path';
A
Alex Dima 已提交
11 12 13 14 15 16 17
import Severity from 'vs/base/common/severity';
import { URI } from 'vs/base/common/uri';
import { TextEditorCursorStyle } from 'vs/editor/common/config/editorOptions';
import { OverviewRulerLane } from 'vs/editor/common/model';
import * as languageConfiguration from 'vs/editor/common/modes/languageConfiguration';
import { score } from 'vs/editor/common/modes/languageSelector';
import * as files from 'vs/platform/files/common/files';
J
Johannes Rieken 已提交
18
import { ExtHostContext, IInitData, IMainContext, MainContext } from 'vs/workbench/api/common/extHost.protocol';
J
Johannes Rieken 已提交
19 20 21 22 23
import { ExtHostApiCommands } from 'vs/workbench/api/common/extHostApiCommands';
import { ExtHostClipboard } from 'vs/workbench/api/common/extHostClipboard';
import { ExtHostCommands } from 'vs/workbench/api/common/extHostCommands';
import { ExtHostComments } from 'vs/workbench/api/common/extHostComments';
import { ExtHostConfiguration, ExtHostConfigProvider } from 'vs/workbench/api/common/extHostConfiguration';
A
Alex Dima 已提交
24
import { ExtHostDebugService } from 'vs/workbench/api/node/extHostDebugService';
J
Johannes Rieken 已提交
25 26 27 28 29 30 31
import { ExtHostDecorations } from 'vs/workbench/api/common/extHostDecorations';
import { ExtHostDiagnostics } from 'vs/workbench/api/common/extHostDiagnostics';
import { ExtHostDialogs } from 'vs/workbench/api/common/extHostDialogs';
import { ExtHostDocumentContentProvider } from 'vs/workbench/api/common/extHostDocumentContentProviders';
import { ExtHostDocumentSaveParticipant } from 'vs/workbench/api/common/extHostDocumentSaveParticipant';
import { ExtHostDocuments } from 'vs/workbench/api/common/extHostDocuments';
import { ExtHostDocumentsAndEditors } from 'vs/workbench/api/common/extHostDocumentsAndEditors';
32
import { ExtensionActivatedByAPI } from 'vs/workbench/api/common/extHostExtensionActivator';
A
Alex Dima 已提交
33
import { ExtHostExtensionService } from 'vs/workbench/api/node/extHostExtensionService';
J
Johannes Rieken 已提交
34 35
import { ExtHostFileSystem } from 'vs/workbench/api/common/extHostFileSystem';
import { ExtHostFileSystemEventService } from 'vs/workbench/api/common/extHostFileSystemEventService';
36
import { ExtHostLanguageFeatures } from 'vs/workbench/api/common/extHostLanguageFeatures';
J
Johannes Rieken 已提交
37
import { ExtHostLanguages } from 'vs/workbench/api/common/extHostLanguages';
J
Johannes Rieken 已提交
38
import { ExtHostLogService } from 'vs/workbench/api/common/extHostLogService';
J
Johannes Rieken 已提交
39
import { ExtHostMessageService } from 'vs/workbench/api/common/extHostMessageService';
40 41
import { ExtHostOutputService } from 'vs/workbench/api/common/extHostOutput';
import { LogOutputChannelFactory } from 'vs/workbench/api/node/extHostOutputService';
J
Johannes Rieken 已提交
42 43 44
import { ExtHostProgress } from 'vs/workbench/api/common/extHostProgress';
import { ExtHostQuickOpen } from 'vs/workbench/api/common/extHostQuickOpen';
import { ExtHostSCM } from 'vs/workbench/api/common/extHostSCM';
A
Alex Dima 已提交
45
import { ExtHostSearch, registerEHSearchProviders } from 'vs/workbench/api/node/extHostSearch';
J
Johannes Rieken 已提交
46 47
import { ExtHostStatusBar } from 'vs/workbench/api/common/extHostStatusBar';
import { ExtHostStorage } from 'vs/workbench/api/common/extHostStorage';
A
Alex Dima 已提交
48
import { ExtHostTask } from 'vs/workbench/api/node/extHostTask';
J
Johannes Rieken 已提交
49
import { ExtHostTerminalService } from 'vs/workbench/api/node/extHostTerminalService';
J
Johannes Rieken 已提交
50 51 52 53 54 55 56 57
import { ExtHostEditors } from 'vs/workbench/api/common/extHostTextEditors';
import { ExtHostTreeViews } from 'vs/workbench/api/common/extHostTreeViews';
import * as typeConverters from 'vs/workbench/api/common/extHostTypeConverters';
import * as extHostTypes from 'vs/workbench/api/common/extHostTypes';
import { ExtHostUrls } from 'vs/workbench/api/common/extHostUrls';
import { ExtHostWebviews } from 'vs/workbench/api/common/extHostWebview';
import { ExtHostWindow } from 'vs/workbench/api/common/extHostWindow';
import { ExtHostWorkspace } from 'vs/workbench/api/common/extHostWorkspace';
J
Johannes Rieken 已提交
58
import { throwProposedApiError, checkProposedApiEnabled } from 'vs/workbench/services/extensions/common/extensions';
J
Johannes Rieken 已提交
59
import { ProxyIdentifier } from 'vs/workbench/services/extensions/common/proxyIdentifier';
60
import { ExtensionDescriptionRegistry } from 'vs/workbench/services/extensions/common/extensionDescriptionRegistry';
A
Alex Dima 已提交
61
import * as vscode from 'vscode';
62
import { ExtensionIdentifier, IExtensionDescription } from 'vs/platform/extensions/common/extensions';
63
import { originalFSPath } from 'vs/base/common/resources';
64
import { CLIServer } from 'vs/workbench/api/node/extHostCLIServer';
65
import { withNullAsUndefined } from 'vs/base/common/types';
J
Johannes Rieken 已提交
66
import { values } from 'vs/base/common/collections';
A
Alex Dima 已提交
67
import { Schemas } from 'vs/base/common/network';
68
import { IURITransformer } from 'vs/base/common/uriIpc';
69
import { ExtHostEditorInsets } from 'vs/workbench/api/common/extHostCodeInsets';
E
Erich Gamma 已提交
70

71
export interface IExtensionApiFactory {
72
	(extension: IExtensionDescription, registry: ExtensionDescriptionRegistry, configProvider: ExtHostConfigProvider): typeof vscode;
73 74
}

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

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

97
	// Addressable instances
98
	rpcProtocol.set(ExtHostContext.ExtHostLogService, extHostLogService);
A
Alex Dima 已提交
99
	const extHostDecorations = rpcProtocol.set(ExtHostContext.ExtHostDecorations, new ExtHostDecorations(rpcProtocol));
M
Matt Bierner 已提交
100
	const extHostWebviews = rpcProtocol.set(ExtHostContext.ExtHostWebviews, new ExtHostWebviews(rpcProtocol));
J
Joao Moreno 已提交
101
	const extHostUrls = rpcProtocol.set(ExtHostContext.ExtHostUrls, new ExtHostUrls(rpcProtocol));
102
	const extHostDocumentsAndEditors = rpcProtocol.set(ExtHostContext.ExtHostDocumentsAndEditors, new ExtHostDocumentsAndEditors(rpcProtocol));
A
Alex Dima 已提交
103
	const extHostDocuments = rpcProtocol.set(ExtHostContext.ExtHostDocuments, new ExtHostDocuments(rpcProtocol, extHostDocumentsAndEditors));
104
	const extHostDocumentContentProviders = rpcProtocol.set(ExtHostContext.ExtHostDocumentContentProviders, new ExtHostDocumentContentProvider(rpcProtocol, extHostDocumentsAndEditors, extHostLogService));
105
	const extHostDocumentSaveParticipant = rpcProtocol.set(ExtHostContext.ExtHostDocumentSaveParticipant, new ExtHostDocumentSaveParticipant(extHostLogService, extHostDocuments, rpcProtocol.getProxy(MainContext.MainThreadTextEditors)));
A
Alex Dima 已提交
106
	const extHostEditors = rpcProtocol.set(ExtHostContext.ExtHostEditors, new ExtHostEditors(rpcProtocol, extHostDocumentsAndEditors));
107
	const extHostCommands = rpcProtocol.set(ExtHostContext.ExtHostCommands, new ExtHostCommands(rpcProtocol, extHostLogService));
S
Sandeep Somavarapu 已提交
108
	const extHostTreeViews = rpcProtocol.set(ExtHostContext.ExtHostTreeViews, new ExtHostTreeViews(rpcProtocol.getProxy(MainContext.MainThreadTreeViews), extHostCommands, extHostLogService));
A
Alex Dima 已提交
109 110
	rpcProtocol.set(ExtHostContext.ExtHostWorkspace, extHostWorkspace);
	rpcProtocol.set(ExtHostContext.ExtHostConfiguration, extHostConfiguration);
111
	const extHostEditorInsets = rpcProtocol.set(ExtHostContext.ExtHostEditorInsets, new ExtHostEditorInsets(rpcProtocol.getProxy(MainContext.MainThreadEditorInsets), extHostEditors));
A
Alex Dima 已提交
112
	const extHostDiagnostics = rpcProtocol.set(ExtHostContext.ExtHostDiagnostics, new ExtHostDiagnostics(rpcProtocol));
113
	const extHostLanguageFeatures = rpcProtocol.set(ExtHostContext.ExtHostLanguageFeatures, new ExtHostLanguageFeatures(rpcProtocol, uriTransformer, extHostDocuments, extHostCommands, extHostDiagnostics, extHostLogService));
114
	const extHostFileSystem = rpcProtocol.set(ExtHostContext.ExtHostFileSystem, new ExtHostFileSystem(rpcProtocol, extHostLanguageFeatures));
115
	const extHostFileSystemEvent = rpcProtocol.set(ExtHostContext.ExtHostFileSystemEventService, new ExtHostFileSystemEventService(rpcProtocol, extHostDocumentsAndEditors));
A
Alex Dima 已提交
116
	const extHostQuickOpen = rpcProtocol.set(ExtHostContext.ExtHostQuickOpen, new ExtHostQuickOpen(rpcProtocol, extHostWorkspace, extHostCommands));
117
	const extHostTerminalService = rpcProtocol.set(ExtHostContext.ExtHostTerminalService, new ExtHostTerminalService(rpcProtocol, extHostConfiguration, extHostWorkspace, extHostDocumentsAndEditors, extHostLogService));
118
	const extHostDebugService = rpcProtocol.set(ExtHostContext.ExtHostDebugService, new ExtHostDebugService(rpcProtocol, extHostWorkspace, extensionService, extHostDocumentsAndEditors, extHostConfiguration, extHostTerminalService, extHostCommands));
119
	const extHostSCM = rpcProtocol.set(ExtHostContext.ExtHostSCM, new ExtHostSCM(rpcProtocol, extHostCommands, extHostLogService));
P
Peng Lyu 已提交
120
	const extHostComment = rpcProtocol.set(ExtHostContext.ExtHostComments, new ExtHostComments(rpcProtocol, extHostCommands, extHostDocuments));
121
	const extHostSearch = rpcProtocol.set(ExtHostContext.ExtHostSearch, new ExtHostSearch(rpcProtocol, uriTransformer, extHostLogService));
122
	const extHostTask = rpcProtocol.set(ExtHostContext.ExtHostTask, new ExtHostTask(rpcProtocol, extHostWorkspace, extHostDocumentsAndEditors, extHostConfiguration, extHostTerminalService));
A
Alex Dima 已提交
123 124
	const extHostWindow = rpcProtocol.set(ExtHostContext.ExtHostWindow, new ExtHostWindow(rpcProtocol));
	rpcProtocol.set(ExtHostContext.ExtHostExtensionService, extensionService);
125
	const extHostProgress = rpcProtocol.set(ExtHostContext.ExtHostProgress, new ExtHostProgress(rpcProtocol.getProxy(MainContext.MainThreadProgress)));
126
	const extHostOutputService = rpcProtocol.set(ExtHostContext.ExtHostOutputService, new ExtHostOutputService(LogOutputChannelFactory, initData.logsLocation, rpcProtocol));
127
	rpcProtocol.set(ExtHostContext.ExtHostStorage, extHostStorage);
128
	if (initData.remote.authority) {
A
Alex Dima 已提交
129 130
		extHostTask.registerTaskSystem(Schemas.vscodeRemote, {
			scheme: Schemas.vscodeRemote,
131
			authority: initData.remote.authority,
A
Alex Dima 已提交
132 133 134 135 136
			platform: process.platform
		});

		registerEHSearchProviders(extHostSearch, extHostLogService);

137 138 139
		const cliServer = new CLIServer(extHostCommands);
		process.env['VSCODE_IPC_HOOK_CLI'] = cliServer.ipcHandlePath;
	}
140 141

	// Check that no named customers are missing
J
Johannes Rieken 已提交
142
	const expected: ProxyIdentifier<any>[] = values(ExtHostContext);
A
Alex Dima 已提交
143
	rpcProtocol.assertRegistered(expected);
144

145
	// Other instances
146
	const extHostClipboard = new ExtHostClipboard(rpcProtocol);
A
Alex Dima 已提交
147 148 149
	const extHostMessageService = new ExtHostMessageService(rpcProtocol);
	const extHostDialogs = new ExtHostDialogs(rpcProtocol);
	const extHostStatusBar = new ExtHostStatusBar(rpcProtocol);
150
	const extHostLanguages = new ExtHostLanguages(rpcProtocol, extHostDocuments);
151

152
	// Register an output channel for exthost log
153
	const outputChannelName = initData.remote.isRemote ? nls.localize('remote extension host Log', "Remote Extension Host") : nls.localize('extension host Log', "Extension Host");
A
Alex Dima 已提交
154
	extHostOutputService.createOutputChannelFromLogFile(outputChannelName, extHostLogService.logFile);
155

156
	// Register API-ish commands
157
	ExtHostApiCommands.register(extHostCommands);
158

159
	return function (extension: IExtensionDescription, extensionRegistry: ExtensionDescriptionRegistry, configProvider: ExtHostConfigProvider): typeof vscode {
160

161 162
		// Check document selectors for being overly generic. Technically this isn't a problem but
		// in practice many extensions say they support `fooLang` but need fs-access to do so. Those
163
		// extension should specify then the `file`-scheme, e.g. `{ scheme: 'fooLang', language: 'fooLang' }`
164 165
		// We only inform once, it is not a warning because we just want to raise awareness and because
		// we cannot say if the extension is doing it right or wrong...
166
		const checkSelector = (function () {
A
Alex Dima 已提交
167
			let done = (!extension.isUnderDevelopment);
168 169
			function informOnce(selector: vscode.DocumentSelector) {
				if (!done) {
170
					console.info(`Extension '${extension.identifier.value}' uses a document selector without scheme. Learn more about this: https://go.microsoft.com/fwlink/?linkid=872305`);
171 172
					done = true;
				}
173
			}
174
			return function perform(selector: vscode.DocumentSelector): vscode.DocumentSelector {
175 176 177 178 179 180 181 182 183 184
				if (Array.isArray(selector)) {
					selector.forEach(perform);
				} else if (typeof selector === 'string') {
					informOnce(selector);
				} else {
					if (typeof selector.scheme === 'undefined') {
						informOnce(selector);
					}
					if (!extension.enableProposedApi && typeof selector.exclusive === 'boolean') {
						throwProposedApiError(extension);
185 186 187 188 189
					}
				}
				return selector;
			};
		})();
190

191

192 193
		// namespace: commands
		const commands: typeof vscode.commands = {
M
Matt Bierner 已提交
194
			registerCommand(id: string, command: <T>(...args: any[]) => T | Thenable<T>, thisArgs?: any): vscode.Disposable {
195
				return extHostCommands.registerCommand(true, id, command, thisArgs);
196
			},
197
			registerTextEditorCommand(id: string, callback: (textEditor: vscode.TextEditor, edit: vscode.TextEditorEdit, ...args: any[]) => void, thisArg?: any): vscode.Disposable {
198
				return extHostCommands.registerCommand(true, id, (...args: any[]): any => {
199
					const activeTextEditor = extHostEditors.getActiveTextEditor();
200 201
					if (!activeTextEditor) {
						console.warn('Cannot execute ' + id + ' because there is no active text editor.');
202
						return undefined;
203
					}
204 205 206 207 208 209 210 211 212 213

					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) => {
214
						console.warn('An error occurred while running command ' + id, err);
215
					});
216
				});
217 218
			},
			registerDiffInformationCommand: proposedApiFunction(extension, (id: string, callback: (diff: vscode.LineChange[], ...args: any[]) => any, thisArg?: any): vscode.Disposable => {
219
				return extHostCommands.registerCommand(true, id, async (...args: any[]): Promise<any> => {
220
					const activeTextEditor = extHostEditors.getActiveTextEditor();
221 222 223 224 225 226 227 228
					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]);
				});
229
			}),
230
			executeCommand<T>(id: string, ...args: any[]): Thenable<T> {
M
Matt Bierner 已提交
231
				return extHostCommands.executeCommand<T>(id, ...args);
232
			},
233 234 235
			getCommands(filterInternal: boolean = false): Thenable<string[]> {
				return extHostCommands.getCommands(filterInternal);
			}
236
		};
237

238
		// namespace: env
239
		const env: typeof vscode.env = {
240 241
			get machineId() { return initData.telemetryInfo.machineId; },
			get sessionId() { return initData.telemetryInfo.sessionId; },
242 243
			get language() { return initData.environment.appLanguage; },
			get appName() { return initData.environment.appName; },
244
			get appRoot() { return initData.environment.appRoot!.fsPath; },
245
			get uriScheme() { return initData.environment.appUriScheme; },
246 247
			get logLevel() {
				checkProposedApiEnabled(extension);
248
				return typeConverters.LogLevel.to(extHostLogService.getLevel());
249 250 251
			},
			get onDidChangeLogLevel() {
				checkProposedApiEnabled(extension);
J
Joao Moreno 已提交
252
				return Event.map(extHostLogService.onDidChangeLogLevel, l => typeConverters.LogLevel.to(l));
253 254 255
			},
			get clipboard(): vscode.Clipboard {
				return extHostClipboard;
256
			},
D
Daniel Imms 已提交
257
			get shell() {
258
				checkProposedApiEnabled(extension);
D
Daniel Imms 已提交
259 260
				return extHostTerminalService.getDefaultShell(configProvider);
			},
J
Johannes Rieken 已提交
261
			openExternal(uri: URI) {
262
				return extHostWindow.openUri(uri, { allowTunneling: !!initData.remote.isRemote });
263 264 265 266 267
			},
			get webviewResourceRoot() {
				checkProposedApiEnabled(extension);
				return initData.environment.webviewResourceRoot;
			},
268 269 270 271 272 273 274 275 276 277 278 279
			get remoteName() {
				checkProposedApiEnabled(extension);
				if (!initData.remote.authority) {
					return undefined;
				}
				const pos = initData.remote.authority.indexOf('+');
				if (pos < 0) {
					// funky? bad authority?
					return initData.remote.authority;
				}
				return initData.remote.authority.substr(0, pos);
			}
280 281 282 283 284
		};
		if (!initData.environment.extensionTestsLocationURI) {
			// allow to patch env-function when running tests
			Object.freeze(env);
		}
E
Erich Gamma 已提交
285

286 287
		// namespace: extensions
		const extensions: typeof vscode.extensions = {
288 289
			getExtension(extensionId: string): Extension<any> | undefined {
				const desc = extensionRegistry.getExtensionDescription(extensionId);
290 291 292
				if (desc) {
					return new Extension(extensionService, desc);
				}
293
				return undefined;
294 295
			},
			get all(): Extension<any>[] {
A
Alex Dima 已提交
296
				return extensionRegistry.getAllExtensionDescriptions().map((desc) => new Extension(extensionService, desc));
297 298 299
			},
			get onDidChange() {
				return extensionRegistry.onDidChange;
E
Erich Gamma 已提交
300
			}
301
		};
E
Erich Gamma 已提交
302

303 304 305 306 307
		// namespace: languages
		const languages: typeof vscode.languages = {
			createDiagnosticCollection(name?: string): vscode.DiagnosticCollection {
				return extHostDiagnostics.createDiagnosticCollection(name);
			},
308 309 310
			get onDidChangeDiagnostics() {
				return extHostDiagnostics.onDidChangeDiagnostics;
			},
A
Alex Dima 已提交
311
			getDiagnostics: (resource?: vscode.Uri) => {
312 313
				return <any>extHostDiagnostics.getDiagnostics(resource);
			},
314
			getLanguages(): Thenable<string[]> {
315 316
				return extHostLanguages.getLanguages();
			},
317
			setTextDocumentLanguage(document: vscode.TextDocument, languageId: string): Thenable<vscode.TextDocument> {
M
mechatroner 已提交
318
				return extHostLanguages.changeLanguage(document.uri, languageId);
319
			},
320
			match(selector: vscode.DocumentSelector, document: vscode.TextDocument): number {
321
				return score(typeConverters.LanguageSelector.from(selector), document.uri, document.languageId, true);
322
			},
323
			registerCodeActionsProvider(selector: vscode.DocumentSelector, provider: vscode.CodeActionProvider, metadata?: vscode.CodeActionProviderMetadata): vscode.Disposable {
324
				return extHostLanguageFeatures.registerCodeActionProvider(extension, checkSelector(selector), provider, metadata);
325 326
			},
			registerCodeLensProvider(selector: vscode.DocumentSelector, provider: vscode.CodeLensProvider): vscode.Disposable {
327
				return extHostLanguageFeatures.registerCodeLensProvider(extension, checkSelector(selector), provider);
328 329
			},
			registerDefinitionProvider(selector: vscode.DocumentSelector, provider: vscode.DefinitionProvider): vscode.Disposable {
330
				return extHostLanguageFeatures.registerDefinitionProvider(extension, checkSelector(selector), provider);
331
			},
332 333 334
			registerDeclarationProvider(selector: vscode.DocumentSelector, provider: vscode.DeclarationProvider): vscode.Disposable {
				return extHostLanguageFeatures.registerDeclarationProvider(extension, checkSelector(selector), provider);
			},
M
Matt Bierner 已提交
335
			registerImplementationProvider(selector: vscode.DocumentSelector, provider: vscode.ImplementationProvider): vscode.Disposable {
336
				return extHostLanguageFeatures.registerImplementationProvider(extension, checkSelector(selector), provider);
337
			},
338
			registerTypeDefinitionProvider(selector: vscode.DocumentSelector, provider: vscode.TypeDefinitionProvider): vscode.Disposable {
339
				return extHostLanguageFeatures.registerTypeDefinitionProvider(extension, checkSelector(selector), provider);
340
			},
341
			registerHoverProvider(selector: vscode.DocumentSelector, provider: vscode.HoverProvider): vscode.Disposable {
342
				return extHostLanguageFeatures.registerHoverProvider(extension, checkSelector(selector), provider, extension.identifier);
343 344
			},
			registerDocumentHighlightProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentHighlightProvider): vscode.Disposable {
345
				return extHostLanguageFeatures.registerDocumentHighlightProvider(extension, checkSelector(selector), provider);
346 347
			},
			registerReferenceProvider(selector: vscode.DocumentSelector, provider: vscode.ReferenceProvider): vscode.Disposable {
348
				return extHostLanguageFeatures.registerReferenceProvider(extension, checkSelector(selector), provider);
349 350
			},
			registerRenameProvider(selector: vscode.DocumentSelector, provider: vscode.RenameProvider): vscode.Disposable {
351
				return extHostLanguageFeatures.registerRenameProvider(extension, checkSelector(selector), provider);
352
			},
353 354
			registerDocumentSymbolProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentSymbolProvider, metadata?: vscode.DocumentSymbolProviderMetadata): vscode.Disposable {
				return extHostLanguageFeatures.registerDocumentSymbolProvider(extension, checkSelector(selector), provider, metadata);
355 356
			},
			registerWorkspaceSymbolProvider(provider: vscode.WorkspaceSymbolProvider): vscode.Disposable {
357
				return extHostLanguageFeatures.registerWorkspaceSymbolProvider(extension, provider);
358 359
			},
			registerDocumentFormattingEditProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentFormattingEditProvider): vscode.Disposable {
360
				return extHostLanguageFeatures.registerDocumentFormattingEditProvider(extension, checkSelector(selector), provider);
361 362
			},
			registerDocumentRangeFormattingEditProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentRangeFormattingEditProvider): vscode.Disposable {
363
				return extHostLanguageFeatures.registerDocumentRangeFormattingEditProvider(extension, checkSelector(selector), provider);
364 365
			},
			registerOnTypeFormattingEditProvider(selector: vscode.DocumentSelector, provider: vscode.OnTypeFormattingEditProvider, firstTriggerCharacter: string, ...moreTriggerCharacters: string[]): vscode.Disposable {
366
				return extHostLanguageFeatures.registerOnTypeFormattingEditProvider(extension, checkSelector(selector), provider, [firstTriggerCharacter].concat(moreTriggerCharacters));
367
			},
368 369
			registerSignatureHelpProvider(selector: vscode.DocumentSelector, provider: vscode.SignatureHelpProvider, firstItem?: string | vscode.SignatureHelpProviderMetadata, ...remaining: string[]): vscode.Disposable {
				if (typeof firstItem === 'object') {
370
					return extHostLanguageFeatures.registerSignatureHelpProvider(extension, checkSelector(selector), provider, firstItem);
371
				}
372
				return extHostLanguageFeatures.registerSignatureHelpProvider(extension, checkSelector(selector), provider, typeof firstItem === 'undefined' ? [] : [firstItem, ...remaining]);
373 374
			},
			registerCompletionItemProvider(selector: vscode.DocumentSelector, provider: vscode.CompletionItemProvider, ...triggerCharacters: string[]): vscode.Disposable {
375
				return extHostLanguageFeatures.registerCompletionItemProvider(extension, checkSelector(selector), provider, triggerCharacters);
376 377
			},
			registerDocumentLinkProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentLinkProvider): vscode.Disposable {
378
				return extHostLanguageFeatures.registerDocumentLinkProvider(extension, checkSelector(selector), provider);
379
			},
380
			registerColorProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentColorProvider): vscode.Disposable {
381
				return extHostLanguageFeatures.registerColorProvider(extension, checkSelector(selector), provider);
382
			},
383
			registerFoldingRangeProvider(selector: vscode.DocumentSelector, provider: vscode.FoldingRangeProvider): vscode.Disposable {
384
				return extHostLanguageFeatures.registerFoldingRangeProvider(extension, checkSelector(selector), provider);
385
			},
386 387 388
			registerSelectionRangeProvider(selector: vscode.DocumentSelector, provider: vscode.SelectionRangeProvider): vscode.Disposable {
				return extHostLanguageFeatures.registerSelectionRangeProvider(extension, selector, provider);
			},
389 390 391 392
			registerCallHierarchyProvider(selector: vscode.DocumentSelector, provider: vscode.CallHierarchyItemProvider): vscode.Disposable {
				checkProposedApiEnabled(extension);
				return extHostLanguageFeatures.registerCallHierarchyProvider(extension, selector, provider);
			},
393
			setLanguageConfiguration: (language: string, configuration: vscode.LanguageConfiguration): vscode.Disposable => {
394
				return extHostLanguageFeatures.setLanguageConfiguration(language, configuration);
395
			}
396
		};
E
Erich Gamma 已提交
397

398 399 400 401 402 403 404 405
		// namespace: window
		const window: typeof vscode.window = {
			get activeTextEditor() {
				return extHostEditors.getActiveTextEditor();
			},
			get visibleTextEditors() {
				return extHostEditors.getVisibleTextEditors();
			},
406
			get activeTerminal() {
D
Daniel Imms 已提交
407
				return extHostTerminalService.activeTerminal;
408
			},
D
Daniel Imms 已提交
409
			get terminals() {
D
Daniel Imms 已提交
410
				return extHostTerminalService.terminals;
D
Daniel Imms 已提交
411
			},
412
			showTextDocument(documentOrUri: vscode.TextDocument | vscode.Uri, columnOrOptions?: vscode.ViewColumn | vscode.TextDocumentShowOptions, preserveFocus?: boolean): Thenable<vscode.TextEditor> {
413
				let documentPromise: Promise<vscode.TextDocument>;
J
Johannes Rieken 已提交
414
				if (URI.isUri(documentOrUri)) {
415
					documentPromise = Promise.resolve(workspace.openTextDocument(documentOrUri));
B
Benjamin Pasero 已提交
416
				} else {
417
					documentPromise = Promise.resolve(<vscode.TextDocument>documentOrUri);
B
Benjamin Pasero 已提交
418 419 420 421
				}
				return documentPromise.then(document => {
					return extHostEditors.showTextDocument(document, columnOrOptions, preserveFocus);
				});
422 423 424 425
			},
			createTextEditorDecorationType(options: vscode.DecorationRenderOptions): vscode.TextEditorDecorationType {
				return extHostEditors.createTextEditorDecorationType(options);
			},
426 427 428
			onDidChangeActiveTextEditor(listener, thisArg?, disposables?) {
				return extHostEditors.onDidChangeActiveTextEditor(listener, thisArg, disposables);
			},
429 430 431
			onDidChangeVisibleTextEditors(listener, thisArg, disposables) {
				return extHostEditors.onDidChangeVisibleTextEditors(listener, thisArg, disposables);
			},
432
			onDidChangeTextEditorSelection(listener: (e: vscode.TextEditorSelectionChangeEvent) => any, thisArgs?: any, disposables?: extHostTypes.Disposable[]) {
433 434
				return extHostEditors.onDidChangeTextEditorSelection(listener, thisArgs, disposables);
			},
435
			onDidChangeTextEditorOptions(listener: (e: vscode.TextEditorOptionsChangeEvent) => any, thisArgs?: any, disposables?: extHostTypes.Disposable[]) {
436 437
				return extHostEditors.onDidChangeTextEditorOptions(listener, thisArgs, disposables);
			},
438
			onDidChangeTextEditorVisibleRanges(listener: (e: vscode.TextEditorVisibleRangesChangeEvent) => any, thisArgs?: any, disposables?: extHostTypes.Disposable[]) {
439
				return extHostEditors.onDidChangeTextEditorVisibleRanges(listener, thisArgs, disposables);
440
			},
441 442 443
			onDidChangeTextEditorViewColumn(listener, thisArg?, disposables?) {
				return extHostEditors.onDidChangeTextEditorViewColumn(listener, thisArg, disposables);
			},
444 445 446
			onDidCloseTerminal(listener, thisArg?, disposables?) {
				return extHostTerminalService.onDidCloseTerminal(listener, thisArg, disposables);
			},
D
Daniel Imms 已提交
447
			onDidOpenTerminal(listener, thisArg?, disposables?) {
448
				return extHostTerminalService.onDidOpenTerminal(listener, thisArg, disposables);
D
Daniel Imms 已提交
449
			},
D
Daniel Imms 已提交
450
			onDidChangeActiveTerminal(listener, thisArg?, disposables?) {
451
				return extHostTerminalService.onDidChangeActiveTerminal(listener, thisArg, disposables);
D
Daniel Imms 已提交
452
			},
453 454 455
			onDidChangeTerminalDimensions(listener, thisArg?, disposables?) {
				return extHostTerminalService.onDidChangeTerminalDimensions(listener, thisArg, disposables);
			},
J
Joao Moreno 已提交
456 457
			get state() {
				return extHostWindow.state;
458
			},
J
Joao Moreno 已提交
459
			onDidChangeWindowState(listener, thisArg?, disposables?) {
J
Joao Moreno 已提交
460
				return extHostWindow.onDidChangeWindowState(listener, thisArg, disposables);
J
Joao Moreno 已提交
461
			},
462
			showInformationMessage(message: string, first: vscode.MessageOptions | string | vscode.MessageItem, ...rest: Array<string | vscode.MessageItem>) {
463
				return extHostMessageService.showMessage(extension, Severity.Info, message, first, rest);
464
			},
465
			showWarningMessage(message: string, first: vscode.MessageOptions | string | vscode.MessageItem, ...rest: Array<string | vscode.MessageItem>) {
466
				return extHostMessageService.showMessage(extension, Severity.Warning, message, first, rest);
467
			},
468
			showErrorMessage(message: string, first: vscode.MessageOptions | string | vscode.MessageItem, ...rest: Array<string | vscode.MessageItem>) {
469
				return extHostMessageService.showMessage(extension, Severity.Error, message, first, rest);
470
			},
C
Christof Marti 已提交
471
			showQuickPick(items: any, options: vscode.QuickPickOptions, token?: vscode.CancellationToken): any {
472
				return extHostQuickOpen.showQuickPick(items, !!extension.enableProposedApi, options, token);
473
			},
474
			showWorkspaceFolderPick(options: vscode.WorkspaceFolderPickOptions) {
475
				return extHostQuickOpen.showWorkspaceFolderPick(options);
476
			},
477
			showInputBox(options?: vscode.InputBoxOptions, token?: vscode.CancellationToken) {
478
				return extHostQuickOpen.showInput(options, token);
C
Christof Marti 已提交
479
			},
480 481 482 483 484 485
			showOpenDialog(options) {
				return extHostDialogs.showOpenDialog(options);
			},
			showSaveDialog(options) {
				return extHostDialogs.showSaveDialog(options);
			},
486 487 488 489
			createStatusBarItem(alignmentOrOptions?: vscode.StatusBarAlignment | vscode.window.StatusBarItemOptions, priority?: number): vscode.StatusBarItem {
				let id: string;
				let name: string;
				let alignment: number | undefined;
B
Benjamin Pasero 已提交
490

491 492 493 494 495 496 497 498 499 500 501 502 503
				if (alignmentOrOptions && typeof alignmentOrOptions !== 'number') {
					id = alignmentOrOptions.id;
					name = alignmentOrOptions.name;
					alignment = alignmentOrOptions.alignment;
					priority = alignmentOrOptions.priority;
				} else {
					id = extension.identifier.value;
					name = nls.localize('extensionLabel', "{0} (Extension)", extension.displayName || extension.name);
					alignment = alignmentOrOptions;
					priority = priority;
				}

				return extHostStatusBar.createStatusBarEntry(id, name, alignment, priority);
504 505 506 507
			},
			setStatusBarMessage(text: string, timeoutOrThenable?: number | Thenable<any>): vscode.Disposable {
				return extHostStatusBar.setStatusBarMessage(text, timeoutOrThenable);
			},
508
			withScmProgress<R>(task: (progress: vscode.Progress<number>) => Thenable<R>) {
509
				console.warn(`[Deprecation Warning] function 'withScmProgress' is deprecated and should no longer be used. Use 'withProgress' instead.`);
510
				return extHostProgress.withProgress(extension, { location: extHostTypes.ProgressLocation.SourceControl }, (progress, token) => task({ report(n: number) { /*noop*/ } }));
J
Johannes Rieken 已提交
511
			},
512
			withProgress<R>(options: vscode.ProgressOptions, task: (progress: vscode.Progress<{ message?: string; worked?: number }>, token: vscode.CancellationToken) => Thenable<R>) {
J
Johannes Rieken 已提交
513
				return extHostProgress.withProgress(extension, options, task);
514
			},
S
Sandeep Somavarapu 已提交
515 516
			createOutputChannel(name: string): vscode.OutputChannel {
				return extHostOutputService.createOutputChannel(name);
517
			},
518
			createWebviewPanel(viewType: string, title: string, showOptions: vscode.ViewColumn | { viewColumn: vscode.ViewColumn, preserveFocus?: boolean }, options: vscode.WebviewPanelOptions & vscode.WebviewOptions): vscode.WebviewPanel {
519
				return extHostWebviews.createWebviewPanel(extension, viewType, title, showOptions, options);
520
			},
521
			createWebviewTextEditorInset(editor: vscode.TextEditor, line: number, height: number, options: vscode.WebviewOptions): vscode.WebviewEditorInset {
522
				checkProposedApiEnabled(extension);
523
				return extHostEditorInsets.createWebviewEditorInset(editor, line, height, options, extension);
524
			},
525
			createTerminal(nameOrOptions?: vscode.TerminalOptions | string, shellPath?: string, shellArgs?: string[] | string): vscode.Terminal {
526
				if (typeof nameOrOptions === 'object') {
527
					return extHostTerminalService.createTerminalFromOptions(nameOrOptions);
528
				}
D
Daniel Imms 已提交
529
				return extHostTerminalService.createTerminal(<string>nameOrOptions, shellPath, shellArgs);
530
			},
531
			createTerminalRenderer(name: string): vscode.TerminalRenderer {
532
				return extHostTerminalService.createTerminalRenderer(name);
533
			},
534
			registerTreeDataProvider(viewId: string, treeDataProvider: vscode.TreeDataProvider<any>): vscode.Disposable {
535
				return extHostTreeViews.registerTreeDataProvider(viewId, treeDataProvider, extension);
536
			},
537
			createTreeView(viewId: string, options: { treeDataProvider: vscode.TreeDataProvider<any> }): vscode.TreeView<any> {
538
				return extHostTreeViews.createTreeView(viewId, options, extension);
S
Sandeep Somavarapu 已提交
539
			},
540 541 542
			registerWebviewPanelSerializer: (viewType: string, serializer: vscode.WebviewPanelSerializer) => {
				return extHostWebviews.registerWebviewPanelSerializer(viewType, serializer);
			},
543
			registerDecorationProvider: proposedApiFunction(extension, (provider: vscode.DecorationProvider) => {
544
				return extHostDecorations.registerDecorationProvider(provider, extension.identifier);
M
Matt Bierner 已提交
545
			}),
J
Joao Moreno 已提交
546
			registerUriHandler(handler: vscode.UriHandler) {
547
				return extHostUrls.registerUriHandler(extension.identifier, handler);
J
Joao Moreno 已提交
548
			},
C
Christof Marti 已提交
549
			createQuickPick<T extends vscode.QuickPickItem>(): vscode.QuickPick<T> {
M
Matt Bierner 已提交
550
				return extHostQuickOpen.createQuickPick(extension.identifier, !!extension.enableProposedApi);
C
Christof Marti 已提交
551 552
			},
			createInputBox(): vscode.InputBox {
553
				return extHostQuickOpen.createInputBox(extension.identifier);
554
			}
555
		};
E
Erich Gamma 已提交
556

557 558 559
		// namespace: workspace
		const workspace: typeof vscode.workspace = {
			get rootPath() {
560
				return extHostWorkspace.getPath();
561 562 563 564
			},
			set rootPath(value) {
				throw errors.readonly();
			},
565
			getWorkspaceFolder(resource) {
566
				return extHostWorkspace.getWorkspaceFolder(resource);
567
			},
568
			get workspaceFolders() {
569
				return extHostWorkspace.getWorkspaceFolders();
570
			},
571
			get name() {
572
				return extHostWorkspace.name;
573 574 575 576
			},
			set name(value) {
				throw errors.readonly();
			},
577 578 579 580 581 582
			get workspaceFile() {
				return extHostWorkspace.workspaceFile;
			},
			set workspaceFile(value) {
				throw errors.readonly();
			},
583
			updateWorkspaceFolders: (index, deleteCount, ...workspaceFoldersToAdd) => {
584
				return extHostWorkspace.updateWorkspaceFolders(extension, index, deleteCount || 0, ...workspaceFoldersToAdd);
585
			},
586
			onDidChangeWorkspaceFolders: function (listener, thisArgs?, disposables?) {
587
				return extHostWorkspace.onDidChangeWorkspace(listener, thisArgs, disposables);
588
			},
589
			asRelativePath: (pathOrUri, includeWorkspace?) => {
590
				return extHostWorkspace.getRelativePath(pathOrUri, includeWorkspace);
591 592
			},
			findFiles: (include, exclude, maxResults?, token?) => {
593
				return extHostWorkspace.findFiles(typeConverters.GlobPattern.from(include), typeConverters.GlobPattern.from(withNullAsUndefined(exclude)), maxResults, extension.identifier, token);
594
			},
595
			findTextInFiles: (query: vscode.TextSearchQuery, optionsOrCallback: vscode.FindTextInFilesOptions | ((result: vscode.TextSearchResult) => void), callbackOrToken?: vscode.CancellationToken | ((result: vscode.TextSearchResult) => void), token?: vscode.CancellationToken) => {
596 597 598 599 600
				let options: vscode.FindTextInFilesOptions;
				let callback: (result: vscode.TextSearchResult) => void;

				if (typeof optionsOrCallback === 'object') {
					options = optionsOrCallback;
601
					callback = callbackOrToken as (result: vscode.TextSearchResult) => void;
602 603 604
				} else {
					options = {};
					callback = optionsOrCallback;
605
					token = callbackOrToken as vscode.CancellationToken;
606 607
				}

608
				return extHostWorkspace.findTextInFiles(query, options || {}, callback, extension.identifier, token);
R
Rob Lourens 已提交
609
			},
610
			saveAll: (includeUntitled?) => {
611
				return extHostWorkspace.saveAll(includeUntitled);
612
			},
613
			applyEdit(edit: vscode.WorkspaceEdit): Thenable<boolean> {
614
				return extHostEditors.applyWorkspaceEdit(edit);
615 616
			},
			createFileSystemWatcher: (pattern, ignoreCreate, ignoreChange, ignoreDelete): vscode.FileSystemWatcher => {
617
				return extHostFileSystemEvent.createFileSystemWatcher(typeConverters.GlobPattern.from(pattern), ignoreCreate, ignoreChange, ignoreDelete);
618 619 620 621 622 623 624
			},
			get textDocuments() {
				return extHostDocuments.getAllDocumentData().map(data => data.document);
			},
			set textDocuments(value) {
				throw errors.readonly();
			},
625
			openTextDocument(uriOrFileNameOrOptions?: vscode.Uri | string | { language?: string; content?: string; }) {
626
				let uriPromise: Thenable<URI>;
B
Benjamin Pasero 已提交
627

628
				const options = uriOrFileNameOrOptions as { language?: string; content?: string; };
B
Benjamin Pasero 已提交
629
				if (typeof uriOrFileNameOrOptions === 'string') {
630
					uriPromise = Promise.resolve(URI.file(uriOrFileNameOrOptions));
B
Benjamin Pasero 已提交
631
				} else if (uriOrFileNameOrOptions instanceof URI) {
632
					uriPromise = Promise.resolve(uriOrFileNameOrOptions);
B
Benjamin Pasero 已提交
633 634
				} else if (!options || typeof options === 'object') {
					uriPromise = extHostDocuments.createDocumentData(options);
635
				} else {
B
Benjamin Pasero 已提交
636
					throw new Error('illegal argument - uriOrFileNameOrOptions');
637
				}
B
Benjamin Pasero 已提交
638 639 640

				return uriPromise.then(uri => {
					return extHostDocuments.ensureDocumentData(uri).then(() => {
M
Matt Bierner 已提交
641
						return extHostDocuments.getDocument(uri);
B
Benjamin Pasero 已提交
642
					});
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
				});
			},
			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?) => {
658
				return extHostDocumentSaveParticipant.getOnWillSaveTextDocumentEvent(extension)(listener, thisArgs, disposables);
659
			},
660
			onDidChangeConfiguration: (listener: (_: any) => any, thisArgs?: any, disposables?: extHostTypes.Disposable[]) => {
661
				return configProvider.onDidChangeConfiguration(listener, thisArgs, disposables);
662
			},
663
			getConfiguration(section?: string, resource?: vscode.Uri): vscode.WorkspaceConfiguration {
R
Rob Lourens 已提交
664
				resource = arguments.length === 1 ? undefined : resource;
665
				return configProvider.getConfiguration(section, resource, extension.identifier);
666
			},
667 668
			registerTextDocumentContentProvider(scheme: string, provider: vscode.TextDocumentContentProvider) {
				return extHostDocumentContentProviders.registerTextDocumentContentProvider(scheme, provider);
669
			},
670
			registerTaskProvider: (type: string, provider: vscode.TaskProvider) => {
671
				return extHostTask.registerTaskProvider(extension, provider);
J
Johannes Rieken 已提交
672
			},
673
			registerFileSystemProvider(scheme, provider, options) {
674
				return extHostFileSystem.registerFileSystemProvider(scheme, provider, options);
675
			},
676 677 678 679
			get fs() {
				checkProposedApiEnabled(extension);
				return extHostFileSystem.fileSystem;
			},
B
Benjamin Pasero 已提交
680
			registerFileSearchProvider: proposedApiFunction(extension, (scheme: string, provider: vscode.FileSearchProvider) => {
681
				return extHostSearch.registerFileSearchProvider(scheme, provider);
M
Matt Bierner 已提交
682
			}),
B
Benjamin Pasero 已提交
683
			registerTextSearchProvider: proposedApiFunction(extension, (scheme: string, provider: vscode.TextSearchProvider) => {
684 685
				return extHostSearch.registerTextSearchProvider(scheme, provider);
			}),
686
			registerDocumentCommentProvider: proposedApiFunction(extension, (provider: vscode.DocumentCommentProvider) => {
687
				return extHostComment.registerDocumentCommentProvider(extension.identifier, provider);
688 689
			}),
			registerWorkspaceCommentProvider: proposedApiFunction(extension, (provider: vscode.WorkspaceCommentProvider) => {
690
				return extHostComment.registerWorkspaceCommentProvider(extension.identifier, provider);
691
			}),
A
Alex Dima 已提交
692 693 694
			registerRemoteAuthorityResolver: proposedApiFunction(extension, (authorityPrefix: string, resolver: vscode.RemoteAuthorityResolver) => {
				return extensionService.registerRemoteAuthorityResolver(authorityPrefix, resolver);
			}),
695 696 697
			registerResourceLabelFormatter: proposedApiFunction(extension, (formatter: vscode.ResourceLabelFormatter) => {
				return extHostFileSystem.registerResourceLabelFormatter(formatter);
			}),
J
Johannes Rieken 已提交
698
			onDidRenameFile: proposedApiFunction(extension, (listener: (e: vscode.FileRenameEvent) => any, thisArg?: any, disposables?: vscode.Disposable[]) => {
699
				return extHostFileSystemEvent.onDidRenameFile(listener, thisArg, disposables);
700
			}),
J
Johannes Rieken 已提交
701
			onWillRenameFile: proposedApiFunction(extension, (listener: (e: vscode.FileWillRenameEvent) => any, thisArg?: any, disposables?: vscode.Disposable[]) => {
702
				return extHostFileSystemEvent.getOnWillRenameFileEvent(extension)(listener, thisArg, disposables);
J
Johannes Rieken 已提交
703
			})
704
		};
705

706 707
		// namespace: scm
		const scm: typeof vscode.scm = {
708
			get inputBox() {
709
				return extHostSCM.getLastInputBox(extension)!; // Strict null override - Deprecated api
710
			},
J
Joao Moreno 已提交
711 712
			createSourceControl(id: string, label: string, rootUri?: vscode.Uri) {
				return extHostSCM.createSourceControl(extension, id, label, rootUri);
J
Joao Moreno 已提交
713
			}
714
		};
J
Joao Moreno 已提交
715

716
		const comment: typeof vscode.comment = {
P
Peng Lyu 已提交
717 718
			createCommentController(id: string, label: string) {
				return extHostComment.createCommentController(extension, id, label);
719
			}
J
Joao Moreno 已提交
720
		};
721

P
Peng Lyu 已提交
722 723
		const comments = comment;

724 725
		// namespace: debug
		const debug: typeof vscode.debug = {
726 727 728
			get activeDebugSession() {
				return extHostDebugService.activeDebugSession;
			},
729 730
			get activeDebugConsole() {
				return extHostDebugService.activeDebugConsole;
731
			},
732 733
			get breakpoints() {
				return extHostDebugService.breakpoints;
734
			},
735 736 737
			onDidStartDebugSession(listener, thisArg?, disposables?) {
				return extHostDebugService.onDidStartDebugSession(listener, thisArg, disposables);
			},
738
			onDidTerminateDebugSession(listener, thisArg?, disposables?) {
739
				return extHostDebugService.onDidTerminateDebugSession(listener, thisArg, disposables);
740
			},
A
Andre Weinand 已提交
741
			onDidChangeActiveDebugSession(listener, thisArg?, disposables?) {
742
				return extHostDebugService.onDidChangeActiveDebugSession(listener, thisArg, disposables);
A
Andre Weinand 已提交
743 744
			},
			onDidReceiveDebugSessionCustomEvent(listener, thisArg?, disposables?) {
A
Andre Weinand 已提交
745
				return extHostDebugService.onDidReceiveDebugSessionCustomEvent(listener, thisArg, disposables);
746
			},
747
			onDidChangeBreakpoints(listener, thisArgs?, disposables?) {
748 749
				return extHostDebugService.onDidChangeBreakpoints(listener, thisArgs, disposables);
			},
A
Andre Weinand 已提交
750
			registerDebugConfigurationProvider(debugType: string, provider: vscode.DebugConfigurationProvider) {
751
				return extHostDebugService.registerDebugConfigurationProvider(debugType, provider);
752
			},
A
Andre Weinand 已提交
753 754
			registerDebugAdapterDescriptorFactory(debugType: string, factory: vscode.DebugAdapterDescriptorFactory) {
				return extHostDebugService.registerDebugAdapterDescriptorFactory(extension, debugType, factory);
755
			},
A
Andre Weinand 已提交
756 757
			registerDebugAdapterTrackerFactory(debugType: string, factory: vscode.DebugAdapterTrackerFactory) {
				return extHostDebugService.registerDebugAdapterTrackerFactory(debugType, factory);
758
			},
759 760
			startDebugging(folder: vscode.WorkspaceFolder | undefined, nameOrConfig: string | vscode.DebugConfiguration, parentSession?: vscode.DebugSession) {
				return extHostDebugService.startDebugging(folder, nameOrConfig, parentSession);
761 762
			},
			addBreakpoints(breakpoints: vscode.Breakpoint[]) {
763
				return extHostDebugService.addBreakpoints(breakpoints);
764 765
			},
			removeBreakpoints(breakpoints: vscode.Breakpoint[]) {
766
				return extHostDebugService.removeBreakpoints(breakpoints);
767
			}
768 769
		};

D
Dirk Baeumer 已提交
770 771 772 773
		const tasks: typeof vscode.tasks = {
			registerTaskProvider: (type: string, provider: vscode.TaskProvider) => {
				return extHostTask.registerTaskProvider(extension, provider);
			},
774
			fetchTasks: (filter?: vscode.TaskFilter): Thenable<vscode.Task[]> => {
D
Dirk Baeumer 已提交
775
				return extHostTask.fetchTasks(filter);
776 777
			},
			executeTask: (task: vscode.Task): Thenable<vscode.TaskExecution> => {
D
Dirk Baeumer 已提交
778
				return extHostTask.executeTask(extension, task);
779
			},
D
Dirk Baeumer 已提交
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795
			get taskExecutions(): vscode.TaskExecution[] {
				return extHostTask.taskExecutions;
			},
			onDidStartTask: (listeners, thisArgs?, disposables?) => {
				return extHostTask.onDidStartTask(listeners, thisArgs, disposables);
			},
			onDidEndTask: (listeners, thisArgs?, disposables?) => {
				return extHostTask.onDidEndTask(listeners, thisArgs, disposables);
			},
			onDidStartTaskProcess: (listeners, thisArgs?, disposables?) => {
				return extHostTask.onDidStartTaskProcess(listeners, thisArgs, disposables);
			},
			onDidEndTaskProcess: (listeners, thisArgs?, disposables?) => {
				return extHostTask.onDidEndTaskProcess(listeners, thisArgs, disposables);
			}
		};
796

797
		return <typeof vscode>{
798
			version: initData.version,
799 800
			// namespaces
			commands,
801
			debug,
802 803 804
			env,
			extensions,
			languages,
J
Joao Moreno 已提交
805
			scm,
806
			comment,
P
Peng Lyu 已提交
807
			comments,
D
Dirk Baeumer 已提交
808
			tasks,
809 810
			window,
			workspace,
811
			// types
812
			Breakpoint: extHostTypes.Breakpoint,
813
			CancellationTokenSource: CancellationTokenSource,
814
			CodeAction: extHostTypes.CodeAction,
M
Matt Bierner 已提交
815
			CodeActionKind: extHostTypes.CodeActionKind,
816
			CodeActionTrigger: extHostTypes.CodeActionTrigger,
817
			CodeLens: extHostTypes.CodeLens,
R
Rob DeLine 已提交
818
			CodeInset: extHostTypes.CodeInset,
819
			Color: extHostTypes.Color,
820
			ColorInformation: extHostTypes.ColorInformation,
821 822
			ColorPresentation: extHostTypes.ColorPresentation,
			CommentThreadCollapsibleState: extHostTypes.CommentThreadCollapsibleState,
P
Peng Lyu 已提交
823
			CommentMode: extHostTypes.CommentMode,
824 825 826
			CompletionItem: extHostTypes.CompletionItem,
			CompletionItemKind: extHostTypes.CompletionItemKind,
			CompletionList: extHostTypes.CompletionList,
M
Matt Bierner 已提交
827
			CompletionTriggerKind: extHostTypes.CompletionTriggerKind,
828
			ConfigurationTarget: extHostTypes.ConfigurationTarget,
829
			DebugAdapterExecutable: extHostTypes.DebugAdapterExecutable,
830
			DebugAdapterServer: extHostTypes.DebugAdapterServer,
831
			DecorationRangeBehavior: extHostTypes.DecorationRangeBehavior,
832
			Diagnostic: extHostTypes.Diagnostic,
833
			DiagnosticRelatedInformation: extHostTypes.DiagnosticRelatedInformation,
834
			DiagnosticSeverity: extHostTypes.DiagnosticSeverity,
835
			DiagnosticTag: extHostTypes.DiagnosticTag,
836 837 838
			Disposable: extHostTypes.Disposable,
			DocumentHighlight: extHostTypes.DocumentHighlight,
			DocumentHighlightKind: extHostTypes.DocumentHighlightKind,
839
			DocumentLink: extHostTypes.DocumentLink,
840 841
			DocumentSymbol: extHostTypes.DocumentSymbol,
			EndOfLine: extHostTypes.EndOfLine,
842
			EventEmitter: Emitter,
843
			ExtensionExecutionContext: extHostTypes.ExtensionExecutionContext,
844
			ExtensionKind: extHostTypes.ExtensionKind,
G
Gabriel DeBacker 已提交
845
			CustomExecution: extHostTypes.CustomExecution,
846 847 848 849 850
			FileChangeType: extHostTypes.FileChangeType,
			FileSystemError: extHostTypes.FileSystemError,
			FileType: files.FileType,
			FoldingRange: extHostTypes.FoldingRange,
			FoldingRangeKind: extHostTypes.FoldingRangeKind,
851
			FunctionBreakpoint: extHostTypes.FunctionBreakpoint,
852
			Hover: extHostTypes.Hover,
853
			IndentAction: languageConfiguration.IndentAction,
854
			Location: extHostTypes.Location,
855
			LogLevel: extHostTypes.LogLevel,
856
			MarkdownString: extHostTypes.MarkdownString,
857
			OverviewRulerLane: OverviewRulerLane,
858 859
			ParameterInformation: extHostTypes.ParameterInformation,
			Position: extHostTypes.Position,
860 861
			ProcessExecution: extHostTypes.ProcessExecution,
			ProgressLocation: extHostTypes.ProgressLocation,
862
			QuickInputButtons: extHostTypes.QuickInputButtons,
863
			Range: extHostTypes.Range,
864
			RelativePattern: extHostTypes.RelativePattern,
A
Alex Dima 已提交
865
			ResolvedAuthority: extHostTypes.ResolvedAuthority,
A
Tweaks  
Alex Dima 已提交
866
			RemoteAuthorityResolverError: extHostTypes.RemoteAuthorityResolverError,
867
			Selection: extHostTypes.Selection,
868
			SelectionRange: extHostTypes.SelectionRange,
869 870
			ShellExecution: extHostTypes.ShellExecution,
			ShellQuoting: extHostTypes.ShellQuoting,
M
Matt Bierner 已提交
871
			SignatureHelpTriggerKind: extHostTypes.SignatureHelpTriggerKind,
872 873 874
			SignatureHelp: extHostTypes.SignatureHelp,
			SignatureInformation: extHostTypes.SignatureInformation,
			SnippetString: extHostTypes.SnippetString,
875
			SourceBreakpoint: extHostTypes.SourceBreakpoint,
876
			SourceControlInputBoxValidationType: extHostTypes.SourceControlInputBoxValidationType,
877 878 879
			StatusBarAlignment: extHostTypes.StatusBarAlignment,
			SymbolInformation: extHostTypes.SymbolInformation,
			SymbolKind: extHostTypes.SymbolKind,
880
			Task: extHostTypes.Task,
A
Alex Ross 已提交
881
			Task2: extHostTypes.Task,
882 883 884 885
			TaskGroup: extHostTypes.TaskGroup,
			TaskPanelKind: extHostTypes.TaskPanelKind,
			TaskRevealKind: extHostTypes.TaskRevealKind,
			TaskScope: extHostTypes.TaskScope,
886 887
			TextDocumentSaveReason: extHostTypes.TextDocumentSaveReason,
			TextEdit: extHostTypes.TextEdit,
888
			TextEditorCursorStyle: TextEditorCursorStyle,
889
			TextEditorLineNumbersStyle: extHostTypes.TextEditorLineNumbersStyle,
890
			TextEditorRevealType: extHostTypes.TextEditorRevealType,
891
			TextEditorSelectionChangeKind: extHostTypes.TextEditorSelectionChangeKind,
892 893 894
			ThemeColor: extHostTypes.ThemeColor,
			ThemeIcon: extHostTypes.ThemeIcon,
			TreeItem: extHostTypes.TreeItem,
895
			TreeItem2: extHostTypes.TreeItem,
896
			TreeItemCollapsibleState: extHostTypes.TreeItemCollapsibleState,
897
			Uri: URI,
898 899
			ViewColumn: extHostTypes.ViewColumn,
			WorkspaceEdit: extHostTypes.WorkspaceEdit,
900 901 902
			// proposed
			CallHierarchyDirection: extHostTypes.CallHierarchyDirection,
			CallHierarchyItem: extHostTypes.CallHierarchyItem
903
		};
904
	};
E
Erich Gamma 已提交
905 906 907 908
}

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

A
Alex Dima 已提交
909
	private _extensionService: ExtHostExtensionService;
910
	private _identifier: ExtensionIdentifier;
E
Erich Gamma 已提交
911 912 913

	public id: string;
	public extensionPath: string;
914
	public packageJSON: IExtensionDescription;
E
Erich Gamma 已提交
915

J
Johannes Rieken 已提交
916
	constructor(extensionService: ExtHostExtensionService, description: IExtensionDescription) {
A
Alex Dima 已提交
917
		this._extensionService = extensionService;
918 919
		this._identifier = description.identifier;
		this.id = description.identifier.value;
920
		this.extensionPath = path.normalize(originalFSPath(description.extensionLocation));
E
Erich Gamma 已提交
921 922 923 924
		this.packageJSON = description;
	}

	get isActive(): boolean {
925
		return this._extensionService.isActivated(this._identifier);
E
Erich Gamma 已提交
926 927 928
	}

	get exports(): T {
929
		if (this.packageJSON.api === 'none') {
930
			return undefined!; // Strict nulloverride - Public api
931
		}
932
		return <T>this._extensionService.getExtensionExports(this._identifier);
E
Erich Gamma 已提交
933 934 935
	}

	activate(): Thenable<T> {
936
		return this._extensionService.activateByIdWithErrors(this._identifier, new ExtensionActivatedByAPI(false)).then(() => this.exports);
E
Erich Gamma 已提交
937 938
	}
}