Merge remote-tracking branch 'upstream/master' into rebornix/review

This commit is contained in:
Peng Lyu
2018-05-18 10:16:19 -07:00
1515 changed files with 30577 additions and 20733 deletions

View File

@@ -32,7 +32,7 @@ export class PreviewHTMLAPICommand {
public static execute(executor: ICommandsExecutor, uri: URI, position?: vscode.ViewColumn, label?: string, options?: any): Thenable<any> {
return executor.executeCommand('_workbench.previewHtml',
uri,
typeof position === 'number' && typeConverters.fromViewColumn(position),
typeof position === 'number' && typeConverters.ViewColumn.from(position),
label,
options
);
@@ -59,8 +59,8 @@ export class DiffAPICommand {
left, right,
label,
undefined,
typeConverters.toTextEditorOptions(options),
options ? typeConverters.fromViewColumn(options.viewColumn) : undefined
typeConverters.TextEditorOptions.from(options),
options ? typeConverters.ViewColumn.from(options.viewColumn) : undefined
]);
}
}
@@ -74,10 +74,10 @@ export class OpenAPICommand {
if (columnOrOptions) {
if (typeof columnOrOptions === 'number') {
column = typeConverters.fromViewColumn(columnOrOptions);
column = typeConverters.ViewColumn.from(columnOrOptions);
} else {
options = typeConverters.toTextEditorOptions(columnOrOptions);
column = typeConverters.fromViewColumn(columnOrOptions.viewColumn);
options = typeConverters.TextEditorOptions.from(columnOrOptions);
column = typeConverters.ViewColumn.from(columnOrOptions.viewColumn);
}
}

View File

@@ -7,7 +7,7 @@
import { Emitter } from 'vs/base/common/event';
import { TernarySearchTree } from 'vs/base/common/map';
import { score } from 'vs/editor/common/modes/languageSelector';
import * as Platform from 'vs/base/common/platform';
import * as platform from 'vs/base/common/platform';
import * as errors from 'vs/base/common/errors';
import product from 'vs/platform/node/product';
import pkg from 'vs/platform/node/package';
@@ -31,7 +31,7 @@ import { ExtHostTerminalService } from 'vs/workbench/api/node/extHostTerminalSer
import { ExtHostMessageService } from 'vs/workbench/api/node/extHostMessageService';
import { ExtHostEditors } from 'vs/workbench/api/node/extHostTextEditors';
import { ExtHostLanguages } from 'vs/workbench/api/node/extHostLanguages';
import { ExtHostLanguageFeatures } from 'vs/workbench/api/node/extHostLanguageFeatures';
import { ExtHostLanguageFeatures, ISchemeTransformer } from 'vs/workbench/api/node/extHostLanguageFeatures';
import { ExtHostApiCommands } from 'vs/workbench/api/node/extHostApiCommands';
import { ExtHostTask } from 'vs/workbench/api/node/extHostTask';
import { ExtHostDebugService } from 'vs/workbench/api/node/extHostDebugService';
@@ -45,6 +45,7 @@ import { TPromise } from 'vs/base/common/winjs.base';
import { CancellationTokenSource } from 'vs/base/common/cancellation';
import * as vscode from 'vscode';
import * as paths from 'vs/base/common/paths';
import * as files from 'vs/platform/files/common/files';
import { MainContext, ExtHostContext, IInitData, IExtHostContext } from './extHost.protocol';
import * as languageConfiguration from 'vs/editor/common/modes/languageConfiguration';
import { TextEditorCursorStyle } from 'vs/editor/common/config/editorOptions';
@@ -52,7 +53,7 @@ import { ProxyIdentifier } from 'vs/workbench/services/extensions/node/proxyIden
import { ExtHostDialogs } from 'vs/workbench/api/node/extHostDialogs';
import { ExtHostFileSystem } from 'vs/workbench/api/node/extHostFileSystem';
import { ExtHostDecorations } from 'vs/workbench/api/node/extHostDecorations';
import { toGlobPattern, toLanguageSelector } from 'vs/workbench/api/node/extHostTypeConverters';
import * as typeConverters from 'vs/workbench/api/node/extHostTypeConverters';
import { ExtensionActivatedByAPI } from 'vs/workbench/api/node/extHostExtensionActivator';
import { OverviewRulerLane } from 'vs/editor/common/model';
import { ExtHostLogService } from 'vs/workbench/api/node/extHostLogService';
@@ -95,6 +96,8 @@ export function createApiFactory(
extHostLogService: ExtHostLogService
): IExtensionApiFactory {
let schemeTransformer: ISchemeTransformer = null;
// Addressable instances
rpcProtocol.set(ExtHostContext.ExtHostLogService, extHostLogService);
const extHostHeapService = rpcProtocol.set(ExtHostContext.ExtHostHeapService, new ExtHostHeapService());
@@ -112,13 +115,13 @@ export function createApiFactory(
const extHostDebugService = rpcProtocol.set(ExtHostContext.ExtHostDebugService, new ExtHostDebugService(rpcProtocol, extHostWorkspace, extensionService, extHostDocumentsAndEditors, extHostConfiguration));
rpcProtocol.set(ExtHostContext.ExtHostConfiguration, extHostConfiguration);
const extHostDiagnostics = rpcProtocol.set(ExtHostContext.ExtHostDiagnostics, new ExtHostDiagnostics(rpcProtocol));
const extHostLanguageFeatures = rpcProtocol.set(ExtHostContext.ExtHostLanguageFeatures, new ExtHostLanguageFeatures(rpcProtocol, null, extHostDocuments, extHostCommands, extHostHeapService, extHostDiagnostics));
const extHostLanguageFeatures = rpcProtocol.set(ExtHostContext.ExtHostLanguageFeatures, new ExtHostLanguageFeatures(rpcProtocol, schemeTransformer, extHostDocuments, extHostCommands, extHostHeapService, extHostDiagnostics));
const extHostFileSystem = rpcProtocol.set(ExtHostContext.ExtHostFileSystem, new ExtHostFileSystem(rpcProtocol, extHostLanguageFeatures));
const extHostFileSystemEvent = rpcProtocol.set(ExtHostContext.ExtHostFileSystemEventService, new ExtHostFileSystemEventService());
const extHostQuickOpen = rpcProtocol.set(ExtHostContext.ExtHostQuickOpen, new ExtHostQuickOpen(rpcProtocol, extHostWorkspace, extHostCommands));
const extHostTerminalService = rpcProtocol.set(ExtHostContext.ExtHostTerminalService, new ExtHostTerminalService(rpcProtocol, extHostConfiguration, extHostLogService));
const extHostSCM = rpcProtocol.set(ExtHostContext.ExtHostSCM, new ExtHostSCM(rpcProtocol, extHostCommands, extHostLogService));
const extHostSearch = rpcProtocol.set(ExtHostContext.ExtHostSearch, new ExtHostSearch(rpcProtocol));
const extHostSearch = rpcProtocol.set(ExtHostContext.ExtHostSearch, new ExtHostSearch(rpcProtocol, schemeTransformer));
const extHostTask = rpcProtocol.set(ExtHostContext.ExtHostTask, new ExtHostTask(rpcProtocol, extHostWorkspace));
const extHostWindow = rpcProtocol.set(ExtHostContext.ExtHostWindow, new ExtHostWindow(rpcProtocol));
rpcProtocol.set(ExtHostContext.ExtHostExtensionService, extensionService);
@@ -126,7 +129,7 @@ export function createApiFactory(
const exthostCommentProviders = rpcProtocol.set(ExtHostContext.ExtHostComments, new ExtHostComments(rpcProtocol, extHostCommands.converter, extHostDocuments));
// Check that no named customers are missing
const expected: ProxyIdentifier<any>[] = Object.keys(ExtHostContext).map((key) => ExtHostContext[key]);
const expected: ProxyIdentifier<any>[] = Object.keys(ExtHostContext).map((key) => (<any>ExtHostContext)[key]);
rpcProtocol.assertRegistered(expected);
// Other instances
@@ -147,19 +150,24 @@ export function createApiFactory(
// We only inform once, it is not a warning because we just want to raise awareness and because
// we cannot say if the extension is doing it right or wrong...
let checkSelector = (function () {
let done = initData.environment.extensionDevelopmentPath !== extension.extensionFolderPath;
function inform(selector: vscode.DocumentSelector) {
console.info(`Extension '${extension.id}' uses a document selector without scheme. Learn more about this: https://go.microsoft.com/fwlink/?linkid=872305`);
done = true;
let done = (!extension.isUnderDevelopment);
function informOnce(selector: vscode.DocumentSelector) {
if (!done) {
console.info(`Extension '${extension.id}' uses a document selector without scheme. Learn more about this: https://go.microsoft.com/fwlink/?linkid=872305`);
done = true;
}
}
return function perform(selector: vscode.DocumentSelector): vscode.DocumentSelector {
if (!done) {
if (Array.isArray(selector)) {
selector.forEach(perform);
} else if (typeof selector === 'string') {
inform(selector);
} else if (typeof selector.scheme === 'undefined') {
inform(selector);
if (Array.isArray(selector)) {
selector.forEach(perform);
} else if (typeof selector === 'string') {
informOnce(selector);
} else {
if (typeof selector.scheme === 'undefined') {
informOnce(selector);
}
if (!extension.enableProposedApi && typeof selector.exclusive === 'boolean') {
throwProposedApiError(extension);
}
}
return selector;
@@ -216,7 +224,7 @@ export function createApiFactory(
const env: typeof vscode.env = Object.freeze({
get machineId() { return initData.telemetryInfo.machineId; },
get sessionId() { return initData.telemetryInfo.sessionId; },
get language() { return Platform.language; },
get language() { return platform.language; },
get appName() { return product.nameLong; },
get appRoot() { return initData.environment.appRoot; },
get logLevel() { return extHostLogService.getLevel(); }
@@ -242,17 +250,16 @@ export function createApiFactory(
return extHostDiagnostics.createDiagnosticCollection(name);
},
get onDidChangeDiagnostics() {
checkProposedApiEnabled(extension);
return extHostDiagnostics.onDidChangeDiagnostics;
},
getDiagnostics: (resource?) => {
getDiagnostics: (resource?: vscode.Uri) => {
return <any>extHostDiagnostics.getDiagnostics(resource);
},
getLanguages(): TPromise<string[]> {
return extHostLanguages.getLanguages();
},
match(selector: vscode.DocumentSelector, document: vscode.TextDocument): number {
return score(toLanguageSelector(selector), document.uri, document.languageId, true);
return score(typeConverters.LanguageSelector.from(selector), document.uri, document.languageId, true);
},
registerCodeActionsProvider(selector: vscode.DocumentSelector, provider: vscode.CodeActionProvider, metadata?: vscode.CodeActionProviderMetadata): vscode.Disposable {
return extHostLanguageFeatures.registerCodeActionProvider(checkSelector(selector), provider, metadata);
@@ -282,7 +289,7 @@ export function createApiFactory(
return extHostLanguageFeatures.registerRenameProvider(checkSelector(selector), provider);
},
registerDocumentSymbolProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentSymbolProvider): vscode.Disposable {
return extHostLanguageFeatures.registerDocumentSymbolProvider(checkSelector(selector), provider);
return extHostLanguageFeatures.registerDocumentSymbolProvider(checkSelector(selector), provider, extension.id);
},
registerWorkspaceSymbolProvider(provider: vscode.WorkspaceSymbolProvider): vscode.Disposable {
return extHostLanguageFeatures.registerWorkspaceSymbolProvider(provider);
@@ -381,13 +388,16 @@ export function createApiFactory(
return extHostMessageService.showMessage(extension, Severity.Error, message, first, rest);
},
showQuickPick(items: any, options: vscode.QuickPickOptions, token?: vscode.CancellationToken): any {
return extHostQuickOpen.showQuickPick(items, options, token);
return extHostQuickOpen.showQuickPick(undefined, items, options, token);
},
showWorkspaceFolderPick(options: vscode.WorkspaceFolderPickOptions) {
return extHostQuickOpen.showWorkspaceFolderPick(options);
},
showInputBox(options?: vscode.InputBoxOptions, token?: vscode.CancellationToken) {
return extHostQuickOpen.showInput(options, token);
return extHostQuickOpen.showInput(undefined, options, token);
},
multiStepInput<T>(handler: (input: vscode.QuickInput, token: vscode.CancellationToken) => Thenable<T>, token?: vscode.CancellationToken): Thenable<T> {
return extHostQuickOpen.multiStepInput(handler, token);
},
showOpenDialog(options) {
return extHostDialogs.showOpenDialog(options);
@@ -411,8 +421,8 @@ export function createApiFactory(
createOutputChannel(name: string): vscode.OutputChannel {
return extHostOutputService.createOutputChannel(name);
},
createWebviewPanel(viewType: string, title: string, column: vscode.ViewColumn, options: vscode.WebviewPanelOptions & vscode.WebviewOptions): vscode.WebviewPanel {
return extHostWebviews.createWebview(viewType, title, column, options, extension.extensionFolderPath);
createWebviewPanel(viewType: string, title: string, showOptions: vscode.ViewColumn | { viewColumn: vscode.ViewColumn, preserveFocus?: boolean }, options: vscode.WebviewPanelOptions & vscode.WebviewOptions): vscode.WebviewPanel {
return extHostWebviews.createWebview(viewType, title, showOptions, options, extension.extensionLocation);
},
createTerminal(nameOrOptions: vscode.TerminalOptions | string, shellPath?: string, shellArgs?: string[]): vscode.Terminal {
if (typeof nameOrOptions === 'object') {
@@ -471,7 +481,7 @@ export function createApiFactory(
return extHostWorkspace.getRelativePath(pathOrUri, includeWorkspace);
},
findFiles: (include, exclude, maxResults?, token?) => {
return extHostWorkspace.findFiles(toGlobPattern(include), toGlobPattern(exclude), maxResults, extension.id, token);
return extHostWorkspace.findFiles(typeConverters.GlobPattern.from(include), typeConverters.GlobPattern.from(exclude), maxResults, extension.id, token);
},
saveAll: (includeUntitled?) => {
return extHostWorkspace.saveAll(includeUntitled);
@@ -480,7 +490,7 @@ export function createApiFactory(
return extHostEditors.applyWorkspaceEdit(edit);
},
createFileSystemWatcher: (pattern, ignoreCreate, ignoreChange, ignoreDelete): vscode.FileSystemWatcher => {
return extHostFileSystemEvent.createFileSystemWatcher(toGlobPattern(pattern), ignoreCreate, ignoreChange, ignoreDelete);
return extHostFileSystemEvent.createFileSystemWatcher(typeConverters.GlobPattern.from(pattern), ignoreCreate, ignoreChange, ignoreDelete);
},
get textDocuments() {
return extHostDocuments.getAllDocumentData().map(data => data.document);
@@ -619,6 +629,32 @@ export function createApiFactory(
}
};
const tasks: typeof vscode.tasks = {
registerTaskProvider: (type: string, provider: vscode.TaskProvider) => {
return extHostTask.registerTaskProvider(extension, provider);
},
fetchTasks: proposedApiFunction(extension, (filter?: vscode.TaskFilter): Thenable<vscode.Task[]> => {
return extHostTask.fetchTasks(filter);
}),
executeTask: proposedApiFunction(extension, (task: vscode.Task): Thenable<vscode.TaskExecution> => {
return extHostTask.executeTask(extension, task);
}),
get taskExecutions(): vscode.TaskExecution[] {
return extHostTask.taskExecutions;
},
onDidStartTask: (listeners, thisArgs?, disposables?) => {
return extHostTask.onDidStartTask(listeners, thisArgs, disposables);
},
onDidEndTask: (listeners, thisArgs?, disposables?) => {
return extHostTask.onDidEndTask(listeners, thisArgs, disposables);
},
onDidStartTaskProcess: (listeners, thisArgs?, disposables?) => {
return extHostTask.onDidStartTaskProcess(listeners, thisArgs, disposables);
},
onDidEndTaskProcess: (listeners, thisArgs?, disposables?) => {
return extHostTask.onDidEndTaskProcess(listeners, thisArgs, disposables);
}
};
return <typeof vscode>{
version: pkg.version,
@@ -631,6 +667,7 @@ export function createApiFactory(
workspace,
scm,
debug,
tasks,
// types
Breakpoint: extHostTypes.Breakpoint,
CancellationTokenSource: CancellationTokenSource,
@@ -648,6 +685,7 @@ export function createApiFactory(
DebugAdapterExecutable: extHostTypes.DebugAdapterExecutable,
Diagnostic: extHostTypes.Diagnostic,
DiagnosticRelatedInformation: extHostTypes.DiagnosticRelatedInformation,
DiagnosticTag: extHostTypes.DiagnosticTag,
DiagnosticSeverity: extHostTypes.DiagnosticSeverity,
Disposable: extHostTypes.Disposable,
DocumentHighlight: extHostTypes.DocumentHighlight,
@@ -671,10 +709,16 @@ export function createApiFactory(
SourceBreakpoint: extHostTypes.SourceBreakpoint,
StatusBarAlignment: extHostTypes.StatusBarAlignment,
SymbolInformation: extHostTypes.SymbolInformation,
HierarchicalSymbolInformation: class extends extHostTypes.HierarchicalSymbolInformation {
constructor(name, kind, keyof, range) {
SymbolInformation2: class extends extHostTypes.SymbolInformation2 {
constructor(name, detail, kind, range, location) {
checkProposedApiEnabled(extension);
super(name, kind, keyof, range);
super(name, detail, kind, range, location);
}
},
Hierarchy: class <T> extends extHostTypes.Hierarchy<T> {
constructor(parent: T) {
checkProposedApiEnabled(extension);
super(parent);
}
},
SymbolKind: extHostTypes.SymbolKind,
@@ -709,6 +753,7 @@ export function createApiFactory(
DeprecatedFileChangeType: extHostTypes.DeprecatedFileChangeType,
DeprecatedFileType: extHostTypes.DeprecatedFileType,
FileChangeType: extHostTypes.FileChangeType,
FileType: files.FileType,
FileSystemError: extHostTypes.FileSystemError,
FoldingRange: extHostTypes.FoldingRange,
FoldingRangeKind: extHostTypes.FoldingRangeKind,
@@ -729,7 +774,7 @@ class Extension<T> implements vscode.Extension<T> {
constructor(extensionService: ExtHostExtensionService, description: IExtensionDescription) {
this._extensionService = extensionService;
this.id = description.id;
this.extensionPath = paths.normalize(description.extensionFolderPath, true);
this.extensionPath = paths.normalize(description.extensionLocation.fsPath, true);
this.packageJSON = description;
}
@@ -758,13 +803,13 @@ function defineAPI(factory: IExtensionApiFactory, extensionPaths: TernarySearchT
const node_module = <any>require.__$__nodeRequire('module');
const original = node_module._load;
node_module._load = function load(request, parent, isMain) {
node_module._load = function load(request: string, parent: any, isMain: any) {
if (request !== 'vscode') {
return original.apply(this, arguments);
}
// get extension id from filename and api for extension
const ext = extensionPaths.findSubstr(parent.filename);
const ext = extensionPaths.findSubstr(URI.file(parent.filename).fsPath);
if (ext) {
let apiImpl = extApiImpl.get(ext.id);
if (!apiImpl) {
@@ -776,6 +821,7 @@ function defineAPI(factory: IExtensionApiFactory, extensionPaths: TernarySearchT
// fall back to a default implementation
if (!defaultApiImpl) {
console.warn(`Could not identify extension for 'vscode' require call from ${parent.filename}`);
defaultApiImpl = factory(nullExtensionDescription);
}
return defaultApiImpl;
@@ -791,8 +837,9 @@ const nullExtensionDescription: IExtensionDescription = {
enableProposedApi: false,
engines: undefined,
extensionDependencies: undefined,
extensionFolderPath: undefined,
extensionLocation: undefined,
isBuiltin: false,
isUnderDevelopment: false,
main: undefined,
version: undefined
};

View File

@@ -26,7 +26,7 @@ import * as modes from 'vs/editor/common/modes';
import { IConfigurationData, ConfigurationTarget, IConfigurationModel } from 'vs/platform/configuration/common/configuration';
import { IConfig, IAdapterExecutable, ITerminalSettings } from 'vs/workbench/parts/debug/common/debug';
import { IPickOpenEntry, IPickOptions } from 'vs/platform/quickOpen/common/quickOpen';
import { IPickOpenEntry, IPickOptions } from 'vs/platform/quickinput/common/quickInput';
import { SaveReason } from 'vs/workbench/services/textfile/common/textfiles';
import { TextEditorCursorStyle } from 'vs/editor/common/config/editorOptions';
import { EndOfLine, TextEditorLineNumbersStyle } from 'vs/workbench/api/node/extHostTypes';
@@ -42,13 +42,13 @@ import { ITreeItem } from 'vs/workbench/common/views';
import { ThemeColor } from 'vs/platform/theme/common/themeService';
import { IDisposable } from 'vs/base/common/lifecycle';
import { SerializedError } from 'vs/base/common/errors';
import { IStat, FileChangeType, IWatchOptions, FileSystemProviderCapabilities, FileOptions } from 'vs/platform/files/common/files';
import { IStat, FileChangeType, IWatchOptions, FileSystemProviderCapabilities, FileWriteOptions, FileType, FileOverwriteOptions } from 'vs/platform/files/common/files';
import { ConfigurationScope } from 'vs/platform/configuration/common/configurationRegistry';
import { CommentRule, CharacterPair, EnterAction } from 'vs/editor/common/modes/languageConfiguration';
import { ISingleEditOperation } from 'vs/editor/common/model';
import { ILineMatch, IPatternInfo } from 'vs/platform/search/common/search';
import { IPatternInfo, IRawSearchQuery, IRawFileMatch2, ISearchCompleteStats } from 'vs/platform/search/common/search';
import { LogLevel } from 'vs/platform/log/common/log';
import { TaskExecutionDTO, TaskDTO, TaskHandleDTO, TaskFilterDTO } from 'vs/workbench/api/shared/tasks';
import { TaskExecutionDTO, TaskDTO, TaskHandleDTO, TaskFilterDTO, TaskProcessStartedDTO, TaskProcessEndedDTO } from 'vs/workbench/api/shared/tasks';
export interface IEnvironment {
isExtensionDevelopmentDebug: boolean;
@@ -214,7 +214,7 @@ export interface MainThreadTextEditorsShape extends IDisposable {
export interface MainThreadTreeViewsShape extends IDisposable {
$registerTreeViewDataProvider(treeViewId: string): void;
$refresh(treeViewId: string, itemsToRefresh?: { [treeItemHandle: string]: ITreeItem }): void;
$refresh(treeViewId: string, itemsToRefresh?: { [treeItemHandle: string]: ITreeItem }): TPromise<void>;
$reveal(treeViewId: string, treeItem: ITreeItem, parentChain: ITreeItem[], options?: { select?: boolean }): TPromise<void>;
}
@@ -266,11 +266,12 @@ export interface ISerializedDocumentFilter {
language?: string;
scheme?: string;
pattern?: vscode.GlobPattern;
exclusive?: boolean;
}
export interface MainThreadLanguageFeaturesShape extends IDisposable {
$unregister(handle: number): void;
$registerOutlineSupport(handle: number, selector: ISerializedDocumentFilter[]): void;
$registerOutlineSupport(handle: number, selector: ISerializedDocumentFilter[], extensionId: string): void;
$registerCodeLensSupport(handle: number, selector: ISerializedDocumentFilter[], eventHandle: number): void;
$emitCodeLensEvent(eventHandle: number, event?: any): void;
$registerDeclaractionSupport(handle: number, selector: ISerializedDocumentFilter[]): void;
@@ -339,10 +340,11 @@ export interface MyQuickPickItems extends IPickOpenEntry {
handle: number;
}
export interface MainThreadQuickOpenShape extends IDisposable {
$show(options: IPickOptions): TPromise<number | number[]>;
$show(multiStepHandle: number | undefined, options: IPickOptions): TPromise<number | number[]>;
$setItems(items: MyQuickPickItems[]): TPromise<any>;
$setError(error: Error): TPromise<any>;
$input(options: vscode.InputBoxOptions, validateInput: boolean): TPromise<string>;
$input(multiStepHandle: number | undefined, options: vscode.InputBoxOptions, validateInput: boolean): TPromise<string>;
$multiStep(handle: number): TPromise<never>;
}
export interface MainThreadStatusBarShape extends IDisposable {
@@ -362,9 +364,9 @@ export interface MainThreadTelemetryShape extends IDisposable {
export type WebviewPanelHandle = string;
export interface MainThreadWebviewsShape extends IDisposable {
$createWebviewPanel(handle: WebviewPanelHandle, viewType: string, title: string, column: EditorPosition, options: vscode.WebviewPanelOptions & vscode.WebviewOptions, extensionFolderPath: string): void;
$createWebviewPanel(handle: WebviewPanelHandle, viewType: string, title: string, viewOptions: { viewColumn: EditorPosition, preserveFocus: boolean }, options: vscode.WebviewPanelOptions & vscode.WebviewOptions, extensionLocation: UriComponents): void;
$disposeWebview(handle: WebviewPanelHandle): void;
$reveal(handle: WebviewPanelHandle, column: EditorPosition | undefined): void;
$reveal(handle: WebviewPanelHandle, viewColumn: EditorPosition | null, preserveFocus: boolean): void;
$setTitle(handle: WebviewPanelHandle, value: string): void;
$setHtml(handle: WebviewPanelHandle, value: string): void;
$postMessage(handle: WebviewPanelHandle, value: any): Thenable<boolean>;
@@ -378,7 +380,6 @@ export interface ExtHostWebviewsShape {
$onDidChangeWebviewPanelViewState(handle: WebviewPanelHandle, active: boolean, position: EditorPosition): void;
$onDidDisposeWebviewPanel(handle: WebviewPanelHandle): Thenable<void>;
$deserializeWebviewPanel(newWebviewHandle: WebviewPanelHandle, viewType: string, title: string, state: any, position: EditorPosition, options: vscode.WebviewOptions): Thenable<void>;
$serializeWebviewPanel(webviewHandle: WebviewPanelHandle): Thenable<any>;
}
export interface MainThreadUrlsShape extends IDisposable {
@@ -411,7 +412,8 @@ export interface MainThreadFileSystemShape extends IDisposable {
export interface MainThreadSearchShape extends IDisposable {
$registerSearchProvider(handle: number, scheme: string): void;
$unregisterProvider(handle: number): void;
$handleFindMatch(handle: number, session, data: UriComponents | [UriComponents, ILineMatch]): void;
$handleFindMatch(handle: number, session: number, data: UriComponents | IRawFileMatch2[]): void;
$handleTelemetry(eventName: string, data: any): void;
}
export interface MainThreadTaskShape extends IDisposable {
@@ -486,10 +488,10 @@ export interface MainThreadSCMShape extends IDisposable {
export type DebugSessionUUID = string;
export interface MainThreadDebugServiceShape extends IDisposable {
$registerDebugTypes(debugTypes: string[]);
$acceptDAMessage(handle: number, message: DebugProtocol.ProtocolMessage);
$acceptDAError(handle: number, name: string, message: string, stack: string);
$acceptDAExit(handle: number, code: number, signal: string);
$registerDebugTypes(debugTypes: string[]): void;
$acceptDAMessage(handle: number, message: DebugProtocol.ProtocolMessage): void;
$acceptDAError(handle: number, name: string, message: string, stack: string): void;
$acceptDAExit(handle: number, code: number, signal: string): void;
$registerDebugConfigurationProvider(type: string, hasProvideMethod: boolean, hasResolveMethod: boolean, hasDebugAdapterExecutable: boolean, handle: number): TPromise<any>;
$unregisterDebugConfigurationProvider(handle: number): TPromise<any>;
$startDebugging(folder: UriComponents | undefined, nameOrConfig: string | vscode.DebugConfiguration): TPromise<boolean>;
@@ -582,6 +584,8 @@ export interface ExtHostDocumentsAndEditorsShape {
export interface ExtHostTreeViewsShape {
$getChildren(treeViewId: string, treeItemHandle?: string): TPromise<ITreeItem[]>;
$setExpanded(treeViewId: string, treeItemHandle: string, expanded: boolean): void;
$setSelection(treeViewId: string, treeItemHandles: string[]): void;
}
export interface ExtHostWorkspaceShape {
@@ -590,20 +594,20 @@ export interface ExtHostWorkspaceShape {
export interface ExtHostFileSystemShape {
$stat(handle: number, resource: UriComponents): TPromise<IStat>;
$readFile(handle: number, resource: UriComponents, opts: FileOptions): TPromise<string>;
$writeFile(handle: number, resource: UriComponents, base64Encoded: string, opts: FileOptions): TPromise<void>;
$rename(handle: number, resource: UriComponents, target: UriComponents, opts: FileOptions): TPromise<IStat>;
$copy(handle: number, resource: UriComponents, target: UriComponents, opts: FileOptions): TPromise<IStat>;
$mkdir(handle: number, resource: UriComponents): TPromise<IStat>;
$readdir(handle: number, resource: UriComponents): TPromise<[string, IStat][]>;
$readdir(handle: number, resource: UriComponents): TPromise<[string, FileType][]>;
$readFile(handle: number, resource: UriComponents): TPromise<string>;
$writeFile(handle: number, resource: UriComponents, base64Encoded: string, opts: FileWriteOptions): TPromise<void>;
$rename(handle: number, resource: UriComponents, target: UriComponents, opts: FileOverwriteOptions): TPromise<void>;
$copy(handle: number, resource: UriComponents, target: UriComponents, opts: FileOverwriteOptions): TPromise<void>;
$mkdir(handle: number, resource: UriComponents): TPromise<void>;
$delete(handle: number, resource: UriComponents): TPromise<void>;
$watch(handle: number, session: number, resource: UriComponents, opts: IWatchOptions): void;
$unwatch(handle: number, session: number): void;
}
export interface ExtHostSearchShape {
$provideFileSearchResults(handle: number, session: number, query: string): TPromise<void>;
$provideTextSearchResults(handle: number, session: number, pattern: IPatternInfo, options: { includes: string[], excludes: string[] }): TPromise<void>;
$provideFileSearchResults(handle: number, session: number, query: IRawSearchQuery): TPromise<ISearchCompleteStats>;
$provideTextSearchResults(handle: number, session: number, pattern: IPatternInfo, query: IRawSearchQuery): TPromise<ISearchCompleteStats>;
}
export interface ExtHostExtensionServiceShape {
@@ -671,6 +675,8 @@ export interface SymbolInformationDto extends IdObject {
containerName?: string;
kind: modes.SymbolKind;
location: LocationDto;
definingRange: IRange;
children?: SymbolInformationDto[];
}
export interface WorkspaceSymbolsDto extends IdObject {
@@ -727,7 +733,7 @@ export interface ExtHostLanguageFeaturesShape {
$provideHover(handle: number, resource: UriComponents, position: IPosition): TPromise<modes.Hover>;
$provideDocumentHighlights(handle: number, resource: UriComponents, position: IPosition): TPromise<modes.DocumentHighlight[]>;
$provideReferences(handle: number, resource: UriComponents, position: IPosition, context: modes.ReferenceContext): TPromise<LocationDto[]>;
$provideCodeActions(handle: number, resource: UriComponents, range: IRange, context: modes.CodeActionContext): TPromise<CodeActionDto[]>;
$provideCodeActions(handle: number, resource: UriComponents, rangeOrSelection: IRange | ISelection, context: modes.CodeActionContext): TPromise<CodeActionDto[]>;
$provideDocumentFormattingEdits(handle: number, resource: UriComponents, options: modes.FormattingOptions): TPromise<ISingleEditOperation[]>;
$provideDocumentRangeFormattingEdits(handle: number, resource: UriComponents, range: IRange, options: modes.FormattingOptions): TPromise<ISingleEditOperation[]>;
$provideOnTypeFormattingEdits(handle: number, resource: UriComponents, position: IPosition, ch: string, options: modes.FormattingOptions): TPromise<ISingleEditOperation[]>;
@@ -764,7 +770,7 @@ export interface ExtHostTerminalServiceShape {
$acceptTerminalClosed(id: number): void;
$acceptTerminalOpened(id: number, name: string): void;
$acceptTerminalProcessId(id: number, processId: number): void;
$acceptTerminalProcessData(id: number, data: string);
$acceptTerminalProcessData(id: number, data: string): void;
$createProcess(id: number, shellLaunchConfig: ShellLaunchConfigDto, cols: number, rows: number): void;
$acceptProcessInput(id: number, data: string): void;
$acceptProcessResize(id: number, cols: number, rows: number): void;
@@ -780,8 +786,10 @@ export interface ExtHostSCMShape {
export interface ExtHostTaskShape {
$provideTasks(handle: number): TPromise<TaskSet>;
$taskStarted(execution: TaskExecutionDTO): void;
$taskEnded(execution: TaskExecutionDTO): void;
$onDidStartTask(execution: TaskExecutionDTO): void;
$onDidStartTaskProcess(value: TaskProcessStartedDTO): void;
$onDidEndTaskProcess(value: TaskProcessEndedDTO): void;
$OnDidEndTask(execution: TaskExecutionDTO): void;
}
export interface IBreakpointDto {
@@ -828,7 +836,7 @@ export interface ISourceMultiBreakpointDto {
export interface ExtHostDebugServiceShape {
$substituteVariables(folder: UriComponents | undefined, config: IConfig): TPromise<IConfig>;
$runInTerminal(args: DebugProtocol.RunInTerminalRequestArguments, config: ITerminalSettings): TPromise<void>;
$startDASession(handle: number, debugType: string, adapterExecutableInfo: IAdapterExecutable | null): TPromise<void>;
$startDASession(handle: number, debugType: string, adapterExecutableInfo: IAdapterExecutable | null, debugPort: number): TPromise<void>;
$stopDASession(handle: number): TPromise<void>;
$sendDAMessage(handle: number, message: DebugProtocol.ProtocolMessage): TPromise<void>;
$resolveDebugConfiguration(handle: number, folder: UriComponents | undefined, debugConfiguration: IConfig): TPromise<IConfig>;
@@ -860,7 +868,7 @@ export interface ExtHostWindowShape {
}
export interface ExtHostLogServiceShape {
$setLevel(level: LogLevel);
$setLevel(level: LogLevel): void;
}
export interface ExtHostProgressShape {

View File

@@ -105,7 +105,7 @@ export class ExtHostApiCommands {
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 => value === void 0 || typeof value === 'string' }
{ name: 'triggerCharacter', description: '(optional) Trigger signature help when the user types the character, like `,` or `(`', constraint: (value: any) => value === void 0 || typeof value === 'string' }
],
returns: 'A promise that resolves to SignatureHelp.'
});
@@ -121,8 +121,8 @@ export class ExtHostApiCommands {
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 => value === void 0 || typeof value === 'string' },
{ name: 'itemResolveCount', description: '(optional) Number of completions to resolve (too large numbers slow down completions)', constraint: value => value === void 0 || typeof value === 'number' }
{ name: 'triggerCharacter', description: '(optional) Trigger completion when the user types the character, like `,` or `(`', constraint: (value: any) => value === void 0 || typeof value === 'string' },
{ name: 'itemResolveCount', description: '(optional) Number of completions to resolve (too large numbers slow down completions)', constraint: (value: any) => value === void 0 || typeof value === 'number' }
],
returns: 'A promise that resolves to a CompletionList-instance.'
});
@@ -138,7 +138,7 @@ export class ExtHostApiCommands {
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 retrun resolved lenses, will impact performance)', constraint: value => value === void 0 || typeof value === 'number' }
{ name: 'itemResolveCount', description: '(optional) Number of lenses that should be resolved and returned. Will only retrun resolved lenses, will impact performance)', constraint: (value: any) => value === void 0 || typeof value === 'number' }
],
returns: 'A promise that resolves to an array of CodeLens-instances.'
});
@@ -219,18 +219,18 @@ export class ExtHostApiCommands {
See [working with the HTML preview](https://code.visualstudio.com/docs/extensionAPI/vscode-api-commands#working-with-the-html-preview) for more information about the HTML preview's integration with the editor and for best practices for extension authors.
`,
args: [
{ name: 'uri', description: 'Uri of the resource to preview.', constraint: value => value instanceof URI || typeof value === 'string' },
{ name: 'column', description: '(optional) Column in which to preview.', constraint: value => typeof value === 'undefined' || (typeof value === 'number' && typeof types.ViewColumn[value] === 'string') },
{ name: 'label', description: '(optional) An human readable string that is used as title for the preview.', constraint: v => typeof v === 'string' || typeof v === 'undefined' },
{ name: 'options', description: '(optional) Options for controlling webview environment.', constraint: v => typeof v === 'object' || typeof v === 'undefined' }
{ name: 'uri', description: 'Uri of the resource to preview.', constraint: (value: any) => value instanceof URI || typeof value === 'string' },
{ name: 'column', description: '(optional) Column in which to preview.', constraint: (value: any) => typeof value === 'undefined' || (typeof value === 'number' && typeof types.ViewColumn[value] === 'string') },
{ name: 'label', description: '(optional) An human readable string that is used as title for the preview.', constraint: (v: any) => typeof v === 'string' || typeof v === 'undefined' },
{ name: 'options', description: '(optional) Options for controlling webview environment.', constraint: (v: any) => typeof v === 'object' || typeof v === 'undefined' }
]
});
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 => value === void 0 || value instanceof URI },
{ name: 'newWindow', description: '(optional) Whether to open the folder/workspace in a new window or the same. Defaults to opening in the same window.', constraint: value => value === void 0 || typeof value === 'boolean' }
{ 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 === void 0 || value instanceof URI },
{ name: 'newWindow', description: '(optional) Whether to open the folder/workspace in a new window or the same. Defaults to opening in the same window.', constraint: (value: any) => value === void 0 || typeof value === 'boolean' }
]
});
@@ -239,7 +239,7 @@ export class ExtHostApiCommands {
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 => v === void 0 || typeof v === 'string' },
{ name: 'title', description: '(optional) Human readable title for the diff editor', constraint: (v: any) => v === void 0 || typeof v === 'string' },
{ name: 'options', description: '(optional) Editor options, see vscode.TextDocumentShowOptions' }
]
});
@@ -248,14 +248,14 @@ export class ExtHostApiCommands {
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 => v === void 0 || typeof v === 'number' || typeof v === 'object' }
{ name: 'columnOrOptions', description: '(optional) Either the column in which to open or editor options, see vscode.TextDocumentShowOptions', constraint: (v: any) => v === void 0 || 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 => typeof value === 'string' }
{ name: 'path', description: 'Path to remove from recently opened.', constraint: (value: any) => typeof value === 'string' }
]
});
}
@@ -278,7 +278,7 @@ export class ExtHostApiCommands {
const result: types.SymbolInformation[] = [];
if (Array.isArray(value)) {
for (let tuple of value) {
result.push(...tuple[1].map(typeConverters.toSymbolInformation));
result.push(...tuple[1].map(typeConverters.SymbolInformation.to));
}
}
return result;
@@ -288,7 +288,7 @@ export class ExtHostApiCommands {
private _executeDefinitionProvider(resource: URI, position: types.Position): Thenable<types.Location[]> {
const args = {
resource,
position: position && typeConverters.fromPosition(position)
position: position && typeConverters.Position.from(position)
};
return this._commands.executeCommand<modes.Location[]>('_executeDefinitionProvider', args)
.then(tryMapWith(typeConverters.location.to));
@@ -297,7 +297,7 @@ export class ExtHostApiCommands {
private _executeTypeDefinitionProvider(resource: URI, position: types.Position): Thenable<types.Location[]> {
const args = {
resource,
position: position && typeConverters.fromPosition(position)
position: position && typeConverters.Position.from(position)
};
return this._commands.executeCommand<modes.Location[]>('_executeTypeDefinitionProvider', args)
.then(tryMapWith(typeConverters.location.to));
@@ -306,7 +306,7 @@ export class ExtHostApiCommands {
private _executeImplementationProvider(resource: URI, position: types.Position): Thenable<types.Location[]> {
const args = {
resource,
position: position && typeConverters.fromPosition(position)
position: position && typeConverters.Position.from(position)
};
return this._commands.executeCommand<modes.Location[]>('_executeImplementationProvider', args)
.then(tryMapWith(typeConverters.location.to));
@@ -315,25 +315,25 @@ export class ExtHostApiCommands {
private _executeHoverProvider(resource: URI, position: types.Position): Thenable<types.Hover[]> {
const args = {
resource,
position: position && typeConverters.fromPosition(position)
position: position && typeConverters.Position.from(position)
};
return this._commands.executeCommand<modes.Hover[]>('_executeHoverProvider', args)
.then(tryMapWith(typeConverters.toHover));
.then(tryMapWith(typeConverters.Hover.to));
}
private _executeDocumentHighlights(resource: URI, position: types.Position): Thenable<types.DocumentHighlight[]> {
const args = {
resource,
position: position && typeConverters.fromPosition(position)
position: position && typeConverters.Position.from(position)
};
return this._commands.executeCommand<modes.DocumentHighlight[]>('_executeDocumentHighlights', args)
.then(tryMapWith(typeConverters.toDocumentHighlight));
.then(tryMapWith(typeConverters.DocumentHighlight.to));
}
private _executeReferenceProvider(resource: URI, position: types.Position): Thenable<types.Location[]> {
const args = {
resource,
position: position && typeConverters.fromPosition(position)
position: position && typeConverters.Position.from(position)
};
return this._commands.executeCommand<modes.Location[]>('_executeReferenceProvider', args)
.then(tryMapWith(typeConverters.location.to));
@@ -342,7 +342,7 @@ export class ExtHostApiCommands {
private _executeDocumentRenameProvider(resource: URI, position: types.Position, newName: string): Thenable<types.WorkspaceEdit> {
const args = {
resource,
position: position && typeConverters.fromPosition(position),
position: position && typeConverters.Position.from(position),
newName
};
return this._commands.executeCommand<modes.WorkspaceEdit>('_executeDocumentRenameProvider', args).then(value => {
@@ -359,7 +359,7 @@ export class ExtHostApiCommands {
private _executeSignatureHelpProvider(resource: URI, position: types.Position, triggerCharacter: string): Thenable<types.SignatureHelp> {
const args = {
resource,
position: position && typeConverters.fromPosition(position),
position: position && typeConverters.Position.from(position),
triggerCharacter
};
return this._commands.executeCommand<modes.SignatureHelp>('_executeSignatureHelpProvider', args).then(value => {
@@ -373,7 +373,7 @@ export class ExtHostApiCommands {
private _executeCompletionItemProvider(resource: URI, position: types.Position, triggerCharacter: string, maxItemsToResolve: number): Thenable<types.CompletionList> {
const args = {
resource,
position: position && typeConverters.fromPosition(position),
position: position && typeConverters.Position.from(position),
triggerCharacter,
maxItemsToResolve
};
@@ -392,7 +392,7 @@ export class ExtHostApiCommands {
};
return this._commands.executeCommand<IRawColorInfo[]>('_executeDocumentColorProvider', args).then(result => {
if (result) {
return result.map(ci => ({ range: typeConverters.toRange(ci.range), color: typeConverters.Color.to(ci.color) }));
return result.map(ci => ({ range: typeConverters.Range.to(ci.range), color: typeConverters.Color.to(ci.color) }));
}
return [];
});
@@ -402,7 +402,7 @@ export class ExtHostApiCommands {
const args = {
resource: context.uri,
color: typeConverters.Color.from(color),
range: typeConverters.fromRange(context.range),
range: typeConverters.Range.from(context.range),
};
return this._commands.executeCommand<modes.IColorPresentation[]>('_executeColorPresentationProvider', args).then(result => {
if (result) {
@@ -418,7 +418,7 @@ export class ExtHostApiCommands {
};
return this._commands.executeCommand<modes.IOutline>('_executeDocumentSymbolProvider', args).then(value => {
if (value && Array.isArray(value.entries)) {
return value.entries.map(typeConverters.toSymbolInformation);
return value.entries.map(typeConverters.SymbolInformation.to);
}
return undefined;
});
@@ -427,7 +427,7 @@ export class ExtHostApiCommands {
private _executeCodeActionProvider(resource: URI, range: types.Range): Thenable<(vscode.CodeAction | vscode.Command)[]> {
const args = {
resource,
range: typeConverters.fromRange(range)
range: typeConverters.Range.from(range)
};
return this._commands.executeCommand<CustomCodeAction[]>('_executeCodeActionProvider', args)
.then(tryMapWith(codeAction => {
@@ -454,7 +454,7 @@ export class ExtHostApiCommands {
return this._commands.executeCommand<modes.ICodeLensSymbol[]>('_executeCodeLensProvider', args)
.then(tryMapWith(item => {
return new types.CodeLens(
typeConverters.toRange(item.range),
typeConverters.Range.to(item.range),
this._commands.converter.fromInternal(item.command));
}));
@@ -466,28 +466,28 @@ export class ExtHostApiCommands {
options
};
return this._commands.executeCommand<ISingleEditOperation[]>('_executeFormatDocumentProvider', args)
.then(tryMapWith(edit => new types.TextEdit(typeConverters.toRange(edit.range), edit.text)));
.then(tryMapWith(edit => new types.TextEdit(typeConverters.Range.to(edit.range), edit.text)));
}
private _executeFormatRangeProvider(resource: URI, range: types.Range, options: vscode.FormattingOptions): Thenable<vscode.TextEdit[]> {
const args = {
resource,
range: typeConverters.fromRange(range),
range: typeConverters.Range.from(range),
options
};
return this._commands.executeCommand<ISingleEditOperation[]>('_executeFormatRangeProvider', args)
.then(tryMapWith(edit => new types.TextEdit(typeConverters.toRange(edit.range), edit.text)));
.then(tryMapWith(edit => new types.TextEdit(typeConverters.Range.to(edit.range), edit.text)));
}
private _executeFormatOnTypeProvider(resource: URI, position: types.Position, ch: string, options: vscode.FormattingOptions): Thenable<vscode.TextEdit[]> {
const args = {
resource,
position: typeConverters.fromPosition(position),
position: typeConverters.Position.from(position),
ch,
options
};
return this._commands.executeCommand<ISingleEditOperation[]>('_executeFormatOnTypeProvider', args)
.then(tryMapWith(edit => new types.TextEdit(typeConverters.toRange(edit.range), edit.text)));
.then(tryMapWith(edit => new types.TextEdit(typeConverters.Range.to(edit.range), edit.text)));
}
private _executeDocumentLinkProvider(resource: URI): Thenable<vscode.DocumentLink[]> {

View File

@@ -92,10 +92,10 @@ export class ExtHostCommands implements ExtHostCommandsShape {
args = cloneAndChange(args, function (value) {
if (value instanceof extHostTypes.Position) {
return extHostTypeConverter.fromPosition(value);
return extHostTypeConverter.Position.from(value);
}
if (value instanceof extHostTypes.Range) {
return extHostTypeConverter.fromRange(value);
return extHostTypeConverter.Range.from(value);
}
if (value instanceof extHostTypes.Location) {
return extHostTypeConverter.location.from(value);

View File

@@ -121,17 +121,17 @@ export class ExtHostConfiguration implements ExtHostConfigurationShape {
}
return result;
},
set: (target: any, property: string, value: any) => {
set: (_target: any, property: string, value: any) => {
cloneTarget();
clonedTarget[property] = value;
return true;
},
deleteProperty: (target: any, property: string) => {
deleteProperty: (_target: any, property: string) => {
cloneTarget();
delete clonedTarget[property];
return true;
},
defineProperty: (target: any, property: string, descriptor: any) => {
defineProperty: (_target: any, property: string, descriptor: any) => {
cloneTarget();
Object.defineProperty(clonedTarget, property, descriptor);
return true;
@@ -179,10 +179,10 @@ export class ExtHostConfiguration implements ExtHostConfigurationShape {
return isObject(target) ?
new Proxy(target, {
get: (target: any, property: string) => readonlyProxy(target[property]),
set: (target: any, property: string, value: any) => { throw new Error(`TypeError: Cannot assign to read only property '${property}' of object`); },
deleteProperty: (target: any, property: string) => { throw new Error(`TypeError: Cannot delete read only property '${property}' of object`); },
defineProperty: (target: any, property: string) => { throw new Error(`TypeError: Cannot define property '${property}' for a readonly object`); },
setPrototypeOf: (target: any) => { throw new Error(`TypeError: Cannot set prototype for a readonly object`); },
set: (_target: any, property: string, _value: any) => { throw new Error(`TypeError: Cannot assign to read only property '${property}' of object`); },
deleteProperty: (_target: any, property: string) => { throw new Error(`TypeError: Cannot delete read only property '${property}' of object`); },
defineProperty: (_target: any, property: string) => { throw new Error(`TypeError: Cannot define property '${property}' for a readonly object`); },
setPrototypeOf: (_target: any) => { throw new Error(`TypeError: Cannot set prototype for a readonly object`); },
isExtensible: () => false,
preventExtensions: () => true
}) : target;

View File

@@ -17,17 +17,18 @@ import {
import * as vscode from 'vscode';
import { Disposable, Position, Location, SourceBreakpoint, FunctionBreakpoint } from 'vs/workbench/api/node/extHostTypes';
import { generateUuid } from 'vs/base/common/uuid';
import { DebugAdapter, convertToVSCPaths, convertToDAPaths } from 'vs/workbench/parts/debug/node/debugAdapter';
import { DebugAdapter, StreamDebugAdapter, SocketDebugAdapter } from 'vs/workbench/parts/debug/node/debugAdapter';
import { ExtHostWorkspace } from 'vs/workbench/api/node/extHostWorkspace';
import { ExtHostExtensionService } from 'vs/workbench/api/node/extHostExtensionService';
import { ExtHostDocumentsAndEditors } from 'vs/workbench/api/node/extHostDocumentsAndEditors';
import { IAdapterExecutable, ITerminalSettings, IDebuggerContribution, IConfig } from 'vs/workbench/parts/debug/common/debug';
import { IAdapterExecutable, ITerminalSettings, IDebuggerContribution, IConfig, IDebugAdapter } from 'vs/workbench/parts/debug/common/debug';
import { getTerminalLauncher } from 'vs/workbench/parts/debug/node/terminals';
import { IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import { VariableResolver } from 'vs/workbench/services/configurationResolver/node/variableResolver';
import { IConfigurationResolverService } from '../../services/configurationResolver/common/configurationResolver';
import { IStringDictionary } from 'vs/base/common/collections';
import { ExtHostConfiguration } from './extHostConfiguration';
import { convertToVSCPaths, convertToDAPaths } from 'vs/workbench/parts/debug/common/debugUtils';
import { IConfigurationResolverService } from 'vs/workbench/services/configurationResolver/common/configurationResolver';
export class ExtHostDebugService implements ExtHostDebugServiceShape {
@@ -61,7 +62,7 @@ export class ExtHostDebugService implements ExtHostDebugServiceShape {
private readonly _onDidChangeBreakpoints: Emitter<vscode.BreakpointsChangeEvent>;
private _debugAdapters: Map<number, DebugAdapter>;
private _debugAdapters: Map<number, IDebugAdapter>;
private _variableResolver: IConfigurationResolverService;
@@ -132,22 +133,41 @@ export class ExtHostDebugService implements ExtHostDebugServiceShape {
return asWinJsPromise(token => DebugAdapter.substituteVariables(folder, config, this._variableResolver));
}
public $startDASession(handle: number, debugType: string, adpaterExecutable: IAdapterExecutable | null): TPromise<void> {
public $startDASession(handle: number, debugType: string, adpaterExecutable: IAdapterExecutable | null, debugPort: number): TPromise<void> {
const mythis = this;
const da = new class extends DebugAdapter {
let da: StreamDebugAdapter = null;
// DA -> VS Code
public acceptMessage(message: DebugProtocol.ProtocolMessage) {
convertToVSCPaths(message, source => {
if (paths.isAbsolute(source.path)) {
(<any>source).path = URI.file(source.path);
}
});
mythis._debugServiceProxy.$acceptDAMessage(handle, message);
}
if (debugPort > 0) {
da = new class extends SocketDebugAdapter {
}(debugType, adpaterExecutable, this._extensionService.getAllExtensionDescriptions());
// DA -> VS Code
public acceptMessage(message: DebugProtocol.ProtocolMessage) {
convertToVSCPaths(message, source => {
if (paths.isAbsolute(source.path)) {
(<any>source).path = URI.file(source.path);
}
});
mythis._debugServiceProxy.$acceptDAMessage(handle, message);
}
}(debugPort);
} else {
da = new class extends DebugAdapter {
// DA -> VS Code
public acceptMessage(message: DebugProtocol.ProtocolMessage) {
convertToVSCPaths(message, source => {
if (paths.isAbsolute(source.path)) {
(<any>source).path = URI.file(source.path);
}
});
mythis._debugServiceProxy.$acceptDAMessage(handle, message);
}
}(debugType, adpaterExecutable, this._extensionService.getAllExtensionDescriptions());
}
this._debugAdapters.set(handle, da);
da.onError(err => this._debugServiceProxy.$acceptDAError(handle, err.name, err.message, err.stack));
@@ -591,4 +611,4 @@ export class ExtHostVariableResolverService implements IConfigurationResolverSer
public executeCommandVariables(configuration: any, variables: IStringDictionary<string>): TPromise<IStringDictionary<string>> {
throw new Error('findAndExecuteCommandVariables not implemented.');
}
}
}

View File

@@ -116,7 +116,7 @@ export class DiagnosticCollection implements vscode.DiagnosticCollection {
orderLoop: for (let i = 0; i < 4; i++) {
for (let diagnostic of diagnostics) {
if (diagnostic.severity === order[i]) {
const len = marker.push(converter.fromDiagnostic(diagnostic));
const len = marker.push(converter.Diagnostic.from(diagnostic));
if (len === DiagnosticCollection._maxDiagnosticsPerFile) {
break orderLoop;
}
@@ -134,7 +134,7 @@ export class DiagnosticCollection implements vscode.DiagnosticCollection {
endColumn: marker[marker.length - 1].endColumn
});
} else {
marker = diagnostics.map(converter.fromDiagnostic);
marker = diagnostics.map(converter.Diagnostic.from);
}
}
@@ -147,6 +147,7 @@ export class DiagnosticCollection implements vscode.DiagnosticCollection {
delete(uri: vscode.Uri): void {
this._checkDisposed();
this._onDidChangeDiagnostics.fire([uri]);
this._data.delete(uri.toString());
this._proxy.$changeMany(this.name, [[uri, undefined]]);
}

View File

@@ -13,6 +13,7 @@ import * as vscode from 'vscode';
import { getWordAtText, ensureValidWordDefinition } from 'vs/editor/common/model/wordHelper';
import { MainThreadDocumentsShape } from './extHost.protocol';
import { TPromise } from 'vs/base/common/winjs.base';
import { Schemas } from 'vs/base/common/network';
const _modeId2WordDefinition = new Map<string, RegExp>();
export function setWordDefinitionFor(modeId: string, wordDefinition: RegExp): void {
@@ -68,8 +69,7 @@ export class ExtHostDocumentData extends MirrorTextModel {
this._document = {
get uri() { return data._uri; },
get fileName() { return data._uri.fsPath; },
// todo@remote -> https://github.com/Microsoft/vscode/issues/48269
get isUntitled() { return data._uri.scheme !== 'file'; },
get isUntitled() { return data._uri.scheme === Schemas.untitled; },
get languageId() { return data._languageId; },
get version() { return data._versionId; },
get isClosed() { return data._isDisposed; },

View File

@@ -10,7 +10,7 @@ import { sequence, always } from 'vs/base/common/async';
import { illegalState } from 'vs/base/common/errors';
import { ExtHostDocumentSaveParticipantShape, MainThreadTextEditorsShape, ResourceTextEditDto } from 'vs/workbench/api/node/extHost.protocol';
import { TextEdit } from 'vs/workbench/api/node/extHostTypes';
import { fromRange, TextDocumentSaveReason, EndOfLine } from 'vs/workbench/api/node/extHostTypeConverters';
import { Range, TextDocumentSaveReason, EndOfLine } from 'vs/workbench/api/node/extHostTypeConverters';
import { ExtHostDocuments } from 'vs/workbench/api/node/extHostDocuments';
import { SaveReason } from 'vs/workbench/services/textfile/common/textfiles';
import * as vscode from 'vscode';
@@ -151,7 +151,7 @@ export class ExtHostDocumentSaveParticipant implements ExtHostDocumentSavePartic
if (Array.isArray(value) && (<vscode.TextEdit[]>value).every(e => e instanceof TextEdit)) {
for (const { newText, newEol, range } of value) {
resourceEdit.edits.push({
range: range && fromRange(range),
range: range && Range.from(range),
text: newText,
eol: EndOfLine.from(newEol)
});

View File

@@ -136,7 +136,7 @@ export class ExtHostDocuments implements ExtHostDocumentsShape {
document: data.document,
contentChanges: events.changes.map((change) => {
return {
range: TypeConverters.toRange(change.range),
range: TypeConverters.Range.to(change.range),
rangeOffset: change.rangeOffset,
rangeLength: change.rangeLength,
text: change.text

View File

@@ -95,10 +95,10 @@ export class ExtHostDocumentsAndEditors implements ExtHostDocumentsAndEditorsSha
this._mainContext.getProxy(MainContext.MainThreadTextEditors),
data.id,
documentData,
data.selections.map(typeConverters.toSelection),
data.selections.map(typeConverters.Selection.to),
data.options,
data.visibleRanges.map(typeConverters.toRange),
typeConverters.toViewColumn(data.editorPosition)
data.visibleRanges.map(typeConverters.Range.to),
typeConverters.ViewColumn.to(data.editorPosition)
);
this._editors.set(data.id, editor);
}

View File

@@ -243,8 +243,7 @@ export class ExtHostExtensionService implements ExtHostExtensionServiceShape {
if (!ext.main) {
return undefined;
}
return realpath(ext.extensionFolderPath).then(value => tree.set(value, ext));
return realpath(ext.extensionLocation.fsPath).then(value => tree.set(value, ext));
});
this._extensionPathIndex = TPromise.join(extensions).then(() => tree);
}
@@ -359,9 +358,9 @@ export class ExtHostExtensionService implements ExtHostExtensionServiceShape {
globalState,
workspaceState,
subscriptions: [],
get extensionPath() { return extensionDescription.extensionFolderPath; },
get extensionPath() { return extensionDescription.extensionLocation.fsPath; },
storagePath: this._storagePath.value(extensionDescription),
asAbsolutePath: (relativePath: string) => { return join(extensionDescription.extensionFolderPath, relativePath); },
asAbsolutePath: (relativePath: string) => { return join(extensionDescription.extensionLocation.fsPath, relativePath); },
get logger() {
checkProposedApiEnabled(extensionDescription);
return that._extHostLogService.getExtLogger(extensionDescription.id);

View File

@@ -49,6 +49,9 @@ class FsLinkProvider implements vscode.DocumentLinkProvider {
let m: RegExpMatchArray;
while (m = this._regex.exec(textLine.text)) {
const target = URI.parse(m[0]);
if (target.path[0] !== '/') {
continue;
}
const range = new Range(line, this._regex.lastIndex - m[0].length, line, this._regex.lastIndex);
result.push({ target, range });
}
@@ -78,34 +81,32 @@ class FileSystemProviderShim implements vscode.FileSystemProvider {
stat(resource: vscode.Uri): Thenable<vscode.FileStat> {
return this._delegate.stat(resource).then(stat => FileSystemProviderShim._modernizeFileStat(stat));
}
rename(oldUri: vscode.Uri, newUri: vscode.Uri): Thenable<vscode.FileStat> {
return this._delegate.move(oldUri, newUri).then(stat => FileSystemProviderShim._modernizeFileStat(stat));
rename(oldUri: vscode.Uri, newUri: vscode.Uri): Thenable<void> {
return this._delegate.move(oldUri, newUri).then(stat => void 0);
}
readDirectory(resource: vscode.Uri): Thenable<[string, vscode.FileStat][]> {
readDirectory(resource: vscode.Uri): Thenable<[string, vscode.FileType][]> {
return this._delegate.readdir(resource).then(tuples => {
return tuples.map(tuple => <[string, vscode.FileStat]>[path.posix.basename(tuple[0].path), FileSystemProviderShim._modernizeFileStat(tuple[1])]);
return tuples.map(tuple => <[string, vscode.FileType]>[path.posix.basename(tuple[0].path), FileSystemProviderShim._modernizeFileStat(tuple[1]).type]);
});
}
private static _modernizeFileStat(stat: vscode.DeprecatedFileStat): vscode.FileStat {
let { mtime, size, type } = stat;
let isFile = false;
let isDirectory = false;
let isSymbolicLink = false;
let newType: files.FileType;
// no support for bitmask, effectively no support for symlinks
switch (type) {
case DeprecatedFileType.Dir:
isDirectory = true;
newType = files.FileType.Directory;
break;
case DeprecatedFileType.File:
isFile = true;
newType = files.FileType.File;
break;
case DeprecatedFileType.Symlink:
isSymbolicLink = true;
newType = files.FileType.File & files.FileType.SymbolicLink;
break;
}
return { mtime, size, isFile, isDirectory, isSymbolicLink };
return { type: newType, ctime: 0, mtime, size };
}
private static _modernizeFileChange(e: vscode.DeprecatedFileChange): vscode.FileChangeEvent {
@@ -137,8 +138,8 @@ class FileSystemProviderShim implements vscode.FileSystemProvider {
}
});
}
createDirectory(resource: vscode.Uri): Thenable<vscode.FileStat> {
return this._delegate.mkdir(resource).then(stat => FileSystemProviderShim._modernizeFileStat(stat));
createDirectory(resource: vscode.Uri): Thenable<void> {
return this._delegate.mkdir(resource).then(stat => void 0);
}
// --- read/write
@@ -154,7 +155,7 @@ class FileSystemProviderShim implements vscode.FileSystemProvider {
});
}
writeFile(resource: vscode.Uri, content: Uint8Array, options: files.FileOptions): Thenable<void> {
writeFile(resource: vscode.Uri, content: Uint8Array, options: files.FileWriteOptions): Thenable<void> {
return this._delegate.write(resource, content);
}
}
@@ -245,40 +246,45 @@ export class ExtHostFileSystem implements ExtHostFileSystemShape {
};
}
private static _asIStat(stat: vscode.FileStat): files.IStat {
const { type, ctime, mtime, size } = stat;
return { type, ctime, mtime, size };
}
$stat(handle: number, resource: UriComponents): TPromise<files.IStat, any> {
return asWinJsPromise(token => this._fsProvider.get(handle).stat(URI.revive(resource), {}, token));
return asWinJsPromise(token => this._fsProvider.get(handle).stat(URI.revive(resource))).then(ExtHostFileSystem._asIStat);
}
$readdir(handle: number, resource: UriComponents): TPromise<[string, files.IStat][], any> {
return asWinJsPromise(token => this._fsProvider.get(handle).readDirectory(URI.revive(resource), {}, token));
$readdir(handle: number, resource: UriComponents): TPromise<[string, files.FileType][], any> {
return asWinJsPromise(token => this._fsProvider.get(handle).readDirectory(URI.revive(resource)));
}
$readFile(handle: number, resource: UriComponents, opts: files.FileOptions): TPromise<string> {
$readFile(handle: number, resource: UriComponents): TPromise<string> {
return asWinJsPromise(token => {
return this._fsProvider.get(handle).readFile(URI.revive(resource), opts, token);
return this._fsProvider.get(handle).readFile(URI.revive(resource));
}).then(data => {
return Buffer.isBuffer(data) ? data.toString('base64') : Buffer.from(data.buffer, data.byteOffset, data.byteLength).toString('base64');
});
}
$writeFile(handle: number, resource: UriComponents, base64Content: string, opts: files.FileOptions): TPromise<void, any> {
return asWinJsPromise(token => this._fsProvider.get(handle).writeFile(URI.revive(resource), Buffer.from(base64Content, 'base64'), opts, token));
$writeFile(handle: number, resource: UriComponents, base64Content: string, opts: files.FileWriteOptions): TPromise<void, any> {
return asWinJsPromise(token => this._fsProvider.get(handle).writeFile(URI.revive(resource), Buffer.from(base64Content, 'base64'), opts));
}
$delete(handle: number, resource: UriComponents): TPromise<void, any> {
return asWinJsPromise(token => this._fsProvider.get(handle).delete(URI.revive(resource), {}, token));
return asWinJsPromise(token => this._fsProvider.get(handle).delete(URI.revive(resource), { recursive: true }));
}
$rename(handle: number, oldUri: UriComponents, newUri: UriComponents, opts: files.FileOptions): TPromise<files.IStat, any> {
return asWinJsPromise(token => this._fsProvider.get(handle).rename(URI.revive(oldUri), URI.revive(newUri), opts, token));
$rename(handle: number, oldUri: UriComponents, newUri: UriComponents, opts: files.FileOverwriteOptions): TPromise<void, any> {
return asWinJsPromise(token => this._fsProvider.get(handle).rename(URI.revive(oldUri), URI.revive(newUri), opts));
}
$copy(handle: number, oldUri: UriComponents, newUri: UriComponents, opts: files.FileOptions): TPromise<files.IStat, any> {
return asWinJsPromise(token => this._fsProvider.get(handle).copy(URI.revive(oldUri), URI.revive(newUri), opts, token));
$copy(handle: number, oldUri: UriComponents, newUri: UriComponents, opts: files.FileOverwriteOptions): TPromise<void, any> {
return asWinJsPromise(token => this._fsProvider.get(handle).copy(URI.revive(oldUri), URI.revive(newUri), opts));
}
$mkdir(handle: number, resource: UriComponents): TPromise<files.IStat, any> {
return asWinJsPromise(token => this._fsProvider.get(handle).createDirectory(URI.revive(resource), {}, token));
$mkdir(handle: number, resource: UriComponents): TPromise<void, any> {
return asWinJsPromise(token => this._fsProvider.get(handle).createDirectory(URI.revive(resource)));
}
$watch(handle: number, session: number, resource: UriComponents, opts: files.IWatchOptions): void {

View File

@@ -8,8 +8,8 @@ import URI, { UriComponents } from 'vs/base/common/uri';
import { TPromise } from 'vs/base/common/winjs.base';
import { mixin } from 'vs/base/common/objects';
import * as vscode from 'vscode';
import * as TypeConverters from 'vs/workbench/api/node/extHostTypeConverters';
import { Range, Disposable, CompletionList, SnippetString, CodeActionKind, HierarchicalSymbolInformation } from 'vs/workbench/api/node/extHostTypes';
import * as typeConvert from 'vs/workbench/api/node/extHostTypeConverters';
import { Range, Disposable, CompletionList, SnippetString, CodeActionKind, SymbolInformation, Hierarchy, SymbolInformation2 } from 'vs/workbench/api/node/extHostTypes';
import { ISingleEditOperation } from 'vs/editor/common/model';
import * as modes from 'vs/editor/common/modes';
import { ExtHostHeapService } from 'vs/workbench/api/node/extHostHeapService';
@@ -23,6 +23,7 @@ import { IPosition } from 'vs/editor/common/core/position';
import { IRange } from 'vs/editor/common/core/range';
import { isFalsyOrEmpty } from 'vs/base/common/arrays';
import { isObject } from 'vs/base/common/types';
import { ISelection, Selection } from 'vs/editor/common/core/selection';
// --- adapter
@@ -39,15 +40,48 @@ class OutlineAdapter {
provideDocumentSymbols(resource: URI): TPromise<SymbolInformationDto[]> {
let doc = this._documents.getDocumentData(resource).document;
return asWinJsPromise(token => this._provider.provideDocumentSymbols(doc, token)).then(value => {
if (value instanceof HierarchicalSymbolInformation) {
value = HierarchicalSymbolInformation.toFlatSymbolInformation(value);
if (isFalsyOrEmpty(value)) {
return undefined;
}
if (Array.isArray(value)) {
return value.map(symbol => IdObject.mixin(TypeConverters.fromSymbolInformation(symbol)));
let [probe] = value;
if (!(probe instanceof Hierarchy)) {
value = OutlineAdapter._asSymbolHierarchy(<SymbolInformation[]>value);
}
return undefined;
return (<Hierarchy<SymbolInformation2>[]>value).map(typeConvert.HierarchicalSymbolInformation.from);
});
}
private static _asSymbolHierarchy(info: SymbolInformation[]): vscode.Hierarchy<SymbolInformation2>[] {
// first sort by start (and end) and then loop over all elements
// and build a tree based on containment.
info = info.slice(0).sort((a, b) => {
let res = a.location.range.start.compareTo(b.location.range.start);
if (res === 0) {
res = b.location.range.end.compareTo(a.location.range.end);
}
return res;
});
let res: Hierarchy<SymbolInformation2>[] = [];
let parentStack: Hierarchy<SymbolInformation2>[] = [];
for (let i = 0; i < info.length; i++) {
let element = new Hierarchy(new SymbolInformation2(info[i].name, '', info[i].kind, info[i].location.range, info[i].location));
while (true) {
if (parentStack.length === 0) {
parentStack.push(element);
res.push(element);
break;
}
let parent = parentStack[parentStack.length - 1];
if (parent.parent.range.contains(element.parent.range)) {
parent.children.push(element);
parentStack.push(element);
break;
}
parentStack.pop();
}
}
return res;
}
}
class CodeLensAdapter {
@@ -74,7 +108,7 @@ class CodeLensAdapter {
return lenses.map(lens => {
const id = this._heapService.keep(lens);
return ObjectIdentifier.mixin({
range: TypeConverters.fromRange(lens.range),
range: typeConvert.Range.from(lens.range),
command: this._commands.toInternal(lens.command)
}, id);
});
@@ -116,12 +150,12 @@ class DefinitionAdapter {
provideDefinition(resource: URI, position: IPosition): TPromise<modes.Definition> {
let doc = this._documents.getDocumentData(resource).document;
let pos = TypeConverters.toPosition(position);
let pos = typeConvert.Position.to(position);
return asWinJsPromise(token => this._provider.provideDefinition(doc, pos, token)).then(value => {
if (Array.isArray(value)) {
return value.map(TypeConverters.location.from);
return value.map(typeConvert.location.from);
} else if (value) {
return TypeConverters.location.from(value);
return typeConvert.location.from(value);
}
return undefined;
});
@@ -139,12 +173,12 @@ class ImplementationAdapter {
provideImplementation(resource: URI, position: IPosition): TPromise<modes.Definition> {
let doc = this._documents.getDocumentData(resource).document;
let pos = TypeConverters.toPosition(position);
let pos = typeConvert.Position.to(position);
return asWinJsPromise(token => this._provider.provideImplementation(doc, pos, token)).then(value => {
if (Array.isArray(value)) {
return value.map(TypeConverters.location.from);
return value.map(typeConvert.location.from);
} else if (value) {
return TypeConverters.location.from(value);
return typeConvert.location.from(value);
}
return undefined;
});
@@ -162,12 +196,12 @@ class TypeDefinitionAdapter {
provideTypeDefinition(resource: URI, position: IPosition): TPromise<modes.Definition> {
const doc = this._documents.getDocumentData(resource).document;
const pos = TypeConverters.toPosition(position);
const pos = typeConvert.Position.to(position);
return asWinJsPromise(token => this._provider.provideTypeDefinition(doc, pos, token)).then(value => {
if (Array.isArray(value)) {
return value.map(TypeConverters.location.from);
return value.map(typeConvert.location.from);
} else if (value) {
return TypeConverters.location.from(value);
return typeConvert.location.from(value);
}
return undefined;
});
@@ -187,7 +221,7 @@ class HoverAdapter {
public provideHover(resource: URI, position: IPosition): TPromise<modes.Hover> {
let doc = this._documents.getDocumentData(resource).document;
let pos = TypeConverters.toPosition(position);
let pos = typeConvert.Position.to(position);
return asWinJsPromise(token => this._provider.provideHover(doc, pos, token)).then(value => {
if (!value || isFalsyOrEmpty(value.contents)) {
@@ -200,7 +234,7 @@ class HoverAdapter {
value.range = new Range(pos, pos);
}
return TypeConverters.fromHover(value);
return typeConvert.Hover.from(value);
});
}
}
@@ -218,22 +252,15 @@ class DocumentHighlightAdapter {
provideDocumentHighlights(resource: URI, position: IPosition): TPromise<modes.DocumentHighlight[]> {
let doc = this._documents.getDocumentData(resource).document;
let pos = TypeConverters.toPosition(position);
let pos = typeConvert.Position.to(position);
return asWinJsPromise(token => this._provider.provideDocumentHighlights(doc, pos, token)).then(value => {
if (Array.isArray(value)) {
return value.map(DocumentHighlightAdapter._convertDocumentHighlight);
return value.map(typeConvert.DocumentHighlight.from);
}
return undefined;
});
}
private static _convertDocumentHighlight(documentHighlight: vscode.DocumentHighlight): modes.DocumentHighlight {
return {
range: TypeConverters.fromRange(documentHighlight.range),
kind: documentHighlight.kind
};
}
}
class ReferenceAdapter {
@@ -248,11 +275,11 @@ class ReferenceAdapter {
provideReferences(resource: URI, position: IPosition, context: modes.ReferenceContext): TPromise<modes.Location[]> {
let doc = this._documents.getDocumentData(resource).document;
let pos = TypeConverters.toPosition(position);
let pos = typeConvert.Position.to(position);
return asWinJsPromise(token => this._provider.provideReferences(doc, pos, context, token)).then(value => {
if (Array.isArray(value)) {
return value.map(TypeConverters.location.from);
return value.map(typeConvert.location.from);
}
return undefined;
});
@@ -265,27 +292,23 @@ export interface CustomCodeAction extends CodeActionDto {
class CodeActionAdapter {
private _documents: ExtHostDocuments;
private _commands: CommandsConverter;
private _diagnostics: ExtHostDiagnostics;
private _provider: vscode.CodeActionProvider;
constructor(
private readonly _documents: ExtHostDocuments,
private readonly _commands: CommandsConverter,
private readonly _diagnostics: ExtHostDiagnostics,
private readonly _provider: vscode.CodeActionProvider
) { }
constructor(documents: ExtHostDocuments, commands: CommandsConverter, diagnostics: ExtHostDiagnostics, provider: vscode.CodeActionProvider) {
this._documents = documents;
this._commands = commands;
this._diagnostics = diagnostics;
this._provider = provider;
}
provideCodeActions(resource: URI, range: IRange, context: modes.CodeActionContext): TPromise<CodeActionDto[]> {
provideCodeActions(resource: URI, rangeOrSelection: IRange | ISelection, context: modes.CodeActionContext): TPromise<CodeActionDto[]> {
const doc = this._documents.getDocumentData(resource).document;
const ran = <vscode.Range>TypeConverters.toRange(range);
const ran = Selection.isISelection(rangeOrSelection)
? <vscode.Selection>typeConvert.Selection.to(rangeOrSelection)
: <vscode.Range>typeConvert.Range.to(rangeOrSelection);
const allDiagnostics: vscode.Diagnostic[] = [];
for (const diagnostic of this._diagnostics.getDiagnostics(resource)) {
if (ran.contains(diagnostic.range)) {
if (ran.intersection(diagnostic.range)) {
allDiagnostics.push(diagnostic);
}
}
@@ -294,6 +317,7 @@ class CodeActionAdapter {
diagnostics: allDiagnostics,
only: context.only ? new CodeActionKind(context.only) : undefined
};
return asWinJsPromise(token =>
this._provider.provideCodeActions(doc, ran, codeActionContext, token)
).then(commandsOrActions => {
@@ -317,8 +341,8 @@ class CodeActionAdapter {
result.push({
title: candidate.title,
command: candidate.command && this._commands.toInternal(candidate.command),
diagnostics: candidate.diagnostics && candidate.diagnostics.map(TypeConverters.fromDiagnostic),
edit: candidate.edit && TypeConverters.WorkspaceEdit.from(candidate.edit),
diagnostics: candidate.diagnostics && candidate.diagnostics.map(typeConvert.Diagnostic.from),
edit: candidate.edit && typeConvert.WorkspaceEdit.from(candidate.edit),
kind: candidate.kind && candidate.kind.value
});
}
@@ -349,7 +373,7 @@ class DocumentFormattingAdapter {
return asWinJsPromise(token => this._provider.provideDocumentFormattingEdits(document, <any>options, token)).then(value => {
if (Array.isArray(value)) {
return value.map(TypeConverters.TextEdit.from);
return value.map(typeConvert.TextEdit.from);
}
return undefined;
});
@@ -369,11 +393,11 @@ class RangeFormattingAdapter {
provideDocumentRangeFormattingEdits(resource: URI, range: IRange, options: modes.FormattingOptions): TPromise<ISingleEditOperation[]> {
const { document } = this._documents.getDocumentData(resource);
const ran = TypeConverters.toRange(range);
const ran = typeConvert.Range.to(range);
return asWinJsPromise(token => this._provider.provideDocumentRangeFormattingEdits(document, ran, <any>options, token)).then(value => {
if (Array.isArray(value)) {
return value.map(TypeConverters.TextEdit.from);
return value.map(typeConvert.TextEdit.from);
}
return undefined;
});
@@ -395,11 +419,11 @@ class OnTypeFormattingAdapter {
provideOnTypeFormattingEdits(resource: URI, position: IPosition, ch: string, options: modes.FormattingOptions): TPromise<ISingleEditOperation[]> {
const { document } = this._documents.getDocumentData(resource);
const pos = TypeConverters.toPosition(position);
const pos = typeConvert.Position.to(position);
return asWinJsPromise(token => this._provider.provideOnTypeFormattingEdits(document, pos, ch, <any>options, token)).then(value => {
if (Array.isArray(value)) {
return value.map(TypeConverters.TextEdit.from);
return value.map(typeConvert.TextEdit.from);
}
return undefined;
});
@@ -429,7 +453,7 @@ class NavigateTypeAdapter {
console.warn('INVALID SymbolInformation, lacks name', item);
continue;
}
const symbol = IdObject.mixin(TypeConverters.fromSymbolInformation(item));
const symbol = IdObject.mixin(typeConvert.SymbolInformation.from(item));
this._symbolCache[symbol._id] = item;
result.symbols.push(symbol);
}
@@ -451,7 +475,7 @@ class NavigateTypeAdapter {
const item = this._symbolCache[symbol._id];
if (item) {
return asWinJsPromise(token => this._provider.resolveWorkspaceSymbol(item, token)).then(value => {
return value && mixin(symbol, TypeConverters.fromSymbolInformation(value), true);
return value && mixin(symbol, typeConvert.SymbolInformation.from(value), true);
});
}
return undefined;
@@ -471,7 +495,7 @@ class NavigateTypeAdapter {
class RenameAdapter {
static supportsResolving(provider: vscode.RenameProvider): boolean {
return typeof provider.resolveRenameLocation === 'function';
return typeof provider.prepareRename === 'function';
}
private _documents: ExtHostDocuments;
@@ -485,13 +509,13 @@ class RenameAdapter {
provideRenameEdits(resource: URI, position: IPosition, newName: string): TPromise<modes.WorkspaceEdit> {
let doc = this._documents.getDocumentData(resource).document;
let pos = TypeConverters.toPosition(position);
let pos = typeConvert.Position.to(position);
return asWinJsPromise(token => this._provider.provideRenameEdits(doc, pos, newName, token)).then(value => {
if (!value) {
return undefined;
}
return TypeConverters.WorkspaceEdit.from(value);
return typeConvert.WorkspaceEdit.from(value);
}, err => {
if (typeof err === 'string') {
return <modes.WorkspaceEdit>{
@@ -511,14 +535,14 @@ class RenameAdapter {
}
resolveRenameLocation(resource: URI, position: IPosition): TPromise<modes.RenameLocation> {
if (typeof this._provider.resolveRenameLocation !== 'function') {
if (typeof this._provider.prepareRename !== 'function') {
return TPromise.as(undefined);
}
let doc = this._documents.getDocumentData(resource).document;
let pos = TypeConverters.toPosition(position);
let pos = typeConvert.Position.to(position);
return asWinJsPromise(token => this._provider.resolveRenameLocation(doc, pos, token)).then(rangeOrLocation => {
return asWinJsPromise(token => this._provider.prepareRename(doc, pos, token)).then(rangeOrLocation => {
let range: vscode.Range;
let text: string;
@@ -539,7 +563,7 @@ class RenameAdapter {
console.warn('INVALID rename location: range must contain position');
return undefined;
}
return { range: TypeConverters.fromRange(range), text };
return { range: typeConvert.Range.from(range), text };
});
}
}
@@ -566,10 +590,10 @@ class SuggestAdapter {
provideCompletionItems(resource: URI, position: IPosition, context: modes.SuggestContext): TPromise<SuggestResultDto> {
const doc = this._documents.getDocumentData(resource).document;
const pos = TypeConverters.toPosition(position);
const pos = typeConvert.Position.to(position);
return asWinJsPromise<vscode.CompletionItem[] | vscode.CompletionList>(token => {
return this._provider.provideCompletionItems(doc, pos, token, TypeConverters.CompletionContext.from(context));
return this._provider.provideCompletionItems(doc, pos, token, typeConvert.CompletionContext.from(context));
}).then(value => {
const _id = this._idPool++;
@@ -629,7 +653,7 @@ class SuggestAdapter {
}
const doc = this._documents.getDocumentData(resource).document;
const pos = TypeConverters.toPosition(position);
const pos = typeConvert.Position.to(position);
const wordRangeBeforePos = (doc.getWordRangeAtPosition(pos) as Range || new Range(pos, pos)).with({ end: pos });
const newSuggestion = this._convertCompletionItem(resolvedItem, pos, wordRangeBeforePos, _id, _parentId);
if (newSuggestion) {
@@ -656,14 +680,14 @@ class SuggestAdapter {
_parentId,
//
label: item.label,
type: TypeConverters.CompletionItemKind.from(item.kind),
type: typeConvert.CompletionItemKind.from(item.kind),
detail: item.detail,
documentation: item.documentation,
filterText: item.filterText,
sortText: item.sortText,
//
insertText: undefined,
additionalTextEdits: item.additionalTextEdits && item.additionalTextEdits.map(TypeConverters.TextEdit.from),
additionalTextEdits: item.additionalTextEdits && item.additionalTextEdits.map(typeConvert.TextEdit.from),
command: this._commands.toInternal(item.command),
commitCharacters: item.commitCharacters
};
@@ -720,11 +744,11 @@ class SignatureHelpAdapter {
provideSignatureHelp(resource: URI, position: IPosition): TPromise<modes.SignatureHelp> {
const doc = this._documents.getDocumentData(resource).document;
const pos = TypeConverters.toPosition(position);
const pos = typeConvert.Position.to(position);
return asWinJsPromise(token => this._provider.provideSignatureHelp(doc, pos, token)).then(value => {
if (value) {
return TypeConverters.SignatureHelp.from(value);
return typeConvert.SignatureHelp.from(value);
}
return undefined;
});
@@ -752,7 +776,7 @@ class LinkProviderAdapter {
}
const result: modes.ILink[] = [];
for (const link of links) {
let data = TypeConverters.DocumentLink.from(link);
let data = typeConvert.DocumentLink.from(link);
let id = this._heapService.keep(link);
ObjectIdentifier.mixin(data, id);
result.push(data);
@@ -774,7 +798,7 @@ class LinkProviderAdapter {
return asWinJsPromise(token => this._provider.resolveDocumentLink(item, token)).then(value => {
if (value) {
return TypeConverters.DocumentLink.from(value);
return typeConvert.DocumentLink.from(value);
}
return undefined;
});
@@ -797,8 +821,8 @@ class ColorProviderAdapter {
const colorInfos: IRawColorInfo[] = colors.map(ci => {
return {
color: TypeConverters.Color.from(ci.color),
range: TypeConverters.fromRange(ci.range)
color: typeConvert.Color.from(ci.color),
range: typeConvert.Range.from(ci.range)
};
});
@@ -808,10 +832,10 @@ class ColorProviderAdapter {
provideColorPresentations(resource: URI, raw: IRawColorInfo): TPromise<modes.IColorPresentation[]> {
const document = this._documents.getDocumentData(resource).document;
const range = TypeConverters.toRange(raw.range);
const color = TypeConverters.Color.to(raw.color);
const range = typeConvert.Range.to(raw.range);
const color = typeConvert.Color.to(raw.color);
return asWinJsPromise(token => this._provider.provideColorPresentations(color, { document, range }, token)).then(value => {
return value.map(TypeConverters.ColorPresentation.from);
return value.map(typeConvert.ColorPresentation.from);
});
}
}
@@ -829,7 +853,7 @@ class FoldingProviderAdapter {
if (!Array.isArray(ranges)) {
return void 0;
}
return ranges.map(TypeConverters.FoldingRange.from);
return ranges.map(typeConvert.FoldingRange.from);
});
}
}
@@ -893,7 +917,8 @@ export class ExtHostLanguageFeatures implements ExtHostLanguageFeaturesShape {
$serialized: true,
language: selector.language,
scheme: this._transformScheme(selector.scheme),
pattern: selector.pattern
pattern: selector.pattern,
exclusive: selector.exclusive
};
}
@@ -934,9 +959,9 @@ export class ExtHostLanguageFeatures implements ExtHostLanguageFeaturesShape {
// --- outline
registerDocumentSymbolProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentSymbolProvider): vscode.Disposable {
registerDocumentSymbolProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentSymbolProvider, extensionId?: string): vscode.Disposable {
const handle = this._addNewAdapter(new OutlineAdapter(this._documents, provider));
this._proxy.$registerOutlineSupport(handle, this._transformDocumentSelector(selector));
this._proxy.$registerOutlineSupport(handle, this._transformDocumentSelector(selector), extensionId);
return this._createDisposable(handle);
}
@@ -1047,8 +1072,8 @@ export class ExtHostLanguageFeatures implements ExtHostLanguageFeaturesShape {
}
$provideCodeActions(handle: number, resource: UriComponents, range: IRange, context: modes.CodeActionContext): TPromise<CodeActionDto[]> {
return this._withAdapter(handle, CodeActionAdapter, adapter => adapter.provideCodeActions(URI.revive(resource), range, context));
$provideCodeActions(handle: number, resource: UriComponents, rangeOrSelection: IRange | ISelection, context: modes.CodeActionContext): TPromise<CodeActionDto[]> {
return this._withAdapter(handle, CodeActionAdapter, adapter => adapter.provideCodeActions(URI.revive(resource), rangeOrSelection, context));
}
// --- formatting
@@ -1116,7 +1141,7 @@ export class ExtHostLanguageFeatures implements ExtHostLanguageFeaturesShape {
}
$resolveRenameLocation(handle: number, resource: URI, position: IPosition): TPromise<modes.RenameLocation> {
return this._withAdapter(handle, RenameAdapter, adapter => adapter.resolveRenameLocation(resource, position));
return this._withAdapter(handle, RenameAdapter, adapter => adapter.resolveRenameLocation(URI.revive(resource), position));
}
// --- suggestion

View File

@@ -6,11 +6,12 @@
import { TPromise } from 'vs/base/common/winjs.base';
import { wireCancellationToken, asWinJsPromise } from 'vs/base/common/async';
import { CancellationToken } from 'vs/base/common/cancellation';
import { QuickPickOptions, QuickPickItem, InputBoxOptions, WorkspaceFolderPickOptions, WorkspaceFolder } from 'vscode';
import { CancellationTokenSource, CancellationToken } from 'vs/base/common/cancellation';
import { QuickPickOptions, QuickPickItem, InputBoxOptions, WorkspaceFolderPickOptions, WorkspaceFolder, QuickInput } from 'vscode';
import { MainContext, MainThreadQuickOpenShape, ExtHostQuickOpenShape, MyQuickPickItems, IMainContext } from './extHost.protocol';
import { ExtHostWorkspace } from 'vs/workbench/api/node/extHostWorkspace';
import { ExtHostCommands } from 'vs/workbench/api/node/extHostCommands';
import { isPromiseCanceledError } from 'vs/base/common/errors';
export type Item = string | QuickPickItem;
@@ -23,29 +24,30 @@ export class ExtHostQuickOpen implements ExtHostQuickOpenShape {
private _onDidSelectItem: (handle: number) => void;
private _validateInput: (input: string) => string | Thenable<string>;
private _nextMultiStepHandle = 1;
constructor(mainContext: IMainContext, workspace: ExtHostWorkspace, commands: ExtHostCommands) {
this._proxy = mainContext.getProxy(MainContext.MainThreadQuickOpen);
this._workspace = workspace;
this._commands = commands;
}
showQuickPick(itemsOrItemsPromise: QuickPickItem[] | Thenable<QuickPickItem[]>, options: QuickPickOptions & { canSelectMany: true; }, token?: CancellationToken): Thenable<QuickPickItem[] | undefined>;
showQuickPick(itemsOrItemsPromise: string[] | Thenable<string[]>, options?: QuickPickOptions, token?: CancellationToken): Thenable<string | undefined>;
showQuickPick(itemsOrItemsPromise: QuickPickItem[] | Thenable<QuickPickItem[]>, options?: QuickPickOptions, token?: CancellationToken): Thenable<QuickPickItem | undefined>;
showQuickPick(itemsOrItemsPromise: Item[] | Thenable<Item[]>, options?: QuickPickOptions, token: CancellationToken = CancellationToken.None): Thenable<Item | Item[] | undefined> {
showQuickPick(multiStepHandle: number | undefined, itemsOrItemsPromise: QuickPickItem[] | Thenable<QuickPickItem[]>, options: QuickPickOptions & { canPickMany: true; }, token?: CancellationToken): Thenable<QuickPickItem[] | undefined>;
showQuickPick(multiStepHandle: number | undefined, itemsOrItemsPromise: string[] | Thenable<string[]>, options?: QuickPickOptions, token?: CancellationToken): Thenable<string | undefined>;
showQuickPick(multiStepHandle: number | undefined, itemsOrItemsPromise: QuickPickItem[] | Thenable<QuickPickItem[]>, options?: QuickPickOptions, token?: CancellationToken): Thenable<QuickPickItem | undefined>;
showQuickPick(multiStepHandle: number | undefined, itemsOrItemsPromise: Item[] | Thenable<Item[]>, options?: QuickPickOptions, token: CancellationToken = CancellationToken.None): Thenable<Item | Item[] | undefined> {
// clear state from last invocation
this._onDidSelectItem = undefined;
const itemsPromise = <TPromise<Item[]>>TPromise.wrap(itemsOrItemsPromise);
const quickPickWidget = this._proxy.$show({
autoFocus: { autoFocusFirstEntry: true },
const quickPickWidget = this._proxy.$show(multiStepHandle, {
placeHolder: options && options.placeHolder,
matchOnDescription: options && options.matchOnDescription,
matchOnDetail: options && options.matchOnDetail,
ignoreFocusLost: options && options.ignoreFocusOut,
canSelectMany: options && options.canPickMany
canPickMany: options && options.canPickMany
});
const promise = TPromise.any(<TPromise<number | Item[]>[]>[quickPickWidget, itemsPromise]).then(values => {
@@ -116,12 +118,12 @@ export class ExtHostQuickOpen implements ExtHostQuickOpenShape {
// ---- input
showInput(options?: InputBoxOptions, token: CancellationToken = CancellationToken.None): Thenable<string> {
showInput(multiStepHandle: number | undefined, options?: InputBoxOptions, token: CancellationToken = CancellationToken.None): Thenable<string> {
// global validate fn used in callback below
this._validateInput = options && options.validateInput;
const promise = this._proxy.$input(options, typeof this._validateInput === 'function');
const promise = this._proxy.$input(multiStepHandle, options, typeof this._validateInput === 'function');
return wireCancellationToken(token, promise, true);
}
@@ -143,4 +145,42 @@ export class ExtHostQuickOpen implements ExtHostQuickOpenShape {
return this._workspace.getWorkspaceFolders().filter(folder => folder.uri.toString() === selectedFolder.uri.toString())[0];
});
}
// ---- Multi-step input
multiStepInput<T>(handler: (input: QuickInput, token: CancellationToken) => Thenable<T>, clientToken: CancellationToken = CancellationToken.None): Thenable<T> {
const handle = this._nextMultiStepHandle++;
const remotePromise = this._proxy.$multiStep(handle);
const cancellationSource = new CancellationTokenSource();
const handlerPromise = TPromise.wrap(handler({
showQuickPick: this.showQuickPick.bind(this, handle),
showInputBox: this.showInput.bind(this, handle)
}, cancellationSource.token));
clientToken.onCancellationRequested(() => {
remotePromise.cancel();
cancellationSource.cancel();
});
return TPromise.join<void, T>([
remotePromise.then(() => {
throw new Error('Unexpectedly fulfilled promise.');
}, err => {
if (!isPromiseCanceledError(err)) {
throw err;
}
cancellationSource.cancel();
}),
handlerPromise.then(result => {
remotePromise.cancel();
return result;
}, err => {
remotePromise.cancel();
throw err;
})
]).then(([_, result]) => result, ([remoteErr, handlerErr]) => {
throw handlerErr || remoteErr;
});
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -21,7 +21,7 @@ import { ExtHostWorkspace } from 'vs/workbench/api/node/extHostWorkspace';
import * as vscode from 'vscode';
import {
TaskDefinitionDTO, TaskExecutionDTO, TaskPresentationOptionsDTO, ProcessExecutionOptionsDTO, ProcessExecutionDTO,
ShellExecutionOptionsDTO, ShellExecutionDTO, TaskDTO, TaskHandleDTO, TaskFilterDTO
ShellExecutionOptionsDTO, ShellExecutionDTO, TaskDTO, TaskHandleDTO, TaskFilterDTO, TaskProcessStartedDTO, TaskProcessEndedDTO
} from '../shared/tasks';
export { TaskExecutionDTO };
@@ -610,7 +610,7 @@ namespace TaskDTO {
scope = value.scope.uri.toJSON();
}
}
if (!execution || !definition || !scope) {
if (!definition || !scope) {
return undefined;
}
let group = (value.group as types.TaskGroup) ? (value.group as types.TaskGroup).id : undefined;
@@ -655,7 +655,7 @@ namespace TaskDTO {
scope = types.TaskScope.Workspace;
}
}
if (!execution || !definition || !scope) {
if (!definition || !scope) {
return undefined;
}
let result = new types.Task(definition, scope, value.name, value.source.label, execution, value.problemMatchers);
@@ -689,21 +689,28 @@ namespace TaskFilterDTO {
}
class TaskExecutionImpl implements vscode.TaskExecution {
constructor(readonly _id: string, private readonly _task: vscode.Task, private readonly _tasks: ExtHostTask) {
constructor(private readonly _tasks: ExtHostTask, readonly _id: string, private readonly _task: vscode.Task) {
}
get task(): vscode.Task {
public get task(): vscode.Task {
return this._task;
}
public terminate(): void {
this._tasks.terminateTask(this);
}
public fireDidStartProcess(value: TaskProcessStartedDTO): void {
}
public fireDidEndProcess(value: TaskProcessEndedDTO): void {
}
}
namespace TaskExecutionDTO {
export function to(value: TaskExecutionDTO, tasks: ExtHostTask): vscode.TaskExecution {
return new TaskExecutionImpl(value.id, TaskDTO.to(value.task, tasks.extHostWorkspace), tasks);
return new TaskExecutionImpl(tasks, value.id, TaskDTO.to(value.task, tasks.extHostWorkspace));
}
export function from(value: vscode.TaskExecution): TaskExecutionDTO {
return {
@@ -729,6 +736,9 @@ export class ExtHostTask implements ExtHostTaskShape {
private readonly _onDidExecuteTask: Emitter<vscode.TaskStartEvent> = new Emitter<vscode.TaskStartEvent>();
private readonly _onDidTerminateTask: Emitter<vscode.TaskEndEvent> = new Emitter<vscode.TaskEndEvent>();
private readonly _onDidTaskProcessStarted: Emitter<vscode.TaskProcessStartEvent> = new Emitter<vscode.TaskProcessStartEvent>();
private readonly _onDidTaskProcessEnded: Emitter<vscode.TaskProcessEndEvent> = new Emitter<vscode.TaskProcessEndEvent>();
constructor(mainContext: IMainContext, extHostWorkspace: ExtHostWorkspace) {
this._proxy = mainContext.getProxy(MainContext.MainThreadTask);
this._extHostWorkspace = extHostWorkspace;
@@ -781,22 +791,12 @@ export class ExtHostTask implements ExtHostTaskShape {
}
}
public $taskStarted(execution: TaskExecutionDTO): void {
this._onDidExecuteTask.fire({
execution: this.getTaskExecution(execution)
});
}
get taskExecutions(): vscode.TaskExecution[] {
public get taskExecutions(): vscode.TaskExecution[] {
let result: vscode.TaskExecution[] = [];
this._taskExecutions.forEach(value => result.push(value));
return result;
}
get onDidStartTask(): Event<vscode.TaskStartEvent> {
return this._onDidExecuteTask.event;
}
public terminateTask(execution: vscode.TaskExecution): TPromise<void> {
if (!(execution instanceof TaskExecutionImpl)) {
throw new Error('No valid task execution provided');
@@ -804,7 +804,21 @@ export class ExtHostTask implements ExtHostTaskShape {
return this._proxy.$terminateTask((execution as TaskExecutionImpl)._id);
}
public $taskEnded(execution: TaskExecutionDTO): void {
public get onDidStartTask(): Event<vscode.TaskStartEvent> {
return this._onDidExecuteTask.event;
}
public $onDidStartTask(execution: TaskExecutionDTO): void {
this._onDidExecuteTask.fire({
execution: this.getTaskExecution(execution)
});
}
public get onDidEndTask(): Event<vscode.TaskEndEvent> {
return this._onDidTerminateTask.event;
}
public $OnDidEndTask(execution: TaskExecutionDTO): void {
const _execution = this.getTaskExecution(execution);
this._taskExecutions.delete(execution.id);
this._onDidTerminateTask.fire({
@@ -812,8 +826,32 @@ export class ExtHostTask implements ExtHostTaskShape {
});
}
get onDidEndTask(): Event<vscode.TaskEndEvent> {
return this._onDidTerminateTask.event;
public get onDidStartTaskProcess(): Event<vscode.TaskProcessStartEvent> {
return this._onDidTaskProcessStarted.event;
}
public $onDidStartTaskProcess(value: TaskProcessStartedDTO): void {
const execution = this.getTaskExecution(value.id);
if (execution) {
this._onDidTaskProcessStarted.fire({
execution: execution,
processId: value.processId
});
}
}
public get onDidEndTaskProcess(): Event<vscode.TaskProcessEndEvent> {
return this._onDidTaskProcessEnded.event;
}
public $onDidEndTaskProcess(value: TaskProcessEndedDTO): void {
const execution = this.getTaskExecution(value.id);
if (execution) {
this._onDidTaskProcessEnded.fire({
execution: execution,
exitCode: value.exitCode
});
}
}
public $provideTasks(handle: number): TPromise<TaskSystem.TaskSet> {
@@ -834,12 +872,16 @@ export class ExtHostTask implements ExtHostTaskShape {
return this._handleCounter++;
}
private getTaskExecution(execution: TaskExecutionDTO, task?: vscode.Task): TaskExecutionImpl {
private getTaskExecution(execution: TaskExecutionDTO | string, task?: vscode.Task): TaskExecutionImpl {
if (typeof execution === 'string') {
return this._taskExecutions.get(execution);
}
let result: TaskExecutionImpl = this._taskExecutions.get(execution.id);
if (result) {
return result;
}
result = new TaskExecutionImpl(execution.id, task ? task : TaskDTO.to(execution.task, this._extHostWorkspace), this);
result = new TaskExecutionImpl(this, execution.id, task ? task : TaskDTO.to(execution.task, this._extHostWorkspace));
this._taskExecutions.set(execution.id, result);
return result;
}

View File

@@ -345,7 +345,7 @@ export class ExtHostTextEditor implements vscode.TextEditor {
}
@deprecated('TextEditor.show') show(column: vscode.ViewColumn) {
this._proxy.$tryShowEditor(this._id, TypeConverters.fromViewColumn(column));
this._proxy.$tryShowEditor(this._id, TypeConverters.ViewColumn.from(column));
}
@deprecated('TextEditor.hide') hide() {
@@ -467,14 +467,14 @@ export class ExtHostTextEditor implements vscode.TextEditor {
this._runOnProxy(
() => this._proxy.$tryRevealRange(
this._id,
TypeConverters.fromRange(range),
TypeConverters.Range.from(range),
(revealType || TextEditorRevealType.Default)
)
);
}
private _trySetSelection(): TPromise<vscode.TextEditor> {
let selection = this._selections.map(TypeConverters.fromSelection);
let selection = this._selections.map(TypeConverters.Selection.from);
return this._runOnProxy(() => this._proxy.$trySetSelections(this._id, selection));
}
@@ -530,7 +530,7 @@ export class ExtHostTextEditor implements vscode.TextEditor {
// prepare data for serialization
let edits: ISingleEditOperation[] = editData.edits.map((edit) => {
return {
range: TypeConverters.fromRange(edit.range),
range: TypeConverters.Range.from(edit.range),
text: edit.text,
forceMoveMarkers: edit.forceMoveMarkers
};
@@ -550,21 +550,21 @@ export class ExtHostTextEditor implements vscode.TextEditor {
let ranges: IRange[];
if (!where || (Array.isArray(where) && where.length === 0)) {
ranges = this._selections.map(TypeConverters.fromRange);
ranges = this._selections.map(TypeConverters.Range.from);
} else if (where instanceof Position) {
const { lineNumber, column } = TypeConverters.fromPosition(where);
const { lineNumber, column } = TypeConverters.Position.from(where);
ranges = [{ startLineNumber: lineNumber, startColumn: column, endLineNumber: lineNumber, endColumn: column }];
} else if (where instanceof Range) {
ranges = [TypeConverters.fromRange(where)];
ranges = [TypeConverters.Range.from(where)];
} else {
ranges = [];
for (const posOrRange of where) {
if (posOrRange instanceof Range) {
ranges.push(TypeConverters.fromRange(posOrRange));
ranges.push(TypeConverters.Range.from(posOrRange));
} else {
const { lineNumber, column } = TypeConverters.fromPosition(posOrRange);
const { lineNumber, column } = TypeConverters.Position.from(posOrRange);
ranges.push({ startLineNumber: lineNumber, startColumn: column, endLineNumber: lineNumber, endColumn: column });
}
}

View File

@@ -61,14 +61,14 @@ export class ExtHostEditors implements ExtHostEditorsShape {
let options: ITextDocumentShowOptions;
if (typeof columnOrOptions === 'number') {
options = {
position: TypeConverters.fromViewColumn(columnOrOptions),
position: TypeConverters.ViewColumn.from(columnOrOptions),
preserveFocus
};
} else if (typeof columnOrOptions === 'object') {
options = {
position: TypeConverters.fromViewColumn(columnOrOptions.viewColumn),
position: TypeConverters.ViewColumn.from(columnOrOptions.viewColumn),
preserveFocus: columnOrOptions.preserveFocus,
selection: typeof columnOrOptions.selection === 'object' ? TypeConverters.fromRange(columnOrOptions.selection) : undefined,
selection: typeof columnOrOptions.selection === 'object' ? TypeConverters.Range.from(columnOrOptions.selection) : undefined,
pinned: typeof columnOrOptions.preview === 'boolean' ? !columnOrOptions.preview : undefined
};
} else {
@@ -123,11 +123,11 @@ export class ExtHostEditors implements ExtHostEditorsShape {
textEditor._acceptOptions(data.options);
}
if (data.selections) {
const selections = data.selections.selections.map(TypeConverters.toSelection);
const selections = data.selections.selections.map(TypeConverters.Selection.to);
textEditor._acceptSelections(selections);
}
if (data.visibleRanges) {
const visibleRanges = data.visibleRanges.map(TypeConverters.toRange);
const visibleRanges = data.visibleRanges.map(TypeConverters.Range.to);
textEditor._acceptVisibleRanges(visibleRanges);
}
@@ -140,7 +140,7 @@ export class ExtHostEditors implements ExtHostEditorsShape {
}
if (data.selections) {
const kind = TextEditorSelectionChangeKind.fromValue(data.selections.source);
const selections = data.selections.selections.map(TypeConverters.toSelection);
const selections = data.selections.selections.map(TypeConverters.Selection.to);
this._onDidChangeTextEditorSelection.fire({
textEditor,
selections,
@@ -148,7 +148,7 @@ export class ExtHostEditors implements ExtHostEditorsShape {
});
}
if (data.visibleRanges) {
const visibleRanges = data.visibleRanges.map(TypeConverters.toRange);
const visibleRanges = data.visibleRanges.map(TypeConverters.Range.to);
this._onDidChangeTextEditorVisibleRanges.fire({
textEditor,
visibleRanges
@@ -159,7 +159,7 @@ export class ExtHostEditors implements ExtHostEditorsShape {
$acceptEditorPositionData(data: ITextEditorPositionData): void {
for (let id in data) {
let textEditor = this._extHostDocumentsAndEditors.getEditor(id);
let viewColumn = TypeConverters.toViewColumn(data[id]);
let viewColumn = TypeConverters.ViewColumn.to(data[id]);
if (textEditor.viewColumn !== viewColumn) {
textEditor._acceptViewColumn(viewColumn);
this._onDidChangeTextEditorViewColumn.fire({ textEditor, viewColumn });

View File

@@ -8,7 +8,7 @@ import { localize } from 'vs/nls';
import * as vscode from 'vscode';
import { basename } from 'vs/base/common/paths';
import URI from 'vs/base/common/uri';
import { debounceEvent } from 'vs/base/common/event';
import { debounceEvent, Emitter, Event } from 'vs/base/common/event';
import { TPromise } from 'vs/base/common/winjs.base';
import { Disposable } from 'vs/base/common/lifecycle';
import { ExtHostTreeViewsShape, MainThreadTreeViewsShape } from './extHost.protocol';
@@ -49,6 +49,9 @@ export class ExtHostTreeViews implements ExtHostTreeViewsShape {
}
const treeView = this.createExtHostTreeViewer(viewId, options.treeDataProvider);
return {
get onDidCollapseElement() { return treeView.onDidCollapseElement; },
get onDidExpandElement() { return treeView.onDidExpandElement; },
get selection() { return treeView.selectedElements; },
reveal: (element: T, options?: { select?: boolean }): Thenable<void> => {
return treeView.reveal(element, options);
},
@@ -67,6 +70,22 @@ export class ExtHostTreeViews implements ExtHostTreeViewsShape {
return treeView.getChildren(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);
}
private createExtHostTreeViewer<T>(id: string, dataProvider: vscode.TreeDataProvider<T>): ExtHostTreeView<T> {
const treeView = new ExtHostTreeView<T>(id, dataProvider, this._proxy, this.commands.converter);
this.treeViews.set(id, treeView);
@@ -94,11 +113,34 @@ class ExtHostTreeView<T> extends Disposable {
private elements: Map<TreeItemHandle, T> = new Map<TreeItemHandle, T>();
private nodes: Map<T, TreeNode> = new Map<T, TreeNode>();
private _selectedElements: T[] = [];
get selectedElements(): T[] { return this._selectedElements; }
private _onDidExpandElement: Emitter<T> = this._register(new Emitter<T>());
readonly onDidExpandElement: Event<T> = this._onDidExpandElement.event;
private _onDidCollapseElement: Emitter<T> = this._register(new Emitter<T>());
readonly onDidCollapseElement: Event<T> = this._onDidCollapseElement.event;
private refreshPromise: TPromise<void> = TPromise.as(null);
constructor(private viewId: string, private dataProvider: vscode.TreeDataProvider<T>, private proxy: MainThreadTreeViewsShape, private commands: CommandsConverter) {
super();
this.proxy.$registerTreeViewDataProvider(viewId);
if (this.dataProvider.onDidChangeTreeData) {
this._register(debounceEvent<T, T[]>(this.dataProvider.onDidChangeTreeData, (last, current) => last ? [...last, current] : [current], 200)(elements => this.refresh(elements)));
let refreshingPromise, promiseCallback;
this._register(debounceEvent<T, T[]>(this.dataProvider.onDidChangeTreeData, (last, current) => {
if (!refreshingPromise) {
// New refresh has started
refreshingPromise = new TPromise((c, e) => promiseCallback = c);
this.refreshPromise = this.refreshPromise.then(() => refreshingPromise);
}
return last ? [...last, current] : [current];
}, 200)(elements => {
const _promiseCallback = promiseCallback;
refreshingPromise = null;
this.refresh(elements).then(() => _promiseCallback());
}));
}
}
@@ -120,13 +162,29 @@ class ExtHostTreeView<T> extends Disposable {
reveal(element: T, options?: { select?: boolean }): TPromise<void> {
if (typeof this.dataProvider.getParent !== 'function') {
return TPromise.wrapError(new Error(`Required registered TreeDataProvider to implement 'getParent' method to access 'reveal' mehtod`));
return TPromise.wrapError(new Error(`Required registered TreeDataProvider to implement 'getParent' method to access 'reveal' method`));
}
return this.resolveUnknownParentChain(element)
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), options)));
}
setExpanded(treeItemHandle: TreeItemHandle, expanded: boolean): void {
const element = this.getExtensionElement(treeItemHandle);
if (element) {
if (expanded) {
this._onDidExpandElement.fire(element);
} else {
this._onDidCollapseElement.fire(element);
}
}
}
setSelection(treeItemHandles: TreeItemHandle[]): void {
this._selectedElements = treeItemHandles.map(handle => this.getExtensionElement(handle)).filter(element => !isUndefinedOrNull(element));
}
private resolveUnknownParentChain(element: T): TPromise<TreeNode[]> {
return this.resolveParent(element)
.then((parent) => {
@@ -194,17 +252,18 @@ class ExtHostTreeView<T> extends Disposable {
.then(nodes => nodes.filter(n => !!n));
}
private refresh(elements: T[]): void {
private refresh(elements: T[]): TPromise<void> {
const hasRoot = elements.some(element => !element);
if (hasRoot) {
this.clearAll(); // clear cache
this.proxy.$refresh(this.viewId);
return this.proxy.$refresh(this.viewId);
} else {
const handlesToRefresh = this.getHandlesToRefresh(elements);
if (handlesToRefresh.length) {
this.refreshHandles(handlesToRefresh);
return this.refreshHandles(handlesToRefresh);
}
}
return TPromise.as(null);
}
private getHandlesToRefresh(elements: T[]): TreeItemHandle[] {

View File

@@ -18,9 +18,9 @@ import { IRange } from 'vs/editor/common/core/range';
import { ISelection } from 'vs/editor/common/core/selection';
import * as htmlContent from 'vs/base/common/htmlContent';
import { IRelativePattern } from 'vs/base/common/glob';
import { LanguageSelector, LanguageFilter } from 'vs/editor/common/modes/languageSelector';
import * as languageSelector from 'vs/editor/common/modes/languageSelector';
import { WorkspaceEditDto, ResourceTextEditDto } from 'vs/workbench/api/node/extHost.protocol';
import { MarkerSeverity, IRelatedInformation, IMarkerData } from 'vs/platform/markers/common/markers';
import { MarkerSeverity, IRelatedInformation, IMarkerData, MarkerTag } from 'vs/platform/markers/common/markers';
export interface PositionLike {
line: number;
@@ -36,131 +36,153 @@ export interface SelectionLike extends RangeLike {
anchor: PositionLike;
active: PositionLike;
}
export namespace Selection {
export function toSelection(selection: ISelection): types.Selection {
let { selectionStartLineNumber, selectionStartColumn, positionLineNumber, positionColumn } = selection;
let start = new types.Position(selectionStartLineNumber - 1, selectionStartColumn - 1);
let end = new types.Position(positionLineNumber - 1, positionColumn - 1);
return new types.Selection(start, end);
export function to(selection: ISelection): types.Selection {
let { selectionStartLineNumber, selectionStartColumn, positionLineNumber, positionColumn } = selection;
let start = new types.Position(selectionStartLineNumber - 1, selectionStartColumn - 1);
let end = new types.Position(positionLineNumber - 1, positionColumn - 1);
return new types.Selection(start, end);
}
export function from(selection: SelectionLike): ISelection {
let { anchor, active } = selection;
return {
selectionStartLineNumber: anchor.line + 1,
selectionStartColumn: anchor.character + 1,
positionLineNumber: active.line + 1,
positionColumn: active.character + 1
};
}
}
export namespace Range {
export function from(range: RangeLike): IRange {
if (!range) {
return undefined;
}
let { start, end } = range;
return {
startLineNumber: start.line + 1,
startColumn: start.character + 1,
endLineNumber: end.line + 1,
endColumn: end.character + 1
};
}
export function to(range: IRange): types.Range {
if (!range) {
return undefined;
}
let { startLineNumber, startColumn, endLineNumber, endColumn } = range;
return new types.Range(startLineNumber - 1, startColumn - 1, endLineNumber - 1, endColumn - 1);
}
}
export function fromSelection(selection: SelectionLike): ISelection {
let { anchor, active } = selection;
return {
selectionStartLineNumber: anchor.line + 1,
selectionStartColumn: anchor.character + 1,
positionLineNumber: active.line + 1,
positionColumn: active.character + 1
};
export namespace Position {
export function to(position: IPosition): types.Position {
return new types.Position(position.lineNumber - 1, position.column - 1);
}
export function from(position: types.Position): IPosition {
return { lineNumber: position.line + 1, column: position.character + 1 };
}
}
export function fromRange(range: RangeLike): IRange {
if (!range) {
export namespace DiagnosticTag {
export function from(value: vscode.DiagnosticTag): MarkerTag {
switch (value) {
case types.DiagnosticTag.Unnecessary:
return MarkerTag.Unnecessary;
}
return undefined;
}
let { start, end } = range;
return {
startLineNumber: start.line + 1,
startColumn: start.character + 1,
endLineNumber: end.line + 1,
endColumn: end.character + 1
};
}
export function toRange(range: IRange): types.Range {
if (!range) {
export namespace Diagnostic {
export function from(value: vscode.Diagnostic): IMarkerData {
return {
...Range.from(value.range),
message: value.message,
source: value.source,
code: String(value.code),
severity: DiagnosticSeverity.from(value.severity),
relatedInformation: value.relatedInformation && value.relatedInformation.map(DiagnosticRelatedInformation.from),
customTags: Array.isArray(value.customTags) ? value.customTags.map(DiagnosticTag.from) : undefined,
};
}
}
export namespace DiagnosticRelatedInformation {
export function from(value: types.DiagnosticRelatedInformation): IRelatedInformation {
return {
...Range.from(value.location.range),
message: value.message,
resource: value.location.uri
};
}
export function to(value: IRelatedInformation): types.DiagnosticRelatedInformation {
return new types.DiagnosticRelatedInformation(new types.Location(value.resource, Range.to(value)), value.message);
}
}
export namespace DiagnosticSeverity {
export function from(value: number): MarkerSeverity {
switch (value) {
case types.DiagnosticSeverity.Error:
return MarkerSeverity.Error;
case types.DiagnosticSeverity.Warning:
return MarkerSeverity.Warning;
case types.DiagnosticSeverity.Information:
return MarkerSeverity.Info;
case types.DiagnosticSeverity.Hint:
return MarkerSeverity.Hint;
}
return MarkerSeverity.Error;
}
export function to(value: MarkerSeverity): types.DiagnosticSeverity {
switch (value) {
case MarkerSeverity.Info:
return types.DiagnosticSeverity.Information;
case MarkerSeverity.Warning:
return types.DiagnosticSeverity.Warning;
case MarkerSeverity.Error:
return types.DiagnosticSeverity.Error;
case MarkerSeverity.Hint:
return types.DiagnosticSeverity.Hint;
}
return types.DiagnosticSeverity.Error;
}
}
export namespace ViewColumn {
export function from(column?: vscode.ViewColumn): EditorPosition {
let editorColumn = EditorPosition.ONE;
if (typeof column !== 'number') {
// stick with ONE
} else if (column === <number>types.ViewColumn.Two) {
editorColumn = EditorPosition.TWO;
} else if (column === <number>types.ViewColumn.Three) {
editorColumn = EditorPosition.THREE;
} else if (column === <number>types.ViewColumn.Active) {
editorColumn = undefined;
}
return editorColumn;
}
export function to(position?: EditorPosition): vscode.ViewColumn {
if (typeof position !== 'number') {
return undefined;
}
if (position === EditorPosition.ONE) {
return <number>types.ViewColumn.One;
} else if (position === EditorPosition.TWO) {
return <number>types.ViewColumn.Two;
} else if (position === EditorPosition.THREE) {
return <number>types.ViewColumn.Three;
}
return undefined;
}
let { startLineNumber, startColumn, endLineNumber, endColumn } = range;
return new types.Range(startLineNumber - 1, startColumn - 1, endLineNumber - 1, endColumn - 1);
}
export function toPosition(position: IPosition): types.Position {
return new types.Position(position.lineNumber - 1, position.column - 1);
}
export function fromPosition(position: types.Position): IPosition {
return { lineNumber: position.line + 1, column: position.character + 1 };
}
export function fromDiagnostic(value: vscode.Diagnostic): IMarkerData {
return {
...fromRange(value.range),
message: value.message,
source: value.source,
code: String(value.code),
severity: fromDiagnosticSeverity(value.severity),
relatedInformation: value.relatedInformation && value.relatedInformation.map(fromDiagnosticRelatedInformation)
};
}
export function fromDiagnosticRelatedInformation(value: types.DiagnosticRelatedInformation): IRelatedInformation {
return {
...fromRange(value.location.range),
message: value.message,
resource: value.location.uri
};
}
export function toDiagnosticRelatedInformation(value: IRelatedInformation): types.DiagnosticRelatedInformation {
return new types.DiagnosticRelatedInformation(new types.Location(value.resource, toRange(value)), value.message);
}
export function fromDiagnosticSeverity(value: number): MarkerSeverity {
switch (value) {
case types.DiagnosticSeverity.Error:
return MarkerSeverity.Error;
case types.DiagnosticSeverity.Warning:
return MarkerSeverity.Warning;
case types.DiagnosticSeverity.Information:
return MarkerSeverity.Info;
case types.DiagnosticSeverity.Hint:
return MarkerSeverity.Hint;
}
return MarkerSeverity.Error;
}
export function toDiagnosticSeverty(value: MarkerSeverity): types.DiagnosticSeverity {
switch (value) {
case MarkerSeverity.Info:
return types.DiagnosticSeverity.Information;
case MarkerSeverity.Warning:
return types.DiagnosticSeverity.Warning;
case MarkerSeverity.Error:
return types.DiagnosticSeverity.Error;
case MarkerSeverity.Hint:
return types.DiagnosticSeverity.Hint;
}
return types.DiagnosticSeverity.Error;
}
export function fromViewColumn(column?: vscode.ViewColumn): EditorPosition {
let editorColumn = EditorPosition.ONE;
if (typeof column !== 'number') {
// stick with ONE
} else if (column === <number>types.ViewColumn.Two) {
editorColumn = EditorPosition.TWO;
} else if (column === <number>types.ViewColumn.Three) {
editorColumn = EditorPosition.THREE;
} else if (column === <number>types.ViewColumn.Active) {
editorColumn = undefined;
}
return editorColumn;
}
export function toViewColumn(position?: EditorPosition): vscode.ViewColumn {
if (typeof position !== 'number') {
return undefined;
}
if (position === EditorPosition.ONE) {
return <number>types.ViewColumn.One;
} else if (position === EditorPosition.TWO) {
return <number>types.ViewColumn.Two;
} else if (position === EditorPosition.THREE) {
return <number>types.ViewColumn.Three;
}
return undefined;
}
function isDecorationOptions(something: any): something is vscode.DecorationOptions {
@@ -221,7 +243,7 @@ export function fromRangeOrRangeWithMessage(ranges: vscode.Range[] | vscode.Deco
if (isDecorationOptionsArr(ranges)) {
return ranges.map(r => {
return {
range: fromRange(r.range),
range: Range.from(r.range),
hoverMessage: Array.isArray(r.hoverMessage) ? MarkdownString.fromMany(r.hoverMessage) : r.hoverMessage && MarkdownString.from(r.hoverMessage),
renderOptions: <any> /* URI vs Uri */r.renderOptions
};
@@ -229,7 +251,7 @@ export function fromRangeOrRangeWithMessage(ranges: vscode.Range[] | vscode.Deco
} else {
return ranges.map((r): IDecorationOptions => {
return {
range: fromRange(r)
range: Range.from(r)
};
});
}
@@ -241,11 +263,11 @@ export const TextEdit = {
return <modes.TextEdit>{
text: edit.newText,
eol: EndOfLine.from(edit.newEol),
range: fromRange(edit.range)
range: Range.from(edit.range)
};
},
to(edit: modes.TextEdit): types.TextEdit {
let result = new types.TextEdit(toRange(edit.range), edit.text);
let result = new types.TextEdit(Range.to(edit.range), edit.text);
result.newEol = EndOfLine.to(edit.eol);
return result;
}
@@ -333,50 +355,88 @@ export namespace SymbolKind {
}
}
export function fromSymbolInformation(info: vscode.SymbolInformation): modes.SymbolInformation {
return <modes.SymbolInformation>{
name: info.name,
kind: SymbolKind.from(info.kind),
containerName: info.containerName,
location: location.from(info.location)
};
export namespace SymbolInformation {
export function from(info: vscode.SymbolInformation): modes.SymbolInformation {
return <modes.SymbolInformation>{
name: info.name,
kind: SymbolKind.from(info.kind),
containerName: info.containerName,
location: location.from(info.location)
};
}
export function to(info: modes.SymbolInformation): types.SymbolInformation {
return new types.SymbolInformation(
info.name,
SymbolKind.to(info.kind),
info.containerName,
location.to(info.location)
);
}
}
export function toSymbolInformation(bearing: modes.SymbolInformation): types.SymbolInformation {
return new types.SymbolInformation(
bearing.name,
SymbolKind.to(bearing.kind),
bearing.containerName,
location.to(bearing.location)
);
export namespace HierarchicalSymbolInformation {
export function from(info: vscode.Hierarchy<vscode.SymbolInformation2>): modes.SymbolInformation {
let result: modes.SymbolInformation = {
name: info.parent.name,
detail: info.parent.detail,
location: location.from(info.parent.location),
definingRange: Range.from(info.parent.range),
kind: SymbolKind.from(info.parent.kind)
};
if (info.children) {
result.children = info.children.map(from);
}
return result;
}
export function to(info: modes.SymbolInformation): types.Hierarchy<vscode.SymbolInformation2> {
let result = new types.Hierarchy<vscode.SymbolInformation2>(new types.SymbolInformation2(
info.name,
info.detail,
SymbolKind.to(info.kind),
Range.to(info.definingRange),
location.to(info.location),
));
if (info.children) {
result.children = info.children.map(to);
}
return result;
}
}
export const location = {
from(value: vscode.Location): modes.Location {
return {
range: value.range && fromRange(value.range),
range: value.range && Range.from(value.range),
uri: value.uri
};
},
to(value: modes.Location): types.Location {
return new types.Location(value.uri, toRange(value.range));
return new types.Location(value.uri, Range.to(value.range));
}
};
export function fromHover(hover: vscode.Hover): modes.Hover {
return <modes.Hover>{
range: fromRange(hover.range),
contents: MarkdownString.fromMany(hover.contents)
};
}
export namespace Hover {
export function from(hover: vscode.Hover): modes.Hover {
return <modes.Hover>{
range: Range.from(hover.range),
contents: MarkdownString.fromMany(hover.contents)
};
}
export function toHover(info: modes.Hover): types.Hover {
return new types.Hover(info.contents.map(MarkdownString.to), toRange(info.range));
export function to(info: modes.Hover): types.Hover {
return new types.Hover(info.contents.map(MarkdownString.to), Range.to(info.range));
}
}
export function toDocumentHighlight(occurrence: modes.DocumentHighlight): types.DocumentHighlight {
return new types.DocumentHighlight(toRange(occurrence.range), occurrence.kind);
export namespace DocumentHighlight {
export function from(documentHighlight: vscode.DocumentHighlight): modes.DocumentHighlight {
return {
range: Range.from(documentHighlight.range),
kind: documentHighlight.kind
};
}
export function to(occurrence: modes.DocumentHighlight): types.DocumentHighlight {
return new types.DocumentHighlight(Range.to(occurrence.range), occurrence.kind);
}
}
export namespace CompletionTriggerKind {
@@ -535,13 +595,13 @@ export namespace DocumentLink {
export function from(link: vscode.DocumentLink): modes.ILink {
return {
range: fromRange(link.range),
range: Range.from(link.range),
url: link.target && link.target.toString()
};
}
export function to(link: modes.ILink): vscode.DocumentLink {
return new types.DocumentLink(toRange(link.range), link.url && URI.parse(link.url));
return new types.DocumentLink(Range.to(link.range), link.url && URI.parse(link.url));
}
}
@@ -625,60 +685,82 @@ export namespace ProgressLocation {
export namespace FoldingRange {
export function from(r: vscode.FoldingRange): modes.FoldingRange {
return { start: r.start + 1, end: r.end + 1, kind: r.kind };
let range: modes.FoldingRange = { start: r.start + 1, end: r.end + 1 };
if (r.kind) {
range.kind = FoldingRangeKind.from(r.kind);
}
return range;
}
}
export function toTextEditorOptions(options?: vscode.TextDocumentShowOptions): ITextEditorOptions {
if (options) {
return {
pinned: typeof options.preview === 'boolean' ? !options.preview : undefined,
preserveFocus: options.preserveFocus,
selection: typeof options.selection === 'object' ? fromRange(options.selection) : undefined
} as ITextEditorOptions;
export namespace FoldingRangeKind {
export function from(kind: vscode.FoldingRangeKind | undefined): modes.FoldingRangeKind | undefined {
if (kind) {
switch (kind) {
case types.FoldingRangeKind.Comment:
return modes.FoldingRangeKind.Comment;
case types.FoldingRangeKind.Imports:
return modes.FoldingRangeKind.Imports;
case types.FoldingRangeKind.Region:
return modes.FoldingRangeKind.Region;
}
}
return void 0;
}
return undefined;
}
export function toGlobPattern(pattern: vscode.GlobPattern): string | IRelativePattern {
if (typeof pattern === 'string') {
return pattern;
export namespace TextEditorOptions {
export function from(options?: vscode.TextDocumentShowOptions): ITextEditorOptions {
if (options) {
return {
pinned: typeof options.preview === 'boolean' ? !options.preview : undefined,
preserveFocus: options.preserveFocus,
selection: typeof options.selection === 'object' ? Range.from(options.selection) : undefined
} as ITextEditorOptions;
}
return undefined;
}
if (isRelativePattern(pattern)) {
return new types.RelativePattern(pattern.base, pattern.pattern);
}
return pattern; // preserve `undefined` and `null`
}
function isRelativePattern(obj: any): obj is vscode.RelativePattern {
const rp = obj as vscode.RelativePattern;
export namespace GlobPattern {
return rp && typeof rp.base === 'string' && typeof rp.pattern === 'string';
}
export function from(pattern: vscode.GlobPattern): string | IRelativePattern {
if (typeof pattern === 'string') {
return pattern;
}
export function toLanguageSelector(selector: vscode.DocumentSelector): LanguageSelector {
if (Array.isArray(selector)) {
return selector.map(sel => doToLanguageSelector(sel));
if (isRelativePattern(pattern)) {
return new types.RelativePattern(pattern.base, pattern.pattern);
}
return pattern; // preserve `undefined` and `null`
}
return doToLanguageSelector(selector);
function isRelativePattern(obj: any): obj is vscode.RelativePattern {
const rp = obj as vscode.RelativePattern;
return rp && typeof rp.base === 'string' && typeof rp.pattern === 'string';
}
}
function doToLanguageSelector(selector: string | vscode.DocumentFilter): string | LanguageFilter {
if (typeof selector === 'string') {
return selector;
}
export namespace LanguageSelector {
if (selector) {
return {
language: selector.language,
scheme: selector.scheme,
pattern: toGlobPattern(selector.pattern)
};
export function from(selector: vscode.DocumentSelector): languageSelector.LanguageSelector {
if (!selector) {
return undefined;
} else if (Array.isArray(selector)) {
return <languageSelector.LanguageSelector>selector.map(from);
} else if (typeof selector === 'string') {
return selector;
} else {
return <languageSelector.LanguageFilter>{
language: selector.language,
scheme: selector.scheme,
pattern: GlobPattern.from(selector.pattern),
exclusive: selector.exclusive
};
}
}
return undefined;
}

View File

@@ -673,6 +673,10 @@ export class SnippetString {
}
}
export enum DiagnosticTag {
Unnecessary = 1,
}
export enum DiagnosticSeverity {
Hint = 3,
Information = 2,
@@ -747,6 +751,7 @@ export class Diagnostic {
code: string | number;
severity: DiagnosticSeverity;
relatedInformation: DiagnosticRelatedInformation[];
customTags?: DiagnosticTag[];
constructor(range: Range, message: string, severity: DiagnosticSeverity = DiagnosticSeverity.Error) {
this.range = range;
@@ -876,36 +881,26 @@ export class SymbolInformation {
}
}
export class HierarchicalSymbolInformation {
name: string;
location: Location;
kind: SymbolKind;
range: Range;
children: HierarchicalSymbolInformation[];
export class SymbolInformation2 extends SymbolInformation {
constructor(name: string, kind: SymbolKind, location: Location, range: Range) {
this.name = name;
this.kind = kind;
this.location = location;
detail: string;
range: Range;
constructor(name: string, detail: string, kind: SymbolKind, range: Range, location: Location) {
super(name, kind, undefined, location);
this.detail = detail;
this.range = range;
}
}
export class Hierarchy<T> {
parent: T;
children: Hierarchy<T>[];
constructor(parent: T) {
this.parent = parent;
this.children = [];
}
static toFlatSymbolInformation(info: HierarchicalSymbolInformation): SymbolInformation[] {
let result: SymbolInformation[] = [];
HierarchicalSymbolInformation._toFlatSymbolInformation(info, undefined, result);
return result;
}
private static _toFlatSymbolInformation(info: HierarchicalSymbolInformation, containerName: string, bucket: SymbolInformation[]): void {
bucket.push(new SymbolInformation(info.name, info.kind, containerName, new Location(info.location.uri, info.range)));
if (Array.isArray(info.children)) {
for (const child of info.children) {
HierarchicalSymbolInformation._toFlatSymbolInformation(child, info.name, bucket);
}
}
}
}
export class CodeAction {
@@ -1878,11 +1873,23 @@ export class FileSystemError extends Error {
static FileIsADirectory(messageOrUri?: string | URI): FileSystemError {
return new FileSystemError(messageOrUri, 'EntryIsADirectory', FileSystemError.FileIsADirectory);
}
static NoPermissions(messageOrUri?: string | URI): FileSystemError {
return new FileSystemError(messageOrUri, 'NoPermissions', FileSystemError.NoPermissions);
}
static Unavailable(messageOrUri?: string | URI): FileSystemError {
return new FileSystemError(messageOrUri, 'Unavailable', FileSystemError.Unavailable);
}
constructor(uriOrMessage?: string | URI, code?: string, terminator?: Function) {
super(URI.isUri(uriOrMessage) ? uriOrMessage.toString(true) : uriOrMessage);
this.name = code ? `${code} (FileSystemError)` : `FileSystemError`;
// workaround when extending builtin objects and when compiling to ES5, see:
// https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
if (typeof (<any>Object).setPrototypeOf === 'function') {
(<any>Object).setPrototypeOf(this, FileSystemError.prototype);
}
if (typeof Error.captureStackTrace === 'function' && typeof terminator === 'function') {
// nice stack traces
Error.captureStackTrace(this, terminator);
@@ -1909,28 +1916,10 @@ export class FoldingRange {
}
}
export class FoldingRangeKind {
/**
* Kind for folding range representing a comment. The value of the kind is 'comment'.
*/
static readonly Comment = new FoldingRangeKind('comment');
/**
* Kind for folding range representing a import. The value of the kind is 'imports'.
*/
static readonly Imports = new FoldingRangeKind('imports');
/**
* Kind for folding range representing regions (for example marked by `#region`, `#endregion`).
* The value of the kind is 'region'.
*/
static readonly Region = new FoldingRangeKind('region');
/**
* Creates a new [FoldingRangeKind](#FoldingRangeKind).
*
* @param value of the kind.
*/
public constructor(public value: string) {
}
export enum FoldingRangeKind {
Comment = 1,
Imports = 2,
Region = 3
}
//#endregion

View File

@@ -14,6 +14,7 @@ export class ExtHostUrls implements ExtHostUrlsShape {
private static HandlePool = 0;
private readonly _proxy: MainThreadUrlsShape;
private handles = new Set<string>();
private handlers = new Map<number, vscode.ProtocolHandler>();
constructor(
@@ -23,11 +24,17 @@ export class ExtHostUrls implements ExtHostUrlsShape {
}
registerProtocolHandler(extensionId: string, handler: vscode.ProtocolHandler): vscode.Disposable {
if (this.handles.has(extensionId)) {
throw new Error(`Protocol handler already registered for extension ${extensionId}`);
}
const handle = ExtHostUrls.HandlePool++;
this.handles.add(extensionId);
this.handlers.set(handle, handler);
this._proxy.$registerProtocolHandler(handle, extensionId);
return toDisposable(() => {
this.handles.delete(extensionId);
this.handlers.delete(handle);
this._proxy.$unregisterProtocolHandler(handle);
});

View File

@@ -10,6 +10,7 @@ import * as typeConverters from 'vs/workbench/api/node/extHostTypeConverters';
import { Position } from 'vs/platform/editor/common/editor';
import { TPromise } from 'vs/base/common/winjs.base';
import { Disposable } from './extHostTypes';
import URI from 'vs/base/common/uri';
export class ExtHostWebview implements vscode.Webview {
private readonly _handle: WebviewPanelHandle;
@@ -171,9 +172,11 @@ export class ExtHostWebviewPanel implements vscode.WebviewPanel {
return this._proxy.$postMessage(this._handle, message);
}
public reveal(viewColumn?: vscode.ViewColumn): void {
public reveal(viewColumn?: vscode.ViewColumn, preserveFocus?: boolean): void {
this.assertNotDisposed();
this._proxy.$reveal(this._handle, viewColumn ? typeConverters.fromViewColumn(viewColumn) : undefined);
this._proxy.$reveal(this._handle,
viewColumn ? typeConverters.ViewColumn.from(viewColumn) : undefined,
!!preserveFocus);
}
private assertNotDisposed() {
@@ -200,12 +203,20 @@ export class ExtHostWebviews implements ExtHostWebviewsShape {
createWebview(
viewType: string,
title: string,
viewColumn: vscode.ViewColumn,
options: vscode.WebviewPanelOptions & vscode.WebviewOptions,
extensionFolderPath: string
showOptions: vscode.ViewColumn | { viewColumn: vscode.ViewColumn, preserveFocus?: boolean },
options: (vscode.WebviewPanelOptions & vscode.WebviewOptions) | undefined,
extensionLocation: URI
): vscode.WebviewPanel {
options = options || {};
const viewColumn = typeof showOptions === 'object' ? showOptions.viewColumn : showOptions;
const webviewShowOptions = {
viewColumn: typeConverters.ViewColumn.from(viewColumn),
preserveFocus: typeof showOptions === 'object' && !!showOptions.preserveFocus
};
const handle = ExtHostWebviews.webviewHandlePool++ + '';
this._proxy.$createWebviewPanel(handle, viewType, title, typeConverters.fromViewColumn(viewColumn), options, extensionFolderPath);
this._proxy.$createWebviewPanel(handle, viewType, title, webviewShowOptions, options, extensionLocation);
const webview = new ExtHostWebview(handle, this._proxy, options);
const panel = new ExtHostWebviewPanel(handle, this._proxy, viewType, title, viewColumn, options, webview);
@@ -240,7 +251,7 @@ export class ExtHostWebviews implements ExtHostWebviewsShape {
$onDidChangeWebviewPanelViewState(handle: WebviewPanelHandle, visible: boolean, position: Position): void {
const panel = this.getWebviewPanel(handle);
if (panel) {
const viewColumn = typeConverters.toViewColumn(position);
const viewColumn = typeConverters.ViewColumn.to(position);
if (panel.visible !== visible || panel.viewColumn !== viewColumn) {
panel._setVisible(visible);
panel._setViewColumn(viewColumn);
@@ -272,28 +283,12 @@ export class ExtHostWebviews implements ExtHostWebviewsShape {
}
const webview = new ExtHostWebview(webviewHandle, this._proxy, options);
const revivedPanel = new ExtHostWebviewPanel(webviewHandle, this._proxy, viewType, title, typeConverters.toViewColumn(position), options, webview);
const revivedPanel = new ExtHostWebviewPanel(webviewHandle, this._proxy, viewType, title, typeConverters.ViewColumn.to(position), options, webview);
this._webviewPanels.set(webviewHandle, revivedPanel);
return serializer.deserializeWebviewPanel(revivedPanel, state);
}
$serializeWebviewPanel(
webviewHandle: WebviewPanelHandle
): Thenable<any> {
const panel = this.getWebviewPanel(webviewHandle);
if (!panel) {
return TPromise.as(undefined);
}
const serialzer = this._serializers.get(panel.viewType);
if (!serialzer) {
return TPromise.as(undefined);
}
return serialzer.serializeWebviewPanel(panel);
}
private getWebviewPanel(handle: WebviewPanelHandle): ExtHostWebviewPanel | undefined {
return this._webviewPanels.get(handle);
}
}
}