Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[plug-in] languages.registerCodeLensProvider API #3414

Merged
merged 1 commit into from
Nov 8, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Change Log

## v0.3.17
- [plug-in] added `languages.registerCodeLensProvider` Plug-in API


## v0.3.16
- [plug-in] added `DocumentLinkProvider` Plug-in API
- [plug-in] Terminal.sendText API adds a new line to the text being sent to the terminal if `addNewLine` parameter wasn't specified
Expand Down
6 changes: 6 additions & 0 deletions packages/plugin-ext/src/api/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,12 @@ export interface DocumentLinkProvider {
resolveLink?: (link: DocumentLink, token: monaco.CancellationToken) => DocumentLink | PromiseLike<DocumentLink[]>;
}

export interface CodeLensSymbol {
range: Range;
id?: string;
command?: Command;
}

export interface CodeAction {
title: string;
command?: Command;
Expand Down
5 changes: 5 additions & 0 deletions packages/plugin-ext/src/api/plugin-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import {
Definition,
DefinitionLink,
DocumentLink,
CodeLensSymbol,
Command,
TextEdit
} from './model';
Expand Down Expand Up @@ -740,6 +741,8 @@ export interface LanguagesExt {
): Promise<ModelSingleEditOperation[] | undefined>;
$provideDocumentLinks(handle: number, resource: UriComponents): Promise<DocumentLink[] | undefined>;
$resolveDocumentLink(handle: number, link: DocumentLink): Promise<DocumentLink | undefined>;
$provideCodeLenses(handle: number, resource: UriComponents): Promise<CodeLensSymbol[] | undefined>;
$resolveCodeLens(handle: number, resource: UriComponents, symbol: CodeLensSymbol): Promise<CodeLensSymbol | undefined>;
$provideCodeActions(
handle: number,
resource: UriComponents,
Expand All @@ -763,6 +766,8 @@ export interface LanguagesMain {
$registerRangeFormattingProvider(handle: number, selector: SerializedDocumentFilter[]): void;
$registerOnTypeFormattingProvider(handle: number, selector: SerializedDocumentFilter[], autoFormatTriggerCharacters: string[]): void;
$registerDocumentLinkProvider(handle: number, selector: SerializedDocumentFilter[]): void;
$registerCodeLensSupport(handle: number, selector: SerializedDocumentFilter[], eventHandle?: number): void;
$emitCodeLensEvent(eventHandle: number, event?: any): void;
}

export const PLUGIN_RPC_CONTEXT = {
Expand Down
38 changes: 37 additions & 1 deletion packages/plugin-ext/src/main/browser/languages-main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import { fromLanguageSelector } from '../../plugin/type-converters';
import { UriComponents } from '../../common/uri-components';
import { LanguageSelector } from '../../plugin/languages';
import { DocumentFilter, MonacoModelIdentifier, testGlob, getLanguages } from 'monaco-languageclient/lib';
import { DisposableCollection } from '@theia/core';
import { DisposableCollection, Emitter } from '@theia/core';

export class LanguagesMainImpl implements LanguagesMain {

Expand Down Expand Up @@ -179,6 +179,42 @@ export class LanguagesMainImpl implements LanguagesMain {
};
}

$registerCodeLensSupport(handle: number, selector: SerializedDocumentFilter[], eventHandle: number): void {
const languageSelector = fromLanguageSelector(selector);
const lensProvider = this.createCodeLensProvider(handle, languageSelector);

if (typeof eventHandle === 'number') {
const emitter = new Emitter<monaco.languages.CodeLensProvider>();
this.disposables.set(eventHandle, emitter);
lensProvider.onDidChange = emitter.event;
}

const disposable = new DisposableCollection();
for (const language of getLanguages()) {
if (this.matchLanguage(languageSelector, language)) {
disposable.push(monaco.languages.registerCodeLensProvider(language, lensProvider));
}
}
this.disposables.set(handle, disposable);
}

protected createCodeLensProvider(handle: number, selector: LanguageSelector | undefined): monaco.languages.CodeLensProvider {
return {
provideCodeLenses: (model, token) =>
this.proxy.$provideCodeLenses(handle, model.uri).then(v => v!)
,
resolveCodeLens: (model, codeLens, token) =>
this.proxy.$resolveCodeLens(handle, model.uri, codeLens).then(v => v!)
};
}

$emitCodeLensEvent(eventHandle: number, event?: any): void {
const obj = this.disposables.get(eventHandle);
if (obj instanceof Emitter) {
obj.fire(event);
}
}

protected createDefinitionProvider(handle: number, selector: LanguageSelector | undefined): monaco.languages.DefinitionProvider {
return {
provideDefinition: (model, position, token) => {
Expand Down
81 changes: 81 additions & 0 deletions packages/plugin-ext/src/plugin/command-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ import * as theia from '@theia/plugin';
import { CommandRegistryExt, PLUGIN_RPC_CONTEXT as Ext, CommandRegistryMain } from '../api/plugin-api';
import { RPCProtocol } from '../api/rpc-protocol';
import { Disposable } from './types-impl';
import { Command } from '../api/model';
import { ObjectIdentifier } from '../common/object-identifier';

// tslint:disable-next-line:no-any
export type Handler = <T>(...args: any[]) => T | PromiseLike<T>;
Expand All @@ -26,8 +28,15 @@ export class CommandRegistryImpl implements CommandRegistryExt {
private proxy: CommandRegistryMain;
private commands = new Map<string, Handler>();

private readonly converter: CommandsConverter;

constructor(rpc: RPCProtocol) {
this.proxy = rpc.getProxy(Ext.COMMAND_REGISTRY_MAIN);
this.converter = new CommandsConverter(this);
}

getConverter(): CommandsConverter {
return this.converter;
}

registerCommand(command: theia.Command, handler?: Handler): Disposable {
Expand Down Expand Up @@ -87,3 +96,75 @@ export class CommandRegistryImpl implements CommandRegistryExt {
}
}
}

/** Converter between internal and api commands. */
export class CommandsConverter {
azatsarynnyy marked this conversation as resolved.
Show resolved Hide resolved

private readonly delegatingCommandId: string;

private cacheId = 0;
private cache = new Map<number, theia.Command>();

constructor(private readonly commands: CommandRegistryImpl) {
this.delegatingCommandId = `_internal_command_delegation_${Date.now()}`;
this.commands.registerHandler(this.delegatingCommandId, this.executeConvertedCommand);
}

toInternal(command: theia.Command | undefined): Command | undefined {
if (!command || !command.label) {
return undefined;
}

const result: Command = {
id: command.id,
title: command.label
};

if (command.id && !CommandsConverter.isFalsyOrEmpty(command.arguments)) {
const id = this.cacheId++;
ObjectIdentifier.mixin(result, id);
this.cache.set(id, command);

result.id = this.delegatingCommandId;
result.arguments = [id];
}

if (command.tooltip) {
result.tooltip = command.tooltip;
}

return result;
}

fromInternal(command: Command | undefined): theia.Command | undefined {
if (!command) {
return undefined;
}

const id = ObjectIdentifier.of(command);
if (typeof id === 'number') {
return this.cache.get(id);
} else {
return {
id: command.id,
label: command.title,
arguments: command.arguments
};
}
}

private executeConvertedCommand(...args: any[]): PromiseLike<any> {
const actualCmd = this.cache.get(args[0]);
if (!actualCmd) {
return Promise.resolve(undefined);
azatsarynnyy marked this conversation as resolved.
Show resolved Hide resolved
}
return this.commands.executeCommand(actualCmd.id, actualCmd.arguments || []);
}

/**
* @returns `false` if the provided object is an array and not empty.
*/
private static isFalsyOrEmpty(obj: any): boolean {
return !Array.isArray(obj) || (<Array<any>>obj).length === 0;
}
}
30 changes: 26 additions & 4 deletions packages/plugin-ext/src/plugin/languages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ import {
FormattingOptions,
Definition,
DefinitionLink,
DocumentLink
DocumentLink,
CodeLensSymbol
} from '../api/model';
import { CompletionAdapter } from './languages/completion';
import { Diagnostics } from './languages/diagnostics';
Expand All @@ -57,6 +58,8 @@ import { OnTypeFormattingAdapter } from './languages/on-type-formatting';
import { DefinitionAdapter } from './languages/definition';
import { CodeActionAdapter } from './languages/code-action';
import { LinkProviderAdapter } from './languages/link-provider';
import { CodeLensAdapter } from './languages/lens';
import { CommandRegistryImpl } from './command-registry';

type Adapter = CompletionAdapter |
SignatureHelpAdapter |
Expand All @@ -65,6 +68,8 @@ type Adapter = CompletionAdapter |
RangeFormattingAdapter |
OnTypeFormattingAdapter |
DefinitionAdapter |
LinkProviderAdapter |
CodeLensAdapter |
CodeActionAdapter |
LinkProviderAdapter;

Expand All @@ -77,7 +82,7 @@ export class LanguagesExtImpl implements LanguagesExt {
private callId = 0;
private adaptersMap = new Map<number, Adapter>();

constructor(rpc: RPCProtocol, private readonly documents: DocumentsExtImpl) {
constructor(rpc: RPCProtocol, private readonly documents: DocumentsExtImpl, private readonly commands: CommandRegistryImpl) {
this.proxy = rpc.getProxy(PLUGIN_RPC_CONTEXT.LANGUAGES_MAIN);
this.diagnostics = new Diagnostics(rpc);
}
Expand Down Expand Up @@ -317,8 +322,25 @@ export class LanguagesExtImpl implements LanguagesExt {

// ### Code Lens Provider begin
registerCodeLensProvider(selector: theia.DocumentSelector, provider: theia.CodeLensProvider): theia.Disposable {
// FIXME: to implement
return new Disposable(() => { });
const callId = this.addNewAdapter(new CodeLensAdapter(provider, this.documents, this.commands.getConverter()));
const eventHandle = typeof provider.onDidChangeCodeLenses === 'function' ? this.nextCallId() : undefined;
this.proxy.$registerCodeLensSupport(callId, this.transformDocumentSelector(selector), eventHandle);
let result = this.createDisposable(callId);

if (eventHandle !== undefined && provider.onDidChangeCodeLenses) {
const subscription = provider.onDidChangeCodeLenses(e => this.proxy.$emitCodeLensEvent(eventHandle));
result = Disposable.from(result, subscription);
}

return result;
}

$provideCodeLenses(handle: number, resource: UriComponents): Promise<CodeLensSymbol[] | undefined> {
return this.withAdapter(handle, CodeLensAdapter, adapter => adapter.provideCodeLenses(URI.revive(resource)));
}

$resolveCodeLens(handle: number, resource: UriComponents, symbol: CodeLensSymbol): Promise<CodeLensSymbol | undefined> {
return this.withAdapter(handle, CodeLensAdapter, adapter => adapter.resolveCodeLens(URI.revive(resource), symbol));
}
// ### Code Lens Provider end

Expand Down
83 changes: 83 additions & 0 deletions packages/plugin-ext/src/plugin/languages/lens.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/********************************************************************************
* Copyright (C) 2018 Red Hat, Inc. and others.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the Eclipse
* Public License v. 2.0 are satisfied: GNU General Public License, version 2
* with the GNU Classpath Exception which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
********************************************************************************/

import URI from 'vscode-uri/lib/umd';
import * as theia from '@theia/plugin';
import { DocumentsExtImpl } from '../documents';
import { CodeLensSymbol } from '../../api/model';
import * as Converter from '../type-converters';
import { ObjectIdentifier } from '../../common/object-identifier';
import { createToken } from '../token-provider';
import { CommandsConverter } from '../command-registry';

/** Adapts the calls from main to extension thread for providing/resolving the code lenses. */
export class CodeLensAdapter {
azatsarynnyy marked this conversation as resolved.
Show resolved Hide resolved

private static readonly BAD_CMD: theia.Command = { id: 'missing', label: '<<MISSING COMMAND>>' };

private cacheId = 0;
private cache = new Map<number, theia.CodeLens>();

constructor(
private readonly provider: theia.CodeLensProvider,
private readonly documents: DocumentsExtImpl,
private readonly commands: CommandsConverter
) { }

provideCodeLenses(resource: URI): Promise<CodeLensSymbol[] | undefined> {
const document = this.documents.getDocumentData(resource);
if (!document) {
return Promise.reject(new Error(`There is no document for ${resource}`));
}

const doc = document.document;

return Promise.resolve(this.provider.provideCodeLenses(doc, createToken())).then(lenses => {
if (Array.isArray(lenses)) {
return lenses.map(lens => {
const id = this.cacheId++;
const lensSymbol = ObjectIdentifier.mixin({
range: Converter.fromRange(lens.range)!,
command: this.commands.toInternal(lens.command)
}, id);
this.cache.set(id, lens);
return lensSymbol;
});
}
return undefined;
});
}

resolveCodeLens(resource: URI, symbol: CodeLensSymbol): Promise<CodeLensSymbol | undefined> {
const lens = this.cache.get(ObjectIdentifier.of(symbol));
if (!lens) {
return Promise.resolve(undefined);
}

let resolve: Promise<theia.CodeLens | undefined>;
if (typeof this.provider.resolveCodeLens !== 'function' || lens.isResolved) {
resolve = Promise.resolve(lens);
} else {
resolve = Promise.resolve(this.provider.resolveCodeLens(lens, createToken()));
}

return resolve.then(newLens => {
newLens = newLens || lens;
symbol.command = this.commands.toInternal(newLens.command || CodeLensAdapter.BAD_CMD);
return symbol;
});
}
}
2 changes: 1 addition & 1 deletion packages/plugin-ext/src/plugin/plugin-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ export function createAPIFactory(
const statusBarMessageRegistryExt = new StatusBarMessageRegistryExt(rpc);
const terminalExt = rpc.set(MAIN_RPC_CONTEXT.TERMINAL_EXT, new TerminalServiceExtImpl(rpc));
const outputChannelRegistryExt = new OutputChannelRegistryExt(rpc);
const languagesExt = rpc.set(MAIN_RPC_CONTEXT.LANGUAGES_EXT, new LanguagesExtImpl(rpc, documents));
const languagesExt = rpc.set(MAIN_RPC_CONTEXT.LANGUAGES_EXT, new LanguagesExtImpl(rpc, documents, commandRegistry));
const treeViewsExt = rpc.set(MAIN_RPC_CONTEXT.TREE_VIEWS_EXT, new TreeViewsExtImpl(rpc, commandRegistry));

return function (plugin: InternalPlugin): typeof theia {
Expand Down
21 changes: 20 additions & 1 deletion packages/plugin/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -533,7 +533,26 @@ const disposable = theia.languages.registerDocumentLinkProvider(documentsSelecto

...

function provideLinks(document: theia.TextDocument): theia.ProviderResult<theia.DocumentLink> {
function provideLinks(document: theia.TextDocument): theia.ProviderResult<theia.DocumentLink[]> {
// code here
}
```

#### Code Lens Provider

A code lens provider allows to add a custom lens detection logic.

Example of code lens provider registration:

```typescript
const documentsSelector: theia.DocumentSelector = { scheme: 'file', language: 'typescript' };
const provider = { provideCodeLenses: provideLenses };

const disposable = theia.languages.registerCodeLensProvider(documentsSelector, provider);

...

function provideLenses(document: theia.TextDocument): theia.ProviderResult<theia.CodeLens[]> {
// code here
}
```