Skip to content
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
2 changes: 1 addition & 1 deletion src/lsptoolshost/activate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ export async function activateRoslynLanguageServer(
registerCodeActionFixAllCommands(context, languageServer, _channel);

registerRazorCommands(context, languageServer);
registerRazorEndpoints(context, languageServer, razorLogger);
registerRazorEndpoints(context, languageServer, razorLogger, platformInfo);

registerUnitTestingCommands(context, languageServer);

Expand Down
24 changes: 24 additions & 0 deletions src/lsptoolshost/razor/htmlDocument.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import * as vscode from 'vscode';
import { getUriPath } from '../../razor/src/uriPaths';

export class HtmlDocument {
public readonly path: string;
private content = '';

public constructor(public readonly uri: vscode.Uri) {
this.path = getUriPath(uri);
}

public getContent() {
return this.content;
}

public setContent(content: string) {
this.content = content;
}
}
49 changes: 49 additions & 0 deletions src/lsptoolshost/razor/htmlDocumentContentProvider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import * as vscode from 'vscode';
import { HtmlDocumentManager } from './htmlDocumentManager';
import { RazorLogger } from '../../razor/src/razorLogger';
import { getUriPath } from '../../razor/src/uriPaths';

export class HtmlDocumentContentProvider implements vscode.TextDocumentContentProvider {
public static readonly scheme = 'razor-html';

private readonly onDidChangeEmitter: vscode.EventEmitter<vscode.Uri> = new vscode.EventEmitter<vscode.Uri>();

constructor(private readonly documentManager: HtmlDocumentManager, private readonly logger: RazorLogger) {}

public get onDidChange() {
return this.onDidChangeEmitter.event;
}

public fireDidChange(uri: vscode.Uri) {
this.onDidChangeEmitter.fire(uri);
}

public provideTextDocumentContent(uri: vscode.Uri) {
const document = this.findDocument(uri);
if (!document) {
// Document was removed from the document manager, meaning there's no more content for this
// file. Report an empty document.
this.logger.logVerbose(
`Could not find document '${getUriPath(
uri
)}' when updating the HTML buffer. This typically happens when a document is removed.`
);
return '';
}

return document.getContent();
}

private findDocument(uri: vscode.Uri) {
const projectedPath = getUriPath(uri);

return this.documentManager.documents.find(
(document) => document.path.localeCompare(projectedPath, undefined, { sensitivity: 'base' }) === 0
);
}
}
127 changes: 127 additions & 0 deletions src/lsptoolshost/razor/htmlDocumentManager.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import * as vscode from 'vscode';
import { RazorLogger } from '../../razor/src/razorLogger';
import { PlatformInformation } from '../../shared/platform';
import { getUriPath } from '../../razor/src/uriPaths';
import { virtualHtmlSuffix } from '../../razor/src/razorConventions';
import { HtmlDocumentContentProvider } from './htmlDocumentContentProvider';
import { HtmlDocument } from './htmlDocument';

export class HtmlDocumentManager {
private readonly htmlDocuments: { [hostDocumentPath: string]: HtmlDocument } = {};
private readonly contentProvider: HtmlDocumentContentProvider;

constructor(private readonly platformInfo: PlatformInformation, private readonly logger: RazorLogger) {
this.contentProvider = new HtmlDocumentContentProvider(this, this.logger);
}

public get documents() {
return Object.values(this.htmlDocuments);
}

public register() {
const didCloseRegistration = vscode.workspace.onDidCloseTextDocument(async (document) => {
// We log when a virtual document is closed just in case it helps track down future bugs
if (document.uri.scheme === HtmlDocumentContentProvider.scheme) {
this.logger.logVerbose(`Virtual document '${document.uri}' timed out.`);
return;
}

// When a Razor document is closed, only then can we be sure its okay to remove the virtual document.
if (document.languageId === 'aspnetcorerazor') {
this.logger.logVerbose(`Document '${document.uri}' was closed.`);

await this.closeDocument(document.uri);

// TODO: Send a notification back to the server so it can cancel any pending sync requests and clear its cache.
}
});

const providerRegistration = vscode.workspace.registerTextDocumentContentProvider(
HtmlDocumentContentProvider.scheme,
this.contentProvider
);

return vscode.Disposable.from(didCloseRegistration, providerRegistration);
}

public async updateDocumentText(uri: vscode.Uri, text: string) {
const document = await this.getDocument(uri);

this.logger.logVerbose(`New content for '${uri}', updating '${document.path}'.`);

document.setContent(text);

this.contentProvider.fireDidChange(document.uri);
}

private async closeDocument(uri: vscode.Uri) {
const document = await this.findDocument(uri);

if (document) {
this.logger.logVerbose(`Removing '${document.uri}' from the document manager.`);

delete this.htmlDocuments[document.path];
}
}

public async getDocument(uri: vscode.Uri): Promise<HtmlDocument> {
let document = this.findDocument(uri);

// This might happen in the case that a file is opened outside the workspace
if (!document) {
this.logger.logMessage(
`File '${uri}' didn't exist in the Razor document list. This is likely because it's from outside the workspace.`
);
document = this.addDocument(uri);
}

await vscode.workspace.openTextDocument(document.uri);

return document!;
}

private addDocument(uri: vscode.Uri): HtmlDocument {
let document = this.findDocument(uri);
if (document) {
this.logger.logMessage(`Skipping document creation for '${document.path}' because it already exists.`);
return document;
}

document = this.createDocument(uri);
this.htmlDocuments[document.path] = document;

return document;
}

private findDocument(uri: vscode.Uri): HtmlDocument | undefined {
let path = getUriPath(uri);

// We might be passed a Razor document Uri, but we store and manage Html projected documents.
if (uri.scheme !== HtmlDocumentContentProvider.scheme) {
path = `${path}${virtualHtmlSuffix}`;
}

if (this.platformInfo.isLinux()) {
return this.htmlDocuments[path];
}

return Object.values(this.htmlDocuments).find(
(document) => document.path.localeCompare(path, undefined, { sensitivity: 'base' }) === 0
);
}

private createDocument(uri: vscode.Uri) {
uri = uri.with({
scheme: HtmlDocumentContentProvider.scheme,
path: `${uri.path}${virtualHtmlSuffix}`,
});
const projectedDocument = new HtmlDocument(uri);

return projectedDocument;
}
}
10 changes: 10 additions & 0 deletions src/lsptoolshost/razor/htmlUpdateParameters.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import { TextDocumentIdentifier } from 'vscode-languageserver-protocol';

export class HtmlUpdateParameters {
constructor(public readonly textDocument: TextDocumentIdentifier, public readonly text: string) {}
}
64 changes: 62 additions & 2 deletions src/lsptoolshost/razor/razorEndpoints.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,76 @@

import { RoslynLanguageServer } from '../server/roslynLanguageServer';
import * as vscode from 'vscode';
import { LogMessageParams, NotificationType } from 'vscode-languageclient';
import {
ColorInformation,
ColorPresentationParams,
ColorPresentationRequest,
DocumentColorParams,
DocumentColorRequest,
LogMessageParams,
NotificationType,
RequestType,
} from 'vscode-languageclient';
import { RazorLogger } from '../../razor/src/razorLogger';
import { HtmlUpdateParameters } from './htmlUpdateParameters';
import { UriConverter } from '../utils/uriConverter';
import { PlatformInformation } from '../../shared/platform';
import { HtmlDocumentManager } from './htmlDocumentManager';
import { DocumentColorHandler } from '../../razor/src/documentColor/documentColorHandler';
import { razorOptions } from '../../shared/options';
import { ColorPresentationHandler } from '../../razor/src/colorPresentation/colorPresentationHandler';
import { ColorPresentation } from 'vscode-html-languageservice';

export function registerRazorEndpoints(
context: vscode.ExtensionContext,
languageServer: RoslynLanguageServer,
razorLogger: RazorLogger
razorLogger: RazorLogger,
platformInfo: PlatformInformation
) {
const logNotificationType = new NotificationType<LogMessageParams>('razor/log');
languageServer.registerOnNotificationWithParams(logNotificationType, (params) =>
razorLogger.log(params.message, params.type)
);

if (!razorOptions.cohostingEnabled) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need to remove registration of dynamicFile endpoints if cohosting is on?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I think so. I think we never call them (though tbh I've put almost no effort into initialization yet)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can be another pr for sure

return;
}

const documentManager = new HtmlDocumentManager(platformInfo, razorLogger);
context.subscriptions.push(documentManager.register());

registerRequestHandler<HtmlUpdateParameters, void>('razor/updateHtml', async (params) => {
const uri = UriConverter.deserialize(params.textDocument.uri);
await documentManager.updateDocumentText(uri, params.text);
});

registerRequestHandler<DocumentColorParams, ColorInformation[]>(DocumentColorRequest.method, async (params) => {
const uri = UriConverter.deserialize(params.textDocument.uri);
const document = await documentManager.getDocument(uri);

return await DocumentColorHandler.doDocumentColorRequest(document.uri);
});

registerRequestHandler<ColorPresentationParams, ColorPresentation[]>(
ColorPresentationRequest.method,
async (params) => {
const uri = UriConverter.deserialize(params.textDocument.uri);
const document = await documentManager.getDocument(uri);

return await ColorPresentationHandler.doColorPresentationRequest(document.uri, params);
}
);

// Helper method that registers a request handler, and logs errors to the Razor logger.
function registerRequestHandler<Params, Result>(method: string, invocation: (params: Params) => Promise<Result>) {
const requestType = new RequestType<Params, Result, Error>(method);
languageServer.registerOnRequest(requestType, async (params) => {
try {
return await invocation(params);
} catch (error) {
razorLogger.logError(`Error: ${error}`, error);
return undefined;
}
});
}
}
38 changes: 23 additions & 15 deletions src/razor/src/colorPresentation/colorPresentationHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,30 +54,38 @@ export class ColorPresentationHandler {
return this.emptyColorInformationResponse;
}

const color = new vscode.Color(
colorPresentationParams.color.red,
colorPresentationParams.color.green,
colorPresentationParams.color.blue,
colorPresentationParams.color.alpha
);
const virtualHtmlUri = razorDocument.htmlDocument.uri;

const colorPresentations = await vscode.commands.executeCommand<vscode.ColorPresentation[]>(
'vscode.executeColorPresentationProvider',
color,
new ColorPresentationContext(virtualHtmlUri, colorPresentationParams.range)
);

const serializableColorPresentations = this.SerializeColorPresentations(colorPresentations);
return serializableColorPresentations;
return await ColorPresentationHandler.doColorPresentationRequest(virtualHtmlUri, colorPresentationParams);
} catch (error) {
this.logger.logWarning(`${ColorPresentationHandler.provideHtmlColorPresentation} failed with ${error}`);
}

return this.emptyColorInformationResponse;
}

private SerializeColorPresentations(colorPresentations: vscode.ColorPresentation[]) {
public static async doColorPresentationRequest(
virtualHtmlUri: vscode.Uri,
colorPresentationParams: SerializableColorPresentationParams
) {
const color = new vscode.Color(
colorPresentationParams.color.red,
colorPresentationParams.color.green,
colorPresentationParams.color.blue,
colorPresentationParams.color.alpha
);

const colorPresentations = await vscode.commands.executeCommand<vscode.ColorPresentation[]>(
'vscode.executeColorPresentationProvider',
color,
new ColorPresentationContext(virtualHtmlUri, colorPresentationParams.range)
);

const serializableColorPresentations = ColorPresentationHandler.SerializeColorPresentations(colorPresentations);
return serializableColorPresentations;
}

private static SerializeColorPresentations(colorPresentations: vscode.ColorPresentation[]) {
const serializableColorPresentations = new Array<SerializableColorPresentation>();
for (const colorPresentation of colorPresentations) {
let serializedTextEdit: any = null;
Expand Down
31 changes: 17 additions & 14 deletions src/razor/src/documentColor/documentColorHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,24 +67,27 @@ export class DocumentColorHandler {
}

const virtualHtmlUri = razorDocument.htmlDocument.uri;

const colorInformation = await vscode.commands.executeCommand<vscode.ColorInformation[]>(
'vscode.executeDocumentColorProvider',
virtualHtmlUri
);

const serializableColorInformation = new Array<SerializableColorInformation>();
for (const color of colorInformation) {
const serializableRange = convertRangeToSerializable(color.range);
const serializableColor = new SerializableColorInformation(serializableRange, color.color);
serializableColorInformation.push(serializableColor);
}

return serializableColorInformation;
return await DocumentColorHandler.doDocumentColorRequest(virtualHtmlUri);
} catch (error) {
this.logger.logWarning(`${DocumentColorHandler.provideHtmlDocumentColorEndpoint} failed with ${error}`);
}

return this.emptyColorInformationResponse;
}

public static async doDocumentColorRequest(virtualHtmlUri: vscode.Uri) {
const colorInformation = await vscode.commands.executeCommand<vscode.ColorInformation[]>(
'vscode.executeDocumentColorProvider',
virtualHtmlUri
);

const serializableColorInformation = new Array<SerializableColorInformation>();
for (const color of colorInformation) {
const serializableRange = convertRangeToSerializable(color.range);
const serializableColor = new SerializableColorInformation(serializableRange, color.color);
serializableColorInformation.push(serializableColor);
}

return serializableColorInformation;
}
}