|
| 1 | +import * as vscode from 'vscode'; |
| 2 | +import { Commands } from './commands'; |
| 3 | +import { getJavaConfiguration } from './utils'; |
| 4 | + |
| 5 | +export function registerSemanticTokensProvider(context: vscode.ExtensionContext) { |
| 6 | + if (isSemanticHTokensEnabled()) { |
| 7 | + getSemanticTokensLegend().then(legend => { |
| 8 | + const semanticTokensProviderDisposable = vscode.languages.registerDocumentSemanticTokensProvider({ scheme: 'file', language: 'java' }, semanticTokensProvider, legend); |
| 9 | + context.subscriptions.push(semanticTokensProviderDisposable); |
| 10 | + onceSemanticTokenEnabledChange(context, semanticTokensProviderDisposable); |
| 11 | + }); |
| 12 | + } else { |
| 13 | + onceSemanticTokenEnabledChange(context, undefined); |
| 14 | + } |
| 15 | +} |
| 16 | + |
| 17 | +class SemanticTokensProvider implements vscode.DocumentSemanticTokensProvider { |
| 18 | + async provideDocumentSemanticTokens(document: vscode.TextDocument, token: vscode.CancellationToken): Promise<vscode.SemanticTokens> { |
| 19 | + const response = await vscode.commands.executeCommand(Commands.EXECUTE_WORKSPACE_COMMAND, Commands.PROVIDE_SEMANTIC_TOKENS, document.uri.toString()); |
| 20 | + if (token.isCancellationRequested) { |
| 21 | + return undefined; |
| 22 | + } |
| 23 | + return response as vscode.SemanticTokens; |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +const semanticTokensProvider = new SemanticTokensProvider(); |
| 28 | + |
| 29 | +async function getSemanticTokensLegend(): Promise<vscode.SemanticTokensLegend | undefined> { |
| 30 | + const response = await vscode.commands.executeCommand(Commands.EXECUTE_WORKSPACE_COMMAND, Commands.GET_SEMANTIC_TOKENS_LEGEND) as vscode.SemanticTokensLegend; |
| 31 | + if (response && response.tokenModifiers !== undefined && response.tokenTypes !== undefined) { |
| 32 | + return new vscode.SemanticTokensLegend(response.tokenTypes, response.tokenModifiers); |
| 33 | + } |
| 34 | + return undefined; |
| 35 | +} |
| 36 | + |
| 37 | +function onceSemanticTokenEnabledChange(context: vscode.ExtensionContext, registeredDisposable?: vscode.Disposable) { |
| 38 | + const configChangeListener = vscode.workspace.onDidChangeConfiguration(e => { |
| 39 | + configChangeListener.dispose(); |
| 40 | + if (e.affectsConfiguration('java.semanticHighlighting.enabled')) { |
| 41 | + if (isSemanticHTokensEnabled()) { |
| 42 | + // turn on |
| 43 | + registerSemanticTokensProvider(context); |
| 44 | + } else if (registeredDisposable) { |
| 45 | + // turn off |
| 46 | + registeredDisposable.dispose(); |
| 47 | + } |
| 48 | + onceSemanticTokenEnabledChange(context); |
| 49 | + } |
| 50 | + }); |
| 51 | +} |
| 52 | + |
| 53 | +function isSemanticHTokensEnabled(): boolean { |
| 54 | + const config = getJavaConfiguration(); |
| 55 | + const section = 'semanticHighlighting.enabled'; |
| 56 | + return config.get(section); |
| 57 | +} |
0 commit comments