Archived
1
0

Merge commit 'be3e8236086165e5e45a5a10783823874b3f3ebd' as 'lib/vscode'

This commit is contained in:
Joe Previte
2020-12-15 15:52:33 -07:00
4649 changed files with 1311795 additions and 0 deletions

View File

@ -0,0 +1,306 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import type * as vscode from 'vscode';
import { URI } from 'vs/base/common/uri';
import * as typeConverters from 'vs/workbench/api/common/extHostTypeConverters';
import { CommandsRegistry, ICommandService, ICommandHandler } from 'vs/platform/commands/common/commands';
import { ITextEditorOptions } from 'vs/platform/editor/common/editor';
import { EditorViewColumn } from 'vs/workbench/api/common/shared/editor';
import { EditorGroupLayout } from 'vs/workbench/services/editor/common/editorGroupsService';
import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { IOpenWindowOptions, IWindowOpenable, IOpenEmptyWindowOptions } from 'vs/platform/windows/common/windows';
import { IWorkspacesService, hasWorkspaceFileExtension, IRecent } from 'vs/platform/workspaces/common/workspaces';
import { Schemas } from 'vs/base/common/network';
import { ILogService } from 'vs/platform/log/common/log';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { IViewDescriptorService, IViewsService, ViewVisibilityState } from 'vs/workbench/common/views';
// -----------------------------------------------------------------
// The following commands are registered on both sides separately.
//
// We are trying to maintain backwards compatibility for cases where
// API commands are encoded as markdown links, for example.
// -----------------------------------------------------------------
export interface ICommandsExecutor {
executeCommand<T>(id: string, ...args: any[]): Promise<T | undefined>;
}
function adjustHandler(handler: (executor: ICommandsExecutor, ...args: any[]) => any): ICommandHandler {
return (accessor, ...args: any[]) => {
return handler(accessor.get(ICommandService), ...args);
};
}
interface IOpenFolderAPICommandOptions {
forceNewWindow?: boolean;
forceReuseWindow?: boolean;
noRecentEntry?: boolean;
}
export class OpenFolderAPICommand {
public static readonly ID = 'vscode.openFolder';
public static execute(executor: ICommandsExecutor, uri?: URI, forceNewWindow?: boolean): Promise<any>;
public static execute(executor: ICommandsExecutor, uri?: URI, options?: IOpenFolderAPICommandOptions): Promise<any>;
public static execute(executor: ICommandsExecutor, uri?: URI, arg: boolean | IOpenFolderAPICommandOptions = {}): Promise<any> {
if (typeof arg === 'boolean') {
arg = { forceNewWindow: arg };
}
if (!uri) {
return executor.executeCommand('_files.pickFolderAndOpen', { forceNewWindow: arg.forceNewWindow });
}
const options: IOpenWindowOptions = { forceNewWindow: arg.forceNewWindow, forceReuseWindow: arg.forceReuseWindow, noRecentEntry: arg.noRecentEntry };
uri = URI.revive(uri);
const uriToOpen: IWindowOpenable = (hasWorkspaceFileExtension(uri) || uri.scheme === Schemas.untitled) ? { workspaceUri: uri } : { folderUri: uri };
return executor.executeCommand('_files.windowOpen', [uriToOpen], options);
}
}
CommandsRegistry.registerCommand({
id: OpenFolderAPICommand.ID,
handler: adjustHandler(OpenFolderAPICommand.execute),
description: {
description: 'Open a folder or workspace in the current window or new window depending on the newWindow argument. Note that opening in the same window will shutdown the current extension host process and start a new one on the given folder/workspace unless the newWindow parameter is set to true.',
args: [
{ name: 'uri', description: '(optional) Uri of the folder or workspace file to open. If not provided, a native dialog will ask the user for the folder', constraint: (value: any) => value === undefined || value instanceof URI },
{ name: 'options', description: '(optional) Options. Object with the following properties: `forceNewWindow `: Whether to open the folder/workspace in a new window or the same. Defaults to opening in the same window. `noRecentEntry`: Wheter the opened URI will appear in the \'Open Recent\' list. Defaults to true. Note, for backward compatibility, options can also be of type boolean, representing the `forceNewWindow` setting.', constraint: (value: any) => value === undefined || typeof value === 'object' || typeof value === 'boolean' }
]
}
});
interface INewWindowAPICommandOptions {
reuseWindow?: boolean;
remoteAuthority?: string;
}
export class NewWindowAPICommand {
public static readonly ID = 'vscode.newWindow';
public static execute(executor: ICommandsExecutor, options?: INewWindowAPICommandOptions): Promise<any> {
const commandOptions: IOpenEmptyWindowOptions = {
forceReuseWindow: options && options.reuseWindow,
remoteAuthority: options && options.remoteAuthority
};
return executor.executeCommand('_files.newWindow', commandOptions);
}
}
CommandsRegistry.registerCommand({
id: NewWindowAPICommand.ID,
handler: adjustHandler(NewWindowAPICommand.execute),
description: {
description: 'Opens an new window',
args: [
]
}
});
export class DiffAPICommand {
public static readonly ID = 'vscode.diff';
public static execute(executor: ICommandsExecutor, left: URI, right: URI, label: string, options?: typeConverters.TextEditorOpenOptions): Promise<any> {
return executor.executeCommand('_workbench.diff', [
left, right,
label,
undefined,
typeConverters.TextEditorOpenOptions.from(options),
options ? typeConverters.ViewColumn.from(options.viewColumn) : undefined
]);
}
}
CommandsRegistry.registerCommand(DiffAPICommand.ID, adjustHandler(DiffAPICommand.execute));
export class OpenAPICommand {
public static readonly ID = 'vscode.open';
public static execute(executor: ICommandsExecutor, resource: URI, columnOrOptions?: vscode.ViewColumn | typeConverters.TextEditorOpenOptions, label?: string): Promise<any> {
let options: ITextEditorOptions | undefined;
let position: EditorViewColumn | undefined;
if (columnOrOptions) {
if (typeof columnOrOptions === 'number') {
position = typeConverters.ViewColumn.from(columnOrOptions);
} else {
options = typeConverters.TextEditorOpenOptions.from(columnOrOptions);
position = typeConverters.ViewColumn.from(columnOrOptions.viewColumn);
}
}
return executor.executeCommand('_workbench.open', [
resource,
options,
position,
label
]);
}
}
CommandsRegistry.registerCommand(OpenAPICommand.ID, adjustHandler(OpenAPICommand.execute));
export class OpenWithAPICommand {
public static readonly ID = 'vscode.openWith';
public static execute(executor: ICommandsExecutor, resource: URI, viewType: string, columnOrOptions?: vscode.ViewColumn | typeConverters.TextEditorOpenOptions): Promise<any> {
let options: ITextEditorOptions | undefined;
let position: EditorViewColumn | undefined;
if (typeof columnOrOptions === 'number') {
position = typeConverters.ViewColumn.from(columnOrOptions);
} else if (typeof columnOrOptions !== 'undefined') {
options = typeConverters.TextEditorOpenOptions.from(columnOrOptions);
}
return executor.executeCommand('_workbench.openWith', [
resource,
viewType,
options,
position
]);
}
}
CommandsRegistry.registerCommand(OpenWithAPICommand.ID, adjustHandler(OpenWithAPICommand.execute));
CommandsRegistry.registerCommand('_workbench.removeFromRecentlyOpened', function (accessor: ServicesAccessor, uri: URI) {
const workspacesService = accessor.get(IWorkspacesService);
return workspacesService.removeRecentlyOpened([uri]);
});
export class RemoveFromRecentlyOpenedAPICommand {
public static readonly ID = 'vscode.removeFromRecentlyOpened';
public static execute(executor: ICommandsExecutor, path: string | URI): Promise<any> {
if (typeof path === 'string') {
path = path.match(/^[^:/?#]+:\/\//) ? URI.parse(path) : URI.file(path);
} else {
path = URI.revive(path); // called from extension host
}
return executor.executeCommand('_workbench.removeFromRecentlyOpened', path);
}
}
CommandsRegistry.registerCommand(RemoveFromRecentlyOpenedAPICommand.ID, adjustHandler(RemoveFromRecentlyOpenedAPICommand.execute));
export interface OpenIssueReporterArgs {
readonly extensionId: string;
readonly issueTitle?: string;
readonly issueBody?: string;
}
export class OpenIssueReporter {
public static readonly ID = 'vscode.openIssueReporter';
public static execute(executor: ICommandsExecutor, args: string | OpenIssueReporterArgs): Promise<void> {
const commandArgs = typeof args === 'string'
? { extensionId: args }
: args;
return executor.executeCommand('workbench.action.openIssueReporter', commandArgs);
}
}
interface RecentEntry {
uri: URI;
type: 'workspace' | 'folder' | 'file';
label?: string;
}
CommandsRegistry.registerCommand('_workbench.addToRecentlyOpened', async function (accessor: ServicesAccessor, recentEntry: RecentEntry) {
const workspacesService = accessor.get(IWorkspacesService);
let recent: IRecent | undefined = undefined;
const uri = recentEntry.uri;
const label = recentEntry.label;
if (recentEntry.type === 'workspace') {
const workspace = await workspacesService.getWorkspaceIdentifier(uri);
recent = { workspace, label };
} else if (recentEntry.type === 'folder') {
recent = { folderUri: uri, label };
} else {
recent = { fileUri: uri, label };
}
return workspacesService.addRecentlyOpened([recent]);
});
CommandsRegistry.registerCommand('_workbench.getRecentlyOpened', async function (accessor: ServicesAccessor) {
const workspacesService = accessor.get(IWorkspacesService);
return workspacesService.getRecentlyOpened();
});
export class SetEditorLayoutAPICommand {
public static readonly ID = 'vscode.setEditorLayout';
public static execute(executor: ICommandsExecutor, layout: EditorGroupLayout): Promise<any> {
return executor.executeCommand('layoutEditorGroups', layout);
}
}
CommandsRegistry.registerCommand({
id: SetEditorLayoutAPICommand.ID,
handler: adjustHandler(SetEditorLayoutAPICommand.execute),
description: {
description: 'Set Editor Layout',
args: [{
name: 'args',
schema: {
'type': 'object',
'required': ['groups'],
'properties': {
'orientation': {
'type': 'number',
'default': 0,
'enum': [0, 1]
},
'groups': {
'$ref': '#/definitions/editorGroupsSchema', // defined in keybindingService.ts ...
'default': [{}, {}],
}
}
}
}]
}
});
CommandsRegistry.registerCommand('_extensionTests.setLogLevel', function (accessor: ServicesAccessor, level: number) {
const logService = accessor.get(ILogService);
const environmentService = accessor.get(IEnvironmentService);
if (environmentService.isExtensionDevelopment && !!environmentService.extensionTestsLocationURI) {
logService.setLevel(level);
}
});
CommandsRegistry.registerCommand('_extensionTests.getLogLevel', function (accessor: ServicesAccessor) {
const logService = accessor.get(ILogService);
return logService.getLevel();
});
CommandsRegistry.registerCommand('_workbench.action.moveViews', async function (accessor: ServicesAccessor, options: { viewIds: string[], destinationId: string }) {
const viewDescriptorService = accessor.get(IViewDescriptorService);
const destination = viewDescriptorService.getViewContainerById(options.destinationId);
if (!destination) {
return;
}
// FYI, don't use `moveViewsToContainer` in 1 shot, because it expects all views to have the same current location
for (const viewId of options.viewIds) {
const viewDescriptor = viewDescriptorService.getViewDescriptorById(viewId);
if (viewDescriptor?.canMoveView) {
viewDescriptorService.moveViewsToContainer([viewDescriptor], destination, ViewVisibilityState.Default);
}
}
await accessor.get(IViewsService).openViewContainer(destination.id, true);
});
export class MoveViewsAPICommand {
public static readonly ID = 'vscode.moveViews';
public static execute(executor: ICommandsExecutor, options: { viewIds: string[], destinationId: string }): Promise<any> {
if (!Array.isArray(options?.viewIds) || typeof options?.destinationId !== 'string') {
return Promise.reject('Invalid arguments');
}
return executor.executeCommand('_workbench.action.moveViews', options);
}
}
CommandsRegistry.registerCommand({
id: MoveViewsAPICommand.ID,
handler: adjustHandler(MoveViewsAPICommand.execute),
description: {
description: 'Move Views',
args: []
}
});

View File

@ -0,0 +1,39 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
export class Cache<T> {
private static readonly enableDebugLogging = false;
private readonly _data = new Map<number, readonly T[]>();
private _idPool = 1;
constructor(
private readonly id: string
) { }
add(item: readonly T[]): number {
const id = this._idPool++;
this._data.set(id, item);
this.logDebugInfo();
return id;
}
get(pid: number, id: number): T | undefined {
return this._data.has(pid) ? this._data.get(pid)![id] : undefined;
}
delete(id: number) {
this._data.delete(id);
this.logDebugInfo();
}
private logDebugInfo() {
if (!Cache.enableDebugLogging) {
return;
}
console.log(`${this.id} cache size — ${this._data.size}`);
}
}

View File

@ -0,0 +1,323 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import * as objects from 'vs/base/common/objects';
import { Registry } from 'vs/platform/registry/common/platform';
import { IJSONSchema } from 'vs/base/common/jsonSchema';
import { ExtensionsRegistry, IExtensionPointUser } from 'vs/workbench/services/extensions/common/extensionsRegistry';
import { IConfigurationNode, IConfigurationRegistry, Extensions, resourceLanguageSettingsSchemaId, validateProperty, ConfigurationScope, OVERRIDE_PROPERTY_PATTERN } from 'vs/platform/configuration/common/configurationRegistry';
import { IJSONContributionRegistry, Extensions as JSONExtensions } from 'vs/platform/jsonschemas/common/jsonContributionRegistry';
import { workspaceSettingsSchemaId, launchSchemaId, tasksSchemaId } from 'vs/workbench/services/configuration/common/configuration';
import { isObject } from 'vs/base/common/types';
import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions';
import { IStringDictionary } from 'vs/base/common/collections';
const configurationRegistry = Registry.as<IConfigurationRegistry>(Extensions.Configuration);
const configurationEntrySchema: IJSONSchema = {
type: 'object',
defaultSnippets: [{ body: { title: '', properties: {} } }],
properties: {
title: {
description: nls.localize('vscode.extension.contributes.configuration.title', 'A summary of the settings. This label will be used in the settings file as separating comment.'),
type: 'string'
},
properties: {
description: nls.localize('vscode.extension.contributes.configuration.properties', 'Description of the configuration properties.'),
type: 'object',
additionalProperties: {
anyOf: [
{ $ref: 'http://json-schema.org/draft-07/schema#' },
{
type: 'object',
properties: {
isExecutable: {
type: 'boolean',
deprecationMessage: 'This property is deprecated. Instead use `scope` property and set it to `machine` value.'
},
scope: {
type: 'string',
enum: ['application', 'machine', 'window', 'resource', 'language-overridable', 'machine-overridable'],
default: 'window',
enumDescriptions: [
nls.localize('scope.application.description', "Configuration that can be configured only in the user settings."),
nls.localize('scope.machine.description', "Configuration that can be configured only in the user settings or only in the remote settings."),
nls.localize('scope.window.description', "Configuration that can be configured in the user, remote or workspace settings."),
nls.localize('scope.resource.description', "Configuration that can be configured in the user, remote, workspace or folder settings."),
nls.localize('scope.language-overridable.description', "Resource configuration that can be configured in language specific settings."),
nls.localize('scope.machine-overridable.description', "Machine configuration that can be configured also in workspace or folder settings.")
],
description: nls.localize('scope.description', "Scope in which the configuration is applicable. Available scopes are `application`, `machine`, `window`, `resource`, and `machine-overridable`.")
},
enumDescriptions: {
type: 'array',
items: {
type: 'string',
},
description: nls.localize('scope.enumDescriptions', 'Descriptions for enum values')
},
markdownEnumDescriptions: {
type: 'array',
items: {
type: 'string',
},
description: nls.localize('scope.markdownEnumDescriptions', 'Descriptions for enum values in the markdown format.')
},
markdownDescription: {
type: 'string',
description: nls.localize('scope.markdownDescription', 'The description in the markdown format.')
},
deprecationMessage: {
type: 'string',
description: nls.localize('scope.deprecationMessage', 'If set, the property is marked as deprecated and the given message is shown as an explanation.')
},
markdownDeprecationMessage: {
type: 'string',
description: nls.localize('scope.markdownDeprecationMessage', 'If set, the property is marked as deprecated and the given message is shown as an explanation in the markdown format.')
}
}
}
]
}
}
}
};
// BEGIN VSCode extension point `configurationDefaults`
const defaultConfigurationExtPoint = ExtensionsRegistry.registerExtensionPoint<IConfigurationNode>({
extensionPoint: 'configurationDefaults',
jsonSchema: {
description: nls.localize('vscode.extension.contributes.defaultConfiguration', 'Contributes default editor configuration settings by language.'),
type: 'object',
patternProperties: {
'^\\[.*\\]$': {
type: 'object',
default: {},
$ref: resourceLanguageSettingsSchemaId,
}
},
errorMessage: nls.localize('config.property.defaultConfiguration.languageExpected', "Language selector expected (e.g. [\"java\"])"),
additionalProperties: false
}
});
defaultConfigurationExtPoint.setHandler((extensions, { added, removed }) => {
if (removed.length) {
const removedDefaultConfigurations = removed.map<IStringDictionary<any>>(extension => objects.deepClone(extension.value));
configurationRegistry.deregisterDefaultConfigurations(removedDefaultConfigurations);
}
if (added.length) {
const addedDefaultConfigurations = added.map<IStringDictionary<any>>(extension => {
const defaults: IStringDictionary<any> = objects.deepClone(extension.value);
for (const key of Object.keys(defaults)) {
if (!OVERRIDE_PROPERTY_PATTERN.test(key) || typeof defaults[key] !== 'object') {
extension.collector.warn(nls.localize('config.property.defaultConfiguration.warning', "Cannot register configuration defaults for '{0}'. Only defaults for language specific settings are supported.", key));
delete defaults[key];
}
}
return defaults;
});
configurationRegistry.registerDefaultConfigurations(addedDefaultConfigurations);
}
});
// END VSCode extension point `configurationDefaults`
// BEGIN VSCode extension point `configuration`
const configurationExtPoint = ExtensionsRegistry.registerExtensionPoint<IConfigurationNode>({
extensionPoint: 'configuration',
deps: [defaultConfigurationExtPoint],
jsonSchema: {
description: nls.localize('vscode.extension.contributes.configuration', 'Contributes configuration settings.'),
oneOf: [
configurationEntrySchema,
{
type: 'array',
items: configurationEntrySchema
}
]
}
});
const extensionConfigurations: Map<string, IConfigurationNode[]> = new Map<string, IConfigurationNode[]>();
configurationExtPoint.setHandler((extensions, { added, removed }) => {
if (removed.length) {
const removedConfigurations: IConfigurationNode[] = [];
for (const extension of removed) {
const key = ExtensionIdentifier.toKey(extension.description.identifier);
removedConfigurations.push(...(extensionConfigurations.get(key) || []));
extensionConfigurations.delete(key);
}
configurationRegistry.deregisterConfigurations(removedConfigurations);
}
function handleConfiguration(node: IConfigurationNode, extension: IExtensionPointUser<any>): IConfigurationNode[] {
const configurations: IConfigurationNode[] = [];
let configuration = objects.deepClone(node);
if (configuration.title && (typeof configuration.title !== 'string')) {
extension.collector.error(nls.localize('invalid.title', "'configuration.title' must be a string"));
}
validateProperties(configuration, extension);
configuration.id = node.id || extension.description.identifier.value;
configuration.extensionInfo = { id: extension.description.identifier.value };
configuration.title = configuration.title || extension.description.displayName || extension.description.identifier.value;
configurations.push(configuration);
return configurations;
}
if (added.length) {
const addedConfigurations: IConfigurationNode[] = [];
for (let extension of added) {
const configurations: IConfigurationNode[] = [];
const value = <IConfigurationNode | IConfigurationNode[]>extension.value;
if (!Array.isArray(value)) {
configurations.push(...handleConfiguration(value, extension));
} else {
value.forEach(v => configurations.push(...handleConfiguration(v, extension)));
}
extensionConfigurations.set(ExtensionIdentifier.toKey(extension.description.identifier), configurations);
addedConfigurations.push(...configurations);
}
configurationRegistry.registerConfigurations(addedConfigurations, false);
}
});
// END VSCode extension point `configuration`
function validateProperties(configuration: IConfigurationNode, extension: IExtensionPointUser<any>): void {
let properties = configuration.properties;
if (properties) {
if (typeof properties !== 'object') {
extension.collector.error(nls.localize('invalid.properties', "'configuration.properties' must be an object"));
configuration.properties = {};
}
for (let key in properties) {
const message = validateProperty(key);
if (message) {
delete properties[key];
extension.collector.warn(message);
continue;
}
const propertyConfiguration = properties[key];
if (!isObject(propertyConfiguration)) {
delete properties[key];
extension.collector.error(nls.localize('invalid.property', "'configuration.property' must be an object"));
continue;
}
if (propertyConfiguration.scope) {
if (propertyConfiguration.scope.toString() === 'application') {
propertyConfiguration.scope = ConfigurationScope.APPLICATION;
} else if (propertyConfiguration.scope.toString() === 'machine') {
propertyConfiguration.scope = ConfigurationScope.MACHINE;
} else if (propertyConfiguration.scope.toString() === 'resource') {
propertyConfiguration.scope = ConfigurationScope.RESOURCE;
} else if (propertyConfiguration.scope.toString() === 'machine-overridable') {
propertyConfiguration.scope = ConfigurationScope.MACHINE_OVERRIDABLE;
} else if (propertyConfiguration.scope.toString() === 'language-overridable') {
propertyConfiguration.scope = ConfigurationScope.LANGUAGE_OVERRIDABLE;
} else {
propertyConfiguration.scope = ConfigurationScope.WINDOW;
}
} else {
propertyConfiguration.scope = ConfigurationScope.WINDOW;
}
}
}
let subNodes = configuration.allOf;
if (subNodes) {
extension.collector.error(nls.localize('invalid.allOf', "'configuration.allOf' is deprecated and should no longer be used. Instead, pass multiple configuration sections as an array to the 'configuration' contribution point."));
for (let node of subNodes) {
validateProperties(node, extension);
}
}
}
const jsonRegistry = Registry.as<IJSONContributionRegistry>(JSONExtensions.JSONContribution);
jsonRegistry.registerSchema('vscode://schemas/workspaceConfig', {
allowComments: true,
allowTrailingCommas: true,
default: {
folders: [
{
path: ''
}
],
settings: {
}
},
required: ['folders'],
properties: {
'folders': {
minItems: 0,
uniqueItems: true,
description: nls.localize('workspaceConfig.folders.description', "List of folders to be loaded in the workspace."),
items: {
type: 'object',
default: { path: '' },
oneOf: [{
properties: {
path: {
type: 'string',
description: nls.localize('workspaceConfig.path.description', "A file path. e.g. `/root/folderA` or `./folderA` for a relative path that will be resolved against the location of the workspace file.")
},
name: {
type: 'string',
description: nls.localize('workspaceConfig.name.description', "An optional name for the folder. ")
}
},
required: ['path']
}, {
properties: {
uri: {
type: 'string',
description: nls.localize('workspaceConfig.uri.description', "URI of the folder")
},
name: {
type: 'string',
description: nls.localize('workspaceConfig.name.description', "An optional name for the folder. ")
}
},
required: ['uri']
}]
}
},
'settings': {
type: 'object',
default: {},
description: nls.localize('workspaceConfig.settings.description', "Workspace settings"),
$ref: workspaceSettingsSchemaId
},
'launch': {
type: 'object',
default: { configurations: [], compounds: [] },
description: nls.localize('workspaceConfig.launch.description', "Workspace launch configurations"),
$ref: launchSchemaId
},
'tasks': {
type: 'object',
default: { version: '2.0.0', tasks: [] },
description: nls.localize('workspaceConfig.tasks.description', "Workspace task configurations"),
$ref: tasksSchemaId
},
'extensions': {
type: 'object',
default: {},
description: nls.localize('workspaceConfig.extensions.description', "Workspace extensions"),
$ref: 'vscode://schemas/extensions'
},
'remoteAuthority': {
type: 'string',
doNotSuggest: true,
description: nls.localize('workspaceConfig.remoteAuthority', "The remote server where the workspace is located. Only used by unsaved remote workspaces."),
}
},
errorMessage: nls.localize('unknownWorkspaceProperty', "Unknown workspace configuration property")
});

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,41 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { IExtHostOutputService, ExtHostOutputService } from 'vs/workbench/api/common/extHostOutput';
import { IExtHostWorkspace, ExtHostWorkspace } from 'vs/workbench/api/common/extHostWorkspace';
import { IExtHostDecorations, ExtHostDecorations } from 'vs/workbench/api/common/extHostDecorations';
import { IExtHostConfiguration, ExtHostConfiguration } from 'vs/workbench/api/common/extHostConfiguration';
import { IExtHostCommands, ExtHostCommands } from 'vs/workbench/api/common/extHostCommands';
import { IExtHostDocumentsAndEditors, ExtHostDocumentsAndEditors } from 'vs/workbench/api/common/extHostDocumentsAndEditors';
import { IExtHostTerminalService, WorkerExtHostTerminalService } from 'vs/workbench/api/common/extHostTerminalService';
import { IExtHostTask, WorkerExtHostTask } from 'vs/workbench/api/common/extHostTask';
import { IExtHostDebugService, WorkerExtHostDebugService } from 'vs/workbench/api/common/extHostDebugService';
import { IExtHostSearch, ExtHostSearch } from 'vs/workbench/api/common/extHostSearch';
import { IExtensionStoragePaths, ExtensionStoragePaths } from 'vs/workbench/api/common/extHostStoragePaths';
import { IExtHostStorage, ExtHostStorage } from 'vs/workbench/api/common/extHostStorage';
import { IExtHostTunnelService, ExtHostTunnelService } from 'vs/workbench/api/common/extHostTunnelService';
import { IExtHostApiDeprecationService, ExtHostApiDeprecationService, } from 'vs/workbench/api/common/extHostApiDeprecationService';
import { IExtHostWindow, ExtHostWindow } from 'vs/workbench/api/common/extHostWindow';
import { IExtHostConsumerFileSystem, ExtHostConsumerFileSystem } from 'vs/workbench/api/common/extHostFileSystemConsumer';
import { IExtHostFileSystemInfo, ExtHostFileSystemInfo } from 'vs/workbench/api/common/extHostFileSystemInfo';
registerSingleton(IExtensionStoragePaths, ExtensionStoragePaths);
registerSingleton(IExtHostApiDeprecationService, ExtHostApiDeprecationService);
registerSingleton(IExtHostCommands, ExtHostCommands);
registerSingleton(IExtHostConfiguration, ExtHostConfiguration);
registerSingleton(IExtHostConsumerFileSystem, ExtHostConsumerFileSystem);
registerSingleton(IExtHostDebugService, WorkerExtHostDebugService);
registerSingleton(IExtHostDecorations, ExtHostDecorations);
registerSingleton(IExtHostDocumentsAndEditors, ExtHostDocumentsAndEditors);
registerSingleton(IExtHostFileSystemInfo, ExtHostFileSystemInfo);
registerSingleton(IExtHostOutputService, ExtHostOutputService);
registerSingleton(IExtHostSearch, ExtHostSearch);
registerSingleton(IExtHostStorage, ExtHostStorage);
registerSingleton(IExtHostTask, WorkerExtHostTask);
registerSingleton(IExtHostTerminalService, WorkerExtHostTerminalService);
registerSingleton(IExtHostTunnelService, ExtHostTunnelService);
registerSingleton(IExtHostWindow, ExtHostWindow);
registerSingleton(IExtHostWorkspace, ExtHostWorkspace);

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,536 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { URI } from 'vs/base/common/uri';
import { DisposableStore, IDisposable } from 'vs/base/common/lifecycle';
import type * as vscode from 'vscode';
import * as typeConverters from 'vs/workbench/api/common/extHostTypeConverters';
import * as types from 'vs/workbench/api/common/extHostTypes';
import { IRawColorInfo, IWorkspaceEditDto, ICallHierarchyItemDto, IIncomingCallDto, IOutgoingCallDto } from 'vs/workbench/api/common/extHost.protocol';
import * as modes from 'vs/editor/common/modes';
import * as search from 'vs/workbench/contrib/search/common/search';
import { ICommandHandlerDescription } from 'vs/platform/commands/common/commands';
import { ExtHostCommands } from 'vs/workbench/api/common/extHostCommands';
import { CustomCodeAction } from 'vs/workbench/api/common/extHostLanguageFeatures';
import { ICommandsExecutor, OpenFolderAPICommand, DiffAPICommand, OpenAPICommand, RemoveFromRecentlyOpenedAPICommand, SetEditorLayoutAPICommand, OpenIssueReporter, OpenIssueReporterArgs } from './apiCommands';
import { EditorGroupLayout } from 'vs/workbench/services/editor/common/editorGroupsService';
import { isFalsyOrEmpty } from 'vs/base/common/arrays';
import { IRange } from 'vs/editor/common/core/range';
import { IPosition } from 'vs/editor/common/core/position';
import { TransientMetadata } from 'vs/workbench/contrib/notebook/common/notebookCommon';
//#region --- NEW world
export class ApiCommandArgument<V, O = V> {
static readonly Uri = new ApiCommandArgument<URI>('uri', 'Uri of a text document', v => URI.isUri(v), v => v);
static readonly Position = new ApiCommandArgument<types.Position, IPosition>('position', 'A position in a text document', v => types.Position.isPosition(v), typeConverters.Position.from);
static readonly Range = new ApiCommandArgument<types.Range, IRange>('range', 'A range in a text document', v => types.Range.isRange(v), typeConverters.Range.from);
static readonly CallHierarchyItem = new ApiCommandArgument('item', 'A call hierarchy item', v => v instanceof types.CallHierarchyItem, typeConverters.CallHierarchyItem.to);
constructor(
readonly name: string,
readonly description: string,
readonly validate: (v: V) => boolean,
readonly convert: (v: V) => O
) { }
}
export class ApiCommandResult<V, O = V> {
constructor(
readonly description: string,
readonly convert: (v: V, apiArgs: any[]) => O
) { }
}
export class ApiCommand {
constructor(
readonly id: string,
readonly internalId: string,
readonly description: string,
readonly args: ApiCommandArgument<any, any>[],
readonly result: ApiCommandResult<any, any>
) { }
register(commands: ExtHostCommands): IDisposable {
return commands.registerCommand(false, this.id, async (...apiArgs) => {
const internalArgs = this.args.map((arg, i) => {
if (!arg.validate(apiArgs[i])) {
throw new Error(`Invalid argument '${arg.name}' when running '${this.id}', receieved: ${apiArgs[i]}`);
}
return arg.convert(apiArgs[i]);
});
const internalResult = await commands.executeCommand(this.internalId, ...internalArgs);
return this.result.convert(internalResult, apiArgs);
}, undefined, this._getCommandHandlerDesc());
}
private _getCommandHandlerDesc(): ICommandHandlerDescription {
return {
description: this.description,
args: this.args,
returns: this.result.description
};
}
}
const newCommands: ApiCommand[] = [
// -- document highlights
new ApiCommand(
'vscode.executeDocumentHighlights', '_executeDocumentHighlights', 'Execute document highlight provider.',
[ApiCommandArgument.Uri, ApiCommandArgument.Position],
new ApiCommandResult<modes.DocumentHighlight[], types.DocumentHighlight[] | undefined>('A promise that resolves to an array of SymbolInformation and DocumentSymbol instances.', tryMapWith(typeConverters.DocumentHighlight.to))
),
// -- document symbols
new ApiCommand(
'vscode.executeDocumentSymbolProvider', '_executeDocumentSymbolProvider', 'Execute document symbol provider.',
[ApiCommandArgument.Uri],
new ApiCommandResult<modes.DocumentSymbol[], vscode.SymbolInformation[] | undefined>('A promise that resolves to an array of DocumentHighlight-instances.', (value, apiArgs) => {
if (isFalsyOrEmpty(value)) {
return undefined;
}
class MergedInfo extends types.SymbolInformation implements vscode.DocumentSymbol {
static to(symbol: modes.DocumentSymbol): MergedInfo {
const res = new MergedInfo(
symbol.name,
typeConverters.SymbolKind.to(symbol.kind),
symbol.containerName || '',
new types.Location(apiArgs[0], typeConverters.Range.to(symbol.range))
);
res.detail = symbol.detail;
res.range = res.location.range;
res.selectionRange = typeConverters.Range.to(symbol.selectionRange);
res.children = symbol.children ? symbol.children.map(MergedInfo.to) : [];
return res;
}
detail!: string;
range!: vscode.Range;
selectionRange!: vscode.Range;
children!: vscode.DocumentSymbol[];
containerName!: string;
}
return value.map(MergedInfo.to);
})
),
// -- formatting
new ApiCommand(
'vscode.executeFormatDocumentProvider', '_executeFormatDocumentProvider', 'Execute document format provider.',
[ApiCommandArgument.Uri, new ApiCommandArgument('options', 'Formatting options', _ => true, v => v)],
new ApiCommandResult<modes.TextEdit[], types.TextEdit[] | undefined>('A promise that resolves to an array of TextEdits.', tryMapWith(typeConverters.TextEdit.to))
),
new ApiCommand(
'vscode.executeFormatRangeProvider', '_executeFormatRangeProvider', 'Execute range format provider.',
[ApiCommandArgument.Uri, ApiCommandArgument.Range, new ApiCommandArgument('options', 'Formatting options', _ => true, v => v)],
new ApiCommandResult<modes.TextEdit[], types.TextEdit[] | undefined>('A promise that resolves to an array of TextEdits.', tryMapWith(typeConverters.TextEdit.to))
),
new ApiCommand(
'vscode.executeFormatOnTypeProvider', '_executeFormatOnTypeProvider', 'Execute format on type provider.',
[ApiCommandArgument.Uri, ApiCommandArgument.Position, new ApiCommandArgument('ch', 'Trigger character', v => typeof v === 'string', v => v), new ApiCommandArgument('options', 'Formatting options', _ => true, v => v)],
new ApiCommandResult<modes.TextEdit[], types.TextEdit[] | undefined>('A promise that resolves to an array of TextEdits.', tryMapWith(typeConverters.TextEdit.to))
),
// -- go to symbol (definition, type definition, declaration, impl, references)
new ApiCommand(
'vscode.executeDefinitionProvider', '_executeDefinitionProvider', 'Execute all definition providers.',
[ApiCommandArgument.Uri, ApiCommandArgument.Position],
new ApiCommandResult<(modes.Location | modes.LocationLink)[], (types.Location | vscode.LocationLink)[] | undefined>('A promise that resolves to an array of Location or LocationLink instances.', mapLocationOrLocationLink)
),
new ApiCommand(
'vscode.executeTypeDefinitionProvider', '_executeTypeDefinitionProvider', 'Execute all type definition providers.',
[ApiCommandArgument.Uri, ApiCommandArgument.Position],
new ApiCommandResult<(modes.Location | modes.LocationLink)[], (types.Location | vscode.LocationLink)[] | undefined>('A promise that resolves to an array of Location or LocationLink instances.', mapLocationOrLocationLink)
),
new ApiCommand(
'vscode.executeDeclarationProvider', '_executeDeclarationProvider', 'Execute all declaration providers.',
[ApiCommandArgument.Uri, ApiCommandArgument.Position],
new ApiCommandResult<(modes.Location | modes.LocationLink)[], (types.Location | vscode.LocationLink)[] | undefined>('A promise that resolves to an array of Location or LocationLink instances.', mapLocationOrLocationLink)
),
new ApiCommand(
'vscode.executeImplementationProvider', '_executeImplementationProvider', 'Execute all implementation providers.',
[ApiCommandArgument.Uri, ApiCommandArgument.Position],
new ApiCommandResult<(modes.Location | modes.LocationLink)[], (types.Location | vscode.LocationLink)[] | undefined>('A promise that resolves to an array of Location or LocationLink instances.', mapLocationOrLocationLink)
),
new ApiCommand(
'vscode.executeReferenceProvider', '_executeReferenceProvider', 'Execute all reference providers.',
[ApiCommandArgument.Uri, ApiCommandArgument.Position],
new ApiCommandResult<modes.Location[], types.Location[] | undefined>('A promise that resolves to an array of Location-instances.', tryMapWith(typeConverters.location.to))
),
// -- hover
new ApiCommand(
'vscode.executeHoverProvider', '_executeHoverProvider', 'Execute all hover providers.',
[ApiCommandArgument.Uri, ApiCommandArgument.Position],
new ApiCommandResult<modes.Hover[], types.Hover[] | undefined>('A promise that resolves to an array of Hover-instances.', tryMapWith(typeConverters.Hover.to))
),
// -- selection range
new ApiCommand(
'vscode.executeSelectionRangeProvider', '_executeSelectionRangeProvider', 'Execute selection range provider.',
[ApiCommandArgument.Uri, new ApiCommandArgument<types.Position[], IPosition[]>('position', 'A positions in a text document', v => Array.isArray(v) && v.every(v => types.Position.isPosition(v)), v => v.map(typeConverters.Position.from))],
new ApiCommandResult<IRange[][], types.SelectionRange[]>('A promise that resolves to an array of ranges.', result => {
return result.map(ranges => {
let node: types.SelectionRange | undefined;
for (const range of ranges.reverse()) {
node = new types.SelectionRange(typeConverters.Range.to(range), node);
}
return node!;
});
})
),
// -- symbol search
new ApiCommand(
'vscode.executeWorkspaceSymbolProvider', '_executeWorkspaceSymbolProvider', 'Execute all workspace symbol providers.',
[new ApiCommandArgument('query', 'Search string', v => typeof v === 'string', v => v)],
new ApiCommandResult<[search.IWorkspaceSymbolProvider, search.IWorkspaceSymbol[]][], types.SymbolInformation[]>('A promise that resolves to an array of SymbolInformation-instances.', value => {
const result: types.SymbolInformation[] = [];
if (Array.isArray(value)) {
for (let tuple of value) {
result.push(...tuple[1].map(typeConverters.WorkspaceSymbol.to));
}
}
return result;
})
),
// --- call hierarchy
new ApiCommand(
'vscode.prepareCallHierarchy', '_executePrepareCallHierarchy', 'Prepare call hierarchy at a position inside a document',
[ApiCommandArgument.Uri, ApiCommandArgument.Position],
new ApiCommandResult<ICallHierarchyItemDto[], types.CallHierarchyItem[]>('A CallHierarchyItem or undefined', v => v.map(typeConverters.CallHierarchyItem.to))
),
new ApiCommand(
'vscode.provideIncomingCalls', '_executeProvideIncomingCalls', 'Compute incoming calls for an item',
[ApiCommandArgument.CallHierarchyItem],
new ApiCommandResult<IIncomingCallDto[], types.CallHierarchyIncomingCall[]>('A CallHierarchyItem or undefined', v => v.map(typeConverters.CallHierarchyIncomingCall.to))
),
new ApiCommand(
'vscode.provideOutgoingCalls', '_executeProvideOutgoingCalls', 'Compute outgoing calls for an item',
[ApiCommandArgument.CallHierarchyItem],
new ApiCommandResult<IOutgoingCallDto[], types.CallHierarchyOutgoingCall[]>('A CallHierarchyItem or undefined', v => v.map(typeConverters.CallHierarchyOutgoingCall.to))
),
// --- rename
new ApiCommand(
'vscode.executeDocumentRenameProvider', '_executeDocumentRenameProvider', 'Execute rename provider.',
[ApiCommandArgument.Uri, ApiCommandArgument.Position, new ApiCommandArgument('newName', 'The new symbol name', v => typeof v === 'string', v => v)],
new ApiCommandResult<IWorkspaceEditDto, types.WorkspaceEdit | undefined>('A promise that resolves to a WorkspaceEdit.', value => {
if (!value) {
return undefined;
}
if (value.rejectReason) {
throw new Error(value.rejectReason);
}
return typeConverters.WorkspaceEdit.to(value);
})
),
// --- links
new ApiCommand(
'vscode.executeLinkProvider', '_executeLinkProvider', 'Execute document link provider.',
[ApiCommandArgument.Uri, new ApiCommandArgument('linkResolveCount', '(optional) Number of links that should be resolved, only when links are unresolved.', v => typeof v === 'number' || typeof v === 'undefined', v => v)],
new ApiCommandResult<modes.ILink[], vscode.DocumentLink[]>('A promise that resolves to an array of DocumentLink-instances.', value => value.map(typeConverters.DocumentLink.to))
)
];
//#endregion
//#region OLD world
export class ExtHostApiCommands {
static register(commands: ExtHostCommands) {
newCommands.forEach(command => command.register(commands));
return new ExtHostApiCommands(commands).registerCommands();
}
private _commands: ExtHostCommands;
private readonly _disposables = new DisposableStore();
private constructor(commands: ExtHostCommands) {
this._commands = commands;
}
registerCommands() {
this._register('vscode.executeSignatureHelpProvider', this._executeSignatureHelpProvider, {
description: 'Execute signature help provider.',
args: [
{ name: 'uri', description: 'Uri of a text document', constraint: URI },
{ name: 'position', description: 'Position in a text document', constraint: types.Position },
{ name: 'triggerCharacter', description: '(optional) Trigger signature help when the user types the character, like `,` or `(`', constraint: (value: any) => value === undefined || typeof value === 'string' }
],
returns: 'A promise that resolves to SignatureHelp.'
});
this._register('vscode.executeCompletionItemProvider', this._executeCompletionItemProvider, {
description: 'Execute completion item provider.',
args: [
{ name: 'uri', description: 'Uri of a text document', constraint: URI },
{ name: 'position', description: 'Position in a text document', constraint: types.Position },
{ name: 'triggerCharacter', description: '(optional) Trigger completion when the user types the character, like `,` or `(`', constraint: (value: any) => value === undefined || typeof value === 'string' },
{ name: 'itemResolveCount', description: '(optional) Number of completions to resolve (too large numbers slow down completions)', constraint: (value: any) => value === undefined || typeof value === 'number' }
],
returns: 'A promise that resolves to a CompletionList-instance.'
});
this._register('vscode.executeCodeActionProvider', this._executeCodeActionProvider, {
description: 'Execute code action provider.',
args: [
{ name: 'uri', description: 'Uri of a text document', constraint: URI },
{ name: 'rangeOrSelection', description: 'Range in a text document. Some refactoring provider requires Selection object.', constraint: types.Range },
{ name: 'kind', description: '(optional) Code action kind to return code actions for', constraint: (value: any) => !value || typeof value.value === 'string' },
{ name: 'itemResolveCount', description: '(optional) Number of code actions to resolve (too large numbers slow down code actions)', constraint: (value: any) => value === undefined || typeof value === 'number' }
],
returns: 'A promise that resolves to an array of Command-instances.'
});
this._register('vscode.executeCodeLensProvider', this._executeCodeLensProvider, {
description: 'Execute CodeLens provider.',
args: [
{ name: 'uri', description: 'Uri of a text document', constraint: URI },
{ name: 'itemResolveCount', description: '(optional) Number of lenses that should be resolved and returned. Will only return resolved lenses, will impact performance)', constraint: (value: any) => value === undefined || typeof value === 'number' }
],
returns: 'A promise that resolves to an array of CodeLens-instances.'
});
this._register('vscode.executeDocumentColorProvider', this._executeDocumentColorProvider, {
description: 'Execute document color provider.',
args: [
{ name: 'uri', description: 'Uri of a text document', constraint: URI },
],
returns: 'A promise that resolves to an array of ColorInformation objects.'
});
this._register('vscode.executeColorPresentationProvider', this._executeColorPresentationProvider, {
description: 'Execute color presentation provider.',
args: [
{ name: 'color', description: 'The color to show and insert', constraint: types.Color },
{ name: 'context', description: 'Context object with uri and range' }
],
returns: 'A promise that resolves to an array of ColorPresentation objects.'
});
this._register('vscode.resolveNotebookContentProviders', this._resolveNotebookContentProviders, {
description: 'Resolve Notebook Content Providers',
args: [],
returns: 'A promise that resolves to an array of NotebookContentProvider static info objects.'
});
// -----------------------------------------------------------------
// The following commands are registered on both sides separately.
//
// We are trying to maintain backwards compatibility for cases where
// API commands are encoded as markdown links, for example.
// -----------------------------------------------------------------
type ICommandHandler = (...args: any[]) => any;
const adjustHandler = (handler: (executor: ICommandsExecutor, ...args: any[]) => any): ICommandHandler => {
return (...args: any[]) => {
return handler(this._commands, ...args);
};
};
this._register(OpenFolderAPICommand.ID, adjustHandler(OpenFolderAPICommand.execute), {
description: 'Open a folder or workspace in the current window or new window depending on the newWindow argument. Note that opening in the same window will shutdown the current extension host process and start a new one on the given folder/workspace unless the newWindow parameter is set to true.',
args: [
{ name: 'uri', description: '(optional) Uri of the folder or workspace file to open. If not provided, a native dialog will ask the user for the folder', constraint: (value: any) => value === undefined || URI.isUri(value) },
{ name: 'options', description: '(optional) Options. Object with the following properties: `forceNewWindow `: Whether to open the folder/workspace in a new window or the same. Defaults to opening in the same window. `noRecentEntry`: Whether the opened URI will appear in the \'Open Recent\' list. Defaults to true. Note, for backward compatibility, options can also be of type boolean, representing the `forceNewWindow` setting.', constraint: (value: any) => value === undefined || typeof value === 'object' || typeof value === 'boolean' }
]
});
this._register(DiffAPICommand.ID, adjustHandler(DiffAPICommand.execute), {
description: 'Opens the provided resources in the diff editor to compare their contents.',
args: [
{ name: 'left', description: 'Left-hand side resource of the diff editor', constraint: URI },
{ name: 'right', description: 'Right-hand side resource of the diff editor', constraint: URI },
{ name: 'title', description: '(optional) Human readable title for the diff editor', constraint: (v: any) => v === undefined || typeof v === 'string' },
{ name: 'options', description: '(optional) Editor options, see vscode.TextDocumentShowOptions' }
]
});
this._register(OpenAPICommand.ID, adjustHandler(OpenAPICommand.execute), {
description: 'Opens the provided resource in the editor. Can be a text or binary file, or a http(s) url. If you need more control over the options for opening a text file, use vscode.window.showTextDocument instead.',
args: [
{ name: 'resource', description: 'Resource to open', constraint: URI },
{ name: 'columnOrOptions', description: '(optional) Either the column in which to open or editor options, see vscode.TextDocumentShowOptions', constraint: (v: any) => v === undefined || typeof v === 'number' || typeof v === 'object' }
]
});
this._register(RemoveFromRecentlyOpenedAPICommand.ID, adjustHandler(RemoveFromRecentlyOpenedAPICommand.execute), {
description: 'Removes an entry with the given path from the recently opened list.',
args: [
{ name: 'path', description: 'Path to remove from recently opened.', constraint: (value: any) => typeof value === 'string' }
]
});
this._register(SetEditorLayoutAPICommand.ID, adjustHandler(SetEditorLayoutAPICommand.execute), {
description: 'Sets the editor layout. The layout is described as object with an initial (optional) orientation (0 = horizontal, 1 = vertical) and an array of editor groups within. Each editor group can have a size and another array of editor groups that will be laid out orthogonal to the orientation. If editor group sizes are provided, their sum must be 1 to be applied per row or column. Example for a 2x2 grid: `{ orientation: 0, groups: [{ groups: [{}, {}], size: 0.5 }, { groups: [{}, {}], size: 0.5 }] }`',
args: [
{ name: 'layout', description: 'The editor layout to set.', constraint: (value: EditorGroupLayout) => typeof value === 'object' && Array.isArray(value.groups) }
]
});
this._register(OpenIssueReporter.ID, adjustHandler(OpenIssueReporter.execute), {
description: 'Opens the issue reporter with the provided extension id as the selected source',
args: [
{ name: 'extensionId', description: 'extensionId to report an issue on', constraint: (value: unknown) => typeof value === 'string' || (typeof value === 'object' && typeof (value as OpenIssueReporterArgs).extensionId === 'string') }
]
});
}
// --- command impl
private _register(id: string, handler: (...args: any[]) => any, description?: ICommandHandlerDescription): void {
const disposable = this._commands.registerCommand(false, id, handler, this, description);
this._disposables.add(disposable);
}
private _executeSignatureHelpProvider(resource: URI, position: types.Position, triggerCharacter: string): Promise<types.SignatureHelp | undefined> {
const args = {
resource,
position: position && typeConverters.Position.from(position),
triggerCharacter
};
return this._commands.executeCommand<modes.SignatureHelp>('_executeSignatureHelpProvider', args).then(value => {
if (value) {
return typeConverters.SignatureHelp.to(value);
}
return undefined;
});
}
private _executeCompletionItemProvider(resource: URI, position: types.Position, triggerCharacter: string, maxItemsToResolve: number): Promise<types.CompletionList | undefined> {
const args = {
resource,
position: position && typeConverters.Position.from(position),
triggerCharacter,
maxItemsToResolve
};
return this._commands.executeCommand<modes.CompletionList>('_executeCompletionItemProvider', args).then(result => {
if (result) {
const items = result.suggestions.map(suggestion => typeConverters.CompletionItem.to(suggestion, this._commands.converter));
return new types.CompletionList(items, result.incomplete);
}
return undefined;
});
}
private _executeDocumentColorProvider(resource: URI): Promise<types.ColorInformation[]> {
const args = {
resource
};
return this._commands.executeCommand<IRawColorInfo[]>('_executeDocumentColorProvider', args).then(result => {
if (result) {
return result.map(ci => ({ range: typeConverters.Range.to(ci.range), color: typeConverters.Color.to(ci.color) }));
}
return [];
});
}
private _executeColorPresentationProvider(color: types.Color, context: { uri: URI, range: types.Range; }): Promise<types.ColorPresentation[]> {
const args = {
resource: context.uri,
color: typeConverters.Color.from(color),
range: typeConverters.Range.from(context.range),
};
return this._commands.executeCommand<modes.IColorPresentation[]>('_executeColorPresentationProvider', args).then(result => {
if (result) {
return result.map(typeConverters.ColorPresentation.to);
}
return [];
});
}
private _executeCodeActionProvider(resource: URI, rangeOrSelection: types.Range | types.Selection, kind?: string, itemResolveCount?: number): Promise<(vscode.CodeAction | vscode.Command | undefined)[] | undefined> {
const args = {
resource,
rangeOrSelection: types.Selection.isSelection(rangeOrSelection)
? typeConverters.Selection.from(rangeOrSelection)
: typeConverters.Range.from(rangeOrSelection),
kind,
itemResolveCount,
};
return this._commands.executeCommand<CustomCodeAction[]>('_executeCodeActionProvider', args)
.then(tryMapWith(codeAction => {
if (codeAction._isSynthetic) {
if (!codeAction.command) {
throw new Error('Synthetic code actions must have a command');
}
return this._commands.converter.fromInternal(codeAction.command);
} else {
const ret = new types.CodeAction(
codeAction.title,
codeAction.kind ? new types.CodeActionKind(codeAction.kind) : undefined
);
if (codeAction.edit) {
ret.edit = typeConverters.WorkspaceEdit.to(codeAction.edit);
}
if (codeAction.command) {
ret.command = this._commands.converter.fromInternal(codeAction.command);
}
ret.isPreferred = codeAction.isPreferred;
return ret;
}
}));
}
private _executeCodeLensProvider(resource: URI, itemResolveCount: number): Promise<vscode.CodeLens[] | undefined> {
const args = { resource, itemResolveCount };
return this._commands.executeCommand<modes.CodeLens[]>('_executeCodeLensProvider', args)
.then(tryMapWith(item => {
return new types.CodeLens(
typeConverters.Range.to(item.range),
item.command ? this._commands.converter.fromInternal(item.command) : undefined);
}));
}
private _resolveNotebookContentProviders(): Promise<{
viewType: string;
displayName: string;
filenamePattern: vscode.NotebookFilenamePattern[];
options: vscode.NotebookDocumentContentOptions;
}[] | undefined> {
return this._commands.executeCommand<{
viewType: string;
displayName: string;
options: { transientOutputs: boolean; transientMetadata: TransientMetadata };
filenamePattern: (string | types.RelativePattern | { include: string | types.RelativePattern, exclude: string | types.RelativePattern })[]
}[]>('_resolveNotebookContentProvider')
.then(tryMapWith(item => {
return {
viewType: item.viewType,
displayName: item.displayName,
options: { transientOutputs: item.options.transientOutputs, transientMetadata: item.options.transientMetadata },
filenamePattern: item.filenamePattern.map(pattern => typeConverters.NotebookExclusiveDocumentPattern.to(pattern))
};
}));
}
}
function tryMapWith<T, R>(f: (x: T) => R) {
return (value: T[]) => {
if (Array.isArray(value)) {
return value.map(f);
}
return undefined;
};
}
function mapLocationOrLocationLink(values: (modes.Location | modes.LocationLink)[]): (types.Location | vscode.LocationLink)[] | undefined {
if (!Array.isArray(values)) {
return undefined;
}
const result: (types.Location | vscode.LocationLink)[] = [];
for (const item of values) {
if (modes.isLocationLink(item)) {
result.push(typeConverters.DefinitionLink.to(item));
} else {
result.push(typeConverters.location.to(item));
}
}
return result;
}

View File

@ -0,0 +1,71 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { ILogService } from 'vs/platform/log/common/log';
import * as extHostProtocol from 'vs/workbench/api/common/extHost.protocol';
import { IExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService';
export interface IExtHostApiDeprecationService {
readonly _serviceBrand: undefined;
report(apiId: string, extension: IExtensionDescription, migrationSuggestion: string): void;
}
export const IExtHostApiDeprecationService = createDecorator<IExtHostApiDeprecationService>('IExtHostApiDeprecationService');
export class ExtHostApiDeprecationService implements IExtHostApiDeprecationService {
declare readonly _serviceBrand: undefined;
private readonly _reportedUsages = new Set<string>();
private readonly _telemetryShape: extHostProtocol.MainThreadTelemetryShape;
constructor(
@IExtHostRpcService rpc: IExtHostRpcService,
@ILogService private readonly _extHostLogService: ILogService,
) {
this._telemetryShape = rpc.getProxy(extHostProtocol.MainContext.MainThreadTelemetry);
}
public report(apiId: string, extension: IExtensionDescription, migrationSuggestion: string): void {
const key = this.getUsageKey(apiId, extension);
if (this._reportedUsages.has(key)) {
return;
}
this._reportedUsages.add(key);
if (extension.isUnderDevelopment) {
this._extHostLogService.warn(`[Deprecation Warning] '${apiId}' is deprecated. ${migrationSuggestion}`);
}
type DeprecationTelemetry = {
extensionId: string;
apiId: string;
};
type DeprecationTelemetryMeta = {
extensionId: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' };
apiId: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' };
};
this._telemetryShape.$publicLog2<DeprecationTelemetry, DeprecationTelemetryMeta>('extHostDeprecatedApiUsage', {
extensionId: extension.identifier.value,
apiId: apiId,
});
}
private getUsageKey(apiId: string, extension: IExtensionDescription): string {
return `${apiId}-${extension.identifier.value}`;
}
}
export const NullApiDeprecationService = Object.freeze(new class implements IExtHostApiDeprecationService {
declare readonly _serviceBrand: undefined;
public report(_apiId: string, _extension: IExtensionDescription, _warningMessage: string): void {
// noop
}
}());

View File

@ -0,0 +1,267 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import type * as vscode from 'vscode';
import * as modes from 'vs/editor/common/modes';
import { Emitter, Event } from 'vs/base/common/event';
import { IMainContext, MainContext, MainThreadAuthenticationShape, ExtHostAuthenticationShape } from 'vs/workbench/api/common/extHost.protocol';
import { Disposable } from 'vs/workbench/api/common/extHostTypes';
import { IExtensionDescription, ExtensionIdentifier } from 'vs/platform/extensions/common/extensions';
interface GetSessionsRequest {
scopes: string;
result: Promise<vscode.AuthenticationSession | undefined>;
}
export class ExtHostAuthentication implements ExtHostAuthenticationShape {
private _proxy: MainThreadAuthenticationShape;
private _authenticationProviders: Map<string, vscode.AuthenticationProvider> = new Map<string, vscode.AuthenticationProvider>();
private _providerIds: string[] = [];
private _providers: vscode.AuthenticationProviderInformation[] = [];
private _onDidChangeAuthenticationProviders = new Emitter<vscode.AuthenticationProvidersChangeEvent>();
readonly onDidChangeAuthenticationProviders: Event<vscode.AuthenticationProvidersChangeEvent> = this._onDidChangeAuthenticationProviders.event;
private _onDidChangeSessions = new Emitter<vscode.AuthenticationSessionsChangeEvent>();
readonly onDidChangeSessions: Event<vscode.AuthenticationSessionsChangeEvent> = this._onDidChangeSessions.event;
private _onDidChangePassword = new Emitter<void>();
readonly onDidChangePassword: Event<void> = this._onDidChangePassword.event;
private _inFlightRequests = new Map<string, GetSessionsRequest[]>();
constructor(mainContext: IMainContext) {
this._proxy = mainContext.getProxy(MainContext.MainThreadAuthentication);
}
$setProviders(providers: vscode.AuthenticationProviderInformation[]): Promise<void> {
this._providers = providers;
return Promise.resolve();
}
getProviderIds(): Promise<ReadonlyArray<string>> {
return this._proxy.$getProviderIds();
}
get providerIds(): string[] {
return this._providerIds;
}
get providers(): ReadonlyArray<vscode.AuthenticationProviderInformation> {
return Object.freeze(this._providers.slice());
}
async getSession(requestingExtension: IExtensionDescription, providerId: string, scopes: string[], options: vscode.AuthenticationGetSessionOptions & { createIfNone: true }): Promise<vscode.AuthenticationSession>;
async getSession(requestingExtension: IExtensionDescription, providerId: string, scopes: string[], options: vscode.AuthenticationGetSessionOptions = {}): Promise<vscode.AuthenticationSession | undefined> {
const extensionId = ExtensionIdentifier.toKey(requestingExtension.identifier);
const inFlightRequests = this._inFlightRequests.get(extensionId) || [];
const sortedScopes = scopes.sort().join(' ');
let inFlightRequest: GetSessionsRequest | undefined = inFlightRequests.find(request => request.scopes === sortedScopes);
if (inFlightRequest) {
return inFlightRequest.result;
} else {
const session = this._getSession(requestingExtension, extensionId, providerId, scopes, options);
inFlightRequest = {
scopes: sortedScopes,
result: session
};
inFlightRequests.push(inFlightRequest);
this._inFlightRequests.set(extensionId, inFlightRequests);
try {
await session;
} finally {
const requestIndex = inFlightRequests.findIndex(request => request.scopes === sortedScopes);
if (requestIndex > -1) {
inFlightRequests.splice(requestIndex);
this._inFlightRequests.set(extensionId, inFlightRequests);
}
}
return session;
}
}
private async _getSession(requestingExtension: IExtensionDescription, extensionId: string, providerId: string, scopes: string[], options: vscode.AuthenticationGetSessionOptions = {}): Promise<vscode.AuthenticationSession | undefined> {
await this._proxy.$ensureProvider(providerId);
const provider = this._authenticationProviders.get(providerId);
const extensionName = requestingExtension.displayName || requestingExtension.name;
if (!provider) {
return this._proxy.$getSession(providerId, scopes, extensionId, extensionName, options);
}
const orderedScopes = scopes.sort().join(' ');
const sessions = (await provider.getSessions()).filter(session => session.scopes.slice().sort().join(' ') === orderedScopes);
let session: vscode.AuthenticationSession | undefined = undefined;
if (sessions.length) {
if (!provider.supportsMultipleAccounts) {
session = sessions[0];
const allowed = await this._proxy.$getSessionsPrompt(providerId, session.account.label, provider.label, extensionId, extensionName);
if (!allowed) {
throw new Error('User did not consent to login.');
}
} else {
// On renderer side, confirm consent, ask user to choose between accounts if multiple sessions are valid
const selected = await this._proxy.$selectSession(providerId, provider.label, extensionId, extensionName, sessions, scopes, !!options.clearSessionPreference);
session = sessions.find(session => session.id === selected.id);
}
} else {
if (options.createIfNone) {
const isAllowed = await this._proxy.$loginPrompt(provider.label, extensionName);
if (!isAllowed) {
throw new Error('User did not consent to login.');
}
session = await provider.login(scopes);
await this._proxy.$setTrustedExtensionAndAccountPreference(providerId, session.account.label, extensionId, extensionName, session.id);
} else {
await this._proxy.$requestNewSession(providerId, scopes, extensionId, extensionName);
}
}
return session;
}
async logout(providerId: string, sessionId: string): Promise<void> {
const provider = this._authenticationProviders.get(providerId);
if (!provider) {
return this._proxy.$logout(providerId, sessionId);
}
return provider.logout(sessionId);
}
registerAuthenticationProvider(provider: vscode.AuthenticationProvider): vscode.Disposable {
if (this._authenticationProviders.get(provider.id)) {
throw new Error(`An authentication provider with id '${provider.id}' is already registered.`);
}
this._authenticationProviders.set(provider.id, provider);
if (!this._providerIds.includes(provider.id)) {
this._providerIds.push(provider.id);
}
if (!this._providers.find(p => p.id === provider.id)) {
this._providers.push({
id: provider.id,
label: provider.label
});
}
const listener = provider.onDidChangeSessions(e => {
this._proxy.$sendDidChangeSessions(provider.id, e);
});
this._proxy.$registerAuthenticationProvider(provider.id, provider.label, provider.supportsMultipleAccounts);
return new Disposable(() => {
listener.dispose();
this._authenticationProviders.delete(provider.id);
const index = this._providerIds.findIndex(id => id === provider.id);
if (index > -1) {
this._providerIds.splice(index);
}
const i = this._providers.findIndex(p => p.id === provider.id);
if (i > -1) {
this._providers.splice(i);
}
this._proxy.$unregisterAuthenticationProvider(provider.id);
});
}
$login(providerId: string, scopes: string[]): Promise<modes.AuthenticationSession> {
const authProvider = this._authenticationProviders.get(providerId);
if (authProvider) {
return Promise.resolve(authProvider.login(scopes));
}
throw new Error(`Unable to find authentication provider with handle: ${providerId}`);
}
$logout(providerId: string, sessionId: string): Promise<void> {
const authProvider = this._authenticationProviders.get(providerId);
if (authProvider) {
return Promise.resolve(authProvider.logout(sessionId));
}
throw new Error(`Unable to find authentication provider with handle: ${providerId}`);
}
$getSessions(providerId: string): Promise<ReadonlyArray<modes.AuthenticationSession>> {
const authProvider = this._authenticationProviders.get(providerId);
if (authProvider) {
return Promise.resolve(authProvider.getSessions());
}
throw new Error(`Unable to find authentication provider with handle: ${providerId}`);
}
async $getSessionAccessToken(providerId: string, sessionId: string): Promise<string> {
const authProvider = this._authenticationProviders.get(providerId);
if (authProvider) {
const sessions = await authProvider.getSessions();
const session = sessions.find(session => session.id === sessionId);
if (session) {
return session.accessToken;
}
throw new Error(`Unable to find session with id: ${sessionId}`);
}
throw new Error(`Unable to find authentication provider with handle: ${providerId}`);
}
$onDidChangeAuthenticationSessions(id: string, label: string, event: modes.AuthenticationSessionsChangeEvent) {
this._onDidChangeSessions.fire({ provider: { id, label }, ...event });
return Promise.resolve();
}
$onDidChangeAuthenticationProviders(added: modes.AuthenticationProviderInformation[], removed: modes.AuthenticationProviderInformation[]) {
added.forEach(provider => {
if (!this._providers.some(p => p.id === provider.id)) {
this._providers.push(provider);
}
});
removed.forEach(p => {
const index = this._providers.findIndex(provider => provider.id === p.id);
if (index > -1) {
this._providers.splice(index);
}
});
this._onDidChangeAuthenticationProviders.fire({ added, removed });
return Promise.resolve();
}
async $onDidChangePassword(): Promise<void> {
this._onDidChangePassword.fire();
}
getPassword(requestingExtension: IExtensionDescription, key: string): Promise<string | undefined> {
const extensionId = ExtensionIdentifier.toKey(requestingExtension.identifier);
return this._proxy.$getPassword(extensionId, key);
}
setPassword(requestingExtension: IExtensionDescription, key: string, value: string): Promise<void> {
const extensionId = ExtensionIdentifier.toKey(requestingExtension.identifier);
return this._proxy.$setPassword(extensionId, key, value);
}
deletePassword(requestingExtension: IExtensionDescription, key: string): Promise<void> {
const extensionId = ExtensionIdentifier.toKey(requestingExtension.identifier);
return this._proxy.$deletePassword(extensionId, key);
}
}

View File

@ -0,0 +1,29 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { MainContext, MainThreadBulkEditsShape } from 'vs/workbench/api/common/extHost.protocol';
import { ExtHostDocumentsAndEditors } from 'vs/workbench/api/common/extHostDocumentsAndEditors';
import { ExtHostNotebookController } from 'vs/workbench/api/common/extHostNotebook';
import { IExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService';
import { WorkspaceEdit } from 'vs/workbench/api/common/extHostTypeConverters';
import type * as vscode from 'vscode';
export class ExtHostBulkEdits {
private readonly _proxy: MainThreadBulkEditsShape;
constructor(
@IExtHostRpcService extHostRpc: IExtHostRpcService,
private readonly _extHostDocumentsAndEditors: ExtHostDocumentsAndEditors,
private readonly _extHostNotebooks: ExtHostNotebookController,
) {
this._proxy = extHostRpc.getProxy(MainContext.MainThreadBulkEdits);
}
applyWorkspaceEdit(edit: vscode.WorkspaceEdit): Promise<boolean> {
const dto = WorkspaceEdit.from(edit, this._extHostDocumentsAndEditors, this._extHostNotebooks);
return this._proxy.$tryApplyWorkspaceEdit(dto);
}
}

View File

@ -0,0 +1,24 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IMainContext, MainContext, MainThreadClipboardShape } from 'vs/workbench/api/common/extHost.protocol';
import type * as vscode from 'vscode';
export class ExtHostClipboard implements vscode.Clipboard {
private readonly _proxy: MainThreadClipboardShape;
constructor(mainContext: IMainContext) {
this._proxy = mainContext.getProxy(MainContext.MainThreadClipboard);
}
readText(): Promise<string> {
return this._proxy.$readText();
}
writeText(value: string): Promise<void> {
return this._proxy.$writeText(value);
}
}

View File

@ -0,0 +1,143 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Emitter } from 'vs/base/common/event';
import { DisposableStore } from 'vs/base/common/lifecycle';
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { ExtHostTextEditor } from 'vs/workbench/api/common/extHostTextEditor';
import { ExtHostEditors } from 'vs/workbench/api/common/extHostTextEditors';
import type * as vscode from 'vscode';
import { ExtHostEditorInsetsShape, MainThreadEditorInsetsShape } from './extHost.protocol';
import { asWebviewUri, WebviewInitData } from 'vs/workbench/api/common/shared/webview';
import { generateUuid } from 'vs/base/common/uuid';
export class ExtHostEditorInsets implements ExtHostEditorInsetsShape {
private _handlePool = 0;
private _disposables = new DisposableStore();
private _insets = new Map<number, { editor: vscode.TextEditor, inset: vscode.WebviewEditorInset, onDidReceiveMessage: Emitter<any> }>();
constructor(
private readonly _proxy: MainThreadEditorInsetsShape,
private readonly _editors: ExtHostEditors,
private readonly _initData: WebviewInitData
) {
// dispose editor inset whenever the hosting editor goes away
this._disposables.add(_editors.onDidChangeVisibleTextEditors(() => {
const visibleEditor = _editors.getVisibleTextEditors();
for (const value of this._insets.values()) {
if (visibleEditor.indexOf(value.editor) < 0) {
value.inset.dispose(); // will remove from `this._insets`
}
}
}));
}
dispose(): void {
this._insets.forEach(value => value.inset.dispose());
this._disposables.dispose();
}
createWebviewEditorInset(editor: vscode.TextEditor, line: number, height: number, options: vscode.WebviewOptions | undefined, extension: IExtensionDescription): vscode.WebviewEditorInset {
let apiEditor: ExtHostTextEditor | undefined;
for (const candidate of this._editors.getVisibleTextEditors()) {
if (candidate === editor) {
apiEditor = <ExtHostTextEditor>candidate;
break;
}
}
if (!apiEditor) {
throw new Error('not a visible editor');
}
const that = this;
const handle = this._handlePool++;
const onDidReceiveMessage = new Emitter<any>();
const onDidDispose = new Emitter<void>();
const webview = new class implements vscode.Webview {
private readonly _uuid = generateUuid();
private _html: string = '';
private _options: vscode.WebviewOptions = Object.create(null);
asWebviewUri(resource: vscode.Uri): vscode.Uri {
return asWebviewUri(that._initData, this._uuid, resource);
}
get cspSource(): string {
return that._initData.webviewCspSource;
}
set options(value: vscode.WebviewOptions) {
this._options = value;
that._proxy.$setOptions(handle, value);
}
get options(): vscode.WebviewOptions {
return this._options;
}
set html(value: string) {
this._html = value;
that._proxy.$setHtml(handle, value);
}
get html(): string {
return this._html;
}
get onDidReceiveMessage(): vscode.Event<any> {
return onDidReceiveMessage.event;
}
postMessage(message: any): Thenable<boolean> {
return that._proxy.$postMessage(handle, message);
}
};
const inset = new class implements vscode.WebviewEditorInset {
readonly editor: vscode.TextEditor = editor;
readonly line: number = line;
readonly height: number = height;
readonly webview: vscode.Webview = webview;
readonly onDidDispose: vscode.Event<void> = onDidDispose.event;
dispose(): void {
if (that._insets.has(handle)) {
that._insets.delete(handle);
that._proxy.$disposeEditorInset(handle);
onDidDispose.fire();
// final cleanup
onDidDispose.dispose();
onDidReceiveMessage.dispose();
}
}
};
this._proxy.$createEditorInset(handle, apiEditor.id, apiEditor.document.uri, line + 1, height, options || {}, extension.identifier, extension.extensionLocation);
this._insets.set(handle, { editor, inset, onDidReceiveMessage });
return inset;
}
$onDidDispose(handle: number): void {
const value = this._insets.get(handle);
if (value) {
value.inset.dispose();
}
}
$onDidReceiveMessage(handle: number, message: any): void {
const value = this._insets.get(handle);
if (value) {
value.onDidReceiveMessage.fire(message);
}
}
}

View File

@ -0,0 +1,297 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { validateConstraint } from 'vs/base/common/types';
import { ICommandHandlerDescription } from 'vs/platform/commands/common/commands';
import * as extHostTypes from 'vs/workbench/api/common/extHostTypes';
import * as extHostTypeConverter from 'vs/workbench/api/common/extHostTypeConverters';
import { cloneAndChange } from 'vs/base/common/objects';
import { MainContext, MainThreadCommandsShape, ExtHostCommandsShape, ObjectIdentifier, ICommandDto } from './extHost.protocol';
import { isNonEmptyArray } from 'vs/base/common/arrays';
import * as modes from 'vs/editor/common/modes';
import type * as vscode from 'vscode';
import { ILogService } from 'vs/platform/log/common/log';
import { revive } from 'vs/base/common/marshalling';
import { Range } from 'vs/editor/common/core/range';
import { Position } from 'vs/editor/common/core/position';
import { URI } from 'vs/base/common/uri';
import { DisposableStore, toDisposable } from 'vs/base/common/lifecycle';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService';
interface CommandHandler {
callback: Function;
thisArg: any;
description?: ICommandHandlerDescription;
}
export interface ArgumentProcessor {
processArgument(arg: any): any;
}
export class ExtHostCommands implements ExtHostCommandsShape {
readonly _serviceBrand: undefined;
private readonly _commands = new Map<string, CommandHandler>();
private readonly _proxy: MainThreadCommandsShape;
private readonly _converter: CommandsConverter;
private readonly _logService: ILogService;
private readonly _argumentProcessors: ArgumentProcessor[];
constructor(
@IExtHostRpcService extHostRpc: IExtHostRpcService,
@ILogService logService: ILogService
) {
this._proxy = extHostRpc.getProxy(MainContext.MainThreadCommands);
this._logService = logService;
this._converter = new CommandsConverter(this, logService);
this._argumentProcessors = [
{
processArgument(a) {
// URI, Regex
return revive(a);
}
},
{
processArgument(arg) {
return cloneAndChange(arg, function (obj) {
// Reverse of https://github.com/microsoft/vscode/blob/1f28c5fc681f4c01226460b6d1c7e91b8acb4a5b/src/vs/workbench/api/node/extHostCommands.ts#L112-L127
if (Range.isIRange(obj)) {
return extHostTypeConverter.Range.to(obj);
}
if (Position.isIPosition(obj)) {
return extHostTypeConverter.Position.to(obj);
}
if (Range.isIRange((obj as modes.Location).range) && URI.isUri((obj as modes.Location).uri)) {
return extHostTypeConverter.location.to(obj);
}
if (!Array.isArray(obj)) {
return obj;
}
});
}
}
];
}
get converter(): CommandsConverter {
return this._converter;
}
registerArgumentProcessor(processor: ArgumentProcessor): void {
this._argumentProcessors.push(processor);
}
registerCommand(global: boolean, id: string, callback: <T>(...args: any[]) => T | Thenable<T>, thisArg?: any, description?: ICommandHandlerDescription): extHostTypes.Disposable {
this._logService.trace('ExtHostCommands#registerCommand', id);
if (!id.trim().length) {
throw new Error('invalid id');
}
if (this._commands.has(id)) {
throw new Error(`command '${id}' already exists`);
}
this._commands.set(id, { callback, thisArg, description });
if (global) {
this._proxy.$registerCommand(id);
}
return new extHostTypes.Disposable(() => {
if (this._commands.delete(id)) {
if (global) {
this._proxy.$unregisterCommand(id);
}
}
});
}
executeCommand<T>(id: string, ...args: any[]): Promise<T> {
this._logService.trace('ExtHostCommands#executeCommand', id);
return this._doExecuteCommand(id, args, true);
}
private async _doExecuteCommand<T>(id: string, args: any[], retry: boolean): Promise<T> {
if (this._commands.has(id)) {
// we stay inside the extension host and support
// to pass any kind of parameters around
return this._executeContributedCommand<T>(id, args);
} else {
// automagically convert some argument types
const toArgs = cloneAndChange(args, function (value) {
if (value instanceof extHostTypes.Position) {
return extHostTypeConverter.Position.from(value);
}
if (value instanceof extHostTypes.Range) {
return extHostTypeConverter.Range.from(value);
}
if (value instanceof extHostTypes.Location) {
return extHostTypeConverter.location.from(value);
}
if (!Array.isArray(value)) {
return value;
}
});
try {
const result = await this._proxy.$executeCommand<T>(id, toArgs, retry);
return revive<any>(result);
} catch (e) {
// Rerun the command when it wasn't known, had arguments, and when retry
// is enabled. We do this because the command might be registered inside
// the extension host now and can therfore accept the arguments as-is.
if (e instanceof Error && e.message === '$executeCommand:retry') {
return this._doExecuteCommand(id, args, false);
} else {
throw e;
}
}
}
}
private _executeContributedCommand<T>(id: string, args: any[]): Promise<T> {
const command = this._commands.get(id);
if (!command) {
throw new Error('Unknown command');
}
let { callback, thisArg, description } = command;
if (description) {
for (let i = 0; i < description.args.length; i++) {
try {
validateConstraint(args[i], description.args[i].constraint);
} catch (err) {
return Promise.reject(new Error(`Running the contributed command: '${id}' failed. Illegal argument '${description.args[i].name}' - ${description.args[i].description}`));
}
}
}
try {
const result = callback.apply(thisArg, args);
return Promise.resolve(result);
} catch (err) {
this._logService.error(err, id);
return Promise.reject(new Error(`Running the contributed command: '${id}' failed.`));
}
}
$executeContributedCommand<T>(id: string, ...args: any[]): Promise<T> {
this._logService.trace('ExtHostCommands#$executeContributedCommand', id);
if (!this._commands.has(id)) {
return Promise.reject(new Error(`Contributed command '${id}' does not exist.`));
} else {
args = args.map(arg => this._argumentProcessors.reduce((r, p) => p.processArgument(r), arg));
return this._executeContributedCommand(id, args);
}
}
getCommands(filterUnderscoreCommands: boolean = false): Promise<string[]> {
this._logService.trace('ExtHostCommands#getCommands', filterUnderscoreCommands);
return this._proxy.$getCommands().then(result => {
if (filterUnderscoreCommands) {
result = result.filter(command => command[0] !== '_');
}
return result;
});
}
$getContributedCommandHandlerDescriptions(): Promise<{ [id: string]: string | ICommandHandlerDescription }> {
const result: { [id: string]: string | ICommandHandlerDescription } = Object.create(null);
for (let [id, command] of this._commands) {
let { description } = command;
if (description) {
result[id] = description;
}
}
return Promise.resolve(result);
}
}
export class CommandsConverter {
private readonly _delegatingCommandId: string;
private readonly _cache = new Map<number, vscode.Command>();
private _cachIdPool = 0;
// --- conversion between internal and api commands
constructor(
private readonly _commands: ExtHostCommands,
private readonly _logService: ILogService
) {
this._delegatingCommandId = `_vscode_delegate_cmd_${Date.now().toString(36)}`;
this._commands.registerCommand(true, this._delegatingCommandId, this._executeConvertedCommand, this);
}
toInternal(command: vscode.Command, disposables: DisposableStore): ICommandDto;
toInternal(command: vscode.Command | undefined, disposables: DisposableStore): ICommandDto | undefined;
toInternal(command: vscode.Command | undefined, disposables: DisposableStore): ICommandDto | undefined {
if (!command) {
return undefined;
}
const result: ICommandDto = {
$ident: undefined,
id: command.command,
title: command.title,
tooltip: command.tooltip
};
if (command.command && isNonEmptyArray(command.arguments)) {
// we have a contributed command with arguments. that
// means we don't want to send the arguments around
const id = ++this._cachIdPool;
this._cache.set(id, command);
disposables.add(toDisposable(() => {
this._cache.delete(id);
this._logService.trace('CommandsConverter#DISPOSE', id);
}));
result.$ident = id;
result.id = this._delegatingCommandId;
result.arguments = [id];
this._logService.trace('CommandsConverter#CREATE', command.command, id);
}
return result;
}
fromInternal(command: modes.Command): vscode.Command | undefined {
const id = ObjectIdentifier.of(command);
if (typeof id === 'number') {
return this._cache.get(id);
} else {
return {
command: command.id,
title: command.title,
arguments: command.arguments
};
}
}
private _executeConvertedCommand<R>(...args: any[]): Promise<R> {
const actualCmd = this._cache.get(args[0]);
this._logService.trace('CommandsConverter#EXECUTE', args[0], actualCmd ? actualCmd.command : 'MISSING');
if (!actualCmd) {
return Promise.reject('actual command NOT FOUND');
}
return this._commands.executeCommand(actualCmd.command, ...(actualCmd.arguments || []));
}
}
export interface IExtHostCommands extends ExtHostCommands { }
export const IExtHostCommands = createDecorator<IExtHostCommands>('IExtHostCommands');

View File

@ -0,0 +1,592 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { asPromise } from 'vs/base/common/async';
import { CancellationToken } from 'vs/base/common/cancellation';
import { debounce } from 'vs/base/common/decorators';
import { Emitter } from 'vs/base/common/event';
import { DisposableStore, IDisposable, MutableDisposable } from 'vs/base/common/lifecycle';
import { URI, UriComponents } from 'vs/base/common/uri';
import { IRange } from 'vs/editor/common/core/range';
import * as modes from 'vs/editor/common/modes';
import { ExtensionIdentifier, IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { ExtHostDocuments } from 'vs/workbench/api/common/extHostDocuments';
import * as extHostTypeConverter from 'vs/workbench/api/common/extHostTypeConverters';
import * as types from 'vs/workbench/api/common/extHostTypes';
import type * as vscode from 'vscode';
import { ExtHostCommentsShape, IMainContext, MainContext, MainThreadCommentsShape, CommentThreadChanges } from './extHost.protocol';
import { ExtHostCommands } from './extHostCommands';
type ProviderHandle = number;
export class ExtHostComments implements ExtHostCommentsShape, IDisposable {
private static handlePool = 0;
private _proxy: MainThreadCommentsShape;
private _commentControllers: Map<ProviderHandle, ExtHostCommentController> = new Map<ProviderHandle, ExtHostCommentController>();
private _commentControllersByExtension: Map<string, ExtHostCommentController[]> = new Map<string, ExtHostCommentController[]>();
constructor(
mainContext: IMainContext,
commands: ExtHostCommands,
private readonly _documents: ExtHostDocuments,
) {
this._proxy = mainContext.getProxy(MainContext.MainThreadComments);
commands.registerArgumentProcessor({
processArgument: arg => {
if (arg && arg.$mid === 6) {
const commentController = this._commentControllers.get(arg.handle);
if (!commentController) {
return arg;
}
return commentController;
} else if (arg && arg.$mid === 7) {
const commentController = this._commentControllers.get(arg.commentControlHandle);
if (!commentController) {
return arg;
}
const commentThread = commentController.getCommentThread(arg.commentThreadHandle);
if (!commentThread) {
return arg;
}
return commentThread;
} else if (arg && arg.$mid === 8) {
const commentController = this._commentControllers.get(arg.thread.commentControlHandle);
if (!commentController) {
return arg;
}
const commentThread = commentController.getCommentThread(arg.thread.commentThreadHandle);
if (!commentThread) {
return arg;
}
return {
thread: commentThread,
text: arg.text
};
} else if (arg && arg.$mid === 9) {
const commentController = this._commentControllers.get(arg.thread.commentControlHandle);
if (!commentController) {
return arg;
}
const commentThread = commentController.getCommentThread(arg.thread.commentThreadHandle);
if (!commentThread) {
return arg;
}
let commentUniqueId = arg.commentUniqueId;
let comment = commentThread.getCommentByUniqueId(commentUniqueId);
if (!comment) {
return arg;
}
return comment;
} else if (arg && arg.$mid === 10) {
const commentController = this._commentControllers.get(arg.thread.commentControlHandle);
if (!commentController) {
return arg;
}
const commentThread = commentController.getCommentThread(arg.thread.commentThreadHandle);
if (!commentThread) {
return arg;
}
let body = arg.text;
let commentUniqueId = arg.commentUniqueId;
let comment = commentThread.getCommentByUniqueId(commentUniqueId);
if (!comment) {
return arg;
}
comment.body = body;
return comment;
}
return arg;
}
});
}
createCommentController(extension: IExtensionDescription, id: string, label: string): vscode.CommentController {
const handle = ExtHostComments.handlePool++;
const commentController = new ExtHostCommentController(extension, handle, this._proxy, id, label);
this._commentControllers.set(commentController.handle, commentController);
const commentControllers = this._commentControllersByExtension.get(ExtensionIdentifier.toKey(extension.identifier)) || [];
commentControllers.push(commentController);
this._commentControllersByExtension.set(ExtensionIdentifier.toKey(extension.identifier), commentControllers);
return commentController;
}
$createCommentThreadTemplate(commentControllerHandle: number, uriComponents: UriComponents, range: IRange): void {
const commentController = this._commentControllers.get(commentControllerHandle);
if (!commentController) {
return;
}
commentController.$createCommentThreadTemplate(uriComponents, range);
}
async $updateCommentThreadTemplate(commentControllerHandle: number, threadHandle: number, range: IRange) {
const commentController = this._commentControllers.get(commentControllerHandle);
if (!commentController) {
return;
}
commentController.$updateCommentThreadTemplate(threadHandle, range);
}
$deleteCommentThread(commentControllerHandle: number, commentThreadHandle: number) {
const commentController = this._commentControllers.get(commentControllerHandle);
if (commentController) {
commentController.$deleteCommentThread(commentThreadHandle);
}
}
$provideCommentingRanges(commentControllerHandle: number, uriComponents: UriComponents, token: CancellationToken): Promise<IRange[] | undefined> {
const commentController = this._commentControllers.get(commentControllerHandle);
if (!commentController || !commentController.commentingRangeProvider) {
return Promise.resolve(undefined);
}
const document = this._documents.getDocument(URI.revive(uriComponents));
return asPromise(() => {
return commentController.commentingRangeProvider!.provideCommentingRanges(document, token);
}).then(ranges => ranges ? ranges.map(x => extHostTypeConverter.Range.from(x)) : undefined);
}
$toggleReaction(commentControllerHandle: number, threadHandle: number, uri: UriComponents, comment: modes.Comment, reaction: modes.CommentReaction): Promise<void> {
const commentController = this._commentControllers.get(commentControllerHandle);
if (!commentController || !commentController.reactionHandler) {
return Promise.resolve(undefined);
}
return asPromise(() => {
const commentThread = commentController.getCommentThread(threadHandle);
if (commentThread) {
const vscodeComment = commentThread.getCommentByUniqueId(comment.uniqueIdInThread);
if (commentController !== undefined && vscodeComment) {
if (commentController.reactionHandler) {
return commentController.reactionHandler(vscodeComment, convertFromReaction(reaction));
}
}
}
return Promise.resolve(undefined);
});
}
dispose() {
}
}
type CommentThreadModification = Partial<{
range: vscode.Range,
label: string | undefined,
contextValue: string | undefined,
comments: vscode.Comment[],
collapsibleState: vscode.CommentThreadCollapsibleState
canReply: boolean;
}>;
export class ExtHostCommentThread implements vscode.CommentThread {
private static _handlePool: number = 0;
readonly handle = ExtHostCommentThread._handlePool++;
public commentHandle: number = 0;
private modifications: CommentThreadModification = Object.create(null);
set threadId(id: string) {
this._id = id;
}
get threadId(): string {
return this._id!;
}
get id(): string {
return this._id!;
}
get resource(): vscode.Uri {
return this._uri;
}
get uri(): vscode.Uri {
return this._uri;
}
private readonly _onDidUpdateCommentThread = new Emitter<void>();
readonly onDidUpdateCommentThread = this._onDidUpdateCommentThread.event;
set range(range: vscode.Range) {
if (!range.isEqual(this._range)) {
this._range = range;
this.modifications.range = range;
this._onDidUpdateCommentThread.fire();
}
}
get range(): vscode.Range {
return this._range;
}
private _canReply: boolean = true;
set canReply(state: boolean) {
if (this._canReply !== state) {
this._canReply = state;
this.modifications.canReply = state;
this._onDidUpdateCommentThread.fire();
}
}
get canReply() {
return this._canReply;
}
private _label: string | undefined;
get label(): string | undefined {
return this._label;
}
set label(label: string | undefined) {
this._label = label;
this.modifications.label = label;
this._onDidUpdateCommentThread.fire();
}
private _contextValue: string | undefined;
get contextValue(): string | undefined {
return this._contextValue;
}
set contextValue(context: string | undefined) {
this._contextValue = context;
this.modifications.contextValue = context;
this._onDidUpdateCommentThread.fire();
}
get comments(): vscode.Comment[] {
return this._comments;
}
set comments(newComments: vscode.Comment[]) {
this._comments = newComments;
this.modifications.comments = newComments;
this._onDidUpdateCommentThread.fire();
}
private _collapseState?: vscode.CommentThreadCollapsibleState;
get collapsibleState(): vscode.CommentThreadCollapsibleState {
return this._collapseState!;
}
set collapsibleState(newState: vscode.CommentThreadCollapsibleState) {
this._collapseState = newState;
this.modifications.collapsibleState = newState;
this._onDidUpdateCommentThread.fire();
}
private _localDisposables: types.Disposable[];
private _isDiposed: boolean;
public get isDisposed(): boolean {
return this._isDiposed;
}
private _commentsMap: Map<vscode.Comment, number> = new Map<vscode.Comment, number>();
private _acceptInputDisposables = new MutableDisposable<DisposableStore>();
constructor(
private _proxy: MainThreadCommentsShape,
private _commentController: ExtHostCommentController,
private _id: string | undefined,
private _uri: vscode.Uri,
private _range: vscode.Range,
private _comments: vscode.Comment[],
extensionId: ExtensionIdentifier
) {
this._acceptInputDisposables.value = new DisposableStore();
if (this._id === undefined) {
this._id = `${_commentController.id}.${this.handle}`;
}
this._proxy.$createCommentThread(
this._commentController.handle,
this.handle,
this._id,
this._uri,
extHostTypeConverter.Range.from(this._range),
extensionId
);
this._localDisposables = [];
this._isDiposed = false;
this._localDisposables.push(this.onDidUpdateCommentThread(() => {
this.eventuallyUpdateCommentThread();
}));
// set up comments after ctor to batch update events.
this.comments = _comments;
}
@debounce(100)
eventuallyUpdateCommentThread(): void {
if (this._isDiposed) {
return;
}
if (!this._acceptInputDisposables.value) {
this._acceptInputDisposables.value = new DisposableStore();
}
const modified = (value: keyof CommentThreadModification): boolean =>
Object.prototype.hasOwnProperty.call(this.modifications, value);
const formattedModifications: CommentThreadChanges = {};
if (modified('range')) {
formattedModifications.range = extHostTypeConverter.Range.from(this._range);
}
if (modified('label')) {
formattedModifications.label = this.label;
}
if (modified('contextValue')) {
formattedModifications.contextValue = this.contextValue;
}
if (modified('comments')) {
formattedModifications.comments =
this._comments.map(cmt => convertToModeComment(this, this._commentController, cmt, this._commentsMap));
}
if (modified('collapsibleState')) {
formattedModifications.collapseState = convertToCollapsibleState(this._collapseState);
}
if (modified('canReply')) {
formattedModifications.canReply = this.canReply;
}
this.modifications = {};
this._proxy.$updateCommentThread(
this._commentController.handle,
this.handle,
this._id!,
this._uri,
formattedModifications
);
}
getCommentByUniqueId(uniqueId: number): vscode.Comment | undefined {
for (let key of this._commentsMap) {
let comment = key[0];
let id = key[1];
if (uniqueId === id) {
return comment;
}
}
return;
}
dispose() {
this._isDiposed = true;
this._acceptInputDisposables.dispose();
this._localDisposables.forEach(disposable => disposable.dispose());
this._proxy.$deleteCommentThread(
this._commentController.handle,
this.handle
);
}
}
type ReactionHandler = (comment: vscode.Comment, reaction: vscode.CommentReaction) => Promise<void>;
class ExtHostCommentController implements vscode.CommentController {
get id(): string {
return this._id;
}
get label(): string {
return this._label;
}
public get handle(): number {
return this._handle;
}
private _threads: Map<number, ExtHostCommentThread> = new Map<number, ExtHostCommentThread>();
commentingRangeProvider?: vscode.CommentingRangeProvider;
private _reactionHandler?: ReactionHandler;
get reactionHandler(): ReactionHandler | undefined {
return this._reactionHandler;
}
set reactionHandler(handler: ReactionHandler | undefined) {
this._reactionHandler = handler;
this._proxy.$updateCommentControllerFeatures(this.handle, { reactionHandler: !!handler });
}
private _options: modes.CommentOptions | undefined;
get options() {
return this._options;
}
set options(options: modes.CommentOptions | undefined) {
this._options = options;
this._proxy.$updateCommentControllerFeatures(this.handle, { options: this._options });
}
constructor(
private _extension: IExtensionDescription,
private _handle: number,
private _proxy: MainThreadCommentsShape,
private _id: string,
private _label: string
) {
this._proxy.$registerCommentController(this.handle, _id, _label);
}
createCommentThread(resource: vscode.Uri, range: vscode.Range, comments: vscode.Comment[]): vscode.CommentThread;
createCommentThread(arg0: vscode.Uri | string, arg1: vscode.Uri | vscode.Range, arg2: vscode.Range | vscode.Comment[], arg3?: vscode.Comment[]): vscode.CommentThread {
if (typeof arg0 === 'string') {
const commentThread = new ExtHostCommentThread(this._proxy, this, arg0, arg1 as vscode.Uri, arg2 as vscode.Range, arg3 as vscode.Comment[], this._extension.identifier);
this._threads.set(commentThread.handle, commentThread);
return commentThread;
} else {
const commentThread = new ExtHostCommentThread(this._proxy, this, undefined, arg0 as vscode.Uri, arg1 as vscode.Range, arg2 as vscode.Comment[], this._extension.identifier);
this._threads.set(commentThread.handle, commentThread);
return commentThread;
}
}
$createCommentThreadTemplate(uriComponents: UriComponents, range: IRange): ExtHostCommentThread {
const commentThread = new ExtHostCommentThread(this._proxy, this, undefined, URI.revive(uriComponents), extHostTypeConverter.Range.to(range), [], this._extension.identifier);
commentThread.collapsibleState = modes.CommentThreadCollapsibleState.Expanded;
this._threads.set(commentThread.handle, commentThread);
return commentThread;
}
$updateCommentThreadTemplate(threadHandle: number, range: IRange): void {
let thread = this._threads.get(threadHandle);
if (thread) {
thread.range = extHostTypeConverter.Range.to(range);
}
}
$deleteCommentThread(threadHandle: number): void {
let thread = this._threads.get(threadHandle);
if (thread) {
thread.dispose();
}
this._threads.delete(threadHandle);
}
getCommentThread(handle: number): ExtHostCommentThread | undefined {
return this._threads.get(handle);
}
dispose(): void {
this._threads.forEach(value => {
value.dispose();
});
this._proxy.$unregisterCommentController(this.handle);
}
}
function convertToModeComment(thread: ExtHostCommentThread, commentController: ExtHostCommentController, vscodeComment: vscode.Comment, commentsMap: Map<vscode.Comment, number>): modes.Comment {
let commentUniqueId = commentsMap.get(vscodeComment)!;
if (!commentUniqueId) {
commentUniqueId = ++thread.commentHandle;
commentsMap.set(vscodeComment, commentUniqueId);
}
const iconPath = vscodeComment.author && vscodeComment.author.iconPath ? vscodeComment.author.iconPath.toString() : undefined;
return {
mode: vscodeComment.mode,
contextValue: vscodeComment.contextValue,
uniqueIdInThread: commentUniqueId,
body: extHostTypeConverter.MarkdownString.from(vscodeComment.body),
userName: vscodeComment.author.name,
userIconPath: iconPath,
label: vscodeComment.label,
commentReactions: vscodeComment.reactions ? vscodeComment.reactions.map(reaction => convertToReaction(reaction)) : undefined
};
}
function convertToReaction(reaction: vscode.CommentReaction): modes.CommentReaction {
return {
label: reaction.label,
iconPath: reaction.iconPath ? extHostTypeConverter.pathOrURIToURI(reaction.iconPath) : undefined,
count: reaction.count,
hasReacted: reaction.authorHasReacted,
};
}
function convertFromReaction(reaction: modes.CommentReaction): vscode.CommentReaction {
return {
label: reaction.label || '',
count: reaction.count || 0,
iconPath: reaction.iconPath ? URI.revive(reaction.iconPath) : '',
authorHasReacted: reaction.hasReacted || false
};
}
function convertToCollapsibleState(kind: vscode.CommentThreadCollapsibleState | undefined): modes.CommentThreadCollapsibleState {
if (kind !== undefined) {
switch (kind) {
case types.CommentThreadCollapsibleState.Expanded:
return modes.CommentThreadCollapsibleState.Expanded;
case types.CommentThreadCollapsibleState.Collapsed:
return modes.CommentThreadCollapsibleState.Collapsed;
}
}
return modes.CommentThreadCollapsibleState.Collapsed;
}

View File

@ -0,0 +1,330 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { mixin, deepClone } from 'vs/base/common/objects';
import { Event, Emitter } from 'vs/base/common/event';
import type * as vscode from 'vscode';
import { ExtHostWorkspace, IExtHostWorkspace } from 'vs/workbench/api/common/extHostWorkspace';
import { ExtHostConfigurationShape, MainThreadConfigurationShape, IConfigurationInitData, MainContext } from './extHost.protocol';
import { ConfigurationTarget as ExtHostConfigurationTarget } from './extHostTypes';
import { ConfigurationTarget, IConfigurationChange, IConfigurationData, IConfigurationOverrides } from 'vs/platform/configuration/common/configuration';
import { Configuration, ConfigurationChangeEvent } from 'vs/platform/configuration/common/configurationModels';
import { ConfigurationScope, OVERRIDE_PROPERTY_PATTERN } from 'vs/platform/configuration/common/configurationRegistry';
import { isObject } from 'vs/base/common/types';
import { ExtensionIdentifier, IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { Barrier } from 'vs/base/common/async';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService';
import { ILogService } from 'vs/platform/log/common/log';
import { Workspace } from 'vs/platform/workspace/common/workspace';
import { URI } from 'vs/base/common/uri';
function lookUp(tree: any, key: string) {
if (key) {
const parts = key.split('.');
let node = tree;
for (let i = 0; node && i < parts.length; i++) {
node = node[parts[i]];
}
return node;
}
}
type ConfigurationInspect<T> = {
key: string;
defaultValue?: T;
globalValue?: T;
workspaceValue?: T,
workspaceFolderValue?: T,
defaultLanguageValue?: T;
globalLanguageValue?: T;
workspaceLanguageValue?: T;
workspaceFolderLanguageValue?: T;
languageIds?: string[];
};
function isUri(thing: any): thing is vscode.Uri {
return thing instanceof URI;
}
function isResourceLanguage(thing: any): thing is { uri: URI, languageId: string } {
return thing
&& thing.uri instanceof URI
&& (thing.languageId && typeof thing.languageId === 'string');
}
function isLanguage(thing: any): thing is { languageId: string } {
return thing
&& !thing.uri
&& (thing.languageId && typeof thing.languageId === 'string');
}
function isWorkspaceFolder(thing: any): thing is vscode.WorkspaceFolder {
return thing
&& thing.uri instanceof URI
&& (!thing.name || typeof thing.name === 'string')
&& (!thing.index || typeof thing.index === 'number');
}
function scopeToOverrides(scope: vscode.ConfigurationScope | undefined | null): IConfigurationOverrides | undefined {
if (isUri(scope)) {
return { resource: scope };
}
if (isResourceLanguage(scope)) {
return { resource: scope.uri, overrideIdentifier: scope.languageId };
}
if (isLanguage(scope)) {
return { overrideIdentifier: scope.languageId };
}
if (isWorkspaceFolder(scope)) {
return { resource: scope.uri };
}
if (scope === null) {
return { resource: null };
}
return undefined;
}
export class ExtHostConfiguration implements ExtHostConfigurationShape {
readonly _serviceBrand: undefined;
private readonly _proxy: MainThreadConfigurationShape;
private readonly _logService: ILogService;
private readonly _extHostWorkspace: ExtHostWorkspace;
private readonly _barrier: Barrier;
private _actual: ExtHostConfigProvider | null;
constructor(
@IExtHostRpcService extHostRpc: IExtHostRpcService,
@IExtHostWorkspace extHostWorkspace: IExtHostWorkspace,
@ILogService logService: ILogService,
) {
this._proxy = extHostRpc.getProxy(MainContext.MainThreadConfiguration);
this._extHostWorkspace = extHostWorkspace;
this._logService = logService;
this._barrier = new Barrier();
this._actual = null;
}
public getConfigProvider(): Promise<ExtHostConfigProvider> {
return this._barrier.wait().then(_ => this._actual!);
}
$initializeConfiguration(data: IConfigurationInitData): void {
this._actual = new ExtHostConfigProvider(this._proxy, this._extHostWorkspace, data, this._logService);
this._barrier.open();
}
$acceptConfigurationChanged(data: IConfigurationInitData, change: IConfigurationChange): void {
this.getConfigProvider().then(provider => provider.$acceptConfigurationChanged(data, change));
}
}
export class ExtHostConfigProvider {
private readonly _onDidChangeConfiguration = new Emitter<vscode.ConfigurationChangeEvent>();
private readonly _proxy: MainThreadConfigurationShape;
private readonly _extHostWorkspace: ExtHostWorkspace;
private _configurationScopes: Map<string, ConfigurationScope | undefined>;
private _configuration: Configuration;
private _logService: ILogService;
constructor(proxy: MainThreadConfigurationShape, extHostWorkspace: ExtHostWorkspace, data: IConfigurationInitData, logService: ILogService) {
this._proxy = proxy;
this._logService = logService;
this._extHostWorkspace = extHostWorkspace;
this._configuration = Configuration.parse(data);
this._configurationScopes = this._toMap(data.configurationScopes);
}
get onDidChangeConfiguration(): Event<vscode.ConfigurationChangeEvent> {
return this._onDidChangeConfiguration && this._onDidChangeConfiguration.event;
}
$acceptConfigurationChanged(data: IConfigurationInitData, change: IConfigurationChange) {
const previous = { data: this._configuration.toData(), workspace: this._extHostWorkspace.workspace };
this._configuration = Configuration.parse(data);
this._configurationScopes = this._toMap(data.configurationScopes);
this._onDidChangeConfiguration.fire(this._toConfigurationChangeEvent(change, previous));
}
getConfiguration(section?: string, scope?: vscode.ConfigurationScope | null, extensionDescription?: IExtensionDescription): vscode.WorkspaceConfiguration {
const overrides = scopeToOverrides(scope) || {};
const config = this._toReadonlyValue(section
? lookUp(this._configuration.getValue(undefined, overrides, this._extHostWorkspace.workspace), section)
: this._configuration.getValue(undefined, overrides, this._extHostWorkspace.workspace));
if (section) {
this._validateConfigurationAccess(section, overrides, extensionDescription?.identifier);
}
function parseConfigurationTarget(arg: boolean | ExtHostConfigurationTarget): ConfigurationTarget | null {
if (arg === undefined || arg === null) {
return null;
}
if (typeof arg === 'boolean') {
return arg ? ConfigurationTarget.USER : ConfigurationTarget.WORKSPACE;
}
switch (arg) {
case ExtHostConfigurationTarget.Global: return ConfigurationTarget.USER;
case ExtHostConfigurationTarget.Workspace: return ConfigurationTarget.WORKSPACE;
case ExtHostConfigurationTarget.WorkspaceFolder: return ConfigurationTarget.WORKSPACE_FOLDER;
}
}
const result: vscode.WorkspaceConfiguration = {
has(key: string): boolean {
return typeof lookUp(config, key) !== 'undefined';
},
get: <T>(key: string, defaultValue?: T) => {
this._validateConfigurationAccess(section ? `${section}.${key}` : key, overrides, extensionDescription?.identifier);
let result = lookUp(config, key);
if (typeof result === 'undefined') {
result = defaultValue;
} else {
let clonedConfig: any | undefined = undefined;
const cloneOnWriteProxy = (target: any, accessor: string): any => {
let clonedTarget: any | undefined = undefined;
const cloneTarget = () => {
clonedConfig = clonedConfig ? clonedConfig : deepClone(config);
clonedTarget = clonedTarget ? clonedTarget : lookUp(clonedConfig, accessor);
};
return isObject(target) ?
new Proxy(target, {
get: (target: any, property: PropertyKey) => {
if (typeof property === 'string' && property.toLowerCase() === 'tojson') {
cloneTarget();
return () => clonedTarget;
}
if (clonedConfig) {
clonedTarget = clonedTarget ? clonedTarget : lookUp(clonedConfig, accessor);
return clonedTarget[property];
}
const result = target[property];
if (typeof property === 'string') {
return cloneOnWriteProxy(result, `${accessor}.${property}`);
}
return result;
},
set: (_target: any, property: PropertyKey, value: any) => {
cloneTarget();
if (clonedTarget) {
clonedTarget[property] = value;
}
return true;
},
deleteProperty: (_target: any, property: PropertyKey) => {
cloneTarget();
if (clonedTarget) {
delete clonedTarget[property];
}
return true;
},
defineProperty: (_target: any, property: PropertyKey, descriptor: any) => {
cloneTarget();
if (clonedTarget) {
Object.defineProperty(clonedTarget, property, descriptor);
}
return true;
}
}) : target;
};
result = cloneOnWriteProxy(result, key);
}
return result;
},
update: (key: string, value: any, extHostConfigurationTarget: ExtHostConfigurationTarget | boolean, scopeToLanguage?: boolean) => {
key = section ? `${section}.${key}` : key;
const target = parseConfigurationTarget(extHostConfigurationTarget);
if (value !== undefined) {
return this._proxy.$updateConfigurationOption(target, key, value, overrides, scopeToLanguage);
} else {
return this._proxy.$removeConfigurationOption(target, key, overrides, scopeToLanguage);
}
},
inspect: <T>(key: string): ConfigurationInspect<T> | undefined => {
key = section ? `${section}.${key}` : key;
const config = deepClone(this._configuration.inspect<T>(key, overrides, this._extHostWorkspace.workspace));
if (config) {
return {
key,
defaultValue: config.default?.value,
globalValue: config.user?.value,
workspaceValue: config.workspace?.value,
workspaceFolderValue: config.workspaceFolder?.value,
defaultLanguageValue: config.default?.override,
globalLanguageValue: config.user?.override,
workspaceLanguageValue: config.workspace?.override,
workspaceFolderLanguageValue: config.workspaceFolder?.override,
languageIds: config.overrideIdentifiers
};
}
return undefined;
}
};
if (typeof config === 'object') {
mixin(result, config, false);
}
return <vscode.WorkspaceConfiguration>Object.freeze(result);
}
private _toReadonlyValue(result: any): any {
const readonlyProxy = (target: any): any => {
return isObject(target) ?
new Proxy(target, {
get: (target: any, property: PropertyKey) => readonlyProxy(target[property]),
set: (_target: any, property: PropertyKey, _value: any) => { throw new Error(`TypeError: Cannot assign to read only property '${String(property)}' of object`); },
deleteProperty: (_target: any, property: PropertyKey) => { throw new Error(`TypeError: Cannot delete read only property '${String(property)}' of object`); },
defineProperty: (_target: any, property: PropertyKey) => { throw new Error(`TypeError: Cannot define property '${String(property)}' for a readonly object`); },
setPrototypeOf: (_target: any) => { throw new Error(`TypeError: Cannot set prototype for a readonly object`); },
isExtensible: () => false,
preventExtensions: () => true
}) : target;
};
return readonlyProxy(result);
}
private _validateConfigurationAccess(key: string, overrides?: IConfigurationOverrides, extensionId?: ExtensionIdentifier): void {
const scope = OVERRIDE_PROPERTY_PATTERN.test(key) ? ConfigurationScope.RESOURCE : this._configurationScopes.get(key);
const extensionIdText = extensionId ? `[${extensionId.value}] ` : '';
if (ConfigurationScope.RESOURCE === scope) {
if (typeof overrides?.resource === 'undefined') {
this._logService.warn(`${extensionIdText}Accessing a resource scoped configuration without providing a resource is not expected. To get the effective value for '${key}', provide the URI of a resource or 'null' for any resource.`);
}
return;
}
if (ConfigurationScope.WINDOW === scope) {
if (overrides?.resource) {
this._logService.warn(`${extensionIdText}Accessing a window scoped configuration for a resource is not expected. To associate '${key}' to a resource, define its scope to 'resource' in configuration contributions in 'package.json'.`);
}
return;
}
}
private _toConfigurationChangeEvent(change: IConfigurationChange, previous: { data: IConfigurationData, workspace: Workspace | undefined }): vscode.ConfigurationChangeEvent {
const event = new ConfigurationChangeEvent(change, previous, this._configuration, this._extHostWorkspace.workspace);
return Object.freeze({
affectsConfiguration: (section: string, scope?: vscode.ConfigurationScope) => event.affectsConfiguration(section, scopeToOverrides(scope))
});
}
private _toMap(scopes: [string, ConfigurationScope | undefined][]): Map<string, ConfigurationScope | undefined> {
return scopes.reduce((result, scope) => { result.set(scope[0], scope[1]); return result; }, new Map<string, ConfigurationScope | undefined>());
}
}
export const IExtHostConfiguration = createDecorator<IExtHostConfiguration>('IExtHostConfiguration');
export interface IExtHostConfiguration extends ExtHostConfiguration { }

View File

@ -0,0 +1,388 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { CancellationToken } from 'vs/base/common/cancellation';
import { hash } from 'vs/base/common/hash';
import { DisposableStore } from 'vs/base/common/lifecycle';
import { Schemas } from 'vs/base/common/network';
import { joinPath } from 'vs/base/common/resources';
import { URI, UriComponents } from 'vs/base/common/uri';
import * as modes from 'vs/editor/common/modes';
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { ExtHostDocuments } from 'vs/workbench/api/common/extHostDocuments';
import { IExtensionStoragePaths } from 'vs/workbench/api/common/extHostStoragePaths';
import { ExtHostWebviews, toExtensionData } from 'vs/workbench/api/common/extHostWebview';
import { ExtHostWebviewPanels } from 'vs/workbench/api/common/extHostWebviewPanels';
import { EditorViewColumn } from 'vs/workbench/api/common/shared/editor';
import type * as vscode from 'vscode';
import { Cache } from './cache';
import * as extHostProtocol from './extHost.protocol';
import * as extHostTypes from './extHostTypes';
class CustomDocumentStoreEntry {
private _backupCounter = 1;
constructor(
public readonly document: vscode.CustomDocument,
private readonly _storagePath: URI | undefined,
) { }
private readonly _edits = new Cache<vscode.CustomDocumentEditEvent>('custom documents');
private _backup?: vscode.CustomDocumentBackup;
addEdit(item: vscode.CustomDocumentEditEvent): number {
return this._edits.add([item]);
}
async undo(editId: number, isDirty: boolean): Promise<void> {
await this.getEdit(editId).undo();
if (!isDirty) {
this.disposeBackup();
}
}
async redo(editId: number, isDirty: boolean): Promise<void> {
await this.getEdit(editId).redo();
if (!isDirty) {
this.disposeBackup();
}
}
disposeEdits(editIds: number[]): void {
for (const id of editIds) {
this._edits.delete(id);
}
}
getNewBackupUri(): URI {
if (!this._storagePath) {
throw new Error('Backup requires a valid storage path');
}
const fileName = hashPath(this.document.uri) + (this._backupCounter++);
return joinPath(this._storagePath, fileName);
}
updateBackup(backup: vscode.CustomDocumentBackup): void {
this._backup?.delete();
this._backup = backup;
}
disposeBackup(): void {
this._backup?.delete();
this._backup = undefined;
}
private getEdit(editId: number): vscode.CustomDocumentEditEvent {
const edit = this._edits.get(editId, 0);
if (!edit) {
throw new Error('No edit found');
}
return edit;
}
}
class CustomDocumentStore {
private readonly _documents = new Map<string, CustomDocumentStoreEntry>();
public get(viewType: string, resource: vscode.Uri): CustomDocumentStoreEntry | undefined {
return this._documents.get(this.key(viewType, resource));
}
public add(viewType: string, document: vscode.CustomDocument, storagePath: URI | undefined): CustomDocumentStoreEntry {
const key = this.key(viewType, document.uri);
if (this._documents.has(key)) {
throw new Error(`Document already exists for viewType:${viewType} resource:${document.uri}`);
}
const entry = new CustomDocumentStoreEntry(document, storagePath);
this._documents.set(key, entry);
return entry;
}
public delete(viewType: string, document: vscode.CustomDocument) {
const key = this.key(viewType, document.uri);
this._documents.delete(key);
}
private key(viewType: string, resource: vscode.Uri): string {
return `${viewType}@@@${resource}`;
}
}
const enum WebviewEditorType {
Text,
Custom
}
type ProviderEntry = {
readonly extension: IExtensionDescription;
readonly type: WebviewEditorType.Text;
readonly provider: vscode.CustomTextEditorProvider;
} | {
readonly extension: IExtensionDescription;
readonly type: WebviewEditorType.Custom;
readonly provider: vscode.CustomReadonlyEditorProvider;
};
class EditorProviderStore {
private readonly _providers = new Map<string, ProviderEntry>();
public addTextProvider(viewType: string, extension: IExtensionDescription, provider: vscode.CustomTextEditorProvider): vscode.Disposable {
return this.add(WebviewEditorType.Text, viewType, extension, provider);
}
public addCustomProvider(viewType: string, extension: IExtensionDescription, provider: vscode.CustomReadonlyEditorProvider): vscode.Disposable {
return this.add(WebviewEditorType.Custom, viewType, extension, provider);
}
public get(viewType: string): ProviderEntry | undefined {
return this._providers.get(viewType);
}
private add(type: WebviewEditorType, viewType: string, extension: IExtensionDescription, provider: vscode.CustomTextEditorProvider | vscode.CustomReadonlyEditorProvider): vscode.Disposable {
if (this._providers.has(viewType)) {
throw new Error(`Provider for viewType:${viewType} already registered`);
}
this._providers.set(viewType, { type, extension, provider } as ProviderEntry);
return new extHostTypes.Disposable(() => this._providers.delete(viewType));
}
}
export class ExtHostCustomEditors implements extHostProtocol.ExtHostCustomEditorsShape {
private readonly _proxy: extHostProtocol.MainThreadCustomEditorsShape;
private readonly _editorProviders = new EditorProviderStore();
private readonly _documents = new CustomDocumentStore();
constructor(
mainContext: extHostProtocol.IMainContext,
private readonly _extHostDocuments: ExtHostDocuments,
private readonly _extensionStoragePaths: IExtensionStoragePaths | undefined,
private readonly _extHostWebview: ExtHostWebviews,
private readonly _extHostWebviewPanels: ExtHostWebviewPanels,
) {
this._proxy = mainContext.getProxy(extHostProtocol.MainContext.MainThreadCustomEditors);
}
public registerCustomEditorProvider(
extension: IExtensionDescription,
viewType: string,
provider: vscode.CustomReadonlyEditorProvider | vscode.CustomTextEditorProvider,
options: { webviewOptions?: vscode.WebviewPanelOptions, supportsMultipleEditorsPerDocument?: boolean },
): vscode.Disposable {
const disposables = new DisposableStore();
if ('resolveCustomTextEditor' in provider) {
disposables.add(this._editorProviders.addTextProvider(viewType, extension, provider));
this._proxy.$registerTextEditorProvider(toExtensionData(extension), viewType, options.webviewOptions || {}, {
supportsMove: !!provider.moveCustomTextEditor,
});
} else {
disposables.add(this._editorProviders.addCustomProvider(viewType, extension, provider));
if (this.supportEditing(provider)) {
disposables.add(provider.onDidChangeCustomDocument(e => {
const entry = this.getCustomDocumentEntry(viewType, e.document.uri);
if (isEditEvent(e)) {
const editId = entry.addEdit(e);
this._proxy.$onDidEdit(e.document.uri, viewType, editId, e.label);
} else {
this._proxy.$onContentChange(e.document.uri, viewType);
}
}));
}
this._proxy.$registerCustomEditorProvider(toExtensionData(extension), viewType, options.webviewOptions || {}, !!options.supportsMultipleEditorsPerDocument);
}
return extHostTypes.Disposable.from(
disposables,
new extHostTypes.Disposable(() => {
this._proxy.$unregisterEditorProvider(viewType);
}));
}
async $createCustomDocument(resource: UriComponents, viewType: string, backupId: string | undefined, cancellation: CancellationToken) {
const entry = this._editorProviders.get(viewType);
if (!entry) {
throw new Error(`No provider found for '${viewType}'`);
}
if (entry.type !== WebviewEditorType.Custom) {
throw new Error(`Invalid provide type for '${viewType}'`);
}
const revivedResource = URI.revive(resource);
const document = await entry.provider.openCustomDocument(revivedResource, { backupId }, cancellation);
let storageRoot: URI | undefined;
if (this.supportEditing(entry.provider) && this._extensionStoragePaths) {
storageRoot = this._extensionStoragePaths.workspaceValue(entry.extension) ?? this._extensionStoragePaths.globalValue(entry.extension);
}
this._documents.add(viewType, document, storageRoot);
return { editable: this.supportEditing(entry.provider) };
}
async $disposeCustomDocument(resource: UriComponents, viewType: string): Promise<void> {
const entry = this._editorProviders.get(viewType);
if (!entry) {
throw new Error(`No provider found for '${viewType}'`);
}
if (entry.type !== WebviewEditorType.Custom) {
throw new Error(`Invalid provider type for '${viewType}'`);
}
const revivedResource = URI.revive(resource);
const { document } = this.getCustomDocumentEntry(viewType, revivedResource);
this._documents.delete(viewType, document);
document.dispose();
}
async $resolveWebviewEditor(
resource: UriComponents,
handle: extHostProtocol.WebviewHandle,
viewType: string,
title: string,
position: EditorViewColumn,
options: modes.IWebviewOptions & modes.IWebviewPanelOptions,
cancellation: CancellationToken,
): Promise<void> {
const entry = this._editorProviders.get(viewType);
if (!entry) {
throw new Error(`No provider found for '${viewType}'`);
}
const webview = this._extHostWebview.createNewWebview(handle, options, entry.extension);
const panel = this._extHostWebviewPanels.createNewWebviewPanel(handle, viewType, title, position, options, webview);
const revivedResource = URI.revive(resource);
switch (entry.type) {
case WebviewEditorType.Custom:
{
const { document } = this.getCustomDocumentEntry(viewType, revivedResource);
return entry.provider.resolveCustomEditor(document, panel, cancellation);
}
case WebviewEditorType.Text:
{
const document = this._extHostDocuments.getDocument(revivedResource);
return entry.provider.resolveCustomTextEditor(document, panel, cancellation);
}
default:
{
throw new Error('Unknown webview provider type');
}
}
}
$disposeEdits(resourceComponents: UriComponents, viewType: string, editIds: number[]): void {
const document = this.getCustomDocumentEntry(viewType, resourceComponents);
document.disposeEdits(editIds);
}
async $onMoveCustomEditor(handle: string, newResourceComponents: UriComponents, viewType: string): Promise<void> {
const entry = this._editorProviders.get(viewType);
if (!entry) {
throw new Error(`No provider found for '${viewType}'`);
}
if (!(entry.provider as vscode.CustomTextEditorProvider).moveCustomTextEditor) {
throw new Error(`Provider does not implement move '${viewType}'`);
}
const webview = this._extHostWebviewPanels.getWebviewPanel(handle);
if (!webview) {
throw new Error(`No webview found`);
}
const resource = URI.revive(newResourceComponents);
const document = this._extHostDocuments.getDocument(resource);
await (entry.provider as vscode.CustomTextEditorProvider).moveCustomTextEditor!(document, webview, CancellationToken.None);
}
async $undo(resourceComponents: UriComponents, viewType: string, editId: number, isDirty: boolean): Promise<void> {
const entry = this.getCustomDocumentEntry(viewType, resourceComponents);
return entry.undo(editId, isDirty);
}
async $redo(resourceComponents: UriComponents, viewType: string, editId: number, isDirty: boolean): Promise<void> {
const entry = this.getCustomDocumentEntry(viewType, resourceComponents);
return entry.redo(editId, isDirty);
}
async $revert(resourceComponents: UriComponents, viewType: string, cancellation: CancellationToken): Promise<void> {
const entry = this.getCustomDocumentEntry(viewType, resourceComponents);
const provider = this.getCustomEditorProvider(viewType);
await provider.revertCustomDocument(entry.document, cancellation);
entry.disposeBackup();
}
async $onSave(resourceComponents: UriComponents, viewType: string, cancellation: CancellationToken): Promise<void> {
const entry = this.getCustomDocumentEntry(viewType, resourceComponents);
const provider = this.getCustomEditorProvider(viewType);
await provider.saveCustomDocument(entry.document, cancellation);
entry.disposeBackup();
}
async $onSaveAs(resourceComponents: UriComponents, viewType: string, targetResource: UriComponents, cancellation: CancellationToken): Promise<void> {
const entry = this.getCustomDocumentEntry(viewType, resourceComponents);
const provider = this.getCustomEditorProvider(viewType);
return provider.saveCustomDocumentAs(entry.document, URI.revive(targetResource), cancellation);
}
async $backup(resourceComponents: UriComponents, viewType: string, cancellation: CancellationToken): Promise<string> {
const entry = this.getCustomDocumentEntry(viewType, resourceComponents);
const provider = this.getCustomEditorProvider(viewType);
const backup = await provider.backupCustomDocument(entry.document, {
destination: entry.getNewBackupUri(),
}, cancellation);
entry.updateBackup(backup);
return backup.id;
}
private getCustomDocumentEntry(viewType: string, resource: UriComponents): CustomDocumentStoreEntry {
const entry = this._documents.get(viewType, URI.revive(resource));
if (!entry) {
throw new Error('No custom document found');
}
return entry;
}
private getCustomEditorProvider(viewType: string): vscode.CustomEditorProvider {
const entry = this._editorProviders.get(viewType);
const provider = entry?.provider;
if (!provider || !this.supportEditing(provider)) {
throw new Error('Custom document is not editable');
}
return provider;
}
private supportEditing(
provider: vscode.CustomTextEditorProvider | vscode.CustomEditorProvider | vscode.CustomReadonlyEditorProvider
): provider is vscode.CustomEditorProvider {
return !!(provider as vscode.CustomEditorProvider).onDidChangeCustomDocument;
}
}
function isEditEvent(e: vscode.CustomDocumentContentChangeEvent | vscode.CustomDocumentEditEvent): e is vscode.CustomDocumentEditEvent {
return typeof (e as vscode.CustomDocumentEditEvent).undo === 'function'
&& typeof (e as vscode.CustomDocumentEditEvent).redo === 'function';
}
function hashPath(resource: URI): string {
const str = resource.scheme === Schemas.file || resource.scheme === Schemas.untitled ? resource.fsPath : resource.toString();
return hash(str) + '';
}

View File

@ -0,0 +1,62 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IDisposable } from 'vs/base/common/lifecycle';
import { IConstructorSignature1, BrandedService } from 'vs/platform/instantiation/common/instantiation';
import { IExtHostContext } from 'vs/workbench/api/common/extHost.protocol';
import { ProxyIdentifier } from 'vs/workbench/services/extensions/common/proxyIdentifier';
export type IExtHostNamedCustomer<T extends IDisposable> = [ProxyIdentifier<T>, IExtHostCustomerCtor<T>];
export type IExtHostCustomerCtor<T extends IDisposable> = IConstructorSignature1<IExtHostContext, T>;
export function extHostNamedCustomer<T extends IDisposable>(id: ProxyIdentifier<T>) {
return function <Services extends BrandedService[]>(ctor: { new(context: IExtHostContext, ...services: Services): T }): void {
ExtHostCustomersRegistryImpl.INSTANCE.registerNamedCustomer(id, ctor as IExtHostCustomerCtor<T>);
};
}
export function extHostCustomer<T extends IDisposable, Services extends BrandedService[]>(ctor: { new(context: IExtHostContext, ...services: Services): T }): void {
ExtHostCustomersRegistryImpl.INSTANCE.registerCustomer(ctor as IExtHostCustomerCtor<T>);
}
export namespace ExtHostCustomersRegistry {
export function getNamedCustomers(): IExtHostNamedCustomer<IDisposable>[] {
return ExtHostCustomersRegistryImpl.INSTANCE.getNamedCustomers();
}
export function getCustomers(): IExtHostCustomerCtor<IDisposable>[] {
return ExtHostCustomersRegistryImpl.INSTANCE.getCustomers();
}
}
class ExtHostCustomersRegistryImpl {
public static readonly INSTANCE = new ExtHostCustomersRegistryImpl();
private _namedCustomers: IExtHostNamedCustomer<any>[];
private _customers: IExtHostCustomerCtor<any>[];
constructor() {
this._namedCustomers = [];
this._customers = [];
}
public registerNamedCustomer<T extends IDisposable>(id: ProxyIdentifier<T>, ctor: IExtHostCustomerCtor<T>): void {
const entry: IExtHostNamedCustomer<T> = [id, ctor];
this._namedCustomers.push(entry);
}
public getNamedCustomers(): IExtHostNamedCustomer<any>[] {
return this._namedCustomers;
}
public registerCustomer<T extends IDisposable>(ctor: IExtHostCustomerCtor<T>): void {
this._customers.push(ctor);
}
public getCustomers(): IExtHostCustomerCtor<any>[] {
return this._customers;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,117 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import type * as vscode from 'vscode';
import { URI } from 'vs/base/common/uri';
import { MainContext, ExtHostDecorationsShape, MainThreadDecorationsShape, DecorationData, DecorationRequest, DecorationReply } from 'vs/workbench/api/common/extHost.protocol';
import { Disposable, FileDecoration } from 'vs/workbench/api/common/extHostTypes';
import { CancellationToken } from 'vs/base/common/cancellation';
import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService';
import { ILogService } from 'vs/platform/log/common/log';
import { asArray, groupBy } from 'vs/base/common/arrays';
import { compare, count } from 'vs/base/common/strings';
import { dirname } from 'vs/base/common/path';
interface ProviderData {
provider: vscode.FileDecorationProvider;
extensionId: ExtensionIdentifier;
}
export class ExtHostDecorations implements ExtHostDecorationsShape {
private static _handlePool = 0;
private static _maxEventSize = 250;
readonly _serviceBrand: undefined;
private readonly _provider = new Map<number, ProviderData>();
private readonly _proxy: MainThreadDecorationsShape;
constructor(
@IExtHostRpcService extHostRpc: IExtHostRpcService,
@ILogService private readonly _logService: ILogService,
) {
this._proxy = extHostRpc.getProxy(MainContext.MainThreadDecorations);
}
registerDecorationProvider(provider: vscode.FileDecorationProvider, extensionId: ExtensionIdentifier): vscode.Disposable {
const handle = ExtHostDecorations._handlePool++;
this._provider.set(handle, { provider, extensionId });
this._proxy.$registerDecorationProvider(handle, extensionId.value);
const listener = provider.onDidChange(e => {
if (!e) {
this._proxy.$onDidChange(handle, null);
return;
}
let array = asArray(e);
if (array.length <= ExtHostDecorations._maxEventSize) {
this._proxy.$onDidChange(handle, array);
return;
}
// too many resources per event. pick one resource per folder, starting
// with parent folders
this._logService.warn('[Decorations] CAPPING events from decorations provider', extensionId.value, array.length);
const mapped = array.map(uri => ({ uri, rank: count(uri.path, '/') }));
const groups = groupBy(mapped, (a, b) => a.rank - b.rank || compare(a.uri.path, b.uri.path));
let picked: URI[] = [];
outer: for (let uris of groups) {
let lastDirname: string | undefined;
for (let obj of uris) {
let myDirname = dirname(obj.uri.path);
if (lastDirname !== myDirname) {
lastDirname = myDirname;
if (picked.push(obj.uri) >= ExtHostDecorations._maxEventSize) {
break outer;
}
}
}
}
this._proxy.$onDidChange(handle, picked);
});
return new Disposable(() => {
listener.dispose();
this._proxy.$unregisterDecorationProvider(handle);
this._provider.delete(handle);
});
}
async $provideDecorations(handle: number, requests: DecorationRequest[], token: CancellationToken): Promise<DecorationReply> {
if (!this._provider.has(handle)) {
// might have been unregistered in the meantime
return Object.create(null);
}
const result: DecorationReply = Object.create(null);
const { provider, extensionId } = this._provider.get(handle)!;
await Promise.all(requests.map(async request => {
try {
const { uri, id } = request;
const data = await Promise.resolve(provider.provideFileDecoration(URI.revive(uri), token));
if (!data) {
return;
}
try {
FileDecoration.validate(data);
result[id] = <DecorationData>[data.propagate, data.tooltip, data.badge, data.color];
} catch (e) {
this._logService.warn(`INVALID decoration from extension '${extensionId.value}': ${e}`);
}
} catch (err) {
this._logService.error(err);
}
}));
return result;
}
}
export const IExtHostDecorations = createDecorator<IExtHostDecorations>('IExtHostDecorations');
export interface IExtHostDecorations extends ExtHostDecorations { }

View File

@ -0,0 +1,350 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { localize } from 'vs/nls';
import { IMarkerData, MarkerSeverity } from 'vs/platform/markers/common/markers';
import { URI, UriComponents } from 'vs/base/common/uri';
import type * as vscode from 'vscode';
import { MainContext, MainThreadDiagnosticsShape, ExtHostDiagnosticsShape, IMainContext } from './extHost.protocol';
import { DiagnosticSeverity } from './extHostTypes';
import * as converter from './extHostTypeConverters';
import { mergeSort } from 'vs/base/common/arrays';
import { Event, Emitter } from 'vs/base/common/event';
import { ILogService } from 'vs/platform/log/common/log';
import { ResourceMap } from 'vs/base/common/map';
import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions';
export class DiagnosticCollection implements vscode.DiagnosticCollection {
private _isDisposed = false;
private _data = new ResourceMap<vscode.Diagnostic[]>();
constructor(
private readonly _name: string,
private readonly _owner: string,
private readonly _maxDiagnosticsPerFile: number,
private readonly _proxy: MainThreadDiagnosticsShape | undefined,
private readonly _onDidChangeDiagnostics: Emitter<vscode.Uri[]>
) { }
dispose(): void {
if (!this._isDisposed) {
this._onDidChangeDiagnostics.fire([...this._data.keys()]);
if (this._proxy) {
this._proxy.$clear(this._owner);
}
this._data = undefined!;
this._isDisposed = true;
}
}
get name(): string {
this._checkDisposed();
return this._name;
}
set(uri: vscode.Uri, diagnostics: ReadonlyArray<vscode.Diagnostic>): void;
set(entries: ReadonlyArray<[vscode.Uri, ReadonlyArray<vscode.Diagnostic>]>): void;
set(first: vscode.Uri | ReadonlyArray<[vscode.Uri, ReadonlyArray<vscode.Diagnostic>]>, diagnostics?: ReadonlyArray<vscode.Diagnostic>) {
if (!first) {
// this set-call is a clear-call
this.clear();
return;
}
// the actual implementation for #set
this._checkDisposed();
let toSync: vscode.Uri[] = [];
if (URI.isUri(first)) {
if (!diagnostics) {
// remove this entry
this.delete(first);
return;
}
// update single row
this._data.set(first, diagnostics.slice());
toSync = [first];
} else if (Array.isArray(first)) {
// update many rows
toSync = [];
let lastUri: vscode.Uri | undefined;
// ensure stable-sort
first = mergeSort([...first], DiagnosticCollection._compareIndexedTuplesByUri);
for (const tuple of first) {
const [uri, diagnostics] = tuple;
if (!lastUri || uri.toString() !== lastUri.toString()) {
if (lastUri && this._data.get(lastUri)!.length === 0) {
this._data.delete(lastUri);
}
lastUri = uri;
toSync.push(uri);
this._data.set(uri, []);
}
if (!diagnostics) {
// [Uri, undefined] means clear this
const currentDiagnostics = this._data.get(uri);
if (currentDiagnostics) {
currentDiagnostics.length = 0;
}
} else {
const currentDiagnostics = this._data.get(uri);
if (currentDiagnostics) {
currentDiagnostics.push(...diagnostics);
}
}
}
}
// send event for extensions
this._onDidChangeDiagnostics.fire(toSync);
// compute change and send to main side
if (!this._proxy) {
return;
}
const entries: [URI, IMarkerData[]][] = [];
for (let uri of toSync) {
let marker: IMarkerData[] = [];
const diagnostics = this._data.get(uri);
if (diagnostics) {
// no more than N diagnostics per file
if (diagnostics.length > this._maxDiagnosticsPerFile) {
marker = [];
const order = [DiagnosticSeverity.Error, DiagnosticSeverity.Warning, DiagnosticSeverity.Information, DiagnosticSeverity.Hint];
orderLoop: for (let i = 0; i < 4; i++) {
for (let diagnostic of diagnostics) {
if (diagnostic.severity === order[i]) {
const len = marker.push(converter.Diagnostic.from(diagnostic));
if (len === this._maxDiagnosticsPerFile) {
break orderLoop;
}
}
}
}
// add 'signal' marker for showing omitted errors/warnings
marker.push({
severity: MarkerSeverity.Info,
message: localize({ key: 'limitHit', comment: ['amount of errors/warning skipped due to limits'] }, "Not showing {0} further errors and warnings.", diagnostics.length - this._maxDiagnosticsPerFile),
startLineNumber: marker[marker.length - 1].startLineNumber,
startColumn: marker[marker.length - 1].startColumn,
endLineNumber: marker[marker.length - 1].endLineNumber,
endColumn: marker[marker.length - 1].endColumn
});
} else {
marker = diagnostics.map(diag => converter.Diagnostic.from(diag));
}
}
entries.push([uri, marker]);
}
this._proxy.$changeMany(this._owner, entries);
}
delete(uri: vscode.Uri): void {
this._checkDisposed();
this._onDidChangeDiagnostics.fire([uri]);
this._data.delete(uri);
if (this._proxy) {
this._proxy.$changeMany(this._owner, [[uri, undefined]]);
}
}
clear(): void {
this._checkDisposed();
this._onDidChangeDiagnostics.fire([...this._data.keys()]);
this._data.clear();
if (this._proxy) {
this._proxy.$clear(this._owner);
}
}
forEach(callback: (uri: URI, diagnostics: ReadonlyArray<vscode.Diagnostic>, collection: DiagnosticCollection) => any, thisArg?: any): void {
this._checkDisposed();
for (let uri of this._data.keys()) {
callback.apply(thisArg, [uri, this.get(uri), this]);
}
}
get(uri: URI): ReadonlyArray<vscode.Diagnostic> {
this._checkDisposed();
const result = this._data.get(uri);
if (Array.isArray(result)) {
return <ReadonlyArray<vscode.Diagnostic>>Object.freeze(result.slice(0));
}
return [];
}
has(uri: URI): boolean {
this._checkDisposed();
return Array.isArray(this._data.get(uri));
}
private _checkDisposed() {
if (this._isDisposed) {
throw new Error('illegal state - object is disposed');
}
}
private static _compareIndexedTuplesByUri(a: [vscode.Uri, readonly vscode.Diagnostic[]], b: [vscode.Uri, readonly vscode.Diagnostic[]]): number {
if (a[0].toString() < b[0].toString()) {
return -1;
} else if (a[0].toString() > b[0].toString()) {
return 1;
} else {
return 0;
}
}
}
export class ExtHostDiagnostics implements ExtHostDiagnosticsShape {
private static _idPool: number = 0;
private static readonly _maxDiagnosticsPerFile: number = 1000;
private readonly _proxy: MainThreadDiagnosticsShape;
private readonly _collections = new Map<string, DiagnosticCollection>();
private readonly _onDidChangeDiagnostics = new Emitter<vscode.Uri[]>();
static _debouncer(last: (vscode.Uri | string)[] | undefined, current: (vscode.Uri | string)[]): (vscode.Uri | string)[] {
if (!last) {
return current;
} else {
return last.concat(current);
}
}
static _mapper(last: (vscode.Uri | string)[]): { uris: vscode.Uri[] } {
const uris: vscode.Uri[] = [];
const map = new Set<string>();
for (const uri of last) {
if (typeof uri === 'string') {
if (!map.has(uri)) {
map.add(uri);
uris.push(URI.parse(uri));
}
} else {
if (!map.has(uri.toString())) {
map.add(uri.toString());
uris.push(uri);
}
}
}
Object.freeze(uris);
return { uris };
}
readonly onDidChangeDiagnostics: Event<vscode.DiagnosticChangeEvent> = Event.map(Event.debounce(this._onDidChangeDiagnostics.event, ExtHostDiagnostics._debouncer, 50), ExtHostDiagnostics._mapper);
constructor(mainContext: IMainContext, @ILogService private readonly _logService: ILogService) {
this._proxy = mainContext.getProxy(MainContext.MainThreadDiagnostics);
}
createDiagnosticCollection(extensionId: ExtensionIdentifier, name?: string): vscode.DiagnosticCollection {
const { _collections, _proxy, _onDidChangeDiagnostics, _logService } = this;
const loggingProxy = new class implements MainThreadDiagnosticsShape {
$changeMany(owner: string, entries: [UriComponents, IMarkerData[] | undefined][]): void {
_proxy.$changeMany(owner, entries);
_logService.trace('[DiagnosticCollection] change many (extension, owner, uris)', extensionId.value, owner, entries.length === 0 ? 'CLEARING' : entries);
}
$clear(owner: string): void {
_proxy.$clear(owner);
_logService.trace('[DiagnosticCollection] remove all (extension, owner)', extensionId.value, owner);
}
dispose(): void {
_proxy.dispose();
}
};
let owner: string;
if (!name) {
name = '_generated_diagnostic_collection_name_#' + ExtHostDiagnostics._idPool++;
owner = name;
} else if (!_collections.has(name)) {
owner = name;
} else {
this._logService.warn(`DiagnosticCollection with name '${name}' does already exist.`);
do {
owner = name + ExtHostDiagnostics._idPool++;
} while (_collections.has(owner));
}
const result = new class extends DiagnosticCollection {
constructor() {
super(name!, owner, ExtHostDiagnostics._maxDiagnosticsPerFile, loggingProxy, _onDidChangeDiagnostics);
_collections.set(owner, this);
}
dispose() {
super.dispose();
_collections.delete(owner);
}
};
return result;
}
getDiagnostics(resource: vscode.Uri): ReadonlyArray<vscode.Diagnostic>;
getDiagnostics(): ReadonlyArray<[vscode.Uri, ReadonlyArray<vscode.Diagnostic>]>;
getDiagnostics(resource?: vscode.Uri): ReadonlyArray<vscode.Diagnostic> | ReadonlyArray<[vscode.Uri, ReadonlyArray<vscode.Diagnostic>]>;
getDiagnostics(resource?: vscode.Uri): ReadonlyArray<vscode.Diagnostic> | ReadonlyArray<[vscode.Uri, ReadonlyArray<vscode.Diagnostic>]> {
if (resource) {
return this._getDiagnostics(resource);
} else {
const index = new Map<string, number>();
const res: [vscode.Uri, vscode.Diagnostic[]][] = [];
for (const collection of this._collections.values()) {
collection.forEach((uri, diagnostics) => {
let idx = index.get(uri.toString());
if (typeof idx === 'undefined') {
idx = res.length;
index.set(uri.toString(), idx);
res.push([uri, []]);
}
res[idx][1] = res[idx][1].concat(...diagnostics);
});
}
return res;
}
}
private _getDiagnostics(resource: vscode.Uri): ReadonlyArray<vscode.Diagnostic> {
let res: vscode.Diagnostic[] = [];
for (let collection of this._collections.values()) {
if (collection.has(resource)) {
res = res.concat(collection.get(resource));
}
}
return res;
}
private _mirrorCollection: vscode.DiagnosticCollection | undefined;
$acceptMarkersChange(data: [UriComponents, IMarkerData[]][]): void {
if (!this._mirrorCollection) {
const name = '_generated_mirror';
const collection = new DiagnosticCollection(name, name, ExtHostDiagnostics._maxDiagnosticsPerFile, undefined, this._onDidChangeDiagnostics);
this._collections.set(name, collection);
this._mirrorCollection = collection;
}
for (const [uri, markers] of data) {
this._mirrorCollection.set(URI.revive(uri), markers.map(converter.Diagnostic.to));
}
}
}

View File

@ -0,0 +1,29 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import type * as vscode from 'vscode';
import { URI } from 'vs/base/common/uri';
import { MainContext, MainThreadDiaglogsShape, IMainContext } from 'vs/workbench/api/common/extHost.protocol';
export class ExtHostDialogs {
private readonly _proxy: MainThreadDiaglogsShape;
constructor(mainContext: IMainContext) {
this._proxy = mainContext.getProxy(MainContext.MainThreadDialogs);
}
showOpenDialog(options?: vscode.OpenDialogOptions): Promise<URI[] | undefined> {
return this._proxy.$showOpenDialog(options).then(filepaths => {
return filepaths ? filepaths.map(p => URI.revive(p)) : undefined;
});
}
showSaveDialog(options?: vscode.SaveDialogOptions): Promise<URI | undefined> {
return this._proxy.$showSaveDialog(options).then(filepath => {
return filepath ? URI.revive(filepath) : undefined;
});
}
}

View File

@ -0,0 +1,93 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { onUnexpectedError } from 'vs/base/common/errors';
import { URI, UriComponents } from 'vs/base/common/uri';
import { IDisposable } from 'vs/base/common/lifecycle';
import { Disposable } from 'vs/workbench/api/common/extHostTypes';
import type * as vscode from 'vscode';
import { MainContext, ExtHostDocumentContentProvidersShape, MainThreadDocumentContentProvidersShape, IMainContext } from './extHost.protocol';
import { ExtHostDocumentsAndEditors } from './extHostDocumentsAndEditors';
import { Schemas } from 'vs/base/common/network';
import { ILogService } from 'vs/platform/log/common/log';
import { CancellationToken } from 'vs/base/common/cancellation';
export class ExtHostDocumentContentProvider implements ExtHostDocumentContentProvidersShape {
private static _handlePool = 0;
private readonly _documentContentProviders = new Map<number, vscode.TextDocumentContentProvider>();
private readonly _proxy: MainThreadDocumentContentProvidersShape;
constructor(
mainContext: IMainContext,
private readonly _documentsAndEditors: ExtHostDocumentsAndEditors,
private readonly _logService: ILogService,
) {
this._proxy = mainContext.getProxy(MainContext.MainThreadDocumentContentProviders);
}
registerTextDocumentContentProvider(scheme: string, provider: vscode.TextDocumentContentProvider): vscode.Disposable {
// todo@remote
// check with scheme from fs-providers!
if (Object.keys(Schemas).indexOf(scheme) >= 0) {
throw new Error(`scheme '${scheme}' already registered`);
}
const handle = ExtHostDocumentContentProvider._handlePool++;
this._documentContentProviders.set(handle, provider);
this._proxy.$registerTextContentProvider(handle, scheme);
let subscription: IDisposable | undefined;
if (typeof provider.onDidChange === 'function') {
subscription = provider.onDidChange(uri => {
if (uri.scheme !== scheme) {
this._logService.warn(`Provider for scheme '${scheme}' is firing event for schema '${uri.scheme}' which will be IGNORED`);
return;
}
if (this._documentsAndEditors.getDocument(uri)) {
this.$provideTextDocumentContent(handle, uri).then(value => {
if (!value && typeof value !== 'string') {
return;
}
const document = this._documentsAndEditors.getDocument(uri);
if (!document) {
// disposed in the meantime
return;
}
// create lines and compare
const lines = value.split(/\r\n|\r|\n/);
// broadcast event when content changed
if (!document.equalLines(lines)) {
return this._proxy.$onVirtualDocumentChange(uri, value);
}
}, onUnexpectedError);
}
});
}
return new Disposable(() => {
if (this._documentContentProviders.delete(handle)) {
this._proxy.$unregisterTextContentProvider(handle);
}
if (subscription) {
subscription.dispose();
subscription = undefined;
}
});
}
$provideTextDocumentContent(handle: number, uri: UriComponents): Promise<string | null | undefined> {
const provider = this._documentContentProviders.get(handle);
if (!provider) {
return Promise.reject(new Error(`unsupported uri-scheme: ${uri.scheme}`));
}
return Promise.resolve(provider.provideTextDocumentContent(URI.revive(uri), CancellationToken.None));
}
}

View File

@ -0,0 +1,283 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ok } from 'vs/base/common/assert';
import { Schemas } from 'vs/base/common/network';
import { regExpLeadsToEndlessLoop } from 'vs/base/common/strings';
import { URI } from 'vs/base/common/uri';
import { MirrorTextModel } from 'vs/editor/common/model/mirrorTextModel';
import { ensureValidWordDefinition, getWordAtText } from 'vs/editor/common/model/wordHelper';
import { MainThreadDocumentsShape } from 'vs/workbench/api/common/extHost.protocol';
import { EndOfLine, Position, Range } from 'vs/workbench/api/common/extHostTypes';
import type * as vscode from 'vscode';
import { equals } from 'vs/base/common/arrays';
const _modeId2WordDefinition = new Map<string, RegExp>();
export function setWordDefinitionFor(modeId: string, wordDefinition: RegExp | undefined): void {
if (!wordDefinition) {
_modeId2WordDefinition.delete(modeId);
} else {
_modeId2WordDefinition.set(modeId, wordDefinition);
}
}
export function getWordDefinitionFor(modeId: string): RegExp | undefined {
return _modeId2WordDefinition.get(modeId);
}
export class ExtHostDocumentData extends MirrorTextModel {
private _document?: vscode.TextDocument;
private _isDisposed: boolean = false;
constructor(
private readonly _proxy: MainThreadDocumentsShape,
uri: URI, lines: string[], eol: string, versionId: number,
private _languageId: string,
private _isDirty: boolean,
private readonly _notebook?: vscode.NotebookDocument | undefined
) {
super(uri, lines, eol, versionId);
}
dispose(): void {
// we don't really dispose documents but let
// extensions still read from them. some
// operations, live saving, will now error tho
ok(!this._isDisposed);
this._isDisposed = true;
this._isDirty = false;
}
equalLines(lines: readonly string[]): boolean {
return equals(this._lines, lines);
}
get document(): vscode.TextDocument {
if (!this._document) {
const that = this;
this._document = {
get uri() { return that._uri; },
get fileName() { return that._uri.fsPath; },
get isUntitled() { return that._uri.scheme === Schemas.untitled; },
get languageId() { return that._languageId; },
get version() { return that._versionId; },
get isClosed() { return that._isDisposed; },
get isDirty() { return that._isDirty; },
get notebook() { return that._notebook; },
save() { return that._save(); },
getText(range?) { return range ? that._getTextInRange(range) : that.getText(); },
get eol() { return that._eol === '\n' ? EndOfLine.LF : EndOfLine.CRLF; },
get lineCount() { return that._lines.length; },
lineAt(lineOrPos: number | vscode.Position) { return that._lineAt(lineOrPos); },
offsetAt(pos) { return that._offsetAt(pos); },
positionAt(offset) { return that._positionAt(offset); },
validateRange(ran) { return that._validateRange(ran); },
validatePosition(pos) { return that._validatePosition(pos); },
getWordRangeAtPosition(pos, regexp?) { return that._getWordRangeAtPosition(pos, regexp); },
};
}
return Object.freeze(this._document);
}
_acceptLanguageId(newLanguageId: string): void {
ok(!this._isDisposed);
this._languageId = newLanguageId;
}
_acceptIsDirty(isDirty: boolean): void {
ok(!this._isDisposed);
this._isDirty = isDirty;
}
private _save(): Promise<boolean> {
if (this._isDisposed) {
return Promise.reject(new Error('Document has been closed'));
}
return this._proxy.$trySaveDocument(this._uri);
}
private _getTextInRange(_range: vscode.Range): string {
const range = this._validateRange(_range);
if (range.isEmpty) {
return '';
}
if (range.isSingleLine) {
return this._lines[range.start.line].substring(range.start.character, range.end.character);
}
const lineEnding = this._eol,
startLineIndex = range.start.line,
endLineIndex = range.end.line,
resultLines: string[] = [];
resultLines.push(this._lines[startLineIndex].substring(range.start.character));
for (let i = startLineIndex + 1; i < endLineIndex; i++) {
resultLines.push(this._lines[i]);
}
resultLines.push(this._lines[endLineIndex].substring(0, range.end.character));
return resultLines.join(lineEnding);
}
private _lineAt(lineOrPosition: number | vscode.Position): vscode.TextLine {
let line: number | undefined;
if (lineOrPosition instanceof Position) {
line = lineOrPosition.line;
} else if (typeof lineOrPosition === 'number') {
line = lineOrPosition;
}
if (typeof line !== 'number' || line < 0 || line >= this._lines.length || Math.floor(line) !== line) {
throw new Error('Illegal value for `line`');
}
return new ExtHostDocumentLine(line, this._lines[line], line === this._lines.length - 1);
}
private _offsetAt(position: vscode.Position): number {
position = this._validatePosition(position);
this._ensureLineStarts();
return this._lineStarts!.getAccumulatedValue(position.line - 1) + position.character;
}
private _positionAt(offset: number): vscode.Position {
offset = Math.floor(offset);
offset = Math.max(0, offset);
this._ensureLineStarts();
const out = this._lineStarts!.getIndexOf(offset);
const lineLength = this._lines[out.index].length;
// Ensure we return a valid position
return new Position(out.index, Math.min(out.remainder, lineLength));
}
// ---- range math
private _validateRange(range: vscode.Range): vscode.Range {
if (!(range instanceof Range)) {
throw new Error('Invalid argument');
}
const start = this._validatePosition(range.start);
const end = this._validatePosition(range.end);
if (start === range.start && end === range.end) {
return range;
}
return new Range(start.line, start.character, end.line, end.character);
}
private _validatePosition(position: vscode.Position): vscode.Position {
if (!(position instanceof Position)) {
throw new Error('Invalid argument');
}
if (this._lines.length === 0) {
return position.with(0, 0);
}
let { line, character } = position;
let hasChanged = false;
if (line < 0) {
line = 0;
character = 0;
hasChanged = true;
}
else if (line >= this._lines.length) {
line = this._lines.length - 1;
character = this._lines[line].length;
hasChanged = true;
}
else {
const maxCharacter = this._lines[line].length;
if (character < 0) {
character = 0;
hasChanged = true;
}
else if (character > maxCharacter) {
character = maxCharacter;
hasChanged = true;
}
}
if (!hasChanged) {
return position;
}
return new Position(line, character);
}
private _getWordRangeAtPosition(_position: vscode.Position, regexp?: RegExp): vscode.Range | undefined {
const position = this._validatePosition(_position);
if (!regexp) {
// use default when custom-regexp isn't provided
regexp = getWordDefinitionFor(this._languageId);
} else if (regExpLeadsToEndlessLoop(regexp)) {
// use default when custom-regexp is bad
throw new Error(`[getWordRangeAtPosition]: ignoring custom regexp '${regexp.source}' because it matches the empty string.`);
}
const wordAtText = getWordAtText(
position.character + 1,
ensureValidWordDefinition(regexp),
this._lines[position.line],
0
);
if (wordAtText) {
return new Range(position.line, wordAtText.startColumn - 1, position.line, wordAtText.endColumn - 1);
}
return undefined;
}
}
export class ExtHostDocumentLine implements vscode.TextLine {
private readonly _line: number;
private readonly _text: string;
private readonly _isLastLine: boolean;
constructor(line: number, text: string, isLastLine: boolean) {
this._line = line;
this._text = text;
this._isLastLine = isLastLine;
}
public get lineNumber(): number {
return this._line;
}
public get text(): string {
return this._text;
}
public get range(): Range {
return new Range(this._line, 0, this._line, this._text.length);
}
public get rangeIncludingLineBreak(): Range {
if (this._isLastLine) {
return this.range;
}
return new Range(this._line, 0, this._line + 1, 0);
}
public get firstNonWhitespaceCharacterIndex(): number {
//TODO@api, rename to 'leadingWhitespaceLength'
return /^(\s*)/.exec(this._text)![1].length;
}
public get isEmptyOrWhitespace(): boolean {
return this.firstNonWhitespaceCharacterIndex === this._text.length;
}
}

View File

@ -0,0 +1,174 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Event } from 'vs/base/common/event';
import { URI, UriComponents } from 'vs/base/common/uri';
import { illegalState } from 'vs/base/common/errors';
import { ExtHostDocumentSaveParticipantShape, IWorkspaceEditDto, WorkspaceEditType, MainThreadBulkEditsShape } from 'vs/workbench/api/common/extHost.protocol';
import { TextEdit } from 'vs/workbench/api/common/extHostTypes';
import { Range, TextDocumentSaveReason, EndOfLine } from 'vs/workbench/api/common/extHostTypeConverters';
import { ExtHostDocuments } from 'vs/workbench/api/common/extHostDocuments';
import { SaveReason } from 'vs/workbench/common/editor';
import type * as vscode from 'vscode';
import { LinkedList } from 'vs/base/common/linkedList';
import { ILogService } from 'vs/platform/log/common/log';
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
type Listener = [Function, any, IExtensionDescription];
export class ExtHostDocumentSaveParticipant implements ExtHostDocumentSaveParticipantShape {
private readonly _callbacks = new LinkedList<Listener>();
private readonly _badListeners = new WeakMap<Function, number>();
constructor(
private readonly _logService: ILogService,
private readonly _documents: ExtHostDocuments,
private readonly _mainThreadBulkEdits: MainThreadBulkEditsShape,
private readonly _thresholds: { timeout: number; errors: number; } = { timeout: 1500, errors: 3 }
) {
//
}
dispose(): void {
this._callbacks.clear();
}
getOnWillSaveTextDocumentEvent(extension: IExtensionDescription): Event<vscode.TextDocumentWillSaveEvent> {
return (listener, thisArg, disposables) => {
const remove = this._callbacks.push([listener, thisArg, extension]);
const result = { dispose: remove };
if (Array.isArray(disposables)) {
disposables.push(result);
}
return result;
};
}
async $participateInSave(data: UriComponents, reason: SaveReason): Promise<boolean[]> {
const resource = URI.revive(data);
let didTimeout = false;
const didTimeoutHandle = setTimeout(() => didTimeout = true, this._thresholds.timeout);
const results: boolean[] = [];
try {
for (let listener of [...this._callbacks]) { // copy to prevent concurrent modifications
if (didTimeout) {
// timeout - no more listeners
break;
}
const document = this._documents.getDocument(resource);
const success = await this._deliverEventAsyncAndBlameBadListeners(listener, <any>{ document, reason: TextDocumentSaveReason.to(reason) });
results.push(success);
}
} finally {
clearTimeout(didTimeoutHandle);
}
return results;
}
private _deliverEventAsyncAndBlameBadListeners([listener, thisArg, extension]: Listener, stubEvent: vscode.TextDocumentWillSaveEvent): Promise<any> {
const errors = this._badListeners.get(listener);
if (typeof errors === 'number' && errors > this._thresholds.errors) {
// bad listener - ignore
return Promise.resolve(false);
}
return this._deliverEventAsync(extension, listener, thisArg, stubEvent).then(() => {
// don't send result across the wire
return true;
}, err => {
this._logService.error(`onWillSaveTextDocument-listener from extension '${extension.identifier.value}' threw ERROR`);
this._logService.error(err);
if (!(err instanceof Error) || (<Error>err).message !== 'concurrent_edits') {
const errors = this._badListeners.get(listener);
this._badListeners.set(listener, !errors ? 1 : errors + 1);
if (typeof errors === 'number' && errors > this._thresholds.errors) {
this._logService.info(`onWillSaveTextDocument-listener from extension '${extension.identifier.value}' will now be IGNORED because of timeouts and/or errors`);
}
}
return false;
});
}
private _deliverEventAsync(extension: IExtensionDescription, listener: Function, thisArg: any, stubEvent: vscode.TextDocumentWillSaveEvent): Promise<any> {
const promises: Promise<vscode.TextEdit[]>[] = [];
const t1 = Date.now();
const { document, reason } = stubEvent;
const { version } = document;
const event = Object.freeze(<vscode.TextDocumentWillSaveEvent>{
document,
reason,
waitUntil(p: Promise<any | vscode.TextEdit[]>) {
if (Object.isFrozen(promises)) {
throw illegalState('waitUntil can not be called async');
}
promises.push(Promise.resolve(p));
}
});
try {
// fire event
listener.apply(thisArg, [event]);
} catch (err) {
return Promise.reject(err);
}
// freeze promises after event call
Object.freeze(promises);
return new Promise<vscode.TextEdit[][]>((resolve, reject) => {
// join on all listener promises, reject after timeout
const handle = setTimeout(() => reject(new Error('timeout')), this._thresholds.timeout);
return Promise.all(promises).then(edits => {
this._logService.debug(`onWillSaveTextDocument-listener from extension '${extension.identifier.value}' finished after ${(Date.now() - t1)}ms`);
clearTimeout(handle);
resolve(edits);
}).catch(err => {
clearTimeout(handle);
reject(err);
});
}).then(values => {
const dto: IWorkspaceEditDto = { edits: [] };
for (const value of values) {
if (Array.isArray(value) && (<vscode.TextEdit[]>value).every(e => e instanceof TextEdit)) {
for (const { newText, newEol, range } of value) {
dto.edits.push({
_type: WorkspaceEditType.Text,
resource: document.uri,
edit: {
range: range && Range.from(range),
text: newText,
eol: newEol && EndOfLine.from(newEol)
}
});
}
}
}
// apply edits if any and if document
// didn't change somehow in the meantime
if (dto.edits.length === 0) {
return undefined;
}
if (version === document.version) {
return this._mainThreadBulkEdits.$tryApplyWorkspaceEdit(dto);
}
return Promise.reject(new Error('concurrent_edits'));
});
}
}

View File

@ -0,0 +1,165 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Emitter, Event } from 'vs/base/common/event';
import { DisposableStore } from 'vs/base/common/lifecycle';
import { URI, UriComponents } from 'vs/base/common/uri';
import { IModelChangedEvent } from 'vs/editor/common/model/mirrorTextModel';
import { ExtHostDocumentsShape, IMainContext, MainContext, MainThreadDocumentsShape } from 'vs/workbench/api/common/extHost.protocol';
import { ExtHostDocumentData, setWordDefinitionFor } from 'vs/workbench/api/common/extHostDocumentData';
import { ExtHostDocumentsAndEditors } from 'vs/workbench/api/common/extHostDocumentsAndEditors';
import * as TypeConverters from 'vs/workbench/api/common/extHostTypeConverters';
import type * as vscode from 'vscode';
import { assertIsDefined } from 'vs/base/common/types';
import { deepFreeze } from 'vs/base/common/objects';
export class ExtHostDocuments implements ExtHostDocumentsShape {
private readonly _onDidAddDocument = new Emitter<vscode.TextDocument>();
private readonly _onDidRemoveDocument = new Emitter<vscode.TextDocument>();
private readonly _onDidChangeDocument = new Emitter<vscode.TextDocumentChangeEvent>();
private readonly _onDidSaveDocument = new Emitter<vscode.TextDocument>();
readonly onDidAddDocument: Event<vscode.TextDocument> = this._onDidAddDocument.event;
readonly onDidRemoveDocument: Event<vscode.TextDocument> = this._onDidRemoveDocument.event;
readonly onDidChangeDocument: Event<vscode.TextDocumentChangeEvent> = this._onDidChangeDocument.event;
readonly onDidSaveDocument: Event<vscode.TextDocument> = this._onDidSaveDocument.event;
private readonly _toDispose = new DisposableStore();
private _proxy: MainThreadDocumentsShape;
private _documentsAndEditors: ExtHostDocumentsAndEditors;
private _documentLoader = new Map<string, Promise<ExtHostDocumentData>>();
constructor(mainContext: IMainContext, documentsAndEditors: ExtHostDocumentsAndEditors) {
this._proxy = mainContext.getProxy(MainContext.MainThreadDocuments);
this._documentsAndEditors = documentsAndEditors;
this._documentsAndEditors.onDidRemoveDocuments(documents => {
for (const data of documents) {
this._onDidRemoveDocument.fire(data.document);
}
}, undefined, this._toDispose);
this._documentsAndEditors.onDidAddDocuments(documents => {
for (const data of documents) {
this._onDidAddDocument.fire(data.document);
}
}, undefined, this._toDispose);
}
public dispose(): void {
this._toDispose.dispose();
}
public getAllDocumentData(): ExtHostDocumentData[] {
return [...this._documentsAndEditors.allDocuments()];
}
public getDocumentData(resource: vscode.Uri): ExtHostDocumentData | undefined {
if (!resource) {
return undefined;
}
const data = this._documentsAndEditors.getDocument(resource);
if (data) {
return data;
}
return undefined;
}
public getDocument(resource: vscode.Uri): vscode.TextDocument {
const data = this.getDocumentData(resource);
if (!data?.document) {
throw new Error(`Unable to retrieve document from URI '${resource}'`);
}
return data.document;
}
public ensureDocumentData(uri: URI): Promise<ExtHostDocumentData> {
const cached = this._documentsAndEditors.getDocument(uri);
if (cached) {
return Promise.resolve(cached);
}
let promise = this._documentLoader.get(uri.toString());
if (!promise) {
promise = this._proxy.$tryOpenDocument(uri).then(uriData => {
this._documentLoader.delete(uri.toString());
const canonicalUri = URI.revive(uriData);
return assertIsDefined(this._documentsAndEditors.getDocument(canonicalUri));
}, err => {
this._documentLoader.delete(uri.toString());
return Promise.reject(err);
});
this._documentLoader.set(uri.toString(), promise);
}
return promise;
}
public createDocumentData(options?: { language?: string; content?: string }): Promise<URI> {
return this._proxy.$tryCreateDocument(options).then(data => URI.revive(data));
}
public $acceptModelModeChanged(uriComponents: UriComponents, oldModeId: string, newModeId: string): void {
const uri = URI.revive(uriComponents);
const data = this._documentsAndEditors.getDocument(uri);
if (!data) {
throw new Error('unknown document');
}
// Treat a mode change as a remove + add
this._onDidRemoveDocument.fire(data.document);
data._acceptLanguageId(newModeId);
this._onDidAddDocument.fire(data.document);
}
public $acceptModelSaved(uriComponents: UriComponents): void {
const uri = URI.revive(uriComponents);
const data = this._documentsAndEditors.getDocument(uri);
if (!data) {
throw new Error('unknown document');
}
this.$acceptDirtyStateChanged(uriComponents, false);
this._onDidSaveDocument.fire(data.document);
}
public $acceptDirtyStateChanged(uriComponents: UriComponents, isDirty: boolean): void {
const uri = URI.revive(uriComponents);
const data = this._documentsAndEditors.getDocument(uri);
if (!data) {
throw new Error('unknown document');
}
data._acceptIsDirty(isDirty);
this._onDidChangeDocument.fire({
document: data.document,
contentChanges: []
});
}
public $acceptModelChanged(uriComponents: UriComponents, events: IModelChangedEvent, isDirty: boolean): void {
const uri = URI.revive(uriComponents);
const data = this._documentsAndEditors.getDocument(uri);
if (!data) {
throw new Error('unknown document');
}
data._acceptIsDirty(isDirty);
data.onEvents(events);
this._onDidChangeDocument.fire(deepFreeze({
document: data.document,
contentChanges: events.changes.map((change) => {
return {
range: TypeConverters.Range.to(change.range),
rangeOffset: change.rangeOffset,
rangeLength: change.rangeLength,
text: change.text
};
})
}));
}
public setWordDefinitionFor(modeId: string, wordDefinition: RegExp | undefined): void {
setWordDefinitionFor(modeId, wordDefinition);
}
}

View File

@ -0,0 +1,198 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'vs/base/common/assert';
import * as vscode from 'vscode';
import { Emitter, Event } from 'vs/base/common/event';
import { dispose } from 'vs/base/common/lifecycle';
import { URI } from 'vs/base/common/uri';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { ExtHostDocumentsAndEditorsShape, IDocumentsAndEditorsDelta, IModelAddedData, MainContext } from 'vs/workbench/api/common/extHost.protocol';
import { ExtHostDocumentData } from 'vs/workbench/api/common/extHostDocumentData';
import { IExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService';
import { ExtHostTextEditor } from 'vs/workbench/api/common/extHostTextEditor';
import * as typeConverters from 'vs/workbench/api/common/extHostTypeConverters';
import { ILogService } from 'vs/platform/log/common/log';
import { ResourceMap } from 'vs/base/common/map';
import { Schemas } from 'vs/base/common/network';
import { Iterable } from 'vs/base/common/iterator';
class Reference<T> {
private _count = 0;
constructor(readonly value: T) { }
ref() {
this._count++;
}
unref() {
return --this._count === 0;
}
}
export interface IExtHostModelAddedData extends IModelAddedData {
notebook?: vscode.NotebookDocument;
}
export interface IExtHostDocumentsAndEditorsDelta extends IDocumentsAndEditorsDelta {
addedDocuments?: IExtHostModelAddedData[];
}
export class ExtHostDocumentsAndEditors implements ExtHostDocumentsAndEditorsShape {
readonly _serviceBrand: undefined;
private _activeEditorId: string | null = null;
private readonly _editors = new Map<string, ExtHostTextEditor>();
private readonly _documents = new ResourceMap<Reference<ExtHostDocumentData>>();
private readonly _onDidAddDocuments = new Emitter<ExtHostDocumentData[]>();
private readonly _onDidRemoveDocuments = new Emitter<ExtHostDocumentData[]>();
private readonly _onDidChangeVisibleTextEditors = new Emitter<ExtHostTextEditor[]>();
private readonly _onDidChangeActiveTextEditor = new Emitter<ExtHostTextEditor | undefined>();
readonly onDidAddDocuments: Event<ExtHostDocumentData[]> = this._onDidAddDocuments.event;
readonly onDidRemoveDocuments: Event<ExtHostDocumentData[]> = this._onDidRemoveDocuments.event;
readonly onDidChangeVisibleTextEditors: Event<ExtHostTextEditor[]> = this._onDidChangeVisibleTextEditors.event;
readonly onDidChangeActiveTextEditor: Event<ExtHostTextEditor | undefined> = this._onDidChangeActiveTextEditor.event;
constructor(
@IExtHostRpcService private readonly _extHostRpc: IExtHostRpcService,
@ILogService private readonly _logService: ILogService
) { }
$acceptDocumentsAndEditorsDelta(delta: IDocumentsAndEditorsDelta): void {
this.acceptDocumentsAndEditorsDelta(delta);
}
acceptDocumentsAndEditorsDelta(delta: IExtHostDocumentsAndEditorsDelta): void {
const removedDocuments: ExtHostDocumentData[] = [];
const addedDocuments: ExtHostDocumentData[] = [];
const removedEditors: ExtHostTextEditor[] = [];
if (delta.removedDocuments) {
for (const uriComponent of delta.removedDocuments) {
const uri = URI.revive(uriComponent);
const data = this._documents.get(uri);
if (data?.unref()) {
this._documents.delete(uri);
removedDocuments.push(data.value);
}
}
}
if (delta.addedDocuments) {
for (const data of delta.addedDocuments) {
const resource = URI.revive(data.uri);
let ref = this._documents.get(resource);
// double check -> only notebook cell documents should be
// referenced/opened more than once...
if (ref) {
if (resource.scheme !== Schemas.vscodeNotebookCell) {
throw new Error(`document '${resource} already exists!'`);
}
}
if (!ref) {
ref = new Reference(new ExtHostDocumentData(
this._extHostRpc.getProxy(MainContext.MainThreadDocuments),
resource,
data.lines,
data.EOL,
data.versionId,
data.modeId,
data.isDirty,
data.notebook
));
this._documents.set(resource, ref);
addedDocuments.push(ref.value);
}
ref.ref();
}
}
if (delta.removedEditors) {
for (const id of delta.removedEditors) {
const editor = this._editors.get(id);
this._editors.delete(id);
if (editor) {
removedEditors.push(editor);
}
}
}
if (delta.addedEditors) {
for (const data of delta.addedEditors) {
const resource = URI.revive(data.documentUri);
assert.ok(this._documents.has(resource), `document '${resource}' does not exist`);
assert.ok(!this._editors.has(data.id), `editor '${data.id}' already exists!`);
const documentData = this._documents.get(resource)!.value;
const editor = new ExtHostTextEditor(
data.id,
this._extHostRpc.getProxy(MainContext.MainThreadTextEditors),
this._logService,
documentData,
data.selections.map(typeConverters.Selection.to),
data.options,
data.visibleRanges.map(range => typeConverters.Range.to(range)),
typeof data.editorPosition === 'number' ? typeConverters.ViewColumn.to(data.editorPosition) : undefined
);
this._editors.set(data.id, editor);
}
}
if (delta.newActiveEditor !== undefined) {
assert.ok(delta.newActiveEditor === null || this._editors.has(delta.newActiveEditor), `active editor '${delta.newActiveEditor}' does not exist`);
this._activeEditorId = delta.newActiveEditor;
}
dispose(removedDocuments);
dispose(removedEditors);
// now that the internal state is complete, fire events
if (delta.removedDocuments) {
this._onDidRemoveDocuments.fire(removedDocuments);
}
if (delta.addedDocuments) {
this._onDidAddDocuments.fire(addedDocuments);
}
if (delta.removedEditors || delta.addedEditors) {
this._onDidChangeVisibleTextEditors.fire(this.allEditors());
}
if (delta.newActiveEditor !== undefined) {
this._onDidChangeActiveTextEditor.fire(this.activeEditor());
}
}
getDocument(uri: URI): ExtHostDocumentData | undefined {
return this._documents.get(uri)?.value;
}
allDocuments(): Iterable<ExtHostDocumentData> {
return Iterable.map(this._documents.values(), ref => ref.value);
}
getEditor(id: string): ExtHostTextEditor | undefined {
return this._editors.get(id);
}
activeEditor(): ExtHostTextEditor | undefined {
if (!this._activeEditorId) {
return undefined;
} else {
return this._editors.get(this._activeEditorId);
}
}
allEditors(): ExtHostTextEditor[] {
return [...this._editors.values()];
}
}
export interface IExtHostDocumentsAndEditors extends ExtHostDocumentsAndEditors { }
export const IExtHostDocumentsAndEditors = createDecorator<IExtHostDocumentsAndEditors>('IExtHostDocumentsAndEditors');

View File

@ -0,0 +1,388 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import type * as vscode from 'vscode';
import { IDisposable } from 'vs/base/common/lifecycle';
import { ExtensionDescriptionRegistry } from 'vs/workbench/services/extensions/common/extensionDescriptionRegistry';
import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions';
import { ExtensionActivationError, MissingDependencyError } from 'vs/workbench/services/extensions/common/extensions';
import { ILogService } from 'vs/platform/log/common/log';
const NO_OP_VOID_PROMISE = Promise.resolve<void>(undefined);
/**
* Represents the source code (module) of an extension.
*/
export interface IExtensionModule {
activate?(ctx: vscode.ExtensionContext): Promise<IExtensionAPI>;
deactivate?(): void;
}
/**
* Represents the API of an extension (return value of `activate`).
*/
export interface IExtensionAPI {
// _extensionAPIBrand: any;
}
export type ExtensionActivationTimesFragment = {
startup?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true };
codeLoadingTime?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true };
activateCallTime?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true };
activateResolvedTime?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true };
};
export class ExtensionActivationTimes {
public static readonly NONE = new ExtensionActivationTimes(false, -1, -1, -1);
public readonly startup: boolean;
public readonly codeLoadingTime: number;
public readonly activateCallTime: number;
public readonly activateResolvedTime: number;
constructor(startup: boolean, codeLoadingTime: number, activateCallTime: number, activateResolvedTime: number) {
this.startup = startup;
this.codeLoadingTime = codeLoadingTime;
this.activateCallTime = activateCallTime;
this.activateResolvedTime = activateResolvedTime;
}
}
export class ExtensionActivationTimesBuilder {
private readonly _startup: boolean;
private _codeLoadingStart: number;
private _codeLoadingStop: number;
private _activateCallStart: number;
private _activateCallStop: number;
private _activateResolveStart: number;
private _activateResolveStop: number;
constructor(startup: boolean) {
this._startup = startup;
this._codeLoadingStart = -1;
this._codeLoadingStop = -1;
this._activateCallStart = -1;
this._activateCallStop = -1;
this._activateResolveStart = -1;
this._activateResolveStop = -1;
}
private _delta(start: number, stop: number): number {
if (start === -1 || stop === -1) {
return -1;
}
return stop - start;
}
public build(): ExtensionActivationTimes {
return new ExtensionActivationTimes(
this._startup,
this._delta(this._codeLoadingStart, this._codeLoadingStop),
this._delta(this._activateCallStart, this._activateCallStop),
this._delta(this._activateResolveStart, this._activateResolveStop)
);
}
public codeLoadingStart(): void {
this._codeLoadingStart = Date.now();
}
public codeLoadingStop(): void {
this._codeLoadingStop = Date.now();
}
public activateCallStart(): void {
this._activateCallStart = Date.now();
}
public activateCallStop(): void {
this._activateCallStop = Date.now();
}
public activateResolveStart(): void {
this._activateResolveStart = Date.now();
}
public activateResolveStop(): void {
this._activateResolveStop = Date.now();
}
}
export class ActivatedExtension {
public readonly activationFailed: boolean;
public readonly activationFailedError: Error | null;
public readonly activationTimes: ExtensionActivationTimes;
public readonly module: IExtensionModule;
public readonly exports: IExtensionAPI | undefined;
public readonly subscriptions: IDisposable[];
constructor(
activationFailed: boolean,
activationFailedError: Error | null,
activationTimes: ExtensionActivationTimes,
module: IExtensionModule,
exports: IExtensionAPI | undefined,
subscriptions: IDisposable[]
) {
this.activationFailed = activationFailed;
this.activationFailedError = activationFailedError;
this.activationTimes = activationTimes;
this.module = module;
this.exports = exports;
this.subscriptions = subscriptions;
}
}
export class EmptyExtension extends ActivatedExtension {
constructor(activationTimes: ExtensionActivationTimes) {
super(false, null, activationTimes, { activate: undefined, deactivate: undefined }, undefined, []);
}
}
export class HostExtension extends ActivatedExtension {
constructor() {
super(false, null, ExtensionActivationTimes.NONE, { activate: undefined, deactivate: undefined }, undefined, []);
}
}
export class FailedExtension extends ActivatedExtension {
constructor(activationError: Error) {
super(true, activationError, ExtensionActivationTimes.NONE, { activate: undefined, deactivate: undefined }, undefined, []);
}
}
export interface IExtensionsActivatorHost {
onExtensionActivationError(extensionId: ExtensionIdentifier, error: ExtensionActivationError): void;
actualActivateExtension(extensionId: ExtensionIdentifier, reason: ExtensionActivationReason): Promise<ActivatedExtension>;
}
export interface ExtensionActivationReason {
readonly startup: boolean;
readonly extensionId: ExtensionIdentifier;
readonly activationEvent: string;
}
type ActivationIdAndReason = { id: ExtensionIdentifier, reason: ExtensionActivationReason };
export class ExtensionsActivator {
private readonly _registry: ExtensionDescriptionRegistry;
private readonly _resolvedExtensionsSet: Set<string>;
private readonly _hostExtensionsMap: Map<string, ExtensionIdentifier>;
private readonly _host: IExtensionsActivatorHost;
private readonly _activatingExtensions: Map<string, Promise<void>>;
private readonly _activatedExtensions: Map<string, ActivatedExtension>;
/**
* A map of already activated events to speed things up if the same activation event is triggered multiple times.
*/
private readonly _alreadyActivatedEvents: { [activationEvent: string]: boolean; };
constructor(
registry: ExtensionDescriptionRegistry,
resolvedExtensions: ExtensionIdentifier[],
hostExtensions: ExtensionIdentifier[],
host: IExtensionsActivatorHost,
@ILogService private readonly _logService: ILogService
) {
this._registry = registry;
this._resolvedExtensionsSet = new Set<string>();
resolvedExtensions.forEach((extensionId) => this._resolvedExtensionsSet.add(ExtensionIdentifier.toKey(extensionId)));
this._hostExtensionsMap = new Map<string, ExtensionIdentifier>();
hostExtensions.forEach((extensionId) => this._hostExtensionsMap.set(ExtensionIdentifier.toKey(extensionId), extensionId));
this._host = host;
this._activatingExtensions = new Map<string, Promise<void>>();
this._activatedExtensions = new Map<string, ActivatedExtension>();
this._alreadyActivatedEvents = Object.create(null);
}
public isActivated(extensionId: ExtensionIdentifier): boolean {
const extensionKey = ExtensionIdentifier.toKey(extensionId);
return this._activatedExtensions.has(extensionKey);
}
public getActivatedExtension(extensionId: ExtensionIdentifier): ActivatedExtension {
const extensionKey = ExtensionIdentifier.toKey(extensionId);
const activatedExtension = this._activatedExtensions.get(extensionKey);
if (!activatedExtension) {
throw new Error('Extension `' + extensionId.value + '` is not known or not activated');
}
return activatedExtension;
}
public activateByEvent(activationEvent: string, startup: boolean): Promise<void> {
if (this._alreadyActivatedEvents[activationEvent]) {
return NO_OP_VOID_PROMISE;
}
const activateExtensions = this._registry.getExtensionDescriptionsForActivationEvent(activationEvent);
return this._activateExtensions(activateExtensions.map(e => ({
id: e.identifier,
reason: { startup, extensionId: e.identifier, activationEvent }
}))).then(() => {
this._alreadyActivatedEvents[activationEvent] = true;
});
}
public activateById(extensionId: ExtensionIdentifier, reason: ExtensionActivationReason): Promise<void> {
const desc = this._registry.getExtensionDescription(extensionId);
if (!desc) {
throw new Error('Extension `' + extensionId + '` is not known');
}
return this._activateExtensions([{
id: desc.identifier,
reason
}]);
}
/**
* Handle semantics related to dependencies for `currentExtension`.
* semantics: `redExtensions` must wait for `greenExtensions`.
*/
private _handleActivateRequest(currentActivation: ActivationIdAndReason, greenExtensions: { [id: string]: ActivationIdAndReason; }, redExtensions: ActivationIdAndReason[]): void {
if (this._hostExtensionsMap.has(ExtensionIdentifier.toKey(currentActivation.id))) {
greenExtensions[ExtensionIdentifier.toKey(currentActivation.id)] = currentActivation;
return;
}
const currentExtension = this._registry.getExtensionDescription(currentActivation.id);
if (!currentExtension) {
// Error condition 0: unknown extension
this._host.onExtensionActivationError(currentActivation.id, new MissingDependencyError(currentActivation.id.value));
const error = new Error(`Unknown dependency '${currentActivation.id.value}'`);
this._activatedExtensions.set(ExtensionIdentifier.toKey(currentActivation.id), new FailedExtension(error));
return;
}
const depIds = (typeof currentExtension.extensionDependencies === 'undefined' ? [] : currentExtension.extensionDependencies);
let currentExtensionGetsGreenLight = true;
for (let j = 0, lenJ = depIds.length; j < lenJ; j++) {
const depId = depIds[j];
if (this._resolvedExtensionsSet.has(ExtensionIdentifier.toKey(depId))) {
// This dependency is already resolved
continue;
}
const dep = this._activatedExtensions.get(ExtensionIdentifier.toKey(depId));
if (dep && !dep.activationFailed) {
// the dependency is already activated OK
continue;
}
if (dep && dep.activationFailed) {
// Error condition 2: a dependency has already failed activation
this._host.onExtensionActivationError(currentExtension.identifier, nls.localize('failedDep1', "Cannot activate extension '{0}' because it depends on extension '{1}', which failed to activate.", currentExtension.displayName || currentExtension.identifier.value, depId));
const error = new Error(`Dependency ${depId} failed to activate`);
(<any>error).detail = dep.activationFailedError;
this._activatedExtensions.set(ExtensionIdentifier.toKey(currentExtension.identifier), new FailedExtension(error));
return;
}
if (this._hostExtensionsMap.has(ExtensionIdentifier.toKey(depId))) {
// must first wait for the dependency to activate
currentExtensionGetsGreenLight = false;
greenExtensions[ExtensionIdentifier.toKey(depId)] = {
id: this._hostExtensionsMap.get(ExtensionIdentifier.toKey(depId))!,
reason: currentActivation.reason
};
continue;
}
const depDesc = this._registry.getExtensionDescription(depId);
if (depDesc) {
// must first wait for the dependency to activate
currentExtensionGetsGreenLight = false;
greenExtensions[ExtensionIdentifier.toKey(depId)] = {
id: depDesc.identifier,
reason: currentActivation.reason
};
continue;
}
// Error condition 1: unknown dependency
this._host.onExtensionActivationError(currentExtension.identifier, new MissingDependencyError(depId));
const error = new Error(`Unknown dependency '${depId}'`);
this._activatedExtensions.set(ExtensionIdentifier.toKey(currentExtension.identifier), new FailedExtension(error));
return;
}
if (currentExtensionGetsGreenLight) {
greenExtensions[ExtensionIdentifier.toKey(currentExtension.identifier)] = currentActivation;
} else {
redExtensions.push(currentActivation);
}
}
private _activateExtensions(extensions: ActivationIdAndReason[]): Promise<void> {
if (extensions.length === 0) {
return Promise.resolve(undefined);
}
extensions = extensions.filter((p) => !this._activatedExtensions.has(ExtensionIdentifier.toKey(p.id)));
if (extensions.length === 0) {
return Promise.resolve(undefined);
}
const greenMap: { [id: string]: ActivationIdAndReason; } = Object.create(null),
red: ActivationIdAndReason[] = [];
for (let i = 0, len = extensions.length; i < len; i++) {
this._handleActivateRequest(extensions[i], greenMap, red);
}
// Make sure no red is also green
for (let i = 0, len = red.length; i < len; i++) {
const redExtensionKey = ExtensionIdentifier.toKey(red[i].id);
if (greenMap[redExtensionKey]) {
delete greenMap[redExtensionKey];
}
}
const green = Object.keys(greenMap).map(id => greenMap[id]);
if (red.length === 0) {
// Finally reached only leafs!
return Promise.all(green.map((p) => this._activateExtension(p.id, p.reason))).then(_ => undefined);
}
return this._activateExtensions(green).then(_ => {
return this._activateExtensions(red);
});
}
private _activateExtension(extensionId: ExtensionIdentifier, reason: ExtensionActivationReason): Promise<void> {
const extensionKey = ExtensionIdentifier.toKey(extensionId);
if (this._activatedExtensions.has(extensionKey)) {
return Promise.resolve(undefined);
}
const currentlyActivatingExtension = this._activatingExtensions.get(extensionKey);
if (currentlyActivatingExtension) {
return currentlyActivatingExtension;
}
const newlyActivatingExtension = this._host.actualActivateExtension(extensionId, reason).then(undefined, (err) => {
this._host.onExtensionActivationError(extensionId, nls.localize('activationError', "Activating extension '{0}' failed: {1}.", extensionId.value, err.message));
this._logService.error(`Activating extension ${extensionId.value} failed due to an error:`);
this._logService.error(err);
// Treat the extension as being empty
return new FailedExtension(err);
}).then((x: ActivatedExtension) => {
this._activatedExtensions.set(extensionKey, x);
this._activatingExtensions.delete(extensionKey);
});
this._activatingExtensions.set(extensionKey, newlyActivatingExtension);
return newlyActivatingExtension;
}
}

View File

@ -0,0 +1,804 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import * as path from 'vs/base/common/path';
import { originalFSPath, joinPath } from 'vs/base/common/resources';
import { Barrier, timeout } from 'vs/base/common/async';
import { dispose, toDisposable, DisposableStore, Disposable } from 'vs/base/common/lifecycle';
import { TernarySearchTree } from 'vs/base/common/map';
import { URI } from 'vs/base/common/uri';
import { ILogService } from 'vs/platform/log/common/log';
import { ExtHostExtensionServiceShape, IInitData, MainContext, MainThreadExtensionServiceShape, MainThreadTelemetryShape, MainThreadWorkspaceShape, IResolveAuthorityResult } from 'vs/workbench/api/common/extHost.protocol';
import { ExtHostConfiguration, IExtHostConfiguration } from 'vs/workbench/api/common/extHostConfiguration';
import { ActivatedExtension, EmptyExtension, ExtensionActivationReason, ExtensionActivationTimes, ExtensionActivationTimesBuilder, ExtensionsActivator, IExtensionAPI, IExtensionModule, HostExtension, ExtensionActivationTimesFragment } from 'vs/workbench/api/common/extHostExtensionActivator';
import { ExtHostStorage, IExtHostStorage } from 'vs/workbench/api/common/extHostStorage';
import { ExtHostWorkspace, IExtHostWorkspace } from 'vs/workbench/api/common/extHostWorkspace';
import { ExtensionActivationError, checkProposedApiEnabled, ActivationKind } from 'vs/workbench/services/extensions/common/extensions';
import { ExtensionDescriptionRegistry } from 'vs/workbench/services/extensions/common/extensionDescriptionRegistry';
import * as errors from 'vs/base/common/errors';
import type * as vscode from 'vscode';
import { ExtensionIdentifier, IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { Schemas } from 'vs/base/common/network';
import { VSBuffer } from 'vs/base/common/buffer';
import { ExtensionGlobalMemento, ExtensionMemento } from 'vs/workbench/api/common/extHostMemento';
import { RemoteAuthorityResolverError, ExtensionMode, ExtensionRuntime } from 'vs/workbench/api/common/extHostTypes';
import { ResolvedAuthority, ResolvedOptions, RemoteAuthorityResolverErrorCode, IRemoteConnectionData } from 'vs/platform/remote/common/remoteAuthorityResolver';
import { IInstantiationService, createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IExtHostInitDataService } from 'vs/workbench/api/common/extHostInitDataService';
import { IExtensionStoragePaths } from 'vs/workbench/api/common/extHostStoragePaths';
import { IExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { IExtHostTunnelService } from 'vs/workbench/api/common/extHostTunnelService';
import { IExtHostTerminalService } from 'vs/workbench/api/common/extHostTerminalService';
import { Emitter, Event } from 'vs/base/common/event';
import { IExtensionActivationHost, checkActivateWorkspaceContainsExtension } from 'vs/workbench/api/common/shared/workspaceContains';
interface ITestRunner {
/** Old test runner API, as exported from `vscode/lib/testrunner` */
run(testsRoot: string, clb: (error: Error, failures?: number) => void): void;
}
interface INewTestRunner {
/** New test runner API, as explained in the extension test doc */
run(): Promise<void>;
}
export const IHostUtils = createDecorator<IHostUtils>('IHostUtils');
export interface IHostUtils {
readonly _serviceBrand: undefined;
exit(code?: number): void;
exists(path: string): Promise<boolean>;
realpath(path: string): Promise<string>;
}
type TelemetryActivationEventFragment = {
id: { classification: 'PublicNonPersonalData', purpose: 'FeatureInsight' };
name: { classification: 'PublicNonPersonalData', purpose: 'FeatureInsight' };
extensionVersion: { classification: 'PublicNonPersonalData', purpose: 'FeatureInsight' };
publisherDisplayName: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
activationEvents: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
isBuiltin: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
reason: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
reasonId: { classification: 'PublicNonPersonalData', purpose: 'FeatureInsight' };
};
export abstract class AbstractExtHostExtensionService extends Disposable implements ExtHostExtensionServiceShape {
readonly _serviceBrand: undefined;
abstract readonly extensionRuntime: ExtensionRuntime;
private readonly _onDidChangeRemoteConnectionData = this._register(new Emitter<void>());
public readonly onDidChangeRemoteConnectionData = this._onDidChangeRemoteConnectionData.event;
protected readonly _hostUtils: IHostUtils;
protected readonly _initData: IInitData;
protected readonly _extHostContext: IExtHostRpcService;
protected readonly _instaService: IInstantiationService;
protected readonly _extHostWorkspace: ExtHostWorkspace;
protected readonly _extHostConfiguration: ExtHostConfiguration;
protected readonly _logService: ILogService;
protected readonly _extHostTunnelService: IExtHostTunnelService;
protected readonly _extHostTerminalService: IExtHostTerminalService;
protected readonly _mainThreadWorkspaceProxy: MainThreadWorkspaceShape;
protected readonly _mainThreadTelemetryProxy: MainThreadTelemetryShape;
protected readonly _mainThreadExtensionsProxy: MainThreadExtensionServiceShape;
private readonly _almostReadyToRunExtensions: Barrier;
private readonly _readyToStartExtensionHost: Barrier;
private readonly _readyToRunExtensions: Barrier;
protected readonly _registry: ExtensionDescriptionRegistry;
private readonly _storage: ExtHostStorage;
private readonly _storagePath: IExtensionStoragePaths;
private readonly _activator: ExtensionsActivator;
private _extensionPathIndex: Promise<TernarySearchTree<string, IExtensionDescription>> | null;
private readonly _resolvers: { [authorityPrefix: string]: vscode.RemoteAuthorityResolver; };
private _started: boolean;
private _remoteConnectionData: IRemoteConnectionData | null;
private readonly _disposables: DisposableStore;
constructor(
@IInstantiationService instaService: IInstantiationService,
@IHostUtils hostUtils: IHostUtils,
@IExtHostRpcService extHostContext: IExtHostRpcService,
@IExtHostWorkspace extHostWorkspace: IExtHostWorkspace,
@IExtHostConfiguration extHostConfiguration: IExtHostConfiguration,
@ILogService logService: ILogService,
@IExtHostInitDataService initData: IExtHostInitDataService,
@IExtensionStoragePaths storagePath: IExtensionStoragePaths,
@IExtHostTunnelService extHostTunnelService: IExtHostTunnelService,
@IExtHostTerminalService extHostTerminalService: IExtHostTerminalService
) {
super();
this._hostUtils = hostUtils;
this._extHostContext = extHostContext;
this._initData = initData;
this._extHostWorkspace = extHostWorkspace;
this._extHostConfiguration = extHostConfiguration;
this._logService = logService;
this._extHostTunnelService = extHostTunnelService;
this._extHostTerminalService = extHostTerminalService;
this._disposables = new DisposableStore();
this._mainThreadWorkspaceProxy = this._extHostContext.getProxy(MainContext.MainThreadWorkspace);
this._mainThreadTelemetryProxy = this._extHostContext.getProxy(MainContext.MainThreadTelemetry);
this._mainThreadExtensionsProxy = this._extHostContext.getProxy(MainContext.MainThreadExtensionService);
this._almostReadyToRunExtensions = new Barrier();
this._readyToStartExtensionHost = new Barrier();
this._readyToRunExtensions = new Barrier();
this._registry = new ExtensionDescriptionRegistry(this._initData.extensions);
this._storage = new ExtHostStorage(this._extHostContext);
this._storagePath = storagePath;
this._instaService = instaService.createChild(new ServiceCollection(
[IExtHostStorage, this._storage]
));
const hostExtensions = new Set<string>();
this._initData.hostExtensions.forEach((extensionId) => hostExtensions.add(ExtensionIdentifier.toKey(extensionId)));
this._activator = new ExtensionsActivator(
this._registry,
this._initData.resolvedExtensions,
this._initData.hostExtensions,
{
onExtensionActivationError: (extensionId: ExtensionIdentifier, error: ExtensionActivationError): void => {
this._mainThreadExtensionsProxy.$onExtensionActivationError(extensionId, error);
},
actualActivateExtension: async (extensionId: ExtensionIdentifier, reason: ExtensionActivationReason): Promise<ActivatedExtension> => {
if (hostExtensions.has(ExtensionIdentifier.toKey(extensionId))) {
await this._mainThreadExtensionsProxy.$activateExtension(extensionId, reason);
return new HostExtension();
}
const extensionDescription = this._registry.getExtensionDescription(extensionId)!;
return this._activateExtension(extensionDescription, reason);
}
},
this._logService
);
this._extensionPathIndex = null;
this._resolvers = Object.create(null);
this._started = false;
this._remoteConnectionData = this._initData.remote.connectionData;
}
public getRemoteConnectionData(): IRemoteConnectionData | null {
return this._remoteConnectionData;
}
public async initialize(): Promise<void> {
try {
await this._beforeAlmostReadyToRunExtensions();
this._almostReadyToRunExtensions.open();
await this._extHostWorkspace.waitForInitializeCall();
this._readyToStartExtensionHost.open();
if (this._initData.autoStart) {
this._startExtensionHost();
}
} catch (err) {
errors.onUnexpectedError(err);
}
}
public async deactivateAll(): Promise<void> {
let allPromises: Promise<void>[] = [];
try {
const allExtensions = this._registry.getAllExtensionDescriptions();
const allExtensionsIds = allExtensions.map(ext => ext.identifier);
const activatedExtensions = allExtensionsIds.filter(id => this.isActivated(id));
allPromises = activatedExtensions.map((extensionId) => {
return this._deactivate(extensionId);
});
} catch (err) {
// TODO: write to log once we have one
}
await Promise.all(allPromises);
}
public isActivated(extensionId: ExtensionIdentifier): boolean {
if (this._readyToRunExtensions.isOpen()) {
return this._activator.isActivated(extensionId);
}
return false;
}
private _activateByEvent(activationEvent: string, startup: boolean): Promise<void> {
return this._activator.activateByEvent(activationEvent, startup);
}
private _activateById(extensionId: ExtensionIdentifier, reason: ExtensionActivationReason): Promise<void> {
return this._activator.activateById(extensionId, reason);
}
public activateByIdWithErrors(extensionId: ExtensionIdentifier, reason: ExtensionActivationReason): Promise<void> {
return this._activateById(extensionId, reason).then(() => {
const extension = this._activator.getActivatedExtension(extensionId);
if (extension.activationFailed) {
// activation failed => bubble up the error as the promise result
return Promise.reject(extension.activationFailedError);
}
return undefined;
});
}
public getExtensionRegistry(): Promise<ExtensionDescriptionRegistry> {
return this._readyToRunExtensions.wait().then(_ => this._registry);
}
public getExtensionExports(extensionId: ExtensionIdentifier): IExtensionAPI | null | undefined {
if (this._readyToRunExtensions.isOpen()) {
return this._activator.getActivatedExtension(extensionId).exports;
} else {
return null;
}
}
// create trie to enable fast 'filename -> extension id' look up
public getExtensionPathIndex(): Promise<TernarySearchTree<string, IExtensionDescription>> {
if (!this._extensionPathIndex) {
const tree = TernarySearchTree.forPaths<IExtensionDescription>();
const extensions = this._registry.getAllExtensionDescriptions().map(ext => {
if (!this._getEntryPoint(ext)) {
return undefined;
}
return this._hostUtils.realpath(ext.extensionLocation.fsPath).then(value => tree.set(URI.file(value).fsPath, ext));
});
this._extensionPathIndex = Promise.all(extensions).then(() => tree);
}
return this._extensionPathIndex;
}
private _deactivate(extensionId: ExtensionIdentifier): Promise<void> {
let result = Promise.resolve(undefined);
if (!this._readyToRunExtensions.isOpen()) {
return result;
}
if (!this._activator.isActivated(extensionId)) {
return result;
}
const extension = this._activator.getActivatedExtension(extensionId);
if (!extension) {
return result;
}
// call deactivate if available
try {
if (typeof extension.module.deactivate === 'function') {
result = Promise.resolve(extension.module.deactivate()).then(undefined, (err) => {
// TODO: Do something with err if this is not the shutdown case
return Promise.resolve(undefined);
});
}
} catch (err) {
// TODO: Do something with err if this is not the shutdown case
}
// clean up subscriptions
try {
dispose(extension.subscriptions);
} catch (err) {
// TODO: Do something with err if this is not the shutdown case
}
return result;
}
// --- impl
private async _activateExtension(extensionDescription: IExtensionDescription, reason: ExtensionActivationReason): Promise<ActivatedExtension> {
if (!this._initData.remote.isRemote) {
// local extension host process
await this._mainThreadExtensionsProxy.$onWillActivateExtension(extensionDescription.identifier);
} else {
// remote extension host process
// do not wait for renderer confirmation
this._mainThreadExtensionsProxy.$onWillActivateExtension(extensionDescription.identifier);
}
return this._doActivateExtension(extensionDescription, reason).then((activatedExtension) => {
const activationTimes = activatedExtension.activationTimes;
this._mainThreadExtensionsProxy.$onDidActivateExtension(extensionDescription.identifier, activationTimes.codeLoadingTime, activationTimes.activateCallTime, activationTimes.activateResolvedTime, reason);
this._logExtensionActivationTimes(extensionDescription, reason, 'success', activationTimes);
return activatedExtension;
}, (err) => {
this._logExtensionActivationTimes(extensionDescription, reason, 'failure');
throw err;
});
}
private _logExtensionActivationTimes(extensionDescription: IExtensionDescription, reason: ExtensionActivationReason, outcome: string, activationTimes?: ExtensionActivationTimes) {
const event = getTelemetryActivationEvent(extensionDescription, reason);
type ExtensionActivationTimesClassification = {
outcome: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
} & TelemetryActivationEventFragment & ExtensionActivationTimesFragment;
type ExtensionActivationTimesEvent = {
outcome: string
} & ActivationTimesEvent & TelemetryActivationEvent;
type ActivationTimesEvent = {
startup?: boolean;
codeLoadingTime?: number;
activateCallTime?: number;
activateResolvedTime?: number;
};
this._mainThreadTelemetryProxy.$publicLog2<ExtensionActivationTimesEvent, ExtensionActivationTimesClassification>('extensionActivationTimes', {
...event,
...(activationTimes || {}),
outcome
});
}
private _doActivateExtension(extensionDescription: IExtensionDescription, reason: ExtensionActivationReason): Promise<ActivatedExtension> {
const event = getTelemetryActivationEvent(extensionDescription, reason);
type ActivatePluginClassification = {} & TelemetryActivationEventFragment;
this._mainThreadTelemetryProxy.$publicLog2<TelemetryActivationEvent, ActivatePluginClassification>('activatePlugin', event);
const entryPoint = this._getEntryPoint(extensionDescription);
if (!entryPoint) {
// Treat the extension as being empty => NOT AN ERROR CASE
return Promise.resolve(new EmptyExtension(ExtensionActivationTimes.NONE));
}
this._logService.info(`ExtensionService#_doActivateExtension ${extensionDescription.identifier.value} ${JSON.stringify(reason)}`);
this._logService.flush();
const activationTimesBuilder = new ExtensionActivationTimesBuilder(reason.startup);
return Promise.all([
this._loadCommonJSModule<IExtensionModule>(joinPath(extensionDescription.extensionLocation, entryPoint), activationTimesBuilder),
this._loadExtensionContext(extensionDescription)
]).then(values => {
return AbstractExtHostExtensionService._callActivate(this._logService, extensionDescription.identifier, values[0], values[1], activationTimesBuilder);
});
}
private _loadExtensionContext(extensionDescription: IExtensionDescription): Promise<vscode.ExtensionContext> {
const globalState = new ExtensionGlobalMemento(extensionDescription, this._storage);
const workspaceState = new ExtensionMemento(extensionDescription.identifier.value, false, this._storage);
const extensionMode = extensionDescription.isUnderDevelopment
? (this._initData.environment.extensionTestsLocationURI ? ExtensionMode.Test : ExtensionMode.Development)
: ExtensionMode.Production;
this._logService.trace(`ExtensionService#loadExtensionContext ${extensionDescription.identifier.value}`);
return Promise.all([
globalState.whenReady,
workspaceState.whenReady,
this._storagePath.whenReady
]).then(() => {
const that = this;
return Object.freeze<vscode.ExtensionContext>({
globalState,
workspaceState,
subscriptions: [],
get extensionUri() { return extensionDescription.extensionLocation; },
get extensionPath() { return extensionDescription.extensionLocation.fsPath; },
asAbsolutePath(relativePath: string) { return path.join(extensionDescription.extensionLocation.fsPath, relativePath); },
get storagePath() { return that._storagePath.workspaceValue(extensionDescription)?.fsPath; },
get globalStoragePath() { return that._storagePath.globalValue(extensionDescription).fsPath; },
get logPath() { return path.join(that._initData.logsLocation.fsPath, extensionDescription.identifier.value); },
get logUri() { return URI.joinPath(that._initData.logsLocation, extensionDescription.identifier.value); },
get storageUri() { return that._storagePath.workspaceValue(extensionDescription); },
get globalStorageUri() { return that._storagePath.globalValue(extensionDescription); },
get extensionMode() { return extensionMode; },
get extensionRuntime() {
checkProposedApiEnabled(extensionDescription);
return that.extensionRuntime;
},
get environmentVariableCollection() { return that._extHostTerminalService.getEnvironmentVariableCollection(extensionDescription); }
});
});
}
private static _callActivate(logService: ILogService, extensionId: ExtensionIdentifier, extensionModule: IExtensionModule, context: vscode.ExtensionContext, activationTimesBuilder: ExtensionActivationTimesBuilder): Promise<ActivatedExtension> {
// Make sure the extension's surface is not undefined
extensionModule = extensionModule || {
activate: undefined,
deactivate: undefined
};
return this._callActivateOptional(logService, extensionId, extensionModule, context, activationTimesBuilder).then((extensionExports) => {
return new ActivatedExtension(false, null, activationTimesBuilder.build(), extensionModule, extensionExports, context.subscriptions);
});
}
private static _callActivateOptional(logService: ILogService, extensionId: ExtensionIdentifier, extensionModule: IExtensionModule, context: vscode.ExtensionContext, activationTimesBuilder: ExtensionActivationTimesBuilder): Promise<IExtensionAPI> {
if (typeof extensionModule.activate === 'function') {
try {
activationTimesBuilder.activateCallStart();
logService.trace(`ExtensionService#_callActivateOptional ${extensionId.value}`);
const scope = typeof global === 'object' ? global : self; // `global` is nodejs while `self` is for workers
const activateResult: Promise<IExtensionAPI> = extensionModule.activate.apply(scope, [context]);
activationTimesBuilder.activateCallStop();
activationTimesBuilder.activateResolveStart();
return Promise.resolve(activateResult).then((value) => {
activationTimesBuilder.activateResolveStop();
return value;
});
} catch (err) {
return Promise.reject(err);
}
} else {
// No activate found => the module is the extension's exports
return Promise.resolve<IExtensionAPI>(extensionModule);
}
}
// -- eager activation
private _activateOneStartupFinished(desc: IExtensionDescription, activationEvent: string): void {
this._activateById(desc.identifier, {
startup: false,
extensionId: desc.identifier,
activationEvent: activationEvent
}).then(undefined, (err) => {
this._logService.error(err);
});
}
private _activateAllStartupFinished(): void {
for (const desc of this._registry.getAllExtensionDescriptions()) {
if (desc.activationEvents) {
for (const activationEvent of desc.activationEvents) {
if (activationEvent === 'onStartupFinished') {
this._activateOneStartupFinished(desc, activationEvent);
}
}
}
}
}
// Handle "eager" activation extensions
private _handleEagerExtensions(): Promise<void> {
const starActivation = this._activateByEvent('*', true).then(undefined, (err) => {
this._logService.error(err);
});
this._disposables.add(this._extHostWorkspace.onDidChangeWorkspace((e) => this._handleWorkspaceContainsEagerExtensions(e.added)));
const folders = this._extHostWorkspace.workspace ? this._extHostWorkspace.workspace.folders : [];
const workspaceContainsActivation = this._handleWorkspaceContainsEagerExtensions(folders);
const eagerExtensionsActivation = Promise.all([starActivation, workspaceContainsActivation]).then(() => { });
Promise.race([eagerExtensionsActivation, timeout(10000)]).then(() => {
this._activateAllStartupFinished();
});
return eagerExtensionsActivation;
}
private _handleWorkspaceContainsEagerExtensions(folders: ReadonlyArray<vscode.WorkspaceFolder>): Promise<void> {
if (folders.length === 0) {
return Promise.resolve(undefined);
}
return Promise.all(
this._registry.getAllExtensionDescriptions().map((desc) => {
return this._handleWorkspaceContainsEagerExtension(folders, desc);
})
).then(() => { });
}
private async _handleWorkspaceContainsEagerExtension(folders: ReadonlyArray<vscode.WorkspaceFolder>, desc: IExtensionDescription): Promise<void> {
if (this.isActivated(desc.identifier)) {
return;
}
const localWithRemote = !this._initData.remote.isRemote && !!this._initData.remote.authority;
const host: IExtensionActivationHost = {
folders: folders.map(folder => folder.uri),
forceUsingSearch: localWithRemote,
exists: (uri) => this._hostUtils.exists(uri.fsPath),
checkExists: (folders, includes, token) => this._mainThreadWorkspaceProxy.$checkExists(folders, includes, token)
};
const result = await checkActivateWorkspaceContainsExtension(host, desc);
if (!result) {
return;
}
return (
this._activateById(desc.identifier, { startup: true, extensionId: desc.identifier, activationEvent: result.activationEvent })
.then(undefined, err => this._logService.error(err))
);
}
private _handleExtensionTests(): Promise<void> {
return this._doHandleExtensionTests().then(undefined, error => {
console.error(error); // ensure any error message makes it onto the console
return Promise.reject(error);
});
}
private async _doHandleExtensionTests(): Promise<void> {
const { extensionDevelopmentLocationURI, extensionTestsLocationURI } = this._initData.environment;
if (!(extensionDevelopmentLocationURI && extensionTestsLocationURI && extensionTestsLocationURI.scheme === Schemas.file)) {
return Promise.resolve(undefined);
}
const extensionTestsPath = originalFSPath(extensionTestsLocationURI);
// Require the test runner via node require from the provided path
let testRunner: ITestRunner | INewTestRunner | undefined;
let requireError: Error | undefined;
try {
testRunner = await this._loadCommonJSModule(URI.file(extensionTestsPath), new ExtensionActivationTimesBuilder(false));
} catch (error) {
requireError = error;
}
// Execute the runner if it follows the old `run` spec
if (testRunner && typeof testRunner.run === 'function') {
return new Promise<void>((c, e) => {
const oldTestRunnerCallback = (error: Error, failures: number | undefined) => {
if (error) {
e(error.toString());
} else {
c(undefined);
}
// after tests have run, we shutdown the host
this._testRunnerExit(error || (typeof failures === 'number' && failures > 0) ? 1 /* ERROR */ : 0 /* OK */);
};
const runResult = testRunner!.run(extensionTestsPath, oldTestRunnerCallback);
// Using the new API `run(): Promise<void>`
if (runResult && runResult.then) {
runResult
.then(() => {
c();
this._testRunnerExit(0);
})
.catch((err: Error) => {
e(err.toString());
this._testRunnerExit(1);
});
}
});
}
// Otherwise make sure to shutdown anyway even in case of an error
else {
this._testRunnerExit(1 /* ERROR */);
}
return Promise.reject(new Error(requireError ? requireError.toString() : nls.localize('extensionTestError', "Path {0} does not point to a valid extension test runner.", extensionTestsPath)));
}
private _testRunnerExit(code: number): void {
// wait at most 5000ms for the renderer to confirm our exit request and for the renderer socket to drain
// (this is to ensure all outstanding messages reach the renderer)
const exitPromise = this._mainThreadExtensionsProxy.$onExtensionHostExit(code);
const drainPromise = this._extHostContext.drain();
Promise.race([Promise.all([exitPromise, drainPromise]), timeout(5000)]).then(() => {
this._hostUtils.exit(code);
});
}
private _startExtensionHost(): Promise<void> {
if (this._started) {
throw new Error(`Extension host is already started!`);
}
this._started = true;
return this._readyToStartExtensionHost.wait()
.then(() => this._readyToRunExtensions.open())
.then(() => this._handleEagerExtensions())
.then(() => this._handleExtensionTests())
.then(() => {
this._logService.info(`eager extensions activated`);
});
}
// -- called by extensions
public registerRemoteAuthorityResolver(authorityPrefix: string, resolver: vscode.RemoteAuthorityResolver): vscode.Disposable {
this._resolvers[authorityPrefix] = resolver;
return toDisposable(() => {
delete this._resolvers[authorityPrefix];
});
}
// -- called by main thread
public async $resolveAuthority(remoteAuthority: string, resolveAttempt: number): Promise<IResolveAuthorityResult> {
const authorityPlusIndex = remoteAuthority.indexOf('+');
if (authorityPlusIndex === -1) {
throw new Error(`Not an authority that can be resolved!`);
}
const authorityPrefix = remoteAuthority.substr(0, authorityPlusIndex);
await this._almostReadyToRunExtensions.wait();
await this._activateByEvent(`onResolveRemoteAuthority:${authorityPrefix}`, false);
const resolver = this._resolvers[authorityPrefix];
if (!resolver) {
return {
type: 'error',
error: {
code: RemoteAuthorityResolverErrorCode.NoResolverFound,
message: `No remote extension installed to resolve ${authorityPrefix}.`,
detail: undefined
}
};
}
try {
const result = await resolver.resolve(remoteAuthority, { resolveAttempt });
this._disposables.add(await this._extHostTunnelService.setTunnelExtensionFunctions(resolver));
// Split merged API result into separate authority/options
const authority: ResolvedAuthority = {
authority: remoteAuthority,
host: result.host,
port: result.port,
connectionToken: result.connectionToken
};
const options: ResolvedOptions = {
extensionHostEnv: result.extensionHostEnv
};
return {
type: 'ok',
value: {
authority,
options,
tunnelInformation: { environmentTunnels: result.environmentTunnels }
}
};
} catch (err) {
if (err instanceof RemoteAuthorityResolverError) {
return {
type: 'error',
error: {
code: err._code,
message: err._message,
detail: err._detail
}
};
}
throw err;
}
}
public $startExtensionHost(enabledExtensionIds: ExtensionIdentifier[]): Promise<void> {
this._registry.keepOnly(enabledExtensionIds);
return this._startExtensionHost();
}
public $activateByEvent(activationEvent: string, activationKind: ActivationKind): Promise<void> {
if (activationKind === ActivationKind.Immediate) {
return this._activateByEvent(activationEvent, false);
}
return (
this._readyToRunExtensions.wait()
.then(_ => this._activateByEvent(activationEvent, false))
);
}
public async $activate(extensionId: ExtensionIdentifier, reason: ExtensionActivationReason): Promise<boolean> {
await this._readyToRunExtensions.wait();
if (!this._registry.getExtensionDescription(extensionId)) {
// unknown extension => ignore
return false;
}
await this._activateById(extensionId, reason);
return true;
}
public async $deltaExtensions(toAdd: IExtensionDescription[], toRemove: ExtensionIdentifier[]): Promise<void> {
toAdd.forEach((extension) => (<any>extension).extensionLocation = URI.revive(extension.extensionLocation));
const trie = await this.getExtensionPathIndex();
await Promise.all(toRemove.map(async (extensionId) => {
const extensionDescription = this._registry.getExtensionDescription(extensionId);
if (!extensionDescription) {
return;
}
const realpathValue = await this._hostUtils.realpath(extensionDescription.extensionLocation.fsPath);
trie.delete(URI.file(realpathValue).fsPath);
}));
await Promise.all(toAdd.map(async (extensionDescription) => {
const realpathValue = await this._hostUtils.realpath(extensionDescription.extensionLocation.fsPath);
trie.set(URI.file(realpathValue).fsPath, extensionDescription);
}));
this._registry.deltaExtensions(toAdd, toRemove);
return Promise.resolve(undefined);
}
public async $test_latency(n: number): Promise<number> {
return n;
}
public async $test_up(b: VSBuffer): Promise<number> {
return b.byteLength;
}
public async $test_down(size: number): Promise<VSBuffer> {
let buff = VSBuffer.alloc(size);
let value = Math.random() % 256;
for (let i = 0; i < size; i++) {
buff.writeUInt8(value, i);
}
return buff;
}
public async $updateRemoteConnectionData(connectionData: IRemoteConnectionData): Promise<void> {
this._remoteConnectionData = connectionData;
this._onDidChangeRemoteConnectionData.fire();
}
protected abstract _beforeAlmostReadyToRunExtensions(): Promise<void>;
protected abstract _getEntryPoint(extensionDescription: IExtensionDescription): string | undefined;
protected abstract _loadCommonJSModule<T>(module: URI, activationTimesBuilder: ExtensionActivationTimesBuilder): Promise<T>;
public abstract $setRemoteEnvironment(env: { [key: string]: string | null }): Promise<void>;
}
type TelemetryActivationEvent = {
id: string;
name: string;
extensionVersion: string;
publisherDisplayName: string;
activationEvents: string | null;
isBuiltin: boolean;
reason: string;
reasonId: string;
};
function getTelemetryActivationEvent(extensionDescription: IExtensionDescription, reason: ExtensionActivationReason): TelemetryActivationEvent {
const event = {
id: extensionDescription.identifier.value,
name: extensionDescription.name,
extensionVersion: extensionDescription.version,
publisherDisplayName: extensionDescription.publisher,
activationEvents: extensionDescription.activationEvents ? extensionDescription.activationEvents.join(',') : null,
isBuiltin: extensionDescription.isBuiltin,
reason: reason.activationEvent,
reasonId: reason.extensionId.value,
};
return event;
}
export const IExtHostExtensionService = createDecorator<IExtHostExtensionService>('IExtHostExtensionService');
export interface IExtHostExtensionService extends AbstractExtHostExtensionService {
readonly _serviceBrand: undefined;
initialize(): Promise<void>;
isActivated(extensionId: ExtensionIdentifier): boolean;
activateByIdWithErrors(extensionId: ExtensionIdentifier, reason: ExtensionActivationReason): Promise<void>;
deactivateAll(): Promise<void>;
getExtensionExports(extensionId: ExtensionIdentifier): IExtensionAPI | null | undefined;
getExtensionRegistry(): Promise<ExtensionDescriptionRegistry>;
getExtensionPathIndex(): Promise<TernarySearchTree<string, IExtensionDescription>>;
registerRemoteAuthorityResolver(authorityPrefix: string, resolver: vscode.RemoteAuthorityResolver): vscode.Disposable;
onDidChangeRemoteConnectionData: Event<void>;
getRemoteConnectionData(): IRemoteConnectionData | null;
}

View File

@ -0,0 +1,306 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { URI, UriComponents } from 'vs/base/common/uri';
import { MainContext, IMainContext, ExtHostFileSystemShape, MainThreadFileSystemShape, IFileChangeDto } from './extHost.protocol';
import type * as vscode from 'vscode';
import * as files from 'vs/platform/files/common/files';
import { IDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { FileChangeType } from 'vs/workbench/api/common/extHostTypes';
import * as typeConverter from 'vs/workbench/api/common/extHostTypeConverters';
import { ExtHostLanguageFeatures } from 'vs/workbench/api/common/extHostLanguageFeatures';
import { State, StateMachine, LinkComputer, Edge } from 'vs/editor/common/modes/linkComputer';
import { commonPrefixLength } from 'vs/base/common/strings';
import { CharCode } from 'vs/base/common/charCode';
import { VSBuffer } from 'vs/base/common/buffer';
import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions';
class FsLinkProvider {
private _schemes: string[] = [];
private _stateMachine?: StateMachine;
add(scheme: string): void {
this._stateMachine = undefined;
this._schemes.push(scheme);
}
delete(scheme: string): void {
const idx = this._schemes.indexOf(scheme);
if (idx >= 0) {
this._schemes.splice(idx, 1);
this._stateMachine = undefined;
}
}
private _initStateMachine(): void {
if (!this._stateMachine) {
// sort and compute common prefix with previous scheme
// then build state transitions based on the data
const schemes = this._schemes.sort();
const edges: Edge[] = [];
let prevScheme: string | undefined;
let prevState: State;
let lastState = State.LastKnownState;
let nextState = State.LastKnownState;
for (const scheme of schemes) {
// skip the common prefix of the prev scheme
// and continue with its last state
let pos = !prevScheme ? 0 : commonPrefixLength(prevScheme, scheme);
if (pos === 0) {
prevState = State.Start;
} else {
prevState = nextState;
}
for (; pos < scheme.length; pos++) {
// keep creating new (next) states until the
// end (and the BeforeColon-state) is reached
if (pos + 1 === scheme.length) {
// Save the last state here, because we need to continue for the next scheme
lastState = nextState;
nextState = State.BeforeColon;
} else {
nextState += 1;
}
edges.push([prevState, scheme.toUpperCase().charCodeAt(pos), nextState]);
edges.push([prevState, scheme.toLowerCase().charCodeAt(pos), nextState]);
prevState = nextState;
}
prevScheme = scheme;
// Restore the last state
nextState = lastState;
}
// all link must match this pattern `<scheme>:/<more>`
edges.push([State.BeforeColon, CharCode.Colon, State.AfterColon]);
edges.push([State.AfterColon, CharCode.Slash, State.End]);
this._stateMachine = new StateMachine(edges);
}
}
provideDocumentLinks(document: vscode.TextDocument): vscode.ProviderResult<vscode.DocumentLink[]> {
this._initStateMachine();
const result: vscode.DocumentLink[] = [];
const links = LinkComputer.computeLinks({
getLineContent(lineNumber: number): string {
return document.lineAt(lineNumber - 1).text;
},
getLineCount(): number {
return document.lineCount;
}
}, this._stateMachine);
for (const link of links) {
const docLink = typeConverter.DocumentLink.to(link);
if (docLink.target) {
result.push(docLink);
}
}
return result;
}
}
export class ExtHostFileSystem implements ExtHostFileSystemShape {
private readonly _proxy: MainThreadFileSystemShape;
private readonly _linkProvider = new FsLinkProvider();
private readonly _fsProvider = new Map<number, vscode.FileSystemProvider>();
private readonly _registeredSchemes = new Set<string>();
private readonly _watches = new Map<number, IDisposable>();
private _linkProviderRegistration?: IDisposable;
private _handlePool: number = 0;
constructor(mainContext: IMainContext, private _extHostLanguageFeatures: ExtHostLanguageFeatures) {
this._proxy = mainContext.getProxy(MainContext.MainThreadFileSystem);
}
dispose(): void {
this._linkProviderRegistration?.dispose();
}
private _registerLinkProviderIfNotYetRegistered(): void {
if (!this._linkProviderRegistration) {
this._linkProviderRegistration = this._extHostLanguageFeatures.registerDocumentLinkProvider(undefined, '*', this._linkProvider);
}
}
registerFileSystemProvider(extension: ExtensionIdentifier, scheme: string, provider: vscode.FileSystemProvider, options: { isCaseSensitive?: boolean, isReadonly?: boolean } = {}) {
if (this._registeredSchemes.has(scheme)) {
throw new Error(`a provider for the scheme '${scheme}' is already registered`);
}
//
this._registerLinkProviderIfNotYetRegistered();
const handle = this._handlePool++;
this._linkProvider.add(scheme);
this._registeredSchemes.add(scheme);
this._fsProvider.set(handle, provider);
let capabilities = files.FileSystemProviderCapabilities.FileReadWrite;
if (options.isCaseSensitive) {
capabilities += files.FileSystemProviderCapabilities.PathCaseSensitive;
}
if (options.isReadonly) {
capabilities += files.FileSystemProviderCapabilities.Readonly;
}
if (typeof provider.copy === 'function') {
capabilities += files.FileSystemProviderCapabilities.FileFolderCopy;
}
if (typeof provider.open === 'function' && typeof provider.close === 'function'
&& typeof provider.read === 'function' && typeof provider.write === 'function'
) {
capabilities += files.FileSystemProviderCapabilities.FileOpenReadWriteClose;
}
this._proxy.$registerFileSystemProvider(handle, scheme, capabilities).catch(err => {
console.error(`FAILED to register filesystem provider of ${extension.value}-extension for the scheme ${scheme}`);
console.error(err);
});
const subscription = provider.onDidChangeFile(event => {
const mapped: IFileChangeDto[] = [];
for (const e of event) {
let { uri: resource, type } = e;
if (resource.scheme !== scheme) {
// dropping events for wrong scheme
continue;
}
let newType: files.FileChangeType | undefined;
switch (type) {
case FileChangeType.Changed:
newType = files.FileChangeType.UPDATED;
break;
case FileChangeType.Created:
newType = files.FileChangeType.ADDED;
break;
case FileChangeType.Deleted:
newType = files.FileChangeType.DELETED;
break;
default:
throw new Error('Unknown FileChangeType');
}
mapped.push({ resource, type: newType });
}
this._proxy.$onFileSystemChange(handle, mapped);
});
return toDisposable(() => {
subscription.dispose();
this._linkProvider.delete(scheme);
this._registeredSchemes.delete(scheme);
this._fsProvider.delete(handle);
this._proxy.$unregisterProvider(handle);
});
}
private static _asIStat(stat: vscode.FileStat): files.IStat {
const { type, ctime, mtime, size } = stat;
return { type, ctime, mtime, size };
}
$stat(handle: number, resource: UriComponents): Promise<files.IStat> {
return Promise.resolve(this._getFsProvider(handle).stat(URI.revive(resource))).then(ExtHostFileSystem._asIStat);
}
$readdir(handle: number, resource: UriComponents): Promise<[string, files.FileType][]> {
return Promise.resolve(this._getFsProvider(handle).readDirectory(URI.revive(resource)));
}
$readFile(handle: number, resource: UriComponents): Promise<VSBuffer> {
return Promise.resolve(this._getFsProvider(handle).readFile(URI.revive(resource))).then(data => VSBuffer.wrap(data));
}
$writeFile(handle: number, resource: UriComponents, content: VSBuffer, opts: files.FileWriteOptions): Promise<void> {
return Promise.resolve(this._getFsProvider(handle).writeFile(URI.revive(resource), content.buffer, opts));
}
$delete(handle: number, resource: UriComponents, opts: files.FileDeleteOptions): Promise<void> {
return Promise.resolve(this._getFsProvider(handle).delete(URI.revive(resource), opts));
}
$rename(handle: number, oldUri: UriComponents, newUri: UriComponents, opts: files.FileOverwriteOptions): Promise<void> {
return Promise.resolve(this._getFsProvider(handle).rename(URI.revive(oldUri), URI.revive(newUri), opts));
}
$copy(handle: number, oldUri: UriComponents, newUri: UriComponents, opts: files.FileOverwriteOptions): Promise<void> {
const provider = this._getFsProvider(handle);
if (!provider.copy) {
throw new Error('FileSystemProvider does not implement "copy"');
}
return Promise.resolve(provider.copy(URI.revive(oldUri), URI.revive(newUri), opts));
}
$mkdir(handle: number, resource: UriComponents): Promise<void> {
return Promise.resolve(this._getFsProvider(handle).createDirectory(URI.revive(resource)));
}
$watch(handle: number, session: number, resource: UriComponents, opts: files.IWatchOptions): void {
const subscription = this._getFsProvider(handle).watch(URI.revive(resource), opts);
this._watches.set(session, subscription);
}
$unwatch(_handle: number, session: number): void {
const subscription = this._watches.get(session);
if (subscription) {
subscription.dispose();
this._watches.delete(session);
}
}
$open(handle: number, resource: UriComponents, opts: files.FileOpenOptions): Promise<number> {
const provider = this._getFsProvider(handle);
if (!provider.open) {
throw new Error('FileSystemProvider does not implement "open"');
}
return Promise.resolve(provider.open(URI.revive(resource), opts));
}
$close(handle: number, fd: number): Promise<void> {
const provider = this._getFsProvider(handle);
if (!provider.close) {
throw new Error('FileSystemProvider does not implement "close"');
}
return Promise.resolve(provider.close(fd));
}
$read(handle: number, fd: number, pos: number, length: number): Promise<VSBuffer> {
const provider = this._getFsProvider(handle);
if (!provider.read) {
throw new Error('FileSystemProvider does not implement "read"');
}
const data = VSBuffer.alloc(length);
return Promise.resolve(provider.read(fd, pos, data.buffer, 0, length)).then(read => {
return data.slice(0, read); // don't send zeros
});
}
$write(handle: number, fd: number, pos: number, data: VSBuffer): Promise<number> {
const provider = this._getFsProvider(handle);
if (!provider.write) {
throw new Error('FileSystemProvider does not implement "write"');
}
return Promise.resolve(provider.write(fd, pos, data.buffer, 0, data.byteLength));
}
private _getFsProvider(handle: number): vscode.FileSystemProvider {
const provider = this._fsProvider.get(handle);
if (!provider) {
const err = new Error();
err.name = 'ENOPRO';
err.message = `no provider`;
throw err;
}
return provider;
}
}

View File

@ -0,0 +1,86 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { MainThreadFileSystemShape, MainContext } from './extHost.protocol';
import * as vscode from 'vscode';
import * as files from 'vs/platform/files/common/files';
import { FileSystemError } from 'vs/workbench/api/common/extHostTypes';
import { VSBuffer } from 'vs/base/common/buffer';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService';
import { IExtHostFileSystemInfo } from 'vs/workbench/api/common/extHostFileSystemInfo';
export class ExtHostConsumerFileSystem implements vscode.FileSystem {
readonly _serviceBrand: undefined;
private readonly _proxy: MainThreadFileSystemShape;
constructor(
@IExtHostRpcService extHostRpc: IExtHostRpcService,
@IExtHostFileSystemInfo private readonly _fileSystemInfo: IExtHostFileSystemInfo,
) {
this._proxy = extHostRpc.getProxy(MainContext.MainThreadFileSystem);
}
stat(uri: vscode.Uri): Promise<vscode.FileStat> {
return this._proxy.$stat(uri).catch(ExtHostConsumerFileSystem._handleError);
}
readDirectory(uri: vscode.Uri): Promise<[string, vscode.FileType][]> {
return this._proxy.$readdir(uri).catch(ExtHostConsumerFileSystem._handleError);
}
createDirectory(uri: vscode.Uri): Promise<void> {
return this._proxy.$mkdir(uri).catch(ExtHostConsumerFileSystem._handleError);
}
async readFile(uri: vscode.Uri): Promise<Uint8Array> {
return this._proxy.$readFile(uri).then(buff => buff.buffer).catch(ExtHostConsumerFileSystem._handleError);
}
writeFile(uri: vscode.Uri, content: Uint8Array): Promise<void> {
return this._proxy.$writeFile(uri, VSBuffer.wrap(content)).catch(ExtHostConsumerFileSystem._handleError);
}
delete(uri: vscode.Uri, options?: { recursive?: boolean; useTrash?: boolean; }): Promise<void> {
return this._proxy.$delete(uri, { ...{ recursive: false, useTrash: false }, ...options }).catch(ExtHostConsumerFileSystem._handleError);
}
rename(oldUri: vscode.Uri, newUri: vscode.Uri, options?: { overwrite?: boolean; }): Promise<void> {
return this._proxy.$rename(oldUri, newUri, { ...{ overwrite: false }, ...options }).catch(ExtHostConsumerFileSystem._handleError);
}
copy(source: vscode.Uri, destination: vscode.Uri, options?: { overwrite?: boolean; }): Promise<void> {
return this._proxy.$copy(source, destination, { ...{ overwrite: false }, ...options }).catch(ExtHostConsumerFileSystem._handleError);
}
isWritableFileSystem(scheme: string): boolean | undefined {
const capabilities = this._fileSystemInfo.getCapabilities(scheme);
if (typeof capabilities === 'number') {
return !(capabilities & files.FileSystemProviderCapabilities.Readonly);
}
return undefined;
}
private static _handleError(err: any): never {
// generic error
if (!(err instanceof Error)) {
throw new FileSystemError(String(err));
}
// no provider (unknown scheme) error
if (err.name === 'ENOPRO') {
throw FileSystemError.Unavailable(err.message);
}
// file system error
switch (err.name) {
case files.FileSystemProviderErrorCode.FileExists: throw FileSystemError.FileExists(err.message);
case files.FileSystemProviderErrorCode.FileNotFound: throw FileSystemError.FileNotFound(err.message);
case files.FileSystemProviderErrorCode.FileNotADirectory: throw FileSystemError.FileNotADirectory(err.message);
case files.FileSystemProviderErrorCode.FileIsADirectory: throw FileSystemError.FileIsADirectory(err.message);
case files.FileSystemProviderErrorCode.NoPermissions: throw FileSystemError.NoPermissions(err.message);
case files.FileSystemProviderErrorCode.Unavailable: throw FileSystemError.Unavailable(err.message);
default: throw new FileSystemError(err.message, err.name as files.FileSystemProviderErrorCode);
}
}
}
export interface IExtHostConsumerFileSystem extends ExtHostConsumerFileSystem { }
export const IExtHostConsumerFileSystem = createDecorator<IExtHostConsumerFileSystem>('IExtHostConsumerFileSystem');

View File

@ -0,0 +1,228 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { AsyncEmitter, Emitter, Event, IWaitUntil } from 'vs/base/common/event';
import { IRelativePattern, parse } from 'vs/base/common/glob';
import { URI } from 'vs/base/common/uri';
import { ExtHostDocumentsAndEditors } from 'vs/workbench/api/common/extHostDocumentsAndEditors';
import type * as vscode from 'vscode';
import { ExtHostFileSystemEventServiceShape, FileSystemEvents, IMainContext, MainContext, SourceTargetPair, IWorkspaceEditDto, MainThreadBulkEditsShape } from './extHost.protocol';
import * as typeConverter from './extHostTypeConverters';
import { Disposable, WorkspaceEdit } from './extHostTypes';
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { FileOperation } from 'vs/platform/files/common/files';
import { CancellationToken } from 'vs/base/common/cancellation';
import { ILogService } from 'vs/platform/log/common/log';
class FileSystemWatcher implements vscode.FileSystemWatcher {
private readonly _onDidCreate = new Emitter<vscode.Uri>();
private readonly _onDidChange = new Emitter<vscode.Uri>();
private readonly _onDidDelete = new Emitter<vscode.Uri>();
private _disposable: Disposable;
private _config: number;
get ignoreCreateEvents(): boolean {
return Boolean(this._config & 0b001);
}
get ignoreChangeEvents(): boolean {
return Boolean(this._config & 0b010);
}
get ignoreDeleteEvents(): boolean {
return Boolean(this._config & 0b100);
}
constructor(dispatcher: Event<FileSystemEvents>, globPattern: string | IRelativePattern, ignoreCreateEvents?: boolean, ignoreChangeEvents?: boolean, ignoreDeleteEvents?: boolean) {
this._config = 0;
if (ignoreCreateEvents) {
this._config += 0b001;
}
if (ignoreChangeEvents) {
this._config += 0b010;
}
if (ignoreDeleteEvents) {
this._config += 0b100;
}
const parsedPattern = parse(globPattern);
const subscription = dispatcher(events => {
if (!ignoreCreateEvents) {
for (let created of events.created) {
const uri = URI.revive(created);
if (parsedPattern(uri.fsPath)) {
this._onDidCreate.fire(uri);
}
}
}
if (!ignoreChangeEvents) {
for (let changed of events.changed) {
const uri = URI.revive(changed);
if (parsedPattern(uri.fsPath)) {
this._onDidChange.fire(uri);
}
}
}
if (!ignoreDeleteEvents) {
for (let deleted of events.deleted) {
const uri = URI.revive(deleted);
if (parsedPattern(uri.fsPath)) {
this._onDidDelete.fire(uri);
}
}
}
});
this._disposable = Disposable.from(this._onDidCreate, this._onDidChange, this._onDidDelete, subscription);
}
dispose() {
this._disposable.dispose();
}
get onDidCreate(): Event<vscode.Uri> {
return this._onDidCreate.event;
}
get onDidChange(): Event<vscode.Uri> {
return this._onDidChange.event;
}
get onDidDelete(): Event<vscode.Uri> {
return this._onDidDelete.event;
}
}
interface IExtensionListener<E> {
extension: IExtensionDescription;
(e: E): any;
}
export class ExtHostFileSystemEventService implements ExtHostFileSystemEventServiceShape {
private readonly _onFileSystemEvent = new Emitter<FileSystemEvents>();
private readonly _onDidRenameFile = new Emitter<vscode.FileRenameEvent>();
private readonly _onDidCreateFile = new Emitter<vscode.FileCreateEvent>();
private readonly _onDidDeleteFile = new Emitter<vscode.FileDeleteEvent>();
private readonly _onWillRenameFile = new AsyncEmitter<vscode.FileWillRenameEvent>();
private readonly _onWillCreateFile = new AsyncEmitter<vscode.FileWillCreateEvent>();
private readonly _onWillDeleteFile = new AsyncEmitter<vscode.FileWillDeleteEvent>();
readonly onDidRenameFile: Event<vscode.FileRenameEvent> = this._onDidRenameFile.event;
readonly onDidCreateFile: Event<vscode.FileCreateEvent> = this._onDidCreateFile.event;
readonly onDidDeleteFile: Event<vscode.FileDeleteEvent> = this._onDidDeleteFile.event;
constructor(
mainContext: IMainContext,
private readonly _logService: ILogService,
private readonly _extHostDocumentsAndEditors: ExtHostDocumentsAndEditors,
private readonly _mainThreadBulkEdits: MainThreadBulkEditsShape = mainContext.getProxy(MainContext.MainThreadBulkEdits)
) {
//
}
//--- file events
createFileSystemWatcher(globPattern: string | IRelativePattern, ignoreCreateEvents?: boolean, ignoreChangeEvents?: boolean, ignoreDeleteEvents?: boolean): vscode.FileSystemWatcher {
return new FileSystemWatcher(this._onFileSystemEvent.event, globPattern, ignoreCreateEvents, ignoreChangeEvents, ignoreDeleteEvents);
}
$onFileEvent(events: FileSystemEvents) {
this._onFileSystemEvent.fire(events);
}
//--- file operations
$onDidRunFileOperation(operation: FileOperation, files: SourceTargetPair[]): void {
switch (operation) {
case FileOperation.MOVE:
this._onDidRenameFile.fire(Object.freeze({ files: files.map(f => ({ oldUri: URI.revive(f.source!), newUri: URI.revive(f.target) })) }));
break;
case FileOperation.DELETE:
this._onDidDeleteFile.fire(Object.freeze({ files: files.map(f => URI.revive(f.target)) }));
break;
case FileOperation.CREATE:
this._onDidCreateFile.fire(Object.freeze({ files: files.map(f => URI.revive(f.target)) }));
break;
default:
//ignore, dont send
}
}
getOnWillRenameFileEvent(extension: IExtensionDescription): Event<vscode.FileWillRenameEvent> {
return this._createWillExecuteEvent(extension, this._onWillRenameFile);
}
getOnWillCreateFileEvent(extension: IExtensionDescription): Event<vscode.FileWillCreateEvent> {
return this._createWillExecuteEvent(extension, this._onWillCreateFile);
}
getOnWillDeleteFileEvent(extension: IExtensionDescription): Event<vscode.FileWillDeleteEvent> {
return this._createWillExecuteEvent(extension, this._onWillDeleteFile);
}
private _createWillExecuteEvent<E extends IWaitUntil>(extension: IExtensionDescription, emitter: AsyncEmitter<E>): Event<E> {
return (listener, thisArg, disposables) => {
const wrappedListener: IExtensionListener<E> = function wrapped(e: E) { listener.call(thisArg, e); };
wrappedListener.extension = extension;
return emitter.event(wrappedListener, undefined, disposables);
};
}
async $onWillRunFileOperation(operation: FileOperation, files: SourceTargetPair[], timeout: number, token: CancellationToken): Promise<any> {
switch (operation) {
case FileOperation.MOVE:
await this._fireWillEvent(this._onWillRenameFile, { files: files.map(f => ({ oldUri: URI.revive(f.source!), newUri: URI.revive(f.target) })) }, timeout, token);
break;
case FileOperation.DELETE:
await this._fireWillEvent(this._onWillDeleteFile, { files: files.map(f => URI.revive(f.target)) }, timeout, token);
break;
case FileOperation.CREATE:
await this._fireWillEvent(this._onWillCreateFile, { files: files.map(f => URI.revive(f.target)) }, timeout, token);
break;
default:
//ignore, dont send
}
}
private async _fireWillEvent<E extends IWaitUntil>(emitter: AsyncEmitter<E>, data: Omit<E, 'waitUntil'>, timeout: number, token: CancellationToken): Promise<any> {
const edits: WorkspaceEdit[] = [];
await emitter.fireAsync(data, token, async (thenable, listener) => {
// ignore all results except for WorkspaceEdits. Those are stored in an array.
const now = Date.now();
const result = await Promise.resolve(thenable);
if (result instanceof WorkspaceEdit) {
edits.push(result);
}
if (Date.now() - now > timeout) {
this._logService.warn('SLOW file-participant', (<IExtensionListener<E>>listener).extension?.identifier);
}
});
if (token.isCancellationRequested) {
return;
}
if (edits.length > 0) {
// concat all WorkspaceEdits collected via waitUntil-call and apply them in one go.
const dto: IWorkspaceEditDto = { edits: [] };
for (let edit of edits) {
let { edits } = typeConverter.WorkspaceEdit.from(edit, this._extHostDocumentsAndEditors);
dto.edits = dto.edits.concat(edits);
}
return this._mainThreadBulkEdits.$tryApplyWorkspaceEdit(dto);
}
}
}

View File

@ -0,0 +1,35 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Schemas } from 'vs/base/common/network';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { ExtHostFileSystemInfoShape } from 'vs/workbench/api/common/extHost.protocol';
export class ExtHostFileSystemInfo implements ExtHostFileSystemInfoShape {
declare readonly _serviceBrand: undefined;
private readonly _systemSchemes = new Set(Object.keys(Schemas));
private readonly _providerInfo = new Map<string, number>();
$acceptProviderInfos(scheme: string, capabilities: number | null): void {
if (capabilities === null) {
this._providerInfo.delete(scheme);
} else {
this._providerInfo.set(scheme, capabilities);
}
}
isFreeScheme(scheme: string): boolean {
return !this._providerInfo.has(scheme) && !this._systemSchemes.has(scheme);
}
getCapabilities(scheme: string): number | undefined {
return this._providerInfo.get(scheme);
}
}
export interface IExtHostFileSystemInfo extends ExtHostFileSystemInfo { }
export const IExtHostFileSystemInfo = createDecorator<IExtHostFileSystemInfo>('IExtHostFileSystemInfo');

View File

@ -0,0 +1,14 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IInitData } from './extHost.protocol';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
export const IExtHostInitDataService = createDecorator<IExtHostInitDataService>('IExtHostInitDataService');
export interface IExtHostInitDataService extends Readonly<IInitData> {
readonly _serviceBrand: undefined;
}

View File

@ -0,0 +1,27 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ResourceLabelFormatter } from 'vs/platform/label/common/label';
import { IDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { MainThreadLabelServiceShape, ExtHostLabelServiceShape, MainContext, IMainContext } from 'vs/workbench/api/common/extHost.protocol';
export class ExtHostLabelService implements ExtHostLabelServiceShape {
private readonly _proxy: MainThreadLabelServiceShape;
private _handlePool: number = 0;
constructor(mainContext: IMainContext) {
this._proxy = mainContext.getProxy(MainContext.MainThreadLabelService);
}
$registerResourceLabelFormatter(formatter: ResourceLabelFormatter): IDisposable {
const handle = this._handlePool++;
this._proxy.$registerResourceLabelFormatter(handle, formatter);
return toDisposable(() => {
this._proxy.$unregisterResourceLabelFormatter(handle);
});
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,64 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { MainContext, MainThreadLanguagesShape, IMainContext } from './extHost.protocol';
import type * as vscode from 'vscode';
import { ExtHostDocuments } from 'vs/workbench/api/common/extHostDocuments';
import * as typeConvert from 'vs/workbench/api/common/extHostTypeConverters';
import { StandardTokenType, Range, Position } from 'vs/workbench/api/common/extHostTypes';
export class ExtHostLanguages {
private readonly _proxy: MainThreadLanguagesShape;
private readonly _documents: ExtHostDocuments;
constructor(
mainContext: IMainContext,
documents: ExtHostDocuments
) {
this._proxy = mainContext.getProxy(MainContext.MainThreadLanguages);
this._documents = documents;
}
getLanguages(): Promise<string[]> {
return this._proxy.$getLanguages();
}
async changeLanguage(uri: vscode.Uri, languageId: string): Promise<vscode.TextDocument> {
await this._proxy.$changeLanguage(uri, languageId);
const data = this._documents.getDocumentData(uri);
if (!data) {
throw new Error(`document '${uri.toString}' NOT found`);
}
return data.document;
}
async tokenAtPosition(document: vscode.TextDocument, position: vscode.Position): Promise<vscode.TokenInformation> {
const versionNow = document.version;
const pos = typeConvert.Position.from(position);
const info = await this._proxy.$tokensAtPosition(document.uri, pos);
const defaultRange = {
type: StandardTokenType.Other,
range: document.getWordRangeAtPosition(position) ?? new Range(position.line, position.character, position.line, position.character)
};
if (!info) {
// no result
return defaultRange;
}
const result = {
range: typeConvert.Range.to(info.range),
type: typeConvert.TokenType.to(info.type)
};
if (!result.range.contains(<Position>position)) {
// bogous result
return defaultRange;
}
if (versionNow !== document.version) {
// concurrent change
return defaultRange;
}
return result;
}
}

View File

@ -0,0 +1,75 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import type * as vscode from 'vscode';
import { IDisposable } from 'vs/base/common/lifecycle';
import { ExtHostStorage } from 'vs/workbench/api/common/extHostStorage';
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
export class ExtensionMemento implements vscode.Memento {
protected readonly _id: string;
private readonly _shared: boolean;
protected readonly _storage: ExtHostStorage;
private readonly _init: Promise<ExtensionMemento>;
private _value?: { [n: string]: any; };
private readonly _storageListener: IDisposable;
constructor(id: string, global: boolean, storage: ExtHostStorage) {
this._id = id;
this._shared = global;
this._storage = storage;
this._init = this._storage.getValue(this._shared, this._id, Object.create(null)).then(value => {
this._value = value;
return this;
});
this._storageListener = this._storage.onDidChangeStorage(e => {
if (e.shared === this._shared && e.key === this._id) {
this._value = e.value;
}
});
}
get whenReady(): Promise<ExtensionMemento> {
return this._init;
}
get<T>(key: string): T | undefined;
get<T>(key: string, defaultValue: T): T;
get<T>(key: string, defaultValue?: T): T {
let value = this._value![key];
if (typeof value === 'undefined') {
value = defaultValue;
}
return value;
}
update(key: string, value: any): Promise<void> {
this._value![key] = value;
return this._storage.setValue(this._shared, this._id, this._value!);
}
dispose(): void {
this._storageListener.dispose();
}
}
export class ExtensionGlobalMemento extends ExtensionMemento {
private readonly _extension: IExtensionDescription;
setKeysForSync(keys: string[]): void {
this._storage.registerExtensionStorageKeysToSync({ id: this._id, version: this._extension.version }, keys);
}
constructor(extensionDescription: IExtensionDescription, storage: ExtHostStorage) {
super(extensionDescription.identifier.value, true, storage);
this._extension = extensionDescription;
}
}

View File

@ -0,0 +1,64 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import Severity from 'vs/base/common/severity';
import type * as vscode from 'vscode';
import { MainContext, MainThreadMessageServiceShape, MainThreadMessageOptions, IMainContext } from './extHost.protocol';
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { ILogService } from 'vs/platform/log/common/log';
function isMessageItem(item: any): item is vscode.MessageItem {
return item && item.title;
}
export class ExtHostMessageService {
private _proxy: MainThreadMessageServiceShape;
constructor(
mainContext: IMainContext,
@ILogService private readonly _logService: ILogService
) {
this._proxy = mainContext.getProxy(MainContext.MainThreadMessageService);
}
showMessage(extension: IExtensionDescription, severity: Severity, message: string, optionsOrFirstItem: vscode.MessageOptions | string | undefined, rest: string[]): Promise<string | undefined>;
showMessage(extension: IExtensionDescription, severity: Severity, message: string, optionsOrFirstItem: vscode.MessageOptions | vscode.MessageItem | undefined, rest: vscode.MessageItem[]): Promise<vscode.MessageItem | undefined>;
showMessage(extension: IExtensionDescription, severity: Severity, message: string, optionsOrFirstItem: vscode.MessageOptions | vscode.MessageItem | string | undefined, rest: Array<vscode.MessageItem | string>): Promise<string | vscode.MessageItem | undefined>;
showMessage(extension: IExtensionDescription, severity: Severity, message: string, optionsOrFirstItem: vscode.MessageOptions | string | vscode.MessageItem | undefined, rest: Array<string | vscode.MessageItem>): Promise<string | vscode.MessageItem | undefined> {
const options: MainThreadMessageOptions = { extension };
let items: (string | vscode.MessageItem)[];
if (typeof optionsOrFirstItem === 'string' || isMessageItem(optionsOrFirstItem)) {
items = [optionsOrFirstItem, ...rest];
} else {
options.modal = optionsOrFirstItem && optionsOrFirstItem.modal;
items = rest;
}
const commands: { title: string; isCloseAffordance: boolean; handle: number; }[] = [];
for (let handle = 0; handle < items.length; handle++) {
const command = items[handle];
if (typeof command === 'string') {
commands.push({ title: command, handle, isCloseAffordance: false });
} else if (typeof command === 'object') {
let { title, isCloseAffordance } = command;
commands.push({ title, isCloseAffordance: !!isCloseAffordance, handle });
} else {
this._logService.warn('Invalid message item:', command);
}
}
return this._proxy.$showMessage(severity, message, options, commands).then(handle => {
if (typeof handle === 'number') {
return items[handle];
}
return undefined;
});
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,188 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as types from 'vs/workbench/api/common/extHostTypes';
import * as vscode from 'vscode';
import { Event, Emitter } from 'vs/base/common/event';
import { ExtHostNotebookController } from 'vs/workbench/api/common/extHostNotebook';
import { ExtHostDocuments } from 'vs/workbench/api/common/extHostDocuments';
import { PrefixSumComputer } from 'vs/editor/common/viewModel/prefixSumComputer';
import { DisposableStore } from 'vs/base/common/lifecycle';
import { score } from 'vs/editor/common/modes/languageSelector';
import { CellKind } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { ResourceMap } from 'vs/base/common/map';
import { URI } from 'vs/base/common/uri';
import { generateUuid } from 'vs/base/common/uuid';
export class ExtHostNotebookConcatDocument implements vscode.NotebookConcatTextDocument {
private _disposables = new DisposableStore();
private _isClosed = false;
private _cells!: vscode.NotebookCell[];
private _cellUris!: ResourceMap<number>;
private _cellLengths!: PrefixSumComputer;
private _cellLines!: PrefixSumComputer;
private _versionId = 0;
private readonly _onDidChange = new Emitter<void>();
readonly onDidChange: Event<void> = this._onDidChange.event;
readonly uri = URI.from({ scheme: 'vscode-concat-doc', path: generateUuid() });
constructor(
extHostNotebooks: ExtHostNotebookController,
extHostDocuments: ExtHostDocuments,
private readonly _notebook: vscode.NotebookDocument,
private readonly _selector: vscode.DocumentSelector | undefined,
) {
this._init();
this._disposables.add(extHostDocuments.onDidChangeDocument(e => {
const cellIdx = this._cellUris.get(e.document.uri);
if (cellIdx !== undefined) {
this._cellLengths.changeValue(cellIdx, this._cells[cellIdx].document.getText().length + 1);
this._cellLines.changeValue(cellIdx, this._cells[cellIdx].document.lineCount);
this._versionId += 1;
this._onDidChange.fire(undefined);
}
}));
const documentChange = (document: vscode.NotebookDocument) => {
if (document === this._notebook) {
this._init();
this._versionId += 1;
this._onDidChange.fire(undefined);
}
};
this._disposables.add(extHostNotebooks.onDidChangeCellLanguage(e => documentChange(e.document)));
this._disposables.add(extHostNotebooks.onDidChangeNotebookCells(e => documentChange(e.document)));
}
dispose(): void {
this._disposables.dispose();
this._isClosed = true;
}
get isClosed() {
return this._isClosed;
}
private _init() {
this._cells = [];
this._cellUris = new ResourceMap();
const cellLengths: number[] = [];
const cellLineCounts: number[] = [];
for (const cell of this._notebook.cells) {
if (cell.cellKind === CellKind.Code && (!this._selector || score(this._selector, cell.uri, cell.language, true))) {
this._cellUris.set(cell.uri, this._cells.length);
this._cells.push(cell);
cellLengths.push(cell.document.getText().length + 1);
cellLineCounts.push(cell.document.lineCount);
}
}
this._cellLengths = new PrefixSumComputer(new Uint32Array(cellLengths));
this._cellLines = new PrefixSumComputer(new Uint32Array(cellLineCounts));
}
get version(): number {
return this._versionId;
}
getText(range?: vscode.Range): string {
if (!range) {
let result = '';
for (const cell of this._cells) {
result += cell.document.getText() + '\n';
}
// remove last newline again
result = result.slice(0, -1);
return result;
}
if (range.isEmpty) {
return '';
}
// get start and end locations and create substrings
const start = this.locationAt(range.start);
const end = this.locationAt(range.end);
const startCell = this._cells[this._cellUris.get(start.uri) ?? -1];
const endCell = this._cells[this._cellUris.get(end.uri) ?? -1];
if (!startCell || !endCell) {
return '';
} else if (startCell === endCell) {
return startCell.document.getText(new types.Range(start.range.start, end.range.end));
} else {
const a = startCell.document.getText(new types.Range(start.range.start, new types.Position(startCell.document.lineCount, 0)));
const b = endCell.document.getText(new types.Range(new types.Position(0, 0), end.range.end));
return a + '\n' + b;
}
}
offsetAt(position: vscode.Position): number {
const idx = this._cellLines.getIndexOf(position.line);
const offset1 = this._cellLengths.getAccumulatedValue(idx.index - 1);
const offset2 = this._cells[idx.index].document.offsetAt(position.with(idx.remainder));
return offset1 + offset2;
}
positionAt(locationOrOffset: vscode.Location | number): vscode.Position {
if (typeof locationOrOffset === 'number') {
const idx = this._cellLengths.getIndexOf(locationOrOffset);
const lineCount = this._cellLines.getAccumulatedValue(idx.index - 1);
return this._cells[idx.index].document.positionAt(idx.remainder).translate(lineCount);
}
const idx = this._cellUris.get(locationOrOffset.uri);
if (idx !== undefined) {
const line = this._cellLines.getAccumulatedValue(idx - 1);
return new types.Position(line + locationOrOffset.range.start.line, locationOrOffset.range.start.character);
}
// do better?
// return undefined;
return new types.Position(0, 0);
}
locationAt(positionOrRange: vscode.Range | vscode.Position): types.Location {
if (!types.Range.isRange(positionOrRange)) {
positionOrRange = new types.Range(<types.Position>positionOrRange, <types.Position>positionOrRange);
}
const startIdx = this._cellLines.getIndexOf(positionOrRange.start.line);
let endIdx = startIdx;
if (!positionOrRange.isEmpty) {
endIdx = this._cellLines.getIndexOf(positionOrRange.end.line);
}
const startPos = new types.Position(startIdx.remainder, positionOrRange.start.character);
const endPos = new types.Position(endIdx.remainder, positionOrRange.end.character);
const range = new types.Range(startPos, endPos);
const startCell = this._cells[startIdx.index];
return new types.Location(startCell.uri, <types.Range>startCell.document.validateRange(range));
}
contains(uri: vscode.Uri): boolean {
return this._cellUris.has(uri);
}
validateRange(range: vscode.Range): vscode.Range {
const start = this.validatePosition(range.start);
const end = this.validatePosition(range.end);
return range.with(start, end);
}
validatePosition(position: vscode.Position): vscode.Position {
const startIdx = this._cellLines.getIndexOf(position.line);
const cellPosition = new types.Position(startIdx.remainder, position.character);
const validCellPosition = this._cells[startIdx.index].document.validatePosition(cellPosition);
const line = this._cellLines.getAccumulatedValue(startIdx.index - 1);
return new types.Position(line + validCellPosition.line, validCellPosition.character);
}
}

View File

@ -0,0 +1,529 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Emitter, Event } from 'vs/base/common/event';
import { hash } from 'vs/base/common/hash';
import { Disposable, DisposableStore, dispose, IDisposable } from 'vs/base/common/lifecycle';
import { Schemas } from 'vs/base/common/network';
import { joinPath } from 'vs/base/common/resources';
import { ISplice } from 'vs/base/common/sequence';
import { URI } from 'vs/base/common/uri';
import * as UUID from 'vs/base/common/uuid';
import { CellKind, INotebookDocumentPropertiesChangeData, IWorkspaceCellEditDto, MainThreadBulkEditsShape, MainThreadNotebookShape, NotebookCellOutputsSplice, WorkspaceEditType } from 'vs/workbench/api/common/extHost.protocol';
import { ExtHostDocumentsAndEditors, IExtHostModelAddedData } from 'vs/workbench/api/common/extHostDocumentsAndEditors';
import { CellEditType, CellOutputKind, diff, IMainCellDto, IProcessedOutput, NotebookCellMetadata, NotebookCellsChangedEventDto, NotebookCellsChangeType, NotebookCellsSplice2, notebookDocumentMetadataDefaults } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import * as vscode from 'vscode';
import { Cache } from './cache';
interface IObservable<T> {
proxy: T;
onDidChange: Event<void>;
}
function getObservable<T extends Object>(obj: T): IObservable<T> {
const onDidChange = new Emitter<void>();
const proxy = new Proxy(obj, {
set(target: T, p: PropertyKey, value: any, _receiver: any): boolean {
target[p as keyof T] = value;
onDidChange.fire();
return true;
}
});
return {
proxy,
onDidChange: onDidChange.event
};
}
class RawContentChangeEvent {
constructor(readonly start: number, readonly deletedCount: number, readonly deletedItems: ExtHostCell[], readonly items: ExtHostCell[]) { }
static asApiEvent(event: RawContentChangeEvent): vscode.NotebookCellsChangeData {
return Object.freeze({
start: event.start,
deletedCount: event.deletedCount,
deletedItems: event.deletedItems.map(data => data.cell),
items: event.items.map(data => data.cell)
});
}
}
export class ExtHostCell extends Disposable {
static asModelAddData(notebook: vscode.NotebookDocument, cell: IMainCellDto): IExtHostModelAddedData {
return {
EOL: cell.eol,
lines: cell.source,
modeId: cell.language,
uri: cell.uri,
isDirty: false,
versionId: 1,
notebook
};
}
private _onDidDispose = new Emitter<void>();
readonly onDidDispose: Event<void> = this._onDidDispose.event;
private _onDidChangeOutputs = new Emitter<ISplice<IProcessedOutput>[]>();
readonly onDidChangeOutputs: Event<ISplice<IProcessedOutput>[]> = this._onDidChangeOutputs.event;
private _outputs: any[];
private _outputMapping = new WeakMap<vscode.CellOutput, string | undefined /* output ID */>();
private _metadata: vscode.NotebookCellMetadata;
private _metadataChangeListener: IDisposable;
readonly handle: number;
readonly uri: URI;
readonly cellKind: CellKind;
private _cell: vscode.NotebookCell | undefined;
constructor(
private readonly _mainThreadBulkEdits: MainThreadBulkEditsShape,
private readonly _notebook: ExtHostNotebookDocument,
private readonly _extHostDocument: ExtHostDocumentsAndEditors,
private readonly _cellData: IMainCellDto,
) {
super();
this.handle = _cellData.handle;
this.uri = URI.revive(_cellData.uri);
this.cellKind = _cellData.cellKind;
this._outputs = _cellData.outputs;
for (const output of this._outputs) {
this._outputMapping.set(output, output.outputId);
delete output.outputId;
}
const observableMetadata = getObservable(_cellData.metadata ?? {});
this._metadata = observableMetadata.proxy;
this._metadataChangeListener = this._register(observableMetadata.onDidChange(() => {
this._updateMetadata();
}));
}
get cell(): vscode.NotebookCell {
if (!this._cell) {
const that = this;
const document = this._extHostDocument.getDocument(this.uri)!.document;
this._cell = Object.freeze({
get index() { return that._notebook.getCellIndex(that); },
notebook: that._notebook.notebookDocument,
uri: that.uri,
cellKind: this._cellData.cellKind,
document,
get language() { return document.languageId; },
get outputs() { return that._outputs; },
set outputs(value) { that._updateOutputs(value); },
get metadata() { return that._metadata; },
set metadata(value) {
that.setMetadata(value);
that._updateMetadata();
},
});
}
return this._cell;
}
dispose() {
super.dispose();
this._onDidDispose.fire();
}
setOutputs(newOutputs: vscode.CellOutput[]): void {
this._outputs = newOutputs;
}
private _updateOutputs(newOutputs: vscode.CellOutput[]) {
const rawDiffs = diff<vscode.CellOutput>(this._outputs || [], newOutputs || [], (a) => {
return this._outputMapping.has(a);
});
const transformedDiffs: ISplice<IProcessedOutput>[] = rawDiffs.map(diff => {
for (let i = diff.start; i < diff.start + diff.deleteCount; i++) {
this._outputMapping.delete(this._outputs[i]);
}
return {
deleteCount: diff.deleteCount,
start: diff.start,
toInsert: diff.toInsert.map((output): IProcessedOutput => {
if (output.outputKind === CellOutputKind.Rich) {
const uuid = UUID.generateUuid();
this._outputMapping.set(output, uuid);
return { ...output, outputId: uuid };
}
this._outputMapping.set(output, undefined);
return output;
})
};
});
this._outputs = newOutputs;
this._onDidChangeOutputs.fire(transformedDiffs);
}
setMetadata(newMetadata: vscode.NotebookCellMetadata): void {
// Don't apply metadata defaults here, 'undefined' means 'inherit from document metadata'
this._metadataChangeListener.dispose();
const observableMetadata = getObservable(newMetadata);
this._metadata = observableMetadata.proxy;
this._metadataChangeListener = this._register(observableMetadata.onDidChange(() => {
this._updateMetadata();
}));
}
private _updateMetadata(): Promise<boolean> {
const index = this._notebook.notebookDocument.cells.indexOf(this.cell);
const edit: IWorkspaceCellEditDto = {
_type: WorkspaceEditType.Cell,
metadata: undefined,
resource: this._notebook.uri,
notebookVersionId: this._notebook.notebookDocument.version,
edit: { editType: CellEditType.Metadata, index, metadata: this._metadata }
};
return this._mainThreadBulkEdits.$tryApplyWorkspaceEdit({ edits: [edit] });
}
}
export interface INotebookEventEmitter {
emitModelChange(events: vscode.NotebookCellsChangeEvent): void;
emitDocumentMetadataChange(event: vscode.NotebookDocumentMetadataChangeEvent): void;
emitCellOutputsChange(event: vscode.NotebookCellOutputsChangeEvent): void;
emitCellLanguageChange(event: vscode.NotebookCellLanguageChangeEvent): void;
emitCellMetadataChange(event: vscode.NotebookCellMetadataChangeEvent): void;
}
function hashPath(resource: URI): string {
const str = resource.scheme === Schemas.file || resource.scheme === Schemas.untitled ? resource.fsPath : resource.toString();
return hash(str) + '';
}
export class ExtHostNotebookDocument extends Disposable {
private static _handlePool: number = 0;
readonly handle = ExtHostNotebookDocument._handlePool++;
private _cells: ExtHostCell[] = [];
private _cellDisposableMapping = new Map<number, DisposableStore>();
private _notebook: vscode.NotebookDocument | undefined;
private _metadata: Required<vscode.NotebookDocumentMetadata>;
private _metadataChangeListener: IDisposable;
private _versionId = 0;
private _isDirty: boolean = false;
private _backupCounter = 1;
private _backup?: vscode.NotebookDocumentBackup;
private _disposed = false;
private _languages: string[] = [];
private readonly _edits = new Cache<vscode.NotebookDocumentEditEvent>('notebook documents');
constructor(
private readonly _proxy: MainThreadNotebookShape,
private readonly _documentsAndEditors: ExtHostDocumentsAndEditors,
private readonly _mainThreadBulkEdits: MainThreadBulkEditsShape,
private readonly _emitter: INotebookEventEmitter,
private readonly _viewType: string,
private readonly _contentOptions: vscode.NotebookDocumentContentOptions,
metadata: Required<vscode.NotebookDocumentMetadata>,
public readonly uri: URI,
private readonly _storagePath: URI | undefined
) {
super();
const observableMetadata = getObservable(metadata);
this._metadata = observableMetadata.proxy;
this._metadataChangeListener = this._register(observableMetadata.onDidChange(() => {
this._tryUpdateMetadata();
}));
}
dispose() {
this._disposed = true;
super.dispose();
dispose(this._cellDisposableMapping.values());
}
private _updateMetadata(newMetadata: Required<vscode.NotebookDocumentMetadata>) {
this._metadataChangeListener.dispose();
newMetadata = {
...notebookDocumentMetadataDefaults,
...newMetadata
};
if (this._metadataChangeListener) {
this._metadataChangeListener.dispose();
}
const observableMetadata = getObservable(newMetadata);
this._metadata = observableMetadata.proxy;
this._metadataChangeListener = this._register(observableMetadata.onDidChange(() => {
this._tryUpdateMetadata();
}));
this._tryUpdateMetadata();
}
private _tryUpdateMetadata() {
const edit: IWorkspaceCellEditDto = {
_type: WorkspaceEditType.Cell,
metadata: undefined,
edit: { editType: CellEditType.DocumentMetadata, metadata: this._metadata },
resource: this.uri,
notebookVersionId: this.notebookDocument.version,
};
return this._mainThreadBulkEdits.$tryApplyWorkspaceEdit({ edits: [edit] });
}
get notebookDocument(): vscode.NotebookDocument {
if (!this._notebook) {
const that = this;
this._notebook = Object.freeze({
get uri() { return that.uri; },
get version() { return that._versionId; },
get fileName() { return that.uri.fsPath; },
get viewType() { return that._viewType; },
get isDirty() { return that._isDirty; },
get isUntitled() { return that.uri.scheme === Schemas.untitled; },
get cells(): ReadonlyArray<vscode.NotebookCell> { return that._cells.map(cell => cell.cell); },
get languages() { return that._languages; },
set languages(value: string[]) { that._trySetLanguages(value); },
get metadata() { return that._metadata; },
set metadata(value: Required<vscode.NotebookDocumentMetadata>) { that._updateMetadata(value); },
get contentOptions() { return that._contentOptions; }
});
}
return this._notebook;
}
private _trySetLanguages(newLanguages: string[]) {
this._languages = newLanguages;
this._proxy.$updateNotebookLanguages(this._viewType, this.uri, this._languages);
}
getNewBackupUri(): URI {
if (!this._storagePath) {
throw new Error('Backup requires a valid storage path');
}
const fileName = hashPath(this.uri) + (this._backupCounter++);
return joinPath(this._storagePath, fileName);
}
updateBackup(backup: vscode.NotebookDocumentBackup): void {
this._backup?.delete();
this._backup = backup;
}
disposeBackup(): void {
this._backup?.delete();
this._backup = undefined;
}
acceptDocumentPropertiesChanged(data: INotebookDocumentPropertiesChangeData) {
const newMetadata = {
...notebookDocumentMetadataDefaults,
...data.metadata
};
if (this._metadataChangeListener) {
this._metadataChangeListener.dispose();
}
const observableMetadata = getObservable(newMetadata);
this._metadata = observableMetadata.proxy;
this._metadataChangeListener = this._register(observableMetadata.onDidChange(() => {
this._tryUpdateMetadata();
}));
this._emitter.emitDocumentMetadataChange({ document: this.notebookDocument });
}
acceptModelChanged(event: NotebookCellsChangedEventDto, isDirty: boolean): void {
this._versionId = event.versionId;
this._isDirty = isDirty;
event.rawEvents.forEach(e => {
if (e.kind === NotebookCellsChangeType.Initialize) {
this._spliceNotebookCells(e.changes, true);
} if (e.kind === NotebookCellsChangeType.ModelChange) {
this._spliceNotebookCells(e.changes, false);
} else if (e.kind === NotebookCellsChangeType.Move) {
this._moveCell(e.index, e.newIdx);
} else if (e.kind === NotebookCellsChangeType.Output) {
this._setCellOutputs(e.index, e.outputs);
} else if (e.kind === NotebookCellsChangeType.ChangeLanguage) {
this._changeCellLanguage(e.index, e.language);
} else if (e.kind === NotebookCellsChangeType.ChangeCellMetadata) {
this._changeCellMetadata(e.index, e.metadata);
}
});
}
private _spliceNotebookCells(splices: NotebookCellsSplice2[], initialization: boolean): void {
if (this._disposed) {
return;
}
const contentChangeEvents: RawContentChangeEvent[] = [];
const addedCellDocuments: IExtHostModelAddedData[] = [];
const removedCellDocuments: URI[] = [];
splices.reverse().forEach(splice => {
const cellDtos = splice[2];
const newCells = cellDtos.map(cell => {
const extCell = new ExtHostCell(this._mainThreadBulkEdits, this, this._documentsAndEditors, cell);
if (!initialization) {
addedCellDocuments.push(ExtHostCell.asModelAddData(this.notebookDocument, cell));
}
if (!this._cellDisposableMapping.has(extCell.handle)) {
const store = new DisposableStore();
store.add(extCell);
this._cellDisposableMapping.set(extCell.handle, store);
}
const store = this._cellDisposableMapping.get(extCell.handle)!;
store.add(extCell.onDidChangeOutputs((diffs) => {
this.eventuallyUpdateCellOutputs(extCell, diffs);
}));
return extCell;
});
for (let j = splice[0]; j < splice[0] + splice[1]; j++) {
this._cellDisposableMapping.get(this._cells[j].handle)?.dispose();
this._cellDisposableMapping.delete(this._cells[j].handle);
}
const deletedItems = this._cells.splice(splice[0], splice[1], ...newCells);
for (let cell of deletedItems) {
removedCellDocuments.push(cell.uri);
}
contentChangeEvents.push(new RawContentChangeEvent(splice[0], splice[1], deletedItems, newCells));
});
this._documentsAndEditors.acceptDocumentsAndEditorsDelta({
addedDocuments: addedCellDocuments,
removedDocuments: removedCellDocuments
});
if (!initialization) {
this._emitter.emitModelChange({
document: this.notebookDocument,
changes: contentChangeEvents.map(RawContentChangeEvent.asApiEvent)
});
}
}
private _moveCell(index: number, newIdx: number): void {
const cells = this._cells.splice(index, 1);
this._cells.splice(newIdx, 0, ...cells);
const changes: vscode.NotebookCellsChangeData[] = [{
start: index,
deletedCount: 1,
deletedItems: cells.map(data => data.cell),
items: []
}, {
start: newIdx,
deletedCount: 0,
deletedItems: [],
items: cells.map(data => data.cell)
}];
this._emitter.emitModelChange({
document: this.notebookDocument,
changes
});
}
private _setCellOutputs(index: number, outputs: IProcessedOutput[]): void {
const cell = this._cells[index];
cell.setOutputs(outputs);
this._emitter.emitCellOutputsChange({ document: this.notebookDocument, cells: [cell.cell] });
}
private _changeCellLanguage(index: number, language: string): void {
const cell = this._cells[index];
const event: vscode.NotebookCellLanguageChangeEvent = { document: this.notebookDocument, cell: cell.cell, language };
this._emitter.emitCellLanguageChange(event);
}
private _changeCellMetadata(index: number, newMetadata: NotebookCellMetadata | undefined): void {
const cell = this._cells[index];
cell.setMetadata(newMetadata || {});
const event: vscode.NotebookCellMetadataChangeEvent = { document: this.notebookDocument, cell: cell.cell };
this._emitter.emitCellMetadataChange(event);
}
async eventuallyUpdateCellOutputs(cell: ExtHostCell, diffs: ISplice<IProcessedOutput>[]) {
const outputDtos: NotebookCellOutputsSplice[] = diffs.map(diff => {
const outputs = diff.toInsert;
return [diff.start, diff.deleteCount, outputs];
});
if (!outputDtos.length) {
return;
}
await this._proxy.$spliceNotebookCellOutputs(this._viewType, this.uri, cell.handle, outputDtos);
this._emitter.emitCellOutputsChange({
document: this.notebookDocument,
cells: [cell.cell]
});
}
getCell(cellHandle: number): ExtHostCell | undefined {
return this._cells.find(cell => cell.handle === cellHandle);
}
getCellIndex(cell: ExtHostCell): number {
return this._cells.indexOf(cell);
}
addEdit(item: vscode.NotebookDocumentEditEvent): number {
return this._edits.add([item]);
}
async undo(editId: number, isDirty: boolean): Promise<void> {
await this.getEdit(editId).undo();
// if (!isDirty) {
// this.disposeBackup();
// }
}
async redo(editId: number, isDirty: boolean): Promise<void> {
await this.getEdit(editId).redo();
// if (!isDirty) {
// this.disposeBackup();
// }
}
private getEdit(editId: number): vscode.NotebookDocumentEditEvent {
const edit = this._edits.get(editId, 0);
if (!edit) {
throw new Error('No edit found');
}
return edit;
}
disposeEdits(editIds: number[]): void {
for (const id of editIds) {
this._edits.delete(id);
}
}
}

View File

@ -0,0 +1,260 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { readonly } from 'vs/base/common/errors';
import { Emitter, Event } from 'vs/base/common/event';
import { Disposable } from 'vs/base/common/lifecycle';
import { MainThreadNotebookShape } from 'vs/workbench/api/common/extHost.protocol';
import * as extHostTypes from 'vs/workbench/api/common/extHostTypes';
import { addIdToOutput, CellEditType, ICellEditOperation, ICellReplaceEdit, INotebookEditData, notebookDocumentMetadataDefaults } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import * as vscode from 'vscode';
import { ExtHostNotebookDocument } from './extHostNotebookDocument';
class NotebookEditorCellEditBuilder implements vscode.NotebookEditorEdit {
private readonly _documentVersionId: number;
private _finalized: boolean = false;
private _collectedEdits: ICellEditOperation[] = [];
constructor(documentVersionId: number) {
this._documentVersionId = documentVersionId;
}
finalize(): INotebookEditData {
this._finalized = true;
return {
documentVersionId: this._documentVersionId,
cellEdits: this._collectedEdits
};
}
private _throwIfFinalized() {
if (this._finalized) {
throw new Error('Edit is only valid while callback runs');
}
}
replaceMetadata(value: vscode.NotebookDocumentMetadata): void {
this._throwIfFinalized();
this._collectedEdits.push({
editType: CellEditType.DocumentMetadata,
metadata: { ...notebookDocumentMetadataDefaults, ...value }
});
}
replaceCellMetadata(index: number, metadata: vscode.NotebookCellMetadata): void {
this._throwIfFinalized();
this._collectedEdits.push({
editType: CellEditType.Metadata,
index,
metadata
});
}
replaceCellOutput(index: number, outputs: (vscode.NotebookCellOutput | vscode.CellOutput)[]): void {
this._throwIfFinalized();
this._collectedEdits.push({
editType: CellEditType.Output,
index,
outputs: outputs.map(output => {
if (extHostTypes.NotebookCellOutput.isNotebookCellOutput(output)) {
return addIdToOutput(output.toJSON());
} else {
return addIdToOutput(output);
}
})
});
}
replaceCells(from: number, to: number, cells: vscode.NotebookCellData[]): void {
this._throwIfFinalized();
if (from === to && cells.length === 0) {
return;
}
this._collectedEdits.push({
editType: CellEditType.Replace,
index: from,
count: to - from,
cells: cells.map(data => {
return {
...data,
outputs: data.outputs.map(output => addIdToOutput(output)),
};
})
});
}
}
export class ExtHostNotebookEditor extends Disposable implements vscode.NotebookEditor {
//TODO@rebornix noop setter?
selection?: vscode.NotebookCell;
private _visibleRanges: vscode.NotebookCellRange[] = [];
private _viewColumn?: vscode.ViewColumn;
private _active: boolean = false;
private _visible: boolean = false;
private _kernel?: vscode.NotebookKernel;
private _onDidDispose = new Emitter<void>();
private _onDidReceiveMessage = new Emitter<any>();
readonly onDidDispose: Event<void> = this._onDidDispose.event;
readonly onDidReceiveMessage: vscode.Event<any> = this._onDidReceiveMessage.event;
private _hasDecorationsForKey: { [key: string]: boolean; } = Object.create(null);
constructor(
readonly id: string,
private readonly _viewType: string,
private readonly _proxy: MainThreadNotebookShape,
private readonly _webComm: vscode.NotebookCommunication,
readonly notebookData: ExtHostNotebookDocument,
) {
super();
this._register(this._webComm.onDidReceiveMessage(e => {
this._onDidReceiveMessage.fire(e);
}));
}
get viewColumn(): vscode.ViewColumn | undefined {
return this._viewColumn;
}
set viewColumn(_value) {
throw readonly('viewColumn');
}
get kernel() {
return this._kernel;
}
set kernel(_kernel: vscode.NotebookKernel | undefined) {
throw readonly('kernel');
}
_acceptKernel(kernel?: vscode.NotebookKernel) {
this._kernel = kernel;
}
get visible(): boolean {
return this._visible;
}
set visible(_state: boolean) {
throw readonly('visible');
}
_acceptVisibility(value: boolean) {
this._visible = value;
}
get visibleRanges() {
return this._visibleRanges;
}
set visibleRanges(_range: vscode.NotebookCellRange[]) {
throw readonly('visibleRanges');
}
_acceptVisibleRanges(value: vscode.NotebookCellRange[]): void {
this._visibleRanges = value;
}
get active(): boolean {
return this._active;
}
set active(_state: boolean) {
throw readonly('active');
}
_acceptActive(value: boolean) {
this._active = value;
}
get document(): vscode.NotebookDocument {
return this.notebookData.notebookDocument;
}
edit(callback: (editBuilder: NotebookEditorCellEditBuilder) => void): Thenable<boolean> {
const edit = new NotebookEditorCellEditBuilder(this.document.version);
callback(edit);
return this._applyEdit(edit.finalize());
}
private _applyEdit(editData: INotebookEditData): Promise<boolean> {
// return when there is nothing to do
if (editData.cellEdits.length === 0) {
return Promise.resolve(true);
}
const compressedEdits: ICellEditOperation[] = [];
let compressedEditsIndex = -1;
for (let i = 0; i < editData.cellEdits.length; i++) {
if (compressedEditsIndex < 0) {
compressedEdits.push(editData.cellEdits[i]);
compressedEditsIndex++;
continue;
}
const prevIndex = compressedEditsIndex;
const prev = compressedEdits[prevIndex];
if (prev.editType === CellEditType.Replace && editData.cellEdits[i].editType === CellEditType.Replace) {
const edit = editData.cellEdits[i];
if ((edit.editType !== CellEditType.DocumentMetadata && edit.editType !== CellEditType.Unknown) && prev.index === edit.index) {
prev.cells.push(...(editData.cellEdits[i] as ICellReplaceEdit).cells);
prev.count += (editData.cellEdits[i] as ICellReplaceEdit).count;
continue;
}
}
compressedEdits.push(editData.cellEdits[i]);
compressedEditsIndex++;
}
return this._proxy.$tryApplyEdits(this._viewType, this.document.uri, editData.documentVersionId, compressedEdits);
}
setDecorations(decorationType: vscode.NotebookEditorDecorationType, range: vscode.NotebookCellRange): void {
const willBeEmpty = (range.start === range.end);
if (willBeEmpty && !this._hasDecorationsForKey[decorationType.key]) {
// avoid no-op call to the renderer
return;
}
if (willBeEmpty) {
delete this._hasDecorationsForKey[decorationType.key];
} else {
this._hasDecorationsForKey[decorationType.key] = true;
}
return this._proxy.$trySetDecorations(
this.id,
range,
decorationType.key
);
}
revealRange(range: vscode.NotebookCellRange, revealType?: extHostTypes.NotebookEditorRevealType) {
this._proxy.$tryRevealRange(this.id, range, revealType || extHostTypes.NotebookEditorRevealType.Default);
}
async postMessage(message: any): Promise<boolean> {
return this._webComm.postMessage(message);
}
asWebviewUri(localResource: vscode.Uri): vscode.Uri {
return this._webComm.asWebviewUri(localResource);
}
dispose() {
this._onDidDispose.fire();
super.dispose();
}
}

View File

@ -0,0 +1,172 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { MainContext, MainThreadOutputServiceShape, ExtHostOutputServiceShape } from './extHost.protocol';
import type * as vscode from 'vscode';
import { URI } from 'vs/base/common/uri';
import { Event, Emitter } from 'vs/base/common/event';
import { Disposable } from 'vs/base/common/lifecycle';
import { VSBuffer } from 'vs/base/common/buffer';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService';
export abstract class AbstractExtHostOutputChannel extends Disposable implements vscode.OutputChannel {
readonly _id: Promise<string>;
private readonly _name: string;
protected readonly _proxy: MainThreadOutputServiceShape;
private _disposed: boolean;
private _offset: number;
protected readonly _onDidAppend: Emitter<void> = this._register(new Emitter<void>());
readonly onDidAppend: Event<void> = this._onDidAppend.event;
constructor(name: string, log: boolean, file: URI | undefined, proxy: MainThreadOutputServiceShape) {
super();
this._name = name;
this._proxy = proxy;
this._id = proxy.$register(this.name, log, file);
this._disposed = false;
this._offset = 0;
}
get name(): string {
return this._name;
}
append(value: string): void {
this.validate();
this._offset += value ? VSBuffer.fromString(value).byteLength : 0;
}
update(): void {
this._id.then(id => this._proxy.$update(id));
}
appendLine(value: string): void {
this.validate();
this.append(value + '\n');
}
clear(): void {
this.validate();
const till = this._offset;
this._id.then(id => this._proxy.$clear(id, till));
}
show(columnOrPreserveFocus?: vscode.ViewColumn | boolean, preserveFocus?: boolean): void {
this.validate();
this._id.then(id => this._proxy.$reveal(id, !!(typeof columnOrPreserveFocus === 'boolean' ? columnOrPreserveFocus : preserveFocus)));
}
hide(): void {
this.validate();
this._id.then(id => this._proxy.$close(id));
}
protected validate(): void {
if (this._disposed) {
throw new Error('Channel has been closed');
}
}
dispose(): void {
super.dispose();
if (!this._disposed) {
this._id
.then(id => this._proxy.$dispose(id))
.then(() => this._disposed = true);
}
}
}
export class ExtHostPushOutputChannel extends AbstractExtHostOutputChannel {
constructor(name: string, proxy: MainThreadOutputServiceShape) {
super(name, false, undefined, proxy);
}
append(value: string): void {
super.append(value);
this._id.then(id => this._proxy.$append(id, value));
this._onDidAppend.fire();
}
}
class ExtHostLogFileOutputChannel extends AbstractExtHostOutputChannel {
constructor(name: string, file: URI, proxy: MainThreadOutputServiceShape) {
super(name, true, file, proxy);
}
append(value: string): void {
throw new Error('Not supported');
}
}
export class LazyOutputChannel implements vscode.OutputChannel {
constructor(
readonly name: string,
private readonly _channel: Promise<AbstractExtHostOutputChannel>
) { }
append(value: string): void {
this._channel.then(channel => channel.append(value));
}
appendLine(value: string): void {
this._channel.then(channel => channel.appendLine(value));
}
clear(): void {
this._channel.then(channel => channel.clear());
}
show(columnOrPreserveFocus?: vscode.ViewColumn | boolean, preserveFocus?: boolean): void {
this._channel.then(channel => channel.show(columnOrPreserveFocus, preserveFocus));
}
hide(): void {
this._channel.then(channel => channel.hide());
}
dispose(): void {
this._channel.then(channel => channel.dispose());
}
}
export class ExtHostOutputService implements ExtHostOutputServiceShape {
readonly _serviceBrand: undefined;
protected readonly _proxy: MainThreadOutputServiceShape;
constructor(@IExtHostRpcService extHostRpc: IExtHostRpcService) {
this._proxy = extHostRpc.getProxy(MainContext.MainThreadOutputService);
}
$setVisibleChannel(channelId: string): void {
}
createOutputChannel(name: string): vscode.OutputChannel {
name = name.trim();
if (!name) {
throw new Error('illegal argument `name`. must not be falsy');
}
return new ExtHostPushOutputChannel(name, this._proxy);
}
createOutputChannelFromLogFile(name: string, file: URI): vscode.OutputChannel {
name = name.trim();
if (!name) {
throw new Error('illegal argument `name`. must not be falsy');
}
if (!file) {
throw new Error('illegal argument `file`. must not be falsy');
}
return new ExtHostLogFileOutputChannel(name, file, this._proxy);
}
}
export interface IExtHostOutputService extends ExtHostOutputService { }
export const IExtHostOutputService = createDecorator<IExtHostOutputService>('IExtHostOutputService');

View File

@ -0,0 +1,93 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ProgressOptions } from 'vscode';
import { MainThreadProgressShape, ExtHostProgressShape } from './extHost.protocol';
import { ProgressLocation } from './extHostTypeConverters';
import { Progress, IProgressStep } from 'vs/platform/progress/common/progress';
import { localize } from 'vs/nls';
import { CancellationTokenSource, CancellationToken } from 'vs/base/common/cancellation';
import { throttle } from 'vs/base/common/decorators';
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
export class ExtHostProgress implements ExtHostProgressShape {
private _proxy: MainThreadProgressShape;
private _handles: number = 0;
private _mapHandleToCancellationSource: Map<number, CancellationTokenSource> = new Map();
constructor(proxy: MainThreadProgressShape) {
this._proxy = proxy;
}
withProgress<R>(extension: IExtensionDescription, options: ProgressOptions, task: (progress: Progress<IProgressStep>, token: CancellationToken) => Thenable<R>): Thenable<R> {
const handle = this._handles++;
const { title, location, cancellable } = options;
const source = localize('extensionSource', "{0} (Extension)", extension.displayName || extension.name);
this._proxy.$startProgress(handle, { location: ProgressLocation.from(location), title, source, cancellable }, extension);
return this._withProgress(handle, task, !!cancellable);
}
private _withProgress<R>(handle: number, task: (progress: Progress<IProgressStep>, token: CancellationToken) => Thenable<R>, cancellable: boolean): Thenable<R> {
let source: CancellationTokenSource | undefined;
if (cancellable) {
source = new CancellationTokenSource();
this._mapHandleToCancellationSource.set(handle, source);
}
const progressEnd = (handle: number): void => {
this._proxy.$progressEnd(handle);
this._mapHandleToCancellationSource.delete(handle);
if (source) {
source.dispose();
}
};
let p: Thenable<R>;
try {
p = task(new ProgressCallback(this._proxy, handle), cancellable && source ? source.token : CancellationToken.None);
} catch (err) {
progressEnd(handle);
throw err;
}
p.then(result => progressEnd(handle), err => progressEnd(handle));
return p;
}
public $acceptProgressCanceled(handle: number): void {
const source = this._mapHandleToCancellationSource.get(handle);
if (source) {
source.cancel();
this._mapHandleToCancellationSource.delete(handle);
}
}
}
function mergeProgress(result: IProgressStep, currentValue: IProgressStep): IProgressStep {
result.message = currentValue.message;
if (typeof currentValue.increment === 'number') {
if (typeof result.increment === 'number') {
result.increment += currentValue.increment;
} else {
result.increment = currentValue.increment;
}
}
return result;
}
class ProgressCallback extends Progress<IProgressStep> {
constructor(private _proxy: MainThreadProgressShape, private _handle: number) {
super(p => this.throttledReport(p));
}
@throttle(100, (result: IProgressStep, currentValue: IProgressStep) => mergeProgress(result, currentValue), () => Object.create(null))
throttledReport(p: IProgressStep): void {
this._proxy.$progressReport(this._handle, p);
}
}

View File

@ -0,0 +1,617 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { asPromise } from 'vs/base/common/async';
import { CancellationToken } from 'vs/base/common/cancellation';
import { Emitter } from 'vs/base/common/event';
import { dispose, IDisposable } from 'vs/base/common/lifecycle';
import { ExtHostCommands } from 'vs/workbench/api/common/extHostCommands';
import { IExtHostWorkspaceProvider } from 'vs/workbench/api/common/extHostWorkspace';
import { InputBox, InputBoxOptions, QuickInput, QuickInputButton, QuickPick, QuickPickItem, QuickPickOptions, WorkspaceFolder, WorkspaceFolderPickOptions } from 'vscode';
import { ExtHostQuickOpenShape, IMainContext, MainContext, MainThreadQuickOpenShape, TransferQuickPickItems, TransferQuickInput, TransferQuickInputButton } from './extHost.protocol';
import { URI } from 'vs/base/common/uri';
import { ThemeIcon, QuickInputButtons } from 'vs/workbench/api/common/extHostTypes';
import { isPromiseCanceledError } from 'vs/base/common/errors';
import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions';
import { coalesce } from 'vs/base/common/arrays';
export type Item = string | QuickPickItem;
export class ExtHostQuickOpen implements ExtHostQuickOpenShape {
private _proxy: MainThreadQuickOpenShape;
private _workspace: IExtHostWorkspaceProvider;
private _commands: ExtHostCommands;
private _onDidSelectItem?: (handle: number) => void;
private _validateInput?: (input: string) => string | undefined | null | Thenable<string | undefined | null>;
private _sessions = new Map<number, ExtHostQuickInput>();
private _instances = 0;
constructor(mainContext: IMainContext, workspace: IExtHostWorkspaceProvider, commands: ExtHostCommands) {
this._proxy = mainContext.getProxy(MainContext.MainThreadQuickOpen);
this._workspace = workspace;
this._commands = commands;
}
showQuickPick(itemsOrItemsPromise: QuickPickItem[] | Promise<QuickPickItem[]>, enableProposedApi: boolean, options: QuickPickOptions & { canPickMany: true; }, token?: CancellationToken): Promise<QuickPickItem[] | undefined>;
showQuickPick(itemsOrItemsPromise: string[] | Promise<string[]>, enableProposedApi: boolean, options?: QuickPickOptions, token?: CancellationToken): Promise<string | undefined>;
showQuickPick(itemsOrItemsPromise: QuickPickItem[] | Promise<QuickPickItem[]>, enableProposedApi: boolean, options?: QuickPickOptions, token?: CancellationToken): Promise<QuickPickItem | undefined>;
showQuickPick(itemsOrItemsPromise: Item[] | Promise<Item[]>, enableProposedApi: boolean, options?: QuickPickOptions, token: CancellationToken = CancellationToken.None): Promise<Item | Item[] | undefined> {
// clear state from last invocation
this._onDidSelectItem = undefined;
const itemsPromise = <Promise<Item[]>>Promise.resolve(itemsOrItemsPromise);
const instance = ++this._instances;
const quickPickWidget = this._proxy.$show(instance, {
placeHolder: options && options.placeHolder,
matchOnDescription: options && options.matchOnDescription,
matchOnDetail: options && options.matchOnDetail,
ignoreFocusLost: options && options.ignoreFocusOut,
canPickMany: options && options.canPickMany
}, token);
const widgetClosedMarker = {};
const widgetClosedPromise = quickPickWidget.then(() => widgetClosedMarker);
return Promise.race([widgetClosedPromise, itemsPromise]).then(result => {
if (result === widgetClosedMarker) {
return undefined;
}
return itemsPromise.then(items => {
const pickItems: TransferQuickPickItems[] = [];
for (let handle = 0; handle < items.length; handle++) {
const item = items[handle];
let label: string;
let description: string | undefined;
let detail: string | undefined;
let picked: boolean | undefined;
let alwaysShow: boolean | undefined;
if (typeof item === 'string') {
label = item;
} else {
label = item.label;
description = item.description;
detail = item.detail;
picked = item.picked;
alwaysShow = item.alwaysShow;
}
pickItems.push({
label,
description,
handle,
detail,
picked,
alwaysShow
});
}
// handle selection changes
if (options && typeof options.onDidSelectItem === 'function') {
this._onDidSelectItem = (handle) => {
options.onDidSelectItem!(items[handle]);
};
}
// show items
this._proxy.$setItems(instance, pickItems);
return quickPickWidget.then(handle => {
if (typeof handle === 'number') {
return items[handle];
} else if (Array.isArray(handle)) {
return handle.map(h => items[h]);
}
return undefined;
});
});
}).then(undefined, err => {
if (isPromiseCanceledError(err)) {
return undefined;
}
this._proxy.$setError(instance, err);
return Promise.reject(err);
});
}
$onItemSelected(handle: number): void {
if (this._onDidSelectItem) {
this._onDidSelectItem(handle);
}
}
// ---- input
showInput(options?: InputBoxOptions, token: CancellationToken = CancellationToken.None): Promise<string | undefined> {
// global validate fn used in callback below
this._validateInput = options ? options.validateInput : undefined;
return this._proxy.$input(options, typeof this._validateInput === 'function', token)
.then(undefined, err => {
if (isPromiseCanceledError(err)) {
return undefined;
}
return Promise.reject(err);
});
}
$validateInput(input: string): Promise<string | null | undefined> {
if (this._validateInput) {
return asPromise(() => this._validateInput!(input));
}
return Promise.resolve(undefined);
}
// ---- workspace folder picker
async showWorkspaceFolderPick(options?: WorkspaceFolderPickOptions, token = CancellationToken.None): Promise<WorkspaceFolder | undefined> {
const selectedFolder = await this._commands.executeCommand<WorkspaceFolder>('_workbench.pickWorkspaceFolder', [options]);
if (!selectedFolder) {
return undefined;
}
const workspaceFolders = await this._workspace.getWorkspaceFolders2();
if (!workspaceFolders) {
return undefined;
}
return workspaceFolders.find(folder => folder.uri.toString() === selectedFolder.uri.toString());
}
// ---- QuickInput
createQuickPick<T extends QuickPickItem>(extensionId: ExtensionIdentifier, enableProposedApi: boolean): QuickPick<T> {
const session: ExtHostQuickPick<T> = new ExtHostQuickPick(this._proxy, extensionId, enableProposedApi, () => this._sessions.delete(session._id));
this._sessions.set(session._id, session);
return session;
}
createInputBox(extensionId: ExtensionIdentifier): InputBox {
const session: ExtHostInputBox = new ExtHostInputBox(this._proxy, extensionId, () => this._sessions.delete(session._id));
this._sessions.set(session._id, session);
return session;
}
$onDidChangeValue(sessionId: number, value: string): void {
const session = this._sessions.get(sessionId);
if (session) {
session._fireDidChangeValue(value);
}
}
$onDidAccept(sessionId: number): void {
const session = this._sessions.get(sessionId);
if (session) {
session._fireDidAccept();
}
}
$onDidChangeActive(sessionId: number, handles: number[]): void {
const session = this._sessions.get(sessionId);
if (session instanceof ExtHostQuickPick) {
session._fireDidChangeActive(handles);
}
}
$onDidChangeSelection(sessionId: number, handles: number[]): void {
const session = this._sessions.get(sessionId);
if (session instanceof ExtHostQuickPick) {
session._fireDidChangeSelection(handles);
}
}
$onDidTriggerButton(sessionId: number, handle: number): void {
const session = this._sessions.get(sessionId);
if (session) {
session._fireDidTriggerButton(handle);
}
}
$onDidHide(sessionId: number): void {
const session = this._sessions.get(sessionId);
if (session) {
session._fireDidHide();
}
}
}
class ExtHostQuickInput implements QuickInput {
private static _nextId = 1;
_id = ExtHostQuickPick._nextId++;
private _title: string | undefined;
private _steps: number | undefined;
private _totalSteps: number | undefined;
private _visible = false;
private _expectingHide = false;
private _enabled = true;
private _busy = false;
private _ignoreFocusOut = true;
private _value = '';
private _placeholder: string | undefined;
private _buttons: QuickInputButton[] = [];
private _handlesToButtons = new Map<number, QuickInputButton>();
private readonly _onDidAcceptEmitter = new Emitter<void>();
private readonly _onDidChangeValueEmitter = new Emitter<string>();
private readonly _onDidTriggerButtonEmitter = new Emitter<QuickInputButton>();
private readonly _onDidHideEmitter = new Emitter<void>();
private _updateTimeout: any;
private _pendingUpdate: TransferQuickInput = { id: this._id };
private _disposed = false;
protected _disposables: IDisposable[] = [
this._onDidTriggerButtonEmitter,
this._onDidHideEmitter,
this._onDidAcceptEmitter,
this._onDidChangeValueEmitter
];
constructor(protected _proxy: MainThreadQuickOpenShape, protected _extensionId: ExtensionIdentifier, private _onDidDispose: () => void) {
}
get title() {
return this._title;
}
set title(title: string | undefined) {
this._title = title;
this.update({ title });
}
get step() {
return this._steps;
}
set step(step: number | undefined) {
this._steps = step;
this.update({ step });
}
get totalSteps() {
return this._totalSteps;
}
set totalSteps(totalSteps: number | undefined) {
this._totalSteps = totalSteps;
this.update({ totalSteps });
}
get enabled() {
return this._enabled;
}
set enabled(enabled: boolean) {
this._enabled = enabled;
this.update({ enabled });
}
get busy() {
return this._busy;
}
set busy(busy: boolean) {
this._busy = busy;
this.update({ busy });
}
get ignoreFocusOut() {
return this._ignoreFocusOut;
}
set ignoreFocusOut(ignoreFocusOut: boolean) {
this._ignoreFocusOut = ignoreFocusOut;
this.update({ ignoreFocusOut });
}
get value() {
return this._value;
}
set value(value: string) {
this._value = value;
this.update({ value });
}
get placeholder() {
return this._placeholder;
}
set placeholder(placeholder: string | undefined) {
this._placeholder = placeholder;
this.update({ placeholder });
}
onDidChangeValue = this._onDidChangeValueEmitter.event;
onDidAccept = this._onDidAcceptEmitter.event;
get buttons() {
return this._buttons;
}
set buttons(buttons: QuickInputButton[]) {
this._buttons = buttons.slice();
this._handlesToButtons.clear();
buttons.forEach((button, i) => {
const handle = button === QuickInputButtons.Back ? -1 : i;
this._handlesToButtons.set(handle, button);
});
this.update({
buttons: buttons.map<TransferQuickInputButton>((button, i) => ({
iconPath: getIconUris(button.iconPath),
tooltip: button.tooltip,
handle: button === QuickInputButtons.Back ? -1 : i,
}))
});
}
onDidTriggerButton = this._onDidTriggerButtonEmitter.event;
show(): void {
this._visible = true;
this._expectingHide = true;
this.update({ visible: true });
}
hide(): void {
this._visible = false;
this.update({ visible: false });
}
onDidHide = this._onDidHideEmitter.event;
_fireDidAccept() {
this._onDidAcceptEmitter.fire();
}
_fireDidChangeValue(value: string) {
this._value = value;
this._onDidChangeValueEmitter.fire(value);
}
_fireDidTriggerButton(handle: number) {
const button = this._handlesToButtons.get(handle);
if (button) {
this._onDidTriggerButtonEmitter.fire(button);
}
}
_fireDidHide() {
if (this._expectingHide) {
this._expectingHide = false;
this._onDidHideEmitter.fire();
}
}
dispose(): void {
if (this._disposed) {
return;
}
this._disposed = true;
this._fireDidHide();
this._disposables = dispose(this._disposables);
if (this._updateTimeout) {
clearTimeout(this._updateTimeout);
this._updateTimeout = undefined;
}
this._onDidDispose();
this._proxy.$dispose(this._id);
}
protected update(properties: Record<string, any>): void {
if (this._disposed) {
return;
}
for (const key of Object.keys(properties)) {
const value = properties[key];
this._pendingUpdate[key] = value === undefined ? null : value;
}
if ('visible' in this._pendingUpdate) {
if (this._updateTimeout) {
clearTimeout(this._updateTimeout);
this._updateTimeout = undefined;
}
this.dispatchUpdate();
} else if (this._visible && !this._updateTimeout) {
// Defer the update so that multiple changes to setters dont cause a redraw each
this._updateTimeout = setTimeout(() => {
this._updateTimeout = undefined;
this.dispatchUpdate();
}, 0);
}
}
private dispatchUpdate() {
this._proxy.$createOrUpdate(this._pendingUpdate);
this._pendingUpdate = { id: this._id };
}
}
function getIconUris(iconPath: QuickInputButton['iconPath']): { dark: URI, light?: URI } | { id: string } {
if (iconPath instanceof ThemeIcon) {
return { id: iconPath.id };
}
const dark = getDarkIconUri(iconPath as URI | { light: URI; dark: URI; });
const light = getLightIconUri(iconPath as URI | { light: URI; dark: URI; });
return { dark, light };
}
function getLightIconUri(iconPath: URI | { light: URI; dark: URI; }) {
return typeof iconPath === 'object' && 'light' in iconPath ? iconPath.light : iconPath;
}
function getDarkIconUri(iconPath: URI | { light: URI; dark: URI; }) {
return typeof iconPath === 'object' && 'dark' in iconPath ? iconPath.dark : iconPath;
}
class ExtHostQuickPick<T extends QuickPickItem> extends ExtHostQuickInput implements QuickPick<T> {
private _items: T[] = [];
private _handlesToItems = new Map<number, T>();
private _itemsToHandles = new Map<T, number>();
private _canSelectMany = false;
private _matchOnDescription = true;
private _matchOnDetail = true;
private _sortByLabel = true;
private _activeItems: T[] = [];
private readonly _onDidChangeActiveEmitter = new Emitter<T[]>();
private _selectedItems: T[] = [];
private readonly _onDidChangeSelectionEmitter = new Emitter<T[]>();
constructor(proxy: MainThreadQuickOpenShape, extensionId: ExtensionIdentifier, enableProposedApi: boolean, onDispose: () => void) {
super(proxy, extensionId, onDispose);
this._disposables.push(
this._onDidChangeActiveEmitter,
this._onDidChangeSelectionEmitter,
);
this.update({ type: 'quickPick' });
}
get items() {
return this._items;
}
set items(items: T[]) {
this._items = items.slice();
this._handlesToItems.clear();
this._itemsToHandles.clear();
items.forEach((item, i) => {
this._handlesToItems.set(i, item);
this._itemsToHandles.set(item, i);
});
this.update({
items: items.map((item, i) => ({
label: item.label,
description: item.description,
handle: i,
detail: item.detail,
picked: item.picked,
alwaysShow: item.alwaysShow
}))
});
}
get canSelectMany() {
return this._canSelectMany;
}
set canSelectMany(canSelectMany: boolean) {
this._canSelectMany = canSelectMany;
this.update({ canSelectMany });
}
get matchOnDescription() {
return this._matchOnDescription;
}
set matchOnDescription(matchOnDescription: boolean) {
this._matchOnDescription = matchOnDescription;
this.update({ matchOnDescription });
}
get matchOnDetail() {
return this._matchOnDetail;
}
set matchOnDetail(matchOnDetail: boolean) {
this._matchOnDetail = matchOnDetail;
this.update({ matchOnDetail });
}
get sortByLabel() {
return this._sortByLabel;
}
set sortByLabel(sortByLabel: boolean) {
this._sortByLabel = sortByLabel;
this.update({ sortByLabel });
}
get activeItems() {
return this._activeItems;
}
set activeItems(activeItems: T[]) {
this._activeItems = activeItems.filter(item => this._itemsToHandles.has(item));
this.update({ activeItems: this._activeItems.map(item => this._itemsToHandles.get(item)) });
}
onDidChangeActive = this._onDidChangeActiveEmitter.event;
get selectedItems() {
return this._selectedItems;
}
set selectedItems(selectedItems: T[]) {
this._selectedItems = selectedItems.filter(item => this._itemsToHandles.has(item));
this.update({ selectedItems: this._selectedItems.map(item => this._itemsToHandles.get(item)) });
}
onDidChangeSelection = this._onDidChangeSelectionEmitter.event;
_fireDidChangeActive(handles: number[]) {
const items = coalesce(handles.map(handle => this._handlesToItems.get(handle)));
this._activeItems = items;
this._onDidChangeActiveEmitter.fire(items);
}
_fireDidChangeSelection(handles: number[]) {
const items = coalesce(handles.map(handle => this._handlesToItems.get(handle)));
this._selectedItems = items;
this._onDidChangeSelectionEmitter.fire(items);
}
}
class ExtHostInputBox extends ExtHostQuickInput implements InputBox {
private _password = false;
private _prompt: string | undefined;
private _validationMessage: string | undefined;
constructor(proxy: MainThreadQuickOpenShape, extensionId: ExtensionIdentifier, onDispose: () => void) {
super(proxy, extensionId, onDispose);
this.update({ type: 'inputBox' });
}
get password() {
return this._password;
}
set password(password: boolean) {
this._password = password;
this.update({ password });
}
get prompt() {
return this._prompt;
}
set prompt(prompt: string | undefined) {
this._prompt = prompt;
this.update({ prompt });
}
get validationMessage() {
return this._validationMessage;
}
set validationMessage(validationMessage: string | undefined) {
this._validationMessage = validationMessage;
this.update({ validationMessage });
}
}

View File

@ -0,0 +1,293 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { TernarySearchTree } from 'vs/base/common/map';
import { URI } from 'vs/base/common/uri';
import { MainThreadTelemetryShape, MainContext } from 'vs/workbench/api/common/extHost.protocol';
import { ExtHostConfigProvider, IExtHostConfiguration } from 'vs/workbench/api/common/extHostConfiguration';
import { nullExtensionDescription } from 'vs/workbench/services/extensions/common/extensions';
import { ExtensionDescriptionRegistry } from 'vs/workbench/services/extensions/common/extensionDescriptionRegistry';
import * as vscode from 'vscode';
import { ExtensionIdentifier, IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { IExtensionApiFactory } from 'vs/workbench/api/common/extHost.api.impl';
import { IExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService';
import { IExtHostInitDataService } from 'vs/workbench/api/common/extHostInitDataService';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IExtHostExtensionService } from 'vs/workbench/api/common/extHostExtensionService';
import { platform } from 'vs/base/common/process';
import { ILogService } from 'vs/platform/log/common/log';
interface LoadFunction {
(request: string): any;
}
interface INodeModuleFactory {
readonly nodeModuleName: string | string[];
load(request: string, parent: URI, original: LoadFunction): any;
alternativeModuleName?(name: string): string | undefined;
}
export abstract class RequireInterceptor {
protected readonly _factories: Map<string, INodeModuleFactory>;
protected readonly _alternatives: ((moduleName: string) => string | undefined)[];
constructor(
private _apiFactory: IExtensionApiFactory,
private _extensionRegistry: ExtensionDescriptionRegistry,
@IInstantiationService private readonly _instaService: IInstantiationService,
@IExtHostConfiguration private readonly _extHostConfiguration: IExtHostConfiguration,
@IExtHostExtensionService private readonly _extHostExtensionService: IExtHostExtensionService,
@IExtHostInitDataService private readonly _initData: IExtHostInitDataService,
@ILogService private readonly _logService: ILogService,
) {
this._factories = new Map<string, INodeModuleFactory>();
this._alternatives = [];
}
async install(): Promise<void> {
this._installInterceptor();
const configProvider = await this._extHostConfiguration.getConfigProvider();
const extensionPaths = await this._extHostExtensionService.getExtensionPathIndex();
this.register(new VSCodeNodeModuleFactory(this._apiFactory, extensionPaths, this._extensionRegistry, configProvider, this._logService));
this.register(this._instaService.createInstance(KeytarNodeModuleFactory));
if (this._initData.remote.isRemote) {
this.register(this._instaService.createInstance(OpenNodeModuleFactory, extensionPaths, this._initData.environment.appUriScheme));
}
}
protected abstract _installInterceptor(): void;
public register(interceptor: INodeModuleFactory): void {
if (Array.isArray(interceptor.nodeModuleName)) {
for (let moduleName of interceptor.nodeModuleName) {
this._factories.set(moduleName, interceptor);
}
} else {
this._factories.set(interceptor.nodeModuleName, interceptor);
}
if (typeof interceptor.alternativeModuleName === 'function') {
this._alternatives.push((moduleName) => {
return interceptor.alternativeModuleName!(moduleName);
});
}
}
}
//#region --- vscode-module
class VSCodeNodeModuleFactory implements INodeModuleFactory {
public readonly nodeModuleName = 'vscode';
private readonly _extApiImpl = new Map<string, typeof vscode>();
private _defaultApiImpl?: typeof vscode;
constructor(
private readonly _apiFactory: IExtensionApiFactory,
private readonly _extensionPaths: TernarySearchTree<string, IExtensionDescription>,
private readonly _extensionRegistry: ExtensionDescriptionRegistry,
private readonly _configProvider: ExtHostConfigProvider,
private readonly _logService: ILogService,
) {
}
public load(_request: string, parent: URI): any {
// get extension id from filename and api for extension
const ext = this._extensionPaths.findSubstr(parent.fsPath);
if (ext) {
let apiImpl = this._extApiImpl.get(ExtensionIdentifier.toKey(ext.identifier));
if (!apiImpl) {
apiImpl = this._apiFactory(ext, this._extensionRegistry, this._configProvider);
this._extApiImpl.set(ExtensionIdentifier.toKey(ext.identifier), apiImpl);
}
return apiImpl;
}
// fall back to a default implementation
if (!this._defaultApiImpl) {
let extensionPathsPretty = '';
this._extensionPaths.forEach((value, index) => extensionPathsPretty += `\t${index} -> ${value.identifier.value}\n`);
this._logService.warn(`Could not identify extension for 'vscode' require call from ${parent.fsPath}. These are the extension path mappings: \n${extensionPathsPretty}`);
this._defaultApiImpl = this._apiFactory(nullExtensionDescription, this._extensionRegistry, this._configProvider);
}
return this._defaultApiImpl;
}
}
//#endregion
//#region --- keytar-module
interface IKeytarModule {
getPassword(service: string, account: string): Promise<string | null>;
setPassword(service: string, account: string, password: string): Promise<void>;
deletePassword(service: string, account: string): Promise<boolean>;
findPassword(service: string): Promise<string | null>;
findCredentials(service: string): Promise<Array<{ account: string, password: string }>>;
}
class KeytarNodeModuleFactory implements INodeModuleFactory {
public readonly nodeModuleName: string = 'keytar';
private alternativeNames: Set<string> | undefined;
private _impl: IKeytarModule;
constructor(
@IExtHostRpcService rpcService: IExtHostRpcService,
@IExtHostInitDataService initData: IExtHostInitDataService,
) {
const { environment } = initData;
const mainThreadKeytar = rpcService.getProxy(MainContext.MainThreadKeytar);
if (environment.appRoot) {
let appRoot = environment.appRoot.fsPath;
if (platform === 'win32') {
appRoot = appRoot.replace(/\\/g, '/');
}
if (appRoot[appRoot.length - 1] === '/') {
appRoot = appRoot.substr(0, appRoot.length - 1);
}
this.alternativeNames = new Set();
this.alternativeNames.add(`${appRoot}/node_modules.asar/keytar`);
this.alternativeNames.add(`${appRoot}/node_modules/keytar`);
}
this._impl = {
getPassword: (service: string, account: string): Promise<string | null> => {
return mainThreadKeytar.$getPassword(service, account);
},
setPassword: (service: string, account: string, password: string): Promise<void> => {
return mainThreadKeytar.$setPassword(service, account, password);
},
deletePassword: (service: string, account: string): Promise<boolean> => {
return mainThreadKeytar.$deletePassword(service, account);
},
findPassword: (service: string): Promise<string | null> => {
return mainThreadKeytar.$findPassword(service);
},
findCredentials(service: string): Promise<Array<{ account: string, password: string }>> {
return mainThreadKeytar.$findCredentials(service);
}
};
}
public load(_request: string, _parent: URI): any {
return this._impl;
}
public alternativeModuleName(name: string): string | undefined {
const length = name.length;
// We need at least something like: `?/keytar` which requires
// more than 7 characters.
if (length <= 7 || !this.alternativeNames) {
return undefined;
}
const sep = length - 7;
if ((name.charAt(sep) === '/' || name.charAt(sep) === '\\') && name.endsWith('keytar')) {
name = name.replace(/\\/g, '/');
if (this.alternativeNames.has(name)) {
return 'keytar';
}
}
return undefined;
}
}
//#endregion
//#region --- opn/open-module
interface OpenOptions {
wait: boolean;
app: string | string[];
}
interface IOriginalOpen {
(target: string, options?: OpenOptions): Thenable<any>;
}
interface IOpenModule {
(target: string, options?: OpenOptions): Thenable<void>;
}
class OpenNodeModuleFactory implements INodeModuleFactory {
public readonly nodeModuleName: string[] = ['open', 'opn'];
private _extensionId: string | undefined;
private _original?: IOriginalOpen;
private _impl: IOpenModule;
private _mainThreadTelemetry: MainThreadTelemetryShape;
constructor(
private readonly _extensionPaths: TernarySearchTree<string, IExtensionDescription>,
private readonly _appUriScheme: string,
@IExtHostRpcService rpcService: IExtHostRpcService,
) {
this._mainThreadTelemetry = rpcService.getProxy(MainContext.MainThreadTelemetry);
const mainThreadWindow = rpcService.getProxy(MainContext.MainThreadWindow);
this._impl = (target, options) => {
const uri: URI = URI.parse(target);
// If we have options use the original method.
if (options) {
return this.callOriginal(target, options);
}
if (uri.scheme === 'http' || uri.scheme === 'https') {
return mainThreadWindow.$openUri(uri, target, { allowTunneling: true });
} else if (uri.scheme === 'mailto' || uri.scheme === this._appUriScheme) {
return mainThreadWindow.$openUri(uri, target, {});
}
return this.callOriginal(target, options);
};
}
public load(request: string, parent: URI, original: LoadFunction): any {
// get extension id from filename and api for extension
const extension = this._extensionPaths.findSubstr(parent.fsPath);
if (extension) {
this._extensionId = extension.identifier.value;
this.sendShimmingTelemetry();
}
this._original = original(request);
return this._impl;
}
private callOriginal(target: string, options: OpenOptions | undefined): Thenable<any> {
this.sendNoForwardTelemetry();
return this._original!(target, options);
}
private sendShimmingTelemetry(): void {
if (!this._extensionId) {
return;
}
type ShimmingOpenClassification = {
extension: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
};
this._mainThreadTelemetry.$publicLog2<{ extension: string }, ShimmingOpenClassification>('shimming.open', { extension: this._extensionId });
}
private sendNoForwardTelemetry(): void {
if (!this._extensionId) {
return;
}
type ShimmingOpenCallNoForwardClassification = {
extension: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
};
this._mainThreadTelemetry.$publicLog2<{ extension: string }, ShimmingOpenCallNoForwardClassification>('shimming.open.call.noForward', { extension: this._extensionId });
}
}
//#endregion

View File

@ -0,0 +1,29 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ProxyIdentifier, IRPCProtocol } from 'vs/workbench/services/extensions/common/proxyIdentifier';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
export const IExtHostRpcService = createDecorator<IExtHostRpcService>('IExtHostRpcService');
export interface IExtHostRpcService extends IRPCProtocol {
readonly _serviceBrand: undefined;
}
export class ExtHostRpcService implements IExtHostRpcService {
readonly _serviceBrand: undefined;
readonly getProxy: <T>(identifier: ProxyIdentifier<T>) => T;
readonly set: <T, R extends T> (identifier: ProxyIdentifier<T>, instance: R) => R;
readonly assertRegistered: (identifiers: ProxyIdentifier<any>[]) => void;
readonly drain: () => Promise<void>;
constructor(rpcProtocol: IRPCProtocol) {
this.getProxy = rpcProtocol.getProxy.bind(rpcProtocol);
this.set = rpcProtocol.set.bind(rpcProtocol);
this.assertRegistered = rpcProtocol.assertRegistered.bind(rpcProtocol);
this.drain = rpcProtocol.drain.bind(rpcProtocol);
}
}

View File

@ -0,0 +1,732 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { URI, UriComponents } from 'vs/base/common/uri';
import { Event, Emitter } from 'vs/base/common/event';
import { debounce } from 'vs/base/common/decorators';
import { DisposableStore, IDisposable, MutableDisposable } from 'vs/base/common/lifecycle';
import { asPromise } from 'vs/base/common/async';
import { ExtHostCommands } from 'vs/workbench/api/common/extHostCommands';
import { MainContext, MainThreadSCMShape, SCMRawResource, SCMRawResourceSplice, SCMRawResourceSplices, IMainContext, ExtHostSCMShape, ICommandDto, MainThreadTelemetryShape, SCMGroupFeatures } from './extHost.protocol';
import { sortedDiff, equals } from 'vs/base/common/arrays';
import { comparePaths } from 'vs/base/common/comparers';
import type * as vscode from 'vscode';
import { ISplice } from 'vs/base/common/sequence';
import { ILogService } from 'vs/platform/log/common/log';
import { CancellationToken } from 'vs/base/common/cancellation';
import { ExtensionIdentifier, IExtensionDescription } from 'vs/platform/extensions/common/extensions';
type ProviderHandle = number;
type GroupHandle = number;
type ResourceStateHandle = number;
function getIconResource(decorations?: vscode.SourceControlResourceThemableDecorations): vscode.Uri | undefined {
if (!decorations) {
return undefined;
} else if (typeof decorations.iconPath === 'string') {
return URI.file(decorations.iconPath);
} else {
return decorations.iconPath;
}
}
function compareResourceThemableDecorations(a: vscode.SourceControlResourceThemableDecorations, b: vscode.SourceControlResourceThemableDecorations): number {
if (!a.iconPath && !b.iconPath) {
return 0;
} else if (!a.iconPath) {
return -1;
} else if (!b.iconPath) {
return 1;
}
const aPath = typeof a.iconPath === 'string' ? a.iconPath : a.iconPath.fsPath;
const bPath = typeof b.iconPath === 'string' ? b.iconPath : b.iconPath.fsPath;
return comparePaths(aPath, bPath);
}
function compareResourceStatesDecorations(a: vscode.SourceControlResourceDecorations, b: vscode.SourceControlResourceDecorations): number {
let result = 0;
if (a.strikeThrough !== b.strikeThrough) {
return a.strikeThrough ? 1 : -1;
}
if (a.faded !== b.faded) {
return a.faded ? 1 : -1;
}
if (a.tooltip !== b.tooltip) {
return (a.tooltip || '').localeCompare(b.tooltip || '');
}
result = compareResourceThemableDecorations(a, b);
if (result !== 0) {
return result;
}
if (a.light && b.light) {
result = compareResourceThemableDecorations(a.light, b.light);
} else if (a.light) {
return 1;
} else if (b.light) {
return -1;
}
if (result !== 0) {
return result;
}
if (a.dark && b.dark) {
result = compareResourceThemableDecorations(a.dark, b.dark);
} else if (a.dark) {
return 1;
} else if (b.dark) {
return -1;
}
return result;
}
function compareResourceStates(a: vscode.SourceControlResourceState, b: vscode.SourceControlResourceState): number {
let result = comparePaths(a.resourceUri.fsPath, b.resourceUri.fsPath, true);
if (result !== 0) {
return result;
}
if (a.decorations && b.decorations) {
result = compareResourceStatesDecorations(a.decorations, b.decorations);
} else if (a.decorations) {
return 1;
} else if (b.decorations) {
return -1;
}
return result;
}
function compareArgs(a: any[], b: any[]): boolean {
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
function commandEquals(a: vscode.Command, b: vscode.Command): boolean {
return a.command === b.command
&& a.title === b.title
&& a.tooltip === b.tooltip
&& (a.arguments && b.arguments ? compareArgs(a.arguments, b.arguments) : a.arguments === b.arguments);
}
function commandListEquals(a: readonly vscode.Command[], b: readonly vscode.Command[]): boolean {
return equals(a, b, commandEquals);
}
export interface IValidateInput {
(value: string, cursorPosition: number): vscode.ProviderResult<vscode.SourceControlInputBoxValidation | undefined | null>;
}
export class ExtHostSCMInputBox implements vscode.SourceControlInputBox {
private _value: string = '';
get value(): string {
return this._value;
}
set value(value: string) {
this._proxy.$setInputBoxValue(this._sourceControlHandle, value);
this.updateValue(value);
}
private readonly _onDidChange = new Emitter<string>();
get onDidChange(): Event<string> {
return this._onDidChange.event;
}
private _placeholder: string = '';
get placeholder(): string {
return this._placeholder;
}
set placeholder(placeholder: string) {
this._proxy.$setInputBoxPlaceholder(this._sourceControlHandle, placeholder);
this._placeholder = placeholder;
}
private _validateInput: IValidateInput | undefined;
get validateInput(): IValidateInput | undefined {
if (!this._extension.enableProposedApi) {
throw new Error(`[${this._extension.identifier.value}]: Proposed API is only available when running out of dev or with the following command line switch: --enable-proposed-api ${this._extension.identifier.value}`);
}
return this._validateInput;
}
set validateInput(fn: IValidateInput | undefined) {
if (!this._extension.enableProposedApi) {
throw new Error(`[${this._extension.identifier.value}]: Proposed API is only available when running out of dev or with the following command line switch: --enable-proposed-api ${this._extension.identifier.value}`);
}
if (fn && typeof fn !== 'function') {
throw new Error(`[${this._extension.identifier.value}]: Invalid SCM input box validation function`);
}
this._validateInput = fn;
this._proxy.$setValidationProviderIsEnabled(this._sourceControlHandle, !!fn);
}
private _visible: boolean = true;
get visible(): boolean {
return this._visible;
}
set visible(visible: boolean) {
visible = !!visible;
if (this._visible === visible) {
return;
}
this._visible = visible;
this._proxy.$setInputBoxVisibility(this._sourceControlHandle, visible);
}
constructor(private _extension: IExtensionDescription, private _proxy: MainThreadSCMShape, private _sourceControlHandle: number) {
// noop
}
$onInputBoxValueChange(value: string): void {
this.updateValue(value);
}
private updateValue(value: string): void {
this._value = value;
this._onDidChange.fire(value);
}
}
class ExtHostSourceControlResourceGroup implements vscode.SourceControlResourceGroup {
private static _handlePool: number = 0;
private _resourceHandlePool: number = 0;
private _resourceStates: vscode.SourceControlResourceState[] = [];
private _resourceStatesMap: Map<ResourceStateHandle, vscode.SourceControlResourceState> = new Map<ResourceStateHandle, vscode.SourceControlResourceState>();
private _resourceStatesCommandsMap: Map<ResourceStateHandle, vscode.Command> = new Map<ResourceStateHandle, vscode.Command>();
private readonly _onDidUpdateResourceStates = new Emitter<void>();
readonly onDidUpdateResourceStates = this._onDidUpdateResourceStates.event;
private _disposed = false;
get disposed(): boolean { return this._disposed; }
private readonly _onDidDispose = new Emitter<void>();
readonly onDidDispose = this._onDidDispose.event;
private _handlesSnapshot: number[] = [];
private _resourceSnapshot: vscode.SourceControlResourceState[] = [];
get id(): string { return this._id; }
get label(): string { return this._label; }
set label(label: string) {
this._label = label;
this._proxy.$updateGroupLabel(this._sourceControlHandle, this.handle, label);
}
private _hideWhenEmpty: boolean | undefined = undefined;
get hideWhenEmpty(): boolean | undefined { return this._hideWhenEmpty; }
set hideWhenEmpty(hideWhenEmpty: boolean | undefined) {
this._hideWhenEmpty = hideWhenEmpty;
this._proxy.$updateGroup(this._sourceControlHandle, this.handle, this.features);
}
get features(): SCMGroupFeatures {
return {
hideWhenEmpty: this.hideWhenEmpty
};
}
get resourceStates(): vscode.SourceControlResourceState[] { return [...this._resourceStates]; }
set resourceStates(resources: vscode.SourceControlResourceState[]) {
this._resourceStates = [...resources];
this._onDidUpdateResourceStates.fire();
}
readonly handle = ExtHostSourceControlResourceGroup._handlePool++;
constructor(
private _proxy: MainThreadSCMShape,
private _commands: ExtHostCommands,
private _sourceControlHandle: number,
private _id: string,
private _label: string,
) { }
getResourceState(handle: number): vscode.SourceControlResourceState | undefined {
return this._resourceStatesMap.get(handle);
}
$executeResourceCommand(handle: number, preserveFocus: boolean): Promise<void> {
const command = this._resourceStatesCommandsMap.get(handle);
if (!command) {
return Promise.resolve(undefined);
}
return asPromise(() => this._commands.executeCommand(command.command, ...(command.arguments || []), preserveFocus));
}
_takeResourceStateSnapshot(): SCMRawResourceSplice[] {
const snapshot = [...this._resourceStates].sort(compareResourceStates);
const diffs = sortedDiff(this._resourceSnapshot, snapshot, compareResourceStates);
const splices = diffs.map<ISplice<{ rawResource: SCMRawResource, handle: number }>>(diff => {
const toInsert = diff.toInsert.map(r => {
const handle = this._resourceHandlePool++;
this._resourceStatesMap.set(handle, r);
const sourceUri = r.resourceUri;
const iconUri = getIconResource(r.decorations);
const lightIconUri = r.decorations && getIconResource(r.decorations.light) || iconUri;
const darkIconUri = r.decorations && getIconResource(r.decorations.dark) || iconUri;
const icons: UriComponents[] = [];
if (r.command) {
this._resourceStatesCommandsMap.set(handle, r.command);
}
if (lightIconUri) {
icons.push(lightIconUri);
}
if (darkIconUri && (darkIconUri.toString() !== lightIconUri?.toString())) {
icons.push(darkIconUri);
}
const tooltip = (r.decorations && r.decorations.tooltip) || '';
const strikeThrough = r.decorations && !!r.decorations.strikeThrough;
const faded = r.decorations && !!r.decorations.faded;
const contextValue = r.contextValue || '';
const rawResource = [handle, sourceUri, icons, tooltip, strikeThrough, faded, contextValue] as SCMRawResource;
return { rawResource, handle };
});
return { start: diff.start, deleteCount: diff.deleteCount, toInsert };
});
const rawResourceSplices = splices
.map(({ start, deleteCount, toInsert }) => [start, deleteCount, toInsert.map(i => i.rawResource)] as SCMRawResourceSplice);
const reverseSplices = splices.reverse();
for (const { start, deleteCount, toInsert } of reverseSplices) {
const handles = toInsert.map(i => i.handle);
const handlesToDelete = this._handlesSnapshot.splice(start, deleteCount, ...handles);
for (const handle of handlesToDelete) {
this._resourceStatesMap.delete(handle);
this._resourceStatesCommandsMap.delete(handle);
}
}
this._resourceSnapshot = snapshot;
return rawResourceSplices;
}
dispose(): void {
this._disposed = true;
this._onDidDispose.fire();
}
}
class ExtHostSourceControl implements vscode.SourceControl {
private static _handlePool: number = 0;
private _groups: Map<GroupHandle, ExtHostSourceControlResourceGroup> = new Map<GroupHandle, ExtHostSourceControlResourceGroup>();
get id(): string {
return this._id;
}
get label(): string {
return this._label;
}
get rootUri(): vscode.Uri | undefined {
return this._rootUri;
}
private _inputBox: ExtHostSCMInputBox;
get inputBox(): ExtHostSCMInputBox { return this._inputBox; }
private _count: number | undefined = undefined;
get count(): number | undefined {
return this._count;
}
set count(count: number | undefined) {
if (this._count === count) {
return;
}
this._count = count;
this._proxy.$updateSourceControl(this.handle, { count });
}
private _quickDiffProvider: vscode.QuickDiffProvider | undefined = undefined;
get quickDiffProvider(): vscode.QuickDiffProvider | undefined {
return this._quickDiffProvider;
}
set quickDiffProvider(quickDiffProvider: vscode.QuickDiffProvider | undefined) {
this._quickDiffProvider = quickDiffProvider;
this._proxy.$updateSourceControl(this.handle, { hasQuickDiffProvider: !!quickDiffProvider });
}
private _commitTemplate: string | undefined = undefined;
get commitTemplate(): string | undefined {
return this._commitTemplate;
}
set commitTemplate(commitTemplate: string | undefined) {
if (commitTemplate === this._commitTemplate) {
return;
}
this._commitTemplate = commitTemplate;
this._proxy.$updateSourceControl(this.handle, { commitTemplate });
}
private _acceptInputDisposables = new MutableDisposable<DisposableStore>();
private _acceptInputCommand: vscode.Command | undefined = undefined;
get acceptInputCommand(): vscode.Command | undefined {
return this._acceptInputCommand;
}
set acceptInputCommand(acceptInputCommand: vscode.Command | undefined) {
this._acceptInputDisposables.value = new DisposableStore();
this._acceptInputCommand = acceptInputCommand;
const internal = this._commands.converter.toInternal(acceptInputCommand, this._acceptInputDisposables.value);
this._proxy.$updateSourceControl(this.handle, { acceptInputCommand: internal });
}
private _statusBarDisposables = new MutableDisposable<DisposableStore>();
private _statusBarCommands: vscode.Command[] | undefined = undefined;
get statusBarCommands(): vscode.Command[] | undefined {
return this._statusBarCommands;
}
set statusBarCommands(statusBarCommands: vscode.Command[] | undefined) {
if (this._statusBarCommands && statusBarCommands && commandListEquals(this._statusBarCommands, statusBarCommands)) {
return;
}
this._statusBarDisposables.value = new DisposableStore();
this._statusBarCommands = statusBarCommands;
const internal = (statusBarCommands || []).map(c => this._commands.converter.toInternal(c, this._statusBarDisposables.value!)) as ICommandDto[];
this._proxy.$updateSourceControl(this.handle, { statusBarCommands: internal });
}
private _selected: boolean = false;
get selected(): boolean {
return this._selected;
}
private readonly _onDidChangeSelection = new Emitter<boolean>();
readonly onDidChangeSelection = this._onDidChangeSelection.event;
private handle: number = ExtHostSourceControl._handlePool++;
constructor(
_extension: IExtensionDescription,
private _proxy: MainThreadSCMShape,
private _commands: ExtHostCommands,
private _id: string,
private _label: string,
private _rootUri?: vscode.Uri
) {
this._inputBox = new ExtHostSCMInputBox(_extension, this._proxy, this.handle);
this._proxy.$registerSourceControl(this.handle, _id, _label, _rootUri);
}
private createdResourceGroups = new Map<ExtHostSourceControlResourceGroup, IDisposable>();
private updatedResourceGroups = new Set<ExtHostSourceControlResourceGroup>();
createResourceGroup(id: string, label: string): ExtHostSourceControlResourceGroup {
const group = new ExtHostSourceControlResourceGroup(this._proxy, this._commands, this.handle, id, label);
const disposable = Event.once(group.onDidDispose)(() => this.createdResourceGroups.delete(group));
this.createdResourceGroups.set(group, disposable);
this.eventuallyAddResourceGroups();
return group;
}
@debounce(100)
eventuallyAddResourceGroups(): void {
const groups: [number /*handle*/, string /*id*/, string /*label*/, SCMGroupFeatures][] = [];
const splices: SCMRawResourceSplices[] = [];
for (const [group, disposable] of this.createdResourceGroups) {
disposable.dispose();
const updateListener = group.onDidUpdateResourceStates(() => {
this.updatedResourceGroups.add(group);
this.eventuallyUpdateResourceStates();
});
Event.once(group.onDidDispose)(() => {
this.updatedResourceGroups.delete(group);
updateListener.dispose();
this._groups.delete(group.handle);
this._proxy.$unregisterGroup(this.handle, group.handle);
});
groups.push([group.handle, group.id, group.label, group.features]);
const snapshot = group._takeResourceStateSnapshot();
if (snapshot.length > 0) {
splices.push([group.handle, snapshot]);
}
this._groups.set(group.handle, group);
}
this._proxy.$registerGroups(this.handle, groups, splices);
this.createdResourceGroups.clear();
}
@debounce(100)
eventuallyUpdateResourceStates(): void {
const splices: SCMRawResourceSplices[] = [];
this.updatedResourceGroups.forEach(group => {
const snapshot = group._takeResourceStateSnapshot();
if (snapshot.length === 0) {
return;
}
splices.push([group.handle, snapshot]);
});
if (splices.length > 0) {
this._proxy.$spliceResourceStates(this.handle, splices);
}
this.updatedResourceGroups.clear();
}
getResourceGroup(handle: GroupHandle): ExtHostSourceControlResourceGroup | undefined {
return this._groups.get(handle);
}
setSelectionState(selected: boolean): void {
this._selected = selected;
this._onDidChangeSelection.fire(selected);
}
dispose(): void {
this._acceptInputDisposables.dispose();
this._statusBarDisposables.dispose();
this._groups.forEach(group => group.dispose());
this._proxy.$unregisterSourceControl(this.handle);
}
}
export class ExtHostSCM implements ExtHostSCMShape {
private static _handlePool: number = 0;
private _proxy: MainThreadSCMShape;
private readonly _telemetry: MainThreadTelemetryShape;
private _sourceControls: Map<ProviderHandle, ExtHostSourceControl> = new Map<ProviderHandle, ExtHostSourceControl>();
private _sourceControlsByExtension: Map<string, ExtHostSourceControl[]> = new Map<string, ExtHostSourceControl[]>();
private readonly _onDidChangeActiveProvider = new Emitter<vscode.SourceControl>();
get onDidChangeActiveProvider(): Event<vscode.SourceControl> { return this._onDidChangeActiveProvider.event; }
private _selectedSourceControlHandle: number | undefined;
constructor(
mainContext: IMainContext,
private _commands: ExtHostCommands,
@ILogService private readonly logService: ILogService
) {
this._proxy = mainContext.getProxy(MainContext.MainThreadSCM);
this._telemetry = mainContext.getProxy(MainContext.MainThreadTelemetry);
_commands.registerArgumentProcessor({
processArgument: arg => {
if (arg && arg.$mid === 3) {
const sourceControl = this._sourceControls.get(arg.sourceControlHandle);
if (!sourceControl) {
return arg;
}
const group = sourceControl.getResourceGroup(arg.groupHandle);
if (!group) {
return arg;
}
return group.getResourceState(arg.handle);
} else if (arg && arg.$mid === 4) {
const sourceControl = this._sourceControls.get(arg.sourceControlHandle);
if (!sourceControl) {
return arg;
}
return sourceControl.getResourceGroup(arg.groupHandle);
} else if (arg && arg.$mid === 5) {
const sourceControl = this._sourceControls.get(arg.handle);
if (!sourceControl) {
return arg;
}
return sourceControl;
}
return arg;
}
});
}
createSourceControl(extension: IExtensionDescription, id: string, label: string, rootUri: vscode.Uri | undefined): vscode.SourceControl {
this.logService.trace('ExtHostSCM#createSourceControl', extension.identifier.value, id, label, rootUri);
type TEvent = { extensionId: string; };
type TMeta = { extensionId: { classification: 'SystemMetaData', purpose: 'FeatureInsight' }; };
this._telemetry.$publicLog2<TEvent, TMeta>('api/scm/createSourceControl', {
extensionId: extension.identifier.value,
});
const handle = ExtHostSCM._handlePool++;
const sourceControl = new ExtHostSourceControl(extension, this._proxy, this._commands, id, label, rootUri);
this._sourceControls.set(handle, sourceControl);
const sourceControls = this._sourceControlsByExtension.get(ExtensionIdentifier.toKey(extension.identifier)) || [];
sourceControls.push(sourceControl);
this._sourceControlsByExtension.set(ExtensionIdentifier.toKey(extension.identifier), sourceControls);
return sourceControl;
}
// Deprecated
getLastInputBox(extension: IExtensionDescription): ExtHostSCMInputBox | undefined {
this.logService.trace('ExtHostSCM#getLastInputBox', extension.identifier.value);
const sourceControls = this._sourceControlsByExtension.get(ExtensionIdentifier.toKey(extension.identifier));
const sourceControl = sourceControls && sourceControls[sourceControls.length - 1];
return sourceControl && sourceControl.inputBox;
}
$provideOriginalResource(sourceControlHandle: number, uriComponents: UriComponents, token: CancellationToken): Promise<UriComponents | null> {
const uri = URI.revive(uriComponents);
this.logService.trace('ExtHostSCM#$provideOriginalResource', sourceControlHandle, uri.toString());
const sourceControl = this._sourceControls.get(sourceControlHandle);
if (!sourceControl || !sourceControl.quickDiffProvider || !sourceControl.quickDiffProvider.provideOriginalResource) {
return Promise.resolve(null);
}
return asPromise(() => sourceControl.quickDiffProvider!.provideOriginalResource!(uri, token))
.then<UriComponents | null>(r => r || null);
}
$onInputBoxValueChange(sourceControlHandle: number, value: string): Promise<void> {
this.logService.trace('ExtHostSCM#$onInputBoxValueChange', sourceControlHandle);
const sourceControl = this._sourceControls.get(sourceControlHandle);
if (!sourceControl) {
return Promise.resolve(undefined);
}
sourceControl.inputBox.$onInputBoxValueChange(value);
return Promise.resolve(undefined);
}
$executeResourceCommand(sourceControlHandle: number, groupHandle: number, handle: number, preserveFocus: boolean): Promise<void> {
this.logService.trace('ExtHostSCM#$executeResourceCommand', sourceControlHandle, groupHandle, handle);
const sourceControl = this._sourceControls.get(sourceControlHandle);
if (!sourceControl) {
return Promise.resolve(undefined);
}
const group = sourceControl.getResourceGroup(groupHandle);
if (!group) {
return Promise.resolve(undefined);
}
return group.$executeResourceCommand(handle, preserveFocus);
}
$validateInput(sourceControlHandle: number, value: string, cursorPosition: number): Promise<[string, number] | undefined> {
this.logService.trace('ExtHostSCM#$validateInput', sourceControlHandle);
const sourceControl = this._sourceControls.get(sourceControlHandle);
if (!sourceControl) {
return Promise.resolve(undefined);
}
if (!sourceControl.inputBox.validateInput) {
return Promise.resolve(undefined);
}
return asPromise(() => sourceControl.inputBox.validateInput!(value, cursorPosition)).then(result => {
if (!result) {
return Promise.resolve(undefined);
}
return Promise.resolve<[string, number]>([result.message, result.type]);
});
}
$setSelectedSourceControl(selectedSourceControlHandle: number | undefined): Promise<void> {
this.logService.trace('ExtHostSCM#$setSelectedSourceControl', selectedSourceControlHandle);
if (selectedSourceControlHandle !== undefined) {
this._sourceControls.get(selectedSourceControlHandle)?.setSelectionState(true);
}
if (this._selectedSourceControlHandle !== undefined) {
this._sourceControls.get(this._selectedSourceControlHandle)?.setSelectionState(false);
}
this._selectedSourceControlHandle = selectedSourceControlHandle;
return Promise.resolve(undefined);
}
}

View File

@ -0,0 +1,131 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IDisposable, toDisposable } from 'vs/base/common/lifecycle';
import type * as vscode from 'vscode';
import { ExtHostSearchShape, MainThreadSearchShape, MainContext } from '../common/extHost.protocol';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { FileSearchManager } from 'vs/workbench/services/search/common/fileSearchManager';
import { IExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService';
import { IURITransformerService } from 'vs/workbench/api/common/extHostUriTransformerService';
import { ILogService } from 'vs/platform/log/common/log';
import { IRawFileQuery, ISearchCompleteStats, IFileQuery, IRawTextQuery, IRawQuery, ITextQuery, IFolderQuery } from 'vs/workbench/services/search/common/search';
import { URI, UriComponents } from 'vs/base/common/uri';
import { TextSearchManager } from 'vs/workbench/services/search/common/textSearchManager';
export interface IExtHostSearch extends ExtHostSearchShape {
registerTextSearchProvider(scheme: string, provider: vscode.TextSearchProvider): IDisposable;
registerFileSearchProvider(scheme: string, provider: vscode.FileSearchProvider): IDisposable;
}
export const IExtHostSearch = createDecorator<IExtHostSearch>('IExtHostSearch');
export class ExtHostSearch implements ExtHostSearchShape {
protected readonly _proxy: MainThreadSearchShape = this.extHostRpc.getProxy(MainContext.MainThreadSearch);
protected _handlePool: number = 0;
private readonly _textSearchProvider = new Map<number, vscode.TextSearchProvider>();
private readonly _textSearchUsedSchemes = new Set<string>();
private readonly _fileSearchProvider = new Map<number, vscode.FileSearchProvider>();
private readonly _fileSearchUsedSchemes = new Set<string>();
private readonly _fileSearchManager = new FileSearchManager();
constructor(
@IExtHostRpcService private extHostRpc: IExtHostRpcService,
@IURITransformerService protected _uriTransformer: IURITransformerService,
@ILogService protected _logService: ILogService
) { }
protected _transformScheme(scheme: string): string {
return this._uriTransformer.transformOutgoingScheme(scheme);
}
registerTextSearchProvider(scheme: string, provider: vscode.TextSearchProvider): IDisposable {
if (this._textSearchUsedSchemes.has(scheme)) {
throw new Error(`a text search provider for the scheme '${scheme}' is already registered`);
}
this._textSearchUsedSchemes.add(scheme);
const handle = this._handlePool++;
this._textSearchProvider.set(handle, provider);
this._proxy.$registerTextSearchProvider(handle, this._transformScheme(scheme));
return toDisposable(() => {
this._textSearchUsedSchemes.delete(scheme);
this._textSearchProvider.delete(handle);
this._proxy.$unregisterProvider(handle);
});
}
registerFileSearchProvider(scheme: string, provider: vscode.FileSearchProvider): IDisposable {
if (this._fileSearchUsedSchemes.has(scheme)) {
throw new Error(`a file search provider for the scheme '${scheme}' is already registered`);
}
this._fileSearchUsedSchemes.add(scheme);
const handle = this._handlePool++;
this._fileSearchProvider.set(handle, provider);
this._proxy.$registerFileSearchProvider(handle, this._transformScheme(scheme));
return toDisposable(() => {
this._fileSearchUsedSchemes.delete(scheme);
this._fileSearchProvider.delete(handle);
this._proxy.$unregisterProvider(handle);
});
}
$provideFileSearchResults(handle: number, session: number, rawQuery: IRawFileQuery, token: vscode.CancellationToken): Promise<ISearchCompleteStats> {
const query = reviveQuery(rawQuery);
const provider = this._fileSearchProvider.get(handle);
if (provider) {
return this._fileSearchManager.fileSearch(query, provider, batch => {
this._proxy.$handleFileMatch(handle, session, batch.map(p => p.resource));
}, token);
} else {
throw new Error('unknown provider: ' + handle);
}
}
$clearCache(cacheKey: string): Promise<void> {
this._fileSearchManager.clearCache(cacheKey);
return Promise.resolve(undefined);
}
$provideTextSearchResults(handle: number, session: number, rawQuery: IRawTextQuery, token: vscode.CancellationToken): Promise<ISearchCompleteStats> {
const provider = this._textSearchProvider.get(handle);
if (!provider || !provider.provideTextSearchResults) {
throw new Error(`Unknown provider ${handle}`);
}
const query = reviveQuery(rawQuery);
const engine = this.createTextSearchManager(query, provider);
return engine.search(progress => this._proxy.$handleTextMatch(handle, session, progress), token);
}
protected createTextSearchManager(query: ITextQuery, provider: vscode.TextSearchProvider): TextSearchManager {
return new TextSearchManager(query, provider, {
readdir: resource => Promise.resolve([]), // TODO@rob implement
toCanonicalName: encoding => encoding
});
}
}
export function reviveQuery<U extends IRawQuery>(rawQuery: U): U extends IRawTextQuery ? ITextQuery : IFileQuery {
return {
...<any>rawQuery, // TODO@rob ???
...{
folderQueries: rawQuery.folderQueries && rawQuery.folderQueries.map(reviveFolderQuery),
extraFileResources: rawQuery.extraFileResources && rawQuery.extraFileResources.map(components => URI.revive(components))
}
};
}
function reviveFolderQuery(rawFolderQuery: IFolderQuery<UriComponents>): IFolderQuery<URI> {
return {
...rawFolderQuery,
folder: URI.revive(rawFolderQuery.folder)
};
}

View File

@ -0,0 +1,230 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { StatusbarAlignment as MainThreadStatusBarAlignment } from 'vs/workbench/services/statusbar/common/statusbar';
import { StatusBarAlignment as ExtHostStatusBarAlignment, Disposable, ThemeColor } from './extHostTypes';
import type * as vscode from 'vscode';
import { MainContext, MainThreadStatusBarShape, IMainContext, ICommandDto } from './extHost.protocol';
import { localize } from 'vs/nls';
import { CommandsConverter } from 'vs/workbench/api/common/extHostCommands';
import { DisposableStore } from 'vs/base/common/lifecycle';
export class ExtHostStatusBarEntry implements vscode.StatusBarItem {
private static ID_GEN = 0;
private _id: number;
private _alignment: number;
private _priority?: number;
private _disposed: boolean = false;
private _visible: boolean = false;
private _statusId: string;
private _statusName: string;
private _text: string = '';
private _tooltip?: string;
private _color?: string | ThemeColor;
private readonly _internalCommandRegistration = new DisposableStore();
private _command?: {
readonly fromApi: string | vscode.Command,
readonly internal: ICommandDto,
};
private _timeoutHandle: any;
private _proxy: MainThreadStatusBarShape;
private _commands: CommandsConverter;
private _accessibilityInformation?: vscode.AccessibilityInformation;
constructor(proxy: MainThreadStatusBarShape, commands: CommandsConverter, id: string, name: string, alignment: ExtHostStatusBarAlignment = ExtHostStatusBarAlignment.Left, priority?: number, accessibilityInformation?: vscode.AccessibilityInformation) {
this._id = ExtHostStatusBarEntry.ID_GEN++;
this._proxy = proxy;
this._commands = commands;
this._statusId = id;
this._statusName = name;
this._alignment = alignment;
this._priority = priority;
this._accessibilityInformation = accessibilityInformation;
}
public get id(): number {
return this._id;
}
public get alignment(): vscode.StatusBarAlignment {
return this._alignment;
}
public get priority(): number | undefined {
return this._priority;
}
public get text(): string {
return this._text;
}
public get tooltip(): string | undefined {
return this._tooltip;
}
public get color(): string | ThemeColor | undefined {
return this._color;
}
public get command(): string | vscode.Command | undefined {
return this._command?.fromApi;
}
public get accessibilityInformation(): vscode.AccessibilityInformation | undefined {
return this._accessibilityInformation;
}
public set text(text: string) {
this._text = text;
this.update();
}
public set tooltip(tooltip: string | undefined) {
this._tooltip = tooltip;
this.update();
}
public set color(color: string | ThemeColor | undefined) {
this._color = color;
this.update();
}
public set command(command: string | vscode.Command | undefined) {
if (this._command?.fromApi === command) {
return;
}
this._internalCommandRegistration.clear();
if (typeof command === 'string') {
this._command = {
fromApi: command,
internal: this._commands.toInternal({ title: '', command }, this._internalCommandRegistration),
};
} else if (command) {
this._command = {
fromApi: command,
internal: this._commands.toInternal(command, this._internalCommandRegistration),
};
} else {
this._command = undefined;
}
this.update();
}
public set accessibilityInformation(accessibilityInformation: vscode.AccessibilityInformation | undefined) {
this._accessibilityInformation = accessibilityInformation;
this.update();
}
public show(): void {
this._visible = true;
this.update();
}
public hide(): void {
clearTimeout(this._timeoutHandle);
this._visible = false;
this._proxy.$dispose(this.id);
}
private update(): void {
if (this._disposed || !this._visible) {
return;
}
clearTimeout(this._timeoutHandle);
// Defer the update so that multiple changes to setters dont cause a redraw each
this._timeoutHandle = setTimeout(() => {
this._timeoutHandle = undefined;
// Set to status bar
this._proxy.$setEntry(this.id, this._statusId, this._statusName, this.text, this.tooltip, this._command?.internal, this.color,
this._alignment === ExtHostStatusBarAlignment.Left ? MainThreadStatusBarAlignment.LEFT : MainThreadStatusBarAlignment.RIGHT,
this._priority, this._accessibilityInformation);
}, 0);
}
public dispose(): void {
this.hide();
this._disposed = true;
}
}
class StatusBarMessage {
private _item: vscode.StatusBarItem;
private _messages: { message: string }[] = [];
constructor(statusBar: ExtHostStatusBar) {
this._item = statusBar.createStatusBarEntry('status.extensionMessage', localize('status.extensionMessage', "Extension Status"), ExtHostStatusBarAlignment.Left, Number.MIN_VALUE);
}
dispose() {
this._messages.length = 0;
this._item.dispose();
}
setMessage(message: string): Disposable {
const data: { message: string } = { message }; // use object to not confuse equal strings
this._messages.unshift(data);
this._update();
return new Disposable(() => {
const idx = this._messages.indexOf(data);
if (idx >= 0) {
this._messages.splice(idx, 1);
this._update();
}
});
}
private _update() {
if (this._messages.length > 0) {
this._item.text = this._messages[0].message;
this._item.show();
} else {
this._item.hide();
}
}
}
export class ExtHostStatusBar {
private readonly _proxy: MainThreadStatusBarShape;
private readonly _commands: CommandsConverter;
private _statusMessage: StatusBarMessage;
constructor(mainContext: IMainContext, commands: CommandsConverter) {
this._proxy = mainContext.getProxy(MainContext.MainThreadStatusBar);
this._commands = commands;
this._statusMessage = new StatusBarMessage(this);
}
createStatusBarEntry(id: string, name: string, alignment?: ExtHostStatusBarAlignment, priority?: number, accessibilityInformation?: vscode.AccessibilityInformation): vscode.StatusBarItem {
return new ExtHostStatusBarEntry(this._proxy, this._commands, id, name, alignment, priority, accessibilityInformation);
}
setStatusBarMessage(text: string, timeoutOrThenable?: number | Thenable<any>): Disposable {
const d = this._statusMessage.setMessage(text);
let handle: any;
if (typeof timeoutOrThenable === 'number') {
handle = setTimeout(() => d.dispose(), timeoutOrThenable);
} else if (typeof timeoutOrThenable !== 'undefined') {
timeoutOrThenable.then(() => d.dispose(), () => d.dispose());
}
return new Disposable(() => {
d.dispose();
clearTimeout(handle);
});
}
}

View File

@ -0,0 +1,49 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { MainContext, MainThreadStorageShape, ExtHostStorageShape } from './extHost.protocol';
import { Emitter } from 'vs/base/common/event';
import { IExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IExtensionIdWithVersion } from 'vs/platform/userDataSync/common/storageKeys';
export interface IStorageChangeEvent {
shared: boolean;
key: string;
value: object;
}
export class ExtHostStorage implements ExtHostStorageShape {
readonly _serviceBrand: undefined;
private _proxy: MainThreadStorageShape;
private readonly _onDidChangeStorage = new Emitter<IStorageChangeEvent>();
readonly onDidChangeStorage = this._onDidChangeStorage.event;
constructor(mainContext: IExtHostRpcService) {
this._proxy = mainContext.getProxy(MainContext.MainThreadStorage);
}
registerExtensionStorageKeysToSync(extension: IExtensionIdWithVersion, keys: string[]): void {
this._proxy.$registerExtensionStorageKeysToSync(extension, keys);
}
getValue<T>(shared: boolean, key: string, defaultValue?: T): Promise<T | undefined> {
return this._proxy.$getValue<T>(shared, key).then(value => value || defaultValue);
}
setValue(shared: boolean, key: string, value: object): Promise<void> {
return this._proxy.$setValue(shared, key, value);
}
$acceptValue(shared: boolean, key: string, value: object): void {
this._onDidChangeStorage.fire({ shared, key, value });
}
}
export interface IExtHostStorage extends ExtHostStorage { }
export const IExtHostStorage = createDecorator<IExtHostStorage>('IExtHostStorage');

View File

@ -0,0 +1,87 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IExtHostInitDataService } from 'vs/workbench/api/common/extHostInitDataService';
import { ILogService } from 'vs/platform/log/common/log';
import { IEnvironment, IStaticWorkspaceData } from 'vs/workbench/api/common/extHost.protocol';
import { IExtHostConsumerFileSystem } from 'vs/workbench/api/common/extHostFileSystemConsumer';
import { URI } from 'vs/base/common/uri';
export const IExtensionStoragePaths = createDecorator<IExtensionStoragePaths>('IExtensionStoragePaths');
export interface IExtensionStoragePaths {
readonly _serviceBrand: undefined;
whenReady: Promise<any>;
workspaceValue(extension: IExtensionDescription): URI | undefined;
globalValue(extension: IExtensionDescription): URI;
}
export class ExtensionStoragePaths implements IExtensionStoragePaths {
readonly _serviceBrand: undefined;
private readonly _workspace?: IStaticWorkspaceData;
private readonly _environment: IEnvironment;
readonly whenReady: Promise<URI | undefined>;
private _value?: URI;
constructor(
@IExtHostInitDataService initData: IExtHostInitDataService,
@ILogService private readonly _logService: ILogService,
@IExtHostConsumerFileSystem private readonly _extHostFileSystem: IExtHostConsumerFileSystem
) {
this._workspace = initData.workspace ?? undefined;
this._environment = initData.environment;
this.whenReady = this._getOrCreateWorkspaceStoragePath().then(value => this._value = value);
}
private async _getOrCreateWorkspaceStoragePath(): Promise<URI | undefined> {
if (!this._workspace) {
return Promise.resolve(undefined);
}
const storageName = this._workspace.id;
const storageUri = URI.joinPath(this._environment.workspaceStorageHome, storageName);
try {
await this._extHostFileSystem.stat(storageUri);
this._logService.trace('[ExtHostStorage] storage dir already exists', storageUri);
return storageUri;
} catch {
// doesn't exist, that's OK
}
try {
this._logService.trace('[ExtHostStorage] creating dir and metadata-file', storageUri);
await this._extHostFileSystem.createDirectory(storageUri);
await this._extHostFileSystem.writeFile(
URI.joinPath(storageUri, 'meta.json'),
new TextEncoder().encode(JSON.stringify({
id: this._workspace.id,
configuration: URI.revive(this._workspace.configuration)?.toString(),
name: this._workspace.name
}, undefined, 2))
);
return storageUri;
} catch (e) {
this._logService.error('[ExtHostStorage]', e);
return undefined;
}
}
workspaceValue(extension: IExtensionDescription): URI | undefined {
if (this._value) {
return URI.joinPath(this._value, extension.identifier.value);
}
return undefined;
}
globalValue(extension: IExtensionDescription): URI {
return URI.joinPath(this._environment.globalStorageHome, extension.identifier.value.toLowerCase());
}
}

View File

@ -0,0 +1,785 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { URI, UriComponents } from 'vs/base/common/uri';
import { asPromise } from 'vs/base/common/async';
import { Event, Emitter } from 'vs/base/common/event';
import { MainContext, MainThreadTaskShape, ExtHostTaskShape } from 'vs/workbench/api/common/extHost.protocol';
import * as types from 'vs/workbench/api/common/extHostTypes';
import { IExtHostWorkspaceProvider, IExtHostWorkspace } from 'vs/workbench/api/common/extHostWorkspace';
import type * as vscode from 'vscode';
import * as tasks from '../common/shared/tasks';
import { IExtHostDocumentsAndEditors } from 'vs/workbench/api/common/extHostDocumentsAndEditors';
import { IExtHostConfiguration } from 'vs/workbench/api/common/extHostConfiguration';
import { CancellationToken } from 'vs/base/common/cancellation';
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { IExtHostTerminalService } from 'vs/workbench/api/common/extHostTerminalService';
import { IExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService';
import { IExtHostInitDataService } from 'vs/workbench/api/common/extHostInitDataService';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { Schemas } from 'vs/base/common/network';
import * as Platform from 'vs/base/common/platform';
import { ILogService } from 'vs/platform/log/common/log';
import { IExtHostApiDeprecationService } from 'vs/workbench/api/common/extHostApiDeprecationService';
import { USER_TASKS_GROUP_KEY } from 'vs/workbench/contrib/tasks/common/taskService';
import { NotSupportedError } from 'vs/base/common/errors';
export interface IExtHostTask extends ExtHostTaskShape {
readonly _serviceBrand: undefined;
taskExecutions: vscode.TaskExecution[];
onDidStartTask: Event<vscode.TaskStartEvent>;
onDidEndTask: Event<vscode.TaskEndEvent>;
onDidStartTaskProcess: Event<vscode.TaskProcessStartEvent>;
onDidEndTaskProcess: Event<vscode.TaskProcessEndEvent>;
registerTaskProvider(extension: IExtensionDescription, type: string, provider: vscode.TaskProvider): vscode.Disposable;
registerTaskSystem(scheme: string, info: tasks.TaskSystemInfoDTO): void;
fetchTasks(filter?: vscode.TaskFilter): Promise<vscode.Task[]>;
executeTask(extension: IExtensionDescription, task: vscode.Task): Promise<vscode.TaskExecution>;
terminateTask(execution: vscode.TaskExecution): Promise<void>;
}
export namespace TaskDefinitionDTO {
export function from(value: vscode.TaskDefinition): tasks.TaskDefinitionDTO | undefined {
if (value === undefined || value === null) {
return undefined;
}
return value;
}
export function to(value: tasks.TaskDefinitionDTO): vscode.TaskDefinition | undefined {
if (value === undefined || value === null) {
return undefined;
}
return value;
}
}
export namespace TaskPresentationOptionsDTO {
export function from(value: vscode.TaskPresentationOptions): tasks.TaskPresentationOptionsDTO | undefined {
if (value === undefined || value === null) {
return undefined;
}
return value;
}
export function to(value: tasks.TaskPresentationOptionsDTO): vscode.TaskPresentationOptions | undefined {
if (value === undefined || value === null) {
return undefined;
}
return value;
}
}
export namespace ProcessExecutionOptionsDTO {
export function from(value: vscode.ProcessExecutionOptions): tasks.ProcessExecutionOptionsDTO | undefined {
if (value === undefined || value === null) {
return undefined;
}
return value;
}
export function to(value: tasks.ProcessExecutionOptionsDTO): vscode.ProcessExecutionOptions | undefined {
if (value === undefined || value === null) {
return undefined;
}
return value;
}
}
export namespace ProcessExecutionDTO {
export function is(value: tasks.ShellExecutionDTO | tasks.ProcessExecutionDTO | tasks.CustomExecutionDTO | undefined): value is tasks.ProcessExecutionDTO {
if (value) {
const candidate = value as tasks.ProcessExecutionDTO;
return candidate && !!candidate.process;
} else {
return false;
}
}
export function from(value: vscode.ProcessExecution): tasks.ProcessExecutionDTO | undefined {
if (value === undefined || value === null) {
return undefined;
}
const result: tasks.ProcessExecutionDTO = {
process: value.process,
args: value.args
};
if (value.options) {
result.options = ProcessExecutionOptionsDTO.from(value.options);
}
return result;
}
export function to(value: tasks.ProcessExecutionDTO): types.ProcessExecution | undefined {
if (value === undefined || value === null) {
return undefined;
}
return new types.ProcessExecution(value.process, value.args, value.options);
}
}
export namespace ShellExecutionOptionsDTO {
export function from(value: vscode.ShellExecutionOptions): tasks.ShellExecutionOptionsDTO | undefined {
if (value === undefined || value === null) {
return undefined;
}
return value;
}
export function to(value: tasks.ShellExecutionOptionsDTO): vscode.ShellExecutionOptions | undefined {
if (value === undefined || value === null) {
return undefined;
}
return value;
}
}
export namespace ShellExecutionDTO {
export function is(value: tasks.ShellExecutionDTO | tasks.ProcessExecutionDTO | tasks.CustomExecutionDTO | undefined): value is tasks.ShellExecutionDTO {
if (value) {
const candidate = value as tasks.ShellExecutionDTO;
return candidate && (!!candidate.commandLine || !!candidate.command);
} else {
return false;
}
}
export function from(value: vscode.ShellExecution): tasks.ShellExecutionDTO | undefined {
if (value === undefined || value === null) {
return undefined;
}
const result: tasks.ShellExecutionDTO = {
};
if (value.commandLine !== undefined) {
result.commandLine = value.commandLine;
} else {
result.command = value.command;
result.args = value.args;
}
if (value.options) {
result.options = ShellExecutionOptionsDTO.from(value.options);
}
return result;
}
export function to(value: tasks.ShellExecutionDTO): types.ShellExecution | undefined {
if (value === undefined || value === null || (value.command === undefined && value.commandLine === undefined)) {
return undefined;
}
if (value.commandLine) {
return new types.ShellExecution(value.commandLine, value.options);
} else {
return new types.ShellExecution(value.command!, value.args ? value.args : [], value.options);
}
}
}
export namespace CustomExecutionDTO {
export function is(value: tasks.ShellExecutionDTO | tasks.ProcessExecutionDTO | tasks.CustomExecutionDTO | undefined): value is tasks.CustomExecutionDTO {
if (value) {
let candidate = value as tasks.CustomExecutionDTO;
return candidate && candidate.customExecution === 'customExecution';
} else {
return false;
}
}
export function from(value: vscode.CustomExecution): tasks.CustomExecutionDTO {
return {
customExecution: 'customExecution'
};
}
}
export namespace TaskHandleDTO {
export function from(value: types.Task, workspaceService?: IExtHostWorkspace): tasks.TaskHandleDTO {
let folder: UriComponents | string;
if (value.scope !== undefined && typeof value.scope !== 'number') {
folder = value.scope.uri;
} else if (value.scope !== undefined && typeof value.scope === 'number') {
if ((value.scope === types.TaskScope.Workspace) && workspaceService && workspaceService.workspaceFile) {
folder = workspaceService.workspaceFile;
} else {
folder = USER_TASKS_GROUP_KEY;
}
}
return {
id: value._id!,
workspaceFolder: folder!
};
}
}
export namespace TaskDTO {
export function fromMany(tasks: vscode.Task[], extension: IExtensionDescription): tasks.TaskDTO[] {
if (tasks === undefined || tasks === null) {
return [];
}
const result: tasks.TaskDTO[] = [];
for (let task of tasks) {
const converted = from(task, extension);
if (converted) {
result.push(converted);
}
}
return result;
}
export function from(value: vscode.Task, extension: IExtensionDescription): tasks.TaskDTO | undefined {
if (value === undefined || value === null) {
return undefined;
}
let execution: tasks.ShellExecutionDTO | tasks.ProcessExecutionDTO | tasks.CustomExecutionDTO | undefined;
if (value.execution instanceof types.ProcessExecution) {
execution = ProcessExecutionDTO.from(value.execution);
} else if (value.execution instanceof types.ShellExecution) {
execution = ShellExecutionDTO.from(value.execution);
} else if (value.execution && value.execution instanceof types.CustomExecution) {
execution = CustomExecutionDTO.from(<types.CustomExecution>value.execution);
}
const definition: tasks.TaskDefinitionDTO | undefined = TaskDefinitionDTO.from(value.definition);
let scope: number | UriComponents;
if (value.scope) {
if (typeof value.scope === 'number') {
scope = value.scope;
} else {
scope = value.scope.uri;
}
} else {
// To continue to support the deprecated task constructor that doesn't take a scope, we must add a scope here:
scope = types.TaskScope.Workspace;
}
if (!definition || !scope) {
return undefined;
}
const group = (value.group as types.TaskGroup) ? (value.group as types.TaskGroup).id : undefined;
const result: tasks.TaskDTO = {
_id: (value as types.Task)._id!,
definition,
name: value.name,
source: {
extensionId: extension.identifier.value,
label: value.source,
scope: scope
},
execution: execution!,
isBackground: value.isBackground,
group: group,
presentationOptions: TaskPresentationOptionsDTO.from(value.presentationOptions),
problemMatchers: value.problemMatchers,
hasDefinedMatchers: (value as types.Task).hasDefinedMatchers,
runOptions: value.runOptions ? value.runOptions : { reevaluateOnRerun: true },
detail: value.detail
};
return result;
}
export async function to(value: tasks.TaskDTO | undefined, workspace: IExtHostWorkspaceProvider): Promise<types.Task | undefined> {
if (value === undefined || value === null) {
return undefined;
}
let execution: types.ShellExecution | types.ProcessExecution | undefined;
if (ProcessExecutionDTO.is(value.execution)) {
execution = ProcessExecutionDTO.to(value.execution);
} else if (ShellExecutionDTO.is(value.execution)) {
execution = ShellExecutionDTO.to(value.execution);
}
const definition: vscode.TaskDefinition | undefined = TaskDefinitionDTO.to(value.definition);
let scope: vscode.TaskScope.Global | vscode.TaskScope.Workspace | vscode.WorkspaceFolder | undefined;
if (value.source) {
if (value.source.scope !== undefined) {
if (typeof value.source.scope === 'number') {
scope = value.source.scope;
} else {
scope = await workspace.resolveWorkspaceFolder(URI.revive(value.source.scope));
}
} else {
scope = types.TaskScope.Workspace;
}
}
if (!definition || !scope) {
return undefined;
}
const result = new types.Task(definition, scope, value.name!, value.source.label, execution, value.problemMatchers);
if (value.isBackground !== undefined) {
result.isBackground = value.isBackground;
}
if (value.group !== undefined) {
result.group = types.TaskGroup.from(value.group);
}
if (value.presentationOptions) {
result.presentationOptions = TaskPresentationOptionsDTO.to(value.presentationOptions)!;
}
if (value._id) {
result._id = value._id;
}
if (value.detail) {
result.detail = value.detail;
}
return result;
}
}
export namespace TaskFilterDTO {
export function from(value: vscode.TaskFilter | undefined): tasks.TaskFilterDTO | undefined {
return value;
}
export function to(value: tasks.TaskFilterDTO): vscode.TaskFilter | undefined {
if (!value) {
return undefined;
}
return Object.assign(Object.create(null), value);
}
}
class TaskExecutionImpl implements vscode.TaskExecution {
constructor(private readonly _tasks: ExtHostTaskBase, readonly _id: string, private readonly _task: vscode.Task) {
}
public get task(): vscode.Task {
return this._task;
}
public terminate(): void {
this._tasks.terminateTask(this);
}
public fireDidStartProcess(value: tasks.TaskProcessStartedDTO): void {
}
public fireDidEndProcess(value: tasks.TaskProcessEndedDTO): void {
}
}
export namespace TaskExecutionDTO {
export async function to(value: tasks.TaskExecutionDTO, tasks: ExtHostTaskBase, workspaceProvider: IExtHostWorkspaceProvider): Promise<vscode.TaskExecution> {
const task = await TaskDTO.to(value.task, workspaceProvider);
if (!task) {
throw new Error('Unexpected: Task cannot be created.');
}
return new TaskExecutionImpl(tasks, value.id, task);
}
export function from(value: vscode.TaskExecution): tasks.TaskExecutionDTO {
return {
id: (value as TaskExecutionImpl)._id,
task: undefined
};
}
}
export interface HandlerData {
type: string;
provider: vscode.TaskProvider;
extension: IExtensionDescription;
}
export abstract class ExtHostTaskBase implements ExtHostTaskShape, IExtHostTask {
readonly _serviceBrand: undefined;
protected readonly _proxy: MainThreadTaskShape;
protected readonly _workspaceProvider: IExtHostWorkspaceProvider;
protected readonly _editorService: IExtHostDocumentsAndEditors;
protected readonly _configurationService: IExtHostConfiguration;
protected readonly _terminalService: IExtHostTerminalService;
protected readonly _logService: ILogService;
protected readonly _deprecationService: IExtHostApiDeprecationService;
protected _handleCounter: number;
protected _handlers: Map<number, HandlerData>;
protected _taskExecutions: Map<string, TaskExecutionImpl>;
protected _taskExecutionPromises: Map<string, Promise<TaskExecutionImpl>>;
protected _providedCustomExecutions2: Map<string, types.CustomExecution>;
private _notProvidedCustomExecutions: Set<string>; // Used for custom executions tasks that are created and run through executeTask.
protected _activeCustomExecutions2: Map<string, types.CustomExecution>;
private _lastStartedTask: string | undefined;
protected readonly _onDidExecuteTask: Emitter<vscode.TaskStartEvent> = new Emitter<vscode.TaskStartEvent>();
protected readonly _onDidTerminateTask: Emitter<vscode.TaskEndEvent> = new Emitter<vscode.TaskEndEvent>();
protected readonly _onDidTaskProcessStarted: Emitter<vscode.TaskProcessStartEvent> = new Emitter<vscode.TaskProcessStartEvent>();
protected readonly _onDidTaskProcessEnded: Emitter<vscode.TaskProcessEndEvent> = new Emitter<vscode.TaskProcessEndEvent>();
constructor(
@IExtHostRpcService extHostRpc: IExtHostRpcService,
@IExtHostInitDataService initData: IExtHostInitDataService,
@IExtHostWorkspace workspaceService: IExtHostWorkspace,
@IExtHostDocumentsAndEditors editorService: IExtHostDocumentsAndEditors,
@IExtHostConfiguration configurationService: IExtHostConfiguration,
@IExtHostTerminalService extHostTerminalService: IExtHostTerminalService,
@ILogService logService: ILogService,
@IExtHostApiDeprecationService deprecationService: IExtHostApiDeprecationService
) {
this._proxy = extHostRpc.getProxy(MainContext.MainThreadTask);
this._workspaceProvider = workspaceService;
this._editorService = editorService;
this._configurationService = configurationService;
this._terminalService = extHostTerminalService;
this._handleCounter = 0;
this._handlers = new Map<number, HandlerData>();
this._taskExecutions = new Map<string, TaskExecutionImpl>();
this._taskExecutionPromises = new Map<string, Promise<TaskExecutionImpl>>();
this._providedCustomExecutions2 = new Map<string, types.CustomExecution>();
this._notProvidedCustomExecutions = new Set<string>();
this._activeCustomExecutions2 = new Map<string, types.CustomExecution>();
this._logService = logService;
this._deprecationService = deprecationService;
this._proxy.$registerSupportedExecutions(true);
}
public registerTaskProvider(extension: IExtensionDescription, type: string, provider: vscode.TaskProvider): vscode.Disposable {
if (!provider) {
return new types.Disposable(() => { });
}
const handle = this.nextHandle();
this._handlers.set(handle, { type, provider, extension });
this._proxy.$registerTaskProvider(handle, type);
return new types.Disposable(() => {
this._handlers.delete(handle);
this._proxy.$unregisterTaskProvider(handle);
});
}
public registerTaskSystem(scheme: string, info: tasks.TaskSystemInfoDTO): void {
this._proxy.$registerTaskSystem(scheme, info);
}
public fetchTasks(filter?: vscode.TaskFilter): Promise<vscode.Task[]> {
return this._proxy.$fetchTasks(TaskFilterDTO.from(filter)).then(async (values) => {
const result: vscode.Task[] = [];
for (let value of values) {
const task = await TaskDTO.to(value, this._workspaceProvider);
if (task) {
result.push(task);
}
}
return result;
});
}
public abstract executeTask(extension: IExtensionDescription, task: vscode.Task): Promise<vscode.TaskExecution>;
public get taskExecutions(): vscode.TaskExecution[] {
const result: vscode.TaskExecution[] = [];
this._taskExecutions.forEach(value => result.push(value));
return result;
}
public terminateTask(execution: vscode.TaskExecution): Promise<void> {
if (!(execution instanceof TaskExecutionImpl)) {
throw new Error('No valid task execution provided');
}
return this._proxy.$terminateTask((execution as TaskExecutionImpl)._id);
}
public get onDidStartTask(): Event<vscode.TaskStartEvent> {
return this._onDidExecuteTask.event;
}
public async $onDidStartTask(execution: tasks.TaskExecutionDTO, terminalId: number, resolvedDefinition: tasks.TaskDefinitionDTO): Promise<void> {
const customExecution: types.CustomExecution | undefined = this._providedCustomExecutions2.get(execution.id);
if (customExecution) {
if (this._activeCustomExecutions2.get(execution.id) !== undefined) {
throw new Error('We should not be trying to start the same custom task executions twice.');
}
// Clone the custom execution to keep the original untouched. This is important for multiple runs of the same task.
this._activeCustomExecutions2.set(execution.id, customExecution);
this._terminalService.attachPtyToTerminal(terminalId, await customExecution.callback(resolvedDefinition));
}
this._lastStartedTask = execution.id;
this._onDidExecuteTask.fire({
execution: await this.getTaskExecution(execution)
});
}
public get onDidEndTask(): Event<vscode.TaskEndEvent> {
return this._onDidTerminateTask.event;
}
public async $OnDidEndTask(execution: tasks.TaskExecutionDTO): Promise<void> {
const _execution = await this.getTaskExecution(execution);
this._taskExecutionPromises.delete(execution.id);
this._taskExecutions.delete(execution.id);
this.customExecutionComplete(execution);
this._onDidTerminateTask.fire({
execution: _execution
});
}
public get onDidStartTaskProcess(): Event<vscode.TaskProcessStartEvent> {
return this._onDidTaskProcessStarted.event;
}
public async $onDidStartTaskProcess(value: tasks.TaskProcessStartedDTO): Promise<void> {
const execution = await this.getTaskExecution(value.id);
this._onDidTaskProcessStarted.fire({
execution: execution,
processId: value.processId
});
}
public get onDidEndTaskProcess(): Event<vscode.TaskProcessEndEvent> {
return this._onDidTaskProcessEnded.event;
}
public async $onDidEndTaskProcess(value: tasks.TaskProcessEndedDTO): Promise<void> {
const execution = await this.getTaskExecution(value.id);
this._onDidTaskProcessEnded.fire({
execution: execution,
exitCode: value.exitCode
});
}
protected abstract provideTasksInternal(validTypes: { [key: string]: boolean; }, taskIdPromises: Promise<void>[], handler: HandlerData, value: vscode.Task[] | null | undefined): { tasks: tasks.TaskDTO[], extension: IExtensionDescription };
public $provideTasks(handle: number, validTypes: { [key: string]: boolean; }): Thenable<tasks.TaskSetDTO> {
const handler = this._handlers.get(handle);
if (!handler) {
return Promise.reject(new Error('no handler found'));
}
// Set up a list of task ID promises that we can wait on
// before returning the provided tasks. The ensures that
// our task IDs are calculated for any custom execution tasks.
// Knowing this ID ahead of time is needed because when a task
// start event is fired this is when the custom execution is called.
// The task start event is also the first time we see the ID from the main
// thread, which is too late for us because we need to save an map
// from an ID to the custom execution function. (Kind of a cart before the horse problem).
const taskIdPromises: Promise<void>[] = [];
const fetchPromise = asPromise(() => handler.provider.provideTasks(CancellationToken.None)).then(value => {
return this.provideTasksInternal(validTypes, taskIdPromises, handler, value);
});
return new Promise((resolve) => {
fetchPromise.then((result) => {
Promise.all(taskIdPromises).then(() => {
resolve(result);
});
});
});
}
protected abstract resolveTaskInternal(resolvedTaskDTO: tasks.TaskDTO): Promise<tasks.TaskDTO | undefined>;
public async $resolveTask(handle: number, taskDTO: tasks.TaskDTO): Promise<tasks.TaskDTO | undefined> {
const handler = this._handlers.get(handle);
if (!handler) {
return Promise.reject(new Error('no handler found'));
}
if (taskDTO.definition.type !== handler.type) {
throw new Error(`Unexpected: Task of type [${taskDTO.definition.type}] cannot be resolved by provider of type [${handler.type}].`);
}
const task = await TaskDTO.to(taskDTO, this._workspaceProvider);
if (!task) {
throw new Error('Unexpected: Task cannot be resolved.');
}
const resolvedTask = await handler.provider.resolveTask(task, CancellationToken.None);
if (!resolvedTask) {
return;
}
this.checkDeprecation(resolvedTask, handler);
const resolvedTaskDTO: tasks.TaskDTO | undefined = TaskDTO.from(resolvedTask, handler.extension);
if (!resolvedTaskDTO) {
throw new Error('Unexpected: Task cannot be resolved.');
}
if (resolvedTask.definition !== task.definition) {
throw new Error('Unexpected: The resolved task definition must be the same object as the original task definition. The task definition cannot be changed.');
}
if (CustomExecutionDTO.is(resolvedTaskDTO.execution)) {
await this.addCustomExecution(resolvedTaskDTO, resolvedTask, true);
}
return await this.resolveTaskInternal(resolvedTaskDTO);
}
public abstract $resolveVariables(uriComponents: UriComponents, toResolve: { process?: { name: string; cwd?: string; path?: string }, variables: string[] }): Promise<{ process?: string, variables: { [key: string]: string; } }>;
public abstract $getDefaultShellAndArgs(): Promise<{ shell: string, args: string[] | string | undefined }>;
private nextHandle(): number {
return this._handleCounter++;
}
protected async addCustomExecution(taskDTO: tasks.TaskDTO, task: vscode.Task, isProvided: boolean): Promise<void> {
const taskId = await this._proxy.$createTaskId(taskDTO);
if (!isProvided && !this._providedCustomExecutions2.has(taskId)) {
this._notProvidedCustomExecutions.add(taskId);
}
this._providedCustomExecutions2.set(taskId, <types.CustomExecution>task.execution);
}
protected async getTaskExecution(execution: tasks.TaskExecutionDTO | string, task?: vscode.Task): Promise<TaskExecutionImpl> {
if (typeof execution === 'string') {
const taskExecution = this._taskExecutionPromises.get(execution);
if (!taskExecution) {
throw new Error('Unexpected: The specified task is missing an execution');
}
return taskExecution;
}
let result: Promise<TaskExecutionImpl> | undefined = this._taskExecutionPromises.get(execution.id);
if (result) {
return result;
}
const createdResult: Promise<TaskExecutionImpl> = new Promise(async (resolve, reject) => {
const taskToCreate = task ? task : await TaskDTO.to(execution.task, this._workspaceProvider);
if (!taskToCreate) {
reject('Unexpected: Task does not exist.');
} else {
resolve(new TaskExecutionImpl(this, execution.id, taskToCreate));
}
});
this._taskExecutionPromises.set(execution.id, createdResult);
return createdResult.then(executionCreatedResult => {
this._taskExecutions.set(execution.id, executionCreatedResult);
return executionCreatedResult;
}, rejected => {
return Promise.reject(rejected);
});
}
protected checkDeprecation(task: vscode.Task, handler: HandlerData) {
const tTask = (task as types.Task);
if (tTask._deprecated) {
this._deprecationService.report('Task.constructor', handler.extension, 'Use the Task constructor that takes a `scope` instead.');
}
}
private customExecutionComplete(execution: tasks.TaskExecutionDTO): void {
const extensionCallback2: vscode.CustomExecution | undefined = this._activeCustomExecutions2.get(execution.id);
if (extensionCallback2) {
this._activeCustomExecutions2.delete(execution.id);
}
// Technically we don't really need to do this, however, if an extension
// is executing a task through "executeTask" over and over again
// with different properties in the task definition, then the map of executions
// could grow indefinitely, something we don't want.
if (this._notProvidedCustomExecutions.has(execution.id) && (this._lastStartedTask !== execution.id)) {
this._providedCustomExecutions2.delete(execution.id);
this._notProvidedCustomExecutions.delete(execution.id);
}
let iterator = this._notProvidedCustomExecutions.values();
let iteratorResult = iterator.next();
while (!iteratorResult.done) {
if (!this._activeCustomExecutions2.has(iteratorResult.value) && (this._lastStartedTask !== iteratorResult.value)) {
this._providedCustomExecutions2.delete(iteratorResult.value);
this._notProvidedCustomExecutions.delete(iteratorResult.value);
}
iteratorResult = iterator.next();
}
}
public abstract $jsonTasksSupported(): Promise<boolean>;
public abstract $findExecutable(command: string, cwd?: string | undefined, paths?: string[] | undefined): Promise<string | undefined>;
}
export class WorkerExtHostTask extends ExtHostTaskBase {
constructor(
@IExtHostRpcService extHostRpc: IExtHostRpcService,
@IExtHostInitDataService initData: IExtHostInitDataService,
@IExtHostWorkspace workspaceService: IExtHostWorkspace,
@IExtHostDocumentsAndEditors editorService: IExtHostDocumentsAndEditors,
@IExtHostConfiguration configurationService: IExtHostConfiguration,
@IExtHostTerminalService extHostTerminalService: IExtHostTerminalService,
@ILogService logService: ILogService,
@IExtHostApiDeprecationService deprecationService: IExtHostApiDeprecationService
) {
super(extHostRpc, initData, workspaceService, editorService, configurationService, extHostTerminalService, logService, deprecationService);
this.registerTaskSystem(Schemas.vscodeRemote, {
scheme: Schemas.vscodeRemote,
authority: '',
platform: Platform.PlatformToString(Platform.Platform.Web)
});
}
public async executeTask(extension: IExtensionDescription, task: vscode.Task): Promise<vscode.TaskExecution> {
const dto = TaskDTO.from(task, extension);
if (dto === undefined) {
throw new Error('Task is not valid');
}
// If this task is a custom execution, then we need to save it away
// in the provided custom execution map that is cleaned up after the
// task is executed.
if (CustomExecutionDTO.is(dto.execution)) {
await this.addCustomExecution(dto, task, false);
} else {
throw new NotSupportedError();
}
// Always get the task execution first to prevent timing issues when retrieving it later
const execution = await this.getTaskExecution(await this._proxy.$getTaskExecution(dto), task);
this._proxy.$executeTask(dto).catch(error => { throw new Error(error); });
return execution;
}
protected provideTasksInternal(validTypes: { [key: string]: boolean; }, taskIdPromises: Promise<void>[], handler: HandlerData, value: vscode.Task[] | null | undefined): { tasks: tasks.TaskDTO[], extension: IExtensionDescription } {
const taskDTOs: tasks.TaskDTO[] = [];
if (value) {
for (let task of value) {
this.checkDeprecation(task, handler);
if (!task.definition || !validTypes[task.definition.type]) {
this._logService.warn(`The task [${task.source}, ${task.name}] uses an undefined task type. The task will be ignored in the future.`);
}
const taskDTO: tasks.TaskDTO | undefined = TaskDTO.from(task, handler.extension);
if (taskDTO && CustomExecutionDTO.is(taskDTO.execution)) {
taskDTOs.push(taskDTO);
// The ID is calculated on the main thread task side, so, let's call into it here.
// We need the task id's pre-computed for custom task executions because when OnDidStartTask
// is invoked, we have to be able to map it back to our data.
taskIdPromises.push(this.addCustomExecution(taskDTO, task, true));
} else {
this._logService.warn('Only custom execution tasks supported.');
}
}
}
return {
tasks: taskDTOs,
extension: handler.extension
};
}
protected async resolveTaskInternal(resolvedTaskDTO: tasks.TaskDTO): Promise<tasks.TaskDTO | undefined> {
if (CustomExecutionDTO.is(resolvedTaskDTO.execution)) {
return resolvedTaskDTO;
} else {
this._logService.warn('Only custom execution tasks supported.');
}
return undefined;
}
public async $resolveVariables(uriComponents: UriComponents, toResolve: { process?: { name: string; cwd?: string; path?: string }, variables: string[] }): Promise<{ process?: string, variables: { [key: string]: string; } }> {
const result = {
process: <unknown>undefined as string,
variables: Object.create(null)
};
return result;
}
public $getDefaultShellAndArgs(): Promise<{ shell: string, args: string[] | string | undefined }> {
throw new Error('Not implemented');
}
public async $jsonTasksSupported(): Promise<boolean> {
return false;
}
public async $findExecutable(command: string, cwd?: string | undefined, paths?: string[] | undefined): Promise<string | undefined> {
return undefined;
}
}
export const IExtHostTask = createDecorator<IExtHostTask>('IExtHostTask');

View File

@ -0,0 +1,856 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import type * as vscode from 'vscode';
import { Event, Emitter } from 'vs/base/common/event';
import { ExtHostTerminalServiceShape, MainContext, MainThreadTerminalServiceShape, IShellLaunchConfigDto, IShellDefinitionDto, IShellAndArgsDto, ITerminalDimensionsDto, ITerminalLinkDto } from 'vs/workbench/api/common/extHost.protocol';
import { ExtHostConfigProvider } from 'vs/workbench/api/common/extHostConfiguration';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { URI, UriComponents } from 'vs/base/common/uri';
import { ITerminalChildProcess, EXT_HOST_CREATION_DELAY, ITerminalLaunchError, ITerminalDimensionsOverride } from 'vs/workbench/contrib/terminal/common/terminal';
import { timeout } from 'vs/base/common/async';
import { IExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService';
import { TerminalDataBufferer } from 'vs/workbench/contrib/terminal/common/terminalDataBuffering';
import { IDisposable, DisposableStore, Disposable } from 'vs/base/common/lifecycle';
import { Disposable as VSCodeDisposable, EnvironmentVariableMutatorType } from './extHostTypes';
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { ISerializableEnvironmentVariableCollection } from 'vs/workbench/contrib/terminal/common/environmentVariable';
import { localize } from 'vs/nls';
import { NotSupportedError } from 'vs/base/common/errors';
import { serializeEnvironmentVariableCollection } from 'vs/workbench/contrib/terminal/common/environmentVariableShared';
import { CancellationTokenSource } from 'vs/base/common/cancellation';
export interface IExtHostTerminalService extends ExtHostTerminalServiceShape, IDisposable {
readonly _serviceBrand: undefined;
activeTerminal: vscode.Terminal | undefined;
terminals: vscode.Terminal[];
onDidCloseTerminal: Event<vscode.Terminal>;
onDidOpenTerminal: Event<vscode.Terminal>;
onDidChangeActiveTerminal: Event<vscode.Terminal | undefined>;
onDidChangeTerminalDimensions: Event<vscode.TerminalDimensionsChangeEvent>;
onDidWriteTerminalData: Event<vscode.TerminalDataWriteEvent>;
createTerminal(name?: string, shellPath?: string, shellArgs?: string[] | string): vscode.Terminal;
createTerminalFromOptions(options: vscode.TerminalOptions, isFeatureTerminal?: boolean): vscode.Terminal;
createExtensionTerminal(options: vscode.ExtensionTerminalOptions): vscode.Terminal;
attachPtyToTerminal(id: number, pty: vscode.Pseudoterminal): void;
getDefaultShell(useAutomationShell: boolean, configProvider: ExtHostConfigProvider): string;
getDefaultShellArgs(useAutomationShell: boolean, configProvider: ExtHostConfigProvider): string[] | string;
registerLinkProvider(provider: vscode.TerminalLinkProvider): vscode.Disposable;
getEnvironmentVariableCollection(extension: IExtensionDescription, persistent?: boolean): vscode.EnvironmentVariableCollection;
}
export const IExtHostTerminalService = createDecorator<IExtHostTerminalService>('IExtHostTerminalService');
export class BaseExtHostTerminal {
public _id: number | undefined;
protected _idPromise: Promise<number>;
private _idPromiseComplete: ((value: number) => any) | undefined;
private _disposed: boolean = false;
private _queuedRequests: ApiRequest[] = [];
constructor(
protected _proxy: MainThreadTerminalServiceShape,
id?: number
) {
this._idPromise = new Promise<number>(c => {
if (id !== undefined) {
this._id = id;
c(id);
} else {
this._idPromiseComplete = c;
}
});
}
public dispose(): void {
if (!this._disposed) {
this._disposed = true;
this._queueApiRequest(this._proxy.$dispose, []);
}
}
protected _checkDisposed() {
if (this._disposed) {
throw new Error('Terminal has already been disposed');
}
}
protected _queueApiRequest(callback: (...args: any[]) => void, args: any[]): void {
const request: ApiRequest = new ApiRequest(callback, args);
if (!this._id) {
this._queuedRequests.push(request);
return;
}
request.run(this._proxy, this._id);
}
public _runQueuedRequests(id: number): void {
this._id = id;
if (this._idPromiseComplete) {
this._idPromiseComplete(id);
this._idPromiseComplete = undefined;
}
this._queuedRequests.forEach((r) => {
r.run(this._proxy, id);
});
this._queuedRequests.length = 0;
}
}
export class ExtHostTerminal extends BaseExtHostTerminal implements vscode.Terminal {
private _pidPromise: Promise<number | undefined>;
private _cols: number | undefined;
private _pidPromiseComplete: ((value: number | undefined) => any) | undefined;
private _rows: number | undefined;
private _exitStatus: vscode.TerminalExitStatus | undefined;
public isOpen: boolean = false;
constructor(
proxy: MainThreadTerminalServiceShape,
private readonly _creationOptions: vscode.TerminalOptions | vscode.ExtensionTerminalOptions,
private _name?: string,
id?: number
) {
super(proxy, id);
this._creationOptions = Object.freeze(this._creationOptions);
this._pidPromise = new Promise<number | undefined>(c => this._pidPromiseComplete = c);
}
public async create(
shellPath?: string,
shellArgs?: string[] | string,
cwd?: string | URI,
env?: { [key: string]: string | null },
waitOnExit?: boolean,
strictEnv?: boolean,
hideFromUser?: boolean,
isFeatureTerminal?: boolean
): Promise<void> {
const result = await this._proxy.$createTerminal({ name: this._name, shellPath, shellArgs, cwd, env, waitOnExit, strictEnv, hideFromUser, isFeatureTerminal });
this._name = result.name;
this._runQueuedRequests(result.id);
}
public async createExtensionTerminal(): Promise<number> {
const result = await this._proxy.$createTerminal({ name: this._name, isExtensionTerminal: true });
this._name = result.name;
this._runQueuedRequests(result.id);
return result.id;
}
public get name(): string {
return this._name || '';
}
public set name(name: string) {
this._name = name;
}
public get exitStatus(): vscode.TerminalExitStatus | undefined {
return this._exitStatus;
}
public get dimensions(): vscode.TerminalDimensions | undefined {
if (this._cols === undefined || this._rows === undefined) {
return undefined;
}
return {
columns: this._cols,
rows: this._rows
};
}
public setExitCode(code: number | undefined) {
this._exitStatus = Object.freeze({ code });
}
public setDimensions(cols: number, rows: number): boolean {
if (cols === this._cols && rows === this._rows) {
// Nothing changed
return false;
}
if (cols === 0 || rows === 0) {
return false;
}
this._cols = cols;
this._rows = rows;
return true;
}
public get processId(): Promise<number | undefined> {
return this._pidPromise;
}
public get creationOptions(): Readonly<vscode.TerminalOptions | vscode.ExtensionTerminalOptions> {
return this._creationOptions;
}
public sendText(text: string, addNewLine: boolean = true): void {
this._checkDisposed();
this._queueApiRequest(this._proxy.$sendText, [text, addNewLine]);
}
public show(preserveFocus: boolean): void {
this._checkDisposed();
this._queueApiRequest(this._proxy.$show, [preserveFocus]);
}
public hide(): void {
this._checkDisposed();
this._queueApiRequest(this._proxy.$hide, []);
}
public _setProcessId(processId: number | undefined): void {
// The event may fire 2 times when the panel is restored
if (this._pidPromiseComplete) {
this._pidPromiseComplete(processId);
this._pidPromiseComplete = undefined;
} else {
// Recreate the promise if this is the nth processId set (e.g. reused task terminals)
this._pidPromise.then(pid => {
if (pid !== processId) {
this._pidPromise = Promise.resolve(processId);
}
});
}
}
}
class ApiRequest {
private _callback: (...args: any[]) => void;
private _args: any[];
constructor(callback: (...args: any[]) => void, args: any[]) {
this._callback = callback;
this._args = args;
}
public run(proxy: MainThreadTerminalServiceShape, id: number) {
this._callback.apply(proxy, [id].concat(this._args));
}
}
export class ExtHostPseudoterminal implements ITerminalChildProcess {
private readonly _onProcessData = new Emitter<string>();
public readonly onProcessData: Event<string> = this._onProcessData.event;
private readonly _onProcessExit = new Emitter<number | undefined>();
public readonly onProcessExit: Event<number | undefined> = this._onProcessExit.event;
private readonly _onProcessReady = new Emitter<{ pid: number, cwd: string }>();
public get onProcessReady(): Event<{ pid: number, cwd: string }> { return this._onProcessReady.event; }
private readonly _onProcessTitleChanged = new Emitter<string>();
public readonly onProcessTitleChanged: Event<string> = this._onProcessTitleChanged.event;
private readonly _onProcessOverrideDimensions = new Emitter<ITerminalDimensionsOverride | undefined>();
public get onProcessOverrideDimensions(): Event<ITerminalDimensionsOverride | undefined> { return this._onProcessOverrideDimensions.event; }
constructor(private readonly _pty: vscode.Pseudoterminal) { }
async start(): Promise<undefined> {
return undefined;
}
shutdown(): void {
this._pty.close();
}
input(data: string): void {
if (this._pty.handleInput) {
this._pty.handleInput(data);
}
}
resize(cols: number, rows: number): void {
if (this._pty.setDimensions) {
this._pty.setDimensions({ columns: cols, rows });
}
}
getInitialCwd(): Promise<string> {
return Promise.resolve('');
}
getCwd(): Promise<string> {
return Promise.resolve('');
}
getLatency(): Promise<number> {
return Promise.resolve(0);
}
startSendingEvents(initialDimensions: ITerminalDimensionsDto | undefined): void {
// Attach the listeners
this._pty.onDidWrite(e => this._onProcessData.fire(e));
if (this._pty.onDidClose) {
this._pty.onDidClose((e: number | void = undefined) => {
this._onProcessExit.fire(e === void 0 ? undefined : e);
});
}
if (this._pty.onDidOverrideDimensions) {
this._pty.onDidOverrideDimensions(e => this._onProcessOverrideDimensions.fire(e ? { cols: e.columns, rows: e.rows } : e));
}
this._pty.open(initialDimensions ? initialDimensions : undefined);
this._onProcessReady.fire({ pid: -1, cwd: '' });
}
}
let nextLinkId = 1;
interface ICachedLinkEntry {
provider: vscode.TerminalLinkProvider;
link: vscode.TerminalLink;
}
export abstract class BaseExtHostTerminalService extends Disposable implements IExtHostTerminalService, ExtHostTerminalServiceShape {
readonly _serviceBrand: undefined;
protected _proxy: MainThreadTerminalServiceShape;
protected _activeTerminal: ExtHostTerminal | undefined;
protected _terminals: ExtHostTerminal[] = [];
protected _terminalProcesses: Map<number, ITerminalChildProcess> = new Map();
protected _terminalProcessDisposables: { [id: number]: IDisposable } = {};
protected _extensionTerminalAwaitingStart: { [id: number]: { initialDimensions: ITerminalDimensionsDto | undefined } | undefined } = {};
protected _getTerminalPromises: { [id: number]: Promise<ExtHostTerminal | undefined> } = {};
protected _environmentVariableCollections: Map<string, EnvironmentVariableCollection> = new Map();
private readonly _bufferer: TerminalDataBufferer;
private readonly _linkProviders: Set<vscode.TerminalLinkProvider> = new Set();
private readonly _terminalLinkCache: Map<number, Map<number, ICachedLinkEntry>> = new Map();
private readonly _terminalLinkCancellationSource: Map<number, CancellationTokenSource> = new Map();
public get activeTerminal(): ExtHostTerminal | undefined { return this._activeTerminal; }
public get terminals(): ExtHostTerminal[] { return this._terminals; }
protected readonly _onDidCloseTerminal: Emitter<vscode.Terminal> = new Emitter<vscode.Terminal>();
public get onDidCloseTerminal(): Event<vscode.Terminal> { return this._onDidCloseTerminal && this._onDidCloseTerminal.event; }
protected readonly _onDidOpenTerminal: Emitter<vscode.Terminal> = new Emitter<vscode.Terminal>();
public get onDidOpenTerminal(): Event<vscode.Terminal> { return this._onDidOpenTerminal && this._onDidOpenTerminal.event; }
protected readonly _onDidChangeActiveTerminal: Emitter<vscode.Terminal | undefined> = new Emitter<vscode.Terminal | undefined>();
public get onDidChangeActiveTerminal(): Event<vscode.Terminal | undefined> { return this._onDidChangeActiveTerminal && this._onDidChangeActiveTerminal.event; }
protected readonly _onDidChangeTerminalDimensions: Emitter<vscode.TerminalDimensionsChangeEvent> = new Emitter<vscode.TerminalDimensionsChangeEvent>();
public get onDidChangeTerminalDimensions(): Event<vscode.TerminalDimensionsChangeEvent> { return this._onDidChangeTerminalDimensions && this._onDidChangeTerminalDimensions.event; }
protected readonly _onDidWriteTerminalData: Emitter<vscode.TerminalDataWriteEvent>;
public get onDidWriteTerminalData(): Event<vscode.TerminalDataWriteEvent> { return this._onDidWriteTerminalData && this._onDidWriteTerminalData.event; }
constructor(
supportsProcesses: boolean,
@IExtHostRpcService extHostRpc: IExtHostRpcService
) {
super();
this._proxy = extHostRpc.getProxy(MainContext.MainThreadTerminalService);
this._bufferer = new TerminalDataBufferer(this._proxy.$sendProcessData);
this._onDidWriteTerminalData = new Emitter<vscode.TerminalDataWriteEvent>({
onFirstListenerAdd: () => this._proxy.$startSendingDataEvents(),
onLastListenerRemove: () => this._proxy.$stopSendingDataEvents()
});
this._proxy.$registerProcessSupport(supportsProcesses);
this._register({
dispose: () => {
for (const [_, terminalProcess] of this._terminalProcesses) {
terminalProcess.shutdown(true);
}
}
});
}
public abstract createTerminal(name?: string, shellPath?: string, shellArgs?: string[] | string): vscode.Terminal;
public abstract createTerminalFromOptions(options: vscode.TerminalOptions): vscode.Terminal;
public abstract getDefaultShell(useAutomationShell: boolean, configProvider: ExtHostConfigProvider): string;
public abstract getDefaultShellArgs(useAutomationShell: boolean, configProvider: ExtHostConfigProvider): string[] | string;
public abstract $spawnExtHostProcess(id: number, shellLaunchConfigDto: IShellLaunchConfigDto, activeWorkspaceRootUriComponents: UriComponents, cols: number, rows: number, isWorkspaceShellAllowed: boolean): Promise<ITerminalLaunchError | undefined>;
public abstract $getAvailableShells(): Promise<IShellDefinitionDto[]>;
public abstract $getDefaultShellAndArgs(useAutomationShell: boolean): Promise<IShellAndArgsDto>;
public abstract $acceptWorkspacePermissionsChanged(isAllowed: boolean): void;
public createExtensionTerminal(options: vscode.ExtensionTerminalOptions): vscode.Terminal {
const terminal = new ExtHostTerminal(this._proxy, options, options.name);
const p = new ExtHostPseudoterminal(options.pty);
terminal.createExtensionTerminal().then(id => {
const disposable = this._setupExtHostProcessListeners(id, p);
this._terminalProcessDisposables[id] = disposable;
});
this._terminals.push(terminal);
return terminal;
}
public attachPtyToTerminal(id: number, pty: vscode.Pseudoterminal): void {
const terminal = this._getTerminalByIdEventually(id);
if (!terminal) {
throw new Error(`Cannot resolve terminal with id ${id} for virtual process`);
}
const p = new ExtHostPseudoterminal(pty);
const disposable = this._setupExtHostProcessListeners(id, p);
this._terminalProcessDisposables[id] = disposable;
}
public async $acceptActiveTerminalChanged(id: number | null): Promise<void> {
const original = this._activeTerminal;
if (id === null) {
this._activeTerminal = undefined;
if (original !== this._activeTerminal) {
this._onDidChangeActiveTerminal.fire(this._activeTerminal);
}
return;
}
const terminal = await this._getTerminalByIdEventually(id);
if (terminal) {
this._activeTerminal = terminal;
if (original !== this._activeTerminal) {
this._onDidChangeActiveTerminal.fire(this._activeTerminal);
}
}
}
public async $acceptTerminalProcessData(id: number, data: string): Promise<void> {
const terminal = await this._getTerminalByIdEventually(id);
if (terminal) {
this._onDidWriteTerminalData.fire({ terminal, data });
}
}
public async $acceptTerminalDimensions(id: number, cols: number, rows: number): Promise<void> {
const terminal = await this._getTerminalByIdEventually(id);
if (terminal) {
if (terminal.setDimensions(cols, rows)) {
this._onDidChangeTerminalDimensions.fire({
terminal: terminal,
dimensions: terminal.dimensions as vscode.TerminalDimensions
});
}
}
}
public async $acceptTerminalMaximumDimensions(id: number, cols: number, rows: number): Promise<void> {
await this._getTerminalByIdEventually(id);
// Extension pty terminal only - when virtual process resize fires it means that the
// terminal's maximum dimensions changed
this._terminalProcesses.get(id)?.resize(cols, rows);
}
public async $acceptTerminalTitleChange(id: number, name: string): Promise<void> {
await this._getTerminalByIdEventually(id);
const extHostTerminal = this._getTerminalObjectById(this.terminals, id);
if (extHostTerminal) {
extHostTerminal.name = name;
}
}
public async $acceptTerminalClosed(id: number, exitCode: number | undefined): Promise<void> {
await this._getTerminalByIdEventually(id);
const index = this._getTerminalObjectIndexById(this.terminals, id);
if (index !== null) {
const terminal = this._terminals.splice(index, 1)[0];
terminal.setExitCode(exitCode);
this._onDidCloseTerminal.fire(terminal);
}
}
public $acceptTerminalOpened(id: number, name: string, shellLaunchConfigDto: IShellLaunchConfigDto): void {
const index = this._getTerminalObjectIndexById(this._terminals, id);
if (index !== null) {
// The terminal has already been created (via createTerminal*), only fire the event
this._onDidOpenTerminal.fire(this.terminals[index]);
this.terminals[index].isOpen = true;
return;
}
const creationOptions: vscode.TerminalOptions = {
name: shellLaunchConfigDto.name,
shellPath: shellLaunchConfigDto.executable,
shellArgs: shellLaunchConfigDto.args,
cwd: typeof shellLaunchConfigDto.cwd === 'string' ? shellLaunchConfigDto.cwd : URI.revive(shellLaunchConfigDto.cwd),
env: shellLaunchConfigDto.env,
hideFromUser: shellLaunchConfigDto.hideFromUser
};
const terminal = new ExtHostTerminal(this._proxy, creationOptions, name, id);
this._terminals.push(terminal);
this._onDidOpenTerminal.fire(terminal);
terminal.isOpen = true;
}
public async $acceptTerminalProcessId(id: number, processId: number): Promise<void> {
const terminal = await this._getTerminalByIdEventually(id);
if (terminal) {
terminal._setProcessId(processId);
}
}
public async $startExtensionTerminal(id: number, initialDimensions: ITerminalDimensionsDto | undefined): Promise<ITerminalLaunchError | undefined> {
// Make sure the ExtHostTerminal exists so onDidOpenTerminal has fired before we call
// Pseudoterminal.start
const terminal = await this._getTerminalByIdEventually(id);
if (!terminal) {
return { message: localize('launchFail.idMissingOnExtHost', "Could not find the terminal with id {0} on the extension host", id) };
}
// Wait for onDidOpenTerminal to fire
if (!terminal.isOpen) {
await new Promise<void>(r => {
// Ensure open is called after onDidOpenTerminal
const listener = this.onDidOpenTerminal(async e => {
if (e === terminal) {
listener.dispose();
r();
}
});
});
}
const terminalProcess = this._terminalProcesses.get(id);
if (terminalProcess) {
(terminalProcess as ExtHostPseudoterminal).startSendingEvents(initialDimensions);
} else {
// Defer startSendingEvents call to when _setupExtHostProcessListeners is called
this._extensionTerminalAwaitingStart[id] = { initialDimensions };
}
return undefined;
}
protected _setupExtHostProcessListeners(id: number, p: ITerminalChildProcess): IDisposable {
const disposables = new DisposableStore();
disposables.add(p.onProcessReady((e: { pid: number, cwd: string }) => this._proxy.$sendProcessReady(id, e.pid, e.cwd)));
disposables.add(p.onProcessTitleChanged(title => this._proxy.$sendProcessTitle(id, title)));
// Buffer data events to reduce the amount of messages going to the renderer
this._bufferer.startBuffering(id, p.onProcessData);
disposables.add(p.onProcessExit(exitCode => this._onProcessExit(id, exitCode)));
if (p.onProcessOverrideDimensions) {
disposables.add(p.onProcessOverrideDimensions(e => this._proxy.$sendOverrideDimensions(id, e)));
}
this._terminalProcesses.set(id, p);
const awaitingStart = this._extensionTerminalAwaitingStart[id];
if (awaitingStart && p instanceof ExtHostPseudoterminal) {
p.startSendingEvents(awaitingStart.initialDimensions);
delete this._extensionTerminalAwaitingStart[id];
}
return disposables;
}
public $acceptProcessInput(id: number, data: string): void {
this._terminalProcesses.get(id)?.input(data);
}
public $acceptProcessResize(id: number, cols: number, rows: number): void {
try {
this._terminalProcesses.get(id)?.resize(cols, rows);
} catch (error) {
// We tried to write to a closed pipe / channel.
if (error.code !== 'EPIPE' && error.code !== 'ERR_IPC_CHANNEL_CLOSED') {
throw (error);
}
}
}
public $acceptProcessShutdown(id: number, immediate: boolean): void {
this._terminalProcesses.get(id)?.shutdown(immediate);
}
public $acceptProcessRequestInitialCwd(id: number): void {
this._terminalProcesses.get(id)?.getInitialCwd().then(initialCwd => this._proxy.$sendProcessInitialCwd(id, initialCwd));
}
public $acceptProcessRequestCwd(id: number): void {
this._terminalProcesses.get(id)?.getCwd().then(cwd => this._proxy.$sendProcessCwd(id, cwd));
}
public $acceptProcessRequestLatency(id: number): number {
return id;
}
public registerLinkProvider(provider: vscode.TerminalLinkProvider): vscode.Disposable {
this._linkProviders.add(provider);
if (this._linkProviders.size === 1) {
this._proxy.$startLinkProvider();
}
return new VSCodeDisposable(() => {
this._linkProviders.delete(provider);
if (this._linkProviders.size === 0) {
this._proxy.$stopLinkProvider();
}
});
}
public async $provideLinks(terminalId: number, line: string): Promise<ITerminalLinkDto[]> {
const terminal = this._getTerminalById(terminalId);
if (!terminal) {
return [];
}
// Discard any cached links the terminal has been holding, currently all links are released
// when new links are provided.
this._terminalLinkCache.delete(terminalId);
const oldToken = this._terminalLinkCancellationSource.get(terminalId);
if (oldToken) {
oldToken.dispose(true);
}
const cancellationSource = new CancellationTokenSource();
this._terminalLinkCancellationSource.set(terminalId, cancellationSource);
const result: ITerminalLinkDto[] = [];
const context: vscode.TerminalLinkContext = { terminal, line };
const promises: vscode.ProviderResult<{ provider: vscode.TerminalLinkProvider, links: vscode.TerminalLink[] }>[] = [];
for (const provider of this._linkProviders) {
promises.push(new Promise(async r => {
cancellationSource.token.onCancellationRequested(() => r({ provider, links: [] }));
const links = (await provider.provideTerminalLinks(context, cancellationSource.token)) || [];
if (!cancellationSource.token.isCancellationRequested) {
r({ provider, links });
}
}));
}
const provideResults = await Promise.all(promises);
if (cancellationSource.token.isCancellationRequested) {
return [];
}
const cacheLinkMap = new Map<number, ICachedLinkEntry>();
for (const provideResult of provideResults) {
if (provideResult && provideResult.links.length > 0) {
result.push(...provideResult.links.map(providerLink => {
const link = {
id: nextLinkId++,
startIndex: providerLink.startIndex,
length: providerLink.length,
label: providerLink.tooltip
};
cacheLinkMap.set(link.id, {
provider: provideResult.provider,
link: providerLink
});
return link;
}));
}
}
this._terminalLinkCache.set(terminalId, cacheLinkMap);
return result;
}
$activateLink(terminalId: number, linkId: number): void {
const cachedLink = this._terminalLinkCache.get(terminalId)?.get(linkId);
if (!cachedLink) {
return;
}
cachedLink.provider.handleTerminalLink(cachedLink.link);
}
private _onProcessExit(id: number, exitCode: number | undefined): void {
this._bufferer.stopBuffering(id);
// Remove process reference
this._terminalProcesses.delete(id);
delete this._extensionTerminalAwaitingStart[id];
// Clean up process disposables
const processDiposable = this._terminalProcessDisposables[id];
if (processDiposable) {
processDiposable.dispose();
delete this._terminalProcessDisposables[id];
}
// Send exit event to main side
this._proxy.$sendProcessExit(id, exitCode);
}
// TODO: This could be improved by using a single promise and resolve it when the terminal is ready
private _getTerminalByIdEventually(id: number, retries: number = 5): Promise<ExtHostTerminal | undefined> {
if (!this._getTerminalPromises[id]) {
this._getTerminalPromises[id] = this._createGetTerminalPromise(id, retries);
}
return this._getTerminalPromises[id];
}
private _createGetTerminalPromise(id: number, retries: number = 5): Promise<ExtHostTerminal | undefined> {
return new Promise(c => {
if (retries === 0) {
c(undefined);
return;
}
const terminal = this._getTerminalById(id);
if (terminal) {
c(terminal);
} else {
// This should only be needed immediately after createTerminalRenderer is called as
// the ExtHostTerminal has not yet been iniitalized
timeout(EXT_HOST_CREATION_DELAY * 2).then(() => c(this._createGetTerminalPromise(id, retries - 1)));
}
});
}
private _getTerminalById(id: number): ExtHostTerminal | null {
return this._getTerminalObjectById(this._terminals, id);
}
private _getTerminalObjectById<T extends ExtHostTerminal>(array: T[], id: number): T | null {
const index = this._getTerminalObjectIndexById(array, id);
return index !== null ? array[index] : null;
}
private _getTerminalObjectIndexById<T extends ExtHostTerminal>(array: T[], id: number): number | null {
let index: number | null = null;
array.some((item, i) => {
const thisId = item._id;
if (thisId === id) {
index = i;
return true;
}
return false;
});
return index;
}
public getEnvironmentVariableCollection(extension: IExtensionDescription): vscode.EnvironmentVariableCollection {
let collection = this._environmentVariableCollections.get(extension.identifier.value);
if (!collection) {
collection = new EnvironmentVariableCollection();
this._setEnvironmentVariableCollection(extension.identifier.value, collection);
}
return collection;
}
private _syncEnvironmentVariableCollection(extensionIdentifier: string, collection: EnvironmentVariableCollection): void {
const serialized = serializeEnvironmentVariableCollection(collection.map);
this._proxy.$setEnvironmentVariableCollection(extensionIdentifier, collection.persistent, serialized.length === 0 ? undefined : serialized);
}
public $initEnvironmentVariableCollections(collections: [string, ISerializableEnvironmentVariableCollection][]): void {
collections.forEach(entry => {
const extensionIdentifier = entry[0];
const collection = new EnvironmentVariableCollection(entry[1]);
this._setEnvironmentVariableCollection(extensionIdentifier, collection);
});
}
private _setEnvironmentVariableCollection(extensionIdentifier: string, collection: EnvironmentVariableCollection): void {
this._environmentVariableCollections.set(extensionIdentifier, collection);
collection.onDidChangeCollection(() => {
// When any collection value changes send this immediately, this is done to ensure
// following calls to createTerminal will be created with the new environment. It will
// result in more noise by sending multiple updates when called but collections are
// expected to be small.
this._syncEnvironmentVariableCollection(extensionIdentifier, collection!);
});
}
}
export class EnvironmentVariableCollection implements vscode.EnvironmentVariableCollection {
readonly map: Map<string, vscode.EnvironmentVariableMutator> = new Map();
private _persistent: boolean = true;
public get persistent(): boolean { return this._persistent; }
public set persistent(value: boolean) {
this._persistent = value;
this._onDidChangeCollection.fire();
}
protected readonly _onDidChangeCollection: Emitter<void> = new Emitter<void>();
get onDidChangeCollection(): Event<void> { return this._onDidChangeCollection && this._onDidChangeCollection.event; }
constructor(
serialized?: ISerializableEnvironmentVariableCollection
) {
this.map = new Map(serialized);
}
get size(): number {
return this.map.size;
}
replace(variable: string, value: string): void {
this._setIfDiffers(variable, { value, type: EnvironmentVariableMutatorType.Replace });
}
append(variable: string, value: string): void {
this._setIfDiffers(variable, { value, type: EnvironmentVariableMutatorType.Append });
}
prepend(variable: string, value: string): void {
this._setIfDiffers(variable, { value, type: EnvironmentVariableMutatorType.Prepend });
}
private _setIfDiffers(variable: string, mutator: vscode.EnvironmentVariableMutator): void {
const current = this.map.get(variable);
if (!current || current.value !== mutator.value || current.type !== mutator.type) {
this.map.set(variable, mutator);
this._onDidChangeCollection.fire();
}
}
get(variable: string): vscode.EnvironmentVariableMutator | undefined {
return this.map.get(variable);
}
forEach(callback: (variable: string, mutator: vscode.EnvironmentVariableMutator, collection: vscode.EnvironmentVariableCollection) => any, thisArg?: any): void {
this.map.forEach((value, key) => callback.call(thisArg, key, value, this));
}
delete(variable: string): void {
this.map.delete(variable);
this._onDidChangeCollection.fire();
}
clear(): void {
this.map.clear();
this._onDidChangeCollection.fire();
}
}
export class WorkerExtHostTerminalService extends BaseExtHostTerminalService {
constructor(
@IExtHostRpcService extHostRpc: IExtHostRpcService
) {
super(false, extHostRpc);
}
public createTerminal(name?: string, shellPath?: string, shellArgs?: string[] | string): vscode.Terminal {
throw new NotSupportedError();
}
public createTerminalFromOptions(options: vscode.TerminalOptions): vscode.Terminal {
throw new NotSupportedError();
}
public getDefaultShell(useAutomationShell: boolean, configProvider: ExtHostConfigProvider): string {
// Return the empty string to avoid throwing
return '';
}
public getDefaultShellArgs(useAutomationShell: boolean, configProvider: ExtHostConfigProvider): string[] | string {
throw new NotSupportedError();
}
public $spawnExtHostProcess(id: number, shellLaunchConfigDto: IShellLaunchConfigDto, activeWorkspaceRootUriComponents: UriComponents, cols: number, rows: number, isWorkspaceShellAllowed: boolean): Promise<ITerminalLaunchError | undefined> {
throw new NotSupportedError();
}
public $getAvailableShells(): Promise<IShellDefinitionDto[]> {
throw new NotSupportedError();
}
public async $getDefaultShellAndArgs(useAutomationShell: boolean): Promise<IShellAndArgsDto> {
throw new NotSupportedError();
}
public $acceptWorkspacePermissionsChanged(isAllowed: boolean): void {
// No-op for web worker ext host as workspace permissions aren't used
}
}

View File

@ -0,0 +1,662 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ok } from 'vs/base/common/assert';
import { illegalArgument, readonly } from 'vs/base/common/errors';
import { IdGenerator } from 'vs/base/common/idGenerator';
import { TextEditorCursorStyle } from 'vs/editor/common/config/editorOptions';
import { IRange } from 'vs/editor/common/core/range';
import { ISingleEditOperation } from 'vs/editor/common/model';
import { IResolvedTextEditorConfiguration, ITextEditorConfigurationUpdate, MainThreadTextEditorsShape } from 'vs/workbench/api/common/extHost.protocol';
import { ExtHostDocumentData } from 'vs/workbench/api/common/extHostDocumentData';
import * as TypeConverters from 'vs/workbench/api/common/extHostTypeConverters';
import { EndOfLine, Position, Range, Selection, SnippetString, TextEditorLineNumbersStyle, TextEditorRevealType } from 'vs/workbench/api/common/extHostTypes';
import type * as vscode from 'vscode';
import { ILogService } from 'vs/platform/log/common/log';
export class TextEditorDecorationType implements vscode.TextEditorDecorationType {
private static readonly _Keys = new IdGenerator('TextEditorDecorationType');
private _proxy: MainThreadTextEditorsShape;
public key: string;
constructor(proxy: MainThreadTextEditorsShape, options: vscode.DecorationRenderOptions) {
this.key = TextEditorDecorationType._Keys.nextId();
this._proxy = proxy;
this._proxy.$registerTextEditorDecorationType(this.key, TypeConverters.DecorationRenderOptions.from(options));
}
public dispose(): void {
this._proxy.$removeTextEditorDecorationType(this.key);
}
}
export interface ITextEditOperation {
range: vscode.Range;
text: string | null;
forceMoveMarkers: boolean;
}
export interface IEditData {
documentVersionId: number;
edits: ITextEditOperation[];
setEndOfLine: EndOfLine | undefined;
undoStopBefore: boolean;
undoStopAfter: boolean;
}
export class TextEditorEdit {
private readonly _document: vscode.TextDocument;
private readonly _documentVersionId: number;
private readonly _undoStopBefore: boolean;
private readonly _undoStopAfter: boolean;
private _collectedEdits: ITextEditOperation[] = [];
private _setEndOfLine: EndOfLine | undefined = undefined;
private _finalized: boolean = false;
constructor(document: vscode.TextDocument, options: { undoStopBefore: boolean; undoStopAfter: boolean; }) {
this._document = document;
this._documentVersionId = document.version;
this._undoStopBefore = options.undoStopBefore;
this._undoStopAfter = options.undoStopAfter;
}
finalize(): IEditData {
this._finalized = true;
return {
documentVersionId: this._documentVersionId,
edits: this._collectedEdits,
setEndOfLine: this._setEndOfLine,
undoStopBefore: this._undoStopBefore,
undoStopAfter: this._undoStopAfter
};
}
private _throwIfFinalized() {
if (this._finalized) {
throw new Error('Edit is only valid while callback runs');
}
}
replace(location: Position | Range | Selection, value: string): void {
this._throwIfFinalized();
let range: Range | null = null;
if (location instanceof Position) {
range = new Range(location, location);
} else if (location instanceof Range) {
range = location;
} else {
throw new Error('Unrecognized location');
}
this._pushEdit(range, value, false);
}
insert(location: Position, value: string): void {
this._throwIfFinalized();
this._pushEdit(new Range(location, location), value, true);
}
delete(location: Range | Selection): void {
this._throwIfFinalized();
let range: Range | null = null;
if (location instanceof Range) {
range = location;
} else {
throw new Error('Unrecognized location');
}
this._pushEdit(range, null, true);
}
private _pushEdit(range: Range, text: string | null, forceMoveMarkers: boolean): void {
const validRange = this._document.validateRange(range);
this._collectedEdits.push({
range: validRange,
text: text,
forceMoveMarkers: forceMoveMarkers
});
}
setEndOfLine(endOfLine: EndOfLine): void {
this._throwIfFinalized();
if (endOfLine !== EndOfLine.LF && endOfLine !== EndOfLine.CRLF) {
throw illegalArgument('endOfLine');
}
this._setEndOfLine = endOfLine;
}
}
export class ExtHostTextEditorOptions implements vscode.TextEditorOptions {
private _proxy: MainThreadTextEditorsShape;
private _id: string;
private _logService: ILogService;
private _tabSize!: number;
private _indentSize!: number;
private _insertSpaces!: boolean;
private _cursorStyle!: TextEditorCursorStyle;
private _lineNumbers!: TextEditorLineNumbersStyle;
constructor(proxy: MainThreadTextEditorsShape, id: string, source: IResolvedTextEditorConfiguration, logService: ILogService) {
this._proxy = proxy;
this._id = id;
this._accept(source);
this._logService = logService;
}
public _accept(source: IResolvedTextEditorConfiguration): void {
this._tabSize = source.tabSize;
this._indentSize = source.indentSize;
this._insertSpaces = source.insertSpaces;
this._cursorStyle = source.cursorStyle;
this._lineNumbers = TypeConverters.TextEditorLineNumbersStyle.to(source.lineNumbers);
}
public get tabSize(): number | string {
return this._tabSize;
}
private _validateTabSize(value: number | string): number | 'auto' | null {
if (value === 'auto') {
return 'auto';
}
if (typeof value === 'number') {
const r = Math.floor(value);
return (r > 0 ? r : null);
}
if (typeof value === 'string') {
const r = parseInt(value, 10);
if (isNaN(r)) {
return null;
}
return (r > 0 ? r : null);
}
return null;
}
public set tabSize(value: number | string) {
const tabSize = this._validateTabSize(value);
if (tabSize === null) {
// ignore invalid call
return;
}
if (typeof tabSize === 'number') {
if (this._tabSize === tabSize) {
// nothing to do
return;
}
// reflect the new tabSize value immediately
this._tabSize = tabSize;
}
this._warnOnError(this._proxy.$trySetOptions(this._id, {
tabSize: tabSize
}));
}
public get indentSize(): number | string {
return this._indentSize;
}
private _validateIndentSize(value: number | string): number | 'tabSize' | null {
if (value === 'tabSize') {
return 'tabSize';
}
if (typeof value === 'number') {
const r = Math.floor(value);
return (r > 0 ? r : null);
}
if (typeof value === 'string') {
const r = parseInt(value, 10);
if (isNaN(r)) {
return null;
}
return (r > 0 ? r : null);
}
return null;
}
public set indentSize(value: number | string) {
const indentSize = this._validateIndentSize(value);
if (indentSize === null) {
// ignore invalid call
return;
}
if (typeof indentSize === 'number') {
if (this._indentSize === indentSize) {
// nothing to do
return;
}
// reflect the new indentSize value immediately
this._indentSize = indentSize;
}
this._warnOnError(this._proxy.$trySetOptions(this._id, {
indentSize: indentSize
}));
}
public get insertSpaces(): boolean | string {
return this._insertSpaces;
}
private _validateInsertSpaces(value: boolean | string): boolean | 'auto' {
if (value === 'auto') {
return 'auto';
}
return (value === 'false' ? false : Boolean(value));
}
public set insertSpaces(value: boolean | string) {
const insertSpaces = this._validateInsertSpaces(value);
if (typeof insertSpaces === 'boolean') {
if (this._insertSpaces === insertSpaces) {
// nothing to do
return;
}
// reflect the new insertSpaces value immediately
this._insertSpaces = insertSpaces;
}
this._warnOnError(this._proxy.$trySetOptions(this._id, {
insertSpaces: insertSpaces
}));
}
public get cursorStyle(): TextEditorCursorStyle {
return this._cursorStyle;
}
public set cursorStyle(value: TextEditorCursorStyle) {
if (this._cursorStyle === value) {
// nothing to do
return;
}
this._cursorStyle = value;
this._warnOnError(this._proxy.$trySetOptions(this._id, {
cursorStyle: value
}));
}
public get lineNumbers(): TextEditorLineNumbersStyle {
return this._lineNumbers;
}
public set lineNumbers(value: TextEditorLineNumbersStyle) {
if (this._lineNumbers === value) {
// nothing to do
return;
}
this._lineNumbers = value;
this._warnOnError(this._proxy.$trySetOptions(this._id, {
lineNumbers: TypeConverters.TextEditorLineNumbersStyle.from(value)
}));
}
public assign(newOptions: vscode.TextEditorOptions) {
const bulkConfigurationUpdate: ITextEditorConfigurationUpdate = {};
let hasUpdate = false;
if (typeof newOptions.tabSize !== 'undefined') {
const tabSize = this._validateTabSize(newOptions.tabSize);
if (tabSize === 'auto') {
hasUpdate = true;
bulkConfigurationUpdate.tabSize = tabSize;
} else if (typeof tabSize === 'number' && this._tabSize !== tabSize) {
// reflect the new tabSize value immediately
this._tabSize = tabSize;
hasUpdate = true;
bulkConfigurationUpdate.tabSize = tabSize;
}
}
// if (typeof newOptions.indentSize !== 'undefined') {
// const indentSize = this._validateIndentSize(newOptions.indentSize);
// if (indentSize === 'tabSize') {
// hasUpdate = true;
// bulkConfigurationUpdate.indentSize = indentSize;
// } else if (typeof indentSize === 'number' && this._indentSize !== indentSize) {
// // reflect the new indentSize value immediately
// this._indentSize = indentSize;
// hasUpdate = true;
// bulkConfigurationUpdate.indentSize = indentSize;
// }
// }
if (typeof newOptions.insertSpaces !== 'undefined') {
const insertSpaces = this._validateInsertSpaces(newOptions.insertSpaces);
if (insertSpaces === 'auto') {
hasUpdate = true;
bulkConfigurationUpdate.insertSpaces = insertSpaces;
} else if (this._insertSpaces !== insertSpaces) {
// reflect the new insertSpaces value immediately
this._insertSpaces = insertSpaces;
hasUpdate = true;
bulkConfigurationUpdate.insertSpaces = insertSpaces;
}
}
if (typeof newOptions.cursorStyle !== 'undefined') {
if (this._cursorStyle !== newOptions.cursorStyle) {
this._cursorStyle = newOptions.cursorStyle;
hasUpdate = true;
bulkConfigurationUpdate.cursorStyle = newOptions.cursorStyle;
}
}
if (typeof newOptions.lineNumbers !== 'undefined') {
if (this._lineNumbers !== newOptions.lineNumbers) {
this._lineNumbers = newOptions.lineNumbers;
hasUpdate = true;
bulkConfigurationUpdate.lineNumbers = TypeConverters.TextEditorLineNumbersStyle.from(newOptions.lineNumbers);
}
}
if (hasUpdate) {
this._warnOnError(this._proxy.$trySetOptions(this._id, bulkConfigurationUpdate));
}
}
private _warnOnError(promise: Promise<any>): void {
promise.catch(err => this._logService.warn(err));
}
}
export class ExtHostTextEditor implements vscode.TextEditor {
private readonly _documentData: ExtHostDocumentData;
private _selections: Selection[];
private _options: ExtHostTextEditorOptions;
private _visibleRanges: Range[];
private _viewColumn: vscode.ViewColumn | undefined;
private _disposed: boolean = false;
private _hasDecorationsForKey: { [key: string]: boolean; };
constructor(
readonly id: string,
private readonly _proxy: MainThreadTextEditorsShape,
private readonly _logService: ILogService,
document: ExtHostDocumentData,
selections: Selection[], options: IResolvedTextEditorConfiguration,
visibleRanges: Range[], viewColumn: vscode.ViewColumn | undefined
) {
this._documentData = document;
this._selections = selections;
this._options = new ExtHostTextEditorOptions(this._proxy, this.id, options, _logService);
this._visibleRanges = visibleRanges;
this._viewColumn = viewColumn;
this._hasDecorationsForKey = Object.create(null);
}
dispose() {
ok(!this._disposed);
this._disposed = true;
}
show(column: vscode.ViewColumn) {
this._proxy.$tryShowEditor(this.id, TypeConverters.ViewColumn.from(column));
}
hide() {
this._proxy.$tryHideEditor(this.id);
}
// ---- the document
get document(): vscode.TextDocument {
return this._documentData.document;
}
set document(value) {
throw readonly('document');
}
// ---- options
get options(): vscode.TextEditorOptions {
return this._options;
}
set options(value: vscode.TextEditorOptions) {
if (!this._disposed) {
this._options.assign(value);
}
}
_acceptOptions(options: IResolvedTextEditorConfiguration): void {
ok(!this._disposed);
this._options._accept(options);
}
// ---- visible ranges
get visibleRanges(): Range[] {
return this._visibleRanges;
}
set visibleRanges(value: Range[]) {
throw readonly('visibleRanges');
}
_acceptVisibleRanges(value: Range[]): void {
ok(!this._disposed);
this._visibleRanges = value;
}
// ---- view column
get viewColumn(): vscode.ViewColumn | undefined {
return this._viewColumn;
}
set viewColumn(value) {
throw readonly('viewColumn');
}
_acceptViewColumn(value: vscode.ViewColumn) {
ok(!this._disposed);
this._viewColumn = value;
}
// ---- selections
get selection(): Selection {
return this._selections && this._selections[0];
}
set selection(value: Selection) {
if (!(value instanceof Selection)) {
throw illegalArgument('selection');
}
this._selections = [value];
this._trySetSelection();
}
get selections(): Selection[] {
return this._selections;
}
set selections(value: Selection[]) {
if (!Array.isArray(value) || value.some(a => !(a instanceof Selection))) {
throw illegalArgument('selections');
}
this._selections = value;
this._trySetSelection();
}
setDecorations(decorationType: vscode.TextEditorDecorationType, ranges: Range[] | vscode.DecorationOptions[]): void {
const willBeEmpty = (ranges.length === 0);
if (willBeEmpty && !this._hasDecorationsForKey[decorationType.key]) {
// avoid no-op call to the renderer
return;
}
if (willBeEmpty) {
delete this._hasDecorationsForKey[decorationType.key];
} else {
this._hasDecorationsForKey[decorationType.key] = true;
}
this._runOnProxy(
() => {
if (TypeConverters.isDecorationOptionsArr(ranges)) {
return this._proxy.$trySetDecorations(
this.id,
decorationType.key,
TypeConverters.fromRangeOrRangeWithMessage(ranges)
);
} else {
const _ranges: number[] = new Array<number>(4 * ranges.length);
for (let i = 0, len = ranges.length; i < len; i++) {
const range = ranges[i];
_ranges[4 * i] = range.start.line + 1;
_ranges[4 * i + 1] = range.start.character + 1;
_ranges[4 * i + 2] = range.end.line + 1;
_ranges[4 * i + 3] = range.end.character + 1;
}
return this._proxy.$trySetDecorationsFast(
this.id,
decorationType.key,
_ranges
);
}
}
);
}
revealRange(range: Range, revealType: vscode.TextEditorRevealType): void {
this._runOnProxy(
() => this._proxy.$tryRevealRange(
this.id,
TypeConverters.Range.from(range),
(revealType || TextEditorRevealType.Default)
)
);
}
private _trySetSelection(): Promise<vscode.TextEditor | null | undefined> {
const selection = this._selections.map(TypeConverters.Selection.from);
return this._runOnProxy(() => this._proxy.$trySetSelections(this.id, selection));
}
_acceptSelections(selections: Selection[]): void {
ok(!this._disposed);
this._selections = selections;
}
// ---- editing
edit(callback: (edit: TextEditorEdit) => void, options: { undoStopBefore: boolean; undoStopAfter: boolean; } = { undoStopBefore: true, undoStopAfter: true }): Promise<boolean> {
if (this._disposed) {
return Promise.reject(new Error('TextEditor#edit not possible on closed editors'));
}
const edit = new TextEditorEdit(this._documentData.document, options);
callback(edit);
return this._applyEdit(edit);
}
private _applyEdit(editBuilder: TextEditorEdit): Promise<boolean> {
const editData = editBuilder.finalize();
// return when there is nothing to do
if (editData.edits.length === 0 && !editData.setEndOfLine) {
return Promise.resolve(true);
}
// check that the edits are not overlapping (i.e. illegal)
const editRanges = editData.edits.map(edit => edit.range);
// sort ascending (by end and then by start)
editRanges.sort((a, b) => {
if (a.end.line === b.end.line) {
if (a.end.character === b.end.character) {
if (a.start.line === b.start.line) {
return a.start.character - b.start.character;
}
return a.start.line - b.start.line;
}
return a.end.character - b.end.character;
}
return a.end.line - b.end.line;
});
// check that no edits are overlapping
for (let i = 0, count = editRanges.length - 1; i < count; i++) {
const rangeEnd = editRanges[i].end;
const nextRangeStart = editRanges[i + 1].start;
if (nextRangeStart.isBefore(rangeEnd)) {
// overlapping ranges
return Promise.reject(
new Error('Overlapping ranges are not allowed!')
);
}
}
// prepare data for serialization
const edits = editData.edits.map((edit): ISingleEditOperation => {
return {
range: TypeConverters.Range.from(edit.range),
text: edit.text,
forceMoveMarkers: edit.forceMoveMarkers
};
});
return this._proxy.$tryApplyEdits(this.id, editData.documentVersionId, edits, {
setEndOfLine: typeof editData.setEndOfLine === 'number' ? TypeConverters.EndOfLine.from(editData.setEndOfLine) : undefined,
undoStopBefore: editData.undoStopBefore,
undoStopAfter: editData.undoStopAfter
});
}
insertSnippet(snippet: SnippetString, where?: Position | readonly Position[] | Range | readonly Range[], options: { undoStopBefore: boolean; undoStopAfter: boolean; } = { undoStopBefore: true, undoStopAfter: true }): Promise<boolean> {
if (this._disposed) {
return Promise.reject(new Error('TextEditor#insertSnippet not possible on closed editors'));
}
let ranges: IRange[];
if (!where || (Array.isArray(where) && where.length === 0)) {
ranges = this._selections.map(range => TypeConverters.Range.from(range));
} else if (where instanceof Position) {
const { lineNumber, column } = TypeConverters.Position.from(where);
ranges = [{ startLineNumber: lineNumber, startColumn: column, endLineNumber: lineNumber, endColumn: column }];
} else if (where instanceof Range) {
ranges = [TypeConverters.Range.from(where)];
} else {
ranges = [];
for (const posOrRange of where) {
if (posOrRange instanceof Range) {
ranges.push(TypeConverters.Range.from(posOrRange));
} else {
const { lineNumber, column } = TypeConverters.Position.from(posOrRange);
ranges.push({ startLineNumber: lineNumber, startColumn: column, endLineNumber: lineNumber, endColumn: column });
}
}
}
return this._proxy.$tryInsertSnippet(this.id, snippet.value, ranges, options);
}
// ---- util
private _runOnProxy(callback: () => Promise<any>): Promise<ExtHostTextEditor | undefined | null> {
if (this._disposed) {
this._logService.warn('TextEditor is closed/disposed');
return Promise.resolve(undefined);
}
return callback().then(() => this, err => {
if (!(err instanceof Error && err.name === 'DISPOSED')) {
this._logService.warn(err);
}
return null;
});
}
}

View File

@ -0,0 +1,156 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Emitter, Event } from 'vs/base/common/event';
import * as arrays from 'vs/base/common/arrays';
import { ExtHostEditorsShape, IEditorPropertiesChangeData, IMainContext, ITextDocumentShowOptions, ITextEditorPositionData, MainContext, MainThreadTextEditorsShape } from 'vs/workbench/api/common/extHost.protocol';
import { ExtHostDocumentsAndEditors } from 'vs/workbench/api/common/extHostDocumentsAndEditors';
import { ExtHostTextEditor, TextEditorDecorationType } from 'vs/workbench/api/common/extHostTextEditor';
import * as TypeConverters from 'vs/workbench/api/common/extHostTypeConverters';
import { TextEditorSelectionChangeKind } from 'vs/workbench/api/common/extHostTypes';
import type * as vscode from 'vscode';
export class ExtHostEditors implements ExtHostEditorsShape {
private readonly _onDidChangeTextEditorSelection = new Emitter<vscode.TextEditorSelectionChangeEvent>();
private readonly _onDidChangeTextEditorOptions = new Emitter<vscode.TextEditorOptionsChangeEvent>();
private readonly _onDidChangeTextEditorVisibleRanges = new Emitter<vscode.TextEditorVisibleRangesChangeEvent>();
private readonly _onDidChangeTextEditorViewColumn = new Emitter<vscode.TextEditorViewColumnChangeEvent>();
private readonly _onDidChangeActiveTextEditor = new Emitter<vscode.TextEditor | undefined>();
private readonly _onDidChangeVisibleTextEditors = new Emitter<vscode.TextEditor[]>();
readonly onDidChangeTextEditorSelection: Event<vscode.TextEditorSelectionChangeEvent> = this._onDidChangeTextEditorSelection.event;
readonly onDidChangeTextEditorOptions: Event<vscode.TextEditorOptionsChangeEvent> = this._onDidChangeTextEditorOptions.event;
readonly onDidChangeTextEditorVisibleRanges: Event<vscode.TextEditorVisibleRangesChangeEvent> = this._onDidChangeTextEditorVisibleRanges.event;
readonly onDidChangeTextEditorViewColumn: Event<vscode.TextEditorViewColumnChangeEvent> = this._onDidChangeTextEditorViewColumn.event;
readonly onDidChangeActiveTextEditor: Event<vscode.TextEditor | undefined> = this._onDidChangeActiveTextEditor.event;
readonly onDidChangeVisibleTextEditors: Event<vscode.TextEditor[]> = this._onDidChangeVisibleTextEditors.event;
private readonly _proxy: MainThreadTextEditorsShape;
constructor(
mainContext: IMainContext,
private readonly _extHostDocumentsAndEditors: ExtHostDocumentsAndEditors,
) {
this._proxy = mainContext.getProxy(MainContext.MainThreadTextEditors);
this._extHostDocumentsAndEditors.onDidChangeVisibleTextEditors(e => this._onDidChangeVisibleTextEditors.fire(e));
this._extHostDocumentsAndEditors.onDidChangeActiveTextEditor(e => this._onDidChangeActiveTextEditor.fire(e));
}
getActiveTextEditor(): ExtHostTextEditor | undefined {
return this._extHostDocumentsAndEditors.activeEditor();
}
getVisibleTextEditors(): vscode.TextEditor[] {
return this._extHostDocumentsAndEditors.allEditors();
}
showTextDocument(document: vscode.TextDocument, column: vscode.ViewColumn, preserveFocus: boolean): Promise<vscode.TextEditor>;
showTextDocument(document: vscode.TextDocument, options: { column: vscode.ViewColumn, preserveFocus: boolean, pinned: boolean }): Promise<vscode.TextEditor>;
showTextDocument(document: vscode.TextDocument, columnOrOptions: vscode.ViewColumn | vscode.TextDocumentShowOptions | undefined, preserveFocus?: boolean): Promise<vscode.TextEditor>;
async showTextDocument(document: vscode.TextDocument, columnOrOptions: vscode.ViewColumn | vscode.TextDocumentShowOptions | undefined, preserveFocus?: boolean): Promise<vscode.TextEditor> {
let options: ITextDocumentShowOptions;
if (typeof columnOrOptions === 'number') {
options = {
position: TypeConverters.ViewColumn.from(columnOrOptions),
preserveFocus
};
} else if (typeof columnOrOptions === 'object') {
options = {
position: TypeConverters.ViewColumn.from(columnOrOptions.viewColumn),
preserveFocus: columnOrOptions.preserveFocus,
selection: typeof columnOrOptions.selection === 'object' ? TypeConverters.Range.from(columnOrOptions.selection) : undefined,
pinned: typeof columnOrOptions.preview === 'boolean' ? !columnOrOptions.preview : undefined
};
} else {
options = {
preserveFocus: false
};
}
const editorId = await this._proxy.$tryShowTextDocument(document.uri, options);
const editor = editorId && this._extHostDocumentsAndEditors.getEditor(editorId);
if (editor) {
return editor;
}
// we have no editor... having an id means that we had an editor
// on the main side and that it isn't the current editor anymore...
if (editorId) {
throw new Error(`Could NOT open editor for "${document.uri.toString()}" because another editor opened in the meantime.`);
} else {
throw new Error(`Could NOT open editor for "${document.uri.toString()}".`);
}
}
createTextEditorDecorationType(options: vscode.DecorationRenderOptions): vscode.TextEditorDecorationType {
return new TextEditorDecorationType(this._proxy, options);
}
// --- called from main thread
$acceptEditorPropertiesChanged(id: string, data: IEditorPropertiesChangeData): void {
const textEditor = this._extHostDocumentsAndEditors.getEditor(id);
if (!textEditor) {
throw new Error('unknown text editor');
}
// (1) set all properties
if (data.options) {
textEditor._acceptOptions(data.options);
}
if (data.selections) {
const selections = data.selections.selections.map(TypeConverters.Selection.to);
textEditor._acceptSelections(selections);
}
if (data.visibleRanges) {
const visibleRanges = arrays.coalesce(data.visibleRanges.map(TypeConverters.Range.to));
textEditor._acceptVisibleRanges(visibleRanges);
}
// (2) fire change events
if (data.options) {
this._onDidChangeTextEditorOptions.fire({
textEditor: textEditor,
options: { ...data.options, lineNumbers: TypeConverters.TextEditorLineNumbersStyle.to(data.options.lineNumbers) }
});
}
if (data.selections) {
const kind = TextEditorSelectionChangeKind.fromValue(data.selections.source);
const selections = data.selections.selections.map(TypeConverters.Selection.to);
this._onDidChangeTextEditorSelection.fire({
textEditor,
selections,
kind
});
}
if (data.visibleRanges) {
const visibleRanges = arrays.coalesce(data.visibleRanges.map(TypeConverters.Range.to));
this._onDidChangeTextEditorVisibleRanges.fire({
textEditor,
visibleRanges
});
}
}
$acceptEditorPositionData(data: ITextEditorPositionData): void {
for (const id in data) {
const textEditor = this._extHostDocumentsAndEditors.getEditor(id);
if (!textEditor) {
throw new Error('Unknown text editor');
}
const viewColumn = TypeConverters.ViewColumn.to(data[id]);
if (textEditor.viewColumn !== viewColumn) {
textEditor._acceptViewColumn(viewColumn);
this._onDidChangeTextEditorViewColumn.fire({ textEditor, viewColumn });
}
}
}
getDiffInformation(id: string): Promise<vscode.LineChange[]> {
return Promise.resolve(this._proxy.$getDiffInformation(id));
}
}

View File

@ -0,0 +1,38 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ColorTheme, ColorThemeKind } from './extHostTypes';
import { IExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService';
import { ExtHostThemingShape } from 'vs/workbench/api/common/extHost.protocol';
import { Emitter, Event } from 'vs/base/common/event';
export class ExtHostTheming implements ExtHostThemingShape {
readonly _serviceBrand: undefined;
private _actual: ColorTheme;
private _onDidChangeActiveColorTheme: Emitter<ColorTheme>;
constructor(
@IExtHostRpcService _extHostRpc: IExtHostRpcService
) {
this._actual = new ColorTheme(ColorThemeKind.Dark);
this._onDidChangeActiveColorTheme = new Emitter<ColorTheme>();
}
public get activeColorTheme(): ColorTheme {
return this._actual;
}
$onColorThemeChange(type: string): void {
let kind = type === 'light' ? ColorThemeKind.Light : type === 'dark' ? ColorThemeKind.Dark : ColorThemeKind.HighContrast;
this._actual = new ColorTheme(kind);
this._onDidChangeActiveColorTheme.fire(this._actual);
}
public get onDidChangeActiveColorTheme(): Event<ColorTheme> {
return this._onDidChangeActiveColorTheme.event;
}
}

View File

@ -0,0 +1,189 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import { UriComponents, URI } from 'vs/base/common/uri';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { ExtHostTimelineShape, MainThreadTimelineShape, IMainContext, MainContext } from 'vs/workbench/api/common/extHost.protocol';
import { Timeline, TimelineItem, TimelineOptions, TimelineProvider, InternalTimelineOptions } from 'vs/workbench/contrib/timeline/common/timeline';
import { IDisposable, toDisposable, DisposableStore } from 'vs/base/common/lifecycle';
import { CancellationToken } from 'vs/base/common/cancellation';
import { CommandsConverter, ExtHostCommands } from 'vs/workbench/api/common/extHostCommands';
import { ThemeIcon } from 'vs/workbench/api/common/extHostTypes';
import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions';
export interface IExtHostTimeline extends ExtHostTimelineShape {
readonly _serviceBrand: undefined;
$getTimeline(id: string, uri: UriComponents, options: vscode.TimelineOptions, token: vscode.CancellationToken, internalOptions?: InternalTimelineOptions): Promise<Timeline | undefined>;
}
export const IExtHostTimeline = createDecorator<IExtHostTimeline>('IExtHostTimeline');
export class ExtHostTimeline implements IExtHostTimeline {
declare readonly _serviceBrand: undefined;
private _proxy: MainThreadTimelineShape;
private _providers = new Map<string, TimelineProvider>();
private _itemsBySourceAndUriMap = new Map<string, Map<string | undefined, Map<string, vscode.TimelineItem>>>();
constructor(
mainContext: IMainContext,
commands: ExtHostCommands,
) {
this._proxy = mainContext.getProxy(MainContext.MainThreadTimeline);
commands.registerArgumentProcessor({
processArgument: arg => {
if (arg && arg.$mid === 11) {
const uri = arg.uri === undefined ? undefined : URI.revive(arg.uri);
return this._itemsBySourceAndUriMap.get(arg.source)?.get(getUriKey(uri))?.get(arg.handle);
}
return arg;
}
});
}
async $getTimeline(id: string, uri: UriComponents, options: vscode.TimelineOptions, token: vscode.CancellationToken, internalOptions?: InternalTimelineOptions): Promise<Timeline | undefined> {
const provider = this._providers.get(id);
return provider?.provideTimeline(URI.revive(uri), options, token, internalOptions);
}
registerTimelineProvider(scheme: string | string[], provider: vscode.TimelineProvider, _extensionId: ExtensionIdentifier, commandConverter: CommandsConverter): IDisposable {
const timelineDisposables = new DisposableStore();
const convertTimelineItem = this.convertTimelineItem(provider.id, commandConverter, timelineDisposables).bind(this);
let disposable: IDisposable | undefined;
if (provider.onDidChange) {
disposable = provider.onDidChange(e => this._proxy.$emitTimelineChangeEvent({ uri: undefined, reset: true, ...e, id: provider.id }), this);
}
const itemsBySourceAndUriMap = this._itemsBySourceAndUriMap;
return this.registerTimelineProviderCore({
...provider,
scheme: scheme,
onDidChange: undefined,
async provideTimeline(uri: URI, options: TimelineOptions, token: CancellationToken, internalOptions?: InternalTimelineOptions) {
if (internalOptions?.resetCache) {
timelineDisposables.clear();
// For now, only allow the caching of a single Uri
// itemsBySourceAndUriMap.get(provider.id)?.get(getUriKey(uri))?.clear();
itemsBySourceAndUriMap.get(provider.id)?.clear();
}
const result = await provider.provideTimeline(uri, options, token);
if (result === undefined || result === null) {
return undefined;
}
// TODO: Should we bother converting all the data if we aren't caching? Meaning it is being requested by an extension?
const convertItem = convertTimelineItem(uri, internalOptions);
return {
...result,
source: provider.id,
items: result.items.map(convertItem)
};
},
dispose() {
for (const sourceMap of itemsBySourceAndUriMap.values()) {
sourceMap.get(provider.id)?.clear();
}
disposable?.dispose();
timelineDisposables.dispose();
}
});
}
private convertTimelineItem(source: string, commandConverter: CommandsConverter, disposables: DisposableStore) {
return (uri: URI, options?: InternalTimelineOptions) => {
let items: Map<string, vscode.TimelineItem> | undefined;
if (options?.cacheResults) {
let itemsByUri = this._itemsBySourceAndUriMap.get(source);
if (itemsByUri === undefined) {
itemsByUri = new Map();
this._itemsBySourceAndUriMap.set(source, itemsByUri);
}
const uriKey = getUriKey(uri);
items = itemsByUri.get(uriKey);
if (items === undefined) {
items = new Map();
itemsByUri.set(uriKey, items);
}
}
return (item: vscode.TimelineItem): TimelineItem => {
const { iconPath, ...props } = item;
const handle = `${source}|${item.id ?? item.timestamp}`;
items?.set(handle, item);
let icon;
let iconDark;
let themeIcon;
if (item.iconPath) {
if (iconPath instanceof ThemeIcon) {
themeIcon = { id: iconPath.id };
}
else if (URI.isUri(iconPath)) {
icon = iconPath;
iconDark = iconPath;
}
else {
({ light: icon, dark: iconDark } = iconPath as { light: URI; dark: URI });
}
}
return {
...props,
id: props.id ?? undefined,
handle: handle,
source: source,
command: item.command ? commandConverter.toInternal(item.command, disposables) : undefined,
icon: icon,
iconDark: iconDark,
themeIcon: themeIcon,
accessibilityInformation: item.accessibilityInformation
};
};
};
}
private registerTimelineProviderCore(provider: TimelineProvider): IDisposable {
// console.log(`ExtHostTimeline#registerTimelineProvider: id=${provider.id}`);
const existing = this._providers.get(provider.id);
if (existing) {
throw new Error(`Timeline Provider ${provider.id} already exists.`);
}
this._proxy.$registerTimelineProvider({
id: provider.id,
label: provider.label,
scheme: provider.scheme
});
this._providers.set(provider.id, provider);
return toDisposable(() => {
for (const sourceMap of this._itemsBySourceAndUriMap.values()) {
sourceMap.get(provider.id)?.clear();
}
this._providers.delete(provider.id);
this._proxy.$unregisterTimelineProvider(provider.id);
provider.dispose();
});
}
}
function getUriKey(uri: URI | undefined): string | undefined {
return uri?.toString();
}

View File

@ -0,0 +1,746 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { localize } from 'vs/nls';
import type * as vscode from 'vscode';
import { basename } from 'vs/base/common/resources';
import { URI } from 'vs/base/common/uri';
import { Emitter, Event } from 'vs/base/common/event';
import { Disposable, DisposableStore, IDisposable } from 'vs/base/common/lifecycle';
import { ExtHostTreeViewsShape, MainThreadTreeViewsShape } from './extHost.protocol';
import { ITreeItem, TreeViewItemHandleArg, ITreeItemLabel, IRevealOptions } from 'vs/workbench/common/views';
import { ExtHostCommands, CommandsConverter } from 'vs/workbench/api/common/extHostCommands';
import { asPromise } from 'vs/base/common/async';
import { TreeItemCollapsibleState, ThemeIcon, MarkdownString as MarkdownStringType } from 'vs/workbench/api/common/extHostTypes';
import { isUndefinedOrNull, isString } from 'vs/base/common/types';
import { equals, coalesce } from 'vs/base/common/arrays';
import { ILogService } from 'vs/platform/log/common/log';
import { checkProposedApiEnabled } from 'vs/workbench/services/extensions/common/extensions';
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { MarkdownString } from 'vs/workbench/api/common/extHostTypeConverters';
import { IMarkdownString } from 'vs/base/common/htmlContent';
import { CancellationTokenSource } from 'vs/base/common/cancellation';
type TreeItemHandle = string;
function toTreeItemLabel(label: any, extension: IExtensionDescription): ITreeItemLabel | undefined {
if (isString(label)) {
return { label };
}
if (label
&& typeof label === 'object'
&& typeof label.label === 'string') {
checkProposedApiEnabled(extension);
let highlights: [number, number][] | undefined = undefined;
if (Array.isArray(label.highlights)) {
highlights = (<[number, number][]>label.highlights).filter((highlight => highlight.length === 2 && typeof highlight[0] === 'number' && typeof highlight[1] === 'number'));
highlights = highlights.length ? highlights : undefined;
}
return { label: label.label, highlights };
}
return undefined;
}
export class ExtHostTreeViews implements ExtHostTreeViewsShape {
private treeViews: Map<string, ExtHostTreeView<any>> = new Map<string, ExtHostTreeView<any>>();
constructor(
private _proxy: MainThreadTreeViewsShape,
private commands: ExtHostCommands,
private logService: ILogService
) {
function isTreeViewItemHandleArg(arg: any): boolean {
return arg && arg.$treeViewId && arg.$treeItemHandle;
}
commands.registerArgumentProcessor({
processArgument: arg => {
if (isTreeViewItemHandleArg(arg)) {
return this.convertArgument(arg);
} else if (Array.isArray(arg) && (arg.length > 0)) {
return arg.map(item => {
if (isTreeViewItemHandleArg(item)) {
return this.convertArgument(item);
}
return item;
});
}
return arg;
}
});
}
registerTreeDataProvider<T>(id: string, treeDataProvider: vscode.TreeDataProvider<T>, extension: IExtensionDescription): vscode.Disposable {
const treeView = this.createTreeView(id, { treeDataProvider }, extension);
return { dispose: () => treeView.dispose() };
}
createTreeView<T>(viewId: string, options: vscode.TreeViewOptions<T>, extension: IExtensionDescription): vscode.TreeView<T> {
if (!options || !options.treeDataProvider) {
throw new Error('Options with treeDataProvider is mandatory');
}
const treeView = this.createExtHostTreeView(viewId, options, extension);
return {
get onDidCollapseElement() { return treeView.onDidCollapseElement; },
get onDidExpandElement() { return treeView.onDidExpandElement; },
get selection() { return treeView.selectedElements; },
get onDidChangeSelection() { return treeView.onDidChangeSelection; },
get visible() { return treeView.visible; },
get onDidChangeVisibility() { return treeView.onDidChangeVisibility; },
get message() { return treeView.message; },
set message(message: string) {
treeView.message = message;
},
get title() { return treeView.title; },
set title(title: string) {
treeView.title = title;
},
get description() {
return treeView.description;
},
set description(description: string | undefined) {
treeView.description = description;
},
reveal: (element: T, options?: IRevealOptions): Promise<void> => {
return treeView.reveal(element, options);
},
dispose: () => {
this.treeViews.delete(viewId);
treeView.dispose();
}
};
}
$getChildren(treeViewId: string, treeItemHandle?: string): Promise<ITreeItem[]> {
const treeView = this.treeViews.get(treeViewId);
if (!treeView) {
return Promise.reject(new Error(localize('treeView.notRegistered', 'No tree view with id \'{0}\' registered.', treeViewId)));
}
return treeView.getChildren(treeItemHandle);
}
async $hasResolve(treeViewId: string): Promise<boolean> {
const treeView = this.treeViews.get(treeViewId);
if (!treeView) {
throw new Error(localize('treeView.notRegistered', 'No tree view with id \'{0}\' registered.', treeViewId));
}
return treeView.hasResolve;
}
$resolve(treeViewId: string, treeItemHandle: string): Promise<ITreeItem | undefined> {
const treeView = this.treeViews.get(treeViewId);
if (!treeView) {
throw new Error(localize('treeView.notRegistered', 'No tree view with id \'{0}\' registered.', treeViewId));
}
return treeView.resolveTreeItem(treeItemHandle);
}
$setExpanded(treeViewId: string, treeItemHandle: string, expanded: boolean): void {
const treeView = this.treeViews.get(treeViewId);
if (!treeView) {
throw new Error(localize('treeView.notRegistered', 'No tree view with id \'{0}\' registered.', treeViewId));
}
treeView.setExpanded(treeItemHandle, expanded);
}
$setSelection(treeViewId: string, treeItemHandles: string[]): void {
const treeView = this.treeViews.get(treeViewId);
if (!treeView) {
throw new Error(localize('treeView.notRegistered', 'No tree view with id \'{0}\' registered.', treeViewId));
}
treeView.setSelection(treeItemHandles);
}
$setVisible(treeViewId: string, isVisible: boolean): void {
const treeView = this.treeViews.get(treeViewId);
if (!treeView) {
throw new Error(localize('treeView.notRegistered', 'No tree view with id \'{0}\' registered.', treeViewId));
}
treeView.setVisible(isVisible);
}
private createExtHostTreeView<T>(id: string, options: vscode.TreeViewOptions<T>, extension: IExtensionDescription): ExtHostTreeView<T> {
const treeView = new ExtHostTreeView<T>(id, options, this._proxy, this.commands.converter, this.logService, extension);
this.treeViews.set(id, treeView);
return treeView;
}
private convertArgument(arg: TreeViewItemHandleArg): any {
const treeView = this.treeViews.get(arg.$treeViewId);
return treeView ? treeView.getExtensionElement(arg.$treeItemHandle) : null;
}
}
type Root = null | undefined | void;
type TreeData<T> = { message: boolean, element: T | Root | false };
interface TreeNode extends IDisposable {
item: ITreeItem;
extensionItem: vscode.TreeItem2;
parent: TreeNode | Root;
children?: TreeNode[];
}
class ExtHostTreeView<T> extends Disposable {
private static readonly LABEL_HANDLE_PREFIX = '0';
private static readonly ID_HANDLE_PREFIX = '1';
private readonly dataProvider: vscode.TreeDataProvider<T>;
private roots: TreeNode[] | null = null;
private elements: Map<TreeItemHandle, T> = new Map<TreeItemHandle, T>();
private nodes: Map<T, TreeNode> = new Map<T, TreeNode>();
private _visible: boolean = false;
get visible(): boolean { return this._visible; }
private _selectedHandles: TreeItemHandle[] = [];
get selectedElements(): T[] { return <T[]>this._selectedHandles.map(handle => this.getExtensionElement(handle)).filter(element => !isUndefinedOrNull(element)); }
private _onDidExpandElement: Emitter<vscode.TreeViewExpansionEvent<T>> = this._register(new Emitter<vscode.TreeViewExpansionEvent<T>>());
readonly onDidExpandElement: Event<vscode.TreeViewExpansionEvent<T>> = this._onDidExpandElement.event;
private _onDidCollapseElement: Emitter<vscode.TreeViewExpansionEvent<T>> = this._register(new Emitter<vscode.TreeViewExpansionEvent<T>>());
readonly onDidCollapseElement: Event<vscode.TreeViewExpansionEvent<T>> = this._onDidCollapseElement.event;
private _onDidChangeSelection: Emitter<vscode.TreeViewSelectionChangeEvent<T>> = this._register(new Emitter<vscode.TreeViewSelectionChangeEvent<T>>());
readonly onDidChangeSelection: Event<vscode.TreeViewSelectionChangeEvent<T>> = this._onDidChangeSelection.event;
private _onDidChangeVisibility: Emitter<vscode.TreeViewVisibilityChangeEvent> = this._register(new Emitter<vscode.TreeViewVisibilityChangeEvent>());
readonly onDidChangeVisibility: Event<vscode.TreeViewVisibilityChangeEvent> = this._onDidChangeVisibility.event;
private _onDidChangeData: Emitter<TreeData<T>> = this._register(new Emitter<TreeData<T>>());
private refreshPromise: Promise<void> = Promise.resolve();
private refreshQueue: Promise<void> = Promise.resolve();
constructor(
private viewId: string, options: vscode.TreeViewOptions<T>,
private proxy: MainThreadTreeViewsShape,
private commands: CommandsConverter,
private logService: ILogService,
private extension: IExtensionDescription
) {
super();
if (extension.contributes && extension.contributes.views) {
for (const location in extension.contributes.views) {
for (const view of extension.contributes.views[location]) {
if (view.id === viewId) {
this._title = view.name;
}
}
}
}
this.dataProvider = options.treeDataProvider;
this.proxy.$registerTreeViewDataProvider(viewId, { showCollapseAll: !!options.showCollapseAll, canSelectMany: !!options.canSelectMany });
if (this.dataProvider.onDidChangeTreeData) {
this._register(this.dataProvider.onDidChangeTreeData(element => this._onDidChangeData.fire({ message: false, element })));
}
let refreshingPromise: Promise<void> | null;
let promiseCallback: () => void;
this._register(Event.debounce<TreeData<T>, { message: boolean, elements: (T | Root)[] }>(this._onDidChangeData.event, (result, current) => {
if (!result) {
result = { message: false, elements: [] };
}
if (current.element !== false) {
if (!refreshingPromise) {
// New refresh has started
refreshingPromise = new Promise(c => promiseCallback = c);
this.refreshPromise = this.refreshPromise.then(() => refreshingPromise!);
}
result.elements.push(current.element);
}
if (current.message) {
result.message = true;
}
return result;
}, 200, true)(({ message, elements }) => {
if (elements.length) {
this.refreshQueue = this.refreshQueue.then(() => {
const _promiseCallback = promiseCallback;
refreshingPromise = null;
return this.refresh(elements).then(() => _promiseCallback());
});
}
if (message) {
this.proxy.$setMessage(this.viewId, this._message);
}
}));
}
getChildren(parentHandle: TreeItemHandle | Root): Promise<ITreeItem[]> {
const parentElement = parentHandle ? this.getExtensionElement(parentHandle) : undefined;
if (parentHandle && !parentElement) {
this.logService.error(`No tree item with id \'${parentHandle}\' found.`);
return Promise.resolve([]);
}
const childrenNodes = this.getChildrenNodes(parentHandle); // Get it from cache
return (childrenNodes ? Promise.resolve(childrenNodes) : this.fetchChildrenNodes(parentElement))
.then(nodes => nodes.map(n => n.item));
}
getExtensionElement(treeItemHandle: TreeItemHandle): T | undefined {
return this.elements.get(treeItemHandle);
}
reveal(element: T, options?: IRevealOptions): Promise<void> {
options = options ? options : { select: true, focus: false };
const select = isUndefinedOrNull(options.select) ? true : options.select;
const focus = isUndefinedOrNull(options.focus) ? false : options.focus;
const expand = isUndefinedOrNull(options.expand) ? false : options.expand;
if (typeof this.dataProvider.getParent !== 'function') {
return Promise.reject(new Error(`Required registered TreeDataProvider to implement 'getParent' method to access 'reveal' method`));
}
return this.refreshPromise
.then(() => this.resolveUnknownParentChain(element))
.then(parentChain => this.resolveTreeNode(element, parentChain[parentChain.length - 1])
.then(treeNode => this.proxy.$reveal(this.viewId, treeNode.item, parentChain.map(p => p.item), { select, focus, expand })), error => this.logService.error(error));
}
private _message: string = '';
get message(): string {
return this._message;
}
set message(message: string) {
this._message = message;
this._onDidChangeData.fire({ message: true, element: false });
}
private _title: string = '';
get title(): string {
return this._title;
}
set title(title: string) {
this._title = title;
this.proxy.$setTitle(this.viewId, title, this._description);
}
private _description: string | undefined;
get description(): string | undefined {
return this._description;
}
set description(description: string | undefined) {
this._description = description;
this.proxy.$setTitle(this.viewId, this._title, description);
}
setExpanded(treeItemHandle: TreeItemHandle, expanded: boolean): void {
const element = this.getExtensionElement(treeItemHandle);
if (element) {
if (expanded) {
this._onDidExpandElement.fire(Object.freeze({ element }));
} else {
this._onDidCollapseElement.fire(Object.freeze({ element }));
}
}
}
setSelection(treeItemHandles: TreeItemHandle[]): void {
if (!equals(this._selectedHandles, treeItemHandles)) {
this._selectedHandles = treeItemHandles;
this._onDidChangeSelection.fire(Object.freeze({ selection: this.selectedElements }));
}
}
setVisible(visible: boolean): void {
if (visible !== this._visible) {
this._visible = visible;
this._onDidChangeVisibility.fire(Object.freeze({ visible: this._visible }));
}
}
get hasResolve(): boolean {
return !!this.dataProvider.resolveTreeItem;
}
async resolveTreeItem(treeItemHandle: string): Promise<ITreeItem | undefined> {
if (!this.dataProvider.resolveTreeItem) {
return;
}
const element = this.elements.get(treeItemHandle);
if (element) {
const node = this.nodes.get(element);
if (node) {
const resolve = await this.dataProvider.resolveTreeItem(element, node.extensionItem);
// Resolvable elements. Currently only tooltip.
node.item.tooltip = this.getTooltip(resolve.tooltip);
return node.item;
}
}
return;
}
private resolveUnknownParentChain(element: T): Promise<TreeNode[]> {
return this.resolveParent(element)
.then((parent) => {
if (!parent) {
return Promise.resolve([]);
}
return this.resolveUnknownParentChain(parent)
.then(result => this.resolveTreeNode(parent, result[result.length - 1])
.then(parentNode => {
result.push(parentNode);
return result;
}));
});
}
private resolveParent(element: T): Promise<T | Root> {
const node = this.nodes.get(element);
if (node) {
return Promise.resolve(node.parent ? this.elements.get(node.parent.item.handle) : undefined);
}
return asPromise(() => this.dataProvider.getParent!(element));
}
private resolveTreeNode(element: T, parent?: TreeNode): Promise<TreeNode> {
const node = this.nodes.get(element);
if (node) {
return Promise.resolve(node);
}
return asPromise(() => this.dataProvider.getTreeItem(element))
.then(extTreeItem => this.createHandle(element, extTreeItem, parent, true))
.then(handle => this.getChildren(parent ? parent.item.handle : undefined)
.then(() => {
const cachedElement = this.getExtensionElement(handle);
if (cachedElement) {
const node = this.nodes.get(cachedElement);
if (node) {
return Promise.resolve(node);
}
}
throw new Error(`Cannot resolve tree item for element ${handle}`);
}));
}
private getChildrenNodes(parentNodeOrHandle: TreeNode | TreeItemHandle | Root): TreeNode[] | null {
if (parentNodeOrHandle) {
let parentNode: TreeNode | undefined;
if (typeof parentNodeOrHandle === 'string') {
const parentElement = this.getExtensionElement(parentNodeOrHandle);
parentNode = parentElement ? this.nodes.get(parentElement) : undefined;
} else {
parentNode = parentNodeOrHandle;
}
return parentNode ? parentNode.children || null : null;
}
return this.roots;
}
private async fetchChildrenNodes(parentElement?: T): Promise<TreeNode[]> {
// clear children cache
this.clearChildren(parentElement);
const cts = new CancellationTokenSource(this._refreshCancellationSource.token);
try {
const parentNode = parentElement ? this.nodes.get(parentElement) : undefined;
const elements = await this.dataProvider.getChildren(parentElement);
if (cts.token.isCancellationRequested) {
return [];
}
const items = await Promise.all(coalesce(elements || []).map(async element => {
const item = await this.dataProvider.getTreeItem(element);
return item && !cts.token.isCancellationRequested ? this.createAndRegisterTreeNode(element, item, parentNode) : null;
}));
if (cts.token.isCancellationRequested) {
return [];
}
return coalesce(items);
} finally {
cts.dispose();
}
}
private _refreshCancellationSource = new CancellationTokenSource();
private refresh(elements: (T | Root)[]): Promise<void> {
const hasRoot = elements.some(element => !element);
if (hasRoot) {
// Cancel any pending children fetches
this._refreshCancellationSource.dispose(true);
this._refreshCancellationSource = new CancellationTokenSource();
this.clearAll(); // clear cache
return this.proxy.$refresh(this.viewId);
} else {
const handlesToRefresh = this.getHandlesToRefresh(<T[]>elements);
if (handlesToRefresh.length) {
return this.refreshHandles(handlesToRefresh);
}
}
return Promise.resolve(undefined);
}
private getHandlesToRefresh(elements: T[]): TreeItemHandle[] {
const elementsToUpdate = new Set<TreeItemHandle>();
for (const element of elements) {
const elementNode = this.nodes.get(element);
if (elementNode && !elementsToUpdate.has(elementNode.item.handle)) {
// check if an ancestor of extElement is already in the elements to update list
let currentNode: TreeNode | undefined = elementNode;
while (currentNode && currentNode.parent && !elementsToUpdate.has(currentNode.parent.item.handle)) {
const parentElement: T | undefined = this.elements.get(currentNode.parent.item.handle);
currentNode = parentElement ? this.nodes.get(parentElement) : undefined;
}
if (currentNode && !currentNode.parent) {
elementsToUpdate.add(elementNode.item.handle);
}
}
}
const handlesToUpdate: TreeItemHandle[] = [];
// Take only top level elements
elementsToUpdate.forEach((handle) => {
const element = this.elements.get(handle);
if (element) {
const node = this.nodes.get(element);
if (node && (!node.parent || !elementsToUpdate.has(node.parent.item.handle))) {
handlesToUpdate.push(handle);
}
}
});
return handlesToUpdate;
}
private refreshHandles(itemHandles: TreeItemHandle[]): Promise<void> {
const itemsToRefresh: { [treeItemHandle: string]: ITreeItem } = {};
return Promise.all(itemHandles.map(treeItemHandle =>
this.refreshNode(treeItemHandle)
.then(node => {
if (node) {
itemsToRefresh[treeItemHandle] = node.item;
}
})))
.then(() => Object.keys(itemsToRefresh).length ? this.proxy.$refresh(this.viewId, itemsToRefresh) : undefined);
}
private refreshNode(treeItemHandle: TreeItemHandle): Promise<TreeNode | null> {
const extElement = this.getExtensionElement(treeItemHandle);
if (extElement) {
const existing = this.nodes.get(extElement);
if (existing) {
this.clearChildren(extElement); // clear children cache
return asPromise(() => this.dataProvider.getTreeItem(extElement))
.then(extTreeItem => {
if (extTreeItem) {
const newNode = this.createTreeNode(extElement, extTreeItem, existing.parent);
this.updateNodeCache(extElement, newNode, existing, existing.parent);
existing.dispose();
return newNode;
}
return null;
});
}
}
return Promise.resolve(null);
}
private createAndRegisterTreeNode(element: T, extTreeItem: vscode.TreeItem, parentNode: TreeNode | Root): TreeNode {
const node = this.createTreeNode(element, extTreeItem, parentNode);
if (extTreeItem.id && this.elements.has(node.item.handle)) {
throw new Error(localize('treeView.duplicateElement', 'Element with id {0} is already registered', extTreeItem.id));
}
this.addNodeToCache(element, node);
this.addNodeToParentCache(node, parentNode);
return node;
}
private getTooltip(tooltip?: string | vscode.MarkdownString): string | IMarkdownString | undefined {
if (MarkdownStringType.isMarkdownString(tooltip)) {
checkProposedApiEnabled(this.extension);
return MarkdownString.from(tooltip);
}
return tooltip;
}
private createTreeNode(element: T, extensionTreeItem: vscode.TreeItem2, parent: TreeNode | Root): TreeNode {
const disposable = new DisposableStore();
const handle = this.createHandle(element, extensionTreeItem, parent);
const icon = this.getLightIconPath(extensionTreeItem);
const item: ITreeItem = {
handle,
parentHandle: parent ? parent.item.handle : undefined,
label: toTreeItemLabel(extensionTreeItem.label, this.extension),
description: extensionTreeItem.description,
resourceUri: extensionTreeItem.resourceUri,
tooltip: this.getTooltip(extensionTreeItem.tooltip),
command: extensionTreeItem.command ? this.commands.toInternal(extensionTreeItem.command, disposable) : undefined,
contextValue: extensionTreeItem.contextValue,
icon,
iconDark: this.getDarkIconPath(extensionTreeItem) || icon,
themeIcon: this.getThemeIcon(extensionTreeItem),
collapsibleState: isUndefinedOrNull(extensionTreeItem.collapsibleState) ? TreeItemCollapsibleState.None : extensionTreeItem.collapsibleState,
accessibilityInformation: extensionTreeItem.accessibilityInformation
};
return {
item,
extensionItem: extensionTreeItem,
parent,
children: undefined,
dispose(): void { disposable.dispose(); }
};
}
private getThemeIcon(extensionTreeItem: vscode.TreeItem2): ThemeIcon | undefined {
return extensionTreeItem.iconPath instanceof ThemeIcon ? extensionTreeItem.iconPath : undefined;
}
private createHandle(element: T, { id, label, resourceUri }: vscode.TreeItem, parent: TreeNode | Root, returnFirst?: boolean): TreeItemHandle {
if (id) {
return `${ExtHostTreeView.ID_HANDLE_PREFIX}/${id}`;
}
const treeItemLabel = toTreeItemLabel(label, this.extension);
const prefix: string = parent ? parent.item.handle : ExtHostTreeView.LABEL_HANDLE_PREFIX;
let elementId = treeItemLabel ? treeItemLabel.label : resourceUri ? basename(resourceUri) : '';
elementId = elementId.indexOf('/') !== -1 ? elementId.replace('/', '//') : elementId;
const existingHandle = this.nodes.has(element) ? this.nodes.get(element)!.item.handle : undefined;
const childrenNodes = (this.getChildrenNodes(parent) || []);
let handle: TreeItemHandle;
let counter = 0;
do {
handle = `${prefix}/${counter}:${elementId}`;
if (returnFirst || !this.elements.has(handle) || existingHandle === handle) {
// Return first if asked for or
// Return if handle does not exist or
// Return if handle is being reused
break;
}
counter++;
} while (counter <= childrenNodes.length);
return handle;
}
private getLightIconPath(extensionTreeItem: vscode.TreeItem): URI | undefined {
if (extensionTreeItem.iconPath && !(extensionTreeItem.iconPath instanceof ThemeIcon)) {
if (typeof extensionTreeItem.iconPath === 'string'
|| URI.isUri(extensionTreeItem.iconPath)) {
return this.getIconPath(extensionTreeItem.iconPath);
}
return this.getIconPath((<{ light: string | URI; dark: string | URI }>extensionTreeItem.iconPath).light);
}
return undefined;
}
private getDarkIconPath(extensionTreeItem: vscode.TreeItem): URI | undefined {
if (extensionTreeItem.iconPath && !(extensionTreeItem.iconPath instanceof ThemeIcon) && (<{ light: string | URI; dark: string | URI }>extensionTreeItem.iconPath).dark) {
return this.getIconPath((<{ light: string | URI; dark: string | URI }>extensionTreeItem.iconPath).dark);
}
return undefined;
}
private getIconPath(iconPath: string | URI): URI {
if (URI.isUri(iconPath)) {
return iconPath;
}
return URI.file(iconPath);
}
private addNodeToCache(element: T, node: TreeNode): void {
this.elements.set(node.item.handle, element);
this.nodes.set(element, node);
}
private updateNodeCache(element: T, newNode: TreeNode, existing: TreeNode, parentNode: TreeNode | Root): void {
// Remove from the cache
this.elements.delete(newNode.item.handle);
this.nodes.delete(element);
if (newNode.item.handle !== existing.item.handle) {
this.elements.delete(existing.item.handle);
}
// Add the new node to the cache
this.addNodeToCache(element, newNode);
// Replace the node in parent's children nodes
const childrenNodes = (this.getChildrenNodes(parentNode) || []);
const childNode = childrenNodes.filter(c => c.item.handle === existing.item.handle)[0];
if (childNode) {
childrenNodes.splice(childrenNodes.indexOf(childNode), 1, newNode);
}
}
private addNodeToParentCache(node: TreeNode, parentNode: TreeNode | Root): void {
if (parentNode) {
if (!parentNode.children) {
parentNode.children = [];
}
parentNode.children.push(node);
} else {
if (!this.roots) {
this.roots = [];
}
this.roots.push(node);
}
}
private clearChildren(parentElement?: T): void {
if (parentElement) {
const node = this.nodes.get(parentElement);
if (node) {
if (node.children) {
for (const child of node.children) {
const childElement = this.elements.get(child.item.handle);
if (childElement) {
this.clear(childElement);
}
}
}
node.children = undefined;
}
} else {
this.clearAll();
}
}
private clear(element: T): void {
const node = this.nodes.get(element);
if (node) {
if (node.children) {
for (const child of node.children) {
const childElement = this.elements.get(child.item.handle);
if (childElement) {
this.clear(childElement);
}
}
}
this.nodes.delete(element);
this.elements.delete(node.item.handle);
node.dispose();
}
}
private clearAll(): void {
this.roots = null;
this.elements.clear();
this.nodes.forEach(node => node.dispose());
this.nodes.clear();
}
dispose() {
this._refreshCancellationSource.dispose();
this.clearAll();
}
}

View File

@ -0,0 +1,73 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ExtHostTunnelServiceShape, MainContext, MainThreadTunnelServiceShape } from 'vs/workbench/api/common/extHost.protocol';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import * as vscode from 'vscode';
import { RemoteTunnel, TunnelOptions } from 'vs/platform/remote/common/tunnel';
import { IDisposable } from 'vs/base/common/lifecycle';
import { Emitter } from 'vs/base/common/event';
import { IExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService';
export interface TunnelDto {
remoteAddress: { port: number, host: string };
localAddress: { port: number, host: string } | string;
}
export namespace TunnelDto {
export function fromApiTunnel(tunnel: vscode.Tunnel): TunnelDto {
return { remoteAddress: tunnel.remoteAddress, localAddress: tunnel.localAddress };
}
export function fromServiceTunnel(tunnel: RemoteTunnel): TunnelDto {
return { remoteAddress: { host: tunnel.tunnelRemoteHost, port: tunnel.tunnelRemotePort }, localAddress: tunnel.localAddress };
}
}
export interface Tunnel extends vscode.Disposable {
remote: { port: number, host: string };
localAddress: string;
}
export interface IExtHostTunnelService extends ExtHostTunnelServiceShape {
readonly _serviceBrand: undefined;
openTunnel(forward: TunnelOptions): Promise<vscode.Tunnel | undefined>;
getTunnels(): Promise<vscode.TunnelDescription[]>;
onDidChangeTunnels: vscode.Event<void>;
setTunnelExtensionFunctions(provider: vscode.RemoteAuthorityResolver | undefined): Promise<IDisposable>;
}
export const IExtHostTunnelService = createDecorator<IExtHostTunnelService>('IExtHostTunnelService');
export class ExtHostTunnelService implements IExtHostTunnelService {
declare readonly _serviceBrand: undefined;
onDidChangeTunnels: vscode.Event<void> = (new Emitter<void>()).event;
private readonly _proxy: MainThreadTunnelServiceShape;
constructor(
@IExtHostRpcService extHostRpc: IExtHostRpcService,
) {
this._proxy = extHostRpc.getProxy(MainContext.MainThreadTunnelService);
}
async openTunnel(forward: TunnelOptions): Promise<vscode.Tunnel | undefined> {
return undefined;
}
async getTunnels(): Promise<vscode.TunnelDescription[]> {
return [];
}
async $findCandidatePorts(): Promise<{ host: string, port: number; detail: string; }[]> {
return [];
}
async $filterCandidates(candidates: { host: string, port: number, detail: string }[]): Promise<boolean[]> {
return candidates.map(() => true);
}
async setTunnelExtensionFunctions(provider: vscode.RemoteAuthorityResolver | undefined): Promise<IDisposable> {
await this._proxy.$tunnelServiceReady();
return { dispose: () => { } };
}
$forwardPort(tunnelOptions: TunnelOptions): Promise<TunnelDto> | undefined { return undefined; }
async $closeTunnel(remote: { host: string, port: number }): Promise<void> { }
async $onDidTunnelsChange(): Promise<void> { }
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,37 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IURITransformer } from 'vs/base/common/uriIpc';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { URI, UriComponents } from 'vs/base/common/uri';
export interface IURITransformerService extends IURITransformer {
readonly _serviceBrand: undefined;
}
export const IURITransformerService = createDecorator<IURITransformerService>('IURITransformerService');
export class URITransformerService implements IURITransformerService {
declare readonly _serviceBrand: undefined;
transformIncoming: (uri: UriComponents) => UriComponents;
transformOutgoing: (uri: UriComponents) => UriComponents;
transformOutgoingURI: (uri: URI) => URI;
transformOutgoingScheme: (scheme: string) => string;
constructor(delegate: IURITransformer | null) {
if (!delegate) {
this.transformIncoming = arg => arg;
this.transformOutgoing = arg => arg;
this.transformOutgoingURI = arg => arg;
this.transformOutgoingScheme = arg => arg;
} else {
this.transformIncoming = delegate.transformIncoming.bind(delegate);
this.transformOutgoing = delegate.transformOutgoing.bind(delegate);
this.transformOutgoingURI = delegate.transformOutgoingURI.bind(delegate);
this.transformOutgoingScheme = delegate.transformOutgoingScheme.bind(delegate);
}
}
}

View File

@ -0,0 +1,62 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import type * as vscode from 'vscode';
import { MainContext, IMainContext, ExtHostUrlsShape, MainThreadUrlsShape } from './extHost.protocol';
import { URI, UriComponents } from 'vs/base/common/uri';
import { toDisposable } from 'vs/base/common/lifecycle';
import { onUnexpectedError } from 'vs/base/common/errors';
import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions';
export class ExtHostUrls implements ExtHostUrlsShape {
private static HandlePool = 0;
private readonly _proxy: MainThreadUrlsShape;
private handles = new Set<string>();
private handlers = new Map<number, vscode.UriHandler>();
constructor(
mainContext: IMainContext
) {
this._proxy = mainContext.getProxy(MainContext.MainThreadUrls);
}
registerUriHandler(extensionId: ExtensionIdentifier, handler: vscode.UriHandler): vscode.Disposable {
if (this.handles.has(ExtensionIdentifier.toKey(extensionId))) {
throw new Error(`Protocol handler already registered for extension ${extensionId}`);
}
const handle = ExtHostUrls.HandlePool++;
this.handles.add(ExtensionIdentifier.toKey(extensionId));
this.handlers.set(handle, handler);
this._proxy.$registerUriHandler(handle, extensionId);
return toDisposable(() => {
this.handles.delete(ExtensionIdentifier.toKey(extensionId));
this.handlers.delete(handle);
this._proxy.$unregisterUriHandler(handle);
});
}
$handleExternalUri(handle: number, uri: UriComponents): Promise<void> {
const handler = this.handlers.get(handle);
if (!handler) {
return Promise.resolve(undefined);
}
try {
handler.handleUri(URI.revive(uri));
} catch (err) {
onUnexpectedError(err);
}
return Promise.resolve(undefined);
}
async createAppUri(uri: URI): Promise<vscode.Uri> {
return URI.revive(await this._proxy.$createAppUri(uri));
}
}

View File

@ -0,0 +1,201 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Emitter, Event } from 'vs/base/common/event';
import { URI } from 'vs/base/common/uri';
import * as modes from 'vs/editor/common/modes';
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { ILogService } from 'vs/platform/log/common/log';
import { IExtHostApiDeprecationService } from 'vs/workbench/api/common/extHostApiDeprecationService';
import { IExtHostWorkspace } from 'vs/workbench/api/common/extHostWorkspace';
import { asWebviewUri, WebviewInitData } from 'vs/workbench/api/common/shared/webview';
import type * as vscode from 'vscode';
import * as extHostProtocol from './extHost.protocol';
export class ExtHostWebview implements vscode.Webview {
readonly #handle: extHostProtocol.WebviewHandle;
readonly #proxy: extHostProtocol.MainThreadWebviewsShape;
readonly #deprecationService: IExtHostApiDeprecationService;
readonly #initData: WebviewInitData;
readonly #workspace: IExtHostWorkspace | undefined;
readonly #extension: IExtensionDescription;
#html: string = '';
#options: vscode.WebviewOptions;
#isDisposed: boolean = false;
#hasCalledAsWebviewUri = false;
constructor(
handle: extHostProtocol.WebviewHandle,
proxy: extHostProtocol.MainThreadWebviewsShape,
options: vscode.WebviewOptions,
initData: WebviewInitData,
workspace: IExtHostWorkspace | undefined,
extension: IExtensionDescription,
deprecationService: IExtHostApiDeprecationService,
) {
this.#handle = handle;
this.#proxy = proxy;
this.#options = options;
this.#initData = initData;
this.#workspace = workspace;
this.#extension = extension;
this.#deprecationService = deprecationService;
}
/* internal */ readonly _onMessageEmitter = new Emitter<any>();
public readonly onDidReceiveMessage: Event<any> = this._onMessageEmitter.event;
readonly #onDidDisposeEmitter = new Emitter<void>();
/* internal */ readonly _onDidDispose: Event<void> = this.#onDidDisposeEmitter.event;
public dispose() {
this.#isDisposed = true;
this.#onDidDisposeEmitter.fire();
this.#onDidDisposeEmitter.dispose();
this._onMessageEmitter.dispose();
}
public asWebviewUri(resource: vscode.Uri): vscode.Uri {
this.#hasCalledAsWebviewUri = true;
return asWebviewUri(this.#initData, this.#handle, resource);
}
public get cspSource(): string {
return this.#initData.webviewCspSource
.replace('{{uuid}}', this.#handle);
}
public get html(): string {
this.assertNotDisposed();
return this.#html;
}
public set html(value: string) {
this.assertNotDisposed();
if (this.#html !== value) {
this.#html = value;
if (!this.#hasCalledAsWebviewUri && /(["'])vscode-resource:([^\s'"]+?)(["'])/i.test(value)) {
this.#hasCalledAsWebviewUri = true;
this.#deprecationService.report('Webview vscode-resource: uris', this.#extension,
`Please migrate to use the 'webview.asWebviewUri' api instead: https://aka.ms/vscode-webview-use-aswebviewuri`);
}
this.#proxy.$setHtml(this.#handle, value);
}
}
public get options(): vscode.WebviewOptions {
this.assertNotDisposed();
return this.#options;
}
public set options(newOptions: vscode.WebviewOptions) {
this.assertNotDisposed();
this.#proxy.$setOptions(this.#handle, convertWebviewOptions(this.#extension, this.#workspace, newOptions));
this.#options = newOptions;
}
public async postMessage(message: any): Promise<boolean> {
if (this.#isDisposed) {
return false;
}
return this.#proxy.$postMessage(this.#handle, message);
}
private assertNotDisposed() {
if (this.#isDisposed) {
throw new Error('Webview is disposed');
}
}
}
export class ExtHostWebviews implements extHostProtocol.ExtHostWebviewsShape {
private readonly _webviewProxy: extHostProtocol.MainThreadWebviewsShape;
private readonly _webviews = new Map<extHostProtocol.WebviewHandle, ExtHostWebview>();
constructor(
mainContext: extHostProtocol.IMainContext,
private readonly initData: WebviewInitData,
private readonly workspace: IExtHostWorkspace | undefined,
private readonly _logService: ILogService,
private readonly _deprecationService: IExtHostApiDeprecationService,
) {
this._webviewProxy = mainContext.getProxy(extHostProtocol.MainContext.MainThreadWebviews);
}
public $onMessage(
handle: extHostProtocol.WebviewHandle,
message: any
): void {
const webview = this.getWebview(handle);
if (webview) {
webview._onMessageEmitter.fire(message);
}
}
public $onMissingCsp(
_handle: extHostProtocol.WebviewHandle,
extensionId: string
): void {
this._logService.warn(`${extensionId} created a webview without a content security policy: https://aka.ms/vscode-webview-missing-csp`);
}
public createNewWebview(handle: string, options: modes.IWebviewOptions & modes.IWebviewPanelOptions, extension: IExtensionDescription): ExtHostWebview {
const webview = new ExtHostWebview(handle, this._webviewProxy, reviveOptions(options), this.initData, this.workspace, extension, this._deprecationService);
this._webviews.set(handle, webview);
webview._onDidDispose(() => { this._webviews.delete(handle); });
return webview;
}
public deleteWebview(handle: string) {
this._webviews.delete(handle);
}
private getWebview(handle: extHostProtocol.WebviewHandle): ExtHostWebview | undefined {
return this._webviews.get(handle);
}
}
export function toExtensionData(extension: IExtensionDescription): extHostProtocol.WebviewExtensionDescription {
return { id: extension.identifier, location: extension.extensionLocation };
}
export function convertWebviewOptions(
extension: IExtensionDescription,
workspace: IExtHostWorkspace | undefined,
options: vscode.WebviewPanelOptions & vscode.WebviewOptions,
): modes.IWebviewOptions {
return {
...options,
localResourceRoots: options.localResourceRoots || getDefaultLocalResourceRoots(extension, workspace)
};
}
function reviveOptions(
options: modes.IWebviewOptions & modes.IWebviewPanelOptions
): vscode.WebviewOptions {
return {
...options,
localResourceRoots: options.localResourceRoots?.map(components => URI.from(components)),
};
}
function getDefaultLocalResourceRoots(
extension: IExtensionDescription,
workspace: IExtHostWorkspace | undefined,
): URI[] {
return [
...(workspace?.getWorkspaceFolders() || []).map(x => x.uri),
extension.extensionLocation,
];
}

View File

@ -0,0 +1,299 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Emitter } from 'vs/base/common/event';
import { Disposable } from 'vs/base/common/lifecycle';
import { URI } from 'vs/base/common/uri';
import { generateUuid } from 'vs/base/common/uuid';
import * as modes from 'vs/editor/common/modes';
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import * as typeConverters from 'vs/workbench/api/common/extHostTypeConverters';
import { convertWebviewOptions, ExtHostWebview, ExtHostWebviews, toExtensionData } from 'vs/workbench/api/common/extHostWebview';
import { IExtHostWorkspace } from 'vs/workbench/api/common/extHostWorkspace';
import { EditorViewColumn } from 'vs/workbench/api/common/shared/editor';
import type * as vscode from 'vscode';
import * as extHostProtocol from './extHost.protocol';
import * as extHostTypes from './extHostTypes';
type IconPath = URI | { light: URI, dark: URI };
class ExtHostWebviewPanel extends Disposable implements vscode.WebviewPanel {
readonly #handle: extHostProtocol.WebviewHandle;
readonly #proxy: extHostProtocol.MainThreadWebviewPanelsShape;
readonly #viewType: string;
readonly #webview: ExtHostWebview;
readonly #options: vscode.WebviewPanelOptions;
#title: string;
#iconPath?: IconPath;
#viewColumn: vscode.ViewColumn | undefined = undefined;
#visible: boolean = true;
#active: boolean = true;
#isDisposed: boolean = false;
readonly #onDidDispose = this._register(new Emitter<void>());
public readonly onDidDispose = this.#onDidDispose.event;
readonly #onDidChangeViewState = this._register(new Emitter<vscode.WebviewPanelOnDidChangeViewStateEvent>());
public readonly onDidChangeViewState = this.#onDidChangeViewState.event;
constructor(
handle: extHostProtocol.WebviewHandle,
proxy: extHostProtocol.MainThreadWebviewPanelsShape,
viewType: string,
title: string,
viewColumn: vscode.ViewColumn | undefined,
editorOptions: vscode.WebviewPanelOptions,
webview: ExtHostWebview
) {
super();
this.#handle = handle;
this.#proxy = proxy;
this.#viewType = viewType;
this.#options = editorOptions;
this.#viewColumn = viewColumn;
this.#title = title;
this.#webview = webview;
}
public dispose() {
if (this.#isDisposed) {
return;
}
this.#isDisposed = true;
this.#onDidDispose.fire();
this.#proxy.$disposeWebview(this.#handle);
this.#webview.dispose();
super.dispose();
}
get webview() {
this.assertNotDisposed();
return this.#webview;
}
get viewType(): string {
this.assertNotDisposed();
return this.#viewType;
}
get title(): string {
this.assertNotDisposed();
return this.#title;
}
set title(value: string) {
this.assertNotDisposed();
if (this.#title !== value) {
this.#title = value;
this.#proxy.$setTitle(this.#handle, value);
}
}
get iconPath(): IconPath | undefined {
this.assertNotDisposed();
return this.#iconPath;
}
set iconPath(value: IconPath | undefined) {
this.assertNotDisposed();
if (this.#iconPath !== value) {
this.#iconPath = value;
this.#proxy.$setIconPath(this.#handle, URI.isUri(value) ? { light: value, dark: value } : value);
}
}
get options() {
return this.#options;
}
get viewColumn(): vscode.ViewColumn | undefined {
this.assertNotDisposed();
if (typeof this.#viewColumn === 'number' && this.#viewColumn < 0) {
// We are using a symbolic view column
// Return undefined instead to indicate that the real view column is currently unknown but will be resolved.
return undefined;
}
return this.#viewColumn;
}
public get active(): boolean {
this.assertNotDisposed();
return this.#active;
}
public get visible(): boolean {
this.assertNotDisposed();
return this.#visible;
}
_updateViewState(newState: { active: boolean; visible: boolean; viewColumn: vscode.ViewColumn; }) {
if (this.#isDisposed) {
return;
}
if (this.active !== newState.active || this.visible !== newState.visible || this.viewColumn !== newState.viewColumn) {
this.#active = newState.active;
this.#visible = newState.visible;
this.#viewColumn = newState.viewColumn;
this.#onDidChangeViewState.fire({ webviewPanel: this });
}
}
public reveal(viewColumn?: vscode.ViewColumn, preserveFocus?: boolean): void {
this.assertNotDisposed();
this.#proxy.$reveal(this.#handle, {
viewColumn: viewColumn ? typeConverters.ViewColumn.from(viewColumn) : undefined,
preserveFocus: !!preserveFocus
});
}
private assertNotDisposed() {
if (this.#isDisposed) {
throw new Error('Webview is disposed');
}
}
}
export class ExtHostWebviewPanels implements extHostProtocol.ExtHostWebviewPanelsShape {
private static newHandle(): extHostProtocol.WebviewHandle {
return generateUuid();
}
private readonly _proxy: extHostProtocol.MainThreadWebviewPanelsShape;
private readonly _webviewPanels = new Map<extHostProtocol.WebviewHandle, ExtHostWebviewPanel>();
private readonly _serializers = new Map<string, {
readonly serializer: vscode.WebviewPanelSerializer;
readonly extension: IExtensionDescription;
}>();
constructor(
mainContext: extHostProtocol.IMainContext,
private readonly webviews: ExtHostWebviews,
private readonly workspace: IExtHostWorkspace | undefined,
) {
this._proxy = mainContext.getProxy(extHostProtocol.MainContext.MainThreadWebviewPanels);
}
public createWebviewPanel(
extension: IExtensionDescription,
viewType: string,
title: string,
showOptions: vscode.ViewColumn | { viewColumn: vscode.ViewColumn, preserveFocus?: boolean },
options: (vscode.WebviewPanelOptions & vscode.WebviewOptions) = {},
): vscode.WebviewPanel {
const viewColumn = typeof showOptions === 'object' ? showOptions.viewColumn : showOptions;
const webviewShowOptions = {
viewColumn: typeConverters.ViewColumn.from(viewColumn),
preserveFocus: typeof showOptions === 'object' && !!showOptions.preserveFocus
};
const handle = ExtHostWebviewPanels.newHandle();
this._proxy.$createWebviewPanel(toExtensionData(extension), handle, viewType, title, webviewShowOptions, convertWebviewOptions(extension, this.workspace, options));
const webview = this.webviews.createNewWebview(handle, options, extension);
const panel = this.createNewWebviewPanel(handle, viewType, title, viewColumn, options, webview);
return panel;
}
public $onDidChangeWebviewPanelViewStates(newStates: extHostProtocol.WebviewPanelViewStateData): void {
const handles = Object.keys(newStates);
// Notify webviews of state changes in the following order:
// - Non-visible
// - Visible
// - Active
handles.sort((a, b) => {
const stateA = newStates[a];
const stateB = newStates[b];
if (stateA.active) {
return 1;
}
if (stateB.active) {
return -1;
}
return (+stateA.visible) - (+stateB.visible);
});
for (const handle of handles) {
const panel = this.getWebviewPanel(handle);
if (!panel) {
continue;
}
const newState = newStates[handle];
panel._updateViewState({
active: newState.active,
visible: newState.visible,
viewColumn: typeConverters.ViewColumn.to(newState.position),
});
}
}
async $onDidDisposeWebviewPanel(handle: extHostProtocol.WebviewHandle): Promise<void> {
const panel = this.getWebviewPanel(handle);
panel?.dispose();
this._webviewPanels.delete(handle);
this.webviews.deleteWebview(handle);
}
public registerWebviewPanelSerializer(
extension: IExtensionDescription,
viewType: string,
serializer: vscode.WebviewPanelSerializer
): vscode.Disposable {
if (this._serializers.has(viewType)) {
throw new Error(`Serializer for '${viewType}' already registered`);
}
this._serializers.set(viewType, { serializer, extension });
this._proxy.$registerSerializer(viewType);
return new extHostTypes.Disposable(() => {
this._serializers.delete(viewType);
this._proxy.$unregisterSerializer(viewType);
});
}
async $deserializeWebviewPanel(
webviewHandle: extHostProtocol.WebviewHandle,
viewType: string,
title: string,
state: any,
position: EditorViewColumn,
options: modes.IWebviewOptions & modes.IWebviewPanelOptions
): Promise<void> {
const entry = this._serializers.get(viewType);
if (!entry) {
throw new Error(`No serializer found for '${viewType}'`);
}
const { serializer, extension } = entry;
const webview = this.webviews.createNewWebview(webviewHandle, options, extension);
const revivedPanel = this.createNewWebviewPanel(webviewHandle, viewType, title, position, options, webview);
await serializer.deserializeWebviewPanel(revivedPanel, state);
}
public createNewWebviewPanel(webviewHandle: string, viewType: string, title: string, position: number, options: modes.IWebviewOptions & modes.IWebviewPanelOptions, webview: ExtHostWebview) {
const panel = new ExtHostWebviewPanel(webviewHandle, this._proxy, viewType, title, typeof position === 'number' && position >= 0 ? typeConverters.ViewColumn.to(position) : undefined, options, webview);
this._webviewPanels.set(webviewHandle, panel);
return panel;
}
public getWebviewPanel(handle: extHostProtocol.WebviewHandle): ExtHostWebviewPanel | undefined {
return this._webviewPanels.get(handle);
}
}

View File

@ -0,0 +1,202 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { CancellationToken } from 'vs/base/common/cancellation';
import { Emitter } from 'vs/base/common/event';
import { Disposable } from 'vs/base/common/lifecycle';
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { ExtHostWebview, ExtHostWebviews, toExtensionData } from 'vs/workbench/api/common/extHostWebview';
import type * as vscode from 'vscode';
import * as extHostProtocol from './extHost.protocol';
import * as extHostTypes from './extHostTypes';
class ExtHostWebviewView extends Disposable implements vscode.WebviewView {
readonly #handle: extHostProtocol.WebviewHandle;
readonly #proxy: extHostProtocol.MainThreadWebviewViewsShape;
readonly #viewType: string;
readonly #webview: ExtHostWebview;
#isDisposed = false;
#isVisible: boolean;
#title: string | undefined;
#description: string | undefined;
constructor(
handle: extHostProtocol.WebviewHandle,
proxy: extHostProtocol.MainThreadWebviewViewsShape,
viewType: string,
title: string | undefined,
webview: ExtHostWebview,
isVisible: boolean,
) {
super();
this.#viewType = viewType;
this.#title = title;
this.#handle = handle;
this.#proxy = proxy;
this.#webview = webview;
this.#isVisible = isVisible;
}
public dispose() {
if (this.#isDisposed) {
return;
}
this.#isDisposed = true;
this.#onDidDispose.fire();
this.#webview.dispose();
super.dispose();
}
readonly #onDidChangeVisibility = this._register(new Emitter<void>());
public readonly onDidChangeVisibility = this.#onDidChangeVisibility.event;
readonly #onDidDispose = this._register(new Emitter<void>());
public readonly onDidDispose = this.#onDidDispose.event;
public get title(): string | undefined {
this.assertNotDisposed();
return this.#title;
}
public set title(value: string | undefined) {
this.assertNotDisposed();
if (this.#title !== value) {
this.#title = value;
this.#proxy.$setWebviewViewTitle(this.#handle, value);
}
}
public get description(): string | undefined {
this.assertNotDisposed();
return this.#description;
}
public set description(value: string | undefined) {
this.assertNotDisposed();
if (this.#description !== value) {
this.#description = value;
this.#proxy.$setWebviewViewDescription(this.#handle, value);
}
}
public get visible(): boolean { return this.#isVisible; }
public get webview(): vscode.Webview { return this.#webview; }
public get viewType(): string { return this.#viewType; }
/* internal */ _setVisible(visible: boolean) {
if (visible === this.#isVisible || this.#isDisposed) {
return;
}
this.#isVisible = visible;
this.#onDidChangeVisibility.fire();
}
public show(preserveFocus?: boolean): void {
this.assertNotDisposed();
this.#proxy.$show(this.#handle, !!preserveFocus);
}
private assertNotDisposed() {
if (this.#isDisposed) {
throw new Error('Webview is disposed');
}
}
}
export class ExtHostWebviewViews implements extHostProtocol.ExtHostWebviewViewsShape {
private readonly _proxy: extHostProtocol.MainThreadWebviewViewsShape;
private readonly _viewProviders = new Map<string, {
readonly provider: vscode.WebviewViewProvider;
readonly extension: IExtensionDescription;
}>();
private readonly _webviewViews = new Map<extHostProtocol.WebviewHandle, ExtHostWebviewView>();
constructor(
mainContext: extHostProtocol.IMainContext,
private readonly _extHostWebview: ExtHostWebviews,
) {
this._proxy = mainContext.getProxy(extHostProtocol.MainContext.MainThreadWebviewViews);
}
public registerWebviewViewProvider(
extension: IExtensionDescription,
viewType: string,
provider: vscode.WebviewViewProvider,
webviewOptions?: {
retainContextWhenHidden?: boolean
},
): vscode.Disposable {
if (this._viewProviders.has(viewType)) {
throw new Error(`View provider for '${viewType}' already registered`);
}
this._viewProviders.set(viewType, { provider, extension });
this._proxy.$registerWebviewViewProvider(toExtensionData(extension), viewType, webviewOptions);
return new extHostTypes.Disposable(() => {
this._viewProviders.delete(viewType);
this._proxy.$unregisterWebviewViewProvider(viewType);
});
}
async $resolveWebviewView(
webviewHandle: string,
viewType: string,
title: string | undefined,
state: any,
cancellation: CancellationToken,
): Promise<void> {
const entry = this._viewProviders.get(viewType);
if (!entry) {
throw new Error(`No view provider found for '${viewType}'`);
}
const { provider, extension } = entry;
const webview = this._extHostWebview.createNewWebview(webviewHandle, { /* todo */ }, extension);
const revivedView = new ExtHostWebviewView(webviewHandle, this._proxy, viewType, title, webview, true);
this._webviewViews.set(webviewHandle, revivedView);
await provider.resolveWebviewView(revivedView, { state }, cancellation);
}
async $onDidChangeWebviewViewVisibility(
webviewHandle: string,
visible: boolean
) {
const webviewView = this.getWebviewView(webviewHandle);
webviewView._setVisible(visible);
}
async $disposeWebviewView(webviewHandle: string) {
const webviewView = this.getWebviewView(webviewHandle);
this._webviewViews.delete(webviewHandle);
webviewView.dispose();
this._extHostWebview.deleteWebview(webviewHandle);
}
private getWebviewView(handle: string): ExtHostWebviewView {
const entry = this._webviewViews.get(handle);
if (!entry) {
throw new Error('No webview found');
}
return entry;
}
}

View File

@ -0,0 +1,74 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Event, Emitter } from 'vs/base/common/event';
import { ExtHostWindowShape, MainContext, MainThreadWindowShape, IOpenUriOptions } from './extHost.protocol';
import { WindowState } from 'vscode';
import { URI } from 'vs/base/common/uri';
import { Schemas } from 'vs/base/common/network';
import { isFalsyOrWhitespace } from 'vs/base/common/strings';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService';
export class ExtHostWindow implements ExtHostWindowShape {
private static InitialState: WindowState = {
focused: true
};
private _proxy: MainThreadWindowShape;
private readonly _onDidChangeWindowState = new Emitter<WindowState>();
readonly onDidChangeWindowState: Event<WindowState> = this._onDidChangeWindowState.event;
private _state = ExtHostWindow.InitialState;
get state(): WindowState { return this._state; }
constructor(@IExtHostRpcService extHostRpc: IExtHostRpcService) {
this._proxy = extHostRpc.getProxy(MainContext.MainThreadWindow);
this._proxy.$getWindowVisibility().then(isFocused => this.$onDidChangeWindowFocus(isFocused));
}
$onDidChangeWindowFocus(focused: boolean): void {
if (focused === this._state.focused) {
return;
}
this._state = { ...this._state, focused };
this._onDidChangeWindowState.fire(this._state);
}
openUri(stringOrUri: string | URI, options: IOpenUriOptions): Promise<boolean> {
let uriAsString: string | undefined;
if (typeof stringOrUri === 'string') {
uriAsString = stringOrUri;
try {
stringOrUri = URI.parse(stringOrUri);
} catch (e) {
return Promise.reject(`Invalid uri - '${stringOrUri}'`);
}
}
if (isFalsyOrWhitespace(stringOrUri.scheme)) {
return Promise.reject('Invalid scheme - cannot be empty');
} else if (stringOrUri.scheme === Schemas.command) {
return Promise.reject(`Invalid scheme '${stringOrUri.scheme}'`);
}
return this._proxy.$openUri(stringOrUri, uriAsString, options);
}
async asExternalUri(uri: URI, options: IOpenUriOptions): Promise<URI> {
if (isFalsyOrWhitespace(uri.scheme)) {
return Promise.reject('Invalid scheme - cannot be empty');
} else if (!new Set([Schemas.http, Schemas.https]).has(uri.scheme)) {
return Promise.reject(`Invalid scheme '${uri.scheme}'`);
}
const result = await this._proxy.$asExternalUri(uri, options);
return URI.from(result);
}
}
export const IExtHostWindow = createDecorator<IExtHostWindow>('IExtHostWindow');
export interface IExtHostWindow extends ExtHostWindow, ExtHostWindowShape { }

View File

@ -0,0 +1,575 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { delta as arrayDelta, mapArrayOrNot } from 'vs/base/common/arrays';
import { Barrier } from 'vs/base/common/async';
import { CancellationToken } from 'vs/base/common/cancellation';
import { Emitter, Event } from 'vs/base/common/event';
import { TernarySearchTree } from 'vs/base/common/map';
import { Schemas } from 'vs/base/common/network';
import { Counter } from 'vs/base/common/numbers';
import { isLinux } from 'vs/base/common/platform';
import { basename, basenameOrAuthority, dirname, isEqual, relativePath } from 'vs/base/common/resources';
import { compare } from 'vs/base/common/strings';
import { withUndefinedAsNull } from 'vs/base/common/types';
import { URI } from 'vs/base/common/uri';
import { localize } from 'vs/nls';
import { ExtensionIdentifier, IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { ILogService } from 'vs/platform/log/common/log';
import { Severity } from 'vs/platform/notification/common/notification';
import { Workspace, WorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import { IExtHostInitDataService } from 'vs/workbench/api/common/extHostInitDataService';
import { IExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService';
import { Range, RelativePattern } from 'vs/workbench/api/common/extHostTypes';
import { ITextQueryBuilderOptions } from 'vs/workbench/contrib/search/common/queryBuilder';
import { IRawFileMatch2, resultIsMatch } from 'vs/workbench/services/search/common/search';
import * as vscode from 'vscode';
import { ExtHostWorkspaceShape, IWorkspaceData, MainContext, MainThreadMessageServiceShape, MainThreadWorkspaceShape } from './extHost.protocol';
export interface IExtHostWorkspaceProvider {
getWorkspaceFolder2(uri: vscode.Uri, resolveParent?: boolean): Promise<vscode.WorkspaceFolder | undefined>;
resolveWorkspaceFolder(uri: vscode.Uri): Promise<vscode.WorkspaceFolder | undefined>;
getWorkspaceFolders2(): Promise<vscode.WorkspaceFolder[] | undefined>;
resolveProxy(url: string): Promise<string | undefined>;
}
function isFolderEqual(folderA: URI, folderB: URI): boolean {
return isEqual(folderA, folderB);
}
function compareWorkspaceFolderByUri(a: vscode.WorkspaceFolder, b: vscode.WorkspaceFolder): number {
return isFolderEqual(a.uri, b.uri) ? 0 : compare(a.uri.toString(), b.uri.toString());
}
function compareWorkspaceFolderByUriAndNameAndIndex(a: vscode.WorkspaceFolder, b: vscode.WorkspaceFolder): number {
if (a.index !== b.index) {
return a.index < b.index ? -1 : 1;
}
return isFolderEqual(a.uri, b.uri) ? compare(a.name, b.name) : compare(a.uri.toString(), b.uri.toString());
}
function delta(oldFolders: vscode.WorkspaceFolder[], newFolders: vscode.WorkspaceFolder[], compare: (a: vscode.WorkspaceFolder, b: vscode.WorkspaceFolder) => number): { removed: vscode.WorkspaceFolder[], added: vscode.WorkspaceFolder[] } {
const oldSortedFolders = oldFolders.slice(0).sort(compare);
const newSortedFolders = newFolders.slice(0).sort(compare);
return arrayDelta(oldSortedFolders, newSortedFolders, compare);
}
interface MutableWorkspaceFolder extends vscode.WorkspaceFolder {
name: string;
index: number;
}
class ExtHostWorkspaceImpl extends Workspace {
static toExtHostWorkspace(data: IWorkspaceData | null, previousConfirmedWorkspace?: ExtHostWorkspaceImpl, previousUnconfirmedWorkspace?: ExtHostWorkspaceImpl): { workspace: ExtHostWorkspaceImpl | null, added: vscode.WorkspaceFolder[], removed: vscode.WorkspaceFolder[] } {
if (!data) {
return { workspace: null, added: [], removed: [] };
}
const { id, name, folders, configuration, isUntitled } = data;
const newWorkspaceFolders: vscode.WorkspaceFolder[] = [];
// If we have an existing workspace, we try to find the folders that match our
// data and update their properties. It could be that an extension stored them
// for later use and we want to keep them "live" if they are still present.
const oldWorkspace = previousConfirmedWorkspace;
if (previousConfirmedWorkspace) {
folders.forEach((folderData, index) => {
const folderUri = URI.revive(folderData.uri);
const existingFolder = ExtHostWorkspaceImpl._findFolder(previousUnconfirmedWorkspace || previousConfirmedWorkspace, folderUri);
if (existingFolder) {
existingFolder.name = folderData.name;
existingFolder.index = folderData.index;
newWorkspaceFolders.push(existingFolder);
} else {
newWorkspaceFolders.push({ uri: folderUri, name: folderData.name, index });
}
});
} else {
newWorkspaceFolders.push(...folders.map(({ uri, name, index }) => ({ uri: URI.revive(uri), name, index })));
}
// make sure to restore sort order based on index
newWorkspaceFolders.sort((f1, f2) => f1.index < f2.index ? -1 : 1);
const workspace = new ExtHostWorkspaceImpl(id, name, newWorkspaceFolders, configuration ? URI.revive(configuration) : null, !!isUntitled);
const { added, removed } = delta(oldWorkspace ? oldWorkspace.workspaceFolders : [], workspace.workspaceFolders, compareWorkspaceFolderByUri);
return { workspace, added, removed };
}
private static _findFolder(workspace: ExtHostWorkspaceImpl, folderUriToFind: URI): MutableWorkspaceFolder | undefined {
for (let i = 0; i < workspace.folders.length; i++) {
const folder = workspace.workspaceFolders[i];
if (isFolderEqual(folder.uri, folderUriToFind)) {
return folder;
}
}
return undefined;
}
private readonly _workspaceFolders: vscode.WorkspaceFolder[] = [];
private readonly _structure = TernarySearchTree.forUris<vscode.WorkspaceFolder>(!isLinux);
constructor(id: string, private _name: string, folders: vscode.WorkspaceFolder[], configuration: URI | null, private _isUntitled: boolean) {
super(id, folders.map(f => new WorkspaceFolder(f)), configuration);
// setup the workspace folder data structure
folders.forEach(folder => {
this._workspaceFolders.push(folder);
this._structure.set(folder.uri, folder);
});
}
get name(): string {
return this._name;
}
get isUntitled(): boolean {
return this._isUntitled;
}
get workspaceFolders(): vscode.WorkspaceFolder[] {
return this._workspaceFolders.slice(0);
}
getWorkspaceFolder(uri: URI, resolveParent?: boolean): vscode.WorkspaceFolder | undefined {
if (resolveParent && this._structure.get(uri)) {
// `uri` is a workspace folder so we check for its parent
uri = dirname(uri);
}
return this._structure.findSubstr(uri);
}
resolveWorkspaceFolder(uri: URI): vscode.WorkspaceFolder | undefined {
return this._structure.get(uri);
}
}
export class ExtHostWorkspace implements ExtHostWorkspaceShape, IExtHostWorkspaceProvider {
readonly _serviceBrand: undefined;
private readonly _onDidChangeWorkspace = new Emitter<vscode.WorkspaceFoldersChangeEvent>();
readonly onDidChangeWorkspace: Event<vscode.WorkspaceFoldersChangeEvent> = this._onDidChangeWorkspace.event;
private readonly _logService: ILogService;
private readonly _requestIdProvider: Counter;
private readonly _barrier: Barrier;
private _confirmedWorkspace?: ExtHostWorkspaceImpl;
private _unconfirmedWorkspace?: ExtHostWorkspaceImpl;
private readonly _proxy: MainThreadWorkspaceShape;
private readonly _messageService: MainThreadMessageServiceShape;
private readonly _activeSearchCallbacks: ((match: IRawFileMatch2) => any)[] = [];
constructor(
@IExtHostRpcService extHostRpc: IExtHostRpcService,
@IExtHostInitDataService initData: IExtHostInitDataService,
@ILogService logService: ILogService,
) {
this._logService = logService;
this._requestIdProvider = new Counter();
this._barrier = new Barrier();
this._proxy = extHostRpc.getProxy(MainContext.MainThreadWorkspace);
this._messageService = extHostRpc.getProxy(MainContext.MainThreadMessageService);
const data = initData.workspace;
this._confirmedWorkspace = data ? new ExtHostWorkspaceImpl(data.id, data.name, [], data.configuration ? URI.revive(data.configuration) : null, !!data.isUntitled) : undefined;
}
$initializeWorkspace(data: IWorkspaceData | null): void {
this.$acceptWorkspaceData(data);
this._barrier.open();
}
waitForInitializeCall(): Promise<boolean> {
return this._barrier.wait();
}
// --- workspace ---
get workspace(): Workspace | undefined {
return this._actualWorkspace;
}
get name(): string | undefined {
return this._actualWorkspace ? this._actualWorkspace.name : undefined;
}
get workspaceFile(): vscode.Uri | undefined {
if (this._actualWorkspace) {
if (this._actualWorkspace.configuration) {
if (this._actualWorkspace.isUntitled) {
return URI.from({ scheme: Schemas.untitled, path: basename(dirname(this._actualWorkspace.configuration)) }); // Untitled Worspace: return untitled URI
}
return this._actualWorkspace.configuration; // Workspace: return the configuration location
}
}
return undefined;
}
private get _actualWorkspace(): ExtHostWorkspaceImpl | undefined {
return this._unconfirmedWorkspace || this._confirmedWorkspace;
}
getWorkspaceFolders(): vscode.WorkspaceFolder[] | undefined {
if (!this._actualWorkspace) {
return undefined;
}
return this._actualWorkspace.workspaceFolders.slice(0);
}
async getWorkspaceFolders2(): Promise<vscode.WorkspaceFolder[] | undefined> {
await this._barrier.wait();
if (!this._actualWorkspace) {
return undefined;
}
return this._actualWorkspace.workspaceFolders.slice(0);
}
updateWorkspaceFolders(extension: IExtensionDescription, index: number, deleteCount: number, ...workspaceFoldersToAdd: { uri: vscode.Uri, name?: string }[]): boolean {
const validatedDistinctWorkspaceFoldersToAdd: { uri: vscode.Uri, name?: string }[] = [];
if (Array.isArray(workspaceFoldersToAdd)) {
workspaceFoldersToAdd.forEach(folderToAdd => {
if (URI.isUri(folderToAdd.uri) && !validatedDistinctWorkspaceFoldersToAdd.some(f => isFolderEqual(f.uri, folderToAdd.uri))) {
validatedDistinctWorkspaceFoldersToAdd.push({ uri: folderToAdd.uri, name: folderToAdd.name || basenameOrAuthority(folderToAdd.uri) });
}
});
}
if (!!this._unconfirmedWorkspace) {
return false; // prevent accumulated calls without a confirmed workspace
}
if ([index, deleteCount].some(i => typeof i !== 'number' || i < 0)) {
return false; // validate numbers
}
if (deleteCount === 0 && validatedDistinctWorkspaceFoldersToAdd.length === 0) {
return false; // nothing to delete or add
}
const currentWorkspaceFolders: MutableWorkspaceFolder[] = this._actualWorkspace ? this._actualWorkspace.workspaceFolders : [];
if (index + deleteCount > currentWorkspaceFolders.length) {
return false; // cannot delete more than we have
}
// Simulate the updateWorkspaceFolders method on our data to do more validation
const newWorkspaceFolders = currentWorkspaceFolders.slice(0);
newWorkspaceFolders.splice(index, deleteCount, ...validatedDistinctWorkspaceFoldersToAdd.map(f => ({ uri: f.uri, name: f.name || basenameOrAuthority(f.uri), index: undefined! /* fixed later */ })));
for (let i = 0; i < newWorkspaceFolders.length; i++) {
const folder = newWorkspaceFolders[i];
if (newWorkspaceFolders.some((otherFolder, index) => index !== i && isFolderEqual(folder.uri, otherFolder.uri))) {
return false; // cannot add the same folder multiple times
}
}
newWorkspaceFolders.forEach((f, index) => f.index = index); // fix index
const { added, removed } = delta(currentWorkspaceFolders, newWorkspaceFolders, compareWorkspaceFolderByUriAndNameAndIndex);
if (added.length === 0 && removed.length === 0) {
return false; // nothing actually changed
}
// Trigger on main side
if (this._proxy) {
const extName = extension.displayName || extension.name;
this._proxy.$updateWorkspaceFolders(extName, index, deleteCount, validatedDistinctWorkspaceFoldersToAdd).then(undefined, error => {
// in case of an error, make sure to clear out the unconfirmed workspace
// because we cannot expect the acknowledgement from the main side for this
this._unconfirmedWorkspace = undefined;
// show error to user
this._messageService.$showMessage(Severity.Error, localize('updateerror', "Extension '{0}' failed to update workspace folders: {1}", extName, error.toString()), { extension }, []);
});
}
// Try to accept directly
this.trySetWorkspaceFolders(newWorkspaceFolders);
return true;
}
getWorkspaceFolder(uri: vscode.Uri, resolveParent?: boolean): vscode.WorkspaceFolder | undefined {
if (!this._actualWorkspace) {
return undefined;
}
return this._actualWorkspace.getWorkspaceFolder(uri, resolveParent);
}
async getWorkspaceFolder2(uri: vscode.Uri, resolveParent?: boolean): Promise<vscode.WorkspaceFolder | undefined> {
await this._barrier.wait();
if (!this._actualWorkspace) {
return undefined;
}
return this._actualWorkspace.getWorkspaceFolder(uri, resolveParent);
}
async resolveWorkspaceFolder(uri: vscode.Uri): Promise<vscode.WorkspaceFolder | undefined> {
await this._barrier.wait();
if (!this._actualWorkspace) {
return undefined;
}
return this._actualWorkspace.resolveWorkspaceFolder(uri);
}
getPath(): string | undefined {
// this is legacy from the days before having
// multi-root and we keep it only alive if there
// is just one workspace folder.
if (!this._actualWorkspace) {
return undefined;
}
const { folders } = this._actualWorkspace;
if (folders.length === 0) {
return undefined;
}
// #54483 @Joh Why are we still using fsPath?
return folders[0].uri.fsPath;
}
getRelativePath(pathOrUri: string | vscode.Uri, includeWorkspace?: boolean): string {
let resource: URI | undefined;
let path: string = '';
if (typeof pathOrUri === 'string') {
resource = URI.file(pathOrUri);
path = pathOrUri;
} else if (typeof pathOrUri !== 'undefined') {
resource = pathOrUri;
path = pathOrUri.fsPath;
}
if (!resource) {
return path;
}
const folder = this.getWorkspaceFolder(
resource,
true
);
if (!folder) {
return path;
}
if (typeof includeWorkspace === 'undefined' && this._actualWorkspace) {
includeWorkspace = this._actualWorkspace.folders.length > 1;
}
let result = relativePath(folder.uri, resource);
if (includeWorkspace && folder.name) {
result = `${folder.name}/${result}`;
}
return result!;
}
private trySetWorkspaceFolders(folders: vscode.WorkspaceFolder[]): void {
// Update directly here. The workspace is unconfirmed as long as we did not get an
// acknowledgement from the main side (via $acceptWorkspaceData)
if (this._actualWorkspace) {
this._unconfirmedWorkspace = ExtHostWorkspaceImpl.toExtHostWorkspace({
id: this._actualWorkspace.id,
name: this._actualWorkspace.name,
configuration: this._actualWorkspace.configuration,
folders,
isUntitled: this._actualWorkspace.isUntitled
} as IWorkspaceData, this._actualWorkspace).workspace || undefined;
}
}
$acceptWorkspaceData(data: IWorkspaceData | null): void {
const { workspace, added, removed } = ExtHostWorkspaceImpl.toExtHostWorkspace(data, this._confirmedWorkspace, this._unconfirmedWorkspace);
// Update our workspace object. We have a confirmed workspace, so we drop our
// unconfirmed workspace.
this._confirmedWorkspace = workspace || undefined;
this._unconfirmedWorkspace = undefined;
// Events
this._onDidChangeWorkspace.fire(Object.freeze({
added,
removed,
}));
}
// --- search ---
/**
* Note, null/undefined have different and important meanings for "exclude"
*/
findFiles(include: string | RelativePattern | undefined, exclude: vscode.GlobPattern | null | undefined, maxResults: number | undefined, extensionId: ExtensionIdentifier, token: vscode.CancellationToken = CancellationToken.None): Promise<vscode.Uri[]> {
this._logService.trace(`extHostWorkspace#findFiles: fileSearch, extension: ${extensionId.value}, entryPoint: findFiles`);
let excludePatternOrDisregardExcludes: string | false | undefined = undefined;
if (exclude === null) {
excludePatternOrDisregardExcludes = false;
} else if (exclude) {
if (typeof exclude === 'string') {
excludePatternOrDisregardExcludes = exclude;
} else {
excludePatternOrDisregardExcludes = exclude.pattern;
}
}
if (token && token.isCancellationRequested) {
return Promise.resolve([]);
}
const { includePattern, folder } = parseSearchInclude(include);
return this._proxy.$startFileSearch(
withUndefinedAsNull(includePattern),
withUndefinedAsNull(folder),
withUndefinedAsNull(excludePatternOrDisregardExcludes),
withUndefinedAsNull(maxResults),
token
)
.then(data => Array.isArray(data) ? data.map(d => URI.revive(d)) : []);
}
async findTextInFiles(query: vscode.TextSearchQuery, options: vscode.FindTextInFilesOptions, callback: (result: vscode.TextSearchResult) => void, extensionId: ExtensionIdentifier, token: vscode.CancellationToken = CancellationToken.None): Promise<vscode.TextSearchComplete> {
this._logService.trace(`extHostWorkspace#findTextInFiles: textSearch, extension: ${extensionId.value}, entryPoint: findTextInFiles`);
const requestId = this._requestIdProvider.getNext();
const previewOptions: vscode.TextSearchPreviewOptions = typeof options.previewOptions === 'undefined' ?
{
matchLines: 100,
charsPerLine: 10000
} :
options.previewOptions;
let includePattern: string | undefined;
let folder: URI | undefined;
if (options.include) {
if (typeof options.include === 'string') {
includePattern = options.include;
} else {
includePattern = options.include.pattern;
folder = (options.include as RelativePattern).baseFolder || URI.file(options.include.base);
}
}
const excludePattern = (typeof options.exclude === 'string') ? options.exclude :
options.exclude ? options.exclude.pattern : undefined;
const queryOptions: ITextQueryBuilderOptions = {
ignoreSymlinks: typeof options.followSymlinks === 'boolean' ? !options.followSymlinks : undefined,
disregardIgnoreFiles: typeof options.useIgnoreFiles === 'boolean' ? !options.useIgnoreFiles : undefined,
disregardGlobalIgnoreFiles: typeof options.useGlobalIgnoreFiles === 'boolean' ? !options.useGlobalIgnoreFiles : undefined,
disregardExcludeSettings: typeof options.useDefaultExcludes === 'boolean' ? !options.useDefaultExcludes : true,
fileEncoding: options.encoding,
maxResults: options.maxResults,
previewOptions,
afterContext: options.afterContext,
beforeContext: options.beforeContext,
includePattern: includePattern,
excludePattern: excludePattern
};
const isCanceled = false;
this._activeSearchCallbacks[requestId] = p => {
if (isCanceled) {
return;
}
const uri = URI.revive(p.resource);
p.results!.forEach(result => {
if (resultIsMatch(result)) {
callback(<vscode.TextSearchMatch>{
uri,
preview: {
text: result.preview.text,
matches: mapArrayOrNot(
result.preview.matches,
m => new Range(m.startLineNumber, m.startColumn, m.endLineNumber, m.endColumn))
},
ranges: mapArrayOrNot(
result.ranges,
r => new Range(r.startLineNumber, r.startColumn, r.endLineNumber, r.endColumn))
});
} else {
callback(<vscode.TextSearchContext>{
uri,
text: result.text,
lineNumber: result.lineNumber
});
}
});
};
if (token.isCancellationRequested) {
return {};
}
try {
const result = await this._proxy.$startTextSearch(
query,
withUndefinedAsNull(folder),
queryOptions,
requestId,
token);
delete this._activeSearchCallbacks[requestId];
return result || {};
} catch (err) {
delete this._activeSearchCallbacks[requestId];
throw err;
}
}
$handleTextSearchResult(result: IRawFileMatch2, requestId: number): void {
if (this._activeSearchCallbacks[requestId]) {
this._activeSearchCallbacks[requestId](result);
}
}
saveAll(includeUntitled?: boolean): Promise<boolean> {
return this._proxy.$saveAll(includeUntitled);
}
resolveProxy(url: string): Promise<string | undefined> {
return this._proxy.$resolveProxy(url);
}
}
export const IExtHostWorkspace = createDecorator<IExtHostWorkspace>('IExtHostWorkspace');
export interface IExtHostWorkspace extends ExtHostWorkspace, ExtHostWorkspaceShape, IExtHostWorkspaceProvider { }
function parseSearchInclude(include: RelativePattern | string | undefined): { includePattern?: string, folder?: URI } {
let includePattern: string | undefined;
let includeFolder: URI | undefined;
if (include) {
if (typeof include === 'string') {
includePattern = include;
} else {
includePattern = include.pattern;
// include.base must be an absolute path
includeFolder = include.baseFolder || URI.file(include.base);
}
}
return {
includePattern: includePattern,
folder: includeFolder
};
}

View File

@ -0,0 +1,84 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { ExtensionsRegistry } from 'vs/workbench/services/extensions/common/extensionsRegistry';
import * as resources from 'vs/base/common/resources';
import { isString } from 'vs/base/common/types';
interface IJSONValidationExtensionPoint {
fileMatch: string | string[];
url: string;
}
const configurationExtPoint = ExtensionsRegistry.registerExtensionPoint<IJSONValidationExtensionPoint[]>({
extensionPoint: 'jsonValidation',
defaultExtensionKind: 'workspace',
jsonSchema: {
description: nls.localize('contributes.jsonValidation', 'Contributes json schema configuration.'),
type: 'array',
defaultSnippets: [{ body: [{ fileMatch: '${1:file.json}', url: '${2:url}' }] }],
items: {
type: 'object',
defaultSnippets: [{ body: { fileMatch: '${1:file.json}', url: '${2:url}' } }],
properties: {
fileMatch: {
type: ['string', 'array'],
description: nls.localize('contributes.jsonValidation.fileMatch', 'The file pattern (or an array of patterns) to match, for example "package.json" or "*.launch". Exclusion patterns start with \'!\''),
items: {
type: ['string']
}
},
url: {
description: nls.localize('contributes.jsonValidation.url', 'A schema URL (\'http:\', \'https:\') or relative path to the extension folder (\'./\').'),
type: 'string'
}
}
}
}
});
export class JSONValidationExtensionPoint {
constructor() {
configurationExtPoint.setHandler((extensions) => {
for (const extension of extensions) {
const extensionValue = <IJSONValidationExtensionPoint[]>extension.value;
const collector = extension.collector;
const extensionLocation = extension.description.extensionLocation;
if (!extensionValue || !Array.isArray(extensionValue)) {
collector.error(nls.localize('invalid.jsonValidation', "'configuration.jsonValidation' must be a array"));
return;
}
extensionValue.forEach(extension => {
if (!isString(extension.fileMatch) && !(Array.isArray(extension.fileMatch) && extension.fileMatch.every(isString))) {
collector.error(nls.localize('invalid.fileMatch', "'configuration.jsonValidation.fileMatch' must be defined as a string or an array of strings."));
return;
}
let uri = extension.url;
if (!isString(uri)) {
collector.error(nls.localize('invalid.url', "'configuration.jsonValidation.url' must be a URL or relative path"));
return;
}
if (uri.startsWith('./')) {
try {
const colorThemeLocation = resources.joinPath(extensionLocation, uri);
if (!resources.isEqualOrParent(colorThemeLocation, extensionLocation)) {
collector.warn(nls.localize('invalid.path.1', "Expected `contributes.{0}.url` ({1}) to be included inside extension's folder ({2}). This might make the extension non-portable.", configurationExtPoint.name, colorThemeLocation.toString(), extensionLocation.path));
}
} catch (e) {
collector.error(nls.localize('invalid.url.fileschema', "'configuration.jsonValidation.url' is an invalid relative URL: {0}", e.message));
}
} else if (!/^[^:/?#]+:\/\//.test(uri)) {
collector.error(nls.localize('invalid.url.schema', "'configuration.jsonValidation.url' must be an absolute URL or start with './' to reference schemas located in the extension."));
return;
}
});
}
});
}
}

View File

@ -0,0 +1,717 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { localize } from 'vs/nls';
import { isFalsyOrWhitespace } from 'vs/base/common/strings';
import * as resources from 'vs/base/common/resources';
import { IJSONSchema } from 'vs/base/common/jsonSchema';
import { forEach } from 'vs/base/common/collections';
import { IExtensionPointUser, ExtensionMessageCollector, ExtensionsRegistry } from 'vs/workbench/services/extensions/common/extensionsRegistry';
import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { MenuId, MenuRegistry, ILocalizedString, IMenuItem, ICommandAction, ISubmenuItem } from 'vs/platform/actions/common/actions';
import { URI } from 'vs/base/common/uri';
import { DisposableStore } from 'vs/base/common/lifecycle';
import { ThemeIcon } from 'vs/platform/theme/common/themeService';
import { Iterable } from 'vs/base/common/iterator';
import { index } from 'vs/base/common/arrays';
interface IAPIMenu {
readonly key: string;
readonly id: MenuId;
readonly description: string;
readonly proposed?: boolean; // defaults to false
readonly supportsSubmenus?: boolean; // defaults to true
}
const apiMenus: IAPIMenu[] = [
{
key: 'commandPalette',
id: MenuId.CommandPalette,
description: localize('menus.commandPalette', "The Command Palette"),
supportsSubmenus: false
},
{
key: 'touchBar',
id: MenuId.TouchBarContext,
description: localize('menus.touchBar', "The touch bar (macOS only)"),
supportsSubmenus: false
},
{
key: 'editor/title',
id: MenuId.EditorTitle,
description: localize('menus.editorTitle', "The editor title menu")
},
{
key: 'editor/context',
id: MenuId.EditorContext,
description: localize('menus.editorContext', "The editor context menu")
},
{
key: 'explorer/context',
id: MenuId.ExplorerContext,
description: localize('menus.explorerContext', "The file explorer context menu")
},
{
key: 'editor/title/context',
id: MenuId.EditorTitleContext,
description: localize('menus.editorTabContext', "The editor tabs context menu")
},
{
key: 'debug/callstack/context',
id: MenuId.DebugCallStackContext,
description: localize('menus.debugCallstackContext', "The debug callstack view context menu")
},
{
key: 'debug/variables/context',
id: MenuId.DebugVariablesContext,
description: localize('menus.debugVariablesContext', "The debug variables view context menu")
},
{
key: 'debug/toolBar',
id: MenuId.DebugToolBar,
description: localize('menus.debugToolBar', "The debug toolbar menu")
},
{
key: 'menuBar/webNavigation',
id: MenuId.MenubarWebNavigationMenu,
description: localize('menus.webNavigation', "The top level navigational menu (web only)"),
proposed: true,
supportsSubmenus: false
},
{
key: 'menuBar/file',
id: MenuId.MenubarFileMenu,
description: localize('menus.file', "The top level file menu"),
proposed: true
},
{
key: 'scm/title',
id: MenuId.SCMTitle,
description: localize('menus.scmTitle', "The Source Control title menu")
},
{
key: 'scm/sourceControl',
id: MenuId.SCMSourceControl,
description: localize('menus.scmSourceControl', "The Source Control menu")
},
{
key: 'scm/resourceState/context',
id: MenuId.SCMResourceContext,
description: localize('menus.resourceGroupContext', "The Source Control resource group context menu")
},
{
key: 'scm/resourceFolder/context',
id: MenuId.SCMResourceFolderContext,
description: localize('menus.resourceStateContext', "The Source Control resource state context menu")
},
{
key: 'scm/resourceGroup/context',
id: MenuId.SCMResourceGroupContext,
description: localize('menus.resourceFolderContext', "The Source Control resource folder context menu")
},
{
key: 'scm/change/title',
id: MenuId.SCMChangeContext,
description: localize('menus.changeTitle', "The Source Control inline change menu")
},
{
key: 'statusBar/windowIndicator',
id: MenuId.StatusBarWindowIndicatorMenu,
description: localize('menus.statusBarWindowIndicator', "The window indicator menu in the status bar"),
proposed: true,
supportsSubmenus: false
},
{
key: 'view/title',
id: MenuId.ViewTitle,
description: localize('view.viewTitle', "The contributed view title menu")
},
{
key: 'view/item/context',
id: MenuId.ViewItemContext,
description: localize('view.itemContext', "The contributed view item context menu")
},
{
key: 'comments/commentThread/title',
id: MenuId.CommentThreadTitle,
description: localize('commentThread.title', "The contributed comment thread title menu")
},
{
key: 'comments/commentThread/context',
id: MenuId.CommentThreadActions,
description: localize('commentThread.actions', "The contributed comment thread context menu, rendered as buttons below the comment editor"),
supportsSubmenus: false
},
{
key: 'comments/comment/title',
id: MenuId.CommentTitle,
description: localize('comment.title', "The contributed comment title menu")
},
{
key: 'comments/comment/context',
id: MenuId.CommentActions,
description: localize('comment.actions', "The contributed comment context menu, rendered as buttons below the comment editor"),
supportsSubmenus: false
},
{
key: 'notebook/cell/title',
id: MenuId.NotebookCellTitle,
description: localize('notebook.cell.title', "The contributed notebook cell title menu"),
proposed: true
},
{
key: 'extension/context',
id: MenuId.ExtensionContext,
description: localize('menus.extensionContext', "The extension context menu")
},
{
key: 'timeline/title',
id: MenuId.TimelineTitle,
description: localize('view.timelineTitle', "The Timeline view title menu")
},
{
key: 'timeline/item/context',
id: MenuId.TimelineItemContext,
description: localize('view.timelineContext', "The Timeline view item context menu")
},
];
namespace schema {
// --- menus, submenus contribution point
export interface IUserFriendlyMenuItem {
command: string;
alt?: string;
when?: string;
group?: string;
}
export interface IUserFriendlySubmenuItem {
submenu: string;
when?: string;
group?: string;
}
export interface IUserFriendlySubmenu {
id: string;
label: string;
icon?: IUserFriendlyIcon;
}
export function isMenuItem(item: IUserFriendlyMenuItem | IUserFriendlySubmenuItem): item is IUserFriendlyMenuItem {
return typeof (item as IUserFriendlyMenuItem).command === 'string';
}
export function isValidMenuItem(item: IUserFriendlyMenuItem, collector: ExtensionMessageCollector): boolean {
if (typeof item.command !== 'string') {
collector.error(localize('requirestring', "property `{0}` is mandatory and must be of type `string`", 'command'));
return false;
}
if (item.alt && typeof item.alt !== 'string') {
collector.error(localize('optstring', "property `{0}` can be omitted or must be of type `string`", 'alt'));
return false;
}
if (item.when && typeof item.when !== 'string') {
collector.error(localize('optstring', "property `{0}` can be omitted or must be of type `string`", 'when'));
return false;
}
if (item.group && typeof item.group !== 'string') {
collector.error(localize('optstring', "property `{0}` can be omitted or must be of type `string`", 'group'));
return false;
}
return true;
}
export function isValidSubmenuItem(item: IUserFriendlySubmenuItem, collector: ExtensionMessageCollector): boolean {
if (typeof item.submenu !== 'string') {
collector.error(localize('requirestring', "property `{0}` is mandatory and must be of type `string`", 'submenu'));
return false;
}
if (item.when && typeof item.when !== 'string') {
collector.error(localize('optstring', "property `{0}` can be omitted or must be of type `string`", 'when'));
return false;
}
if (item.group && typeof item.group !== 'string') {
collector.error(localize('optstring', "property `{0}` can be omitted or must be of type `string`", 'group'));
return false;
}
return true;
}
export function isValidItems(items: (IUserFriendlyMenuItem | IUserFriendlySubmenuItem)[], collector: ExtensionMessageCollector): boolean {
if (!Array.isArray(items)) {
collector.error(localize('requirearray', "submenu items must be an array"));
return false;
}
for (let item of items) {
if (isMenuItem(item)) {
if (!isValidMenuItem(item, collector)) {
return false;
}
} else {
if (!isValidSubmenuItem(item, collector)) {
return false;
}
}
}
return true;
}
export function isValidSubmenu(submenu: IUserFriendlySubmenu, collector: ExtensionMessageCollector): boolean {
if (typeof submenu !== 'object') {
collector.error(localize('require', "submenu items must be an object"));
return false;
}
if (typeof submenu.id !== 'string') {
collector.error(localize('requirestring', "property `{0}` is mandatory and must be of type `string`", 'id'));
return false;
}
if (typeof submenu.label !== 'string') {
collector.error(localize('requirestring', "property `{0}` is mandatory and must be of type `string`", 'label'));
return false;
}
return true;
}
const menuItem: IJSONSchema = {
type: 'object',
required: ['command'],
properties: {
command: {
description: localize('vscode.extension.contributes.menuItem.command', 'Identifier of the command to execute. The command must be declared in the \'commands\'-section'),
type: 'string'
},
alt: {
description: localize('vscode.extension.contributes.menuItem.alt', 'Identifier of an alternative command to execute. The command must be declared in the \'commands\'-section'),
type: 'string'
},
when: {
description: localize('vscode.extension.contributes.menuItem.when', 'Condition which must be true to show this item'),
type: 'string'
},
group: {
description: localize('vscode.extension.contributes.menuItem.group', 'Group into which this item belongs'),
type: 'string'
}
}
};
const submenuItem: IJSONSchema = {
type: 'object',
required: ['submenu'],
properties: {
submenu: {
description: localize('vscode.extension.contributes.menuItem.submenu', 'Identifier of the submenu to display in this item.'),
type: 'string'
},
when: {
description: localize('vscode.extension.contributes.menuItem.when', 'Condition which must be true to show this item'),
type: 'string'
},
group: {
description: localize('vscode.extension.contributes.menuItem.group', 'Group into which this item belongs'),
type: 'string'
}
}
};
const submenu: IJSONSchema = {
type: 'object',
required: ['id', 'label'],
properties: {
id: {
description: localize('vscode.extension.contributes.submenu.id', 'Identifier of the menu to display as a submenu.'),
type: 'string'
},
label: {
description: localize('vscode.extension.contributes.submenu.label', 'The label of the menu item which leads to this submenu.'),
type: 'string'
},
icon: {
description: localize('vscode.extension.contributes.submenu.icon', '(Optional) Icon which is used to represent the submenu in the UI. Either a file path, an object with file paths for dark and light themes, or a theme icon references, like `\\$(zap)`'),
anyOf: [{
type: 'string'
},
{
type: 'object',
properties: {
light: {
description: localize('vscode.extension.contributes.submenu.icon.light', 'Icon path when a light theme is used'),
type: 'string'
},
dark: {
description: localize('vscode.extension.contributes.submenu.icon.dark', 'Icon path when a dark theme is used'),
type: 'string'
}
}
}]
}
}
};
export const menusContribution: IJSONSchema = {
description: localize('vscode.extension.contributes.menus', "Contributes menu items to the editor"),
type: 'object',
properties: index(apiMenus, menu => menu.key, menu => ({
description: menu.proposed ? `(${localize('proposed', "Proposed API")}) ${menu.description}` : menu.description,
type: 'array',
items: menu.supportsSubmenus === false ? menuItem : { oneOf: [menuItem, submenuItem] }
})),
additionalProperties: {
description: 'Submenu',
type: 'array',
items: { oneOf: [menuItem, submenuItem] }
}
};
export const submenusContribution: IJSONSchema = {
description: localize('vscode.extension.contributes.submenus', "Contributes submenu items to the editor"),
type: 'array',
items: submenu
};
// --- commands contribution point
export interface IUserFriendlyCommand {
command: string;
title: string | ILocalizedString;
enablement?: string;
category?: string | ILocalizedString;
icon?: IUserFriendlyIcon;
}
export type IUserFriendlyIcon = string | { light: string; dark: string; };
export function isValidCommand(command: IUserFriendlyCommand, collector: ExtensionMessageCollector): boolean {
if (!command) {
collector.error(localize('nonempty', "expected non-empty value."));
return false;
}
if (isFalsyOrWhitespace(command.command)) {
collector.error(localize('requirestring', "property `{0}` is mandatory and must be of type `string`", 'command'));
return false;
}
if (!isValidLocalizedString(command.title, collector, 'title')) {
return false;
}
if (command.enablement && typeof command.enablement !== 'string') {
collector.error(localize('optstring', "property `{0}` can be omitted or must be of type `string`", 'precondition'));
return false;
}
if (command.category && !isValidLocalizedString(command.category, collector, 'category')) {
return false;
}
if (!isValidIcon(command.icon, collector)) {
return false;
}
return true;
}
function isValidIcon(icon: IUserFriendlyIcon | undefined, collector: ExtensionMessageCollector): boolean {
if (typeof icon === 'undefined') {
return true;
}
if (typeof icon === 'string') {
return true;
} else if (typeof icon.dark === 'string' && typeof icon.light === 'string') {
return true;
}
collector.error(localize('opticon', "property `icon` can be omitted or must be either a string or a literal like `{dark, light}`"));
return false;
}
function isValidLocalizedString(localized: string | ILocalizedString, collector: ExtensionMessageCollector, propertyName: string): boolean {
if (typeof localized === 'undefined') {
collector.error(localize('requireStringOrObject', "property `{0}` is mandatory and must be of type `string` or `object`", propertyName));
return false;
} else if (typeof localized === 'string' && isFalsyOrWhitespace(localized)) {
collector.error(localize('requirestring', "property `{0}` is mandatory and must be of type `string`", propertyName));
return false;
} else if (typeof localized !== 'string' && (isFalsyOrWhitespace(localized.original) || isFalsyOrWhitespace(localized.value))) {
collector.error(localize('requirestrings', "properties `{0}` and `{1}` are mandatory and must be of type `string`", `${propertyName}.value`, `${propertyName}.original`));
return false;
}
return true;
}
const commandType: IJSONSchema = {
type: 'object',
required: ['command', 'title'],
properties: {
command: {
description: localize('vscode.extension.contributes.commandType.command', 'Identifier of the command to execute'),
type: 'string'
},
title: {
description: localize('vscode.extension.contributes.commandType.title', 'Title by which the command is represented in the UI'),
type: 'string'
},
category: {
description: localize('vscode.extension.contributes.commandType.category', '(Optional) Category string by the command is grouped in the UI'),
type: 'string'
},
enablement: {
description: localize('vscode.extension.contributes.commandType.precondition', '(Optional) Condition which must be true to enable the command'),
type: 'string'
},
icon: {
description: localize('vscode.extension.contributes.commandType.icon', '(Optional) Icon which is used to represent the command in the UI. Either a file path, an object with file paths for dark and light themes, or a theme icon references, like `\\$(zap)`'),
anyOf: [{
type: 'string'
},
{
type: 'object',
properties: {
light: {
description: localize('vscode.extension.contributes.commandType.icon.light', 'Icon path when a light theme is used'),
type: 'string'
},
dark: {
description: localize('vscode.extension.contributes.commandType.icon.dark', 'Icon path when a dark theme is used'),
type: 'string'
}
}
}]
}
}
};
export const commandsContribution: IJSONSchema = {
description: localize('vscode.extension.contributes.commands', "Contributes commands to the command palette."),
oneOf: [
commandType,
{
type: 'array',
items: commandType
}
]
};
}
const _commandRegistrations = new DisposableStore();
export const commandsExtensionPoint = ExtensionsRegistry.registerExtensionPoint<schema.IUserFriendlyCommand | schema.IUserFriendlyCommand[]>({
extensionPoint: 'commands',
jsonSchema: schema.commandsContribution
});
commandsExtensionPoint.setHandler(extensions => {
function handleCommand(userFriendlyCommand: schema.IUserFriendlyCommand, extension: IExtensionPointUser<any>, bucket: ICommandAction[]) {
if (!schema.isValidCommand(userFriendlyCommand, extension.collector)) {
return;
}
const { icon, enablement, category, title, command } = userFriendlyCommand;
let absoluteIcon: { dark: URI; light?: URI; } | ThemeIcon | undefined;
if (icon) {
if (typeof icon === 'string') {
absoluteIcon = ThemeIcon.fromString(icon) || { dark: resources.joinPath(extension.description.extensionLocation, icon) };
} else {
absoluteIcon = {
dark: resources.joinPath(extension.description.extensionLocation, icon.dark),
light: resources.joinPath(extension.description.extensionLocation, icon.light)
};
}
}
if (MenuRegistry.getCommand(command)) {
extension.collector.info(localize('dup', "Command `{0}` appears multiple times in the `commands` section.", userFriendlyCommand.command));
}
bucket.push({
id: command,
title,
category,
precondition: ContextKeyExpr.deserialize(enablement),
icon: absoluteIcon
});
}
// remove all previous command registrations
_commandRegistrations.clear();
const newCommands: ICommandAction[] = [];
for (const extension of extensions) {
const { value } = extension;
if (Array.isArray(value)) {
for (const command of value) {
handleCommand(command, extension, newCommands);
}
} else {
handleCommand(value, extension, newCommands);
}
}
_commandRegistrations.add(MenuRegistry.addCommands(newCommands));
});
interface IRegisteredSubmenu {
readonly id: MenuId;
readonly label: string;
readonly icon?: { dark: URI; light?: URI; } | ThemeIcon;
}
const _submenus = new Map<string, IRegisteredSubmenu>();
const submenusExtensionPoint = ExtensionsRegistry.registerExtensionPoint<schema.IUserFriendlySubmenu[]>({
extensionPoint: 'submenus',
jsonSchema: schema.submenusContribution
});
submenusExtensionPoint.setHandler(extensions => {
_submenus.clear();
for (let extension of extensions) {
const { value, collector } = extension;
forEach(value, entry => {
if (!schema.isValidSubmenu(entry.value, collector)) {
return;
}
if (!entry.value.id) {
collector.warn(localize('submenuId.invalid.id', "`{0}` is not a valid submenu identifier", entry.value.id));
return;
}
if (!entry.value.label) {
collector.warn(localize('submenuId.invalid.label', "`{0}` is not a valid submenu label", entry.value.label));
return;
}
let absoluteIcon: { dark: URI; light?: URI; } | ThemeIcon | undefined;
if (entry.value.icon) {
if (typeof entry.value.icon === 'string') {
absoluteIcon = ThemeIcon.fromString(entry.value.icon) || { dark: resources.joinPath(extension.description.extensionLocation, entry.value.icon) };
} else {
absoluteIcon = {
dark: resources.joinPath(extension.description.extensionLocation, entry.value.icon.dark),
light: resources.joinPath(extension.description.extensionLocation, entry.value.icon.light)
};
}
}
const item: IRegisteredSubmenu = {
id: new MenuId(`api:${entry.value.id}`),
label: entry.value.label,
icon: absoluteIcon
};
_submenus.set(entry.value.id, item);
});
}
});
const _apiMenusByKey = new Map(Iterable.map(Iterable.from(apiMenus), menu => ([menu.key, menu])));
const _menuRegistrations = new DisposableStore();
const menusExtensionPoint = ExtensionsRegistry.registerExtensionPoint<{ [loc: string]: (schema.IUserFriendlyMenuItem | schema.IUserFriendlySubmenuItem)[] }>({
extensionPoint: 'menus',
jsonSchema: schema.menusContribution,
deps: [submenusExtensionPoint]
});
menusExtensionPoint.setHandler(extensions => {
// remove all previous menu registrations
_menuRegistrations.clear();
const items: { id: MenuId, item: IMenuItem | ISubmenuItem }[] = [];
for (let extension of extensions) {
const { value, collector } = extension;
forEach(value, entry => {
if (!schema.isValidItems(entry.value, collector)) {
return;
}
let menu = _apiMenusByKey.get(entry.key);
if (!menu) {
const submenu = _submenus.get(entry.key);
if (submenu) {
menu = {
key: entry.key,
id: submenu.id,
description: ''
};
}
}
if (!menu) {
collector.warn(localize('menuId.invalid', "`{0}` is not a valid menu identifier", entry.key));
return;
}
if (menu.proposed && !extension.description.enableProposedApi) {
collector.error(localize('proposedAPI.invalid', "{0} is a proposed menu identifier and is only available when running out of dev or with the following command line switch: --enable-proposed-api {1}", entry.key, extension.description.identifier.value));
return;
}
for (const menuItem of entry.value) {
let item: IMenuItem | ISubmenuItem;
if (schema.isMenuItem(menuItem)) {
const command = MenuRegistry.getCommand(menuItem.command);
const alt = menuItem.alt && MenuRegistry.getCommand(menuItem.alt) || undefined;
if (!command) {
collector.error(localize('missing.command', "Menu item references a command `{0}` which is not defined in the 'commands' section.", menuItem.command));
continue;
}
if (menuItem.alt && !alt) {
collector.warn(localize('missing.altCommand', "Menu item references an alt-command `{0}` which is not defined in the 'commands' section.", menuItem.alt));
}
if (menuItem.command === menuItem.alt) {
collector.info(localize('dupe.command', "Menu item references the same command as default and alt-command"));
}
item = { command, alt, group: undefined, order: undefined, when: undefined };
} else {
if (menu.supportsSubmenus === false) {
collector.error(localize('unsupported.submenureference', "Menu item references a submenu for a menu which doesn't have submenu support."));
continue;
}
const submenu = _submenus.get(menuItem.submenu);
if (!submenu) {
collector.error(localize('missing.submenu', "Menu item references a submenu `{0}` which is not defined in the 'submenus' section.", menuItem.submenu));
continue;
}
item = { submenu: submenu.id, icon: submenu.icon, title: submenu.label, group: undefined, order: undefined, when: undefined };
}
if (menuItem.group) {
const idx = menuItem.group.lastIndexOf('@');
if (idx > 0) {
item.group = menuItem.group.substr(0, idx);
item.order = Number(menuItem.group.substr(idx + 1)) || undefined;
} else {
item.group = menuItem.group;
}
}
item.when = ContextKeyExpr.deserialize(menuItem.when);
items.push({ id: menu.id, item });
}
});
}
_menuRegistrations.add(MenuRegistry.appendMenuItems(items));
});

View File

@ -0,0 +1,39 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IEditorGroupsService, IEditorGroup, GroupsOrder } from 'vs/workbench/services/editor/common/editorGroupsService';
import { GroupIdentifier } from 'vs/workbench/common/editor';
import { ACTIVE_GROUP, SIDE_GROUP } from 'vs/workbench/services/editor/common/editorService';
export type EditorViewColumn = number;
export function viewColumnToEditorGroup(editorGroupService: IEditorGroupsService, position?: EditorViewColumn): GroupIdentifier {
if (typeof position !== 'number' || position === ACTIVE_GROUP) {
return ACTIVE_GROUP; // prefer active group when position is undefined or passed in as such
}
const groups = editorGroupService.getGroups(GroupsOrder.GRID_APPEARANCE);
let candidate = groups[position];
if (candidate) {
return candidate.id; // found direct match
}
let firstGroup = groups[0];
if (groups.length === 1 && firstGroup.count === 0) {
return firstGroup.id; // first editor should always open in first group independent from position provided
}
return SIDE_GROUP; // open to the side if group not found or we are instructed to
}
export function editorGroupToViewColumn(editorGroupService: IEditorGroupsService, editorGroup: IEditorGroup | GroupIdentifier): EditorViewColumn {
const group = (typeof editorGroup === 'number') ? editorGroupService.getGroup(editorGroup) : editorGroup;
if (!group) {
throw new Error('Invalid group provided');
}
return editorGroupService.getGroups(GroupsOrder.GRID_APPEARANCE).indexOf(group);
}

View File

@ -0,0 +1,152 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { VSBuffer } from 'vs/base/common/buffer';
import * as platform from 'vs/base/common/platform';
export interface IFullSemanticTokensDto {
id: number;
type: 'full';
data: Uint32Array;
}
export interface IDeltaSemanticTokensDto {
id: number;
type: 'delta';
deltas: { start: number; deleteCount: number; data?: Uint32Array; }[];
}
export type ISemanticTokensDto = IFullSemanticTokensDto | IDeltaSemanticTokensDto;
const enum EncodedSemanticTokensType {
Full = 1,
Delta = 2
}
function reverseEndianness(arr: Uint8Array): void {
for (let i = 0, len = arr.length; i < len; i += 4) {
// flip bytes 0<->3 and 1<->2
const b0 = arr[i + 0];
const b1 = arr[i + 1];
const b2 = arr[i + 2];
const b3 = arr[i + 3];
arr[i + 0] = b3;
arr[i + 1] = b2;
arr[i + 2] = b1;
arr[i + 3] = b0;
}
}
function toLittleEndianBuffer(arr: Uint32Array): VSBuffer {
const uint8Arr = new Uint8Array(arr.buffer, arr.byteOffset, arr.length * 4);
if (!platform.isLittleEndian()) {
// the byte order must be changed
reverseEndianness(uint8Arr);
}
return VSBuffer.wrap(uint8Arr);
}
function fromLittleEndianBuffer(buff: VSBuffer): Uint32Array {
const uint8Arr = buff.buffer;
if (!platform.isLittleEndian()) {
// the byte order must be changed
reverseEndianness(uint8Arr);
}
if (uint8Arr.byteOffset % 4 === 0) {
return new Uint32Array(uint8Arr.buffer, uint8Arr.byteOffset, uint8Arr.length / 4);
} else {
// unaligned memory access doesn't work on all platforms
const data = new Uint8Array(uint8Arr.byteLength);
data.set(uint8Arr);
return new Uint32Array(data.buffer, data.byteOffset, data.length / 4);
}
}
export function encodeSemanticTokensDto(semanticTokens: ISemanticTokensDto): VSBuffer {
const dest = new Uint32Array(encodeSemanticTokensDtoSize(semanticTokens));
let offset = 0;
dest[offset++] = semanticTokens.id;
if (semanticTokens.type === 'full') {
dest[offset++] = EncodedSemanticTokensType.Full;
dest[offset++] = semanticTokens.data.length;
dest.set(semanticTokens.data, offset); offset += semanticTokens.data.length;
} else {
dest[offset++] = EncodedSemanticTokensType.Delta;
dest[offset++] = semanticTokens.deltas.length;
for (const delta of semanticTokens.deltas) {
dest[offset++] = delta.start;
dest[offset++] = delta.deleteCount;
if (delta.data) {
dest[offset++] = delta.data.length;
dest.set(delta.data, offset); offset += delta.data.length;
} else {
dest[offset++] = 0;
}
}
}
return toLittleEndianBuffer(dest);
}
function encodeSemanticTokensDtoSize(semanticTokens: ISemanticTokensDto): number {
let result = 0;
result += (
+ 1 // id
+ 1 // type
);
if (semanticTokens.type === 'full') {
result += (
+ 1 // data length
+ semanticTokens.data.length
);
} else {
result += (
+ 1 // delta count
);
result += (
+ 1 // start
+ 1 // deleteCount
+ 1 // data length
) * semanticTokens.deltas.length;
for (const delta of semanticTokens.deltas) {
if (delta.data) {
result += delta.data.length;
}
}
}
return result;
}
export function decodeSemanticTokensDto(_buff: VSBuffer): ISemanticTokensDto {
const src = fromLittleEndianBuffer(_buff);
let offset = 0;
const id = src[offset++];
const type: EncodedSemanticTokensType = src[offset++];
if (type === EncodedSemanticTokensType.Full) {
const length = src[offset++];
const data = src.subarray(offset, offset + length); offset += length;
return {
id: id,
type: 'full',
data: data
};
}
const deltaCount = src[offset++];
let deltas: { start: number; deleteCount: number; data?: Uint32Array; }[] = [];
for (let i = 0; i < deltaCount; i++) {
const start = src[offset++];
const deleteCount = src[offset++];
const length = src[offset++];
let data: Uint32Array | undefined;
if (length > 0) {
data = src.subarray(offset, offset + length); offset += length;
}
deltas[i] = { start, deleteCount, data };
}
return {
id: id,
type: 'delta',
deltas: deltas
};
}

View File

@ -0,0 +1,129 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { UriComponents } from 'vs/base/common/uri';
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
export interface TaskDefinitionDTO {
type: string;
[name: string]: any;
}
export interface TaskPresentationOptionsDTO {
reveal?: number;
echo?: boolean;
focus?: boolean;
panel?: number;
showReuseMessage?: boolean;
clear?: boolean;
group?: string;
}
export interface RunOptionsDTO {
reevaluateOnRerun?: boolean;
}
export interface ExecutionOptionsDTO {
cwd?: string;
env?: { [key: string]: string };
}
export interface ProcessExecutionOptionsDTO extends ExecutionOptionsDTO {
}
export interface ProcessExecutionDTO {
process: string;
args: string[];
options?: ProcessExecutionOptionsDTO;
}
export interface ShellQuotingOptionsDTO {
escape?: string | {
escapeChar: string;
charsToEscape: string;
};
strong?: string;
weak?: string;
}
export interface ShellExecutionOptionsDTO extends ExecutionOptionsDTO {
executable?: string;
shellArgs?: string[];
shellQuoting?: ShellQuotingOptionsDTO;
}
export interface ShellQuotedStringDTO {
value: string;
quoting: number;
}
export interface ShellExecutionDTO {
commandLine?: string;
command?: string | ShellQuotedStringDTO;
args?: Array<string | ShellQuotedStringDTO>;
options?: ShellExecutionOptionsDTO;
}
export interface CustomExecutionDTO {
customExecution: 'customExecution';
}
export interface TaskSourceDTO {
label: string;
extensionId?: string;
scope?: number | UriComponents;
}
export interface TaskHandleDTO {
id: string;
workspaceFolder: UriComponents | string;
}
export interface TaskDTO {
_id: string;
name?: string;
execution: ProcessExecutionDTO | ShellExecutionDTO | CustomExecutionDTO | undefined;
definition: TaskDefinitionDTO;
isBackground?: boolean;
source: TaskSourceDTO;
group?: string;
detail?: string;
presentationOptions?: TaskPresentationOptionsDTO;
problemMatchers: string[];
hasDefinedMatchers: boolean;
runOptions?: RunOptionsDTO;
}
export interface TaskSetDTO {
tasks: TaskDTO[];
extension: IExtensionDescription;
}
export interface TaskExecutionDTO {
id: string;
task: TaskDTO | undefined;
}
export interface TaskProcessStartedDTO {
id: string;
processId: number;
}
export interface TaskProcessEndedDTO {
id: string;
exitCode: number;
}
export interface TaskFilterDTO {
version?: string;
type?: string;
}
export interface TaskSystemInfoDTO {
scheme: string;
authority: string;
platform: string;
}

View File

@ -0,0 +1,30 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { URI } from 'vs/base/common/uri';
import type * as vscode from 'vscode';
export interface WebviewInitData {
readonly isExtensionDevelopmentDebug: boolean;
readonly webviewResourceRoot: string;
readonly webviewCspSource: string;
}
export function asWebviewUri(
initData: WebviewInitData,
uuid: string,
resource: vscode.Uri,
): vscode.Uri {
const uri = initData.webviewResourceRoot
// Make sure we preserve the scheme of the resource but convert it into a normal path segment
// The scheme is important as we need to know if we are requesting a local or a remote resource.
.replace('{{resource}}', resource.scheme + withoutScheme(resource))
.replace('{{uuid}}', uuid);
return URI.parse(uri);
}
function withoutScheme(resource: vscode.Uri): string {
return resource.toString().replace(/^\S+?:/, '');
}

View File

@ -0,0 +1,138 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as resources from 'vs/base/common/resources';
import { URI, UriComponents } from 'vs/base/common/uri';
import { CancellationTokenSource, CancellationToken } from 'vs/base/common/cancellation';
import * as errors from 'vs/base/common/errors';
import { ExtensionIdentifier, IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { QueryBuilder } from 'vs/workbench/contrib/search/common/queryBuilder';
import { ISearchService } from 'vs/workbench/services/search/common/search';
import { toWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
const WORKSPACE_CONTAINS_TIMEOUT = 7000;
export interface IExtensionActivationHost {
readonly folders: readonly UriComponents[];
readonly forceUsingSearch: boolean;
exists(uri: URI): Promise<boolean>;
checkExists(folders: readonly UriComponents[], includes: string[], token: CancellationToken): Promise<boolean>;
}
export interface IExtensionActivationResult {
activationEvent: string;
}
export function checkActivateWorkspaceContainsExtension(host: IExtensionActivationHost, desc: IExtensionDescription): Promise<IExtensionActivationResult | undefined> {
const activationEvents = desc.activationEvents;
if (!activationEvents) {
return Promise.resolve(undefined);
}
const fileNames: string[] = [];
const globPatterns: string[] = [];
for (const activationEvent of activationEvents) {
if (/^workspaceContains:/.test(activationEvent)) {
const fileNameOrGlob = activationEvent.substr('workspaceContains:'.length);
if (fileNameOrGlob.indexOf('*') >= 0 || fileNameOrGlob.indexOf('?') >= 0 || host.forceUsingSearch) {
globPatterns.push(fileNameOrGlob);
} else {
fileNames.push(fileNameOrGlob);
}
}
}
if (fileNames.length === 0 && globPatterns.length === 0) {
return Promise.resolve(undefined);
}
let resolveResult: (value: IExtensionActivationResult | undefined) => void;
const result = new Promise<IExtensionActivationResult | undefined>((resolve, reject) => { resolveResult = resolve; });
const activate = (activationEvent: string) => resolveResult({ activationEvent });
const fileNamePromise = Promise.all(fileNames.map((fileName) => _activateIfFileName(host, fileName, activate))).then(() => { });
const globPatternPromise = _activateIfGlobPatterns(host, desc.identifier, globPatterns, activate);
Promise.all([fileNamePromise, globPatternPromise]).then(() => {
// when all are done, resolve with undefined (relevant only if it was not activated so far)
resolveResult(undefined);
});
return result;
}
async function _activateIfFileName(host: IExtensionActivationHost, fileName: string, activate: (activationEvent: string) => void): Promise<void> {
// find exact path
for (const uri of host.folders) {
if (await host.exists(resources.joinPath(URI.revive(uri), fileName))) {
// the file was found
activate(`workspaceContains:${fileName}`);
return;
}
}
}
async function _activateIfGlobPatterns(host: IExtensionActivationHost, extensionId: ExtensionIdentifier, globPatterns: string[], activate: (activationEvent: string) => void): Promise<void> {
if (globPatterns.length === 0) {
return Promise.resolve(undefined);
}
const tokenSource = new CancellationTokenSource();
const searchP = host.checkExists(host.folders, globPatterns, tokenSource.token);
const timer = setTimeout(async () => {
tokenSource.cancel();
activate(`workspaceContainsTimeout:${globPatterns.join(',')}`);
}, WORKSPACE_CONTAINS_TIMEOUT);
let exists: boolean = false;
try {
exists = await searchP;
} catch (err) {
if (!errors.isPromiseCanceledError(err)) {
errors.onUnexpectedError(err);
}
}
tokenSource.dispose();
clearTimeout(timer);
if (exists) {
// a file was found matching one of the glob patterns
activate(`workspaceContains:${globPatterns.join(',')}`);
}
}
export function checkGlobFileExists(
accessor: ServicesAccessor,
folders: readonly UriComponents[],
includes: string[],
token: CancellationToken,
): Promise<boolean> {
const instantiationService = accessor.get(IInstantiationService);
const searchService = accessor.get(ISearchService);
const queryBuilder = instantiationService.createInstance(QueryBuilder);
const query = queryBuilder.file(folders.map(folder => toWorkspaceFolder(URI.revive(folder))), {
_reason: 'checkExists',
includePattern: includes.join(', '),
expandPatterns: true,
exists: true
});
return searchService.fileSearch(query, token).then(
result => {
return !!result.limitHit;
},
err => {
if (!errors.isPromiseCanceledError(err)) {
return Promise.reject(err);
}
return false;
});
}