diff --git a/Razor.sln b/Razor.sln index 9dc0317821c..2cac6cfe48c 100644 --- a/Razor.sln +++ b/Razor.sln @@ -66,10 +66,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.Razor. EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.Razor.LanguageServer.Test.Common", "src\Razor\test\Microsoft.AspNetCore.Razor.LanguageServer.Test.Common\Microsoft.AspNetCore.Razor.LanguageServer.Test.Common.csproj", "{9D300F9A-1F78-45C9-B4BB-476EF12E40F8}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.Razor.OmniSharpPlugin", "src\Razor\src\Microsoft.AspNetCore.Razor.OmniSharpPlugin\Microsoft.AspNetCore.Razor.OmniSharpPlugin.csproj", "{305354FD-5ED7-4E89-8B1D-58FCCA3E08AD}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.Razor.OmniSharpPlugin.Test", "src\Razor\test\Microsoft.AspNetCore.Razor.OmniSharpPlugin.Test\Microsoft.AspNetCore.Razor.OmniSharpPlugin.Test.csproj", "{4ED6CC87-11C4-4ECD-B9A1-AFC5C2DACABE}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.VisualStudio.LanguageServerClient.Razor", "src\Razor\src\Microsoft.VisualStudio.LanguageServerClient.Razor\Microsoft.VisualStudio.LanguageServerClient.Razor.csproj", "{70E70B52-EB70-42D1-B785-8618BD0B950E}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.VisualStudio.LanguageServerClient.Razor.Test", "src\Razor\test\Microsoft.VisualStudio.LanguageServerClient.Razor.Test\Microsoft.VisualStudio.LanguageServerClient.Razor.Test.csproj", "{F6E8EEA2-BDD8-4AAF-A0CE-9E33A9A7CE8E}" @@ -171,8 +167,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Compiler Tests", "Compiler EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.Razor.Microbenchmarks.Generator", "src\Compiler\perf\Microsoft.AspNetCore.Razor.Microbenchmarks.Generator\Microsoft.AspNetCore.Razor.Microbenchmarks.Generator.csproj", "{7400A168-2552-49C7-93E3-D4DAA90C216F}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp", "src\Razor\src\Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp\Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.csproj", "{3E2B6DF5-524F-4909-8A66-7F8C6383620A}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.Razor.ExternalAccess.RoslynWorkspace", "src\Razor\src\Microsoft.AspNetCore.Razor.ExternalAccess.RoslynWorkspace\Microsoft.AspNetCore.Razor.ExternalAccess.RoslynWorkspace.csproj", "{2223B8FD-D98A-47BE-94A9-6A3A6B8557B8}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.Razor.ProjectEngineHost", "src\Razor\src\Microsoft.AspNetCore.Razor.ProjectEngineHost\Microsoft.AspNetCore.Razor.ProjectEngineHost.csproj", "{2FB4801C-A083-4F08-A4FB-C4910985DE31}" @@ -409,22 +403,6 @@ Global {9D300F9A-1F78-45C9-B4BB-476EF12E40F8}.Release|Any CPU.Build.0 = Release|Any CPU {9D300F9A-1F78-45C9-B4BB-476EF12E40F8}.ReleaseNoVSIX|Any CPU.ActiveCfg = Release|Any CPU {9D300F9A-1F78-45C9-B4BB-476EF12E40F8}.ReleaseNoVSIX|Any CPU.Build.0 = Release|Any CPU - {305354FD-5ED7-4E89-8B1D-58FCCA3E08AD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {305354FD-5ED7-4E89-8B1D-58FCCA3E08AD}.Debug|Any CPU.Build.0 = Debug|Any CPU - {305354FD-5ED7-4E89-8B1D-58FCCA3E08AD}.DebugNoVSIX|Any CPU.ActiveCfg = Debug|Any CPU - {305354FD-5ED7-4E89-8B1D-58FCCA3E08AD}.DebugNoVSIX|Any CPU.Build.0 = Debug|Any CPU - {305354FD-5ED7-4E89-8B1D-58FCCA3E08AD}.Release|Any CPU.ActiveCfg = Release|Any CPU - {305354FD-5ED7-4E89-8B1D-58FCCA3E08AD}.Release|Any CPU.Build.0 = Release|Any CPU - {305354FD-5ED7-4E89-8B1D-58FCCA3E08AD}.ReleaseNoVSIX|Any CPU.ActiveCfg = Release|Any CPU - {305354FD-5ED7-4E89-8B1D-58FCCA3E08AD}.ReleaseNoVSIX|Any CPU.Build.0 = Release|Any CPU - {4ED6CC87-11C4-4ECD-B9A1-AFC5C2DACABE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {4ED6CC87-11C4-4ECD-B9A1-AFC5C2DACABE}.Debug|Any CPU.Build.0 = Debug|Any CPU - {4ED6CC87-11C4-4ECD-B9A1-AFC5C2DACABE}.DebugNoVSIX|Any CPU.ActiveCfg = Debug|Any CPU - {4ED6CC87-11C4-4ECD-B9A1-AFC5C2DACABE}.DebugNoVSIX|Any CPU.Build.0 = Debug|Any CPU - {4ED6CC87-11C4-4ECD-B9A1-AFC5C2DACABE}.Release|Any CPU.ActiveCfg = Release|Any CPU - {4ED6CC87-11C4-4ECD-B9A1-AFC5C2DACABE}.Release|Any CPU.Build.0 = Release|Any CPU - {4ED6CC87-11C4-4ECD-B9A1-AFC5C2DACABE}.ReleaseNoVSIX|Any CPU.ActiveCfg = Release|Any CPU - {4ED6CC87-11C4-4ECD-B9A1-AFC5C2DACABE}.ReleaseNoVSIX|Any CPU.Build.0 = Release|Any CPU {70E70B52-EB70-42D1-B785-8618BD0B950E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {70E70B52-EB70-42D1-B785-8618BD0B950E}.Debug|Any CPU.Build.0 = Debug|Any CPU {70E70B52-EB70-42D1-B785-8618BD0B950E}.DebugNoVSIX|Any CPU.ActiveCfg = Debug|Any CPU @@ -721,14 +699,6 @@ Global {7400A168-2552-49C7-93E3-D4DAA90C216F}.Release|Any CPU.Build.0 = Release|Any CPU {7400A168-2552-49C7-93E3-D4DAA90C216F}.ReleaseNoVSIX|Any CPU.ActiveCfg = Release|Any CPU {7400A168-2552-49C7-93E3-D4DAA90C216F}.ReleaseNoVSIX|Any CPU.Build.0 = Release|Any CPU - {3E2B6DF5-524F-4909-8A66-7F8C6383620A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {3E2B6DF5-524F-4909-8A66-7F8C6383620A}.Debug|Any CPU.Build.0 = Debug|Any CPU - {3E2B6DF5-524F-4909-8A66-7F8C6383620A}.DebugNoVSIX|Any CPU.ActiveCfg = Debug|Any CPU - {3E2B6DF5-524F-4909-8A66-7F8C6383620A}.DebugNoVSIX|Any CPU.Build.0 = Debug|Any CPU - {3E2B6DF5-524F-4909-8A66-7F8C6383620A}.Release|Any CPU.ActiveCfg = Release|Any CPU - {3E2B6DF5-524F-4909-8A66-7F8C6383620A}.Release|Any CPU.Build.0 = Release|Any CPU - {3E2B6DF5-524F-4909-8A66-7F8C6383620A}.ReleaseNoVSIX|Any CPU.ActiveCfg = Release|Any CPU - {3E2B6DF5-524F-4909-8A66-7F8C6383620A}.ReleaseNoVSIX|Any CPU.Build.0 = Release|Any CPU {2223B8FD-D98A-47BE-94A9-6A3A6B8557B8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2223B8FD-D98A-47BE-94A9-6A3A6B8557B8}.Debug|Any CPU.Build.0 = Debug|Any CPU {2223B8FD-D98A-47BE-94A9-6A3A6B8557B8}.DebugNoVSIX|Any CPU.ActiveCfg = Debug|Any CPU @@ -809,8 +779,6 @@ Global {6C8A42B5-B41C-4334-959F-684E647A24E1} = {92463391-81BE-462B-AC3C-78C6C760741F} {FBAE9975-77BE-411B-A1A3-4790C8A367EF} = {92463391-81BE-462B-AC3C-78C6C760741F} {9D300F9A-1F78-45C9-B4BB-476EF12E40F8} = {92463391-81BE-462B-AC3C-78C6C760741F} - {305354FD-5ED7-4E89-8B1D-58FCCA3E08AD} = {3C0D6505-79B3-49D0-B4C3-176F0F1836ED} - {4ED6CC87-11C4-4ECD-B9A1-AFC5C2DACABE} = {92463391-81BE-462B-AC3C-78C6C760741F} {70E70B52-EB70-42D1-B785-8618BD0B950E} = {3C0D6505-79B3-49D0-B4C3-176F0F1836ED} {F6E8EEA2-BDD8-4AAF-A0CE-9E33A9A7CE8E} = {92463391-81BE-462B-AC3C-78C6C760741F} {35FEC0EA-09B5-45D2-832D-D6FEBA364871} = {3C0D6505-79B3-49D0-B4C3-176F0F1836ED} @@ -855,7 +823,6 @@ Global {97DE8703-467C-49A7-BCE4-42FF1FEC8AC2} = {FB7C870E-A173-4F75-BE63-4EF39C79A759} {A9F9B5E5-C5C2-4860-BE56-038C70ADBAC9} = {FB7C870E-A173-4F75-BE63-4EF39C79A759} {7400A168-2552-49C7-93E3-D4DAA90C216F} = {C2C98051-0F39-47F2-80B6-E72B29159F2C} - {3E2B6DF5-524F-4909-8A66-7F8C6383620A} = {3C0D6505-79B3-49D0-B4C3-176F0F1836ED} {2223B8FD-D98A-47BE-94A9-6A3A6B8557B8} = {3C0D6505-79B3-49D0-B4C3-176F0F1836ED} {2FB4801C-A083-4F08-A4FB-C4910985DE31} = {3C0D6505-79B3-49D0-B4C3-176F0F1836ED} {70C6EAF1-202B-481B-ADD4-D30DF1396BDE} = {92463391-81BE-462B-AC3C-78C6C760741F} diff --git a/docs/ProjectsAndLayering.md b/docs/ProjectsAndLayering.md index e8829a743ef..355af513d07 100644 --- a/docs/ProjectsAndLayering.md +++ b/docs/ProjectsAndLayering.md @@ -9,7 +9,6 @@ Created with https://www.sankeymatic.com/build/ Input: ``` -OmniSharp [1] MS.AspNetCore.Razor.LanguageServer.Common RoslynWorkspace [1] ProjectEngineHost MS.AspNetCore.Razor.LanguageServer [1] MS.AspNetCore.Razor.LanguageServer.Common MS.AspNetCore.Razor.LanguageServer.Common [1] Compiler @@ -114,13 +113,6 @@ target the broadest set of frameworks. - Microsoft.VisualStudio.Mac.LanguageServices.Razor - Microsoft.VisualStudio.Mac.RazorAddin -### Visual Studio Code (OmniSharp Plug-in) - -- Target Framework: `net472` -- Projects: - - Microsoft.AspNetCore.Razor.OmniSharpPlugin - - Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp - ### Miscellaneous / Test hosting - Target Framework: net7.0 @@ -170,7 +162,3 @@ target the broadest set of frameworks. ### Visual Studio (Mac) Tests - Microsoft.VisualStudio.Mac.LanguageServices.Razor.Test (`net472`) - -### Visual Studio Code (OmniSharp Plug-in) Tests - -- Microsoft.AspNetCore.Razor.OmniSharpPlugin.Test (`net472`) diff --git a/docs/contributing/BuildFromSource.md b/docs/contributing/BuildFromSource.md index b0c2c43dd42..2d598f1e2d2 100644 --- a/docs/contributing/BuildFromSource.md +++ b/docs/contributing/BuildFromSource.md @@ -82,27 +82,7 @@ In most cases, this is because the option _Use previews of the .NET Core SDK_ in ## Building with Visual Studio Code -Note, the [Visual Studio Code C# Extension](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csharp) is required. - -1. Run `Restore.cmd` on the command line. -1. Launch the `razor` repo in VS Code. -2. Open VS Code settings (`CTRL+,`) and navigate to the `Razor > Plugin: Path` setting: -![image](https://user-images.githubusercontent.com/16968319/192892840-ae2b102c-a282-472f-b1f1-ef3dad671874.png) -3. Set path to `C:\path_to_razor_repo\artifacts\bin\Microsoft.AspNetCore.Razor.OmniSharpPlugin\Debug\net472\Microsoft.AspNetCore.Razor.OmniSharpPlugin.dll`. -4. Launch extension via `Run and Debug -> Run Extension`. -5. Install missing assets if prompted. - -### If you want to make changes within the Razor language server -1. Make the changes, then run `Build.cmd -pack`. -2. To debug through the language server code, open VS Code settings and check the box `Razor > Language Server: Debug`. -![image](https://user-images.githubusercontent.com/16968319/192892444-1e4e514a-d41a-4aea-b739-cecee48d12d6.png) -3. Attach your Visual Studio instance to `rzls.exe`. - -### If you want to make changes within Razor VS Code -(i.e. anywhere within the `Microsoft.AspNetCore.Razor.VSCode` folder) -1. Make the changes, then delete the existing `node_modules` folder within `Microsoft.AspNetCore.Razor.VSCode.Extension` if one exists. (Deleting the `node_modules` folder is supposed to be unnecessary, but there is currently a bug preventing changes from being detected - tracked by [#6788](https://github.com/dotnet/razor-tooling/issues/6788)). -2. Run `Restore.cmd`. -3. When debugging, ensure breakpoints are set within the `*.js` equivalent of a given `*.ts` file. This file can generally be found in the `node_modules` folder within `Microsoft.AspNetCore.Razor.VSCode.Extension`. +Outside of Razor's language server and C# workspace logic, the bulk of our VS Code logic now lives in the [dotnet/vscode-csharp](https://github.com/dotnet/vscode-csharp) repo. ## Building on command-line diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/.editorconfig b/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/.editorconfig deleted file mode 100644 index bb66e48ef6f..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/.editorconfig +++ /dev/null @@ -1,3 +0,0 @@ -[*.cs] -# RS0016: Add public types and members to the declared API -dotnet_diagnostic.RS0016.severity = warning \ No newline at end of file diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Document/OmniSharpBackgroundDocumentGenerator.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Document/OmniSharpBackgroundDocumentGenerator.cs deleted file mode 100644 index d2c64922a13..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Document/OmniSharpBackgroundDocumentGenerator.cs +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project; -using Microsoft.AspNetCore.Razor.Language; -using Microsoft.AspNetCore.Razor.LanguageServer; -using Microsoft.AspNetCore.Razor.LanguageServer.Common; -using Microsoft.CodeAnalysis.Razor.ProjectSystem; - -namespace Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document; - -public class OmniSharpBackgroundDocumentGenerator : IOmniSharpProjectSnapshotManagerChangeTrigger -{ - private readonly BackgroundDocumentGenerator _backgroundDocumentGenerator; - - public OmniSharpBackgroundDocumentGenerator( - OmniSharpProjectSnapshotManagerDispatcher projectSnapshotManagerDispatcher, - RemoteTextLoaderFactory remoteTextLoaderFactory, - IEnumerable documentProcessedListeners) - { - if (projectSnapshotManagerDispatcher is null) - { - throw new ArgumentNullException(nameof(projectSnapshotManagerDispatcher)); - } - - if (remoteTextLoaderFactory is null) - { - throw new ArgumentNullException(nameof(remoteTextLoaderFactory)); - } - - if (documentProcessedListeners is null) - { - throw new ArgumentNullException(nameof(documentProcessedListeners)); - } - - var wrappedListeners = documentProcessedListeners.Select(listener => new WrappedDocumentProcessedListener(remoteTextLoaderFactory, listener)); - _backgroundDocumentGenerator = new BackgroundDocumentGenerator(projectSnapshotManagerDispatcher.InternalDispatcher, wrappedListeners); - } - - public void Initialize(OmniSharpProjectSnapshotManager projectManager) - { - _backgroundDocumentGenerator.Initialize(projectManager.InternalProjectSnapshotManager); - } - - private class WrappedDocumentProcessedListener : DocumentProcessedListener - { - private readonly RemoteTextLoaderFactory _remoteTextLoaderFactory; - private readonly OmniSharpDocumentProcessedListener _innerDocumentProcessedListener; - - internal WrappedDocumentProcessedListener( - RemoteTextLoaderFactory remoteTextLoaderFactory, - OmniSharpDocumentProcessedListener innerDocumentProcessedListener) - { - if (remoteTextLoaderFactory is null) - { - throw new ArgumentNullException(nameof(remoteTextLoaderFactory)); - } - - if (innerDocumentProcessedListener is null) - { - throw new ArgumentNullException(nameof(innerDocumentProcessedListener)); - } - - _remoteTextLoaderFactory = remoteTextLoaderFactory; - _innerDocumentProcessedListener = innerDocumentProcessedListener; - } - - public override void DocumentProcessed(RazorCodeDocument codeDocument, IDocumentSnapshot document) - { - var omniSharpDocument = new OmniSharpDocumentSnapshot(document); - _innerDocumentProcessedListener.DocumentProcessed(codeDocument, omniSharpDocument); - } - - public override void Initialize(ProjectSnapshotManager projectManager) - { - var omniSharpProjectManager = new OmniSharpProjectSnapshotManager((ProjectSnapshotManagerBase)projectManager, _remoteTextLoaderFactory); - _innerDocumentProcessedListener.Initialize(omniSharpProjectManager); - } - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Document/OmniSharpDocumentProcessedListener.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Document/OmniSharpDocumentProcessedListener.cs deleted file mode 100644 index 1f0ecd32874..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Document/OmniSharpDocumentProcessedListener.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project; -using Microsoft.AspNetCore.Razor.Language; - -namespace Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document; - -public abstract class OmniSharpDocumentProcessedListener -{ - public abstract void Initialize(OmniSharpProjectSnapshotManager projectManager); - - public abstract void DocumentProcessed(RazorCodeDocument codeDocument, OmniSharpDocumentSnapshot document); -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Document/OmniSharpDocumentSnapshot.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Document/OmniSharpDocumentSnapshot.cs deleted file mode 100644 index b10ec190c03..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Document/OmniSharpDocumentSnapshot.cs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project; -using Microsoft.CodeAnalysis.Razor.ProjectSystem; - -namespace Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document; - -public sealed class OmniSharpDocumentSnapshot -{ - private readonly IDocumentSnapshot _documentSnapshot; - private readonly object _projectLock; - private OmniSharpHostDocument? _hostDocument; - private OmniSharpProjectSnapshot? _project; - - internal OmniSharpDocumentSnapshot(IDocumentSnapshot documentSnapshot) - { - if (documentSnapshot is null) - { - throw new ArgumentNullException(nameof(documentSnapshot)); - } - - _documentSnapshot = documentSnapshot; - _projectLock = new object(); - } - - public OmniSharpHostDocument HostDocument - { - get - { - if (_hostDocument is null) - { - var defaultDocumentSnapshot = (DocumentSnapshot)_documentSnapshot; - var hostDocument = defaultDocumentSnapshot.State.HostDocument; - _hostDocument = new OmniSharpHostDocument(hostDocument.FilePath, hostDocument.TargetPath, hostDocument.FileKind); - } - - return _hostDocument; - } - } - - public string? FileKind => _documentSnapshot.FileKind; - - public string? FilePath => _documentSnapshot.FilePath; - - public OmniSharpProjectSnapshot Project - { - get - { - lock (_projectLock) - { - _project ??= new OmniSharpProjectSnapshot(_documentSnapshot.Project); - } - - return _project; - } - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Document/OmniSharpHostDocument.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Document/OmniSharpHostDocument.cs deleted file mode 100644 index 89d3ff53d38..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Document/OmniSharpHostDocument.cs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -using Microsoft.CodeAnalysis.Razor.ProjectSystem; - -namespace Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document; - -public sealed class OmniSharpHostDocument -{ - public OmniSharpHostDocument(string filePath, string targetPath, string kind) - { - InternalHostDocument = new HostDocument(filePath, targetPath, kind); - - if (targetPath.Contains("/")) - { - throw new FormatException("TargetPath's must use '\\' instead of '/'"); - } - - if (targetPath.StartsWith("\\", StringComparison.Ordinal)) - { - throw new FormatException("TargetPath's can't start with '\\'"); - } - } - - public string FilePath => InternalHostDocument.FilePath; - - internal string TargetPath => InternalHostDocument.TargetPath; - - internal string FileKind => InternalHostDocument.FileKind; - - internal HostDocument InternalHostDocument { get; } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Document/OmniSharpHostDocumentComparer.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Document/OmniSharpHostDocumentComparer.cs deleted file mode 100644 index 9e0efb2d09f..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Document/OmniSharpHostDocumentComparer.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.LanguageServer.Common; - -namespace Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document; - -public sealed class OmniSharpHostDocumentComparer : IEqualityComparer -{ - public static readonly OmniSharpHostDocumentComparer Instance = new(); - - private OmniSharpHostDocumentComparer() - { - } - - public bool Equals(OmniSharpHostDocument? x, OmniSharpHostDocument? y) => - HostDocumentComparer.Instance.Equals(x?.InternalHostDocument, y?.InternalHostDocument); - - public int GetHashCode(OmniSharpHostDocument hostDocument) => - HostDocumentComparer.Instance.GetHashCode(hostDocument.InternalHostDocument); -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/ExportedTagHelperResolverFactory.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/ExportedTagHelperResolverFactory.cs deleted file mode 100644 index f43283d9e7d..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/ExportedTagHelperResolverFactory.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -using System.Composition; -using Microsoft.AspNetCore.Razor.Telemetry; -using Microsoft.CodeAnalysis.Host; -using Microsoft.CodeAnalysis.Host.Mef; -using Microsoft.CodeAnalysis.Razor; - -namespace Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp; - -[Shared] -[ExportWorkspaceServiceFactory(typeof(TagHelperResolver), ServiceLayer.Default)] -internal class ExportedTagHelperResolverFactory : IWorkspaceServiceFactory -{ - private readonly ITelemetryReporter _telemetryReporter; - - [ImportingConstructor] - public ExportedTagHelperResolverFactory() - { - _telemetryReporter = new OmniSharpTelemetryReporter(); - } - - public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) - { - return new DefaultTagHelperResolver(_telemetryReporter); - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Extensions/OmniSharpRazorCodeDocumentExtensions.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Extensions/OmniSharpRazorCodeDocumentExtensions.cs deleted file mode 100644 index dac85b791d0..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Extensions/OmniSharpRazorCodeDocumentExtensions.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Language; -using Microsoft.CodeAnalysis.Razor.Workspaces.Extensions; -using Microsoft.CodeAnalysis.Text; - -namespace Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Extensions; - -public static class OmniSharpRazorCodeDocumentExtensions -{ - public static SourceText GetInternalCSharpSourceText(this RazorCodeDocument codeDocument) - { - return codeDocument.GetCSharpSourceText(); - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/FallbackRazorConfiguration.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/FallbackRazorConfiguration.cs deleted file mode 100644 index 638c05d9d90..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/FallbackRazorConfiguration.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Language; - -namespace Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp; - -public class FallbackRazorConfiguration -{ - public static RazorConfiguration SelectConfiguration(Version version) => CodeAnalysis.Razor.ProjectSystem.FallbackRazorConfiguration.SelectConfiguration(version); -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.csproj b/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.csproj deleted file mode 100644 index 35f622c9a27..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.csproj +++ /dev/null @@ -1,11 +0,0 @@ - - - $(DefaultNetCoreTargetFrameworks);$(DefaultNetFxTargetFramework) - enable - enable - - - - - - diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/OmniSharpLanguageServerFeatureOptions.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/OmniSharpLanguageServerFeatureOptions.cs deleted file mode 100644 index bf91362a471..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/OmniSharpLanguageServerFeatureOptions.cs +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.LanguageServer; -using Microsoft.CodeAnalysis.Razor.Workspaces; - -namespace Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp; - -public class OmniSharpLanguageServerFeatureOptions -{ - internal LanguageServerFeatureOptions InternalLanguageServerFeatureOptions { get; } = new DefaultLanguageServerFeatureOptions(); -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/IOmniSharpProjectSnapshotManagerChangeTrigger.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/IOmniSharpProjectSnapshotManagerChangeTrigger.cs deleted file mode 100644 index 25e726d3570..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/IOmniSharpProjectSnapshotManagerChangeTrigger.cs +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -namespace Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project; - -public interface IOmniSharpProjectSnapshotManagerChangeTrigger -{ - void Initialize(OmniSharpProjectSnapshotManager projectManager); -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/OmniSharpHostProject.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/OmniSharpHostProject.cs deleted file mode 100644 index c00640c856d..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/OmniSharpHostProject.cs +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.Language; -using Microsoft.CodeAnalysis.Razor.ProjectSystem; - -namespace Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project; - -public sealed class OmniSharpHostProject -{ - public OmniSharpHostProject(string projectFilePath, string intermediateOutputPath, RazorConfiguration razorConfiguration, string rootNamespace) - { - if (projectFilePath is null) - { - throw new ArgumentNullException(nameof(projectFilePath)); - } - - if (intermediateOutputPath is null) - { - throw new ArgumentNullException(nameof(intermediateOutputPath)); - } - - if (razorConfiguration is null) - { - throw new ArgumentNullException(nameof(razorConfiguration)); - } - - InternalHostProject = new HostProject(projectFilePath, intermediateOutputPath, razorConfiguration, rootNamespace); - } - - public OmniSharpProjectKey Key => new OmniSharpProjectKey(InternalHostProject.Key); - - internal HostProject InternalHostProject { get; } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/OmniSharpProjectChangeEventArgs.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/OmniSharpProjectChangeEventArgs.cs deleted file mode 100644 index 493b1f9f7ed..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/OmniSharpProjectChangeEventArgs.cs +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -using Microsoft.CodeAnalysis.Razor.ProjectSystem; - -namespace Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project; - -public class OmniSharpProjectChangeEventArgs : EventArgs -{ - internal OmniSharpProjectChangeEventArgs(ProjectChangeEventArgs args) : this( - OmniSharpProjectSnapshot.Convert(args.Older), - OmniSharpProjectSnapshot.Convert(args.Newer), - args.DocumentFilePath, - (OmniSharpProjectChangeKind)args.Kind) - { - } - - public OmniSharpProjectChangeEventArgs(OmniSharpProjectSnapshot? older, OmniSharpProjectSnapshot? newer, string? documentFilePath, OmniSharpProjectChangeKind kind) - { - if (older is null && newer is null) - { - throw new ArgumentException("Both projects cannot be null."); - } - - Older = older; - Newer = newer; - DocumentFilePath = documentFilePath; - Kind = kind; - } - - public OmniSharpProjectSnapshot? Older { get; } - - public OmniSharpProjectSnapshot? Newer { get; } - - public string? DocumentFilePath { get; } - - public OmniSharpProjectChangeKind Kind { get; } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/OmniSharpProjectChangeKind.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/OmniSharpProjectChangeKind.cs deleted file mode 100644 index 93cd7399257..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/OmniSharpProjectChangeKind.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -using Microsoft.CodeAnalysis.Razor.ProjectSystem; - -namespace Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project; - -public enum OmniSharpProjectChangeKind -{ - ProjectAdded = ProjectChangeKind.ProjectAdded, - ProjectRemoved = ProjectChangeKind.ProjectRemoved, - ProjectChanged = ProjectChangeKind.ProjectChanged, - DocumentAdded = ProjectChangeKind.DocumentAdded, - DocumentRemoved = ProjectChangeKind.DocumentRemoved, -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/OmniSharpProjectKey.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/OmniSharpProjectKey.cs deleted file mode 100644 index 4bb8ee82175..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/OmniSharpProjectKey.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -using Microsoft.CodeAnalysis.Razor.ProjectSystem; - -namespace Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project; - -public sealed class OmniSharpProjectKey -{ - public static OmniSharpProjectKey? From(CodeAnalysis.Project workspaceProject) - { - var key = ProjectKey.From(workspaceProject); - return key is null ? null : new(key.Value); - } - - internal ProjectKey Key { get; } - - internal OmniSharpProjectKey(ProjectKey key) - { - this.Key = key; - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/OmniSharpProjectSnapshot.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/OmniSharpProjectSnapshot.cs deleted file mode 100644 index df301316af6..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/OmniSharpProjectSnapshot.cs +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document; -using Microsoft.AspNetCore.Razor.ProjectSystem; -using Microsoft.CodeAnalysis.Razor.ProjectSystem; -using Microsoft.CodeAnalysis.Razor.Workspaces.ProjectSystem; -using Newtonsoft.Json; - -namespace Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project; - -public sealed class OmniSharpProjectSnapshot -{ - internal readonly IProjectSnapshot InternalProjectSnapshot; - - internal OmniSharpProjectSnapshot(IProjectSnapshot projectSnapshot) - { - InternalProjectSnapshot = projectSnapshot; - } - - public OmniSharpProjectKey Key => new OmniSharpProjectKey(InternalProjectSnapshot.Key); - - public string FilePath => InternalProjectSnapshot.FilePath; - - public IEnumerable DocumentFilePaths => InternalProjectSnapshot.DocumentFilePaths; - - public ProjectWorkspaceState? ProjectWorkspaceState => InternalProjectSnapshot.ProjectWorkspaceState; - - public OmniSharpDocumentSnapshot? GetDocument(string filePath) - { - var documentSnapshot = InternalProjectSnapshot.GetDocument(filePath); - if (documentSnapshot is null) - { - return null; - } - - var internalDocumentSnapshot = new OmniSharpDocumentSnapshot(documentSnapshot); - return internalDocumentSnapshot; - } - - public void Serialize(string publishFilePath, JsonSerializer serializer, StreamWriter writer) - { - var projectRazorJson = InternalProjectSnapshot.ToProjectRazorJson(publishFilePath); - serializer.Serialize(writer, projectRazorJson); - } - - internal static OmniSharpProjectSnapshot? Convert(IProjectSnapshot? projectSnapshot) - { - if (projectSnapshot is null) - { - return null; - } - - return new OmniSharpProjectSnapshot(projectSnapshot); - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/OmniSharpProjectSnapshotManager.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/OmniSharpProjectSnapshotManager.cs deleted file mode 100644 index e65f036d4c2..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/OmniSharpProjectSnapshotManager.cs +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -using System.Collections.Immutable; -using Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document; -using Microsoft.AspNetCore.Razor.LanguageServer.Common; -using Microsoft.CodeAnalysis.Razor.ProjectSystem; - -namespace Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project; - -public class OmniSharpProjectSnapshotManager -{ - private readonly RemoteTextLoaderFactory _remoteTextLoaderFactory; - - internal OmniSharpProjectSnapshotManager( - ProjectSnapshotManagerBase projectSnapshotManager, - RemoteTextLoaderFactory remoteTextLoaderFactory) - { - if (projectSnapshotManager is null) - { - throw new ArgumentNullException(nameof(projectSnapshotManager)); - } - - if (remoteTextLoaderFactory is null) - { - throw new ArgumentNullException(nameof(remoteTextLoaderFactory)); - } - - InternalProjectSnapshotManager = projectSnapshotManager; - _remoteTextLoaderFactory = remoteTextLoaderFactory; - InternalProjectSnapshotManager.Changed += ProjectSnapshotManager_Changed; - } - - internal ProjectSnapshotManagerBase InternalProjectSnapshotManager { get; } - - public IReadOnlyList Projects => InternalProjectSnapshotManager.GetProjects().Select(project => OmniSharpProjectSnapshot.Convert(project)!).ToList(); - - public event EventHandler? Changed; - - public OmniSharpProjectSnapshot GetLoadedProject(OmniSharpProjectKey projectKey) - { - var projectSnapshot = InternalProjectSnapshotManager.GetLoadedProject(projectKey.Key); - // Forgiving null because we should only return null when projectSnapshot is null - var converted = OmniSharpProjectSnapshot.Convert(projectSnapshot)!; - - return converted; - } - - public ImmutableArray GetAllProjectKeys(string projectFilePath) - { - var keys = InternalProjectSnapshotManager.GetAllProjectKeys(projectFilePath); - - return ImmutableArray.Empty.AddRange(keys.Select(k => new OmniSharpProjectKey(k))); - } - - public void ProjectAdded(OmniSharpHostProject hostProject) - { - InternalProjectSnapshotManager.ProjectAdded(hostProject.InternalHostProject); - } - - public void ProjectConfigurationChanged(OmniSharpHostProject hostProject) - { - InternalProjectSnapshotManager.ProjectConfigurationChanged(hostProject.InternalHostProject); - } - - public void DocumentAdded(OmniSharpHostProject hostProject, OmniSharpHostDocument hostDocument) - { - var textLoader = _remoteTextLoaderFactory.Create(hostDocument.FilePath); - InternalProjectSnapshotManager.DocumentAdded(hostProject.InternalHostProject.Key, hostDocument.InternalHostDocument, textLoader); - } - - public void DocumentChanged(string projectFilePath, string documentFilePath) - { - var textLoader = _remoteTextLoaderFactory.Create(documentFilePath); - foreach (var projectKey in InternalProjectSnapshotManager.GetAllProjectKeys(projectFilePath)) - { - InternalProjectSnapshotManager.DocumentChanged(projectKey, documentFilePath, textLoader); - } - } - - public void DocumentRemoved(OmniSharpHostProject hostProject, OmniSharpHostDocument hostDocument) - { - InternalProjectSnapshotManager.DocumentRemoved(hostProject.InternalHostProject.Key, hostDocument.InternalHostDocument); - } - - private void ProjectSnapshotManager_Changed(object? sender, ProjectChangeEventArgs args) - { - var convertedArgs = new OmniSharpProjectChangeEventArgs(args); - Changed?.Invoke(this, convertedArgs); - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/OmniSharpProjectSnapshotManagerAccessor.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/OmniSharpProjectSnapshotManagerAccessor.cs deleted file mode 100644 index 80b7aeca4f2..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/OmniSharpProjectSnapshotManagerAccessor.cs +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.LanguageServer.Common; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Razor; -using Microsoft.CodeAnalysis.Razor.ProjectSystem; - -namespace Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project; - -public class OmniSharpProjectSnapshotManagerAccessor -{ - private readonly RemoteTextLoaderFactory _remoteTextLoaderFactory; - private readonly IEnumerable _projectChangeTriggers; - private readonly OmniSharpProjectSnapshotManagerDispatcher _projectSnapshotManagerDispatcher; - private readonly Workspace _workspace; - private OmniSharpProjectSnapshotManager? _instance; - - public OmniSharpProjectSnapshotManagerAccessor( - RemoteTextLoaderFactory remoteTextLoaderFactory, - IEnumerable projectChangeTriggers, - OmniSharpProjectSnapshotManagerDispatcher projectSnapshotManagerDispatcher, - Workspace workspace) - { - if (remoteTextLoaderFactory is null) - { - throw new ArgumentNullException(nameof(remoteTextLoaderFactory)); - } - - if (projectChangeTriggers is null) - { - throw new ArgumentNullException(nameof(projectChangeTriggers)); - } - - if (projectSnapshotManagerDispatcher is null) - { - throw new ArgumentNullException(nameof(projectSnapshotManagerDispatcher)); - } - - if (workspace is null) - { - throw new ArgumentNullException(nameof(workspace)); - } - - _remoteTextLoaderFactory = remoteTextLoaderFactory; - _projectChangeTriggers = projectChangeTriggers; - _projectSnapshotManagerDispatcher = projectSnapshotManagerDispatcher; - _workspace = workspace; - } - - public OmniSharpProjectSnapshotManager Instance - { - get - { - if (_instance is null) - { - var projectSnapshotManager = new DefaultProjectSnapshotManager( - ErrorReporter.Instance, - Array.Empty(), - _workspace); - - var instance = new OmniSharpProjectSnapshotManager(projectSnapshotManager, _remoteTextLoaderFactory); - _instance = instance; - foreach (var changeTrigger in _projectChangeTriggers) - { - changeTrigger.Initialize(instance); - } - } - - return _instance; - } - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/OmniSharpProjectSnapshotManagerDispatcher.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/OmniSharpProjectSnapshotManagerDispatcher.cs deleted file mode 100644 index 44a2554dc9f..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/OmniSharpProjectSnapshotManagerDispatcher.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -using System.Runtime.CompilerServices; -using Microsoft.CodeAnalysis.Razor; -using Microsoft.CodeAnalysis.Razor.Workspaces; - -namespace Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project; - -public class OmniSharpProjectSnapshotManagerDispatcher -{ - public OmniSharpProjectSnapshotManagerDispatcher() - { - InternalDispatcher = new InternalOmniSharpProjectSnapshotManagerDispatcher(); - } - - internal ProjectSnapshotManagerDispatcher InternalDispatcher { get; private protected set; } - - public Task RunOnDispatcherThreadAsync(Action action, CancellationToken cancellationToken) - => InternalDispatcher.RunOnDispatcherThreadAsync(action, cancellationToken); - - public TaskScheduler DispatcherScheduler => InternalDispatcher.DispatcherScheduler; - - public void AssertDispatcherThread([CallerMemberName] string? caller = null) => InternalDispatcher.AssertDispatcherThread(caller); - - private class InternalOmniSharpProjectSnapshotManagerDispatcher : ProjectSnapshotManagerDispatcherBase - { - private const string ThreadName = "Razor." + nameof(OmniSharpProjectSnapshotManagerDispatcher); - - internal InternalOmniSharpProjectSnapshotManagerDispatcher() : base(ThreadName) - { - } - - public override void LogException(Exception ex) - { - // We don't currently have logging mechanisms in place for O#. - } - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/OmniSharpProjectWorkspaceStateGenerator.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/OmniSharpProjectWorkspaceStateGenerator.cs deleted file mode 100644 index f87d8ba1ac1..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/OmniSharpProjectWorkspaceStateGenerator.cs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -using Microsoft.CodeAnalysis.Razor; - -namespace Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project; - -public class OmniSharpProjectWorkspaceStateGenerator : IOmniSharpProjectSnapshotManagerChangeTrigger -{ - // Internal for testing -#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. - internal OmniSharpProjectWorkspaceStateGenerator() -#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. - { - } - - public OmniSharpProjectWorkspaceStateGenerator(OmniSharpProjectSnapshotManagerDispatcher projectSnapshotManagerDispatcher) - { - if (projectSnapshotManagerDispatcher is null) - { - throw new ArgumentNullException(nameof(projectSnapshotManagerDispatcher)); - } - - InternalWorkspaceStateGenerator = new DefaultProjectWorkspaceStateGenerator(projectSnapshotManagerDispatcher.InternalDispatcher); - } - - internal DefaultProjectWorkspaceStateGenerator InternalWorkspaceStateGenerator { get; } - - public void Initialize(OmniSharpProjectSnapshotManager projectManager) => InternalWorkspaceStateGenerator.Initialize(projectManager.InternalProjectSnapshotManager); - - public virtual void Update(CodeAnalysis.Project workspaceProject, OmniSharpProjectSnapshot projectSnapshot) => InternalWorkspaceStateGenerator.Update(workspaceProject, projectSnapshot.InternalProjectSnapshot, CancellationToken.None); -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/OmniSharpTelemetryReporter.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/OmniSharpTelemetryReporter.cs deleted file mode 100644 index 6f4b868e72e..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/OmniSharpTelemetryReporter.cs +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -using System.Collections.Immutable; -using Microsoft.AspNetCore.Razor.Telemetry; - -namespace Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp; - -internal class OmniSharpTelemetryReporter : ITelemetryReporter -{ - public void ReportEvent(string name, Severity severity) - { - } - - public void ReportEvent(string name, Severity severity, ImmutableDictionary values) - { - } - - public void ReportFault(Exception exception, string? message, params object?[] @params) - { - } - - public IDisposable BeginBlock(string name, Severity severity) - { - return NullScope.Instance; - } - - public IDisposable BeginBlock(string name, Severity severity, ImmutableDictionary values) - { - return NullScope.Instance; - } - - public IDisposable TrackLspRequest(string lspMethodName, string lspServerName, Guid correlationId) - { - return NullScope.Instance; - } - - private class NullScope : IDisposable - { - public static NullScope Instance { get; } = new NullScope(); - private NullScope() { } - public void Dispose() { } - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/OmniSharpWorkspaceProjectStateChangeDetector.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/OmniSharpWorkspaceProjectStateChangeDetector.cs deleted file mode 100644 index 81370dd55c9..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/OmniSharpWorkspaceProjectStateChangeDetector.cs +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -using System.Diagnostics; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Razor; -using Microsoft.CodeAnalysis.Razor.ProjectSystem; -using Microsoft.CodeAnalysis.Razor.Workspaces; -using Microsoft.VisualStudio.Threading; - -namespace Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project; - -public class OmniSharpWorkspaceProjectStateChangeDetector : IOmniSharpProjectSnapshotManagerChangeTrigger -{ - public OmniSharpWorkspaceProjectStateChangeDetector( - OmniSharpProjectSnapshotManagerDispatcher projectSnapshotManagerDispatcher, - OmniSharpProjectWorkspaceStateGenerator workspaceStateGenerator, - OmniSharpLanguageServerFeatureOptions languageServerFeatureOptions) - { - if (projectSnapshotManagerDispatcher is null) - { - throw new ArgumentNullException(nameof(projectSnapshotManagerDispatcher)); - } - - if (workspaceStateGenerator is null) - { - throw new ArgumentNullException(nameof(workspaceStateGenerator)); - } - - InternalWorkspaceProjectStateChangeDetector = new ProjectSnapshotManagerWorkspaceProjectStateChangeDetector( - projectSnapshotManagerDispatcher.InternalDispatcher, - workspaceStateGenerator.InternalWorkspaceStateGenerator, - languageServerFeatureOptions.InternalLanguageServerFeatureOptions); - } - - private WorkspaceProjectStateChangeDetector InternalWorkspaceProjectStateChangeDetector { get; } - - public void Initialize(OmniSharpProjectSnapshotManager projectManager) - { - InternalWorkspaceProjectStateChangeDetector.Initialize(projectManager.InternalProjectSnapshotManager); - } - - private class ProjectSnapshotManagerWorkspaceProjectStateChangeDetector : WorkspaceProjectStateChangeDetector - { - private readonly ProjectSnapshotManagerDispatcher _projectSnapshotManagerDispatcher; - - internal ProjectSnapshotManagerWorkspaceProjectStateChangeDetector( - ProjectSnapshotManagerDispatcher projectSnapshotManagerDispatcher, - ProjectWorkspaceStateGenerator workspaceStateGenerator, - LanguageServerFeatureOptions languageServerFeatureOptions) - : base(workspaceStateGenerator, projectSnapshotManagerDispatcher, languageServerFeatureOptions) - { - if (projectSnapshotManagerDispatcher is null) - { - throw new ArgumentNullException(nameof(projectSnapshotManagerDispatcher)); - } - - _projectSnapshotManagerDispatcher = projectSnapshotManagerDispatcher; - } - - // We override the InitializeSolution in order to enforce calls to this to be on the project snapshot manager's - // thread. OmniSharp currently has an issue where they update the Solution on multiple different threads resulting - // in change events dispatching through the Workspace on multiple different threads. This normalizes - // that abnormality. - protected override void InitializeSolution(Solution solution) - { - _ = InitializeSolutionAsync(solution, CancellationToken.None); - } - - private async Task InitializeSolutionAsync(Solution solution, CancellationToken cancellationToken) - { - try - { - await _projectSnapshotManagerDispatcher.RunOnDispatcherThreadAsync( - () => - { - base.InitializeSolution(solution); - }, - cancellationToken).ConfigureAwait(false); - } - catch (Exception ex) - { - Debug.Fail("Unexpected error when initializing solution: " + ex); - } - } - - // We override Workspace_WorkspaceChanged in order to enforce calls to this to be on the project snapshot manager's - // thread. OmniSharp currently has an issue where they update the Solution on multiple different threads resulting - // in change events dispatching through the Workspace on multiple different threads. This normalizes - // that abnormality. - internal override void Workspace_WorkspaceChanged(object? sender, WorkspaceChangeEventArgs args) - { - Workspace_WorkspaceChangedAsync(sender, args).Forget(); - } - - private async Task Workspace_WorkspaceChangedAsync(object? sender, WorkspaceChangeEventArgs args) - { - try - { - await _projectSnapshotManagerDispatcher.RunOnDispatcherThreadAsync( - () => - { - base.Workspace_WorkspaceChanged(sender, args); - }, - CancellationToken.None).ConfigureAwait(false); - } - catch (Exception ex) - { - Debug.Fail("Unexpected error when handling a workspace changed event: " + ex); - } - } - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/ProjectSnapshotProjectEngineFactoryFactory.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/ProjectSnapshotProjectEngineFactoryFactory.cs deleted file mode 100644 index becbae6ee75..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Project/ProjectSnapshotProjectEngineFactoryFactory.cs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -using System.Composition; -using Microsoft.AspNetCore.Razor.LanguageServer.Common; -using Microsoft.CodeAnalysis.Host; -using Microsoft.CodeAnalysis.Host.Mef; -using Microsoft.CodeAnalysis.Razor; - -namespace Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project; - -[Shared] -[ExportWorkspaceServiceFactory(typeof(ProjectSnapshotProjectEngineFactory))] -internal class ProjectSnapshotProjectEngineFactoryFactory : IWorkspaceServiceFactory -{ - public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) - { - if (workspaceServices is null) - { - throw new ArgumentNullException(nameof(workspaceServices)); - } - - return new DefaultProjectSnapshotProjectEngineFactory(new FallbackProjectEngineFactory(), MefProjectEngineFactories.Factories); - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Properties/AssemblyInfo.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Properties/AssemblyInfo.cs deleted file mode 100644 index 75ec63d46c5..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,6 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -using System.Runtime.CompilerServices; - -[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")] diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/PublicAPI.Shipped.txt b/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/PublicAPI.Shipped.txt deleted file mode 100644 index 815c92006af..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/PublicAPI.Shipped.txt +++ /dev/null @@ -1 +0,0 @@ -#nullable enable \ No newline at end of file diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/PublicAPI.Unshipped.txt b/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/PublicAPI.Unshipped.txt deleted file mode 100644 index ab6ee9451d1..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/PublicAPI.Unshipped.txt +++ /dev/null @@ -1,80 +0,0 @@ -#nullable enable -abstract Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document.OmniSharpDocumentProcessedListener.DocumentProcessed(Microsoft.AspNetCore.Razor.Language.RazorCodeDocument! codeDocument, Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document.OmniSharpDocumentSnapshot! document) -> void -abstract Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document.OmniSharpDocumentProcessedListener.Initialize(Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshotManager! projectManager) -> void -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document.OmniSharpBackgroundDocumentGenerator -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document.OmniSharpBackgroundDocumentGenerator.Initialize(Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshotManager! projectManager) -> void -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document.OmniSharpBackgroundDocumentGenerator.OmniSharpBackgroundDocumentGenerator(Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshotManagerDispatcher! projectSnapshotManagerDispatcher, Microsoft.AspNetCore.Razor.LanguageServer.Common.RemoteTextLoaderFactory! remoteTextLoaderFactory, System.Collections.Generic.IEnumerable! documentProcessedListeners) -> void -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document.OmniSharpDocumentProcessedListener -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document.OmniSharpDocumentProcessedListener.OmniSharpDocumentProcessedListener() -> void -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document.OmniSharpDocumentSnapshot -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document.OmniSharpDocumentSnapshot.FileKind.get -> string? -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document.OmniSharpDocumentSnapshot.FilePath.get -> string? -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document.OmniSharpDocumentSnapshot.HostDocument.get -> Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document.OmniSharpHostDocument! -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document.OmniSharpDocumentSnapshot.Project.get -> Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshot! -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document.OmniSharpHostDocument -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document.OmniSharpHostDocument.FilePath.get -> string! -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document.OmniSharpHostDocument.OmniSharpHostDocument(string! filePath, string! targetPath, string! kind) -> void -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document.OmniSharpHostDocumentComparer -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document.OmniSharpHostDocumentComparer.Equals(Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document.OmniSharpHostDocument? x, Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document.OmniSharpHostDocument? y) -> bool -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document.OmniSharpHostDocumentComparer.GetHashCode(Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document.OmniSharpHostDocument! hostDocument) -> int -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Extensions.OmniSharpRazorCodeDocumentExtensions -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.FallbackRazorConfiguration -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.FallbackRazorConfiguration.FallbackRazorConfiguration() -> void -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.OmniSharpLanguageServerFeatureOptions -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.OmniSharpLanguageServerFeatureOptions.OmniSharpLanguageServerFeatureOptions() -> void -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.IOmniSharpProjectSnapshotManagerChangeTrigger -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.IOmniSharpProjectSnapshotManagerChangeTrigger.Initialize(Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshotManager! projectManager) -> void -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpHostProject -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpHostProject.Key.get -> Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectKey! -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpHostProject.OmniSharpHostProject(string! projectFilePath, string! intermediateOutputPath, Microsoft.AspNetCore.Razor.Language.RazorConfiguration! razorConfiguration, string! rootNamespace) -> void -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectChangeEventArgs -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectChangeEventArgs.DocumentFilePath.get -> string? -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectChangeEventArgs.Kind.get -> Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectChangeKind -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectChangeEventArgs.Newer.get -> Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshot? -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectChangeEventArgs.Older.get -> Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshot? -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectChangeEventArgs.OmniSharpProjectChangeEventArgs(Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshot? older, Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshot? newer, string? documentFilePath, Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectChangeKind kind) -> void -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectChangeKind -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectChangeKind.DocumentAdded = 3 -> Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectChangeKind -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectChangeKind.DocumentRemoved = 4 -> Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectChangeKind -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectChangeKind.ProjectAdded = 0 -> Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectChangeKind -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectChangeKind.ProjectChanged = 2 -> Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectChangeKind -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectChangeKind.ProjectRemoved = 1 -> Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectChangeKind -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectKey -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshot -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshot.DocumentFilePaths.get -> System.Collections.Generic.IEnumerable! -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshot.FilePath.get -> string! -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshot.GetDocument(string! filePath) -> Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document.OmniSharpDocumentSnapshot? -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshot.Key.get -> Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectKey! -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshot.ProjectWorkspaceState.get -> Microsoft.AspNetCore.Razor.ProjectSystem.ProjectWorkspaceState? -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshot.Serialize(string! publishFilePath, Newtonsoft.Json.JsonSerializer! serializer, System.IO.StreamWriter! writer) -> void -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshotManager -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshotManager.Changed -> System.EventHandler? -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshotManager.DocumentAdded(Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpHostProject! hostProject, Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document.OmniSharpHostDocument! hostDocument) -> void -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshotManager.DocumentChanged(string! projectFilePath, string! documentFilePath) -> void -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshotManager.DocumentRemoved(Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpHostProject! hostProject, Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document.OmniSharpHostDocument! hostDocument) -> void -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshotManager.GetAllProjectKeys(string! projectFilePath) -> System.Collections.Immutable.ImmutableArray -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshotManager.GetLoadedProject(Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectKey! projectKey) -> Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshot! -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshotManager.ProjectAdded(Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpHostProject! hostProject) -> void -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshotManager.ProjectConfigurationChanged(Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpHostProject! hostProject) -> void -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshotManager.Projects.get -> System.Collections.Generic.IReadOnlyList! -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshotManagerAccessor -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshotManagerAccessor.Instance.get -> Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshotManager! -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshotManagerAccessor.OmniSharpProjectSnapshotManagerAccessor(Microsoft.AspNetCore.Razor.LanguageServer.Common.RemoteTextLoaderFactory! remoteTextLoaderFactory, System.Collections.Generic.IEnumerable! projectChangeTriggers, Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshotManagerDispatcher! projectSnapshotManagerDispatcher, Microsoft.CodeAnalysis.Workspace! workspace) -> void -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshotManagerDispatcher -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshotManagerDispatcher.AssertDispatcherThread(string? caller = null) -> void -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshotManagerDispatcher.DispatcherScheduler.get -> System.Threading.Tasks.TaskScheduler! -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshotManagerDispatcher.OmniSharpProjectSnapshotManagerDispatcher() -> void -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshotManagerDispatcher.RunOnDispatcherThreadAsync(System.Action! action, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectWorkspaceStateGenerator -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectWorkspaceStateGenerator.Initialize(Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshotManager! projectManager) -> void -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectWorkspaceStateGenerator.OmniSharpProjectWorkspaceStateGenerator(Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshotManagerDispatcher! projectSnapshotManagerDispatcher) -> void -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpWorkspaceProjectStateChangeDetector -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpWorkspaceProjectStateChangeDetector.Initialize(Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshotManager! projectManager) -> void -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpWorkspaceProjectStateChangeDetector.OmniSharpWorkspaceProjectStateChangeDetector(Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshotManagerDispatcher! projectSnapshotManagerDispatcher, Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectWorkspaceStateGenerator! workspaceStateGenerator, Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.OmniSharpLanguageServerFeatureOptions! languageServerFeatureOptions) -> void -Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Serialization.JsonConverterCollectionExtensions -static Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Extensions.OmniSharpRazorCodeDocumentExtensions.GetInternalCSharpSourceText(this Microsoft.AspNetCore.Razor.Language.RazorCodeDocument! codeDocument) -> Microsoft.CodeAnalysis.Text.SourceText! -static Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.FallbackRazorConfiguration.SelectConfiguration(System.Version! version) -> Microsoft.AspNetCore.Razor.Language.RazorConfiguration! -static Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectKey.From(Microsoft.CodeAnalysis.Project! workspaceProject) -> Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectKey? -static Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Serialization.JsonConverterCollectionExtensions.RegisterOmniSharpRazorConverters(this Newtonsoft.Json.JsonConverterCollection! collection) -> void -static readonly Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document.OmniSharpHostDocumentComparer.Instance -> Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document.OmniSharpHostDocumentComparer! -virtual Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectWorkspaceStateGenerator.Update(Microsoft.CodeAnalysis.Project! workspaceProject, Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project.OmniSharpProjectSnapshot! projectSnapshot) -> void \ No newline at end of file diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Serialization/JsonConverterCollectionExtensions.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Serialization/JsonConverterCollectionExtensions.cs deleted file mode 100644 index 6490efd382f..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp/Serialization/JsonConverterCollectionExtensions.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project; -using Microsoft.AspNetCore.Razor.Serialization.Converters; -using Newtonsoft.Json; - -namespace Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Serialization; - -public static class JsonConverterCollectionExtensions -{ - public static void RegisterOmniSharpRazorConverters(this JsonConverterCollection collection) - { - collection.RegisterRazorConverters(); - collection.Add(OmniSharpProjectSnapshotHandleJsonConverter.Instance); - } - - private class OmniSharpProjectSnapshotHandleJsonConverter : JsonConverter - { - internal static readonly OmniSharpProjectSnapshotHandleJsonConverter Instance = new(); - - public override bool CanConvert(Type objectType) - { - return typeof(OmniSharpProjectSnapshot).IsAssignableFrom(objectType); - } - - public override object ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) - { - throw new NotImplementedException(); - } - - public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) - { - var snapshot = (OmniSharpProjectSnapshot)value!; - - serializer.Serialize(writer, snapshot.InternalProjectSnapshot); - } - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/BackgroundDocumentProcessedPublisher.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/BackgroundDocumentProcessedPublisher.cs deleted file mode 100644 index d3b1b528b5b..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/BackgroundDocumentProcessedPublisher.cs +++ /dev/null @@ -1,299 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -#nullable disable - -using System; -using System.Composition; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document; -using Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Extensions; -using Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project; -using Microsoft.AspNetCore.Razor.Language; -using Microsoft.CodeAnalysis; -using Microsoft.Extensions.Logging; -using OmniSharp; - -namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin; - -// This class is responsible for listening to document processed events and then synchronizing their existence in the C# workspace. -// Key scenarios are: -// 1. A Razor document is not open - Publish Razor documents C# content to workspace under a background convention file path (i.e. Index.razor__bg__virtual.cs) -// 2. A Razor document is already open - Active C# content for the open doc already exists in the workspace (i.e. Index.razor__virtual.cs), noop. -// 3. A Razor document gets opened - Remove background generated C# content from workspace so active C# content gets prioritized -// 4. A Razor document gets closed - Need to transition active C# content to background C# content in the workspace. -// -// Since we don't have LSP access to fully understand if a document opens/closes we utilize the convention of our active and background generated C# -// file paths to understand if a Razor document is open or closed. - -[Shared] -[Export(typeof(OmniSharpDocumentProcessedListener))] -internal class BackgroundDocumentProcessedPublisher : OmniSharpDocumentProcessedListener -{ - // File paths need to align with the file path that's used to create virutal document buffers in the RazorDocumentFactory.ts. - // The purpose of the alignment is to ensure that when a Razor virtual C# buffer opens we can properly detect its existence. - internal const string ActiveVirtualDocumentSuffix = "__virtual.cs"; - internal const string BackgroundVirtualDocumentSuffix = "__bg" + ActiveVirtualDocumentSuffix; - - private readonly OmniSharpProjectSnapshotManagerDispatcher _projectSnapshotManagerDispatcher; - private readonly OmniSharpWorkspace _workspace; - private readonly ILogger _logger; - private OmniSharpProjectSnapshotManager _projectManager; - private readonly object _workspaceChangedLock; - - [ImportingConstructor] - public BackgroundDocumentProcessedPublisher( - OmniSharpProjectSnapshotManagerDispatcher projectSnapshotManagerDispatcher, - OmniSharpWorkspace workspace, - ILoggerFactory loggerFactory) - { - if (projectSnapshotManagerDispatcher is null) - { - throw new ArgumentNullException(nameof(projectSnapshotManagerDispatcher)); - } - - if (workspace is null) - { - throw new ArgumentNullException(nameof(workspace)); - } - - if (loggerFactory is null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } - - _projectSnapshotManagerDispatcher = projectSnapshotManagerDispatcher; - _workspace = workspace; - _logger = loggerFactory.CreateLogger(); - _workspaceChangedLock = new object(); - - _workspace.WorkspaceChanged += Workspace_WorkspaceChanged; - } - - // A Razor file has been processed, this portion is responsible for the decision of whether we need to create or update - // the Razor documents background C# representation. - public override void DocumentProcessed(RazorCodeDocument codeDocument, OmniSharpDocumentSnapshot document) - { - if (document is null) - { - throw new ArgumentNullException(nameof(document)); - } - - _projectSnapshotManagerDispatcher.AssertDispatcherThread(); - - lock (_workspaceChangedLock) - { - if (FileKinds.IsComponentImport(document.FileKind)) - { - // Razor component imports don't have any C# to generate anyways, don't do the work. This doesn't capture _ViewImports.cshtml because we never - // associated a FileKind with those files. - return; - } - - var openVirtualFilePath = document.FilePath + ActiveVirtualDocumentSuffix; - var openDocument = _workspace.GetDocument(openVirtualFilePath); - if (openDocument != null) - { - // This document is open in the editor, no reason for us to populate anything in the workspace the editor will do that. - return; - } - - var backgroundVirtualFilePath = document.FilePath + BackgroundVirtualDocumentSuffix; - var currentDocument = _workspace.GetDocument(backgroundVirtualFilePath); - if (currentDocument is null) - { - // Background document doesn't exist, we need to create it - - var roslynProject = GetRoslynProject(document.Project); - if (roslynProject is null) - { - // There's no Roslyn project associated with the Razor document. - _logger.LogTrace("Could not find a Roslyn project for Razor virtual document '{backgroundVirtualFilePath}'.", backgroundVirtualFilePath); - return; - } - - var documentId = DocumentId.CreateNewId(roslynProject.Id); - var name = Path.GetFileName(backgroundVirtualFilePath); - var emptyTextLoader = new EmptyTextLoader(backgroundVirtualFilePath); - var documentInfo = DocumentInfo.Create(documentId, name, filePath: backgroundVirtualFilePath, loader: emptyTextLoader); - _workspace.AddDocument(documentInfo); - currentDocument = _workspace.GetDocument(backgroundVirtualFilePath); - - Debug.Assert(currentDocument != null, "We just added the document, it should definitely be there."); - } - - // Update document content - - var sourceText = codeDocument.GetInternalCSharpSourceText(); - _workspace.OnDocumentChanged(currentDocument.Id, sourceText); - } - } - - public override void Initialize(OmniSharpProjectSnapshotManager projectManager) - { - if (projectManager is null) - { - throw new ArgumentNullException(nameof(projectManager)); - } - - _projectManager = projectManager; - _projectManager.Changed += ProjectManager_Changed; - } - - // Here we're specifically listening for cases when a user opens a Razor document and an active C# content gets created. - internal void Workspace_WorkspaceChanged(object sender, WorkspaceChangeEventArgs args) - { - lock (_workspaceChangedLock) - { - switch (args.Kind) - { - case WorkspaceChangeKind.DocumentAdded: - { - // We could technically listen for DocumentAdded here but just because a document gets added doesn't mean it has content included. - // Therefore we need to wait for content to populated for Razor files so we don't preemptively remove the corresponding background - // C# before the active C# content has been populated. - - var project = args.NewSolution.GetProject(args.ProjectId); - var document = project.GetDocument(args.DocumentId); - - if (document.FilePath is null) - { - break; - } - - if (document.FilePath.EndsWith(ActiveVirtualDocumentSuffix, StringComparison.Ordinal) && !document.FilePath.EndsWith(BackgroundVirtualDocumentSuffix, StringComparison.Ordinal)) - { - // Document from editor got opened, clear out any background documents of the same type - - var razorDocumentFilePath = GetRazorDocumentFilePath(document); - var backgroundDocumentFilePath = GetBackgroundVirtualDocumentFilePath(razorDocumentFilePath); - var backgroundDocument = GetRoslynDocument(project, backgroundDocumentFilePath); - if (backgroundDocument != null) - { - _workspace.RemoveDocument(backgroundDocument.Id); - } - } - - break; - } - case WorkspaceChangeKind.DocumentRemoved: - { - var project = args.OldSolution.GetProject(args.ProjectId); - var document = project.GetDocument(args.DocumentId); - - if (document.FilePath is null) - { - break; - } - - if (document.FilePath.EndsWith(ActiveVirtualDocumentSuffix, StringComparison.Ordinal) && !document.FilePath.EndsWith(BackgroundVirtualDocumentSuffix, StringComparison.Ordinal)) - { - var razorDocumentFilePath = GetRazorDocumentFilePath(document); - - if (File.Exists(razorDocumentFilePath)) - { - // Razor document closed because the backing C# virtual document went away - var backgroundDocumentFilePath = GetBackgroundVirtualDocumentFilePath(razorDocumentFilePath); - var newName = Path.GetFileName(backgroundDocumentFilePath); - var delegatedTextLoader = new DelegatedTextLoader(document); - var movedDocumentInfo = DocumentInfo.Create(args.DocumentId, newName, loader: delegatedTextLoader, filePath: backgroundDocumentFilePath); - _workspace.AddDocument(movedDocumentInfo); - } - } - } - - break; - } - } - } - - // When the Razor project manager forgets about a document we need remove its background C# representation - // so that content doesn't get stale. - private void ProjectManager_Changed(object sender, OmniSharpProjectChangeEventArgs args) - { - switch (args.Kind) - { - case OmniSharpProjectChangeKind.DocumentRemoved: - var roslynProject = GetRoslynProject(args.Older); - if (roslynProject is null) - { - // Project no longer exists - return; - } - - var backgroundVirtualFilePath = GetBackgroundVirtualDocumentFilePath(args.DocumentFilePath); - var backgroundDocument = GetRoslynDocument(roslynProject, backgroundVirtualFilePath); - if (backgroundDocument is null) - { - // No background document associated - return; - } - - // There's still a background document associated with the removed Razor document. - _workspace.RemoveDocument(backgroundDocument.Id); - break; - } - } - - private Project GetRoslynProject(OmniSharpProjectSnapshot project) - { - var roslynProject = _workspace.CurrentSolution.Projects.FirstOrDefault(roslynProject => string.Equals(roslynProject.FilePath, project.FilePath, FilePathComparison.Instance)); - return roslynProject; - } - - private static Document GetRoslynDocument(Project project, string backgroundDocumentFilePath) - { - var roslynDocument = project.Documents.FirstOrDefault(document => string.Equals(document.FilePath, backgroundDocumentFilePath, FilePathComparison.Instance)); - return roslynDocument; - } - - private static string GetRazorDocumentFilePath(Document document) - { - if (document.FilePath.EndsWith(BackgroundVirtualDocumentSuffix, StringComparison.Ordinal)) - { - var razorDocumentFilePath = document.FilePath.Substring(0, document.FilePath.Length - BackgroundVirtualDocumentSuffix.Length); - return razorDocumentFilePath; - } - else if (document.FilePath.EndsWith(ActiveVirtualDocumentSuffix, StringComparison.Ordinal)) - { - var razorDocumentFilePath = document.FilePath.Substring(0, document.FilePath.Length - ActiveVirtualDocumentSuffix.Length); - return razorDocumentFilePath; - } - - Debug.Fail($"The caller should have ensured that '{document.FilePath}' is associated with a Razor file path."); - return null; - } - - private static string GetBackgroundVirtualDocumentFilePath(string razorDocumentFilePath) - { - var backgroundDocumentFilePath = razorDocumentFilePath + BackgroundVirtualDocumentSuffix; - return backgroundDocumentFilePath; - } - - private class DelegatedTextLoader : TextLoader - { - private readonly Document _document; - - public DelegatedTextLoader(Document document) - { - if (document is null) - { - throw new ArgumentNullException(nameof(document)); - } - - _document = document; - } - - public async override Task LoadTextAndVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) - { - var sourceText = await _document.GetTextAsync(cancellationToken); - var textVersion = await _document.GetTextVersionAsync(cancellationToken); - var textAndVersion = TextAndVersion.Create(sourceText, textVersion); - return textAndVersion; - } - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/CoreProjectConfigurationProvider.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/CoreProjectConfigurationProvider.cs deleted file mode 100644 index 054130ee977..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/CoreProjectConfigurationProvider.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -#nullable disable - -using System; -using System.Linq; - -namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin; - -public abstract class CoreProjectConfigurationProvider : ProjectConfigurationProvider -{ - // Internal for testing - internal const string DotNetCoreRazorCapability = "DotNetCoreRazor"; - internal const string DotNetCoreWebCapability = "DotNetCoreWeb"; - internal const string DotNetCoreRazorConfigurationCapability = "DotNetCoreRazorConfiguration"; - - protected bool HasRazorCoreCapability(ProjectConfigurationProviderContext context) => - context.ProjectCapabilities.Contains(DotNetCoreRazorCapability) || - context.ProjectCapabilities.Contains(DotNetCoreWebCapability); - - protected bool HasRazorCoreConfigurationCapability(ProjectConfigurationProviderContext context) => - context.ProjectCapabilities.Contains(DotNetCoreRazorConfigurationCapability); -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/DefaultProjectChangePublisher.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/DefaultProjectChangePublisher.cs deleted file mode 100644 index f6cff5d718b..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/DefaultProjectChangePublisher.cs +++ /dev/null @@ -1,213 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -#nullable disable - -using System; -using System.Collections.Generic; -using System.Composition; -using System.IO; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project; -using Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Serialization; -using Microsoft.Extensions.Logging; -using Newtonsoft.Json; - -namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin; - -[Shared] -[Export(typeof(ProjectChangePublisher))] -[Export(typeof(IOmniSharpProjectSnapshotManagerChangeTrigger))] -internal class DefaultProjectChangePublisher : ProjectChangePublisher, IOmniSharpProjectSnapshotManagerChangeTrigger -{ - private const string TempFileExt = ".temp"; - - // Internal for testing - internal readonly Dictionary DeferredPublishTasks; - private readonly ILogger _logger; - private readonly JsonSerializer _serializer; - private readonly Dictionary _publishFilePathMappings; - private readonly Dictionary _pendingProjectPublishes; - private readonly object _publishLock; - private OmniSharpProjectSnapshotManager _projectManager; - - [ImportingConstructor] - public DefaultProjectChangePublisher(ILoggerFactory loggerFactory) - { - if (loggerFactory is null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } - - _logger = loggerFactory.CreateLogger(); - - _serializer = new JsonSerializer() - { - Formatting = Formatting.Indented, - }; - - _serializer.Converters.RegisterOmniSharpRazorConverters(); - _publishFilePathMappings = new Dictionary(FilePathComparer.Instance); - DeferredPublishTasks = new Dictionary(FilePathComparer.Instance); - _pendingProjectPublishes = new Dictionary(FilePathComparer.Instance); - _publishLock = new object(); - } - - // Internal settable for testing - // 250ms between publishes to prevent bursts of changes yet still be responsive to changes. - internal int EnqueueDelay { get; set; } = 250; - - public void Initialize(OmniSharpProjectSnapshotManager projectManager) - { - if (projectManager is null) - { - throw new ArgumentNullException(nameof(projectManager)); - } - - _projectManager = projectManager; - _projectManager.Changed += ProjectManager_Changed; - } - - public override void SetPublishFilePath(string projectFilePath, string publishFilePath) - { - lock (_publishLock) - { - _publishFilePathMappings[projectFilePath] = publishFilePath; - } - } - - // Virtual for testing - protected virtual void SerializeToFile(OmniSharpProjectSnapshot projectSnapshot, string publishFilePath) - { - // We need to avoid having an incomplete file at any point, but our - // project configuration is large enough that it will be written as multiple operations. - var tempFilePath = string.Concat(publishFilePath, TempFileExt); - var tempFileInfo = new FileInfo(tempFilePath); - - if (tempFileInfo.Exists) - { - // This could be caused by failures during serialization or early process termination. - tempFileInfo.Delete(); - } - - // This needs to be in explicit brackets because the operation needs to be completed - // by the time we move the tempfile into its place - using (var writer = tempFileInfo.CreateText()) - { - projectSnapshot.Serialize(publishFilePath, _serializer, writer); - } - - var fileInfo = new FileInfo(publishFilePath); - if (fileInfo.Exists) - { - fileInfo.Delete(); - } - - File.Move(tempFileInfo.FullName, publishFilePath); - } - - // Internal for testing - internal void Publish(OmniSharpProjectSnapshot projectSnapshot) - { - if (projectSnapshot is null) - { - throw new ArgumentNullException(nameof(projectSnapshot)); - } - - lock (_publishLock) - { - string publishFilePath = null; - try - { - if (!_publishFilePathMappings.TryGetValue(projectSnapshot.FilePath, out publishFilePath)) - { - return; - } - - SerializeToFile(projectSnapshot, publishFilePath); - } - catch (Exception ex) - { - _logger.LogWarning(@"Could not update Razor project configuration file '{publishFilePath}': -{ex}", publishFilePath, ex); - } - } - } - - // Internal for testing - internal void EnqueuePublish(OmniSharpProjectSnapshot projectSnapshot) - { - lock (_publishLock) - { - _pendingProjectPublishes[projectSnapshot.FilePath] = projectSnapshot; - - if (!DeferredPublishTasks.TryGetValue(projectSnapshot.FilePath, out var update) || update.IsCompleted) - { - DeferredPublishTasks[projectSnapshot.FilePath] = PublishAfterDelayAsync(projectSnapshot.FilePath); - } - } - } - - // Internal for testing - internal void ProjectManager_Changed(object sender, OmniSharpProjectChangeEventArgs args) - { - switch (args.Kind) - { - case OmniSharpProjectChangeKind.DocumentRemoved: - case OmniSharpProjectChangeKind.DocumentAdded: - case OmniSharpProjectChangeKind.ProjectChanged: - // These changes can come in bursts so we don't want to overload the publishing system. Therefore, - // we enqueue publishes and then publish the latest project after a delay. - - if (args.Newer.ProjectWorkspaceState != null) - { - EnqueuePublish(args.Newer); - } - - break; - case OmniSharpProjectChangeKind.ProjectRemoved: - RemovePublishingData(args.Older); - break; - - // We don't care about ProjectAdded scenarios because a newly added project does not have a workspace state associated with it meaning - // it isn't interesting for us to serialize quite yet. - } - } - - internal void RemovePublishingData(OmniSharpProjectSnapshot projectSnapshot) - { - lock (_publishLock) - { - var oldProjectFilePath = projectSnapshot.FilePath; - if (!_publishFilePathMappings.TryGetValue(oldProjectFilePath, out var configurationFilePath)) - { - // If we don't track the value in PublishFilePathMappings that means it's already been removed, do nothing. - return; - } - - if (_pendingProjectPublishes.TryGetValue(oldProjectFilePath, out _)) - { - // Project was removed while a delayed publish was in flight. Clear the in-flight publish so it noops. - _pendingProjectPublishes.Remove(oldProjectFilePath); - } - } - } - - private async Task PublishAfterDelayAsync(string projectFilePath) - { - await Task.Delay(EnqueueDelay); - - lock (_publishLock) - { - if (!_pendingProjectPublishes.TryGetValue(projectFilePath, out var projectSnapshot)) - { - // Project was removed while waiting for the publish delay. - return; - } - - _pendingProjectPublishes.Remove(projectFilePath); - - Publish(projectSnapshot); - } - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/DefaultProjectInstanceEvaluator.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/DefaultProjectInstanceEvaluator.cs deleted file mode 100644 index cb027f0405d..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/DefaultProjectInstanceEvaluator.cs +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -#nullable disable - -using System; -using System.Collections.Generic; -using System.Composition; -using System.Linq; -using Microsoft.Build.Evaluation; -using Microsoft.Build.Execution; -using Microsoft.Build.Framework; - -namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin; - -// This class enables us to re-evaluate MSBuild project instances. Doing such a thing isn't directly -// supported by the ProjectInstance type because they're meant to be a snapshot of an MSBuild project -// at a certain point in time. Therefore, we re-create the MSBuild project environment by lifting all -// configuration values from the project instance and re-creating our own MSBuild project collection -// that can duplicate the work that OmniSharp does. -// -// Project re-evaluation is required for two reasons: -// 1. Razor file additions/deletions. OmniSharp tells us when a change happens to impact the csproj -// configuration but not the opaque items of a project such as content/initial compile items. -// 2. When OmniSharp initially evaluates the users project they don't do a true design time build. -// Because of this several bits of Razor information get left out in the initial project instance, -// we then need to force the execution of the appropriate targets to populate that information on -// the project instance. -[Shared] -[Export(typeof(ProjectInstanceEvaluator))] -public class DefaultProjectInstanceEvaluator : ProjectInstanceEvaluator -{ - internal const string TargetFrameworkPropertyName = "TargetFramework"; - internal const string TargetFrameworksPropertyName = "TargetFrameworks"; - private const string CompileTargetName = "Compile"; - private const string CoreCompileTargetName = "CoreCompile"; - private const string RazorGenerateDesignTimeTargetName = "RazorGenerateDesignTime"; - private const string RazorGenerateComponentDesignTimeTargetName = "RazorGenerateComponentDesignTime"; - private static readonly IEnumerable s_emptyMSBuildLoggers = Enumerable.Empty(); - private readonly object _evaluationLock = new object(); - - [ImportingConstructor] - public DefaultProjectInstanceEvaluator() - { - } - - public override ProjectInstance Evaluate(ProjectInstance projectInstance) - { - if (projectInstance is null) - { - throw new ArgumentNullException(nameof(projectInstance)); - } - - lock (_evaluationLock) - { - var refreshTargets = new List() - { - // These are the default targets for the project instance that OmniSharp runs. - CompileTargetName, - CoreCompileTargetName - }; - - if (projectInstance.Targets.ContainsKey(RazorGenerateDesignTimeTargetName)) - { - refreshTargets.Add(RazorGenerateDesignTimeTargetName); - } - - if (projectInstance.Targets.ContainsKey(RazorGenerateComponentDesignTimeTargetName)) - { - refreshTargets.Add(RazorGenerateComponentDesignTimeTargetName); - } - - if (refreshTargets.Count > 2) - { - var projectCollection = new ProjectCollection(projectInstance.GlobalProperties); - var project = projectCollection.LoadProject(projectInstance.ProjectFileLocation.File, projectInstance.ToolsVersion); - SetTargetFrameworkIfNeeded(project); - - var refreshedProjectInstance = project.CreateProjectInstance(); - - // Force a Razor information refresh - refreshedProjectInstance.Build(refreshTargets.ToArray(), s_emptyMSBuildLoggers); - - return refreshedProjectInstance; - } - - return projectInstance; - } - } - - private static void SetTargetFrameworkIfNeeded(Project evaluatedProject) - { - var targetFramework = evaluatedProject.GetPropertyValue(TargetFrameworkPropertyName); - var targetFrameworksRaw = evaluatedProject.GetPropertyValue(TargetFrameworksPropertyName); - var targetFrameworks = targetFrameworksRaw - .Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) - .Select(framework => framework.Trim()) - .ToArray(); - - if (string.IsNullOrWhiteSpace(targetFramework) && targetFrameworks.Length > 0) - { - // Pick first target framework to replicate what OmniSharp does. - targetFramework = targetFrameworks[0]; - evaluatedProject.SetProperty(TargetFrameworkPropertyName, targetFramework); - evaluatedProject.ReevaluateIfNecessary(); - } - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/DocumentChangedSynchronizationService.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/DocumentChangedSynchronizationService.cs deleted file mode 100644 index 3de30498385..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/DocumentChangedSynchronizationService.cs +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -#nullable disable - -using System; -using System.Composition; -using System.Threading; -using Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project; -using Microsoft.AspNetCore.Razor.OmniSharpPlugin; - -namespace Microsoft.AspNetCore.Razor.LanguageServer.Common; - -[Shared] -[Export(typeof(IRazorDocumentChangeListener))] -[Export(typeof(IOmniSharpProjectSnapshotManagerChangeTrigger))] -internal class DocumentChangedSynchronizationService : IOmniSharpProjectSnapshotManagerChangeTrigger, IRazorDocumentChangeListener -{ - private readonly OmniSharpProjectSnapshotManagerDispatcher _projectSnapshotManagerDispatcher; - private OmniSharpProjectSnapshotManager _projectManager; - - [ImportingConstructor] - public DocumentChangedSynchronizationService(OmniSharpProjectSnapshotManagerDispatcher projectSnapshotManagerDispatcher) - { - if (projectSnapshotManagerDispatcher is null) - { - throw new ArgumentNullException(nameof(projectSnapshotManagerDispatcher)); - } - - _projectSnapshotManagerDispatcher = projectSnapshotManagerDispatcher; - } - - public void Initialize(OmniSharpProjectSnapshotManager projectManager) - { - if (projectManager is null) - { - throw new ArgumentNullException(nameof(projectManager)); - } - - _projectManager = projectManager; - } - - public void RazorDocumentChanged(RazorFileChangeEventArgs args) - { - if (args is null) - { - throw new ArgumentNullException(nameof(args)); - } - - if (args.Kind != RazorFileChangeKind.Changed) - { - return; - } - - var projectFilePath = args.UnevaluatedProjectInstance.ProjectFileLocation.File; - var documentFilePath = args.FilePath; - - _ = _projectSnapshotManagerDispatcher.RunOnDispatcherThreadAsync( - () => _projectManager.DocumentChanged(projectFilePath, documentFilePath), - CancellationToken.None).ConfigureAwait(false); - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/EmptyTextLoader.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/EmptyTextLoader.cs deleted file mode 100644 index 19f89ff77d9..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/EmptyTextLoader.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -#nullable disable - -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Text; - -namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin; - -internal class EmptyTextLoader : TextLoader -{ - private readonly string _filePath; - private readonly VersionStamp _version; - - public EmptyTextLoader(string filePath) - { - _filePath = filePath; - _version = VersionStamp.Create(); // Version will never change so this can be reused. - } - - public override Task LoadTextAndVersionAsync(LoadTextOptions options, CancellationToken cancellationToken) - { - // Providing an encoding here is important for debuggability. Without this edit-and-continue - // won't work for projects with Razor files. - return Task.FromResult(TextAndVersion.Create(SourceText.From(string.Empty, Encoding.UTF8), _version, _filePath)); - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/FallbackConfigurationProvider.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/FallbackConfigurationProvider.cs deleted file mode 100644 index 560cb79375f..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/FallbackConfigurationProvider.cs +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -#nullable disable - -using System; -using System.IO; -using System.Reflection.Metadata; -using System.Reflection.PortableExecutable; -using Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp; -using Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document; - -namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin; - -internal class FallbackConfigurationProvider : CoreProjectConfigurationProvider -{ - public static FallbackConfigurationProvider Instance = new FallbackConfigurationProvider(); - - // Internal for testing - internal const string ReferencePathWithRefAssembliesItemType = "ReferencePathWithRefAssemblies"; - internal const string MvcAssemblyFileName = "Microsoft.AspNetCore.Mvc.Razor.dll"; - - public override bool TryResolveConfiguration(ProjectConfigurationProviderContext context, out ProjectConfiguration configuration) - { - if (!HasRazorCoreCapability(context)) - { - configuration = null; - return false; - } - - var compilationReferences = context.ProjectInstance.GetItems(ReferencePathWithRefAssembliesItemType); - string mvcReferenceFullPath = null; - foreach (var compilationReference in compilationReferences) - { - var assemblyFullPath = compilationReference.EvaluatedInclude; - if (assemblyFullPath.EndsWith(MvcAssemblyFileName, FilePathComparison.Instance)) - { - var potentialPathSeparator = assemblyFullPath[assemblyFullPath.Length - MvcAssemblyFileName.Length - 1]; - if (potentialPathSeparator == '/' || potentialPathSeparator == '\\') - { - mvcReferenceFullPath = assemblyFullPath; - break; - } - } - } - - if (mvcReferenceFullPath is null) - { - configuration = null; - return false; - } - - var version = GetAssemblyVersion(mvcReferenceFullPath); - if (version is null) - { - configuration = null; - return false; - } - - var razorConfiguration = FallbackRazorConfiguration.SelectConfiguration(version); - configuration = new ProjectConfiguration(razorConfiguration, Array.Empty(), rootNamespace: null); - return true; - } - - // Protected virtual for testing - protected virtual Version GetAssemblyVersion(string filePath) - { - try - { - using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)) - using (var reader = new PEReader(stream)) - { - var metadataReader = reader.GetMetadataReader(); - - var assemblyDefinition = metadataReader.GetAssemblyDefinition(); - return assemblyDefinition.Version; - } - } - catch - { - // We're purposely silencing any kinds of I/O exceptions here, just in case something wacky is going on. - return null; - } - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/FilePathComparer.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/FilePathComparer.cs deleted file mode 100644 index 16923aeffca..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/FilePathComparer.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -#nullable disable - -using System; -using System.Runtime.InteropServices; - -namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin; - -internal static class FilePathComparer -{ - private static StringComparer s_instance; - - public static StringComparer Instance - { - get - { - if (s_instance is null && RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - s_instance = StringComparer.Ordinal; - } - else if (s_instance is null) - { - s_instance = StringComparer.OrdinalIgnoreCase; - } - - return s_instance; - } - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/FilePathComparison.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/FilePathComparison.cs deleted file mode 100644 index 79fd4d5b13f..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/FilePathComparison.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -#nullable disable - -using System; -using System.Runtime.InteropServices; - -namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin; - -internal static class FilePathComparison -{ - private static StringComparison? s_instance; - - public static StringComparison Instance - { - get - { - if (s_instance is null && RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - s_instance = StringComparison.Ordinal; - } - else if (s_instance is null) - { - s_instance = StringComparison.OrdinalIgnoreCase; - } - - return s_instance.Value; - } - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/IRazorDocumentChangeListener.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/IRazorDocumentChangeListener.cs deleted file mode 100644 index 8ca5c8c9df2..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/IRazorDocumentChangeListener.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -#nullable disable - -namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin; - -internal interface IRazorDocumentChangeListener -{ - void RazorDocumentChanged(RazorFileChangeEventArgs args); -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/IRazorDocumentOutputChangeListener.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/IRazorDocumentOutputChangeListener.cs deleted file mode 100644 index ee9a91bfeb2..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/IRazorDocumentOutputChangeListener.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -#nullable disable - -namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin; - -internal interface IRazorDocumentOutputChangeListener -{ - void RazorDocumentOutputChanged(RazorFileChangeEventArgs args); -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/LatestProjectConfigurationProvider.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/LatestProjectConfigurationProvider.cs deleted file mode 100644 index fa93c211bbd..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/LatestProjectConfigurationProvider.cs +++ /dev/null @@ -1,290 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -#nullable disable - -using System; -using System.Collections.Generic; -using System.Composition; -using System.IO; -using System.Linq; -using Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document; -using Microsoft.AspNetCore.Razor.Language; -using Microsoft.Build.Execution; - -namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin; - -[Shared] -[Export(typeof(ProjectConfigurationProvider))] -internal class LatestProjectConfigurationProvider : CoreProjectConfigurationProvider -{ - // Internal for testing - internal const string RazorGenerateWithTargetPathItemType = "RazorGenerateWithTargetPath"; - internal const string RazorComponentWithTargetPathItemType = "RazorComponentWithTargetPath"; - internal const string RazorTargetPathMetadataName = "TargetPath"; - internal const string RootNamespaceProperty = "RootNamespace"; - - private const string RazorLangVersionProperty = "RazorLangVersion"; - private const string RazorDefaultConfigurationProperty = "RazorDefaultConfiguration"; - private const string RazorExtensionItemType = "RazorExtension"; - private const string RazorConfigurationItemType = "RazorConfiguration"; - private const string RazorConfigurationItemTypeExtensionsProperty = "Extensions"; - - public override bool TryResolveConfiguration(ProjectConfigurationProviderContext context, out ProjectConfiguration configuration) - { - if (!HasRazorCoreCapability(context)) - { - configuration = null; - return false; - } - - if (!HasRazorCoreConfigurationCapability(context)) - { - // Razor project is < 2.1, we don't handle that. - configuration = null; - return false; - } - - var projectInstance = context.ProjectInstance; - if (!TryGetConfiguration(projectInstance, out configuration)) - { - configuration = null; - return false; - } - - return true; - } - - // Internal for testing - internal static bool TryGetConfiguration( - ProjectInstance projectInstance, - out ProjectConfiguration configuration) - { - if (!TryGetDefaultConfiguration(projectInstance, out var defaultConfiguration)) - { - configuration = null; - return false; - } - - if (!TryGetLanguageVersion(projectInstance, out var languageVersion)) - { - configuration = null; - return false; - } - - if (!TryGetConfigurationItem(defaultConfiguration, projectInstance.Items, out var configurationItem)) - { - configuration = null; - return false; - } - - var configuredExtensionNames = GetConfiguredExtensionNames(configurationItem); - var rootNamespace = GetRootNamespace(projectInstance); - var extensions = GetExtensions(configuredExtensionNames, projectInstance.Items); - var razorConfiguration = new ProjectSystemRazorConfiguration(languageVersion, configurationItem.EvaluatedInclude, extensions); - var hostDocuments = GetHostDocuments(projectInstance.Items); - - configuration = new ProjectConfiguration(razorConfiguration, hostDocuments, rootNamespace); - return true; - } - - // Internal for testing - internal static string GetRootNamespace(ProjectInstance projectInstance) - { - var rootNamespace = projectInstance.GetPropertyValue(RootNamespaceProperty); - if (string.IsNullOrEmpty(rootNamespace)) - { - return null; - } - - return rootNamespace; - } - - // Internal for testing - internal static IReadOnlyList GetHostDocuments(ICollection projectItems) - { - var hostDocuments = new HashSet(); - - foreach (var item in projectItems) - { - if (item.ItemType == RazorGenerateWithTargetPathItemType) - { - var filePath = Path.Combine(item.Project.Directory, item.EvaluatedInclude); - var originalTargetPath = item.GetMetadataValue(RazorTargetPathMetadataName); - var normalizedTargetPath = NormalizeTargetPath(originalTargetPath); - var hostDocument = new OmniSharpHostDocument(filePath, normalizedTargetPath, FileKinds.Legacy); - hostDocuments.Add(hostDocument); - } - else if (item.ItemType == RazorComponentWithTargetPathItemType) - { - var filePath = Path.Combine(item.Project.Directory, item.EvaluatedInclude); - var originalTargetPath = item.GetMetadataValue(RazorTargetPathMetadataName); - var normalizedTargetPath = NormalizeTargetPath(originalTargetPath); - var fileKind = FileKinds.GetComponentFileKindFromFilePath(filePath); - var hostDocument = new OmniSharpHostDocument(filePath, normalizedTargetPath, fileKind); - hostDocuments.Add(hostDocument); - } - } - - return hostDocuments.ToList(); - } - - // Internal for testing - internal static bool TryGetDefaultConfiguration(ProjectInstance projectInstance, out string defaultConfiguration) - { - defaultConfiguration = projectInstance.GetPropertyValue(RazorDefaultConfigurationProperty); - if (string.IsNullOrEmpty(defaultConfiguration)) - { - defaultConfiguration = null; - return false; - } - - return true; - } - - // Internal for testing - internal static bool TryGetLanguageVersion(ProjectInstance projectInstance, out RazorLanguageVersion languageVersion) - { - var languageVersionValue = projectInstance.GetPropertyValue(RazorLangVersionProperty); - if (string.IsNullOrEmpty(languageVersionValue)) - { - languageVersion = null; - return false; - } - - if (!RazorLanguageVersion.TryParse(languageVersionValue, out languageVersion)) - { - languageVersion = RazorLanguageVersion.Latest; - } - - return true; - } - - // Internal for testing - internal static bool TryGetConfigurationItem( - string configuration, - IEnumerable projectItems, - out ProjectItemInstance configurationItem) - { - foreach (var item in projectItems) - { - if (item.ItemType == RazorConfigurationItemType && item.EvaluatedInclude == configuration) - { - configurationItem = item; - return true; - } - } - - configurationItem = null; - return false; - } - - // Internal for testing - internal static string[] GetConfiguredExtensionNames(ProjectItemInstance configurationItem) - { - var extensionNamesValue = configurationItem.GetMetadataValue(RazorConfigurationItemTypeExtensionsProperty); - - if (string.IsNullOrEmpty(extensionNamesValue)) - { - return Array.Empty(); - } - - var configuredExtensionNames = extensionNamesValue.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); - return configuredExtensionNames; - } - - // Internal for testing - internal static ProjectSystemRazorExtension[] GetExtensions( - string[] configuredExtensionNames, - IEnumerable projectItems) - { - var extensions = new List(); - - foreach (var item in projectItems) - { - if (item.ItemType != RazorExtensionItemType) - { - // Not a RazorExtension - continue; - } - - var extensionName = item.EvaluatedInclude; - if (configuredExtensionNames.Contains(extensionName)) - { - extensions.Add(new ProjectSystemRazorExtension(extensionName)); - } - } - - return extensions.ToArray(); - } - - /// - /// TargetPath is defined as using '\' but some Tasks used to set that parameter don't respect that, so we normalize. - /// - /// The TargetPath to be normalized. - /// A normalized TargetPath - internal static string NormalizeTargetPath(string targetPath) - { - if (targetPath is null) - { - throw new ArgumentNullException(nameof(targetPath)); - } - - var normalizedTargetPath = targetPath.Replace('/', '\\'); - normalizedTargetPath = normalizedTargetPath.TrimStart('\\'); - return normalizedTargetPath; - } - - private class ProjectSystemRazorConfiguration : RazorConfiguration - { - public ProjectSystemRazorConfiguration( - RazorLanguageVersion languageVersion, - string configurationName, - RazorExtension[] extensions, - bool useConsolidatedMvcViews = false) - { - if (languageVersion is null) - { - throw new ArgumentNullException(nameof(languageVersion)); - } - - if (configurationName is null) - { - throw new ArgumentNullException(nameof(configurationName)); - } - - if (extensions is null) - { - throw new ArgumentNullException(nameof(extensions)); - } - - LanguageVersion = languageVersion; - ConfigurationName = configurationName; - Extensions = extensions; - UseConsolidatedMvcViews = useConsolidatedMvcViews; - } - - public override string ConfigurationName { get; } - - public override IReadOnlyList Extensions { get; } - - public override RazorLanguageVersion LanguageVersion { get; } - - public override bool UseConsolidatedMvcViews { get; } - } - - internal class ProjectSystemRazorExtension : RazorExtension - { - public ProjectSystemRazorExtension(string extensionName) - { - if (extensionName is null) - { - throw new ArgumentNullException(nameof(extensionName)); - } - - ExtensionName = extensionName; - } - - public override string ExtensionName { get; } - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/MSBuildProjectDocumentChangeDetector.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/MSBuildProjectDocumentChangeDetector.cs deleted file mode 100644 index cfac12599a2..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/MSBuildProjectDocumentChangeDetector.cs +++ /dev/null @@ -1,162 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -#nullable disable - -using System; -using System.Collections.Generic; -using System.Composition; -using System.IO; -using System.Linq; -using Microsoft.AspNetCore.Razor.LanguageServer.Common; -using Microsoft.Build.Execution; -using OmniSharp.MSBuild.Notification; - -namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin; - -[Shared] -[Export(typeof(IMSBuildEventSink))] -internal class MSBuildProjectDocumentChangeDetector : IMSBuildEventSink -{ - private const string MSBuildProjectFullPathPropertyName = "MSBuildProjectFullPath"; - private const string MSBuildProjectDirectoryPropertyName = "MSBuildProjectDirectory"; - private static readonly IReadOnlyList s_razorFileExtensions = new[] { ".razor", ".cshtml" }; - - private readonly Dictionary> _watcherMap; - private readonly IReadOnlyList _documentChangeListeners; - private readonly List _documentOutputChangeListeners; - - [ImportingConstructor] - public MSBuildProjectDocumentChangeDetector( - [ImportMany] IEnumerable documentChangeListeners, - [ImportMany] IEnumerable documentOutputChangeListeners) - { - if (documentChangeListeners is null) - { - throw new ArgumentNullException(nameof(documentChangeListeners)); - } - - if (documentOutputChangeListeners is null) - { - throw new ArgumentNullException(nameof(documentOutputChangeListeners)); - } - - _watcherMap = new Dictionary>(FilePathComparer.Instance); - _documentChangeListeners = documentChangeListeners.ToList(); - _documentOutputChangeListeners = documentOutputChangeListeners.ToList(); - } - - public void ProjectLoaded(ProjectLoadedEventArgs loadedArgs) - { - if (loadedArgs is null) - { - throw new ArgumentNullException(nameof(loadedArgs)); - } - - var projectInstance = loadedArgs.ProjectInstance; - var projectFilePath = projectInstance.GetPropertyValue(MSBuildProjectFullPathPropertyName); - if (string.IsNullOrEmpty(projectFilePath)) - { - // This should never be true but we're being extra careful. - return; - } - - var projectDirectory = projectInstance.GetPropertyValue(MSBuildProjectDirectoryPropertyName); - if (string.IsNullOrEmpty(projectDirectory)) - { - // This should never be true but we're beign extra careful. - return; - } - - if (_watcherMap.TryGetValue(projectDirectory, out var existingWatchers)) - { - for (var i = 0; i < existingWatchers.Count; i++) - { - existingWatchers[i].Dispose(); - } - } - - var watchers = new List(s_razorFileExtensions.Count); - for (var i = 0; i < s_razorFileExtensions.Count; i++) - { - var documentWatcher = new FileSystemWatcher(projectDirectory, "*" + s_razorFileExtensions[i]) - { - NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.CreationTime, - IncludeSubdirectories = true, - }; - - documentWatcher.Created += (sender, args) => FileSystemWatcher_RazorDocumentEvent(args.FullPath, projectInstance, RazorFileChangeKind.Added); - documentWatcher.Deleted += (sender, args) => FileSystemWatcher_RazorDocumentEvent(args.FullPath, projectInstance, RazorFileChangeKind.Removed); - documentWatcher.Changed += (sender, args) => FileSystemWatcher_RazorDocumentEvent(args.FullPath, projectInstance, RazorFileChangeKind.Changed); - documentWatcher.Renamed += (sender, args) => - { - // Translate file renames into remove / add - - if (s_razorFileExtensions.Any(extension => args.OldFullPath.EndsWith(extension, StringComparison.Ordinal))) - { - // Renaming from Razor file to something else. - FileSystemWatcher_RazorDocumentEvent(args.OldFullPath, projectInstance, RazorFileChangeKind.Removed); - } - - if (s_razorFileExtensions.Any(extension => args.FullPath.EndsWith(extension, StringComparison.Ordinal))) - { - // Renaming into a Razor file. This typically occurs when users go from .cshtml => .razor - FileSystemWatcher_RazorDocumentEvent(args.FullPath, projectInstance, RazorFileChangeKind.Added); - } - }; - watchers.Add(documentWatcher); - - var documentOutputWatcher = new FileSystemWatcher(projectDirectory, "*" + s_razorFileExtensions[i] + ".g.cs") - { - NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite, - IncludeSubdirectories = true, - }; - - documentOutputWatcher.Created += (sender, args) => FileSystemWatcher_RazorDocumentOutputEvent(args.FullPath, projectInstance, RazorFileChangeKind.Added); - documentOutputWatcher.Deleted += (sender, args) => FileSystemWatcher_RazorDocumentOutputEvent(args.FullPath, projectInstance, RazorFileChangeKind.Removed); - documentOutputWatcher.Changed += (sender, args) => FileSystemWatcher_RazorDocumentOutputEvent(args.FullPath, projectInstance, RazorFileChangeKind.Changed); - documentOutputWatcher.Renamed += (sender, args) => - { - // Translate file renames into remove / add - - if (s_razorFileExtensions.Any(extension => args.OldFullPath.EndsWith(extension + ".g.cs", StringComparison.Ordinal))) - { - // Renaming from Razor background file to something else. - FileSystemWatcher_RazorDocumentOutputEvent(args.OldFullPath, projectInstance, RazorFileChangeKind.Removed); - } - - if (s_razorFileExtensions.Any(extension => args.FullPath.EndsWith(extension + ".g.cs", StringComparison.Ordinal))) - { - // Renaming into a Razor generated file. - FileSystemWatcher_RazorDocumentOutputEvent(args.FullPath, projectInstance, RazorFileChangeKind.Added); - } - }; - watchers.Add(documentOutputWatcher); - - documentWatcher.EnableRaisingEvents = true; - documentOutputWatcher.EnableRaisingEvents = true; - } - - _watcherMap[projectDirectory] = watchers; - } - - // Internal for testing - internal void FileSystemWatcher_RazorDocumentEvent(string filePath, ProjectInstance projectInstance, RazorFileChangeKind changeKind) - { - var args = new RazorFileChangeEventArgs(filePath, projectInstance, changeKind); - for (var i = 0; i < _documentChangeListeners.Count; i++) - { - _documentChangeListeners[i].RazorDocumentChanged(args); - } - } - - // Internal for testing - internal void FileSystemWatcher_RazorDocumentOutputEvent(string filePath, ProjectInstance projectInstance, RazorFileChangeKind changeKind) - { - var args = new RazorFileChangeEventArgs(filePath, projectInstance, changeKind); - for (var i = 0; i < _documentOutputChangeListeners.Count; i++) - { - _documentOutputChangeListeners[i].RazorDocumentOutputChanged(args); - } - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/MSBuildProjectManager.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/MSBuildProjectManager.cs deleted file mode 100644 index 6fa8a2ec8ed..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/MSBuildProjectManager.cs +++ /dev/null @@ -1,327 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Composition; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document; -using Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project; -using Microsoft.AspNetCore.Razor.LanguageServer.Common; -using Microsoft.AspNetCore.Razor.OmniSharpPlugin; -using Microsoft.Build.Execution; -using Microsoft.Extensions.Logging; -using OmniSharp.MSBuild.Notification; - -namespace Microsoft.AspNetCore.Razor.OmnisharpPlugin; - -[Shared] -[Export(typeof(IMSBuildEventSink))] -[Export(typeof(IRazorDocumentChangeListener))] -[Export(typeof(IOmniSharpProjectSnapshotManagerChangeTrigger))] -internal class MSBuildProjectManager : IOmniSharpProjectSnapshotManagerChangeTrigger, IMSBuildEventSink, IRazorDocumentChangeListener -{ - // Internal for testing - internal const string IntermediateOutputPathPropertyName = "IntermediateOutputPath"; - internal const string MSBuildProjectDirectoryPropertyName = "MSBuildProjectDirectory"; - internal const string ProjectCapabilityItemType = "ProjectCapability"; - - private const string MSBuildProjectFullPathPropertyName = "MSBuildProjectFullPath"; - private const string DebugRazorOmnisharpPluginPropertyName = "_DebugRazorOmnisharpPlugin_"; - private readonly ILogger _logger; - private readonly IEnumerable _projectConfigurationProviders; - private readonly ProjectInstanceEvaluator _projectInstanceEvaluator; - private readonly ProjectChangePublisher _projectConfigurationPublisher; - private readonly OmniSharpProjectSnapshotManagerDispatcher _projectSnapshotManagerDispatcher; - private OmniSharpProjectSnapshotManager? _projectManager; - - [ImportingConstructor] - public MSBuildProjectManager( - [ImportMany] IEnumerable projectConfigurationProviders, - ProjectInstanceEvaluator projectInstanceEvaluator, - ProjectChangePublisher projectConfigurationPublisher, - OmniSharpProjectSnapshotManagerDispatcher projectSnapshotManagerDispatcher, - ILoggerFactory loggerFactory) - { - if (projectConfigurationProviders is null) - { - throw new ArgumentNullException(nameof(projectConfigurationProviders)); - } - - if (projectInstanceEvaluator is null) - { - throw new ArgumentNullException(nameof(projectInstanceEvaluator)); - } - - if (projectConfigurationPublisher is null) - { - throw new ArgumentNullException(nameof(projectConfigurationPublisher)); - } - - if (projectSnapshotManagerDispatcher is null) - { - throw new ArgumentNullException(nameof(projectSnapshotManagerDispatcher)); - } - - if (loggerFactory is null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } - - _logger = loggerFactory.CreateLogger(); - _projectConfigurationProviders = projectConfigurationProviders; - _projectInstanceEvaluator = projectInstanceEvaluator; - _projectConfigurationPublisher = projectConfigurationPublisher; - _projectSnapshotManagerDispatcher = projectSnapshotManagerDispatcher; - } - - public OmniSharpProjectSnapshotManager ProjectManager => _projectManager ?? throw new InvalidOperationException($"{nameof(ProjectManager)} was unexpectedly 'null'. Has {nameof(Initialize)} been called?"); - - public void Initialize(OmniSharpProjectSnapshotManager projectManager) - { - if (projectManager is null) - { - throw new ArgumentNullException(nameof(projectManager)); - } - - _projectManager = projectManager; - } - - public void ProjectLoaded(ProjectLoadedEventArgs args) - { - _ = ProjectLoadedAsync(args, CancellationToken.None); - } - - public void RazorDocumentChanged(RazorFileChangeEventArgs args) - { - if (args.Kind == RazorFileChangeKind.Added || - args.Kind == RazorFileChangeKind.Removed) - { - // When documents get added or removed we need to refresh project state to properly reflect the host documents in the project. - - var evaluatedProjectInstance = _projectInstanceEvaluator.Evaluate(args.UnevaluatedProjectInstance); - _ = _projectSnapshotManagerDispatcher.RunOnDispatcherThreadAsync( - () => UpdateProjectState(evaluatedProjectInstance), CancellationToken.None).ConfigureAwait(false); - } - } - - // Internal for testing - internal async Task ProjectLoadedAsync(ProjectLoadedEventArgs args, CancellationToken cancellationToken) - { - try - { - var projectInstance = args.ProjectInstance; - HandleDebug(projectInstance); - - if (!TryResolveConfigurationOutputPath(projectInstance, out var configPath)) - { - return; - } - - var projectFilePath = projectInstance.GetPropertyValue(MSBuildProjectFullPathPropertyName); - if (string.IsNullOrEmpty(projectFilePath)) - { - // This should never be true but we're being extra careful. - return; - } - - _projectConfigurationPublisher.SetPublishFilePath(projectFilePath, configPath); - - // Force project instance evaluation to ensure that all Razor specific targets have run. - projectInstance = _projectInstanceEvaluator.Evaluate(projectInstance); - - await _projectSnapshotManagerDispatcher.RunOnDispatcherThreadAsync( - () => UpdateProjectState(projectInstance), cancellationToken).ConfigureAwait(false); - - } - catch (Exception ex) - { - _logger.LogError("Unexpected exception got thrown from the Razor plugin: {exception}", ex); - } - } - - private void UpdateProjectState(ProjectInstance projectInstance) - { - _projectSnapshotManagerDispatcher.AssertDispatcherThread(); - - var projectFilePath = projectInstance.GetPropertyValue(MSBuildProjectFullPathPropertyName); - if (string.IsNullOrEmpty(projectFilePath)) - { - // This should never be true but we're being extra careful. - return; - } - - var projectConfiguration = GetProjectConfiguration(projectInstance, _projectConfigurationProviders); - if (projectConfiguration is null) - { - // Not a Razor project - return; - } - - if (!TryResolveConfigurationOutputPath(projectInstance, out var configPath) || configPath is null) - { - return; - } - - var hostProject = new OmniSharpHostProject(projectFilePath, configPath, projectConfiguration.Configuration, projectConfiguration.RootNamespace); - var projectSnapshot = ProjectManager.GetLoadedProject(hostProject.Key); - if (projectSnapshot is null) - { - // Project doesn't exist yet, create it and set it up with all of its host documents. - - ProjectManager.ProjectAdded(hostProject); - - foreach (var hostDocument in projectConfiguration.Documents) - { - ProjectManager.DocumentAdded(hostProject, hostDocument); - } - } - else - { - // Project already exists (project change). Reconfigure the project and add or remove host documents to synchronize it with the configured host documents. - - ProjectManager.ProjectConfigurationChanged(hostProject); - - SynchronizeDocuments(projectConfiguration.Documents, projectSnapshot, hostProject); - } - } - - // Internal for testing - internal void SynchronizeDocuments( - IReadOnlyList configuredHostDocuments, - OmniSharpProjectSnapshot projectSnapshot, - OmniSharpHostProject hostProject) - { - // Remove any documents that need to be removed - foreach (var documentFilePath in projectSnapshot.DocumentFilePaths) - { - OmniSharpHostDocument? associatedHostDocument = null; - - var documentSnapshot = projectSnapshot.GetDocument(documentFilePath); - if (documentSnapshot is null) - { - _logger.LogWarning("Missing DocumentSnapshot for {documentFilePath}.", documentFilePath); - continue; - } - - var currentHostDocument = documentSnapshot.HostDocument; - - for (var i = 0; i < configuredHostDocuments.Count; i++) - { - var configuredHostDocument = configuredHostDocuments[i]; - if (OmniSharpHostDocumentComparer.Instance.Equals(configuredHostDocument, currentHostDocument)) - { - associatedHostDocument = configuredHostDocument; - break; - } - } - - if (associatedHostDocument is null) - { - // Document was removed - ProjectManager.DocumentRemoved(hostProject, currentHostDocument); - } - } - - // Refresh the project snapshot to reflect any removed documents. - projectSnapshot = ProjectManager.GetLoadedProject(projectSnapshot.Key); - - // Add any documents that need to be added - for (var i = 0; i < configuredHostDocuments.Count; i++) - { - var hostDocument = configuredHostDocuments[i]; - if (!projectSnapshot.DocumentFilePaths.Contains(hostDocument.FilePath, FilePathComparer.Instance)) - { - // Document was added. - ProjectManager.DocumentAdded(hostProject, hostDocument); - } - } - } - - // Internal for testing - internal static ProjectConfiguration? GetProjectConfiguration( - ProjectInstance projectInstance, - IEnumerable projectConfigurationProviders) - { - if (projectInstance is null) - { - throw new ArgumentNullException(nameof(projectInstance)); - } - - if (projectConfigurationProviders is null) - { - throw new ArgumentNullException(nameof(projectConfigurationProviders)); - } - - var projectCapabilities = projectInstance - .GetItems(ProjectCapabilityItemType) - .Select(capability => capability.EvaluatedInclude) - .ToList(); - - var context = new ProjectConfigurationProviderContext(projectCapabilities, projectInstance); - foreach (var projectConfigurationProvider in projectConfigurationProviders) - { - if (projectConfigurationProvider.TryResolveConfiguration(context, out var configuration)) - { - return configuration; - } - } - - if (FallbackConfigurationProvider.Instance.TryResolveConfiguration(context, out var fallbackConfiguration)) - { - return fallbackConfiguration; - } - - return null; - } - - private static void HandleDebug(ProjectInstance projectInstance) - { - var debugPlugin = projectInstance.GetPropertyValue(DebugRazorOmnisharpPluginPropertyName); - if (!string.IsNullOrEmpty(debugPlugin) && string.Equals(debugPlugin, "true", StringComparison.OrdinalIgnoreCase)) - { - Console.WriteLine($"Waiting for a debugger to attach to the Razor Plugin. Process id: {Process.GetCurrentProcess().Id}"); - while (!Debugger.IsAttached) - { - Thread.Sleep(1000); - } - - Debugger.Break(); - } - } - - // Internal for testing - internal static bool TryResolveConfigurationOutputPath(ProjectInstance projectInstance, out string? path) - { - var intermediateOutputPath = projectInstance.GetPropertyValue(IntermediateOutputPathPropertyName); - if (string.IsNullOrEmpty(intermediateOutputPath)) - { - path = null; - return false; - } - - if (!Path.IsPathRooted(intermediateOutputPath)) - { - // Relative path, need to convert to absolute. - var projectDirectory = projectInstance.GetPropertyValue(MSBuildProjectDirectoryPropertyName); - if (string.IsNullOrEmpty(projectDirectory)) - { - // This should never be true but we're being extra careful. - path = null; - return false; - } - - intermediateOutputPath = Path.Combine(projectDirectory, intermediateOutputPath); - } - - intermediateOutputPath = intermediateOutputPath - .Replace('\\', Path.DirectorySeparatorChar) - .Replace('/', Path.DirectorySeparatorChar); - path = Path.Combine(intermediateOutputPath, LanguageServerConstants.DefaultProjectConfigurationFile); - return true; - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/Microsoft.AspNetCore.Razor.OmniSharpPlugin.csproj b/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/Microsoft.AspNetCore.Razor.OmniSharpPlugin.csproj deleted file mode 100644 index 2ccab2b01c4..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/Microsoft.AspNetCore.Razor.OmniSharpPlugin.csproj +++ /dev/null @@ -1,22 +0,0 @@ - - - - $(DefaultNetFxTargetFramework) - - Razor is a markup syntax for adding logic to pages. This package contains the Omnisharp Razor plugin that extracts Razor configuration information from projects. - false - false - - - - - - - - - - - - - - diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/OmniSharpPluginStrongNamedRoslynServiceProvider.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/OmniSharpPluginStrongNamedRoslynServiceProvider.cs deleted file mode 100644 index 53ed12e026d..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/OmniSharpPluginStrongNamedRoslynServiceProvider.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -#nullable disable - -using System.Collections.Immutable; -using System.Composition; -using System.Reflection; -using OmniSharp.Services; - -namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin; - -// This service provider is here to enable the OmniSharp process to indirectly utilize internal types that are exposed via the strong named -// Razor assemblies by re-exporting them via the Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp assembly. For example, we re-export the -// DefaultTagHelperResolver's factory in the strong named assembly because it's internal to Razor and can only be accessed in a strong named -// assembly. -// -// We're also unable to directly load and discover Roslyn exports in the Microsoft.CodeAnalysis.Razor.Workspaces.dll due to mismatches in -// MSBuild metadata dependencies. The expectations of the MSBuild that is loaded with OmniSharp doesn't understand the version that Razor -// is compiled against. If we could there'd be no need for this class. - -[Shared] -[Export(typeof(IHostServicesProvider))] -public class OmniSharpPluginStrongNamedRoslynServiceProvider : IHostServicesProvider -{ - public OmniSharpPluginStrongNamedRoslynServiceProvider() - { - var strongNamedAssembly = Assembly.Load("Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp"); - Assemblies = ImmutableArray.Create(strongNamedAssembly); - } - - public ImmutableArray Assemblies { get; } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/OmniSharpStrongNamedExports.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/OmniSharpStrongNamedExports.cs deleted file mode 100644 index 970789218b1..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/OmniSharpStrongNamedExports.cs +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -#nullable disable - -using System.Collections.Generic; -using System.Composition; -using Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document; -using Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project; -using Microsoft.AspNetCore.Razor.LanguageServer.Common; -using Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp; -using OmniSharp; - -namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin; - -// We need to re-export MEF based services from the OmniSharp plugin strong named assembly in order -// to make those services available via MEF. This isn't an issue for Roslyn based services because -// we're able to hook into OmniSharp's Roslyn service aggregator to allow it to inspect the strong -// named plugin assembly. - -[Shared] -[Export(typeof(OmniSharpProjectSnapshotManagerDispatcher))] -internal class ExportOmniSharpProjectSnapshotManagerDispatcher : OmniSharpProjectSnapshotManagerDispatcher -{ -} - -[Shared] -[Export(typeof(RemoteTextLoaderFactory))] -internal class ExportRemoteTextLoaderFactory : DefaultRemoteTextLoaderFactory -{ -} - -[Shared] -[Export(typeof(OmniSharpProjectSnapshotManagerAccessor))] -internal class ExportDefaultOmniSharpProjectSnapshotManagerAccessor : OmniSharpProjectSnapshotManagerAccessor -{ - [ImportingConstructor] - public ExportDefaultOmniSharpProjectSnapshotManagerAccessor( - RemoteTextLoaderFactory remoteTextLoaderFactory, - [ImportMany] IEnumerable projectChangeTriggers, - OmniSharpProjectSnapshotManagerDispatcher projectSnapshotManagerDispatcher, - OmniSharpWorkspace workspace) : base(remoteTextLoaderFactory, projectChangeTriggers, projectSnapshotManagerDispatcher, workspace) - { - } -} - -[Shared] -[Export(typeof(IOmniSharpProjectSnapshotManagerChangeTrigger))] -internal class ExportOmniSharpWorkspaceProjectStateChangeDetector : OmniSharpWorkspaceProjectStateChangeDetector -{ - [ImportingConstructor] - public ExportOmniSharpWorkspaceProjectStateChangeDetector( - OmniSharpProjectSnapshotManagerDispatcher projectSnapshotManagerDispatcher, - OmniSharpProjectWorkspaceStateGenerator workspaceStateGenerator, - OmniSharpLanguageServerFeatureOptions languageServerFeatureOptions) - : base(projectSnapshotManagerDispatcher, workspaceStateGenerator, languageServerFeatureOptions) - { - } -} - -[Shared] -[Export(typeof(IOmniSharpProjectSnapshotManagerChangeTrigger))] -[Export(typeof(OmniSharpProjectWorkspaceStateGenerator))] -internal class ExportOmniSharpProjectWorkspaceStateGenerator : OmniSharpProjectWorkspaceStateGenerator -{ - [ImportingConstructor] - public ExportOmniSharpProjectWorkspaceStateGenerator(OmniSharpProjectSnapshotManagerDispatcher projectSnapshotManagerDispatcher) : base(projectSnapshotManagerDispatcher) - { - } -} - -[Shared] -[Export(typeof(IOmniSharpProjectSnapshotManagerChangeTrigger))] -internal class ExportOmniSharpBackgroundDocumentGenerator : OmniSharpBackgroundDocumentGenerator -{ - [ImportingConstructor] - public ExportOmniSharpBackgroundDocumentGenerator( - OmniSharpProjectSnapshotManagerDispatcher projectSnapshotManagerDispatcher, - RemoteTextLoaderFactory remoteTextLoaderFactory, - [ImportMany] IEnumerable documentProcessedListeners) : base(projectSnapshotManagerDispatcher, remoteTextLoaderFactory, documentProcessedListeners) - { - } -} - -[Shared] -[Export(typeof(OmniSharpLanguageServerFeatureOptions))] -internal class ExportOmniSharpLanguageServerFeatureOptions : OmniSharpLanguageServerFeatureOptions -{ - [ImportingConstructor] - public ExportOmniSharpLanguageServerFeatureOptions() : base() - { - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/PrecompiledRazorPageSuppressor.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/PrecompiledRazorPageSuppressor.cs deleted file mode 100644 index c8bacbc3460..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/PrecompiledRazorPageSuppressor.cs +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -#nullable disable - -using System; -using System.Composition; -using Microsoft.CodeAnalysis; -using OmniSharp; -using OmniSharp.MSBuild.Notification; - -namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin; - -// This entire class is a temporary work around for https://github.com/OmniSharp/omnisharp-roslyn/issues/1443. -// We hack together a heuristic to detect when Razor documents that shouldn't be added to the workspace are and to then -// remove them from the workspace. In the primary case we're watching for pre-compiled Razor files that are generated -// from calling dotnet build and removing them from the workspace once they're added. - -[Shared] -[Export(typeof(IMSBuildEventSink))] -public class PrecompiledRazorPageSuppressor : IMSBuildEventSink -{ - private readonly OmniSharpWorkspace _workspace; - - [ImportingConstructor] - public PrecompiledRazorPageSuppressor(OmniSharpWorkspace workspace) - { - if (workspace is null) - { - throw new ArgumentNullException(nameof(workspace)); - } - - _workspace = workspace; - - _workspace.WorkspaceChanged += Workspace_WorkspaceChanged; - } - - // Internal for testing - internal void Workspace_WorkspaceChanged(object sender, WorkspaceChangeEventArgs args) - { - switch (args.Kind) - { - case WorkspaceChangeKind.DocumentAdded: - case WorkspaceChangeKind.DocumentChanged: - var project = args.NewSolution.GetProject(args.ProjectId); - var document = project.GetDocument(args.DocumentId); - - if (document.FilePath is null) - { - break; - } - - if (document.FilePath.EndsWith(".RazorTargetAssemblyInfo.cs", StringComparison.Ordinal) || - document.FilePath.EndsWith(".RazorAssemblyInfo.cs", StringComparison.Ordinal)) - { - // Razor assembly info. This doesn't catch cases when users have customized their assembly info but captures all of the - // default cases for now. Once the omnisharp-roslyn bug has been fixed this entire class can go awy so we're hacking for now. - _workspace.RemoveDocument(document.Id); - break; - } - - if (!document.FilePath.EndsWith(".cshtml.g.cs", StringComparison.Ordinal) && - !document.FilePath.EndsWith(".razor.g.cs", StringComparison.Ordinal) && - - // 2.2 only extension for generated Razor files - !document.FilePath.EndsWith(".g.cshtml.cs", StringComparison.Ordinal)) - { - break; - } - - // Razor output file - _workspace.RemoveDocument(document.Id); - - break; - } - } - - public void ProjectLoaded(ProjectLoadedEventArgs e) - { - // We don't do anything on project load we're just using the IMSBuildEventSink to ensure we're instantiated. - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/ProjectChangePublisher.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/ProjectChangePublisher.cs deleted file mode 100644 index ede7c1cc1f5..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/ProjectChangePublisher.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -#nullable disable - -namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin; - -internal abstract class ProjectChangePublisher -{ - public abstract void SetPublishFilePath(string projectFilePath, string publishFilePath); -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/ProjectConfiguration.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/ProjectConfiguration.cs deleted file mode 100644 index 68f95d85a0a..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/ProjectConfiguration.cs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -#nullable disable - -using System; -using System.Collections.Generic; -using Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document; -using Microsoft.AspNetCore.Razor.Language; - -namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin; - -public sealed class ProjectConfiguration -{ - internal ProjectConfiguration(RazorConfiguration configuration, IReadOnlyList documents, string rootNamespace) - { - if (configuration is null) - { - throw new ArgumentNullException(nameof(configuration)); - } - - if (documents is null) - { - throw new ArgumentNullException(nameof(documents)); - } - - Configuration = configuration; - Documents = documents; - RootNamespace = rootNamespace; - } - - public RazorConfiguration Configuration { get; } - - internal IReadOnlyList Documents { get; } - - public string RootNamespace { get; } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/ProjectConfigurationProvider.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/ProjectConfigurationProvider.cs deleted file mode 100644 index c5dd2975b6d..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/ProjectConfigurationProvider.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -#nullable disable - -namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin; - -public abstract class ProjectConfigurationProvider -{ - public abstract bool TryResolveConfiguration(ProjectConfigurationProviderContext context, out ProjectConfiguration configuration); -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/ProjectConfigurationProviderContext.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/ProjectConfigurationProviderContext.cs deleted file mode 100644 index dc7d6d0e57d..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/ProjectConfigurationProviderContext.cs +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -#nullable disable - -using System; -using System.Collections.Generic; -using Microsoft.Build.Execution; - -namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin; - -public sealed class ProjectConfigurationProviderContext -{ - public ProjectConfigurationProviderContext( - IReadOnlyList projectCapabilities, - ProjectInstance projectInstance) - { - if (projectCapabilities is null) - { - throw new ArgumentNullException(nameof(projectCapabilities)); - } - - if (projectInstance is null) - { - throw new ArgumentNullException(nameof(projectInstance)); - } - - ProjectCapabilities = projectCapabilities; - ProjectInstance = projectInstance; - } - - public IReadOnlyList ProjectCapabilities { get; } - - public ProjectInstance ProjectInstance { get; } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/ProjectInstanceEvaluator.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/ProjectInstanceEvaluator.cs deleted file mode 100644 index dba511e63f4..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/ProjectInstanceEvaluator.cs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -#nullable disable - -using Microsoft.Build.Execution; - -namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin; - -public abstract class ProjectInstanceEvaluator -{ - public abstract ProjectInstance Evaluate(ProjectInstance projectInstance); -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/ProjectSnapshotManagerInstantiator.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/ProjectSnapshotManagerInstantiator.cs deleted file mode 100644 index afa8f482f37..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/ProjectSnapshotManagerInstantiator.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -#nullable disable - -using System.Composition; -using Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project; -using OmniSharp.MSBuild.Notification; - -namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin; - -[Shared] -[Export(typeof(IMSBuildEventSink))] -internal class ProjectSnapshotManagerInstantiator : IMSBuildEventSink -{ - // The entire purpose of this class is to ensure the project manager is instantiated. - // Without this class all exporters of AbstractOmniSharpProjectSnapshotManagerChangeTrigger - // would never be called (the class wouldn't have been created). So instead we rely - // on OmniSharp to instantiate the snapshot manager and therefore configure the - // dependent change triggers. - - private readonly OmniSharpProjectSnapshotManager _projectManager; - - [ImportingConstructor] - public ProjectSnapshotManagerInstantiator(OmniSharpProjectSnapshotManagerAccessor accessor) - { - _projectManager = accessor.Instance; - } - - public void ProjectLoaded(ProjectLoadedEventArgs _) - { - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/Properties/AssemblyInfo.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/Properties/AssemblyInfo.cs deleted file mode 100644 index a5d4cb28609..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -#nullable disable - -using System.Runtime.CompilerServices; - -[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")] -[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Razor.OmniSharpPlugin.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/RazorFileChangeEventArgs.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/RazorFileChangeEventArgs.cs deleted file mode 100644 index 75fef3adebb..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/RazorFileChangeEventArgs.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -#nullable disable - -using System; -using Microsoft.AspNetCore.Razor.LanguageServer.Common; -using Microsoft.Build.Execution; - -namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin; - -internal class RazorFileChangeEventArgs : EventArgs -{ - public RazorFileChangeEventArgs( - string filePath, - ProjectInstance projectInstance, - RazorFileChangeKind kind) - { - if (filePath is null) - { - throw new ArgumentNullException(nameof(filePath)); - } - - if (projectInstance is null) - { - throw new ArgumentNullException(nameof(projectInstance)); - } - - FilePath = filePath; - UnevaluatedProjectInstance = projectInstance; - Kind = kind; - } - - public string FilePath { get; } - - public ProjectInstance UnevaluatedProjectInstance { get; } - - public RazorFileChangeKind Kind { get; } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/SystemWebConfigurationProvider.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/SystemWebConfigurationProvider.cs deleted file mode 100644 index c9627cc6f2d..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/SystemWebConfigurationProvider.cs +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -#nullable disable - -using System; -using System.Composition; -using Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Document; -using Microsoft.AspNetCore.Razor.ProjectEngineHost; - -namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin; - -[Shared] -[Export(typeof(ProjectConfigurationProvider))] -internal class SystemWebConfigurationProvider : CoreProjectConfigurationProvider -{ - // Internal for testing - internal const string ReferencePathWithRefAssembliesItemType = "ReferencePathWithRefAssemblies"; - internal const string SystemWebRazorAssemblyFileName = "System.Web.Razor.dll"; - - public override bool TryResolveConfiguration(ProjectConfigurationProviderContext context, out ProjectConfiguration configuration) - { - if (HasRazorCoreCapability(context)) - { - configuration = null; - return false; - } - - var compilationReferences = context.ProjectInstance.GetItems(ReferencePathWithRefAssembliesItemType); - foreach (var compilationReference in compilationReferences) - { - var assemblyFullPath = compilationReference.EvaluatedInclude; - if (assemblyFullPath.EndsWith(SystemWebRazorAssemblyFileName, FilePathComparison.Instance)) - { - var potentialPathSeparator = assemblyFullPath[assemblyFullPath.Length - SystemWebRazorAssemblyFileName.Length - 1]; - if (potentialPathSeparator == '/' || potentialPathSeparator == '\\') - { - configuration = new ProjectConfiguration(UnsupportedRazorConfiguration.Instance, Array.Empty(), rootNamespace: null); - return true; - } - } - } - - configuration = null; - return false; - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/TagHelperRefreshTrigger.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/TagHelperRefreshTrigger.cs deleted file mode 100644 index a4eb54c01a9..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/TagHelperRefreshTrigger.cs +++ /dev/null @@ -1,202 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -#nullable disable - -using System; -using System.Collections.Generic; -using System.Composition; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Razor.ExternalAccess.OmniSharp.Project; -using Microsoft.AspNetCore.Razor.Language; -using Microsoft.CodeAnalysis; -using OmniSharp; -using OmniSharp.MSBuild.Notification; - -namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin; - -[Shared] -[Export(typeof(IMSBuildEventSink))] -[Export(typeof(IRazorDocumentChangeListener))] -[Export(typeof(IRazorDocumentOutputChangeListener))] -[Export(typeof(IOmniSharpProjectSnapshotManagerChangeTrigger))] -internal class TagHelperRefreshTrigger : IOmniSharpProjectSnapshotManagerChangeTrigger, IMSBuildEventSink, IRazorDocumentOutputChangeListener, IRazorDocumentChangeListener -{ - private readonly OmniSharpProjectSnapshotManagerDispatcher _projectSnapshotManagerDispatcher; - private readonly Workspace _omniSharpWorkspace; - private readonly OmniSharpProjectWorkspaceStateGenerator _workspaceStateGenerator; - private readonly Dictionary _deferredUpdates; - private OmniSharpProjectSnapshotManager _projectManager; - - [ImportingConstructor] - public TagHelperRefreshTrigger( - OmniSharpProjectSnapshotManagerDispatcher projectSnapshotManagerDispatcher, - OmniSharpWorkspace omniSharpWorkspace, - OmniSharpProjectWorkspaceStateGenerator workspaceStateGenerator) - : this(projectSnapshotManagerDispatcher, (Workspace)omniSharpWorkspace, workspaceStateGenerator) - { - } - - // Internal for testing - internal TagHelperRefreshTrigger( - OmniSharpProjectSnapshotManagerDispatcher projectSnapshotManagerDispatcher, - Workspace omniSharpWorkspace, - OmniSharpProjectWorkspaceStateGenerator workspaceStateGenerator) - { - if (projectSnapshotManagerDispatcher is null) - { - throw new ArgumentNullException(nameof(projectSnapshotManagerDispatcher)); - } - - if (omniSharpWorkspace is null) - { - throw new ArgumentNullException(nameof(omniSharpWorkspace)); - } - - if (workspaceStateGenerator is null) - { - throw new ArgumentNullException(nameof(workspaceStateGenerator)); - } - - _projectSnapshotManagerDispatcher = projectSnapshotManagerDispatcher; - _omniSharpWorkspace = omniSharpWorkspace; - _workspaceStateGenerator = workspaceStateGenerator; - _deferredUpdates = new Dictionary(); - } - - public int EnqueueDelay { get; set; } = 3 * 1000; - - public void Initialize(OmniSharpProjectSnapshotManager projectManager) - { - if (projectManager is null) - { - throw new ArgumentNullException(nameof(projectManager)); - } - - _projectManager = projectManager; - } - - public void ProjectLoaded(ProjectLoadedEventArgs args) - { - if (args is null) - { - throw new ArgumentNullException(nameof(args)); - } - - // Project file was modified or impacted in a significant way. - - _ = _projectSnapshotManagerDispatcher.RunOnDispatcherThreadAsync( - () => EnqueueUpdate(args.ProjectInstance.ProjectFileLocation.File), - CancellationToken.None).ConfigureAwait(false); - } - - public void RazorDocumentChanged(RazorFileChangeEventArgs args) - { - if (args is null) - { - throw new ArgumentNullException(nameof(args)); - } - - // Razor document changed - - _ = Task.Factory.StartNew( - () => - { - if (IsComponentFile(args.FilePath, args.UnevaluatedProjectInstance.ProjectFileLocation.File)) - { - // Razor component file changed. - - EnqueueUpdate(args.UnevaluatedProjectInstance.ProjectFileLocation.File); - } - }, - CancellationToken.None, - TaskCreationOptions.None, - _projectSnapshotManagerDispatcher.DispatcherScheduler).ConfigureAwait(false); - } - - public void RazorDocumentOutputChanged(RazorFileChangeEventArgs args) - { - if (args is null) - { - throw new ArgumentNullException(nameof(args)); - } - - // Razor build occurred - - _ = Task.Factory.StartNew( - () => EnqueueUpdate(args.UnevaluatedProjectInstance.ProjectFileLocation.File), - CancellationToken.None, - TaskCreationOptions.None, - _projectSnapshotManagerDispatcher.DispatcherScheduler).ConfigureAwait(false); - } - - // Internal for testing - internal async Task UpdateAfterDelayAsync(string projectFilePath) - { - if (string.IsNullOrEmpty(projectFilePath)) - { - return; - } - - await Task.Delay(EnqueueDelay); - - var solution = _omniSharpWorkspace.CurrentSolution; - var workspaceProject = solution.Projects.FirstOrDefault(project => FilePathComparer.Instance.Equals(project.FilePath, projectFilePath)); - if (workspaceProject != null && TryGetProjectSnapshot(OmniSharpProjectKey.From(workspaceProject), out var projectSnapshot)) - { - _workspaceStateGenerator.Update(workspaceProject, projectSnapshot); - } - } - - private void EnqueueUpdate(string projectFilePath) - { - _projectSnapshotManagerDispatcher.AssertDispatcherThread(); - - // A race is not possible here because we use the main thread to synchronize the updates - // by capturing the sync context. - if (!_deferredUpdates.TryGetValue(projectFilePath, out var update) || update.IsCompleted) - { - _deferredUpdates[projectFilePath] = UpdateAfterDelayAsync(projectFilePath); - } - } - - private bool TryGetProjectSnapshot(OmniSharpProjectKey projectKey, out OmniSharpProjectSnapshot projectSnapshot) - { - if (projectKey is null) - { - projectSnapshot = null; - return false; - } - - projectSnapshot = _projectManager.GetLoadedProject(projectKey); - return projectSnapshot != null; - } - - // Internal for testing - internal bool IsComponentFile(string relativeDocumentFilePath, string projectFilePath) - { - _projectSnapshotManagerDispatcher.AssertDispatcherThread(); - - foreach (var key in _projectManager.GetAllProjectKeys(projectFilePath)) - { - var projectSnapshot = _projectManager.GetLoadedProject(key); - if (projectSnapshot is null) - { - continue; - } - - var documentSnapshot = projectSnapshot.GetDocument(relativeDocumentFilePath); - if (documentSnapshot is null) - { - continue; - } - - var isComponentKind = FileKinds.IsComponent(documentSnapshot.FileKind); - return isComponentKind; - } - - return false; - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode.Extension/Microsoft.AspNetCore.Razor.VSCode.Extension.npmproj b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode.Extension/Microsoft.AspNetCore.Razor.VSCode.Extension.npmproj index d08bd9da86a..6c91a6accb3 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode.Extension/Microsoft.AspNetCore.Razor.VSCode.Extension.npmproj +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode.Extension/Microsoft.AspNetCore.Razor.VSCode.Extension.npmproj @@ -7,19 +7,6 @@ false - - - - - - - - diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode.Extension/README.md b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode.Extension/README.md deleted file mode 100644 index 622cd06563b..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode.Extension/README.md +++ /dev/null @@ -1,19 +0,0 @@ -# Info - -In practice the Razor VSCode extension operates as a library that [OmniSharp](https://github.com/omnisharp/omnisharp-vscode) (O#) bootstraps and includes in its operation flow. Therefore, in order to provide a dev experience for testing out Razor VSCode extension changes this project attempts to replicate what O# does to bootstrap Razor's VSCode extension library. - -## Debugging - -1. npm install -g typescript -1. npm install -g yarn -1. .\build.cmd - -### Debugging with Omnisharp-vscode - -If you need to make changes to both the Razor-vscode extension and the Omnisharp-vscode extension you might find it useful to debug through both of them at the same time. - -1. Do all the steps for debugging this repo -1. Clone -1. In that repo do all the steps to debug except pressing F5. -1. Edit to include a second `--extensionDevelopmentPath` which points to our workspace. -1. F5 on their repo. diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode.Extension/language-configuration.json b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode.Extension/language-configuration.json deleted file mode 100644 index 806ffbf0d9b..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode.Extension/language-configuration.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "comments": { - "blockComment": [ "@*", "*@" ] - }, - "brackets": [ - [""], - ["<", ">"], - ["{", "}"], - ["(", ")"] - ], - "autoClosingPairs": [ - { "open": "{", "close": "}"}, - { "open": "[", "close": "]"}, - { "open": "(", "close": ")" }, - { "open": "'", "close": "'" }, - { "open": "\"", "close": "\"" }, - { "open": "@*", "close": "*@" } - ], - "surroundingPairs": [ - { "open": "'", "close": "'" }, - { "open": "\"", "close": "\"" }, - { "open": "<", "close": ">" } - ] -} \ No newline at end of file diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode.Extension/package.json b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode.Extension/package.json index 312efa1cb3a..01ec59b325f 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode.Extension/package.json +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode.Extension/package.json @@ -1,525 +1,10 @@ { - "name": "razor-vscode", - "private": true, - "displayName": "Razor", - "description": "Razor VS Code extension bootstrapper. This extension attempts to replicate what O# does to bootstrap Razor's VSCode extension library. ", - "version": "0.0.1", - "defaults": { - "razor": "0.0.1" - }, - "publisher": "ms-dotnettools", - "engines": { - "vscode": "^1.69.0" - }, - "categories": [ - "Other" - ], - "activationEvents": [ - "onWebviewPanel:razorReportIssue", - "onDebugInitialConfigurations", - "onDebugResolve:blazorwasm", - "onDebugResolve:coreclr", - "onDebugResolve:clr", - "onLanguage:csharp", - "onLanguage:aspnetcorerazor", - "onCommand:o.restart", - "onCommand:o.pickProjectAndStart", - "onCommand:o.showOutput", - "onCommand:dotnet.restore.project", - "onCommand:dotnet.restore.all", - "onCommand:dotnet.generateAssets", - "onCommand:csharp.downloadDebugger", - "onCommand:csharp.listProcess", - "onCommand:csharp.listRemoteProcess", - "onCommand:extension.configureRazorDevMode", - "onCommand:extension.resetRazorDevModeConfiguration", - "onCommand:extension.razorActivated", - "workspaceContains:project.json", - "workspaceContains:*.csproj", - "workspaceContains:*.sln", - "workspaceContains:*.csx", - "workspaceContains:*.cake", - "workspaceContains:**/*.csproj", - "workspaceContains:**/*.sln", - "workspaceContains:**/*.csx", - "workspaceContains:**/*.cake" - ], - "main": "../Microsoft.AspNetCore.Razor.VSCode.Extension/dist/extension.js", - "contributes": { - "breakpoints": [ - { - "language": "aspnetcorerazor" - }, - { - "language": "csharp" - } - ], - "debuggers": [ - { - "type": "blazorwasm", - "label": "Blazor WebAssembly Debug", - "initialConfigurations": [ - { - "type": "blazorwasm", - "name": "Launch and Debug Blazor WebAssembly Application", - "request": "launch" - } - ], - "configurationAttributes": { - "launch": { - "properties": { - "cwd": { - "type": "string", - "description": "The directory of the Blazor WebAssembly app, defaults to the workspace folder.", - "default": "${workspaceFolder}" - }, - "url": { - "type": "string", - "description": "The URL of the application", - "default": "https://localhost:5001" - }, - "browser": { - "type": "string", - "description": "The debugging browser to launch (Edge or Chrome)", - "default": "edge", - "enum": [ - "chrome", - "edge" - ] - }, - "trace": { - "type": [ - "boolean", - "string" - ], - "default": "true", - "enum": [ - "verbose", - true - ], - "description": "If true, verbose logs from JS debugger are sent to log file. If 'verbose', send logs to console." - }, - "hosted": { - "type": "boolean", - "default": "false", - "description": "True if the app is a hosted Blazor WebAssembly app, false otherwise." - }, - "webRoot": { - "type": "string", - "default": "${workspaceFolder}", - "description": "Specifies the absolute path to the webserver root." - }, - "timeout": { - "type": "number", - "default": 30000, - "description": "Retry for this number of milliseconds to connect to browser." - }, - "program": { - "type": "string", - "default": "${workspaceFolder}/Server/bin/Debug//", - "description": "The path of the DLL to execute when launching a hosted server app" - }, - "env": { - "type": "object", - "description": "Environment variables passed to dotnet. Only valid for hosted apps." - }, - "dotNetConfig": { - "description": "Options passed to the underlying .NET debugger. For more info, see https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger.md.", - "type": "object", - "required": [], - "default": {}, - "properties": { - "justMyCode": { - "type": "boolean", - "description": "Optional flag to only show user code.", - "default": true - }, - "sourceFileMap": { - "type": "object", - "description": "Optional source file mappings passed to the debug engine. Example: '{ \"C:\\foo\":\"/home/user/foo\" }'", - "additionalProperties": { - "type": "string" - }, - "default": { - "": "" - } - }, - "logging": { - "description": "Optional flags to determine what types of messages should be logged to the output window.", - "type": "object", - "required": [], - "default": {}, - "properties": { - "exceptions": { - "type": "boolean", - "description": "Optional flag to determine whether exception messages should be logged to the output window.", - "default": true - }, - "moduleLoad": { - "type": "boolean", - "description": "Optional flag to determine whether module load events should be logged to the output window.", - "default": true - }, - "programOutput": { - "type": "boolean", - "description": "Optional flag to determine whether program output should be logged to the output window when not using an external console.", - "default": true - }, - "engineLogging": { - "type": "boolean", - "description": "Optional flag to determine whether diagnostic engine logs should be logged to the output window.", - "default": false - }, - "browserStdOut": { - "type": "boolean", - "description": "Optional flag to determine if stdout text from the launching the web browser should be logged to the output window.", - "default": true - }, - "elapsedTiming": { - "type": "boolean", - "description": "If true, engine logging will include `adapterElapsedTime` and `engineElapsedTime` properties to indicate the amount of time, in microseconds, that a request took.", - "default": false - }, - "threadExit": { - "type": "boolean", - "description": "Controls if a message is logged when a thread in the target process exits. Default: `false`.", - "default": false - }, - "processExit": { - "type": "boolean", - "description": "Controls if a message is logged when the target process exits, or debugging is stopped. Default: `true`.", - "default": true - } - } - } - } - }, - "browserConfig": { - "description": "Options based to the underlying JavaScript debugger. For more info, see https://github.com/microsoft/vscode-js-debug/blob/main/OPTIONS.md.", - "type": "object", - "required": [], - "default": {}, - "properties": { - "outputCapture": { - "enum": [ - "console", - "std" - ], - "description": "From where to capture output messages: the default debug API if set to `console`, or stdout/stderr streams if set to `std`.", - "default": "console" - } - } - } - } - }, - "attach": { - "properties": { - "url": { - "type": "string", - "description": "The URL of the application", - "default": "https://localhost:5001" - }, - "cwd": { - "type": "string", - "description": "The directory of the Blazor WebAssembly app, defaults to the workspace folder.", - "default": "${workspaceFolder}" - }, - "browser": { - "type": "string", - "description": "The debugging browser to launch (Edge or Chrome)", - "default": "chrome", - "enum": [ - "chrome", - "edge" - ] - }, - "trace": { - "type": [ - "boolean", - "string" - ], - "default": "true", - "enum": [ - "verbose", - true - ], - "description": "If true, verbose logs from JS debugger are sent to log file. If 'verbose', send logs to console." - }, - "webRoot": { - "type": "string", - "default": "${workspaceFolder}", - "description": "Specifies the absolute path to the webserver root." - }, - "timeout": { - "type": "number", - "default": 30000, - "description": "Retry for this number of milliseconds to connect to browser." - } - } - } - } - } - ], - "semanticTokenTypes": [ - { - "id": "razorComponentElement", - "description": "A Razor component element" - }, - { - "id": "razorComponentAttribute", - "description": "A Razor component attribute" - }, - { - "id": "razorTagHelperElement", - "description": "A Razor TagHelper Element" - }, - { - "id": "razorTagHelperAttribute", - "description": "A Razor TagHelper Attribute" - }, - { - "id": "razorTransition", - "description": "A Razor transition" - }, - { - "id": "razorDirectiveAttribute", - "description": "A Razor Directive Attribute" - }, - { - "id": "razorDirectiveColon", - "description": "A colon between directive attribute parameters" - }, - { - "id": "razorDirective", - "description": "A Razor directive such as 'code' or 'function'" - }, - { - "id": "razorComment", - "description": "A Razor comment" - }, - { - "id": "markupCommentPunctuation", - "description": "The '@' or '*' of a Razor comment." - }, - { - "id": "markupTagDelimiter", - "description": "Markup delimiters like '<', '>', and '/'." - }, - { - "id": "markupOperator", - "description": "Delimiter for Markup Attribute Key-Value pairs." - }, - { - "id": "markupElement", - "description": "The name of a Markup element." - }, - { - "id": "markupAttribute", - "description": "The name of a Markup attribute." - }, - { - "id": "markupComment", - "description": "The contents of a Markup comment." - }, - { - "id": "markupCommentPunctuation", - "description": "The begining or ending punctuation of a Markup comment." - } - ], - "semanticTokenScopes": [ - { - "scopes": { - "razorComponentElement": [ - "entity.name.class.element.component" - ], - "razorComponentAttribute": [ - "entity.name.class.attribute.component" - ], - "razorTagHelperElement": [ - "entity.name.class.element.taghelper" - ], - "razorTagHelperAttribute": [ - "entity.name.class.attribute.taghelper" - ], - "razorTransition": [ - "keyword.control.razor.transition" - ], - "razorDirectiveAttribute": [ - "keyword.control.razor.directive.attribute", - "keyword.control.cshtml.directive.attribute" - ], - "razorDirectiveColon": [ - "keyword.control.razor.directive.colon", - "keyword.control.cshtml.directive.colon" - ], - "razorDirective": [ - "keyword.control.razor.directive", - "keyword.control.cshtml.directive" - ], - "razorComment": [ - "comment.block.razor" - ], - "razorCommentTransition": [ - "meta.comment.razor", - "keyword.control.cshtml.transition" - ], - "razorCommentStar": [ - "keyword.control.razor.comment.star", - "meta.comment.razor" - ], - "angleBracket": [ - "punctuation.definition.tag" - ], - "forwardSlash": [ - "punctuation.definition.tag" - ], - "equals": [ - "punctuation.separator.key-value.html" - ], - "markupElement": [ - "entity.name.tag.html" - ], - "markupAttribute": [ - "entity.other.attribute-name.html" - ], - "markupComment": [ - "comment.block.html" - ], - "markupCommentPunctuation": [ - "punctuation.definition.comment.html", - "comment.block.html" - ] - } - } - ], - "languages": [ - { - "id": "aspnetcorerazor", - "extensions": [ - ".cshtml", - ".razor" - ], - "mimetypes": [ - "text/x-cshtml" - ], - "configuration": "./language-configuration.json" - } - ], - "grammars": [ - { - "language": "aspnetcorerazor", - "scopeName": "text.aspnetcorerazor", - "path": "./syntaxes/aspnetcorerazor.tmLanguage.json", - "embeddedLanguages": { - "source.cs": "csharp", - "text.html.basic": "html", - "source.js": "javascript", - "source.css": "css" - } - } - ], - "commands": [ - { - "command": "extension.showRazorCSharpWindow", - "title": "Show Razor CSharp", - "category": "Razor" - }, - { - "command": "extension.showRazorHtmlWindow", - "title": "Show Razor Html", - "category": "Razor" - }, - { - "command": "razor.reportIssue", - "title": "Report a Razor issue", - "category": "Razor" - }, - { - "command": "extension.configureRazorDevMode", - "title": "Configure workspace for Razor extension development", - "category": "Razor" - }, - { - "command": "extension.resetRazorDevModeConfiguration", - "title": "Reset workspace Razor dev mode configuration", - "category": "Razor" - }, - { - "command": "extension.razorActivated", - "title": "Force activation of Razor extension", - "category": "Razor" - } - ], - "menus": { - "editor/title": [ - { - "command": "extension.showRazorCSharpWindow", - "when": "resourceLangId == aspnetcorerazor" - }, - { - "command": "extension.showRazorHtmlWindow", - "when": "resourceLangId == aspnetcorerazor" - }, - { - "command": "razor.reportIssue", - "when": "resourceLangId == aspnetcorerazor" - }, - { - "command": "extension.configureRazorDevMode" - }, - { - "command": "extension.resetRazorDevModeConfiguration" - }, - { - "command": "extension.razorActivated" - } - ] - }, - "configuration": { - "title": "Razor Configuration", - "properties": { - "razor.plugin.path": { - "type": [ - "string", - "null" - ], - "default": null, - "description": "Overrides the path to the Razor plugin dll." - }, - "razor.languageServer.debug": { - "type": "boolean", - "default": false, - "description": "Specifies whether to wait for debug attach when launching the language server." - }, - "razor.format.enable": { - "type": "boolean", - "scope": "window", - "default": true, - "description": "Enable/disable default Razor formatter." - } - } - } - }, "scripts": { "vscode:prepublish": "yarn run compile", - "clean": "rimraf dist", - "build": "yarn run clean && yarn run lint && tsc -p ./ && yarn run compile:TextMate", - "lint": "tslint --project ./", - "watch": "yarn run clean && yarn run lint && tsc -watch -p ./", + "build": "yarn run compile:TextMate", "compile:TextMate": "npx js-yaml syntaxes/aspnetcorerazor.tmLanguage.yml > syntaxes/aspnetcorerazor.tmLanguage.json" }, "devDependencies": { - "@types/node": "^17.0.2", - "@types/vscode": "1.69.0", - "cross-env": "^5.2.0", - "js-yaml": ">=3.13.1", - "minimatch": "3.0.5", - "rimraf": "2.6.3", - "tslint": "^5.11.0", - "typescript": "^4.5.4" - }, - "dependencies": { - "diff": ">=3.5.0", - "microsoft.aspnetcore.razor.vscode": "file:../Microsoft.AspNetCore.Razor.VSCode" + "js-yaml": ">=3.13.1" } -} +} \ No newline at end of file diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode.Extension/src/RazorDevModeHelpers.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode.Extension/src/RazorDevModeHelpers.ts deleted file mode 100644 index 47956da62a6..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode.Extension/src/RazorDevModeHelpers.ts +++ /dev/null @@ -1,62 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -import * as fs from 'fs'; -import * as path from 'path'; -import * as vscode from 'vscode'; - -export async function registerRazorDevModeHelpers(context: vscode.ExtensionContext) { - const razorConfiguration = vscode.workspace.getConfiguration('razor'); - - const unconfigureSubscription = vscode.commands.registerCommand('extension.resetRazorDevModeConfiguration', async () => { - await razorConfiguration.update('devmode', undefined); - - const pluginConfiguration = vscode.workspace.getConfiguration('razor.plugin'); - await pluginConfiguration.update('path', undefined); - - // Settings have been updated, lets reload the window. - await vscode.commands.executeCommand('workbench.action.reloadWindow'); - }); - context.subscriptions.push(unconfigureSubscription); - - const configureSubscription = vscode.commands.registerCommand('extension.configureRazorDevMode', async () => { - await razorConfiguration.update('devmode', true); - await razorConfiguration.update('trace', 'Verbose'); - - const config = process.env.config ? process.env.config : 'Debug'; - const pluginPath = path.join( - __dirname, '..', '..', '..', '..', '..', 'artifacts', 'bin', 'Microsoft.AspNetCore.Razor.OmniSharpPlugin', config, 'net472', 'Microsoft.AspNetCore.Razor.OmniSharpPlugin.dll'); - - if (!fs.existsSync(pluginPath)) { - vscode.window.showErrorMessage(`The Razor Language Server O# plugin has not yet been built - could not find ${pluginPath}`); - return; - } - - const pluginConfiguration = vscode.workspace.getConfiguration('razor.plugin'); - await pluginConfiguration.update('path', pluginPath); - - // Settings have been updated, lets reload the window. - await vscode.commands.executeCommand('workbench.action.reloadWindow'); - }); - context.subscriptions.push(configureSubscription); -} - -export function ensureWorkspaceIsConfigured() { - const razorConfiguration = vscode.workspace.getConfiguration('razor'); - if (!razorConfiguration.get('devmode')) { - // Running in a workspace without devmode enabled. We should prompt the user to configure the workspace. - vscode.window.showErrorMessage( - 'This workspace is not configured to use the local Razor extension.', - 'Configure and Reload').then(async (reloadResponse) => { - if (reloadResponse === 'Configure and Reload') { - await vscode.commands.executeCommand('extension.configureRazorDevMode'); - } - }); - - return false; - } - - return true; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode.Extension/src/extension.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode.Extension/src/extension.ts deleted file mode 100644 index 688c330772e..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode.Extension/src/extension.ts +++ /dev/null @@ -1,63 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -import * as fs from 'fs'; -import * as razorExtensionPackage from 'microsoft.aspnetcore.razor.vscode'; -import * as path from 'path'; -import * as vscode from 'vscode'; -import { ensureWorkspaceIsConfigured, registerRazorDevModeHelpers } from './RazorDevModeHelpers'; - -let activationResolver: (value?: any) => void; -export const extensionActivated = new Promise(resolve => { - activationResolver = resolve; -}); - -export async function activate(context: vscode.ExtensionContext) { - // Because this extension is only used for local development and tests in CI, - // we know the Razor Language Server is at a specific path within this repo - const config = process.env.config ? process.env.config : 'Debug'; - - const languageServerDir = path.join( - __dirname, '..', '..', '..', '..', '..', 'artifacts', 'bin', 'rzls', config, 'net7.0'); - - if (!fs.existsSync(languageServerDir)) { - vscode.window.showErrorMessage(`The Razor Language Server project has not yet been built - could not find ${languageServerDir}`); - return; - } - - const hostEventStream = { - post: (event: any) => { - // 1 corresponds to the telemetry event type from OmniSharp - if (event.type === 1) { - console.log(`Telemetry Event: ${event.eventName}.`); - if (event.properties) { - const propertiesString = JSON.stringify(event.properties, null, 2); - console.log(propertiesString); - } - } else { - console.log(`Unknown event: ${event.eventName}`); - } - }, - }; - - vscode.commands.registerCommand('extension.razorActivated', () => extensionActivated); - - await registerRazorDevModeHelpers(context); - const workspaceConfigured = ensureWorkspaceIsConfigured(); - - if (workspaceConfigured) { - await razorExtensionPackage.activate( - vscode, - context, - languageServerDir, - hostEventStream, - /* enabledProposedApis */true); - } else { - console.warn('Razor workspace was not configured, extension activation skipped.'); - console.warn('To configure your workspace run the following command (ctrl+shift+p) in the experimental instance "Razor: Configure workspace for Razor extension development"'); - } - - activationResolver(); -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode.Extension/tsconfig.json b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode.Extension/tsconfig.json deleted file mode 100644 index 9143e181a64..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode.Extension/tsconfig.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "extends": "../../tsconfig.json", - "compilerOptions": { - "outDir": "dist" - }, - "include": [ - "./src/**/*" - ] - } \ No newline at end of file diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode.Extension/tslint.json b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode.Extension/tslint.json deleted file mode 100644 index 40a18cdec2d..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode.Extension/tslint.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": "../../tslint.json" -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/.npmrc b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/.npmrc deleted file mode 100644 index 4648b8ba45b..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/.npmrc +++ /dev/null @@ -1,2 +0,0 @@ -# Auto generated file from Gardener Plugin CentralFeedServiceAdoptionPlugin -registry=https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-public-npm/npm/registry/ \ No newline at end of file diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/Microsoft.AspNetCore.Razor.VSCode.npmproj b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/Microsoft.AspNetCore.Razor.VSCode.npmproj deleted file mode 100644 index 88b64bd2ace..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/Microsoft.AspNetCore.Razor.VSCode.npmproj +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - microsoft.aspnetcore.razor.vscode - netstandard2.0 - true - - - false - - - - - - - - - diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/package.json b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/package.json deleted file mode 100644 index a176fa23462..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/package.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "microsoft.aspnetcore.razor.vscode", - "private": true, - "version": "0.0.1", - "defaults": { - "razor": "0.0.1" - }, - "description": "VS Code library for Razor language support.", - "devDependencies": { - "@types/node": "^10.9.4", - "@types/vscode": "1.69.0", - "js-yaml": ">=3.13.1", - "minimatch": "3.0.5", - "rimraf": "2.6.3", - "tslint": "^5.11.0", - "typescript": "~4.5.4" - }, - "dependencies": { - "ps-list": "7.2.0", - "vscode-html-languageservice": "^5.0.1", - "vscode-languageclient": "8.0.2", - "vscode-languageserver-textdocument": "^1.0.5" - }, - "main": "./dist/extension.js", - "types": "./dist/extension.d.ts", - "engines": { - "vscode": "1.69.0" - }, - "scripts": { - "clean": "rimraf out && rimraf dist", - "build": "yarn run clean && yarn run lint && tsc -p ./", - "lint": "tslint ./src/**/*.ts --project ./", - "watch": "tsc -watch -p ./" - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/BlazorDebug/BlazorDebugConfigurationProvider.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/BlazorDebug/BlazorDebugConfigurationProvider.ts deleted file mode 100644 index 81d9574862b..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/BlazorDebug/BlazorDebugConfigurationProvider.ts +++ /dev/null @@ -1,142 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ -import { readFileSync } from 'fs'; -import { join } from 'path'; -import { fileURLToPath } from 'url'; -import * as vscode from 'vscode'; - -import { RazorLogger } from '../RazorLogger'; -import { JS_DEBUG_NAME, SERVER_APP_NAME } from './Constants'; -import { onDidTerminateDebugSession } from './TerminateDebugHandler'; - -export class BlazorDebugConfigurationProvider implements vscode.DebugConfigurationProvider { - - constructor(private readonly logger: RazorLogger, private readonly vscodeType: typeof vscode) { } - - public async resolveDebugConfiguration(folder: vscode.WorkspaceFolder | undefined, configuration: vscode.DebugConfiguration): Promise { - /** - * The Blazor WebAssembly app should only be launched if the - * launch configuration is a launch request. Attach requests will - * only launch the browser. - */ - if (configuration.request === 'launch') { - await this.launchApp(folder, configuration); - } - - let inspectUri = '{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}'; - let url = 'https://localhost:5001'; - try { - if (folder !== undefined) { - let folderPath = configuration.cwd ? configuration.cwd : fileURLToPath(folder.uri.toString()); - folderPath = folderPath.replace('${workspaceFolder}', fileURLToPath(folder.uri.toString())); - const launchSettings = JSON.parse(readFileSync(join(folderPath, 'Properties', 'launchSettings.json'), 'utf8')); - if (launchSettings?.profiles && launchSettings?.profiles[Object.keys(launchSettings.profiles)[0]]?.inspectUri) { - inspectUri = launchSettings.profiles[Object.keys(launchSettings.profiles)[0]].inspectUri; - url = launchSettings.profiles[Object.keys(launchSettings.profiles)[0]].applicationUrl.split(';', 1)[0]; - } - } - } catch (error: any) { - this.logger.logError('[DEBUGGER] Error while getting information from launchSettings.json: ', error as Error); - } - - await this.launchBrowser( - folder, - configuration, - inspectUri, - url); - - /** - * If `resolveDebugConfiguration` returns undefined, then the debugger - * launch is canceled. Here, we opt to manually launch the browser - * configuration using `startDebugging` above instead of returning - * the configuration to avoid a bug where VS Code is unable to resolve - * the debug adapter for the browser debugger. - */ - return undefined; - } - - private async launchApp(folder: vscode.WorkspaceFolder | undefined, configuration: vscode.DebugConfiguration) { - const program = configuration.hosted ? configuration.program : 'dotnet'; - const cwd = configuration.cwd || '${workspaceFolder}'; - const args = configuration.hosted ? [] : ['run']; - - const app = { - name: SERVER_APP_NAME, - type: 'coreclr', - request: 'launch', - prelaunchTask: 'build', - program, - args, - cwd, - env: { - ASPNETCORE_ENVIRONMENT: 'Development', - ...configuration.env, - }, - launchBrowser: { - enabled: false, - }, - ...configuration.dotNetConfig, - }; - - try { - await this.vscodeType.debug.startDebugging(folder, app); - if (process.platform !== 'win32') { - const terminate = this.vscodeType.debug.onDidTerminateDebugSession(async event => { - const blazorDevServer = 'blazor-devserver\\.dll'; - const dir = folder && folder.uri && folder.uri.fsPath; - const regexEscapedDir = dir!.toLowerCase()!.replace(/\//g, '\\/'); - const launchedApp = configuration.hosted ? app.program : `${regexEscapedDir}.*${blazorDevServer}|${blazorDevServer}.*${regexEscapedDir}`; - await onDidTerminateDebugSession(event, this.logger, launchedApp); - terminate.dispose(); - }); - } - } catch (error) { - this.logger.logError('[DEBUGGER] Error when launching application: ', error as Error); - } - } - - private async launchBrowser(folder: vscode.WorkspaceFolder | undefined, configuration: vscode.DebugConfiguration, inspectUri: string, url: string) { - const browser = { - name: JS_DEBUG_NAME, - type: configuration.browser === 'edge' ? 'pwa-msedge' : 'pwa-chrome', - request: 'launch', - timeout: configuration.timeout || 30000, - url: configuration.url || url, - webRoot: configuration.webRoot || '${workspaceFolder}', - inspectUri, - trace: configuration.trace || false, - noDebug: configuration.noDebug || false, - ...configuration.browserConfig, - // When the browser debugging session is stopped, propogate - // this and terminate the debugging session of the Blazor dev server. - cascadeTerminateToConfigurations: [SERVER_APP_NAME], - }; - - try { - /** - * The browser debugger will immediately launch after the - * application process is started. It waits a `timeout` - * interval before crashing after being unable to find the launched - * process. - * - * We do this to provide immediate visual feedback to the user - * that their debugger session has started. - */ - await this.vscodeType.debug.startDebugging(folder, browser); - } catch (error) { - this.logger.logError( - '[DEBUGGER] Error when launching browser debugger: ', - error as Error, - ); - const message = `There was an unexpected error while launching your debugging session. Check the console for helpful logs and visit the debugging docs for more info.`; - this.vscodeType.window.showErrorMessage(message, `View Debug Docs`, `Ignore`).then(async result => { - if (result === 'View Debug Docs') { - const debugDocsUri = 'https://aka.ms/blazorwasmcodedebug'; - await this.vscodeType.commands.executeCommand(`vcode.open`, debugDocsUri); - } - }); - } - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/BlazorDebug/Constants.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/BlazorDebug/Constants.ts deleted file mode 100644 index 8386314dff4..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/BlazorDebug/Constants.ts +++ /dev/null @@ -1,7 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -export const SERVER_APP_NAME = '.NET Application Server'; -export const JS_DEBUG_NAME = 'Debug Blazor Web Assembly in Browser'; diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/BlazorDebug/TerminateDebugHandler.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/BlazorDebug/TerminateDebugHandler.ts deleted file mode 100644 index 912d767789e..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/BlazorDebug/TerminateDebugHandler.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -import * as psList from 'ps-list'; -import { DebugSession } from 'vscode'; -import { RazorLogger } from '../RazorLogger'; -import { JS_DEBUG_NAME, SERVER_APP_NAME } from './Constants'; - -export const isValidEvent = (name: string) => { - - // The name can be of the form: `Debug Blazor Web Assembly in Browser: https://localhost:7291` - // hence we have to examine what the name **startsWith** - // we cannot use startsWith otherwise when we close a login window we will receive a name like this - // `Debug Blazor Web Assembly in Browser: https://localhost:5001/authentication/login-callback#state=eyJpZCI6ImEwYjQ5MDMzL` and will kill the app - return name === JS_DEBUG_NAME || name === SERVER_APP_NAME; -}; - -const killProcess = (targetPid: number | undefined, logger: RazorLogger) => { - // If no PID was provided, then exit early. - if (!targetPid) { - return; - } - - try { - logger.logVerbose(`[DEBUGGER] Terminating debugging session with PID ${targetPid}...`); - process.kill(targetPid); - } catch (error) { - logger.logError(`[DEBUGGER] Error terminating debug processes with PID ${targetPid}: `, error as Error); - } -}; - -export async function onDidTerminateDebugSession( - event: DebugSession, - logger: RazorLogger, - target: string | number | undefined, -) { - if (!target) { - return; - } - - if (typeof target === 'number') { - terminateByPid(event, logger, target); - } else { - await terminateByProcessName(event, logger, target); - } -} - -function terminateByPid( - event: DebugSession, - logger: RazorLogger, - targetPid: number | undefined, -) { - // Ignore debug sessions that are not applicable to us - if (!isValidEvent(event.name)) { - return; - } - - killProcess(targetPid, logger); -} - -async function terminateByProcessName( - event: DebugSession, - logger: RazorLogger, - targetProcess: string, -) { - // Ignore debug sessions that are not applicable to us - if (!isValidEvent(event.name)) { - return; - } - - let processes: psList.ProcessDescriptor[] = []; - try { - processes = await psList(); - } catch (error) { - logger.logError(`Error retrieving processes to clean-up: `, error as Error); - } - - const devserver = processes.find( - (process: psList.ProcessDescriptor) => !!(process && process.cmd && process.cmd.toLowerCase().match(targetProcess))); - - if (devserver) { - killProcess(devserver.pid, logger); - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CSharp/CSharpPreviewPanel.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CSharp/CSharpPreviewPanel.ts deleted file mode 100644 index 98a0d9e21b8..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CSharp/CSharpPreviewPanel.ts +++ /dev/null @@ -1,141 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { IRazorDocumentChangeEvent } from '../Document/IRazorDocumentChangeEvent'; -import { RazorDocumentChangeKind } from '../Document/RazorDocumentChangeKind'; -import { RazorDocumentManager } from '../Document/RazorDocumentManager'; -import { getUriPath } from '../UriPaths'; - -export class CSharpPreviewPanel { - public static readonly viewType = 'razorCSharpPreview'; - - private panel: vscode.WebviewPanel | undefined; - private csharpContent: string | undefined; - - constructor( - private readonly documentManager: RazorDocumentManager) { - documentManager.onChange((event) => this.documentChanged(event)); - } - - public async show() { - if (this.panel) { - this.panel.reveal(vscode.ViewColumn.Two); - } else { - this.panel = vscode.window.createWebviewPanel( - CSharpPreviewPanel.viewType, - 'Razor C# Preview', - vscode.ViewColumn.Two, { - enableScripts: true, - // Disallow any remote sources - localResourceRoots: [], - }); - this.attachToCurrentPanel(); - } - - await this.update(); - } - - public async revive(panel: vscode.WebviewPanel) { - this.panel = panel; - this.attachToCurrentPanel(); - await this.update(); - } - - private async documentChanged(event: IRazorDocumentChangeEvent) { - if (!this.panel) { - return; - } - - if (event.kind === RazorDocumentChangeKind.csharpChanged || - event.kind === RazorDocumentChangeKind.opened || - event.kind === RazorDocumentChangeKind.closed) { - await this.update(); - } - } - - private attachToCurrentPanel() { - if (!this.panel) { - vscode.window.showErrorMessage('Unexpected error when attaching to C# preview window.'); - return; - } - - this.panel.webview.onDidReceiveMessage(async message => { - switch (message.command) { - case 'copy': - if (!this.csharpContent) { - return; - } - - await vscode.env.clipboard.writeText(this.csharpContent); - vscode.window.showInformationMessage('Razor C# copied to clipboard'); - return; - } - }); - this.panel.onDidDispose(() => this.panel = undefined); - } - - private async update() { - if (!this.panel) { - return; - } - const document = await this.documentManager.getActiveDocument(); - let hostDocumentFilePath = ''; - let virtualDocumentFilePath = ''; - - if (document) { - // The document is guaranteed to be a Razor document - this.csharpContent = document.csharpDocument.getContent(); - hostDocumentFilePath = getUriPath(document.uri); - virtualDocumentFilePath = getUriPath(document.csharpDocument.uri); - } else { - this.csharpContent = undefined; - } - - let content = this.csharpContent ? this.csharpContent : ''; - content = content.replace(/ - - - - - - Report a Razor issue - - - - - -

Host document file path: ${hostDocumentFilePath}

-

Virtual document file path: ${virtualDocumentFilePath}

-
-
${content}
- -`; - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CSharp/CSharpProjectedDocument.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CSharp/CSharpProjectedDocument.ts deleted file mode 100644 index d01e73dc844..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CSharp/CSharpProjectedDocument.ts +++ /dev/null @@ -1,102 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -import { IProjectedDocument } from '../Projection/IProjectedDocument'; -import { ServerTextChange } from '../RPC/ServerTextChange'; -import { getUriPath } from '../UriPaths'; -import * as vscode from '../vscodeAdapter'; - -export class CSharpProjectedDocument implements IProjectedDocument { - public readonly path: string; - - private content = ''; - private preProvisionalContent: string | undefined; - private provisionalEditAt: number | undefined; - private hostDocumentVersion: number | null = null; - private projectedDocumentVersion = 0; - - public constructor(public readonly uri: vscode.Uri) { - this.path = getUriPath(uri); - } - - public get hostDocumentSyncVersion(): number | null { - return this.hostDocumentVersion; - } - - public get projectedDocumentSyncVersion(): number { - return this.projectedDocumentVersion; - } - - public update(edits: ServerTextChange[], hostDocumentVersion: number) { - this.removeProvisionalDot(); - - this.hostDocumentVersion = hostDocumentVersion; - - if (edits.length === 0) { - return; - } - - let content = this.content; - for (const edit of edits.reverse()) { - // TODO: Use a better data structure to represent the content, string concatenation is slow. - content = this.getEditedContent(edit.newText, edit.span.start, edit.span.start + edit.span.length, content); - } - - this.setContent(content); - } - - public reset() { - this.provisionalEditAt = undefined; - this.preProvisionalContent = undefined; - this.hostDocumentVersion = null; - this.setContent(''); - } - - public getContent() { - return this.content; - } - - // A provisional dot represents a '.' that's inserted into the projected document but will be - // removed prior to any edits that get applied. In Razor's case a provisional dot is used to - // show completions after an expression for a dot that's usually interpreted as Html. - public addProvisionalDotAt(index: number) { - if (this.provisionalEditAt === index) { - // Edits already applied. - return; - } - - this.removeProvisionalDot(); - - const newContent = this.getEditedContent('.', index, index, this.content); - this.preProvisionalContent = this.content; - this.provisionalEditAt = index; - this.setContent(newContent); - } - - public removeProvisionalDot() { - if (this.provisionalEditAt && this.preProvisionalContent) { - // Undo provisional edit if one was applied. - this.setContent(this.preProvisionalContent); - this.provisionalEditAt = undefined; - this.preProvisionalContent = undefined; - return true; - } - - return false; - } - - private getEditedContent(newText: string, start: number, end: number, content: string) { - const before = content.substr(0, start); - const after = content.substr(end); - content = `${before}${newText}${after}`; - - return content; - } - - private setContent(content: string) { - this.projectedDocumentVersion++; - this.content = content; - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CSharp/CSharpProjectedDocumentContentProvider.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CSharp/CSharpProjectedDocumentContentProvider.ts deleted file mode 100644 index 88a801c8b2f..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CSharp/CSharpProjectedDocumentContentProvider.ts +++ /dev/null @@ -1,70 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -import { IRazorDocumentChangeEvent } from '../Document/IRazorDocumentChangeEvent'; -import { IRazorDocumentManager } from '../Document/IRazorDocumentManager'; -import { RazorDocumentChangeKind } from '../Document/RazorDocumentChangeKind'; -import { IEventEmitterFactory } from '../IEventEmitterFactory'; -import { RazorLogger } from '../RazorLogger'; -import { getUriPath } from '../UriPaths'; -import * as vscode from '../vscodeAdapter'; - -export class CSharpProjectedDocumentContentProvider implements vscode.TextDocumentContentProvider { - public static readonly scheme = 'virtualCSharp-razor'; - - private readonly onDidChangeEmitter: vscode.EventEmitter; - - constructor( - private readonly documentManager: IRazorDocumentManager, - eventEmitterFactory: IEventEmitterFactory, - private readonly logger: RazorLogger) { - documentManager.onChange((event: IRazorDocumentChangeEvent) => this.documentChanged(event)); - this.onDidChangeEmitter = eventEmitterFactory.create(); - } - - public get onDidChange() { return this.onDidChangeEmitter.event; } - - public async provideTextDocumentContent(uri: vscode.Uri) { - const razorDocument = this.findRazorDocument(uri); - if (!razorDocument) { - // Document was removed from the document manager, meaning there's no more content for this - // file. Report an empty document. - - if (this.logger.verboseEnabled) { - this.logger.logVerbose( - `Could not find document '${getUriPath(uri)}' when updating the C# buffer. This typically happens when a document is removed.`); - } - return ''; - } - - const content = `${razorDocument.csharpDocument.getContent()} -// ${razorDocument.csharpDocument.projectedDocumentSyncVersion}`; - - return content; - } - - public ensureDocumentContent(uri: vscode.Uri) { - this.onDidChangeEmitter.fire(uri); - } - - private documentChanged(event: IRazorDocumentChangeEvent) { - if (event.kind === RazorDocumentChangeKind.csharpChanged || - event.kind === RazorDocumentChangeKind.opened || - event.kind === RazorDocumentChangeKind.removed) { - // We also notify changes on document removal in order to tell VSCode that there's no more - // C# content for the file. - - this.onDidChangeEmitter.fire(event.document.csharpDocument.uri); - } - } - - private findRazorDocument(uri: vscode.Uri) { - const projectedPath = getUriPath(uri); - - return this.documentManager.documents.find(razorDocument => - razorDocument.csharpDocument.path.localeCompare( - projectedPath, undefined, { sensitivity: 'base' }) === 0); - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CSharp/RazorCSharpFeature.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CSharp/RazorCSharpFeature.ts deleted file mode 100644 index a2b92dae03c..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CSharp/RazorCSharpFeature.ts +++ /dev/null @@ -1,43 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { RazorDocumentManager } from '../Document/RazorDocumentManager'; -import { IEventEmitterFactory } from '../IEventEmitterFactory'; -import { RazorLogger } from '../RazorLogger'; -import { CSharpPreviewPanel } from './CSharpPreviewPanel'; -import { CSharpProjectedDocumentContentProvider } from './CSharpProjectedDocumentContentProvider'; - -export class RazorCSharpFeature { - public readonly projectionProvider: CSharpProjectedDocumentContentProvider; - private readonly csharpPreviewPanel: CSharpPreviewPanel; - - constructor( - documentManager: RazorDocumentManager, - eventEmitterFactory: IEventEmitterFactory, - logger: RazorLogger) { - this.projectionProvider = new CSharpProjectedDocumentContentProvider(documentManager, eventEmitterFactory, logger); - this.csharpPreviewPanel = new CSharpPreviewPanel(documentManager); - } - - public register() { - const registrations = [ - vscode.workspace.registerTextDocumentContentProvider( - CSharpProjectedDocumentContentProvider.scheme, this.projectionProvider), - vscode.commands.registerCommand( - 'extension.showRazorCSharpWindow', () => this.csharpPreviewPanel.show()), - ]; - - if (vscode.window.registerWebviewPanelSerializer) { - registrations.push(vscode.window.registerWebviewPanelSerializer(CSharpPreviewPanel.viewType, { - deserializeWebviewPanel: async (panel: vscode.WebviewPanel) => { - await this.csharpPreviewPanel.revive(panel); - }, - })); - } - - return vscode.Disposable.from(...registrations); - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CodeActions/CodeActionsHandler.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CodeActions/CodeActionsHandler.ts deleted file mode 100644 index cb3608e4bc4..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CodeActions/CodeActionsHandler.ts +++ /dev/null @@ -1,66 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * 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 { RequestType } from 'vscode-languageclient'; -import { RazorDocumentManager } from '../Document/RazorDocumentManager'; -import { RazorLanguageServerClient } from '../RazorLanguageServerClient'; -import { RazorLogger } from '../RazorLogger'; -import { convertRangeFromSerializable } from '../RPC/SerializableRange'; -import { RazorCodeAction } from './RazorCodeAction'; -import { SerializableDelegatedCodeActionParams } from './SerializableDelegatedCodeActionParams'; - -export class CodeActionsHandler { - private static readonly provideCodeActionsEndpoint = 'razor/provideCodeActions'; - private codeActionRequestType: RequestType = new RequestType(CodeActionsHandler.provideCodeActionsEndpoint); - private emptyCodeActionResponse: RazorCodeAction[] = []; - - constructor( - private readonly documentManager: RazorDocumentManager, - private readonly serverClient: RazorLanguageServerClient, - private readonly logger: RazorLogger) { } - - public register() { - return this.serverClient.onRequestWithParams( - this.codeActionRequestType, - async (request, token) => this.provideCodeActions(request, token)); - } - - private async provideCodeActions( - delegatedCodeActionParams: SerializableDelegatedCodeActionParams, - cancellationToken: vscode.CancellationToken) { - try { - const codeActionParams = delegatedCodeActionParams.codeActionParams; - const razorDocumentUri = vscode.Uri.parse(codeActionParams.textDocument.uri, true); - const razorDocument = await this.documentManager.getDocument(razorDocumentUri); - if (razorDocument === undefined) { - return this.emptyCodeActionResponse; - } - - const virtualCSharpUri = razorDocument.csharpDocument.uri; - - const range = convertRangeFromSerializable(codeActionParams.range); - - const commands = await vscode.commands.executeCommand( - 'vscode.executeCodeActionProvider', - virtualCSharpUri, - range) as vscode.Command[]; - - if (commands.length === 0) { - return this.emptyCodeActionResponse; - } - - return commands.map(c => this.commandAsCodeAction(c)); - } catch (error) { - this.logger.logWarning(`${CodeActionsHandler.provideCodeActionsEndpoint} failed with ${error}`); - } - - return this.emptyCodeActionResponse; - } - - private commandAsCodeAction(command: vscode.Command): RazorCodeAction { - return { title: command.title, data: { CustomTags: ['CodeActionFromVSCode'] } } as RazorCodeAction; - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CodeActions/RazorCodeAction.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CodeActions/RazorCodeAction.ts deleted file mode 100644 index 49a63fd601f..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CodeActions/RazorCodeAction.ts +++ /dev/null @@ -1,14 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -import { SerializableWorkspaceEdit } from '../RPC/SerializableWorkspaceEdit'; -import { RazorCodeActionDataParams } from './RazorCodeActionDataParams'; -import { RazorCodeActionResolutionParams } from './RazorCodeActionResolutionParams'; - -export interface RazorCodeAction { - title: string; - edit: SerializableWorkspaceEdit; - data: RazorCodeActionResolutionParams | RazorCodeActionDataParams; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CodeActions/RazorCodeActionDataParams.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CodeActions/RazorCodeActionDataParams.ts deleted file mode 100644 index a15d48dc9a1..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CodeActions/RazorCodeActionDataParams.ts +++ /dev/null @@ -1,8 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -export interface RazorCodeActionDataParams { - CustomTags: string[]; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CodeActions/RazorCodeActionResolutionParams.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CodeActions/RazorCodeActionResolutionParams.ts deleted file mode 100644 index c2938e1d75e..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CodeActions/RazorCodeActionResolutionParams.ts +++ /dev/null @@ -1,9 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -export interface RazorCodeActionResolutionParams { - action: string; - data: object; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CodeActions/RazorCodeActionRunner.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CodeActions/RazorCodeActionRunner.ts deleted file mode 100644 index 351a5dbe5da..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CodeActions/RazorCodeActionRunner.ts +++ /dev/null @@ -1,47 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { RazorLanguageServerClient } from '../RazorLanguageServerClient'; -import { RazorLogger } from '../RazorLogger'; -import { convertWorkspaceEditFromSerializable } from '../RPC/SerializableWorkspaceEdit'; -import { RazorCodeAction } from './RazorCodeAction'; -import { RazorCodeActionResolutionParams } from './RazorCodeActionResolutionParams'; - -export class RazorCodeActionRunner { - private static readonly codeActionResolveEndpoint = 'textDocument/codeActionResolve'; - private static readonly razorCodeActionRunnerCommand = 'razor/runCodeAction'; - - constructor( - private readonly serverClient: RazorLanguageServerClient, - private readonly logger: RazorLogger, - ) {} - - public register(): vscode.Disposable { - return vscode.commands.registerCommand( - RazorCodeActionRunner.razorCodeActionRunnerCommand, - (request: RazorCodeActionResolutionParams) => this.runCodeAction(request), - this); - } - - private async runCodeAction(request: RazorCodeActionResolutionParams): Promise { - const response: RazorCodeAction = await this.serverClient.sendRequest( - RazorCodeActionRunner.codeActionResolveEndpoint, - { data: request, title: request.action }); - - let changesWorkspaceEdit: vscode.WorkspaceEdit; - let documentChangesWorkspaceEdit: vscode.WorkspaceEdit; - - try { - changesWorkspaceEdit = convertWorkspaceEditFromSerializable({changes: response.edit.changes}); - documentChangesWorkspaceEdit = convertWorkspaceEditFromSerializable({documentChanges: response.edit.documentChanges}); - } catch (error) { - this.logger.logError(`Unexpected error deserializing code action for ${request.action}`, error as Error); - return Promise.resolve(false); - } - - return vscode.workspace.applyEdit(documentChangesWorkspaceEdit).then(() => vscode.workspace.applyEdit(changesWorkspaceEdit)); - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CodeActions/SerializableCodeActionParams.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CodeActions/SerializableCodeActionParams.ts deleted file mode 100644 index 9db223e9915..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CodeActions/SerializableCodeActionParams.ts +++ /dev/null @@ -1,12 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -import { SerializableRange } from '../RPC/SerializableRange'; -import { SerializableTextDocumentIdentifier } from '../RPC/SerializableTextDocumentIdentifier'; - -export interface SerializableCodeActionParams { - textDocument: SerializableTextDocumentIdentifier; - range: SerializableRange; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CodeActions/SerializableDelegatedCodeActionParams.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CodeActions/SerializableDelegatedCodeActionParams.ts deleted file mode 100644 index adae7b6e520..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CodeActions/SerializableDelegatedCodeActionParams.ts +++ /dev/null @@ -1,10 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -import { SerializableCodeActionParams } from './SerializableCodeActionParams'; - -export interface SerializableDelegatedCodeActionParams { - codeActionParams: SerializableCodeActionParams; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CodeLens/RazorCodeLens.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CodeLens/RazorCodeLens.ts deleted file mode 100644 index 973fc82a8dc..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CodeLens/RazorCodeLens.ts +++ /dev/null @@ -1,17 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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'; - -export class RazorCodeLens extends vscode.CodeLens { - constructor( - range: vscode.Range, - public uri: vscode.Uri, - public document: vscode.TextDocument, - command?: vscode.Command) { - - super(range, command); - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CodeLens/RazorCodeLensProvider.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CodeLens/RazorCodeLensProvider.ts deleted file mode 100644 index 8768dbe626a..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/CodeLens/RazorCodeLensProvider.ts +++ /dev/null @@ -1,134 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { RazorDocumentChangeKind } from '../Document/RazorDocumentChangeKind'; -import { RazorDocumentManager } from '../Document/RazorDocumentManager'; -import { RazorDocumentSynchronizer } from '../Document/RazorDocumentSynchronizer'; -import { RazorLanguageFeatureBase } from '../RazorLanguageFeatureBase'; -import { RazorLanguageServiceClient } from '../RazorLanguageServiceClient'; -import { RazorLogger } from '../RazorLogger'; -import { LanguageKind } from '../RPC/LanguageKind'; -import { RazorCodeLens } from './RazorCodeLens'; -export class RazorCodeLensProvider - extends RazorLanguageFeatureBase - implements vscode.CodeLensProvider { - - public onDidChangeCodeLenses: vscode.Event; - - constructor( - documentSynchronizer: RazorDocumentSynchronizer, - documentManager: RazorDocumentManager, - serviceClient: RazorLanguageServiceClient, - logger: RazorLogger) { - - super(documentSynchronizer, documentManager, serviceClient, logger); - - const onCodeLensChangedEmitter = new vscode.EventEmitter(); - this.onDidChangeCodeLenses = onCodeLensChangedEmitter.event; - - documentManager.onChange(async (event) => { - if (event.kind !== RazorDocumentChangeKind.added) { - return; - } - - // Sometimes when a file already open in the editor is renamed, provideCodeLens would return empty - // because the background C# document is not ready yet. So, when that happens we should manually invoke - // a code lens refresh after waiting for a little while. - const openDocumentUris = vscode.workspace.textDocuments.filter(doc => !doc.isClosed).map(doc => doc.uri); - if (openDocumentUris.includes(event.document.uri)) { - await new Promise(r => setTimeout(r, 5000)); - onCodeLensChangedEmitter.fire(); - } - }); - } - - public async provideCodeLenses(document: vscode.TextDocument, token: vscode.CancellationToken) { - try { - const razorDocument = await this.documentManager.getDocument(document.uri); - if (!razorDocument) { - return; - } - - const csharpDocument = razorDocument.csharpDocument; - - // Get all the code lenses that applies to our projected C# document. - const codeLenses = await vscode.commands.executeCommand( - 'vscode.executeCodeLensProvider', - csharpDocument.uri) as vscode.CodeLens[]; - if (!codeLenses) { - return; - } - - // Re-map the CodeLens locations to the original Razor document. - const remappedCodeLenses = new Array(); - for (const codeLens of codeLenses) { - const result = await this.serviceClient.mapToDocumentRanges( - LanguageKind.CSharp, - [codeLens.range], - razorDocument.uri); - if (result && result.ranges.length > 0) { - const newCodeLens = new RazorCodeLens(result.ranges[0], razorDocument.uri, document, codeLens.command); - remappedCodeLenses.push(newCodeLens); - } else { - // This means this CodeLens was for non-user code. We can safely ignore those. - } - } - - return remappedCodeLenses; - - } catch (error) { - this.logger.logWarning(`provideCodeLens failed with ${error}`); - return []; - } - } - - public async resolveCodeLens(codeLens: vscode.CodeLens, token: vscode.CancellationToken) { - if (codeLens instanceof RazorCodeLens) { - return this.resolveRazorCodeLens(codeLens, token); - } - } - - private async resolveRazorCodeLens(codeLens: RazorCodeLens, token: vscode.CancellationToken): Promise { - // Initialize with default values. - codeLens.command = { - title: '', - command: '', - arguments: [], - }; - - try { - const razorDocument = await this.documentManager.getDocument(codeLens.uri); - if (!razorDocument) { - return codeLens; - } - - // Make sure this CodeLens is for a valid location in the projected C# document. - const projection = await this.getProjection(codeLens.document, codeLens.range.start, token); - if (!projection || projection.languageKind !== LanguageKind.CSharp) { - return codeLens; - } - - const references = await vscode.commands.executeCommand( - 'vscode.executeReferenceProvider', - projection.uri, - projection.position) as vscode.Location[]; - - // We now have a list of references to show in the CodeLens. - const count = references.length; - codeLens.command = { - title: count === 1 ? '1 reference' : `${count} references`, - command: 'editor.action.showReferences', - arguments: [razorDocument.uri, codeLens.range.start, references], - }; - - return codeLens; - - } catch (error) { - this.logger.logWarning(`resolveCodeLens failed with ${error}`); - return codeLens; - } - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/ColorPresentation/ColorPresentationContext.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/ColorPresentation/ColorPresentationContext.ts deleted file mode 100644 index 309fb127320..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/ColorPresentation/ColorPresentationContext.ts +++ /dev/null @@ -1,14 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { Range } from 'vscode-languageserver-types'; - -export class ColorPresentationContext { - constructor( - public readonly uri: vscode.Uri, - public readonly range: Range) { - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/ColorPresentation/ColorPresentationHandler.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/ColorPresentation/ColorPresentationHandler.ts deleted file mode 100644 index 5feca93009f..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/ColorPresentation/ColorPresentationHandler.ts +++ /dev/null @@ -1,92 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * 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 { RequestType } from 'vscode-languageclient'; -import { RazorDocumentManager } from '../Document/RazorDocumentManager'; -import { RazorLanguageServerClient } from '../RazorLanguageServerClient'; -import { RazorLogger } from '../RazorLogger'; -import { convertTextEditToSerializable, SerializableTextEdit } from '../RPC/SerializableTextEdit'; -import { ColorPresentationContext } from './ColorPresentationContext'; -import { SerializableColorPresentation } from './SerializableColorPresentation'; -import { SerializableColorPresentationParams } from './SerializableColorPresentationParams'; - -export class ColorPresentationHandler { - private static readonly provideHtmlColorPresentation = 'razor/provideHtmlColorPresentation'; - private colorPresentationRequestType: RequestType = - new RequestType(ColorPresentationHandler.provideHtmlColorPresentation); - private emptyColorInformationResponse: SerializableColorPresentation[] = []; - - constructor( - private readonly documentManager: RazorDocumentManager, - private readonly serverClient: RazorLanguageServerClient, - private readonly logger: RazorLogger) { - } - - public register() { - return this.serverClient.onRequestWithParams( - this.colorPresentationRequestType, - async (request: SerializableColorPresentationParams, token: vscode.CancellationToken) => this.provideHtmlColorPresentation(request, token)); - } - - private async provideHtmlColorPresentation( - colorPresentationParams: SerializableColorPresentationParams, - cancellationToken: vscode.CancellationToken) { - try { - const razorDocumentUri = vscode.Uri.parse(`${colorPresentationParams.textDocument.uri}`, true); - const razorDocument = await this.documentManager.getDocument(razorDocumentUri); - if (razorDocument === undefined) { - this.logger.logWarning(`Could not find Razor document ${razorDocumentUri}; returning empty color information.`); - 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.executeColorPresentationProvider', - color, - new ColorPresentationContext(virtualHtmlUri, colorPresentationParams.range)); - - const serializableColorPresentations = this.SerializeColorPresentations(colorPresentations); - return serializableColorPresentations; - } catch (error) { - this.logger.logWarning(`${ColorPresentationHandler.provideHtmlColorPresentation} failed with ${error}`); - } - - return this.emptyColorInformationResponse; - } - - private SerializeColorPresentations(colorPresentations: vscode.ColorPresentation[]) { - const serializableColorPresentations = new Array(); - for (const colorPresentation of colorPresentations) { - let serializedTextEdit: any = null; - const serializableAdditionalTextEdits = new Array(); - - if (colorPresentation.textEdit) { - serializedTextEdit = convertTextEditToSerializable(colorPresentation.textEdit); - } - - if (colorPresentation.additionalTextEdits) { - for (const additionalTextEdit of colorPresentation.additionalTextEdits) { - const serializableAdditionalTextEdit = convertTextEditToSerializable(additionalTextEdit); - serializableAdditionalTextEdits.push(serializableAdditionalTextEdit); - } - } - - const serializableColorPresentation = new SerializableColorPresentation( - colorPresentation.label, - serializedTextEdit, - serializableAdditionalTextEdits); - serializableColorPresentations.push(serializableColorPresentation); - } - - return serializableColorPresentations; - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/ColorPresentation/SerializableColorPresentation.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/ColorPresentation/SerializableColorPresentation.ts deleted file mode 100644 index a4ef352c7ff..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/ColorPresentation/SerializableColorPresentation.ts +++ /dev/null @@ -1,14 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -import { SerializableTextEdit } from '../RPC/SerializableTextEdit'; - -export class SerializableColorPresentation { - constructor( - public readonly label: string, - public readonly textEdit?: SerializableTextEdit, - public readonly additionalTextEdits?: SerializableTextEdit[]) { - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/ColorPresentation/SerializableColorPresentationParams.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/ColorPresentation/SerializableColorPresentationParams.ts deleted file mode 100644 index 1c08b3dbc04..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/ColorPresentation/SerializableColorPresentationParams.ts +++ /dev/null @@ -1,14 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { SerializableRange } from '../RPC/SerializableRange'; -import { SerializableTextDocumentIdentifier } from '../RPC/SerializableTextDocumentIdentifier'; - -export interface SerializableColorPresentationParams { - textDocument: SerializableTextDocumentIdentifier; - color: vscode.Color; - range: SerializableRange; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Completion/ProvisionalCompletionOrchestrator.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Completion/ProvisionalCompletionOrchestrator.ts deleted file mode 100644 index 44e084b7a90..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Completion/ProvisionalCompletionOrchestrator.ts +++ /dev/null @@ -1,169 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { CSharpProjectedDocument } from '../CSharp/CSharpProjectedDocument'; -import { CSharpProjectedDocumentContentProvider } from '../CSharp/CSharpProjectedDocumentContentProvider'; -import { RazorDocumentManager } from '../Document/RazorDocumentManager'; -import { ProjectionResult } from '../Projection/ProjectionResult'; -import { RazorLanguage } from '../RazorLanguage'; -import { RazorLanguageServiceClient } from '../RazorLanguageServiceClient'; -import { RazorLogger } from '../RazorLogger'; -import { LanguageKind } from '../RPC/LanguageKind'; -import { RazorCompletionItemProvider } from './RazorCompletionItemProvider'; - -export class ProvisionalCompletionOrchestrator { - private provisionalDotsMayBeActive = false; - private currentActiveDocument: vscode.TextDocument | undefined; - - constructor( - private readonly documentManager: RazorDocumentManager, - private readonly projectedCSharpProvider: CSharpProjectedDocumentContentProvider, - private readonly serviceClient: RazorLanguageServiceClient, - private readonly logger: RazorLogger) { - } - - public register() { - if (vscode.window.activeTextEditor) { - this.currentActiveDocument = vscode.window.activeTextEditor.document; - } - - // There's no event in VSCode to let us know when the completion window has been dismissed. - // Because of this restriction we do a best effort to understand when the user has gone onto - // different actions (other than viewing completion). - - const onDidChangeSelectionRegistration = vscode.window.onDidChangeTextEditorSelection( - args => this.tryRemoveProvisionalDot(args.textEditor.document)); - const onDidChangeRegistration = vscode.workspace.onDidChangeTextDocument(async args => { - if (args.contentChanges.length === 1 && args.contentChanges[0].text === '.') { - // Don't want to remove a provisional dot that we just added. - return; - } - - await this.tryRemoveProvisionalDot(args.document); - }); - const onDidChangeActiveEditorRegistration = vscode.window.onDidChangeActiveTextEditor(async args => { - if (this.currentActiveDocument) { - await this.tryRemoveProvisionalDot(this.currentActiveDocument); - } - - if (args) { - this.currentActiveDocument = args.document; - } else { - this.currentActiveDocument = undefined; - } - }); - - return vscode.Disposable.from( - onDidChangeRegistration, - onDidChangeSelectionRegistration, - onDidChangeActiveEditorRegistration); - } - - public async tryGetProvisionalCompletions( - hostDocumentUri: vscode.Uri, - projection: ProjectionResult, - completionContext: vscode.CompletionContext) { - // We expect to be called in scenarios where the user has just typed a dot after - // some identifier. - // Such as (cursor is pipe): "DateTime.| " - // In this case Razor interprets after the dot as Html and before it as C#. We - // use this criteria to provide a better completion experience for what we call - // provisional changes. - - if (projection.languageKind !== LanguageKind.Html) { - return null; - } - - if (completionContext.triggerCharacter !== '.') { - return null; - } - - const htmlPosition = projection.position; - if (htmlPosition.character === 0) { - return null; - } - - const previousCharacterPosition = new vscode.Position( - htmlPosition.line, - htmlPosition.character - 1, - ); - const previousCharacterQuery = await this.serviceClient.languageQuery( - previousCharacterPosition, - hostDocumentUri); - - if (previousCharacterQuery.kind !== LanguageKind.CSharp) { - return null; - } - - const document = await this.documentManager.getDocument(hostDocumentUri); - const projectedDocument = document.csharpDocument as CSharpProjectedDocument; - const absoluteIndex = previousCharacterQuery.positionIndex; - - if (this.logger.verboseEnabled) { - this.logger.logVerbose(`Applying provisional completion on ${projectedDocument.uri} ` + - `at (${previousCharacterQuery.position.line}, ${previousCharacterQuery.position.character})`); - } - - // Edit the projected document to contain a '.'. This allows C# completion to provide valid completion items - // for moments when a user has typed a '.' that's typically interpreted as Html. - // This provisional dot is removed when one of the following is true: - // 1. The user starts typing - // 2. The user swaps active documents - // 3. The user selects different content - // 4. The projected document gets an update request - projectedDocument.addProvisionalDotAt(absoluteIndex); - this.projectedCSharpProvider.ensureDocumentContent(projectedDocument.uri); - - // We open and then re-save because we're adding content to the text document within an event. - // We need to allow the system to propogate this text document change. - const newDocument = await vscode.workspace.openTextDocument(projectedDocument.uri); - await newDocument.save(); - - const provisionalPosition = new vscode.Position( - previousCharacterQuery.position.line, - previousCharacterQuery.position.character + 1); - const completionList = await RazorCompletionItemProvider.getCompletions( - projectedDocument.uri, - htmlPosition, - provisionalPosition, - completionContext.triggerCharacter); - - // We track when we add provisional dots to avoid doing unnecessary work on commonly invoked events. - this.provisionalDotsMayBeActive = true; - - return completionList; - } - - private async tryRemoveProvisionalDot(document: vscode.TextDocument) { - if (!this.provisionalDotsMayBeActive) { - return; - } - - if (document.languageId !== RazorLanguage.id) { - return; - } - - const razorDocument = await this.documentManager.getActiveDocument(); - if (!razorDocument) { - return; - } - - const projectedDocument = razorDocument.csharpDocument as CSharpProjectedDocument; - if (projectedDocument.removeProvisionalDot()) { - this.projectedCSharpProvider.ensureDocumentContent(projectedDocument.uri); - - if (this.logger.verboseEnabled) { - this.logger.logVerbose(`Ensured removal of provisional completion on ${projectedDocument.uri}.`); - } - } - - // Don't need to force the document to refresh here by saving because the user has already - // moved onto a different action. We only want to re-save the projected document when we - // expect instant interactions with the projected document. - - this.provisionalDotsMayBeActive = false; - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Completion/RazorCompletionItemProvider.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Completion/RazorCompletionItemProvider.ts deleted file mode 100644 index c9d997b030d..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Completion/RazorCompletionItemProvider.ts +++ /dev/null @@ -1,144 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { RazorDocumentManager } from '../Document/RazorDocumentManager'; -import { RazorDocumentSynchronizer } from '../Document/RazorDocumentSynchronizer'; -import { RazorLanguageFeatureBase } from '../RazorLanguageFeatureBase'; -import { RazorLanguageServiceClient } from '../RazorLanguageServiceClient'; -import { RazorLogger } from '../RazorLogger'; -import { getUriPath } from '../UriPaths'; -import { ProvisionalCompletionOrchestrator } from './ProvisionalCompletionOrchestrator'; - -export class RazorCompletionItemProvider - extends RazorLanguageFeatureBase - implements vscode.CompletionItemProvider { - - public static async getCompletions( - projectedUri: vscode.Uri, hostDocumentPosition: vscode.Position, - projectedPosition: vscode.Position, triggerCharacter: string | undefined) { - - if (projectedUri) { - // "@" is not a valid trigger character for C# / HTML and therefore we need to translate - // it into a non-trigger invocation. - const modifiedTriggerCharacter = triggerCharacter === '@' ? undefined : triggerCharacter; - - const completions = await vscode - .commands - .executeCommand( - 'vscode.executeCompletionItemProvider', - projectedUri, - projectedPosition, - modifiedTriggerCharacter); - - const completionItems = - completions instanceof Array ? completions // was vscode.CompletionItem[] - : completions ? completions.items // was vscode.CompletionList - : []; - - // There are times when the generated code will not line up with the content of the .razor/.cshtml file. - // Therefore, we need to offset all completion items' characters by a certain amount in order - // to have proper completion. An example of this is typing @DateTime at the beginning of a line. - // In the code behind it's represented as __o = DateTime. - const completionCharacterOffset = projectedPosition.character - hostDocumentPosition.character; - for (const completionItem of completionItems) { - const doc = completionItem.documentation as vscode.MarkdownString; - if (doc) { - // Without this, the documentation doesn't get rendered in the editor. - const newDoc = new vscode.MarkdownString(doc.value); - newDoc.isTrusted = false; - completionItem.documentation = newDoc; - } - - if (completionItem.range) { - const range = completionItem.range; - const insertingRange = (range as any).inserting; - if (insertingRange) { - const insertingRangeStart = this.offsetColumn(completionCharacterOffset, hostDocumentPosition.line, insertingRange.start); - const insertingRangeEnd = this.offsetColumn(completionCharacterOffset, hostDocumentPosition.line, insertingRange.end); - (range as any).inserting = new vscode.Range(insertingRangeStart, insertingRangeEnd); - } - - const replacingRange = (range as any).replacing; - if (replacingRange) { - const replacingRangeStart = this.offsetColumn(completionCharacterOffset, hostDocumentPosition.line, replacingRange.start); - const replacingRangeEnd = this.offsetColumn(completionCharacterOffset, hostDocumentPosition.line, replacingRange.end); - (range as any).replacing = new vscode.Range(replacingRangeStart, replacingRangeEnd); - } - - if (range instanceof vscode.Range && range.start && range.end) { - const rangeStart = this.offsetColumn(completionCharacterOffset, hostDocumentPosition.line, range.start); - const rangeEnd = this.offsetColumn(completionCharacterOffset, hostDocumentPosition.line, range.end); - completionItem.range = new vscode.Range(rangeStart, rangeEnd); - } - } - - // textEdit is deprecated in favor of .range. Clear out its value to avoid any unexpected behavior. - completionItem.textEdit = undefined; - - if (triggerCharacter === '@' && - completionItem.commitCharacters) { - // We remove `{`, '(', and '*' from the commit characters to prevent auto-completing the first - // completion item with a curly brace when a user intended to type `@{}` or `@()`. - completionItem.commitCharacters = completionItem.commitCharacters.filter( - commitChar => commitChar !== '{' && commitChar !== '(' && commitChar !== '*'); - } - } - - const isIncomplete = completions instanceof Array ? false - : completions ? completions.isIncomplete - : false; - return new vscode.CompletionList(completionItems, isIncomplete); - } - } - - private static offsetColumn(offset: number, hostDocumentLine: number, projectedPosition: vscode.Position) { - const offsetPosition = new vscode.Position( - hostDocumentLine, - projectedPosition.character - offset); - return offsetPosition; - } - - constructor( - documentSynchronizer: RazorDocumentSynchronizer, - documentManager: RazorDocumentManager, - serviceClient: RazorLanguageServiceClient, - private readonly provisionalCompletionOrchestrator: ProvisionalCompletionOrchestrator, - logger: RazorLogger) { - super(documentSynchronizer, documentManager, serviceClient, logger); - } - - public async provideCompletionItems( - document: vscode.TextDocument, position: vscode.Position, - token: vscode.CancellationToken, context: vscode.CompletionContext) { - const projection = await this.getProjection(document, position, token); - - if (this.logger.verboseEnabled) { - this.logger.logVerbose(`Providing completions for document ${getUriPath(document.uri)} ` + - `at location (${position.line}, ${position.character})`); - } - - if (!projection) { - return { isIncomplete: true, items: [] } as vscode.CompletionList; - } - - const provisionalCompletions = await this.provisionalCompletionOrchestrator.tryGetProvisionalCompletions( - document.uri, - projection, - context); - if (provisionalCompletions) { - return provisionalCompletions; - } - - // Not a provisional completion - - const completionList = await RazorCompletionItemProvider.getCompletions( - projection.uri, - position, - projection.position, - context.triggerCharacter); - return completionList; - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/ConfigurationChangeListener.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/ConfigurationChangeListener.ts deleted file mode 100644 index ea6b8555b26..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/ConfigurationChangeListener.ts +++ /dev/null @@ -1,31 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { RazorLanguageServerClient } from './RazorLanguageServerClient'; - -export function listenToConfigurationChanges( - languageServerClient: RazorLanguageServerClient): vscode.Disposable { - return vscode.workspace.onDidChangeConfiguration(event => { - if (event.affectsConfiguration('razor.trace')) { - razorTraceConfigurationChangeHandler(languageServerClient); - } - }); -} - -function razorTraceConfigurationChangeHandler(languageServerClient: RazorLanguageServerClient) { - const promptText = 'Would you like to restart the Razor Language Server to enable the Razor trace configuration change?'; - const restartButtonText = 'Restart'; - - vscode.window.showInformationMessage(promptText, restartButtonText).then(async result => { - if (result !== restartButtonText) { - return; - } - - await languageServerClient.stop(); - languageServerClient.updateTraceLevel(); - await languageServerClient.start(); - }); -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Definition/RazorDefinitionProvider.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Definition/RazorDefinitionProvider.ts deleted file mode 100644 index 1cde3b455cf..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Definition/RazorDefinitionProvider.ts +++ /dev/null @@ -1,50 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { getRazorDocumentUri, isRazorHtmlFile } from '../RazorConventions'; -import { RazorLanguageFeatureBase } from '../RazorLanguageFeatureBase'; -import { LanguageKind } from '../RPC/LanguageKind'; - -export class RazorDefinitionProvider - extends RazorLanguageFeatureBase - implements vscode.DefinitionProvider { - - public async provideDefinition( - document: vscode.TextDocument, position: vscode.Position, - token: vscode.CancellationToken) { - - const projection = await this.getProjection(document, position, token); - if (!projection || projection.languageKind === LanguageKind.Razor) { - return; - } - - const definitions = await vscode.commands.executeCommand( - 'vscode.executeDefinitionProvider', - projection.uri, - projection.position) as vscode.Location[]; - - const result = new Array(); - for (const definition of definitions) { - if (projection.languageKind === LanguageKind.Html && isRazorHtmlFile(definition.uri)) { - - // Because the line pragmas for html are generated referencing the projected document - // we need to remap their file locations to reference the top level Razor document. - const razorFile = getRazorDocumentUri(definition.uri); - result.push(new vscode.Location(razorFile, definition.range)); - - } else { - // This means it is one of the following, - // 1. A .razor/.cshtml file (because OmniSharp already remapped the background C# to the original document) - // 2. A .cs file - // 3. A .html/.js file - // In all of these cases, we don't need to remap. So accept it as is and move on. - result.push(definition); - } - } - - return result; - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Diagnostics/IReportIssueDataCollectionResult.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Diagnostics/IReportIssueDataCollectionResult.ts deleted file mode 100644 index 3c7b1d834ff..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Diagnostics/IReportIssueDataCollectionResult.ts +++ /dev/null @@ -1,11 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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'; - -export interface IReportIssueDataCollectionResult { - readonly document: vscode.TextDocument | undefined; - readonly logOutput: string; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Diagnostics/RazorIssueDataCollector.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Diagnostics/RazorIssueDataCollector.ts deleted file mode 100644 index 144227242c8..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Diagnostics/RazorIssueDataCollector.ts +++ /dev/null @@ -1,48 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -import * as os from 'os'; -import * as vscode from 'vscode'; -import { RazorLogger } from '../RazorLogger'; -import { IReportIssueDataCollectionResult } from './IReportIssueDataCollectionResult'; - -export class ReportIssueDataCollector { - private readonly logMessages: string[] = []; - private logOutput = ''; - private focusRegistration: vscode.Disposable | undefined; - private logRegistration: vscode.Disposable | undefined; - private lastFocusedRazorDocument: vscode.TextDocument | undefined; - constructor( - private readonly razorFileFocusChange: vscode.Event, - private readonly logger: RazorLogger) { - } - - public start() { - this.focusRegistration = this.razorFileFocusChange((razorDocument) => this.lastFocusedRazorDocument = razorDocument); - this.logRegistration = this.logger.onLog(message => this.logMessages.push(message)); - - this.logger.outputChannel.show(/* preserveFocus: */ true); - this.logger.logAlways('-- Starting Issue Data Collection-- '); - } - - public stop() { - this.logger.logAlways('-- Stopping Issue Data Collection-- '); - this.logOutput = this.logMessages.join(os.EOL); - this.logMessages.length = 0; - if (this.focusRegistration) { - this.focusRegistration.dispose(); - } - if (this.logRegistration) { - this.logRegistration.dispose(); - } - } - - public collect(): IReportIssueDataCollectionResult { - return { - document: this.lastFocusedRazorDocument, - logOutput: this.logOutput, - }; - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Diagnostics/ReportIssueCommand.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Diagnostics/ReportIssueCommand.ts deleted file mode 100644 index 45c39b3bdf0..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Diagnostics/ReportIssueCommand.ts +++ /dev/null @@ -1,43 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - -import { RazorDocumentManager } from '../Document/RazorDocumentManager'; -import { RazorLogger } from '../RazorLogger'; -import { api } from '../vscodeAdapter'; -import * as vscode from '../vscodeAdapter'; -import { ReportIssueCreator } from './ReportIssueCreator'; -import { ReportIssueDataCollectorFactory } from './ReportIssueDataCollectorFactory'; -import { ReportIssuePanel } from './ReportIssuePanel'; - -export class ReportIssueCommand { - private readonly issuePanel: ReportIssuePanel; - private readonly issueCreator: ReportIssueCreator; - private readonly dataCollectorFactory: ReportIssueDataCollectorFactory; - - constructor( - private readonly vscodeApi: api, - documentManager: RazorDocumentManager, - logger: RazorLogger) { - this.dataCollectorFactory = new ReportIssueDataCollectorFactory(logger); - this.issueCreator = new ReportIssueCreator(this.vscodeApi, documentManager); - this.issuePanel = new ReportIssuePanel(this.dataCollectorFactory, this.issueCreator, logger); - } - - public register() { - const registrations: vscode.Disposable[] = []; - registrations.push( - this.dataCollectorFactory.register(), - this.vscodeApi.commands.registerCommand('razor.reportIssue', () => this.issuePanel.show())); - if (this.vscodeApi.window.registerWebviewPanelSerializer) { - registrations.push(this.vscodeApi.window.registerWebviewPanelSerializer(ReportIssuePanel.viewType, { - deserializeWebviewPanel: async (panel: vscode.WebviewPanel) => { - await this.issuePanel.revive(panel); - }, - })); - } - - return this.vscodeApi.Disposable.from(...registrations); - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Diagnostics/ReportIssueCreator.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Diagnostics/ReportIssueCreator.ts deleted file mode 100644 index 3c896e2eb6b..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Diagnostics/ReportIssueCreator.ts +++ /dev/null @@ -1,267 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -import * as cp from 'child_process'; -import * as os from 'os'; -import { IRazorDocument } from '../Document/IRazorDocument'; -import { IRazorDocumentManager } from '../Document/IRazorDocumentManager'; -import { razorExtensionId } from '../RazorExtensionId'; -import * as vscode from '../vscodeAdapter'; -import { IReportIssueDataCollectionResult } from './IReportIssueDataCollectionResult'; - -export class ReportIssueCreator { - constructor( - private readonly vscodeApi: vscode.api, - private readonly documentManager: IRazorDocumentManager) { - } - - public async create(collectionResult: IReportIssueDataCollectionResult) { - let razorContent: string; - let csharpContent: string; - let htmlContent: string; - - if (collectionResult.document) { - razorContent = await this.getRazor(collectionResult.document); - - const razorDocument = await this.documentManager.getDocument(collectionResult.document.uri); - csharpContent = await this.getProjectedCSharp(razorDocument); - htmlContent = await this.getProjectedHtml(razorDocument); - } else { - razorContent = 'Non Razor file as active document'; - csharpContent = 'Could not determine CSharp content'; - htmlContent = 'Could not determine Html content'; - } - - const razorExtensionVersion = this.getExtensionVersion(); - let dotnetInfo = ''; - try { - dotnetInfo = await this.getDotnetInfo(); - } catch (error) { - dotnetInfo = `A valid dotnet installation could not be found: ${error}`; - } - const extensionTable = this.generateExtensionTable(); - - const sanitizedLogOutput = this.sanitize(collectionResult.logOutput); - const sanitizedRazorContent = this.sanitize(razorContent); - const sanitizedCSharpContent = this.sanitize(csharpContent); - const sanitizedHtmlContent = this.sanitize(htmlContent); - const sanitizedDotnetInfo = this.sanitize(dotnetInfo); - return `## Is this a Bug or Feature request?: -Bug - -## Steps to reproduce -------------------- Please fill in this section ------------------------- - -## Description of the problem: -------------------- Please fill in this section ------------------------- - -Expected behavior: - -Actual behavior: - -## Logs - -#### OmniSharp -------------------- Please fill in this section ------------------------- -To find the OmniSharp log, open VS Code's "Output" pane, then in the dropdown choose "OmniSharp Log". - -#### Razor -
Expand -

- -\`\`\` -${sanitizedLogOutput} -\`\`\` - -

-
- -## Workspace information - -#### Razor document: -
Expand -

- -\`\`\`Razor -${sanitizedRazorContent} -\`\`\` - -

-
- -#### Projected CSharp document: -
Expand -

- -\`\`\`C# -${sanitizedCSharpContent} -\`\`\` - -

-
- -#### Projected Html document: -
Expand -

- -\`\`\`Html -${sanitizedHtmlContent} -\`\`\` - -

-
- -## Machine information - - -**VSCode version**: ${this.vscodeApi.version} -**Razor.VSCode version**: ${razorExtensionVersion} -#### \`dotnet --info\` - -
Expand -

- -\`\`\` -${sanitizedDotnetInfo} -\`\`\` - -

-
- -#### Extensions -
Expand -

- -${extensionTable} - -

-
`; - } - - // Protected for testing - protected sanitize(content: string) { - const user = process.env.USERNAME === undefined ? process.env.USER : process.env.USERNAME; - - if (user === undefined) { - // Couldn't determine user, therefore can't truly sanitize the content. - return content; - } - - const replacer = new RegExp(user, 'g'); - const sanitizedContent = content.replace(replacer, 'anonymous'); - return sanitizedContent; - } - - // Protected for testing - protected async getRazor(document: vscode.TextDocument) { - const content = document.getText(); - - return content; - } - - // Protected for testing - protected async getProjectedCSharp(razorDocument: IRazorDocument) { - let csharpContent = `////////////////////// Projected CSharp as seen by extension /////////////////////// -${razorDocument.csharpDocument.getContent()} - - -////////////////////// Projected CSharp as seen by VSCode ///////////////////////`; - - try { - const csharpTextDocument = await this.vscodeApi.workspace.openTextDocument(razorDocument.csharpDocument.uri); - if (csharpTextDocument) { - csharpContent = `${csharpContent} -${csharpTextDocument.getText()}`; - } else { - csharpContent = `${csharpContent} -Unable to resolve VSCode's version of CSharp`; - } - } catch (e) { - csharpContent = `${csharpContent} -Unable to resolve VSCode's version of CSharp`; - } - - return csharpContent; - } - - // Protected for testing - protected async getProjectedHtml(razorDocument: IRazorDocument) { - let htmlContent = `////////////////////// Projected Html as seen by extension /////////////////////// -${razorDocument.htmlDocument.getContent()} - - -////////////////////// Projected Html as seen by VSCode ///////////////////////`; - - try { - const htmlTextDocument = await this.vscodeApi.workspace.openTextDocument(razorDocument.htmlDocument.uri); - if (htmlTextDocument) { - htmlContent = `${htmlContent} -${htmlTextDocument.getText()}`; - } else { - htmlContent = `${htmlContent} -Unable to resolve VSCode's version of Html`; - } - } catch (e) { - htmlContent = `${htmlContent} -Unable to resolve VSCode's version of Html`; - } - - return htmlContent; - } - - // Protected for testing - protected getExtensionVersion(): string { - const extension = this.vscodeApi.extensions.getExtension(razorExtensionId); - if (!extension) { - return 'Unable to find Razor extension version.'; - } - return extension.packageJSON.version; - } - - // Protected for testing - protected getInstalledExtensions() { - const extensions: Array> = this.vscodeApi.extensions.all - .filter(extension => extension.packageJSON.isBuiltin === false); - - return extensions.sort((a, b) => - a.packageJSON.name.toLowerCase().localeCompare(b.packageJSON.name.toLowerCase())); - } - - // Protected for testing - protected generateExtensionTable() { - const extensions = this.getInstalledExtensions(); - if (extensions.length <= 0) { - return 'none'; - } - - const tableHeader = `|Extension|Author|Version|${os.EOL}|---|---|---|`; - const table = extensions.map( - (e) => `|${e.packageJSON.name}|${e.packageJSON.publisher}|${e.packageJSON.version}|`).join(os.EOL); - - const extensionTable = ` -${tableHeader}${os.EOL}${table}; -`; - - return extensionTable; - } - - private getDotnetInfo(): Promise { - return new Promise((resolve, reject) => { - try { - cp.exec('dotnet --info', { cwd: process.cwd(), maxBuffer: 500 * 1024 }, (error, stdout, stderr) => { - if (error) { - reject(error); - } else if (stderr && stderr.length > 0) { - reject(error); - } else { - resolve(stdout); - } - }); - } catch (error) { - reject(error); - } - }); - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Diagnostics/ReportIssueDataCollector.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Diagnostics/ReportIssueDataCollector.ts deleted file mode 100644 index 5cd90c55aed..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Diagnostics/ReportIssueDataCollector.ts +++ /dev/null @@ -1,46 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -import * as os from 'os'; -import * as vscode from 'vscode'; -import { RazorLogger } from '../RazorLogger'; -import { IReportIssueDataCollectionResult } from './IReportIssueDataCollectionResult'; - -export class ReportIssueDataCollector { - private readonly logMessages: string[] = []; - private logOutput = ''; - private focusRegistration: vscode.Disposable | undefined; - private logRegistration: vscode.Disposable | undefined; - private lastFocusedRazorDocument: vscode.TextDocument | undefined; - constructor( - private readonly razorFileFocusChange: vscode.Event, - private readonly logger: RazorLogger) { - - this.focusRegistration = this.razorFileFocusChange((razorDocument) => this.lastFocusedRazorDocument = razorDocument); - this.logRegistration = this.logger.onLog(message => this.logMessages.push(message)); - - this.logger.outputChannel.show(/* preserveFocus: */ true); - this.logger.logAlways('-- Starting Issue Data Collection-- '); - } - - public stop() { - this.logger.logAlways('-- Stopping Issue Data Collection-- '); - this.logOutput = this.logMessages.join(os.EOL); - this.logMessages.length = 0; - if (this.focusRegistration) { - this.focusRegistration.dispose(); - } - if (this.logRegistration) { - this.logRegistration.dispose(); - } - } - - public collect(): IReportIssueDataCollectionResult { - return { - document: this.lastFocusedRazorDocument, - logOutput: this.logOutput, - }; - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Diagnostics/ReportIssueDataCollectorFactory.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Diagnostics/ReportIssueDataCollectorFactory.ts deleted file mode 100644 index 792f282b8f8..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Diagnostics/ReportIssueDataCollectorFactory.ts +++ /dev/null @@ -1,30 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { RazorLanguage } from '../RazorLanguage'; -import { RazorLogger } from '../RazorLogger'; -import { ReportIssueDataCollector } from './ReportIssueDataCollector'; - -export class ReportIssueDataCollectorFactory { - private onRazorDocumentFocusedEmitter = new vscode.EventEmitter(); - - constructor(private readonly logger: RazorLogger) { - this.onRazorDocumentFocusedEmitter = new vscode.EventEmitter(); - } - - public register() { - return vscode.window.onDidChangeActiveTextEditor((newEditor) => { - if (newEditor && RazorLanguage.fileExtensions.some(ext => newEditor.document.fileName.endsWith(ext))) { - this.onRazorDocumentFocusedEmitter.fire(newEditor.document); - } - }); - } - - public create() { - const collector = new ReportIssueDataCollector(this.onRazorDocumentFocusedEmitter.event, this.logger); - return collector; - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Diagnostics/ReportIssuePanel.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Diagnostics/ReportIssuePanel.ts deleted file mode 100644 index e53f9ad06c2..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Diagnostics/ReportIssuePanel.ts +++ /dev/null @@ -1,182 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 '../RazorLogger'; -import { Trace } from '../Trace'; -import { ReportIssueCreator } from './ReportIssueCreator'; -import { ReportIssueDataCollector } from './ReportIssueDataCollector'; -import { ReportIssueDataCollectorFactory } from './ReportIssueDataCollectorFactory'; - -export class ReportIssuePanel { - public static readonly viewType = 'razorReportIssue'; - - private panel: vscode.WebviewPanel | undefined; - private dataCollector: ReportIssueDataCollector | undefined; - private issueContent: string | undefined; - private traceLevelChange: vscode.Disposable | undefined; - - constructor( - private readonly dataCollectorFactory: ReportIssueDataCollectorFactory, - private readonly reportIssueCreator: ReportIssueCreator, - private readonly logger: RazorLogger) { - } - - public async show() { - if (this.panel) { - this.panel.reveal(vscode.ViewColumn.Two); - } else { - this.panel = vscode.window.createWebviewPanel( - ReportIssuePanel.viewType, - 'Report Razor Issue', - vscode.ViewColumn.Two, { - enableScripts: true, - // Disallow any remote sources - localResourceRoots: [], - }); - this.attachToCurrentPanel(); - } - - await this.update(); - } - - public async revive(panel: vscode.WebviewPanel) { - this.panel = panel; - this.attachToCurrentPanel(); - await this.update(); - } - - private attachToCurrentPanel() { - if (!this.panel) { - vscode.window.showErrorMessage('Unexpected error when attaching to report Razor issue window.'); - return; - } - - this.panel.webview.onDidReceiveMessage(async message => { - switch (message.command) { - case 'copyIssue': - if (!this.issueContent) { - if (!this.dataCollector) { - vscode.window.showErrorMessage('You must first start the data collection before copying.'); - return; - } - const collectionResult = this.dataCollector.collect(); - this.issueContent = await this.reportIssueCreator.create(collectionResult); - this.dataCollector = undefined; - } - - await vscode.env.clipboard.writeText(this.issueContent); - vscode.window.showInformationMessage('Razor issue copied to clipboard'); - return; - case 'startIssue': - if (this.dataCollector) { - this.dataCollector.stop(); - this.dataCollector = undefined; - } - this.issueContent = undefined; - this.dataCollector = this.dataCollectorFactory.create(); - vscode.window.showInformationMessage('Razor issue data collection started. Reproduce the issue then press "Stop"'); - return; - case 'stopIssue': - if (!this.dataCollector) { - vscode.window.showErrorMessage('You must first start the data collection before stopping.'); - return; - } - this.dataCollector.stop(); - vscode.window.showInformationMessage('Razor issue data collection stopped. Copying issue content...'); - return; - } - }); - - this.traceLevelChange = this.logger.onTraceLevelChange(async () => this.update()); - - this.panel.onDidDispose(() => { - if (this.traceLevelChange) { - this.traceLevelChange.dispose(); - } - this.panel = undefined; - }); - } - - private async update() { - if (!this.panel) { - return; - } - - let panelBodyContent = ''; - if (this.logger.trace.valueOf() === Trace.Verbose) { - panelBodyContent = `
    -
  1. Press
  2. -
  3. Perform the actions (or no action) that resulted in your Razor issue
  4. -
  5. Click . This will copy all relevant issue information.
  6. -
  7. Go to GitHub, paste your issue contents as the body of the issue. Don't forget to fill out any details left unfilled.
  8. -
- -

Privacy Alert! The contents copied to your clipboard may contain personal data. Prior to posting to -GitHub, please remove any personal data which should not be publicly viewable. -https://privacy.microsoft.com/en-US/privacystatement

- -`; - } else { - panelBodyContent = `

Cannot start collecting Razor logs when razor.trace is set to ${Trace[this.logger.trace]}. -Please set razor.trace to ${Trace[Trace.Verbose]} and then reload your VSCode environment and re-run the report Razor issue command.

`; - } - - this.panel.webview.html = ` - - - - - - Report a Razor issue - - - - - -

Report a Razor issue

-${panelBodyContent} - -`; - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Document/IRazorDocument.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Document/IRazorDocument.ts deleted file mode 100644 index 1eed677ee8a..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Document/IRazorDocument.ts +++ /dev/null @@ -1,14 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { IProjectedDocument } from '../Projection/IProjectedDocument'; - -export interface IRazorDocument { - readonly path: string; - readonly uri: vscode.Uri; - readonly csharpDocument: IProjectedDocument; - readonly htmlDocument: IProjectedDocument; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Document/IRazorDocumentChangeEvent.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Document/IRazorDocumentChangeEvent.ts deleted file mode 100644 index b837dd8ed0f..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Document/IRazorDocumentChangeEvent.ts +++ /dev/null @@ -1,12 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -import { IRazorDocument } from './IRazorDocument'; -import { RazorDocumentChangeKind } from './RazorDocumentChangeKind'; - -export interface IRazorDocumentChangeEvent { - readonly document: IRazorDocument; - readonly kind: RazorDocumentChangeKind; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Document/IRazorDocumentManager.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Document/IRazorDocumentManager.ts deleted file mode 100644 index 8a7866b86b0..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Document/IRazorDocumentManager.ts +++ /dev/null @@ -1,17 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 '../vscodeAdapter'; -import { IRazorDocument } from './IRazorDocument'; -import { IRazorDocumentChangeEvent } from './IRazorDocumentChangeEvent'; - -export interface IRazorDocumentManager { - readonly onChange: vscode.Event; - readonly documents: IRazorDocument[]; - getDocument(uri: vscode.Uri): Promise; - getActiveDocument(): Promise; - initialize(): Promise; - register(): vscode.Disposable; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Document/RazorDocumentChangeKind.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Document/RazorDocumentChangeKind.ts deleted file mode 100644 index a038bf4d080..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Document/RazorDocumentChangeKind.ts +++ /dev/null @@ -1,13 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -export enum RazorDocumentChangeKind { - added, - removed, - opened, - closed, - csharpChanged, - htmlChanged, -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Document/RazorDocumentFactory.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Document/RazorDocumentFactory.ts deleted file mode 100644 index aa379a58880..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Document/RazorDocumentFactory.ts +++ /dev/null @@ -1,50 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { CSharpProjectedDocument } from '../CSharp/CSharpProjectedDocument'; -import { CSharpProjectedDocumentContentProvider } from '../CSharp/CSharpProjectedDocumentContentProvider'; -import { HtmlProjectedDocument } from '../Html/HtmlProjectedDocument'; -import { HtmlProjectedDocumentContentProvider } from '../Html/HtmlProjectedDocumentContentProvider'; -import { virtualCSharpSuffix, virtualHtmlSuffix } from '../RazorConventions'; -import { getUriPath } from '../UriPaths'; -import { IRazorDocument } from './IRazorDocument'; - -export function createDocument(uri: vscode.Uri) { - const csharpDocument = createProjectedCSharpDocument(uri); - const htmlDocument = createProjectedHtmlDocument(uri); - const path = getUriPath(uri); - - const document: IRazorDocument = { - uri, - path, - csharpDocument, - htmlDocument, - }; - - return document; -} - -function createProjectedHtmlDocument(hostDocumentUri: vscode.Uri) { - // Index.cshtml => Index.cshtml__virtual.html - const path = getUriPath(hostDocumentUri); - const projectedPath = `${path}${virtualHtmlSuffix}`; - let uri = vscode.Uri.file(projectedPath); - uri = uri.with({ scheme: HtmlProjectedDocumentContentProvider.scheme }); - const projectedDocument = new HtmlProjectedDocument(uri); - - return projectedDocument; -} - -function createProjectedCSharpDocument(hostDocumentUri: vscode.Uri) { - // Index.cshtml => Index.cshtml__virtual.cs - const path = getUriPath(hostDocumentUri); - const projectedPath = `${path}${virtualCSharpSuffix}`; - let uri = vscode.Uri.file(projectedPath); - uri = uri.with({ scheme: CSharpProjectedDocumentContentProvider.scheme }); - const projectedDocument = new CSharpProjectedDocument(uri); - - return projectedDocument; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Document/RazorDocumentManager.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Document/RazorDocumentManager.ts deleted file mode 100644 index ab08096c1ae..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Document/RazorDocumentManager.ts +++ /dev/null @@ -1,244 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { CSharpProjectedDocument } from '../CSharp/CSharpProjectedDocument'; -import { HtmlProjectedDocument } from '../Html/HtmlProjectedDocument'; -import { RazorLanguage } from '../RazorLanguage'; -import { RazorLanguageServerClient } from '../RazorLanguageServerClient'; -import { RazorLogger } from '../RazorLogger'; -import { UpdateBufferRequest } from '../RPC/UpdateBufferRequest'; -import { getUriPath } from '../UriPaths'; -import { IRazorDocument } from './IRazorDocument'; -import { IRazorDocumentChangeEvent } from './IRazorDocumentChangeEvent'; -import { IRazorDocumentManager } from './IRazorDocumentManager'; -import { RazorDocumentChangeKind } from './RazorDocumentChangeKind'; -import { createDocument } from './RazorDocumentFactory'; - -export class RazorDocumentManager implements IRazorDocumentManager { - private readonly razorDocuments: { [hostDocumentPath: string]: IRazorDocument } = {}; - private onChangeEmitter = new vscode.EventEmitter(); - - constructor( - private readonly serverClient: RazorLanguageServerClient, - private readonly logger: RazorLogger) { - } - - public get onChange() { return this.onChangeEmitter.event; } - - public get documents() { - return Object.values(this.razorDocuments); - } - - public async getDocument(uri: vscode.Uri) { - const document = this._getDocument(uri); - - await this.ensureProjectedDocumentsOpen(document); - - return document; - } - - public async getActiveDocument() { - if (!vscode.window.activeTextEditor) { - return null; - } - - if (vscode.window.activeTextEditor.document.languageId !== RazorLanguage.id) { - return null; - } - - const activeDocument = await this.getDocument(vscode.window.activeTextEditor.document.uri); - return activeDocument; - } - - public async initialize() { - // Track current documents - const documentUris = await vscode.workspace.findFiles(RazorLanguage.globbingPattern); - - for (const uri of documentUris) { - this.addDocument(uri); - } - - for (const textDocument of vscode.workspace.textDocuments) { - if (textDocument.languageId !== RazorLanguage.id) { - continue; - } - - if (textDocument.isClosed) { - continue; - } - - this.openDocument(textDocument.uri); - } - } - - public register() { - // Track future documents - const watcher = vscode.workspace.createFileSystemWatcher(RazorLanguage.globbingPattern); - const didCreateRegistration = watcher.onDidCreate( - async (uri: vscode.Uri) => this.addDocument(uri)); - const didDeleteRegistration = watcher.onDidDelete( - async (uri: vscode.Uri) => this.removeDocument(uri)); - const didOpenRegistration = vscode.workspace.onDidOpenTextDocument(document => { - if (document.languageId !== RazorLanguage.id) { - return; - } - - this.openDocument(document.uri); - }); - const didCloseRegistration = vscode.workspace.onDidCloseTextDocument(document => { - if (document.languageId !== RazorLanguage.id) { - return; - } - - this.closeDocument(document.uri); - }); - this.serverClient.onNotification( - 'razor/updateCSharpBuffer', - async updateBufferRequest => this.updateCSharpBuffer(updateBufferRequest)); - - this.serverClient.onNotification( - 'razor/updateHtmlBuffer', - async updateBufferRequest => this.updateHtmlBuffer(updateBufferRequest)); - - return vscode.Disposable.from( - watcher, - didCreateRegistration, - didDeleteRegistration, - didOpenRegistration, - didCloseRegistration); - } - - private _getDocument(uri: vscode.Uri) { - const path = getUriPath(uri); - let document = this.razorDocuments[path]; - - // This might happen in the case that a file is opened outside the workspace - if (!document) { - this.logger.logMessage(`File '${path}' didn't exist in the Razor document list. This is likely because it's from outside the workspace.`); - document = this.addDocument(uri); - } - - return document; - } - - private openDocument(uri: vscode.Uri) { - const document = this._getDocument(uri); - - this.notifyDocumentChange(document, RazorDocumentChangeKind.opened); - } - - private closeDocument(uri: vscode.Uri) { - const document = this._getDocument(uri); - - const csharpDocument = document.csharpDocument; - const csharpProjectedDocument = csharpDocument as CSharpProjectedDocument; - const htmlDocument = document.htmlDocument; - const htmlProjectedDocument = htmlDocument as HtmlProjectedDocument; - - // Reset the projected documents, VSCode resets all sync versions when a document closes. - csharpProjectedDocument.reset(); - htmlProjectedDocument.reset(); - - // Files outside of the workspace will return undefined from getWorkspaceFolder - const workspaceFolder = vscode.workspace.getWorkspaceFolder(uri); - if (!workspaceFolder) { - // Out of workspace files should be removed once they're closed - this.removeDocument(uri); - } - - this.notifyDocumentChange(document, RazorDocumentChangeKind.closed); - } - - private addDocument(uri: vscode.Uri) { - const path = getUriPath(uri); - let document = this.razorDocuments[path]; - if (document) { - this.logger.logMessage(`Skipping document creation for '${path}' because it already exists.`); - return document; - } - - document = createDocument(uri); - this.razorDocuments[document.path] = document; - - this.notifyDocumentChange(document, RazorDocumentChangeKind.added); - - return document; - } - - private removeDocument(uri: vscode.Uri) { - const document = this._getDocument(uri); - delete this.razorDocuments[document.path]; - - this.notifyDocumentChange(document, RazorDocumentChangeKind.removed); - } - - private async updateCSharpBuffer(updateBufferRequest: UpdateBufferRequest) { - if (this.logger.verboseEnabled) { - this.logger.logVerbose( - `Updating the C# document for Razor file '${updateBufferRequest.hostDocumentFilePath}' ` + - `(${updateBufferRequest.hostDocumentVersion})`); - } - - const hostDocumentUri = vscode.Uri.file(updateBufferRequest.hostDocumentFilePath); - const document = this._getDocument(hostDocumentUri); - const projectedDocument = document.csharpDocument; - - if (!projectedDocument.hostDocumentSyncVersion || - projectedDocument.hostDocumentSyncVersion <= updateBufferRequest.hostDocumentVersion) { - // We allow re-setting of the updated content from the same doc sync version in the case - // of project or file import changes. - const csharpProjectedDocument = projectedDocument as CSharpProjectedDocument; - csharpProjectedDocument.update(updateBufferRequest.changes, updateBufferRequest.hostDocumentVersion); - - this.notifyDocumentChange(document, RazorDocumentChangeKind.csharpChanged); - } else { - this.logger.logWarning('Failed to update the C# document buffer. This is unexpected and may result in incorrect C# interactions.'); - } - } - - private async updateHtmlBuffer(updateBufferRequest: UpdateBufferRequest) { - if (this.logger.verboseEnabled) { - this.logger.logVerbose( - `Updating the HTML document for Razor file '${updateBufferRequest.hostDocumentFilePath}' ` + - `(${updateBufferRequest.hostDocumentVersion})`); - } - - const hostDocumentUri = vscode.Uri.file(updateBufferRequest.hostDocumentFilePath); - const document = this._getDocument(hostDocumentUri); - const projectedDocument = document.htmlDocument; - - if (!projectedDocument.hostDocumentSyncVersion || - projectedDocument.hostDocumentSyncVersion <= updateBufferRequest.hostDocumentVersion) { - // We allow re-setting of the updated content from the same doc sync version in the case - // of project or file import changes. - const htmlProjectedDocument = projectedDocument as HtmlProjectedDocument; - htmlProjectedDocument.update(updateBufferRequest.changes, updateBufferRequest.hostDocumentVersion); - - this.notifyDocumentChange(document, RazorDocumentChangeKind.htmlChanged); - } else { - this.logger.logWarning('Failed to update the HTML document buffer. This is unexpected and may result in incorrect HTML interactions.'); - } - } - - private notifyDocumentChange(document: IRazorDocument, kind: RazorDocumentChangeKind) { - if (this.logger.verboseEnabled) { - this.logger.logVerbose( - `Notifying document '${getUriPath(document.uri)}' changed '${RazorDocumentChangeKind[kind]}'`); - } - - const args: IRazorDocumentChangeEvent = { - document, - kind, - }; - - this.onChangeEmitter.fire(args); - } - - private async ensureProjectedDocumentsOpen(document: IRazorDocument) { - await vscode.workspace.openTextDocument(document.csharpDocument.uri); - await vscode.workspace.openTextDocument(document.htmlDocument.uri); - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Document/RazorDocumentSynchronizer.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Document/RazorDocumentSynchronizer.ts deleted file mode 100644 index def40af897f..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Document/RazorDocumentSynchronizer.ts +++ /dev/null @@ -1,274 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { CSharpProjectedDocumentContentProvider } from '../CSharp/CSharpProjectedDocumentContentProvider'; -import { HtmlProjectedDocumentContentProvider } from '../Html/HtmlProjectedDocumentContentProvider'; -import { IProjectedDocument } from '../Projection/IProjectedDocument'; -import { RazorLogger } from '../RazorLogger'; -import { getUriPath } from '../UriPaths'; -import { IRazorDocumentChangeEvent } from './IRazorDocumentChangeEvent'; -import { RazorDocumentChangeKind } from './RazorDocumentChangeKind'; -import { RazorDocumentManager } from './RazorDocumentManager'; - -export class RazorDocumentSynchronizer { - private readonly synchronizations: { [uri: string]: SynchronizationContext[] } = {}; - private synchronizationIdentifier = 0; - - constructor( - private readonly documentManager: RazorDocumentManager, - private readonly logger: RazorLogger) { - } - - public register() { - const documentManagerRegistration = this.documentManager.onChange( - event => this.documentChanged(event)); - const textDocumentChangeRegistration = vscode.workspace.onDidChangeTextDocument( - event => this.textDocumentChanged(event)); - - return vscode.Disposable.from(documentManagerRegistration, textDocumentChangeRegistration); - } - - public async trySynchronizeProjectedDocument( - hostDocument: vscode.TextDocument, - projectedDocument: IProjectedDocument, - expectedHostDocumentVersion: number, - token: vscode.CancellationToken) { - - const logId = ++this.synchronizationIdentifier; - - const documentKey = getUriPath(projectedDocument.uri); - if (this.logger.verboseEnabled) { - const ehdv = expectedHostDocumentVersion; - this.logger.logVerbose( - `${logId} - Synchronizing '${documentKey}': - Currently at ${projectedDocument.hostDocumentSyncVersion}, synchronizing to version '${ehdv}'. - Current host document version: '${hostDocument.version}' - Current projected document version: '${projectedDocument.projectedDocumentSyncVersion}'`); - } - - if (hostDocument.version !== expectedHostDocumentVersion) { - if (this.logger.verboseEnabled) { - this.logger.logVerbose( - `${logId} - toHostDocumentVersion and hostDocument.version already out of date.`); - } - - // Already out-of-date. Allowing synchronizations for now to see if this actually causes any issues. - } - - const context: SynchronizationContext = this.createSynchronizationContext( - documentKey, - projectedDocument, - expectedHostDocumentVersion, - hostDocument, - token); - - try { - if (projectedDocument.hostDocumentSyncVersion !== expectedHostDocumentVersion) { - if (this.logger.verboseEnabled) { - this.logger.logVerbose( - `${logId} - Projected document not in sync with host document, waiting for update... - Current host document sync version: ${projectedDocument.hostDocumentSyncVersion}`); - } - await context.onProjectedDocumentSynchronized; - } - - if (this.logger.verboseEnabled) { - this.logger.logVerbose( - `${logId} - Projected document in sync with host document`); - } - - // Projected document is the one we expect. - - const projectedTextDocument = await vscode.workspace.openTextDocument(projectedDocument.uri); - const projectedTextDocumentVersion = this.getProjectedTextDocumentVersion(projectedTextDocument); - if (projectedDocument.projectedDocumentSyncVersion !== projectedTextDocumentVersion) { - if (this.logger.verboseEnabled) { - this.logger.logVerbose( - `${logId} - Projected text document not in sync with data type, waiting for update... - Current projected text document sync version: ${projectedTextDocumentVersion}`); - } - await context.onProjectedTextDocumentSynchronized; - } - - if (this.logger.verboseEnabled) { - this.logger.logVerbose( - `${logId} - Projected text document in sync with data type`); - } - - // Projected text document is the one we expect - } catch (cancellationReason) { - this.removeSynchronization(context); - - if (this.logger.verboseEnabled) { - this.logger.logVerbose( - `${logId} - Synchronization failed: ${cancellationReason}`); - } - - return false; - } - - this.removeSynchronization(context); - - if (this.logger.verboseEnabled) { - this.logger.logVerbose( - `${logId} - Synchronization successful!`); - } - - return true; - } - - private removeSynchronization(context: SynchronizationContext) { - const documentKey = getUriPath(context.projectedDocument.uri); - const synchronizations = this.synchronizations[documentKey]; - clearTimeout(context.timeoutId); - - if (synchronizations.length === 1) { - delete this.synchronizations[documentKey]; - return; - } - - this.synchronizations[documentKey] = synchronizations.filter(item => item !== context); - } - - private createSynchronizationContext( - documentKey: string, - projectedDocument: IProjectedDocument, - toHostDocumentVersion: number, - hostDocument: vscode.TextDocument, - token: vscode.CancellationToken) { - - const rejectionsForCancel: Array<(reason: string) => void> = []; - let projectedDocumentSynchronized: () => void = Function; - const onProjectedDocumentSynchronized = new Promise((resolve, reject) => { - projectedDocumentSynchronized = resolve; - rejectionsForCancel.push(reject); - }); - let projectedTextDocumentSynchronized: () => void = Function; - const onProjectedTextDocumentSynchronized = new Promise((resolve, reject) => { - projectedTextDocumentSynchronized = resolve; - rejectionsForCancel.push(reject); - }); - - token.onCancellationRequested((reason) => { - context.cancel(`Token cancellation requested: ${reason}`); - }); - const timeoutId = setTimeout(() => { - context.cancel('Synchronization timed out'); - }, 2000); - const context: SynchronizationContext = { - projectedDocument, - logIdentifier: this.synchronizationIdentifier, - timeoutId, - toHostDocumentVersion, - hostDocumentVersion: hostDocument.version, - cancel: (reason) => { - for (const reject of rejectionsForCancel) { - reject(reason); - } - }, - projectedDocumentSynchronized, - onProjectedDocumentSynchronized, - projectedTextDocumentSynchronized, - onProjectedTextDocumentSynchronized, - }; - - let synchronizations = this.synchronizations[documentKey]; - if (!synchronizations) { - synchronizations = []; - this.synchronizations[documentKey] = synchronizations; - } - - synchronizations.push(context); - - return context; - } - - private textDocumentChanged(event: vscode.TextDocumentChangeEvent) { - if (event.document.uri.scheme !== CSharpProjectedDocumentContentProvider.scheme && - event.document.uri.scheme !== HtmlProjectedDocumentContentProvider.scheme) { - return; - } - - const projectedTextDocumentVersion = this.getProjectedTextDocumentVersion(event.document); - if (projectedTextDocumentVersion === null) { - return; - } - - const documentKey = getUriPath(event.document.uri); - const synchronizationContexts = this.synchronizations[documentKey]; - - if (!synchronizationContexts) { - return; - } - - for (const context of synchronizationContexts) { - if (context.projectedDocument.projectedDocumentSyncVersion === projectedTextDocumentVersion) { - if (this.logger.verboseEnabled) { - const li = context.logIdentifier; - const ptdv = projectedTextDocumentVersion; - this.logger.logVerbose(`${li} - Projected text document synchronized to ${ptdv}.`); - } - context.projectedTextDocumentSynchronized(); - } - } - } - - private documentChanged(event: IRazorDocumentChangeEvent) { - let projectedDocument: IProjectedDocument; - if (event.kind === RazorDocumentChangeKind.csharpChanged) { - projectedDocument = event.document.csharpDocument; - } else if (event.kind === RazorDocumentChangeKind.htmlChanged) { - projectedDocument = event.document.htmlDocument; - } else { - return; - } - - const hostDocumentSyncVersion = projectedDocument.hostDocumentSyncVersion; - if (hostDocumentSyncVersion === null) { - return; - } - - const documentKey = getUriPath(projectedDocument.uri); - const synchronizationContexts = this.synchronizations[documentKey]; - if (!synchronizationContexts) { - return; - } - - for (const context of synchronizationContexts) { - if (context.toHostDocumentVersion === projectedDocument.hostDocumentSyncVersion) { - context.projectedDocumentSynchronized(); - } - } - } - - private getProjectedTextDocumentVersion(textDocument: vscode.TextDocument) { - // Logic defined in this method is heavily dependent on the functionality in the projected - // document content providers to append versions to the end of text documents. - - if (textDocument.lineCount <= 0) { - return null; - } - - const lastLine = textDocument.lineAt(textDocument.lineCount - 1); - const versionString = lastLine.text.substring(3 /* //_ */); - const textDocumentProjectedVersion = parseInt(versionString, 10); - - return textDocumentProjectedVersion; - } -} - -interface SynchronizationContext { - readonly projectedDocument: IProjectedDocument; - readonly logIdentifier: number; - readonly toHostDocumentVersion: number; - readonly hostDocumentVersion: number; - readonly timeoutId: NodeJS.Timer; - readonly projectedDocumentSynchronized: () => void; - readonly onProjectedDocumentSynchronized: Promise; - readonly projectedTextDocumentSynchronized: () => void; - readonly onProjectedTextDocumentSynchronized: Promise; - readonly cancel: (reason: string) => void; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/DocumentColor/DocumentColorHandler.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/DocumentColor/DocumentColorHandler.ts deleted file mode 100644 index aa70568b9c8..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/DocumentColor/DocumentColorHandler.ts +++ /dev/null @@ -1,62 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * 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 { RequestType } from 'vscode-languageclient'; -import { RazorDocumentManager } from '../Document/RazorDocumentManager'; -import { RazorLanguageServerClient } from '../RazorLanguageServerClient'; -import { RazorLogger } from '../RazorLogger'; -import { convertRangeToSerializable } from '../RPC/SerializableRange'; -import { SerializableColorInformation } from './SerializableColorInformation'; -import { SerializableDocumentColorParams } from './SerializableDocumentColorParams'; - -export class DocumentColorHandler { - private static readonly provideHtmlDocumentColorEndpoint = 'razor/provideHtmlDocumentColor'; - private documentColorRequestType: RequestType = new RequestType(DocumentColorHandler.provideHtmlDocumentColorEndpoint); - private emptyColorInformationResponse: SerializableColorInformation[] = []; - - constructor( - private readonly documentManager: RazorDocumentManager, - private readonly serverClient: RazorLanguageServerClient, - private readonly logger: RazorLogger) { } - - public register() { - return this.serverClient.onRequestWithParams( - this.documentColorRequestType, - async (request: SerializableDocumentColorParams, token: vscode.CancellationToken) => this.provideHtmlDocumentColors(request, token)); - } - - private async provideHtmlDocumentColors( - documentColorParams: SerializableDocumentColorParams, - cancellationToken: vscode.CancellationToken) { - try { - const razorDocumentUri = vscode.Uri.parse(documentColorParams.textDocument.uri, true); - const razorDocument = await this.documentManager.getDocument(razorDocumentUri); - if (razorDocument === undefined) { - this.logger.logWarning(`Could not find Razor document ${razorDocumentUri}; returning empty color information.`); - return this.emptyColorInformationResponse; - } - - const virtualHtmlUri = razorDocument.htmlDocument.uri; - - const colorInformation = await vscode.commands.executeCommand( - 'vscode.executeDocumentColorProvider', - virtualHtmlUri); - - const serializableColorInformation = new Array(); - for (const color of colorInformation) { - const serializableRange = convertRangeToSerializable(color.range); - const serializableColor = new SerializableColorInformation(serializableRange, color.color); - serializableColorInformation.push(serializableColor); - } - - return serializableColorInformation; - } catch (error) { - this.logger.logWarning(`${DocumentColorHandler.provideHtmlDocumentColorEndpoint} failed with ${error}`); - } - - return this.emptyColorInformationResponse; - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/DocumentColor/SerializableColorInformation.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/DocumentColor/SerializableColorInformation.ts deleted file mode 100644 index ac0abbd5cc8..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/DocumentColor/SerializableColorInformation.ts +++ /dev/null @@ -1,14 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { SerializableRange } from '../RPC/SerializableRange'; - -export class SerializableColorInformation { - constructor( - public readonly range: SerializableRange, - public readonly color: vscode.Color) { - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/DocumentColor/SerializableDocumentColorParams.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/DocumentColor/SerializableDocumentColorParams.ts deleted file mode 100644 index 9de27937002..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/DocumentColor/SerializableDocumentColorParams.ts +++ /dev/null @@ -1,10 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -import { SerializableTextDocumentIdentifier } from '../RPC/SerializableTextDocumentIdentifier'; - -export interface SerializableDocumentColorParams { - textDocument: SerializableTextDocumentIdentifier; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/DocumentHighlight/RazorDocumentHighlightProvider.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/DocumentHighlight/RazorDocumentHighlightProvider.ts deleted file mode 100644 index 2f9069cbe49..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/DocumentHighlight/RazorDocumentHighlightProvider.ts +++ /dev/null @@ -1,62 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { RazorLanguageFeatureBase } from './../RazorLanguageFeatureBase'; -import { LanguageKind } from './../RPC/LanguageKind'; - -export class RazorDocumentHighlightProvider - extends RazorLanguageFeatureBase - implements vscode.DocumentHighlightProvider { - - public async provideDocumentHighlights( - document: vscode.TextDocument, - position: vscode.Position, - token: vscode.CancellationToken) { - - const projection = await this.getProjection(document, position, token); - if (!projection || projection.languageKind === LanguageKind.Razor) { - return; - } - - const highlights = await vscode.commands.executeCommand( - 'vscode.executeDocumentHighlights', - projection.uri, - projection.position); - - if (!highlights || highlights.length === 0) { - return; - } - - const remappedHighlights = new Array(); - - // Re-map the projected document ranges to host document ranges - for (const highlight of highlights) { - const remappedResponse = await this.serviceClient.mapToDocumentRanges( - projection.languageKind, - [highlight.range], - document.uri); - - if (!remappedResponse || - !remappedResponse.ranges || - !remappedResponse.ranges[0]) { - // Couldn't remap the projected highlight location. - continue; - } - - if (document.version !== remappedResponse.hostDocumentVersion) { - // This highlight result is for a different version of the text document, bail. - continue; - } - - const remappedHighlight = new vscode.DocumentHighlight( - remappedResponse.ranges[0], - highlight.kind); - remappedHighlights.push(remappedHighlight); - } - - return remappedHighlights; - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/DocumentTelemetryListener.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/DocumentTelemetryListener.ts deleted file mode 100644 index e928977bbb8..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/DocumentTelemetryListener.ts +++ /dev/null @@ -1,20 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -import { RazorDocumentChangeKind } from './Document/RazorDocumentChangeKind'; -import { RazorDocumentManager } from './Document/RazorDocumentManager'; -import { TelemetryReporter } from './TelemetryReporter'; - -export function reportTelemetryForDocuments( - documentManager: RazorDocumentManager, - telemetryReporter: TelemetryReporter) { - documentManager.onChange((event) => { - switch (event.kind) { - case RazorDocumentChangeKind.added: - telemetryReporter.reportWorkspaceContainsRazor(); - break; - } - }); -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Folding/FoldingRangeHandler.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Folding/FoldingRangeHandler.ts deleted file mode 100644 index ea8d199bb36..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Folding/FoldingRangeHandler.ts +++ /dev/null @@ -1,87 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * 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 { FoldingRange, FoldingRangeKind, RequestType } from 'vscode-languageclient'; -import { RazorDocumentManager } from '../Document/RazorDocumentManager'; -import { RazorLanguageServerClient } from '../RazorLanguageServerClient'; -import { RazorLogger } from '../RazorLogger'; -import { SerializableFoldingRangeParams } from './SerializableFoldingRangeParams'; -import { SerializableFoldingRangeResponse } from './SerializableFoldingRangeResponse'; - -export class FoldingRangeHandler { - private static readonly provideFoldingRange = 'razor/foldingRange'; - private foldingRangeRequestType: RequestType = new RequestType(FoldingRangeHandler.provideFoldingRange); - private emptyFoldingRangeReponse: SerializableFoldingRangeResponse = new SerializableFoldingRangeResponse(new Array(), new Array()); - - constructor( - private readonly serverClient: RazorLanguageServerClient, - private readonly documentManager: RazorDocumentManager, - private readonly logger: RazorLogger) { } - - public register() { - return this.serverClient.onRequestWithParams( - this.foldingRangeRequestType, - async (request, token) => this.provideFoldingRanges(request, token)); - } - - private async provideFoldingRanges( - foldingRangeParams: SerializableFoldingRangeParams, - cancellationToken: vscode.CancellationToken) { - try { - const razorDocumentUri = vscode.Uri.parse(foldingRangeParams.textDocument.uri, true); - const razorDocument = await this.documentManager.getDocument(razorDocumentUri); - if (razorDocument === undefined) { - return this.emptyFoldingRangeReponse; - } - - const virtualHtmlUri = razorDocument.htmlDocument.uri; - const virtualCSharpUri = razorDocument.csharpDocument.uri; - - const htmlFoldingRanges = await vscode.commands.executeCommand('vscode.executeFoldingRangeProvider', virtualHtmlUri); - const csharpFoldingRanges = await vscode.commands.executeCommand('vscode.executeFoldingRangeProvider', virtualCSharpUri); - - const convertedHtmlFoldingRanges = htmlFoldingRanges === undefined ? new Array() : this.convertFoldingRanges(htmlFoldingRanges); - const convertedCSharpFoldingRanges = csharpFoldingRanges === undefined ? new Array() : this.convertFoldingRanges(csharpFoldingRanges); - - const response = new SerializableFoldingRangeResponse(convertedHtmlFoldingRanges, convertedCSharpFoldingRanges); - return response; - } catch (error) { - this.logger.logWarning(`${FoldingRangeHandler.provideFoldingRange} failed with ${error}`); - } - - return this.emptyFoldingRangeReponse; - } - - private convertFoldingRanges(foldingRanges: vscode.FoldingRange[]) { - const convertedFoldingRanges = new Array(); - foldingRanges.forEach(foldingRange => { - const convertedFoldingRange: FoldingRange = { - startLine: foldingRange.start, - startCharacter: 0, - endLine: foldingRange.end, - endCharacter: 0, - kind: foldingRange.kind === undefined ? undefined : this.convertFoldingRangeKind(foldingRange.kind), - }; - - convertedFoldingRanges.push(convertedFoldingRange); - }); - - return convertedFoldingRanges; - } - - private convertFoldingRangeKind(kind: vscode.FoldingRangeKind) { - if (kind === vscode.FoldingRangeKind.Comment) { - return FoldingRangeKind.Comment; - } else if (kind === vscode.FoldingRangeKind.Imports) { - return FoldingRangeKind.Imports; - } else if (kind === vscode.FoldingRangeKind.Region) { - return FoldingRangeKind.Region; - } else { - this.logger.logWarning(`Unexpected FoldingRangeKind ${kind}`); - return undefined; - } - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Folding/SerializableFoldingRangeParams.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Folding/SerializableFoldingRangeParams.ts deleted file mode 100644 index 303d858e4e0..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Folding/SerializableFoldingRangeParams.ts +++ /dev/null @@ -1,12 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -import { integer } from 'vscode-languageserver-types'; -import { SerializableTextDocumentIdentifier } from '../RPC/SerializableTextDocumentIdentifier'; - -export interface SerializableFoldingRangeParams { - hostDocumentVersion: integer; - textDocument: SerializableTextDocumentIdentifier; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Folding/SerializableFoldingRangeResponse.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Folding/SerializableFoldingRangeResponse.ts deleted file mode 100644 index e72b7a940e1..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Folding/SerializableFoldingRangeResponse.ts +++ /dev/null @@ -1,10 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -import { FoldingRange } from 'vscode-languageclient'; - -export class SerializableFoldingRangeResponse { - constructor(public htmlRanges: FoldingRange[], public csharpRanges: FoldingRange[]) {} -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Formatting/FormattingHandler.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Formatting/FormattingHandler.ts deleted file mode 100644 index ca55edb2b34..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Formatting/FormattingHandler.ts +++ /dev/null @@ -1,176 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * 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 { RequestType } from 'vscode-languageclient'; -import { IRazorDocument } from '../Document/IRazorDocument'; -import { RazorDocumentManager } from '../Document/RazorDocumentManager'; -import { RazorDocumentSynchronizer } from '../Document/RazorDocumentSynchronizer'; -import { RazorLanguageServerClient } from '../RazorLanguageServerClient'; -import { RazorLogger } from '../RazorLogger'; -import { convertTextEditToSerializable, SerializableTextEdit } from '../RPC/SerializableTextEdit'; -import { SerializableFormattingParams } from './SerializableFormattingParams'; -import { SerializableFormattingResponse } from './SerializableFormattingResponse'; -import { SerializableOnTypeFormattingParams } from './SerializableOnTypeFormattingParams'; - -export class FormattingHandler { - private static readonly provideFormattingEndpoint = 'razor/htmlFormatting'; - private static readonly provideOnTypeFormattingEndpoint = 'razor/htmlOnTypeFormatting'; - private formattingRequestType: RequestType = new RequestType(FormattingHandler.provideFormattingEndpoint); - private onTypeFormattingRequestType: RequestType = new RequestType(FormattingHandler.provideOnTypeFormattingEndpoint); - private emptyFormattingResponse = new SerializableFormattingResponse(); - - constructor( - private readonly documentManager: RazorDocumentManager, - private readonly documentSynchronizer: RazorDocumentSynchronizer, - private readonly serverClient: RazorLanguageServerClient, - private readonly logger: RazorLogger) { } - - public async register() { - await this.serverClient.onRequestWithParams( - this.formattingRequestType, - async (request, token) => this.provideFormatting(request, token)); - await this.serverClient.onRequestWithParams( - this.onTypeFormattingRequestType, - async (request, token) => this.provideOnTypeFormatting(request, token)); - } - - private async provideFormatting( - formattingParams: SerializableFormattingParams, - cancellationToken: vscode.CancellationToken) { - try { - const razorDocumentUri = vscode.Uri.parse(formattingParams.textDocument.uri); - const razorDocument = await this.documentManager.getDocument(razorDocumentUri); - if (razorDocument === undefined) { - return this.emptyFormattingResponse; - } - - const textDocument = await vscode.workspace.openTextDocument(razorDocumentUri); - const synchronized = await this.documentSynchronizer.trySynchronizeProjectedDocument(textDocument, razorDocument.csharpDocument, formattingParams.hostDocumentVersion, cancellationToken); - if (!synchronized) { - return this.emptyFormattingResponse; - } - - const virtualHtmlUri = razorDocument.htmlDocument.uri; - - const textEdits = await vscode.commands.executeCommand( - 'vscode.executeFormatDocumentProvider', - virtualHtmlUri, - formattingParams.options); - - if (textEdits === undefined) { - return this.emptyFormattingResponse; - } - - const serializableTextEdits = this.sanitizeTextEdits(razorDocument, textEdits); - - return new SerializableFormattingResponse(serializableTextEdits); - } catch (error) { - this.logger.logWarning(`${FormattingHandler.provideFormattingEndpoint} failed with ${error}`); - } - - return this.emptyFormattingResponse; - } - - private async provideOnTypeFormatting( - formattingParams: SerializableOnTypeFormattingParams, - cancellationToken: vscode.CancellationToken) { - try { - const razorDocumentUri = vscode.Uri.parse(formattingParams.textDocument.uri); - const razorDocument = await this.documentManager.getDocument(razorDocumentUri); - if (razorDocument === undefined) { - return this.emptyFormattingResponse; - } - - const textDocument = await vscode.workspace.openTextDocument(razorDocumentUri); - const synchronized = await this.documentSynchronizer.trySynchronizeProjectedDocument(textDocument, razorDocument.csharpDocument, formattingParams.hostDocumentVersion, cancellationToken); - if (!synchronized) { - return this.emptyFormattingResponse; - } - - const virtualHtmlUri = razorDocument.htmlDocument.uri; - - const textEdits = await vscode.commands.executeCommand( - 'vscode.executeFormatOnTypeProvider', - virtualHtmlUri, - formattingParams.position, - formattingParams.ch, - formattingParams.options); - - if (textEdits === undefined) { - return this.emptyFormattingResponse; - } - - const serializableTextEdits = this.sanitizeTextEdits(razorDocument, textEdits); - - return new SerializableFormattingResponse(serializableTextEdits); - } catch (error) { - this.logger.logWarning(`${FormattingHandler.provideFormattingEndpoint} failed with ${error}`); - } - - return this.emptyFormattingResponse; - } - - private sanitizeTextEdits(razorDocument: IRazorDocument, textEdits: vscode.TextEdit[]) { - const htmlDocText = razorDocument.htmlDocument.getContent(); - const zeroBasedLineCount = this.countLines(htmlDocText); - const serializableTextEdits = Array(); - for (let textEdit of textEdits) { - // The below workaround is needed due to a bug on the HTML side where - // they'll sometimes send us an end position that exceeds the length - // of the document. Tracked by https://github.com/microsoft/vscode/issues/175298. - if (textEdit.range.end.line > zeroBasedLineCount || - textEdit.range.start.line > zeroBasedLineCount) { - const lastLineLength = this.getLastLineLength(htmlDocText); - const updatedPosition = new vscode.Position(zeroBasedLineCount, lastLineLength); - - let start = textEdit.range.start; - let end = textEdit.range.end; - if (textEdit.range.start.line > zeroBasedLineCount) { - start = updatedPosition; - } - - if (textEdit.range.end.line > zeroBasedLineCount) { - end = updatedPosition; - } - - const updatedRange = new vscode.Range(start, end); - textEdit = new vscode.TextEdit(updatedRange, textEdit.newText); - } - - const serializableTextEdit = convertTextEditToSerializable(textEdit); - serializableTextEdits.push(serializableTextEdit); - } - return serializableTextEdits; - } - - private countLines(text: string) { - let lineCount = 0; - for (const i of text) { - if (i === '\n') { - lineCount++; - } - } - - return lineCount; - } - - private getLastLineLength(text: string) { - let currentLineLength = 0; - for (let i = 0; i < text.length; i++) { - // Take into account different line ending types ('\r\n' vs. '\n') - if (i + 1 < text.length && text[i] === '\r' && text[i + 1] === '\n') { - currentLineLength = 0; - i++; - } else if (text[i] === '\n') { - currentLineLength = 0; - } else { - currentLineLength++; - } - } - - return currentLineLength; - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Formatting/SerializableFormattingParams.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Formatting/SerializableFormattingParams.ts deleted file mode 100644 index 41251fb9ba2..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Formatting/SerializableFormattingParams.ts +++ /dev/null @@ -1,13 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { SerializableTextDocumentIdentifier } from './../RPC/SerializableTextDocumentIdentifier'; - -export interface SerializableFormattingParams { - hostDocumentVersion: number; - textDocument: SerializableTextDocumentIdentifier; - options: vscode.FormattingOptions; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Formatting/SerializableFormattingResponse.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Formatting/SerializableFormattingResponse.ts deleted file mode 100644 index 1ba634d6e21..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Formatting/SerializableFormattingResponse.ts +++ /dev/null @@ -1,12 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -import { SerializableTextEdit } from './../RPC/SerializableTextEdit'; - -export class SerializableFormattingResponse { - constructor( - public readonly edits?: SerializableTextEdit[]) { - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Formatting/SerializableOnTypeFormattingParams.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Formatting/SerializableOnTypeFormattingParams.ts deleted file mode 100644 index 947a913935f..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Formatting/SerializableOnTypeFormattingParams.ts +++ /dev/null @@ -1,16 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { SerializablePosition } from '../RPC/SerializablePosition'; -import { SerializableTextDocumentIdentifier } from './../RPC/SerializableTextDocumentIdentifier'; - -export interface SerializableOnTypeFormattingParams { - hostDocumentVersion: number; - textDocument: SerializableTextDocumentIdentifier; - ch: string; - position: SerializablePosition; - options: vscode.FormattingOptions; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/HostEventStream.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/HostEventStream.ts deleted file mode 100644 index 39056129038..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/HostEventStream.ts +++ /dev/null @@ -1,65 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -// Bits in this file are contracts defined in https://github.com/omnisharp/omnisharp-vscode - -export interface HostEventStream { - post(event: BaseEvent): void; -} - -export function createTelemetryEvent( - eventName: string, - properties?: { [key: string]: string }, - measures?: { [key: string]: number }): TelemetryEvent { - - return { - type: EventType.TelemetryEvent, - eventName, - properties, - measures, - }; -} - -export function createTelemetryErrorEvent( - eventName: string, - properties?: { [key: string]: string }, - measures?: { [key: string]: number }, - errorProps?: string[]): TelemetryErrorEvent { - - return { - type: EventType.TelemetryErrorEvent, - eventName, - properties, - measures, - errorProps, - }; -} - -interface TelemetryEvent extends BaseEvent { - type: EventType.TelemetryEvent; - - eventName: string; - properties?: { [key: string]: string }; - measures?: { [key: string]: number }; -} - -interface TelemetryErrorEvent extends BaseEvent { - type: EventType.TelemetryErrorEvent; - - eventName: string; - properties?: { [key: string]: string }; - measures?: { [key: string]: number }; - errorProps?: string[]; -} - -interface BaseEvent { - type: any; -} - -// This is a sub-copied portion of OmniSharp's EventType class. -enum EventType { - TelemetryEvent = 1, - TelemetryErrorEvent = 78, -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Hover/RazorHoverProvider.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Hover/RazorHoverProvider.ts deleted file mode 100644 index a0af43e809b..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Hover/RazorHoverProvider.ts +++ /dev/null @@ -1,82 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { RazorLanguageFeatureBase } from '../RazorLanguageFeatureBase'; - -export class RazorHoverProvider - extends RazorLanguageFeatureBase - implements vscode.HoverProvider { - - public async provideHover( - document: vscode.TextDocument, position: vscode.Position, - token: vscode.CancellationToken) { - - const projection = await this.getProjection(document, position, token); - if (!projection) { - return; - } - - const results = await vscode.commands.executeCommand( - 'vscode.executeHoverProvider', - projection.uri, - projection.position); - - if (!results || results.length === 0) { - return; - } - - // At the vscode.HoverProvider layer we can only return a single hover result. Because of this limitation we need to - // be smart about combining multiple hovers content or only take a single hover result. For now we'll only take one - // of them and then based on user feedback we can change this approach in the future. - const applicableHover = results.filter(item => item.range)[0]; - if (!applicableHover) { - // No hovers available with a range. - return; - } - - // Re-map the projected hover range to the host document range - const remappedResponse = await this.serviceClient.mapToDocumentRanges( - projection.languageKind, - [applicableHover.range!], - document.uri); - - if (!remappedResponse || - !remappedResponse.ranges || - !remappedResponse.ranges[0]) { - // Couldn't remap the projected hover location, there's no hover information available. - return; - } - - if (document.version !== remappedResponse.hostDocumentVersion) { - // This hover result is for a different version of the text document, bail. - return; - } - - const rewrittenContent = new Array(); - for (const content of applicableHover.contents) { - // For some reason VSCode doesn't respect the hover contents as-is. Because of this we need to look at each permutation - // of "content" (MarkdownString | string | { language: string; value: string }) and re-compute it as a MarkdownString or - // string. - - if (typeof content === 'string') { - const markdownString = new vscode.MarkdownString(content); - rewrittenContent.push(markdownString); - } else if ((content as { language: string; value: string }).language) { - const contentObject = (content as { language: string; value: string }); - const markdownString = new vscode.MarkdownString(); - markdownString.appendCodeblock(contentObject.value, contentObject.language); - rewrittenContent.push(markdownString); - } else { - const contentValue = (content as vscode.MarkdownString).value; - const markdownString = new vscode.MarkdownString(contentValue); - rewrittenContent.push(markdownString); - } - } - - const hover = new vscode.Hover(rewrittenContent, remappedResponse.ranges[0]); - return hover; - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Html/HtmlPreviewPanel.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Html/HtmlPreviewPanel.ts deleted file mode 100644 index 6222ebf8497..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Html/HtmlPreviewPanel.ts +++ /dev/null @@ -1,141 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { IRazorDocumentChangeEvent } from '../Document/IRazorDocumentChangeEvent'; -import { RazorDocumentChangeKind } from '../Document/RazorDocumentChangeKind'; -import { RazorDocumentManager } from '../Document/RazorDocumentManager'; -import { getUriPath } from '../UriPaths'; - -export class HtmlPreviewPanel { - public static readonly viewType = 'razorHtmlPreview'; - - private panel: vscode.WebviewPanel | undefined; - private htmlContent: string | undefined; - - constructor( - private readonly documentManager: RazorDocumentManager) { - documentManager.onChange((event) => this.documentChanged(event)); - } - - public async show() { - if (this.panel) { - this.panel.reveal(vscode.ViewColumn.Two); - } else { - this.panel = vscode.window.createWebviewPanel( - HtmlPreviewPanel.viewType, - 'Razor HTML Preview', - vscode.ViewColumn.Two, { - enableScripts: true, - // Dissallow any remote sources - localResourceRoots: [], - }); - this.attachToCurrentPanel(); - } - - await this.update(); - } - - public async revive(panel: vscode.WebviewPanel) { - this.panel = panel; - this.attachToCurrentPanel(); - await this.update(); - } - - private async documentChanged(event: IRazorDocumentChangeEvent) { - if (!this.panel) { - return; - } - - if (event.kind === RazorDocumentChangeKind.htmlChanged || - event.kind === RazorDocumentChangeKind.opened || - event.kind === RazorDocumentChangeKind.closed) { - await this.update(); - } - } - - private attachToCurrentPanel() { - if (!this.panel) { - vscode.window.showErrorMessage('Unexpected error when attaching to HTML preview window.'); - return; - } - - this.panel.webview.onDidReceiveMessage(async message => { - switch (message.command) { - case 'copy': - if (!this.htmlContent) { - return; - } - - await vscode.env.clipboard.writeText(this.htmlContent); - vscode.window.showInformationMessage('Razor HTML copied to clipboard'); - return; - } - }); - this.panel.onDidDispose(() => this.panel = undefined); - } - - private async update() { - if (!this.panel) { - return; - } - const document = await this.documentManager.getActiveDocument(); - let hostDocumentFilePath = ''; - let virtualDocumentFilePath = ''; - - if (document) { - // The document is guaranteed to be a Razor document - this.htmlContent = document.htmlDocument.getContent(); - hostDocumentFilePath = getUriPath(document.uri); - virtualDocumentFilePath = getUriPath(document.htmlDocument.uri); - } else { - this.htmlContent = undefined; - } - - let content = this.htmlContent ? this.htmlContent : ''; - content = content.replace(/ - - - - - - Report a Razor issue - - - - - -

Host document file path: ${hostDocumentFilePath}

-

Virtual document file path: ${virtualDocumentFilePath}

-

-
-
${content}
- -`; - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Html/HtmlProjectedDocument.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Html/HtmlProjectedDocument.ts deleted file mode 100644 index 29d608a22b4..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Html/HtmlProjectedDocument.ts +++ /dev/null @@ -1,67 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { IProjectedDocument } from '../Projection/IProjectedDocument'; -import { ServerTextChange } from '../RPC/ServerTextChange'; -import { getUriPath } from '../UriPaths'; - -export class HtmlProjectedDocument implements IProjectedDocument { - public readonly path: string; - private content = ''; - private hostDocumentVersion: number | null = null; - private projectedDocumentVersion = 0; - - public constructor(public readonly uri: vscode.Uri) { - this.path = getUriPath(uri); - } - - public get hostDocumentSyncVersion(): number | null { - return this.hostDocumentVersion; - } - - public get projectedDocumentSyncVersion(): number { - return this.projectedDocumentVersion; - } - - public update(edits: ServerTextChange[], hostDocumentVersion: number) { - this.hostDocumentVersion = hostDocumentVersion; - - if (edits.length === 0) { - return; - } - - let content = this.content; - for (const edit of edits.reverse()) { - // TODO: Use a better data structure to represent the content, string concatenation is slow. - content = this.getEditedContent(edit.newText, edit.span.start, edit.span.start + edit.span.length, content); - } - - this.setContent(content); - } - - public getContent() { - return this.content; - } - - public reset() { - this.projectedDocumentVersion++; - this.hostDocumentVersion = null; - this.setContent(''); - } - - private getEditedContent(newText: string, start: number, end: number, content: string) { - const before = content.substr(0, start); - const after = content.substr(end); - content = `${before}${newText}${after}`; - - return content; - } - - private setContent(content: string) { - this.projectedDocumentVersion++; - this.content = content; - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Html/HtmlProjectedDocumentContentProvider.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Html/HtmlProjectedDocumentContentProvider.ts deleted file mode 100644 index ea4ef4c1dd0..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Html/HtmlProjectedDocumentContentProvider.ts +++ /dev/null @@ -1,66 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -import { IRazorDocumentChangeEvent } from '../Document/IRazorDocumentChangeEvent'; -import { IRazorDocumentManager } from '../Document/IRazorDocumentManager'; -import { RazorDocumentChangeKind } from '../Document/RazorDocumentChangeKind'; -import { IEventEmitterFactory } from '../IEventEmitterFactory'; -import { RazorLogger } from '../RazorLogger'; -import { getUriPath } from '../UriPaths'; -import * as vscode from '../vscodeAdapter'; - -export class HtmlProjectedDocumentContentProvider implements vscode.TextDocumentContentProvider { - public static readonly scheme = 'razor-html'; - - private readonly onDidChangeEmitter: vscode.EventEmitter; - - constructor( - private readonly documentManager: IRazorDocumentManager, - eventEmitterFactory: IEventEmitterFactory, - private readonly logger: RazorLogger) { - documentManager.onChange((event: IRazorDocumentChangeEvent) => this.documentChanged(event)); - this.onDidChangeEmitter = eventEmitterFactory.create(); - } - - public get onDidChange() { return this.onDidChangeEmitter.event; } - - public provideTextDocumentContent(uri: vscode.Uri) { - const razorDocument = this.findRazorDocument(uri); - if (!razorDocument) { - // Document was removed from the document manager, meaning there's no more content for this - // file. Report an empty document. - - if (this.logger.verboseEnabled) { - this.logger.logVerbose( - `Could not find document '${getUriPath(uri)}' when updating the HTML buffer. This typically happens when a document is removed.`); - } - return ''; - } - - const content = `${razorDocument.htmlDocument.getContent()} -// ${razorDocument.htmlDocument.projectedDocumentSyncVersion}`; - - return content; - } - - private documentChanged(event: IRazorDocumentChangeEvent) { - if (event.kind === RazorDocumentChangeKind.htmlChanged || - event.kind === RazorDocumentChangeKind.opened || - event.kind === RazorDocumentChangeKind.removed) { - // We also notify changes on document removal in order to tell VSCode that there's no more - // HTML content for the file. - - this.onDidChangeEmitter.fire(event.document.htmlDocument.uri); - } - } - - private findRazorDocument(uri: vscode.Uri) { - const projectedPath = getUriPath(uri); - - return this.documentManager.documents.find(razorDocument => - razorDocument.htmlDocument.path.localeCompare( - projectedPath, undefined, { sensitivity: 'base' }) === 0); - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Html/HtmlTagCompletionProvider.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Html/HtmlTagCompletionProvider.ts deleted file mode 100644 index 40c5821191e..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Html/HtmlTagCompletionProvider.ts +++ /dev/null @@ -1,175 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { - getLanguageService as getHtmlLanguageService, - LanguageService as HtmlLanguageService, -} from 'vscode-html-languageservice'; -import { TextDocument as ServiceTextDocument } from 'vscode-languageserver-textdocument'; -import { IRazorDocumentManager } from '../Document/IRazorDocumentManager'; -import { RazorLanguage } from '../RazorLanguage'; -import { RazorLanguageServiceClient } from '../RazorLanguageServiceClient'; -import { LanguageKind } from '../RPC/LanguageKind'; - -export class HtmlTagCompletionProvider { - private timeout: NodeJS.Timer | undefined = void 0; - private enabled = false; - private htmlLanguageService: HtmlLanguageService | undefined; - - constructor(private readonly documentManager: IRazorDocumentManager, - private readonly serviceClient: RazorLanguageServiceClient) { - } - - public register() { - this.htmlLanguageService = getHtmlLanguageService(); - - const onChangeRegistration = vscode.workspace.onDidChangeTextDocument( - args => this.onDidChangeTextDocument(args.document, args.contentChanges)); - - const onActiveTextEditorChange = vscode.window.onDidChangeActiveTextEditor(() => this.checkIfEnabled()); - - this.checkIfEnabled(); - - return vscode.Disposable.from(onChangeRegistration, onActiveTextEditorChange); - } - - private checkIfEnabled() { - this.enabled = false; - - const editor = vscode.window.activeTextEditor; - if (!editor) { - return; - } - - const document = editor.document; - if (document.languageId !== RazorLanguage.id) { - return; - } - - if (!vscode.workspace.getConfiguration(void 0, document.uri).get('html.autoClosingTags')) { - return; - } - - this.enabled = true; - } - - private async onDidChangeTextDocument( - document: vscode.TextDocument, - changes: ReadonlyArray) { - if (!this.enabled) { - return; - } - - if (changes.length === 0) { - return; - } - - if (!vscode.window.activeTextEditor || vscode.window.activeTextEditor.document !== document) { - // Don't trigger for virtual documents - return; - } - - // At this point we're guarunteed to be looking at the correct document. - if (this.timeout !== undefined) { - clearTimeout(this.timeout); - } - - const lastChange = changes[changes.length - 1]; - if (lastChange.rangeLength > 0) { - // Don't auto-complete self-closing tags when replacing. - return; - } - - const lastCharacter = lastChange.text[lastChange.text.length - 1]; - if (lastCharacter !== '>') { - // We only want to operate on open tags - return; - } - - const rangeStart = lastChange.range.start; - - if (rangeStart.character < 2) { - // Only operate when we're working with a semi-usable tag such as '' where O is some sort of identifier. - return; - } - - const changeOffset = document.offsetAt(lastChange.range.start); - let documentContent = document.getText(); - const potentialSelfClosingCharacter = documentContent.charAt(changeOffset - 1); - if (potentialSelfClosingCharacter === '/' || potentialSelfClosingCharacter === '>') { - // Tag was already closed or is incomplete no need to auto-complete. - return; - } - - if (this.atMarkupTransition(documentContent, changeOffset)) { - // We're at a tag, no need to check if we're operating in a non-HTML area - // (we want to auto-complete ). - } else { - // Check language kind - const languageResponse = await this.serviceClient.languageQuery(lastChange.range.start, document.uri); - if (languageResponse.kind !== LanguageKind.Html) { - // This prevents auto-completion of things like C# generics - return; - } - } - - const version = document.version; - - // We set a timeout to allow for multi-changes or quick document switches (opening a document then - // instantly swapping to another) to flow through the system. Basically, if content that would trigger - // an auto-close occurs we allow a small amount of time for other edits to invalidate the current - // auto-close task. - this.timeout = setTimeout(async () => { - if (!this.enabled) { - return; - } - - const activeEditor = vscode.window.activeTextEditor; - if (!activeEditor) { - return; - } - const activeDocument = activeEditor.document; - if (document !== activeDocument || activeDocument.version !== version) { - // User has already moved on or the current document was already edited. - return; - } - - const position = new vscode.Position(rangeStart.line, rangeStart.character + lastChange.text.length); - if (!this.htmlLanguageService) { - return; - } - - const razorDoc = await this.documentManager.getActiveDocument(); - if (razorDoc) { - // The document is guaranteed to be a Razor document - documentContent = razorDoc.htmlDocument.getContent(); - } - - const serviceTextDocument = ServiceTextDocument.create( - document.uri.fsPath, - document.languageId, - document.version, - documentContent); - const htmlDocument = this.htmlLanguageService.parseHTMLDocument(serviceTextDocument); - const tagCompletion = this.htmlLanguageService.doTagComplete(serviceTextDocument, position, htmlDocument); - - if (!tagCompletion) { - return; - } - - const selections = activeEditor.selections; - if (selections.length && selections.some(s => s.active.isEqual(position))) { - activeEditor.insertSnippet(new vscode.SnippetString(tagCompletion), selections.map(s => s.active)); - } else { - activeEditor.insertSnippet(new vscode.SnippetString(tagCompletion), position); - } - }, 75); - } - - private atMarkupTransition(documentContent: string, changeOffset: number): boolean { - return documentContent.substring(changeOffset - ' this.htmlPreviewPanel.show()), - this.htmlTagCompletionProvider.register(), - ]; - - if (vscode.window.registerWebviewPanelSerializer) { - registrations.push(vscode.window.registerWebviewPanelSerializer(HtmlPreviewPanel.viewType, { - deserializeWebviewPanel: async (panel: vscode.WebviewPanel) => { - await this.htmlPreviewPanel.revive(panel); - }, - })); - } - - return vscode.Disposable.from(...registrations); - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/IEventEmitterFactory.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/IEventEmitterFactory.ts deleted file mode 100644 index dbb663e80c5..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/IEventEmitterFactory.ts +++ /dev/null @@ -1,10 +0,0 @@ -/* -------------------------------------------------------------------------------------------- -* Copyright (c) Microsoft Corporation. All rights reserved. -* Licensed under the MIT License. See License.txt in the project root for license information. -* ------------------------------------------------------------------------------------------ */ - -import { EventEmitter } from './vscodeAdapter'; - -export interface IEventEmitterFactory { - create: () => EventEmitter; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/IRazorProject.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/IRazorProject.ts deleted file mode 100644 index 1c08db4f23f..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/IRazorProject.ts +++ /dev/null @@ -1,13 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { IRazorProjectConfiguration } from './IRazorProjectConfiguration'; - -export interface IRazorProject { - readonly uri: vscode.Uri; - readonly path: string; - readonly configuration?: IRazorProjectConfiguration; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/IRazorProjectChangeEvent.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/IRazorProjectChangeEvent.ts deleted file mode 100644 index 2b707aa28ac..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/IRazorProjectChangeEvent.ts +++ /dev/null @@ -1,12 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -import { IRazorProject } from './IRazorProject'; -import { RazorProjectChangeKind } from './RazorProjectChangeKind'; - -export interface IRazorProjectChangeEvent { - readonly project: IRazorProject; - readonly kind: RazorProjectChangeKind; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/IRazorProjectConfiguration.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/IRazorProjectConfiguration.ts deleted file mode 100644 index 7c4a3ea70ef..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/IRazorProjectConfiguration.ts +++ /dev/null @@ -1,19 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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'; - -export interface IRazorProjectConfiguration { - readonly path: string; - readonly uri: vscode.Uri; - readonly projectPath: string; - readonly projectUri: vscode.Uri; - readonly configuration: any; - readonly rootNamespace: string; - readonly projectWorkspaceState: any; - readonly lastUpdated: Date; - readonly documents: any; - readonly serializationFormat: string; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Implementation/RazorImplementationProvider.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Implementation/RazorImplementationProvider.ts deleted file mode 100644 index 9976de6bbbd..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Implementation/RazorImplementationProvider.ts +++ /dev/null @@ -1,36 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { RazorLanguageFeatureBase } from '../RazorLanguageFeatureBase'; -import { LanguageKind } from '../RPC/LanguageKind'; - -export class RazorImplementationProvider - extends RazorLanguageFeatureBase - implements vscode.ImplementationProvider { - - public async provideImplementation( - document: vscode.TextDocument, - position: vscode.Position, - token: vscode.CancellationToken) { - - const projection = await this.getProjection(document, position, token); - if (!projection || - projection.languageKind === LanguageKind.Html || - projection.languageKind === LanguageKind.Razor) { - // We don't think that javascript implementations are supported by VSCodes HTML support. - // Since we shim through to them we'll do nothing until we get an ask. - return; - } - - const implementations = await vscode.commands.executeCommand( - 'vscode.executeImplementationProvider', - projection.uri, - projection.position) as vscode.Location[]; - - // Omnisharp should have already done all the remapping. Nothing for us to do here. - return implementations; - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Projection/IProjectedDocument.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Projection/IProjectedDocument.ts deleted file mode 100644 index 643cc2ec438..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Projection/IProjectedDocument.ts +++ /dev/null @@ -1,14 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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'; - -export interface IProjectedDocument { - readonly path: string; - readonly uri: vscode.Uri; - readonly hostDocumentSyncVersion: number | null; - readonly projectedDocumentSyncVersion: number; - getContent(): string; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Projection/ProjectionResult.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Projection/ProjectionResult.ts deleted file mode 100644 index 0c702fbf9db..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Projection/ProjectionResult.ts +++ /dev/null @@ -1,13 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { LanguageKind } from '../RPC/LanguageKind'; - -export interface ProjectionResult { - uri: vscode.Uri; - position: vscode.Position; - languageKind: LanguageKind; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/ProposedApisFeature.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/ProposedApisFeature.ts deleted file mode 100644 index 2087995d31c..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/ProposedApisFeature.ts +++ /dev/null @@ -1,15 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 * as vscodeapi from 'vscode'; - -export class ProposedApisFeature { - public async register(vscodeType: typeof vscodeapi, localRegistrations: vscode.Disposable[]) { - if (vscodeType.env.appName.endsWith('Insiders')) { - return; - } - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/LanguageKind.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/LanguageKind.ts deleted file mode 100644 index e7f58bd75ac..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/LanguageKind.ts +++ /dev/null @@ -1,10 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - - export enum LanguageKind { - CSharp = 1, - Html = 2, - Razor = 3, -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/LanguageQueryRequest.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/LanguageQueryRequest.ts deleted file mode 100644 index bf6b3081086..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/LanguageQueryRequest.ts +++ /dev/null @@ -1,14 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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'; - -export class LanguageQueryRequest { - public readonly uri: string; - - constructor(public readonly position: vscode.Position, uri: vscode.Uri) { - this.uri = uri.toString(); - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/LanguageQueryResponse.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/LanguageQueryResponse.ts deleted file mode 100644 index 149d785eafb..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/LanguageQueryResponse.ts +++ /dev/null @@ -1,14 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { LanguageKind } from './LanguageKind'; - -export interface LanguageQueryResponse { - kind: LanguageKind; - position: vscode.Position; - positionIndex: number; - hostDocumentVersion: number | undefined; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/RazorMapToDocumentRangesRequest.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/RazorMapToDocumentRangesRequest.ts deleted file mode 100644 index 3bdfe31a03f..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/RazorMapToDocumentRangesRequest.ts +++ /dev/null @@ -1,19 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { LanguageKind } from './LanguageKind'; -import { SerializableRange } from './SerializableRange'; - -export class RazorMapToDocumentRangesRequest { - public readonly razorDocumentUri: string; - - constructor( - public readonly kind: LanguageKind, - public readonly projectedRanges: SerializableRange[], - razorDocumentUri: vscode.Uri) { - this.razorDocumentUri = razorDocumentUri.toString(); - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/RazorMapToDocumentRangesResponse.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/RazorMapToDocumentRangesResponse.ts deleted file mode 100644 index 6b2eeee63c0..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/RazorMapToDocumentRangesResponse.ts +++ /dev/null @@ -1,11 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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'; - -export interface RazorMapToDocumentRangesResponse { - ranges: vscode.Range[]; - hostDocumentVersion: number; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/RazorTextDocumentItem.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/RazorTextDocumentItem.ts deleted file mode 100644 index b68b339ba2a..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/RazorTextDocumentItem.ts +++ /dev/null @@ -1,20 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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'; - -export class RazorTextDocumentItem { - public readonly languageId: string; - public readonly version: number; - public readonly text: string; - public readonly uri: string; - - constructor(document: vscode.TextDocument) { - this.languageId = document.languageId; - this.version = document.version; - this.text = document.getText(); - this.uri = document.uri.toString(); - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/SerializableCreateDocument.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/SerializableCreateDocument.ts deleted file mode 100644 index d0e2ab190c4..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/SerializableCreateDocument.ts +++ /dev/null @@ -1,13 +0,0 @@ -/* -------------------------------------------------------------------------------------------- -* Copyright (c) Microsoft Corporation. All rights reserved. -* Licensed under the MIT License. See License.txt in the project root for license information. -* ------------------------------------------------------------------------------------------ */ - -export interface SerializableCreateDocument { - kind: 'create'; - uri: string; - options: { - overwrite: boolean; - ignoreIfExists: boolean; - }; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/SerializableDeleteDocument.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/SerializableDeleteDocument.ts deleted file mode 100644 index a25049fe6a6..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/SerializableDeleteDocument.ts +++ /dev/null @@ -1,13 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - - export interface SerializableDeleteDocument { - kind: 'delete'; - uri: string; - options: { - recursive: boolean; - ignoreIfNotExists: boolean; - }; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/SerializablePosition.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/SerializablePosition.ts deleted file mode 100644 index 7da61a9619b..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/SerializablePosition.ts +++ /dev/null @@ -1,23 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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'; - -// We'd typically just use vscode.Position here; however, that type doesn't serialize properly over the wire. -export interface SerializablePosition { - readonly line: number; - readonly character: number; -} - -export function convertPositionToSerializable(position: vscode.Position): SerializablePosition { - return { - line: position.line, - character: position.character, - }; -} - -export function convertPositionFromSerializable(position: SerializablePosition): vscode.Position { - return new vscode.Position(position.line, position.character); -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/SerializableRange.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/SerializableRange.ts deleted file mode 100644 index 7b97232bffa..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/SerializableRange.ts +++ /dev/null @@ -1,26 +0,0 @@ -/* -------------------------------------------------------------------------------------------- -* 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 { convertPositionFromSerializable, convertPositionToSerializable, SerializablePosition } from './SerializablePosition'; - -// We'd typically just use vscode.Range here; however, that type doesn't serialize properly over the wire. -export interface SerializableRange { - readonly start: SerializablePosition; - readonly end: SerializablePosition; -} - -export function convertRangeToSerializable(range: vscode.Range): SerializableRange { - return { - start: convertPositionToSerializable(range.start), - end: convertPositionToSerializable(range.end), - }; -} - -export function convertRangeFromSerializable(range: SerializableRange): vscode.Range { - return new vscode.Range( - convertPositionFromSerializable(range.start), - convertPositionFromSerializable(range.end)); -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/SerializableTextDocumentEdit.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/SerializableTextDocumentEdit.ts deleted file mode 100644 index e70cbbe488f..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/SerializableTextDocumentEdit.ts +++ /dev/null @@ -1,15 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -import { SerializableTextEdit } from './SerializableTextEdit'; - -export interface SerializableTextDocumentEdit { - kind: undefined; - textDocument: { - uri: string; - version: number; - }; - edits: Array; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/SerializableTextDocumentIdentifier.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/SerializableTextDocumentIdentifier.ts deleted file mode 100644 index 7216464a442..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/SerializableTextDocumentIdentifier.ts +++ /dev/null @@ -1,8 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -export interface SerializableTextDocumentIdentifier { - uri: string; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/SerializableTextEdit.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/SerializableTextEdit.ts deleted file mode 100644 index 5d94fe6ada0..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/SerializableTextEdit.ts +++ /dev/null @@ -1,26 +0,0 @@ -/* -------------------------------------------------------------------------------------------- -* 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 { convertRangeFromSerializable, convertRangeToSerializable, SerializableRange } from './SerializableRange'; - -// We'd typically just use vscode.TextEdit here; however, that type doesn't serialize properly over the wire. -export interface SerializableTextEdit { - readonly range: SerializableRange; - readonly newText: string; -} - -export function convertTextEditToSerializable(textEdit: vscode.TextEdit): SerializableTextEdit { - return { - range: convertRangeToSerializable(textEdit.range), - newText: textEdit.newText, - }; -} - -export function convertTextEditFromSerializable(textEdit: SerializableTextEdit): vscode.TextEdit { - return new vscode.TextEdit( - convertRangeFromSerializable(textEdit.range), - textEdit.newText); -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/SerializableWorkspaceEdit.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/SerializableWorkspaceEdit.ts deleted file mode 100644 index 415560cf2b7..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/SerializableWorkspaceEdit.ts +++ /dev/null @@ -1,49 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { SerializableRenameDocument } from '../Rename/SerializableRenameDocument'; -import { SerializableCreateDocument } from './SerializableCreateDocument'; -import { SerializableDeleteDocument } from './SerializableDeleteDocument'; -import { SerializableTextDocumentEdit } from './SerializableTextDocumentEdit'; -import { convertTextEditFromSerializable, SerializableTextEdit } from './SerializableTextEdit'; - -type SerializableDocumentChange = SerializableCreateDocument | SerializableRenameDocument | SerializableDeleteDocument | SerializableTextDocumentEdit; - -export interface SerializableWorkspaceEdit { - changes?: {[key: string]: Array}; - documentChanges?: Array; -} - -export function convertWorkspaceEditFromSerializable(data: SerializableWorkspaceEdit): vscode.WorkspaceEdit { - const workspaceEdit = new vscode.WorkspaceEdit(); - - if (Array.isArray(data.documentChanges)) { - for (const documentChange of data.documentChanges) { - if (documentChange.kind === 'create') { - workspaceEdit.createFile(vscode.Uri.parse(documentChange.uri), documentChange.options); - } else if (documentChange.kind === 'rename') { - workspaceEdit.renameFile(vscode.Uri.parse(documentChange.oldUri), vscode.Uri.parse(documentChange.newUri), documentChange.options); - } else if (documentChange.kind === 'delete') { - workspaceEdit.deleteFile(vscode.Uri.parse(documentChange.uri), documentChange.options); - } else { - const changes = documentChange.edits.map(convertTextEditFromSerializable); - workspaceEdit.set(vscode.Uri.parse(documentChange.textDocument.uri), changes); - } - } - } - - if (data.changes !== undefined) { - for (const uri in data.changes) { - if (!data.changes.hasOwnProperty(uri)) { - continue; - } - const changes = data.changes[uri].map(convertTextEditFromSerializable); - workspaceEdit.set(vscode.Uri.parse(uri), changes); - } - } - - return workspaceEdit; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/ServerTextChange.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/ServerTextChange.ts deleted file mode 100644 index d3af53a6f33..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/ServerTextChange.ts +++ /dev/null @@ -1,11 +0,0 @@ -/* -------------------------------------------------------------------------------------------- -* Copyright (c) Microsoft Corporation. All rights reserved. -* Licensed under the MIT License. See License.txt in the project root for license information. -* ------------------------------------------------------------------------------------------ */ - -import { ServerTextSpan } from './ServerTextSpan'; - -export interface ServerTextChange { - readonly newText: string; - readonly span: ServerTextSpan; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/ServerTextSpan.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/ServerTextSpan.ts deleted file mode 100644 index 2ee37befa43..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/ServerTextSpan.ts +++ /dev/null @@ -1,9 +0,0 @@ -/* -------------------------------------------------------------------------------------------- -* Copyright (c) Microsoft Corporation. All rights reserved. -* Licensed under the MIT License. See License.txt in the project root for license information. -* ------------------------------------------------------------------------------------------ */ - -export interface ServerTextSpan { - readonly start: number; - readonly length: number; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/UpdateBufferRequest.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/UpdateBufferRequest.ts deleted file mode 100644 index 850a6d04b23..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RPC/UpdateBufferRequest.ts +++ /dev/null @@ -1,14 +0,0 @@ -/* -------------------------------------------------------------------------------------------- -* Copyright (c) Microsoft Corporation. All rights reserved. -* Licensed under the MIT License. See License.txt in the project root for license information. -* ------------------------------------------------------------------------------------------ */ - -import { ServerTextChange } from './ServerTextChange'; - -export class UpdateBufferRequest { - constructor( - public readonly hostDocumentVersion: number, - public readonly hostDocumentFilePath: string, - public readonly changes: ServerTextChange[]) { - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorCSharpLanguageMiddleware.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorCSharpLanguageMiddleware.ts deleted file mode 100644 index d2b60e5dec7..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorCSharpLanguageMiddleware.ts +++ /dev/null @@ -1,137 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { getRazorDocumentUri, isRazorCSharpFile } from './RazorConventions'; -import { RazorLanguageServiceClient } from './RazorLanguageServiceClient'; -import { RazorLogger } from './RazorLogger'; -import { LanguageKind } from './RPC/LanguageKind'; - -// This interface should exactly match the `LanguageMiddleware` interface defined in Omnisharp. -// https://github.com/OmniSharp/omnisharp-vscode/blob/master/src/omnisharp/LanguageMiddlewareFeature.ts#L9-L16 -interface LanguageMiddleware { - - language: string; - - remapWorkspaceEdit?(workspaceEdit: vscode.WorkspaceEdit, token: vscode.CancellationToken): vscode.ProviderResult; - - remapLocations?(locations: vscode.Location[], token: vscode.CancellationToken): vscode.ProviderResult; -} - -export class RazorCSharpLanguageMiddleware implements LanguageMiddleware { - public readonly language = 'Razor'; - - constructor( - private readonly serviceClient: RazorLanguageServiceClient, - private readonly logger: RazorLogger) {} - - public async remapWorkspaceEdit(workspaceEdit: vscode.WorkspaceEdit, token: vscode.CancellationToken) { - const map = new Map(); - - // The returned edits will be for the projected C# documents. We now need to re-map that to the original document. - for (const entry of workspaceEdit.entries()) { - const uri = entry[0]; - const edits = entry[1]; - - if (!isRazorCSharpFile(uri)) { - // This edit happens outside of a Razor document. Let the edit go through as is. - map.set(uri, edits); - continue; - } - - // We're now working with a Razor CSharp document. - const documentUri = getRazorDocumentUri(uri); - - // Re-map each edit to its position in the original Razor document. - for (const edit of edits) { - const remappedResponse = await this.serviceClient.mapToDocumentRanges( - LanguageKind.CSharp, - [edit.range], - documentUri); - - if (!remappedResponse || - !remappedResponse.ranges || - !remappedResponse.ranges[0]) { - // This is kind of wrong. Workspace edits commonly consist of a bunch of different edits which - // don't make sense individually. If we try to introspect on them individually there won't be - // enough context to do anything intelligent. But we also need to know if the edit can just - // be handled by mapToDocumentRange (something went wrong here), so we ignore the edit. - this.logger.logWarning(`Unable to remap file ${uri.path} at ${edit.range}.`); - continue; - } else { - const remappedEdit = new vscode.TextEdit(remappedResponse.ranges[0], edit.newText); - - this.logger.logVerbose( - `Re-mapping text ${edit.newText} at ${edit.range} in ${uri.path} to ${remappedResponse.ranges[0]} in ${documentUri.path}`); - - this.addElementToDictionary(map, documentUri, remappedEdit); - } - - } - } - - const result = this.mapToTextEdit(map); - return result; - } - - public async remapLocations(locations: vscode.Location[], token: vscode.CancellationToken) { - const result: vscode.Location[] = []; - - for (const location of locations) { - if (!isRazorCSharpFile(location.uri)) { - // This location exists outside of a Razor document. Leave it unchanged. - result.push(location); - continue; - } - - // We're now working with a Razor CSharp document. - const documentUri = getRazorDocumentUri(location.uri); - const remappedResponse = await this.serviceClient.mapToDocumentRanges( - LanguageKind.CSharp, - [location.range], - documentUri); - - if (!remappedResponse || - !remappedResponse.ranges || - !remappedResponse.ranges[0]) { - // Something went wrong when re-mapping to the original document. Ignore this location. - this.logger.logWarning(`Unable to remap file ${location.uri.path} at ${location.range}.`); - continue; - } - - const newLocation = new vscode.Location(documentUri, remappedResponse.ranges[0]); - result.push(newLocation); - - this.logger.logVerbose( - `Re-mapping location ${location.range} in ${location.uri.path} to ${remappedResponse.ranges[0]} in ${documentUri.path}`); - } - - return result; - } - - private mapToTextEdit(map: Map): vscode.WorkspaceEdit { - const result = new vscode.WorkspaceEdit(); - map.forEach((value, key) => { - result.set(key, value); - }); - - return result; - } - - private addElementToDictionary(map: Map, uri: vscode.Uri, edit: vscode.TextEdit) { - let mapArray: vscode.TextEdit[] | undefined; - - if (map.has(uri)) { - mapArray = map.get(uri); - if (mapArray) { - mapArray.push(edit); - } - } else { - const editArray = new Array(); - editArray.push(edit); - map.set(uri, editArray); - } - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorConventions.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorConventions.ts deleted file mode 100644 index 11f3d01f542..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorConventions.ts +++ /dev/null @@ -1,31 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 './UriPaths'; - -export const virtualHtmlSuffix = '__virtual.html'; -export const virtualCSharpSuffix = '__virtual.cs'; -export const backgroundVirtualCSharpSuffix = `__bg${virtualCSharpSuffix}`; - -export function isRazorCSharpFile(uri: vscode.Uri) { - const path = getUriPath(uri); - return path.endsWith(virtualCSharpSuffix); -} - -export function isRazorHtmlFile(uri: vscode.Uri) { - const path = getUriPath(uri); - return path.endsWith(virtualHtmlSuffix); -} - -export function getRazorDocumentUri(uri: vscode.Uri) { - const path = getUriPath(uri); - let originalDocumentPath = path.replace(backgroundVirtualCSharpSuffix, ''); - originalDocumentPath = originalDocumentPath.replace(virtualCSharpSuffix, ''); - originalDocumentPath = originalDocumentPath.replace(virtualHtmlSuffix, ''); - - const documentUri = vscode.Uri.file(originalDocumentPath); - return documentUri; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorExtensionId.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorExtensionId.ts deleted file mode 100644 index 690ca024144..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorExtensionId.ts +++ /dev/null @@ -1,7 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - -// The Razor experience is shipped as part of OmniSharp, this is their extension ID. -export const razorExtensionId = 'ms-dotnettools.csharp'; diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorLanguage.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorLanguage.ts deleted file mode 100644 index ab2128539ff..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorLanguage.ts +++ /dev/null @@ -1,13 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 './vscodeAdapter'; - -export class RazorLanguage { - public static id = 'aspnetcorerazor'; - public static fileExtensions = [ 'cshtml', 'razor' ]; - public static globbingPattern = `**/*.{${RazorLanguage.fileExtensions.join(',')}}`; - public static documentSelector: vscode.DocumentSelector = { language: this.id, pattern: RazorLanguage.globbingPattern }; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorLanguageConfiguration.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorLanguageConfiguration.ts deleted file mode 100644 index 965e1f21b36..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorLanguageConfiguration.ts +++ /dev/null @@ -1,49 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { RazorLanguage } from './RazorLanguage'; - -const VOID_ELEMENTS: string[] = [ - 'area', - 'base', - 'br', - 'col', - 'embed', - 'hr', - 'img', - 'input', - 'keygen', - 'link', - 'menuitem', - 'meta', - 'param', - 'source', - 'track', - 'wbr', -]; - -export class RazorLanguageConfiguration { - public register() { - const configurationRegistration = vscode.languages.setLanguageConfiguration(RazorLanguage.id, { - wordPattern: /(-?\d*\.\d\w*)|([^\`\~\!\@\$\^\&\*\(\)\-\=\+\[\{\]\}\\\|\;\:\'\"\,\.\<\>\/\s]+)/g, - onEnterRules: [ - { - beforeText: new RegExp( - `<(?!(?:${VOID_ELEMENTS.join('|')}))([_:\\w][_:\\w-.\\d]*)([^/>]*(?!/)>)[^<]*$`, 'i'), - afterText: /^<\/([_:\w][_:\w-.\d]*)\s*>/i, - action: { indentAction: vscode.IndentAction.IndentOutdent }, - }, - { - beforeText: new RegExp( - `<(?!(?:${VOID_ELEMENTS.join('|')}))(\\w[\\w\\d]*)([^/>]*(?!/)>)[^<]*$`, 'i'), - action: { indentAction: vscode.IndentAction.Indent }, - }, - ], - }); - - return configurationRegistration; - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorLanguageFeatureBase.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorLanguageFeatureBase.ts deleted file mode 100644 index 62f87c527ab..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorLanguageFeatureBase.ts +++ /dev/null @@ -1,67 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { RazorDocumentManager } from './Document/RazorDocumentManager'; -import { RazorDocumentSynchronizer } from './Document/RazorDocumentSynchronizer'; -import { ProjectionResult } from './Projection/ProjectionResult'; -import { RazorLanguageServiceClient } from './RazorLanguageServiceClient'; -import { RazorLogger } from './RazorLogger'; -import { LanguageKind } from './RPC/LanguageKind'; -import { getUriPath } from './UriPaths'; - -export class RazorLanguageFeatureBase { - constructor( - private readonly documentSynchronizer: RazorDocumentSynchronizer, - protected readonly documentManager: RazorDocumentManager, - protected readonly serviceClient: RazorLanguageServiceClient, - protected readonly logger: RazorLogger) { - } - - protected async getProjection( - document: vscode.TextDocument, - position: vscode.Position, - token: vscode.CancellationToken) { - const languageResponse = await this.serviceClient.languageQuery(position, document.uri); - - switch (languageResponse.kind) { - case LanguageKind.CSharp: - case LanguageKind.Html: - const razorDocument = await this.documentManager.getDocument(document.uri); - const projectedDocument = languageResponse.kind === LanguageKind.CSharp - ? razorDocument.csharpDocument - : razorDocument.htmlDocument; - - if (languageResponse.hostDocumentVersion === undefined) { - // There should always be a document version attached to an open document. - // Log it and move on as if it was synchronized. - if (this.logger.verboseEnabled) { - this.logger.logVerbose( - `Could not find a document version associated with the document '${getUriPath(document.uri)}'.`); - } - } else { - const synchronized = await this.documentSynchronizer.trySynchronizeProjectedDocument( - document, - projectedDocument, - languageResponse.hostDocumentVersion, - token); - if (!synchronized) { - // Could not synchronize - return null; - } - } - - const projectedUri = projectedDocument.uri; - return { - uri: projectedUri, - position: languageResponse.position, - languageKind: languageResponse.kind, - } as ProjectionResult; - - default: - return null; - } - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorLanguageServerClient.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorLanguageServerClient.ts deleted file mode 100644 index f7b225bc296..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorLanguageServerClient.ts +++ /dev/null @@ -1,247 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -import { EventEmitter } from 'events'; -import * as vscode from 'vscode'; -import { - RequestHandler, - RequestType, -} from 'vscode-jsonrpc'; -import { - GenericNotificationHandler, - InitializeResult, - LanguageClientOptions, - State, -} from 'vscode-languageclient'; -import { - LanguageClient, - ServerOptions, -} from 'vscode-languageclient/node'; -import { RazorLanguage } from './RazorLanguage'; -import { RazorLanguageServerOptions } from './RazorLanguageServerOptions'; -import { resolveRazorLanguageServerOptions } from './RazorLanguageServerOptionsResolver'; -import { resolveRazorLanguageServerTrace } from './RazorLanguageServerTraceResolver'; -import { RazorLogger } from './RazorLogger'; -import { TelemetryReporter } from './TelemetryReporter'; - -const events = { - ServerStop: 'ServerStop', -}; - -export class RazorLanguageServerClient implements vscode.Disposable { - private clientOptions!: LanguageClientOptions; - private serverOptions!: ServerOptions; - private client!: LanguageClient; - private onStartListeners: Array<() => Promise> = []; - private onStartedListeners: Array<() => Promise> = []; - private eventBus: EventEmitter; - private isStarted: boolean; - private startHandle: Promise | undefined; - private stopHandle: Promise | undefined; - - constructor( - private readonly vscodeType: typeof vscode, - private readonly languageServerDir: string, - private readonly telemetryReporter: TelemetryReporter, - private readonly logger: RazorLogger) { - this.isStarted = false; - - this.setupLanguageServer(); - - this.eventBus = new EventEmitter(); - } - - public get initializeResult(): InitializeResult | undefined { - return this.client.initializeResult; - } - - public updateTraceLevel() { - const languageServerTrace = resolveRazorLanguageServerTrace(this.vscodeType); - this.setupLanguageServer(); - this.logger.setTraceLevel(languageServerTrace); - } - - public onStarted(listener: () => Promise) { - this.onStartedListeners.push(listener); - } - - public onStart(listener: () => Promise) { - this.onStartListeners.push(listener); - } - - public onStop(listener: () => any) { - this.eventBus.addListener(events.ServerStop, listener); - - const disposable = new vscode.Disposable(() => - this.eventBus.removeListener(events.ServerStop, listener)); - return disposable; - } - - public async start() { - if (this.startHandle) { - return this.startHandle; - } - - let resolve: () => void = Function; - let reject: (reason: any) => void = Function; - this.startHandle = new Promise((resolver, rejecter) => { - resolve = resolver; - reject = rejecter; - }); - - // Workaround https://github.com/Microsoft/vscode-languageserver-node/issues/472 by tying into state - // change events to detect when restarts are occuring and then properly reject the Language Server - // start listeners. - let restartCount = 0; - const didChangeStateDisposable = this.client.onDidChangeState((stateChangeEvent: { newState: any; oldState: any; }) => { - if (stateChangeEvent.oldState === State.Starting && stateChangeEvent.newState === State.Stopped) { - restartCount++; - - if (restartCount === 5) { - // Timeout, the built-in LanguageClient retries a hardcoded 5 times before giving up. We tie into that - // and then given up on starting the language server if we can't start by then. - reject('Server failed to start after retrying 5 times.'); - } - } else if (stateChangeEvent.newState === State.Running) { - restartCount = 0; - } - }); - - try { - this.logger.logMessage('Starting Razor Language Server...'); - await this.client.start(); - this.logger.logMessage('Server started, waiting for client to be ready...'); - this.isStarted = true; - for (const listener of this.onStartListeners) { - await listener(); - } - - // Succesfully started, notify listeners. - resolve(); - - this.logger.logMessage('Server ready!'); - for (const listener of this.onStartedListeners) { - await listener(); - } - - // We don't want to track restart management after the server has been initially started, - // the language client will handle that. - didChangeStateDisposable.dispose(); - } catch (error) { - vscode.window.showErrorMessage( - 'Razor Language Server failed to start unexpectedly, ' + - 'please check the \'Razor Log\' and report an issue.'); - - this.telemetryReporter.reportErrorOnServerStart(error as Error); - reject(error); - } - - return this.startHandle; - } - - public async sendRequest(method: string, param: any) { - if (!this.isStarted) { - throw new Error('Tried to send requests while server is not started.'); - } - - return this.client.sendRequest(method, param); - } - - public async onRequestWithParams(method: RequestType, handler: RequestHandler) { - if (!this.isStarted) { - throw new Error('Tried to bind on request logic while server is not started.'); - } - - this.client.onRequest(method, handler); - } - - public onNotification(method: string, handler: GenericNotificationHandler) { - if (!this.isStarted) { - throw new Error('Tried to bind on notification logic while server is not started.'); - } - - this.client.onNotification(method, handler); - } - - public dispose() { - this.logger.logMessage('Disposing Razor Language Server.'); - - this.isStarted = false; - this.startHandle = undefined; - this.eventBus.emit(events.ServerStop); - } - - public async stop() { - let resolve: () => void = Function; - let reject: (reason: any) => void = Function; - this.stopHandle = new Promise((resolver, rejecter) => { - resolve = resolver; - reject = rejecter; - }); - - if (!this.startHandle) { - reject(new Error('Cannot stop Razor Language Server as it is already stopped.')); - } - - this.logger.logMessage('Stopping Razor Language Server.'); - - try { - if (this.client) { - await this.client.stop(); - } - - this.dispose(); - - resolve(); - } catch (error) { - vscode.window.showErrorMessage( - 'Razor Language Server failed to stop correctly, ' + - 'please check the \'Razor Log\' and report an issue.'); - - reject(error); - } - - return this.stopHandle; - } - - private setupLanguageServer() { - const languageServerTrace = resolveRazorLanguageServerTrace(this.vscodeType); - const options: RazorLanguageServerOptions = resolveRazorLanguageServerOptions(this.vscodeType, this.languageServerDir, languageServerTrace, this.logger); - - this.clientOptions = { - outputChannel: options.outputChannel, - documentSelector: [ { language: RazorLanguage.id, pattern: RazorLanguage.globbingPattern } ], - }; - - const args: string[] = []; - let command = options.serverPath; - if (options.serverPath.endsWith('.dll')) { - this.logger.logMessage('Razor Language Server path is an assembly. ' + - 'Using \'dotnet\' from the current path to start the server.'); - - command = 'dotnet'; - args.push(options.serverPath); - } - - this.logger.logMessage(`Razor language server path: ${options.serverPath}`); - - args.push('-lsp'); - args.push('--trace'); - - this.telemetryReporter.reportTraceLevel(options.trace); - - args.push(options.trace.toString()); - - if (options.debug) { - this.telemetryReporter.reportDebugLanguageServer(); - - this.logger.logMessage('Debug flag set for Razor Language Server.'); - args.push('--debug'); - } - - this.serverOptions = { command, args }; - this.client = new LanguageClient('razorLanguageServer', 'Razor Language Server', this.serverOptions, this.clientOptions); - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorLanguageServerOptions.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorLanguageServerOptions.ts deleted file mode 100644 index e18f7389c5e..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorLanguageServerOptions.ts +++ /dev/null @@ -1,14 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { Trace } from './Trace'; - -export interface RazorLanguageServerOptions { - serverPath: string; - outputChannel?: vscode.OutputChannel; - debug?: boolean; - trace: Trace; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorLanguageServerOptionsResolver.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorLanguageServerOptionsResolver.ts deleted file mode 100644 index 46fb9b7b192..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorLanguageServerOptionsResolver.ts +++ /dev/null @@ -1,58 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -import * as fs from 'fs'; -import * as os from 'os'; -import * as path from 'path'; -import { RazorLanguageServerOptions } from './RazorLanguageServerOptions'; -import { RazorLogger } from './RazorLogger'; -import { Trace } from './Trace'; -import * as vscode from './vscodeAdapter'; - -export function resolveRazorLanguageServerOptions( - vscodeApi: vscode.api, - languageServerDir: string, - trace: Trace, - logger: RazorLogger) { - const languageServerExecutablePath = findLanguageServerExecutable(languageServerDir); - const serverConfig = vscodeApi.workspace.getConfiguration('razor.languageServer'); - const debugLanguageServer = serverConfig.get('debug'); - - return { - serverPath: languageServerExecutablePath, - debug: debugLanguageServer, - trace, - outputChannel: logger.outputChannel, - } as RazorLanguageServerOptions; -} - -function findLanguageServerExecutable(withinDir: string) { - const extension = isWindows() ? '.exe' : ''; - const executablePath = path.join( - withinDir, - `rzls${extension}`); - let fullPath = ''; - - if (fs.existsSync(executablePath)) { - fullPath = executablePath; - } else { - // Exe doesn't exist. - const dllPath = path.join( - withinDir, - 'rzls.dll'); - - if (!fs.existsSync(dllPath)) { - throw new Error(`Could not find Razor Language Server executable within directory '${withinDir}'`); - } - - fullPath = dllPath; - } - - return fullPath; -} - -function isWindows() { - return !!os.platform().match(/^win/); -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorLanguageServerTraceResolver.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorLanguageServerTraceResolver.ts deleted file mode 100644 index 241682c18ce..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorLanguageServerTraceResolver.ts +++ /dev/null @@ -1,29 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -import { Trace } from './Trace'; -import * as vscode from './vscodeAdapter'; - -export function resolveRazorLanguageServerTrace(vscodeApi: vscode.api) { - const languageConfig = vscodeApi.workspace.getConfiguration('razor'); - const traceString = languageConfig.get('trace'); - const trace = parseTraceString(traceString); - - return trace; -} - -function parseTraceString(traceString: string | undefined) { - switch (traceString) { - case 'Off': - return Trace.Off; - case 'Messages': - return Trace.Messages; - case 'Verbose': - return Trace.Verbose; - default: - console.log('Invalid trace setting for Razor language server. Defaulting to \'Off\''); - return Trace.Off; - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorLanguageServiceClient.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorLanguageServiceClient.ts deleted file mode 100644 index 8bddaa3a9e8..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorLanguageServiceClient.ts +++ /dev/null @@ -1,67 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { RazorLanguageServerClient } from './RazorLanguageServerClient'; -import { LanguageKind } from './RPC/LanguageKind'; -import { LanguageQueryRequest } from './RPC/LanguageQueryRequest'; -import { LanguageQueryResponse } from './RPC/LanguageQueryResponse'; -import { RazorMapToDocumentRangesRequest } from './RPC/RazorMapToDocumentRangesRequest'; -import { RazorMapToDocumentRangesResponse } from './RPC/RazorMapToDocumentRangesResponse'; -import { convertRangeFromSerializable, convertRangeToSerializable } from './RPC/SerializableRange'; -import { SemanticTokensRangeRequest } from './Semantic/SemanticTokensRangeRequest'; - -export class RazorLanguageServiceClient { - constructor(private readonly serverClient: RazorLanguageServerClient) { - } - - public async languageQuery(position: vscode.Position, uri: vscode.Uri) { - await this.ensureStarted(); - - const request = new LanguageQueryRequest(position, uri); - const response = await this.serverClient.sendRequest('razor/languageQuery', request); - response.position = new vscode.Position(response.position.line, response.position.character); - return response; - } - - public async mapToDocumentRanges(languageKind: LanguageKind, ranges: vscode.Range[], uri: vscode.Uri) { - await this.ensureStarted(); - - const serializableRanges = []; - for (const range of ranges) { - const serializableRange = convertRangeToSerializable(range); - serializableRanges.push(serializableRange); - } - - const request = new RazorMapToDocumentRangesRequest(languageKind, serializableRanges, uri); - const response = await this.serverClient.sendRequest('razor/mapToDocumentRanges', request); - const responseRanges = []; - for (const range of response.ranges) { - if (range.start.line >= 0) { - const remappedRange = convertRangeFromSerializable(response.ranges[0]); - responseRanges.push(remappedRange); - } - } - - response.ranges = responseRanges; - return response; - } - - public async semanticTokensRange(uri: vscode.Uri, range: vscode.Range): Promise { - await this.ensureStarted(); - - const request = new SemanticTokensRangeRequest(uri, range); - const response = await this.serverClient.sendRequest('textDocument/semanticTokens/range', request); - - if (response.data && response.data.length > 0) { - return response; - } - } - - private async ensureStarted() { - // If the server is already started this will instantly return. - await this.serverClient.start(); - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorLogger.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorLogger.ts deleted file mode 100644 index c1a0b525e8d..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorLogger.ts +++ /dev/null @@ -1,147 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -import * as fs from 'fs'; -import * as path from 'path'; -import { IEventEmitterFactory } from './IEventEmitterFactory'; -import { Trace } from './Trace'; -import * as vscode from './vscodeAdapter'; - -export class RazorLogger implements vscode.Disposable { - public static readonly logName = 'Razor Log'; - public verboseEnabled!: boolean; - public messageEnabled!: boolean; - public readonly outputChannel: vscode.OutputChannel; - - private readonly onLogEmitter: vscode.EventEmitter; - private readonly onTraceLevelChangeEmitter: vscode.EventEmitter; - - constructor( - private readonly vscodeApi: vscode.api, - eventEmitterFactory: IEventEmitterFactory, - public trace: Trace) { - this.processTraceLevel(); - this.onLogEmitter = eventEmitterFactory.create(); - this.onTraceLevelChangeEmitter = eventEmitterFactory.create(); - - this.outputChannel = this.vscodeApi.window.createOutputChannel(RazorLogger.logName); - - this.logRazorInformation(); - } - - public setTraceLevel(trace: Trace) { - this.trace = trace; - this.processTraceLevel(); - this.logMessage(`Updated trace level to: ${Trace[this.trace]}`); - this.onTraceLevelChangeEmitter.fire(this.trace); - } - - public get onLog() { return this.onLogEmitter.event; } - - public get onTraceLevelChange() { return this.onTraceLevelChangeEmitter.event; } - - public logAlways(message: string) { - this.logWithMarker(message); - } - - public logWarning(message: string) { - // Always log warnings - const warningPrefixedMessage = `(Warning) ${message}`; - this.logAlways(warningPrefixedMessage); - } - - public logError(message: string, error: unknown) { - if (error instanceof Error) { - this.logErrorInternal(message, error); - } else { - const errorMsg = String(error); - this.logErrorInternal(message, Error(errorMsg)); - } - } - - public logMessage(message: string) { - if (this.messageEnabled) { - this.logWithMarker(message); - } - } - - public logVerbose(message: string) { - if (this.verboseEnabled) { - this.logWithMarker(message); - } - } - - public dispose() { - this.outputChannel.dispose(); - } - - private logErrorInternal(message: string, error: Error) { - // Always log errors - const errorPrefixedMessage = `(Error) ${message} -${error.message} -Stack Trace: -${error.stack}`; - this.logAlways(errorPrefixedMessage); - } - - private logWithMarker(message: string) { - const timeString = new Date().toLocaleTimeString(); - const markedMessage = `[Client - ${timeString}] ${message}`; - - this.log(markedMessage); - } - - private log(message: string) { - this.outputChannel.appendLine(message); - - this.onLogEmitter.fire(message); - } - - private logRazorInformation() { - const packageJsonContents = readOwnPackageJson(); - - this.log( - '--------------------------------------------------------------------------------'); - this.log(`Razor.VSCode version ${packageJsonContents.defaults.razor}`); - this.log( - '--------------------------------------------------------------------------------'); - this.log(`Razor's trace level is currently set to '${Trace[this.trace]}'`); - this.log( - ' - To change Razor\'s trace level set \'razor.trace\' to ' + - '\'Off\', \'Messages\' or \'Verbose\' and then restart VSCode.'); - this.log( - ' - To report issues invoke the \'Report a Razor issue\' command via the command palette.'); - this.log( - '-----------------------------------------------------------------------' + - '------------------------------------------------------'); - this.log(''); - } - - private processTraceLevel() { - this.verboseEnabled = this.trace >= Trace.Verbose; - this.messageEnabled = this.trace >= Trace.Messages; - } -} - -function readOwnPackageJson() { - const packageJsonPath = findInDirectoryOrAncestor(__dirname, 'package.json'); - return JSON.parse(fs.readFileSync(packageJsonPath).toString()); -} - -function findInDirectoryOrAncestor(dir: string, filename: string) { - while (true) { - const candidate = path.join(dir, filename); - if (fs.existsSync(candidate)) { - return candidate; - } - - const parentDir = path.dirname(dir); - if (parentDir === dir) { - throw new Error(`Could not find '${filename}' in or above '${dir}'.`); - } - - dir = parentDir; - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorProjectChangeKind.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorProjectChangeKind.ts deleted file mode 100644 index b4d78cb4859..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/RazorProjectChangeKind.ts +++ /dev/null @@ -1,10 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -export enum RazorProjectChangeKind { - added, - removed, - changed, -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Reference/RazorReferenceProvider.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Reference/RazorReferenceProvider.ts deleted file mode 100644 index c3de466ec16..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Reference/RazorReferenceProvider.ts +++ /dev/null @@ -1,52 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { getRazorDocumentUri, isRazorHtmlFile } from '../RazorConventions'; -import { RazorLanguageFeatureBase } from '../RazorLanguageFeatureBase'; -import { LanguageKind } from '../RPC/LanguageKind'; - -export class RazorReferenceProvider - extends RazorLanguageFeatureBase - implements vscode.ReferenceProvider { - - public async provideReferences( - document: vscode.TextDocument, - position: vscode.Position, - context: vscode.ReferenceContext, - token: vscode.CancellationToken) { - - const projection = await this.getProjection(document, position, token); - if (!projection || projection.languageKind === LanguageKind.Razor) { - return; - } - - const references = await vscode.commands.executeCommand( - 'vscode.executeReferenceProvider', - projection.uri, - projection.position) as vscode.Location[]; - - const result = new Array(); - for (const reference of references) { - if (projection.languageKind === LanguageKind.Html && isRazorHtmlFile(reference.uri)) { - - // Because the line pragmas for html are generated referencing the projected document - // we need to remap their file locations to reference the top level Razor document. - const razorFile = getRazorDocumentUri(reference.uri); - result.push(new vscode.Location(razorFile, reference.range)); - - } else { - // This means it is one of the following, - // 1. A .razor/.cshtml file (because OmniSharp already remapped the background C# to the original document) - // 2. A .cs file - // 3. A .html/.js file - // In all of these cases, we don't need to remap. So accept it as is and move on. - result.push(reference); - } - } - - return result; - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Rename/RazorRenameProvider.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Rename/RazorRenameProvider.ts deleted file mode 100644 index 18de64b7122..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Rename/RazorRenameProvider.ts +++ /dev/null @@ -1,74 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { RazorDocumentManager } from '../Document/RazorDocumentManager'; -import { RazorDocumentSynchronizer } from '../Document/RazorDocumentSynchronizer'; -import { RazorLanguageFeatureBase } from '../RazorLanguageFeatureBase'; -import { RazorLanguageServiceClient } from '../RazorLanguageServiceClient'; -import { RazorLogger } from '../RazorLogger'; -import { LanguageKind } from '../RPC/LanguageKind'; - -export class RazorRenameProvider - extends RazorLanguageFeatureBase - implements vscode.RenameProvider { - - constructor( - documentSynchronizer: RazorDocumentSynchronizer, - documentManager: RazorDocumentManager, - serviceClient: RazorLanguageServiceClient, - logger: RazorLogger) { - super(documentSynchronizer, documentManager, serviceClient, logger); - } - - public async prepareRename( - document: vscode.TextDocument, - position: vscode.Position, - token: vscode.CancellationToken) { - - const projection = await this.getProjection(document, position, token); - if (!projection || projection.languageKind !== LanguageKind.CSharp) { - // We only support C# renames for now. Reject the rename request. - // Originally we rejected here. However due to how the language - // server client currently works, if we reject here it prevents - // other servers from being able to return a response instead. - // Null is the only return that allows us to handle renaming - // from the Razor language server. - return null; // Promise.reject('Cannot rename this symbol.'); - } - - // Let the rename go through. OmniSharp doesn't currently support "prepareRename" so we need to utilize document - // APIs in order to resolve the appropriate rename range. - const range = document.getWordRangeAtPosition(position); - return range; - } - - public async provideRenameEdits( - document: vscode.TextDocument, - position: vscode.Position, - newName: string, - token: vscode.CancellationToken) { - - const projection = await this.getProjection(document, position, token); - if (!projection) { - return; - } - - if (projection.languageKind !== LanguageKind.CSharp) { - // We only support C# renames for now. - return; - } - - // Send a rename command to Omnisharp which in turn would call our command to get the Razor documents re-mapped. - const response = await vscode.commands.executeCommand( - 'vscode.executeDocumentRenameProvider', - projection.uri, - projection.position, - newName, - ); - - return response; - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Rename/SerializableRenameDocument.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Rename/SerializableRenameDocument.ts deleted file mode 100644 index 91b6f937ad2..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Rename/SerializableRenameDocument.ts +++ /dev/null @@ -1,14 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - - export interface SerializableRenameDocument { - kind: 'rename'; - oldUri: string; - newUri: string; - options: { - overwrite: boolean; - ignoreIfExists: boolean; - }; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Semantic/ProvideSemanticTokensResponse.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Semantic/ProvideSemanticTokensResponse.ts deleted file mode 100644 index 5bec77de3a9..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Semantic/ProvideSemanticTokensResponse.ts +++ /dev/null @@ -1,11 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - -import { SemanticTokensResponse } from './SemanticTokensResponse'; - -export class ProvideSemanticTokensResponse { - // tslint:disable-next-line: variable-name - constructor(public Result: SemanticTokensResponse, public HostDocumentSyncVersion: number | null) {} -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Semantic/RazorDocumentSemanticTokensProvider.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Semantic/RazorDocumentSemanticTokensProvider.ts deleted file mode 100644 index 0c004f410e6..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Semantic/RazorDocumentSemanticTokensProvider.ts +++ /dev/null @@ -1,28 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { RazorLanguageFeatureBase } from '../RazorLanguageFeatureBase'; - -export class RazorDocumentSemanticTokensProvider - extends RazorLanguageFeatureBase - implements vscode.DocumentRangeSemanticTokensProvider { - public async provideDocumentRangeSemanticTokens( - document: vscode.TextDocument, - range: vscode.Range, - token: vscode.CancellationToken, - ): Promise { - let semanticRangeResponse = await this.serviceClient.semanticTokensRange(document.uri, range); - - if (semanticRangeResponse) { - // However we're serializing into Uint32Array doesn't set byteLength, which is checked by some stuff under the covers. - // Solution? Create a new one, blat it over the old one, go home for the weekend. - const fixedArray = new Uint32Array(semanticRangeResponse.data); - semanticRangeResponse = new vscode.SemanticTokens(fixedArray, semanticRangeResponse.resultId); - } - - return semanticRangeResponse; - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Semantic/SemanticTokens.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Semantic/SemanticTokens.ts deleted file mode 100644 index cc4059dff34..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Semantic/SemanticTokens.ts +++ /dev/null @@ -1,8 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -export interface SemanticTokens { - data: number[]; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Semantic/SemanticTokensRangeHandler.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Semantic/SemanticTokensRangeHandler.ts deleted file mode 100644 index e18fd45411f..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Semantic/SemanticTokensRangeHandler.ts +++ /dev/null @@ -1,39 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * 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 { RequestType } from 'vscode-languageclient'; -import { RazorLanguageServerClient } from '../RazorLanguageServerClient'; -import { ProvideSemanticTokensResponse } from './ProvideSemanticTokensResponse'; -import { SemanticTokensResponse } from './SemanticTokensResponse'; -import { SerializableSemanticTokensParams } from './SerializableSemanticTokensParams'; - -export class SemanticTokensRangeHandler { - private static readonly getSemanticTokensRangeEndpoint = 'razor/provideSemanticTokensRange'; - private semanticTokensRequestType: RequestType = - new RequestType(SemanticTokensRangeHandler.getSemanticTokensRangeEndpoint); - private emptySemanticTokensResponse: ProvideSemanticTokensResponse = new ProvideSemanticTokensResponse( - new SemanticTokensResponse(new Array(), ''), - null); - - constructor(private readonly serverClient: RazorLanguageServerClient) { } - - public register() { - return this.serverClient.onRequestWithParams( - this.semanticTokensRequestType, - async (request: SerializableSemanticTokensParams, token: vscode.CancellationToken) => this.getSemanticTokens(request, token)); - } - - private async getSemanticTokens( - semanticTokensParams: SerializableSemanticTokensParams, - cancellationToken: vscode.CancellationToken): Promise { - - // This is currently a no-op since (1) the default C# semantic tokens experience is already powerful and - // (2) there seems to be an issue with the semantic tokens execute command - possibly either O# not - // returning tokens, or an issue with the command itself: - // https://github.com/dotnet/razor-tooling/issues/6922 - return this.emptySemanticTokensResponse; - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Semantic/SemanticTokensRangeRequest.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Semantic/SemanticTokensRangeRequest.ts deleted file mode 100644 index 905e8b22b5c..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Semantic/SemanticTokensRangeRequest.ts +++ /dev/null @@ -1,21 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { TextDocumentIdentifier } from 'vscode-languageclient'; -import { convertRangeToSerializable, SerializableRange } from '../RPC/SerializableRange'; - -export class SemanticTokensRangeRequest { - public readonly range: SerializableRange; - public readonly textDocument: TextDocumentIdentifier; - - constructor( - razorDocumentUri: vscode.Uri, - range: vscode.Range, - ) { - this.textDocument = TextDocumentIdentifier.create(razorDocumentUri.toString()); - this.range = convertRangeToSerializable(range); - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Semantic/SemanticTokensResponse.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Semantic/SemanticTokensResponse.ts deleted file mode 100644 index 89e11498334..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Semantic/SemanticTokensResponse.ts +++ /dev/null @@ -1,11 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -export class SemanticTokensResponse { - constructor( - public readonly data: Array, - public readonly resultId?: string) { - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Semantic/SerializableSemanticTokensParams.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Semantic/SerializableSemanticTokensParams.ts deleted file mode 100644 index a1e0883db6f..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Semantic/SerializableSemanticTokensParams.ts +++ /dev/null @@ -1,12 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -import { SerializableRange } from '../RPC/SerializableRange'; -import { SerializableTextDocumentIdentifier } from '../RPC/SerializableTextDocumentIdentifier'; - -export interface SerializableSemanticTokensParams { - textDocument: SerializableTextDocumentIdentifier; - range: SerializableRange; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/SignatureHelp/RazorSignatureHelpProvider.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/SignatureHelp/RazorSignatureHelpProvider.ts deleted file mode 100644 index fcb0d7da516..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/SignatureHelp/RazorSignatureHelpProvider.ts +++ /dev/null @@ -1,26 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 { RazorLanguageFeatureBase } from './../RazorLanguageFeatureBase'; - -export class RazorSignatureHelpProvider - extends RazorLanguageFeatureBase - implements vscode.SignatureHelpProvider { - - public async provideSignatureHelp( - document: vscode.TextDocument, position: vscode.Position, - token: vscode.CancellationToken) { - - const projection = await this.getProjection(document, position, token); - if (projection) { - const result = await vscode.commands.executeCommand( - 'vscode.executeSignatureHelpProvider', - projection.uri, - projection.position); - return result; - } - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/TelemetryReporter.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/TelemetryReporter.ts deleted file mode 100644 index 7bf71e27fcb..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/TelemetryReporter.ts +++ /dev/null @@ -1,76 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -import { createTelemetryErrorEvent, createTelemetryEvent, HostEventStream } from './HostEventStream'; -import { Trace } from './Trace'; - -export class TelemetryReporter { - private readonly razorExtensionActivated = createTelemetryEvent('VSCode.Razor.RazorExtensionActivated'); - private readonly debugLanguageServerEvent = createTelemetryEvent('VSCode.Razor.DebugLanguageServer'); - private readonly workspaceContainsRazorEvent = createTelemetryEvent('VSCode.Razor.WorkspaceContainsRazor'); - private reportedWorkspaceContainsRazor = false; - - constructor( - private readonly eventStream: HostEventStream) { - // If this telemetry reporter is created it means the rest of the Razor extension world was created. - this.eventStream.post(this.razorExtensionActivated); - } - - public reportTraceLevel(trace: Trace) { - const traceLevelEvent = createTelemetryEvent( - 'VSCode.Razor.TraceLevel', - { - trace: Trace[trace], - }); - this.eventStream.post(traceLevelEvent); - } - - public reportErrorOnServerStart(error: unknown) { - let realError; - if (error instanceof Error) { - realError = error; - } else { - realError = Error(String(error)); - } - - this.reportError('VSCode.Razor.ErrorOnServerStart', realError); - } - - public reportErrorOnActivation(error: unknown) { - let realError; - if (error instanceof Error) { - realError = error; - } else { - realError = Error(String(error)); - } - - this.reportError('VSCode.Razor.ErrorOnActivation', realError); - } - - public reportDebugLanguageServer() { - this.eventStream.post(this.debugLanguageServerEvent); - } - - public reportWorkspaceContainsRazor() { - if (this.reportedWorkspaceContainsRazor) { - return; - } - - this.reportedWorkspaceContainsRazor = true; - this.eventStream.post(this.workspaceContainsRazorEvent); - } - - private reportError(eventName: string, error: Error) { - const errorOnActivationEvent = createTelemetryErrorEvent( - eventName, - { - error: JSON.stringify(error), - }, - /*measures*/ undefined, - /*errorProps*/['error']); - - this.eventStream.post(errorOnActivationEvent); - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Trace.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Trace.ts deleted file mode 100644 index 77ccc632454..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/Trace.ts +++ /dev/null @@ -1,10 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - -export enum Trace { - Off = 0, - Messages = 1, - Verbose = 2, -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/UriPaths.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/UriPaths.ts deleted file mode 100644 index 5bb269c53db..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/UriPaths.ts +++ /dev/null @@ -1,17 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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'; - -export function getUriPath(uri: vscode.Uri) { - let newUri = uri; - if (uri.authority && uri.scheme === 'file') { - // UNC path. The host(authority) part of this is case-insensitive. Let's normalize it so we don't create duplicate documents. - const authority = uri.authority.toLowerCase(); - newUri = uri.with({ authority }); - } - - return newUri.fsPath || newUri.path; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/extension.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/extension.ts deleted file mode 100644 index 657e043fcf0..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/extension.ts +++ /dev/null @@ -1,258 +0,0 @@ -/* -------------------------------------------------------------------------------------------- - * 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 * as vscodeapi from 'vscode'; -import { ExtensionContext } from 'vscode'; -import { BlazorDebugConfigurationProvider } from './BlazorDebug/BlazorDebugConfigurationProvider'; -import { RazorCodeActionRunner } from './CodeActions/RazorCodeActionRunner'; -import { RazorCodeLensProvider } from './CodeLens/RazorCodeLensProvider'; -import { ColorPresentationHandler } from './ColorPresentation/ColorPresentationHandler'; -import { ProvisionalCompletionOrchestrator } from './Completion/ProvisionalCompletionOrchestrator'; -import { RazorCompletionItemProvider } from './Completion/RazorCompletionItemProvider'; -import { listenToConfigurationChanges } from './ConfigurationChangeListener'; -import { RazorCSharpFeature } from './CSharp/RazorCSharpFeature'; -import { RazorDefinitionProvider } from './Definition/RazorDefinitionProvider'; -import { ReportIssueCommand } from './Diagnostics/ReportIssueCommand'; -import { RazorDocumentManager } from './Document/RazorDocumentManager'; -import { RazorDocumentSynchronizer } from './Document/RazorDocumentSynchronizer'; -import { DocumentColorHandler } from './DocumentColor/DocumentColorHandler'; -import { RazorDocumentHighlightProvider } from './DocumentHighlight/RazorDocumentHighlightProvider'; -import { reportTelemetryForDocuments } from './DocumentTelemetryListener'; -import { FoldingRangeHandler } from './Folding/FoldingRangeHandler'; -import { FormattingHandler } from './Formatting/FormattingHandler'; -import { HostEventStream } from './HostEventStream'; -import { RazorHoverProvider } from './Hover/RazorHoverProvider'; -import { RazorHtmlFeature } from './Html/RazorHtmlFeature'; -import { IEventEmitterFactory } from './IEventEmitterFactory'; -import { RazorImplementationProvider } from './Implementation/RazorImplementationProvider'; -import { ProposedApisFeature } from './ProposedApisFeature'; -import { RazorCSharpLanguageMiddleware } from './RazorCSharpLanguageMiddleware'; -import { RazorLanguage } from './RazorLanguage'; -import { RazorLanguageConfiguration } from './RazorLanguageConfiguration'; -import { RazorLanguageServerClient } from './RazorLanguageServerClient'; -import { resolveRazorLanguageServerTrace } from './RazorLanguageServerTraceResolver'; -import { RazorLanguageServiceClient } from './RazorLanguageServiceClient'; -import { RazorLogger } from './RazorLogger'; -import { RazorReferenceProvider } from './Reference/RazorReferenceProvider'; -import { RazorRenameProvider } from './Rename/RazorRenameProvider'; -import { RazorDocumentSemanticTokensProvider } from './Semantic/RazorDocumentSemanticTokensProvider'; -import { SemanticTokensRangeHandler } from './Semantic/SemanticTokensRangeHandler'; -import { RazorSignatureHelpProvider } from './SignatureHelp/RazorSignatureHelpProvider'; -import { TelemetryReporter } from './TelemetryReporter'; - -// We specifically need to take a reference to a particular instance of the vscode namespace, -// otherwise providers attempt to operate on the null extension. -export async function activate(vscodeType: typeof vscodeapi, context: ExtensionContext, languageServerDir: string, eventStream: HostEventStream, enableProposedApis = false) { - const telemetryReporter = new TelemetryReporter(eventStream); - const eventEmitterFactory: IEventEmitterFactory = { - create: () => new vscode.EventEmitter(), - }; - - const languageServerTrace = resolveRazorLanguageServerTrace(vscodeType); - const logger = new RazorLogger(vscodeType, eventEmitterFactory, languageServerTrace); - - try { - const languageServerClient = new RazorLanguageServerClient(vscodeType, languageServerDir, telemetryReporter, logger); - const languageServiceClient = new RazorLanguageServiceClient(languageServerClient); - - const razorLanguageMiddleware = new RazorCSharpLanguageMiddleware(languageServiceClient, logger); - - const documentManager = new RazorDocumentManager(languageServerClient, logger); - reportTelemetryForDocuments(documentManager, telemetryReporter); - const languageConfiguration = new RazorLanguageConfiguration(); - const csharpFeature = new RazorCSharpFeature(documentManager, eventEmitterFactory, logger); - const htmlFeature = new RazorHtmlFeature(documentManager, languageServiceClient, eventEmitterFactory, logger); - const localRegistrations: vscode.Disposable[] = []; - const reportIssueCommand = new ReportIssueCommand(vscodeType, documentManager, logger); - const razorCodeActionRunner = new RazorCodeActionRunner(languageServerClient, logger); - - let documentSynchronizer: RazorDocumentSynchronizer; - languageServerClient.onStart(async () => { - vscodeType.commands.executeCommand('omnisharp.registerLanguageMiddleware', razorLanguageMiddleware); - documentSynchronizer = new RazorDocumentSynchronizer(documentManager, logger); - const provisionalCompletionOrchestrator = new ProvisionalCompletionOrchestrator( - documentManager, - csharpFeature.projectionProvider, - languageServiceClient, - logger); - const semanticTokenHandler = new SemanticTokensRangeHandler(languageServerClient); - const colorPresentationHandler = new ColorPresentationHandler( - documentManager, - languageServerClient, - logger); - const documentColorHandler = new DocumentColorHandler( - documentManager, - languageServerClient, - logger); - const foldingRangeHandler = new FoldingRangeHandler( - languageServerClient, - documentManager, - logger); - const formattingHandler = new FormattingHandler( - documentManager, - documentSynchronizer, - languageServerClient, - logger); - - const completionItemProvider = new RazorCompletionItemProvider( - documentSynchronizer, - documentManager, - languageServiceClient, - provisionalCompletionOrchestrator, - logger); - const signatureHelpProvider = new RazorSignatureHelpProvider( - documentSynchronizer, - documentManager, - languageServiceClient, - logger); - const definitionProvider = new RazorDefinitionProvider( - documentSynchronizer, - documentManager, - languageServiceClient, - logger); - const implementationProvider = new RazorImplementationProvider( - documentSynchronizer, - documentManager, - languageServiceClient, - logger); - const hoverProvider = new RazorHoverProvider( - documentSynchronizer, - documentManager, - languageServiceClient, - logger); - const codeLensProvider = new RazorCodeLensProvider( - documentSynchronizer, - documentManager, - languageServiceClient, - logger); - const renameProvider = new RazorRenameProvider( - documentSynchronizer, - documentManager, - languageServiceClient, - logger); - const referenceProvider = new RazorReferenceProvider( - documentSynchronizer, - documentManager, - languageServiceClient, - logger); - const documentHighlightProvider = new RazorDocumentHighlightProvider( - documentSynchronizer, - documentManager, - languageServiceClient, - logger); - - localRegistrations.push( - languageConfiguration.register(), - provisionalCompletionOrchestrator.register(), - vscodeType.languages.registerCompletionItemProvider( - RazorLanguage.id, - completionItemProvider, - '.', '<', '@'), - vscodeType.languages.registerSignatureHelpProvider( - RazorLanguage.id, - signatureHelpProvider, - '(', ','), - vscodeType.languages.registerDefinitionProvider( - RazorLanguage.id, - definitionProvider), - vscodeType.languages.registerImplementationProvider( - RazorLanguage.id, - implementationProvider), - vscodeType.languages.registerHoverProvider( - RazorLanguage.documentSelector, - hoverProvider), - vscodeType.languages.registerReferenceProvider( - RazorLanguage.id, - referenceProvider), - vscodeType.languages.registerCodeLensProvider( - RazorLanguage.id, - codeLensProvider), - vscodeType.languages.registerRenameProvider( - RazorLanguage.id, - renameProvider), - vscodeType.languages.registerDocumentHighlightProvider( - RazorLanguage.id, - documentHighlightProvider), - documentManager.register(), - csharpFeature.register(), - htmlFeature.register(), - documentSynchronizer.register(), - reportIssueCommand.register(), - listenToConfigurationChanges(languageServerClient)); - - if (enableProposedApis) { - const proposedApisFeature = new ProposedApisFeature(); - - await proposedApisFeature.register(vscodeType, localRegistrations); - } - - razorCodeActionRunner.register(); - await colorPresentationHandler.register(); - await documentColorHandler.register(); - await foldingRangeHandler.register(); - await formattingHandler.register(); - await semanticTokenHandler.register(); - }); - - const onStopRegistration = languageServerClient.onStop(() => { - localRegistrations.forEach(r => r.dispose()); - localRegistrations.length = 0; - }); - - const provider = new BlazorDebugConfigurationProvider(logger, vscodeType); - context.subscriptions.push(vscodeType.debug.registerDebugConfigurationProvider('blazorwasm', provider)); - - languageServerClient.onStarted(async () => { - const legend = languageServerClient.initializeResult?.capabilities.semanticTokensProvider?.legend; - const semanticTokenProvider = new RazorDocumentSemanticTokensProvider( - documentSynchronizer, - documentManager, - languageServiceClient, - logger); - if (legend) { - localRegistrations.push(vscodeType.languages.registerDocumentRangeSemanticTokensProvider(RazorLanguage.id, semanticTokenProvider, legend)); - } - - await documentManager.initialize(); - }); - - await startLanguageServer(vscodeType, languageServerClient, logger, context); - - context.subscriptions.push(languageServerClient, onStopRegistration, logger); - } catch (error) { - logger.logError('Failed when activating Razor VSCode.', error as Error); - telemetryReporter.reportErrorOnActivation(error as Error); - } -} - -async function startLanguageServer( - vscodeType: typeof vscodeapi, - languageServerClient: RazorLanguageServerClient, - logger: RazorLogger, - context: vscode.ExtensionContext) { - - const razorFiles = await vscodeType.workspace.findFiles(RazorLanguage.globbingPattern); - if (razorFiles.length === 0) { - // No Razor files in workspace, language server should stay off until one is added or opened. - logger.logAlways('No Razor files detected in workspace, delaying language server start.'); - - const watcher = vscodeType.workspace.createFileSystemWatcher(RazorLanguage.globbingPattern); - const delayedLanguageServerStart = async () => { - razorFileCreatedRegistration.dispose(); - razorFileOpenedRegistration.dispose(); - await languageServerClient.start(); - }; - const razorFileCreatedRegistration = watcher.onDidCreate(() => delayedLanguageServerStart()); - const razorFileOpenedRegistration = vscodeType.workspace.onDidOpenTextDocument(async (event) => { - if (event.languageId === RazorLanguage.id) { - await delayedLanguageServerStart(); - } - }); - context.subscriptions.push(razorFileCreatedRegistration, razorFileOpenedRegistration); - } else { - await languageServerClient.start(); - } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/vscode.proposed.d.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/vscode.proposed.d.ts deleted file mode 100644 index 3780fc1a59b..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/vscode.proposed.d.ts +++ /dev/null @@ -1,21 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - -/** - * This is the place for API experiments and proposals. - * These API are NOT stable and subject to change. They are only available in the Insiders - * distribution and CANNOT be used in published extensions. - * - * To test these API in local environment: - * - Use Insiders release of VS Code. - * - Add `"enableProposedApi": true` to your package.json. - * - Copy this file to your project. - */ - -/* tslint:disable:max-classes-per-file */ -declare module 'vscode' { - -} -/* tslint:enable:max-classes-per-file */ diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/vscodeAdapter.ts b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/vscodeAdapter.ts deleted file mode 100644 index 8e30777c033..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/src/vscodeAdapter.ts +++ /dev/null @@ -1,1468 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -/* tslint:disable */ - -export type ProviderResult = T | undefined | null | Thenable; - -/** - * A text document content provider allows to add readonly documents - * to the editor, such as source from a dll or generated html from md. - * - * Content providers are [registered](#workspace.registerTextDocumentContentProvider) - * for a [uri-scheme](#Uri.scheme). When a uri with that scheme is to - * be [loaded](#workspace.openTextDocument) the content provider is - * asked. - */ -export interface TextDocumentContentProvider { - - /** - * An event to signal a resource has changed. - */ - onDidChange?: Event; - - /** - * Provide textual content for a given uri. - * - * The editor will use the returned string-content to create a readonly - * [document](#TextDocument). Resources allocated should be released when - * the corresponding document has been [closed](#workspace.onDidCloseTextDocument). - * - * **Note**: The contents of the created [document](#TextDocument) might not be - * identical to the provided text due to end-of-line-sequence normalization. - * - * @param uri An uri which scheme matches the scheme this provider was [registered](#workspace.registerTextDocumentContentProvider) for. - * @param token A cancellation token. - * @return A string or a thenable that resolves to such. - */ - provideTextDocumentContent(uri: Uri, token: CancellationToken): ProviderResult; -} - -/** - * Represents a typed event. - * - * A function that represents an event to which you subscribe by calling it with - * a listener function as argument. - * - * @sample `item.onDidChange(function(event) { console.log("Event happened: " + event); });` - */ -export interface Event { - - /** - * A function that represents an event to which you subscribe by calling it with - * a listener function as argument. - * - * @param listener The listener function will be called when the event happens. - * @param thisArgs The `this`-argument which will be used when calling the event listener. - * @param disposables An array to which a [disposable](#Disposable) will be added. - * @return A disposable which unsubscribes the event listener. - */ - (listener: (e: T) => any, thisArgs?: any, disposables?: Disposable[]): Disposable; -} - -/** - * An event emitter can be used to create and manage an [event](#Event) for others - * to subscribe to. One emitter always owns one event. - * - * Use this class if you want to provide event from within your extension, for instance - * inside a [TextDocumentContentProvider](#TextDocumentContentProvider) or when providing - * API to other extensions. - */ -export declare class EventEmitter { - /** - * The event listeners can subscribe to. - */ - event: Event; - - /** - * Notify all subscribers of the [event](EventEmitter#event). Failure - * of one or more listener will not fail this function call. - * - * @param data The event object. - */ - fire(data: T): void; - - /** - * Dispose this object and free resources. - */ - dispose(): void; -} - -export interface OutputChannel { - - /** - * The human-readable name of this output channel. - */ - readonly name: string; - - /** - * Append the given value to the channel. - * - * @param value A string, falsy values will not be printed. - */ - append(value: string): void; - - /** - * Append the given value and a line feed character - * to the channel. - * - * @param value A string, falsy values will be printed. - */ - appendLine(value: string): void; - - /** - * Removes all output from the channel. - */ - clear(): void; - - /** - * Reveal this channel in the UI. - * - * @param preserveFocus When `true` the channel will not take focus. - */ - show(preserveFocus?: boolean): void; - - /** - * Hide this channel from the UI. - */ - hide(): void; - - /** - * Dispose and free associated resources. - */ - dispose(): void; -} - -export enum ViewColumn { - /** - * A *symbolic* editor column representing the currently - * active column. This value can be used when opening editors, but the - * *resolved* [viewColumn](#TextEditor.viewColumn)-value of editors will always - * be `One`, `Two`, `Three`, or `undefined` but never `Active`. - */ - Active = -1, - /** - * The left most editor column. - */ - One = 1, - /** - * The center editor column. - */ - Two = 2, - /** - * The right most editor column. - */ - Three = 3 -} - -export interface WorkspaceConfiguration { - - /** - * Return a value from this configuration. - * - * @param section Configuration name, supports _dotted_ names. - * @return The value `section` denotes or `undefined`. - */ - get(section: string): T | undefined; - - /** - * Return a value from this configuration. - * - * @param section Configuration name, supports _dotted_ names. - * @param defaultValue A value should be returned when no value could be found, is `undefined`. - * @return The value `section` denotes or the default. - */ - get(section: string, defaultValue: T): T; - - /** - * Check if this configuration has a certain value. - * - * @param section Configuration name, supports _dotted_ names. - * @return `true` if the section doesn't resolve to `undefined`. - */ - has(section: string): boolean; - - /** - * Retrieve all information about a configuration setting. A configuration value - * often consists of a *default* value, a global or installation-wide value, - * a workspace-specific value and a folder-specific value. - * - * The *effective* value (returned by [`get`](#WorkspaceConfiguration.get)) - * is computed like this: `defaultValue` overwritten by `globalValue`, - * `globalValue` overwritten by `workspaceValue`. `workspaceValue` overwritten by `workspaceFolderValue`. - * Refer to [Settings Inheritance](https://code.visualstudio.com/docs/getstarted/settings) - * for more information. - * - * *Note:* The configuration name must denote a leaf in the configuration tree - * (`editor.fontSize` vs `editor`) otherwise no result is returned. - * - * @param section Configuration name, supports _dotted_ names. - * @return Information about a configuration setting or `undefined`. - */ - inspect(section: string): { key: string; defaultValue?: T; globalValue?: T; workspaceValue?: T, workspaceFolderValue?: T } | undefined; - - /** - * Update a configuration value. The updated configuration values are persisted. - * - * A value can be changed in - * - * - [Global configuration](#ConfigurationTarget.Global): Changes the value for all instances of the editor. - * - [Workspace configuration](#ConfigurationTarget.Workspace): Changes the value for current workspace, if available. - * - [Workspace folder configuration](#ConfigurationTarget.WorkspaceFolder): Changes the value for the - * [Workspace folder](#workspace.workspaceFolders) to which the current [configuration](#WorkspaceConfiguration) is scoped to. - * - * *Note 1:* Setting a global value in the presence of a more specific workspace value - * has no observable effect in that workspace, but in others. Setting a workspace value - * in the presence of a more specific folder value has no observable effect for the resources - * under respective [folder](#workspace.workspaceFolders), but in others. Refer to - * [Settings Inheritance](https://code.visualstudio.com/docs/getstarted/settings) for more information. - * - * *Note 2:* To remove a configuration value use `undefined`, like so: `config.update('somekey', undefined)` - * - * Will throw error when - * - Writing a configuration which is not registered. - * - Writing a configuration to workspace or folder target when no workspace is opened - * - Writing a configuration to folder target when there is no folder settings - * - Writing to folder target without passing a resource when getting the configuration (`workspace.getConfiguration(section, resource)`) - * - Writing a window configuration to folder target - * - * @param section Configuration name, supports _dotted_ names. - * @param value The new value. - * @param configurationTarget The [configuration target](#ConfigurationTarget) or a boolean value. - * - If `true` configuration target is `ConfigurationTarget.Global`. - * - If `false` configuration target is `ConfigurationTarget.Workspace`. - * - If `undefined` or `null` configuration target is - * `ConfigurationTarget.WorkspaceFolder` when configuration is resource specific - * `ConfigurationTarget.Workspace` otherwise. - */ - update(section: string, value: any, configurationTarget?: ConfigurationTarget | boolean): Thenable; - - /** - * Readable dictionary that backs this configuration. - */ - readonly [key: string]: any; -} - -/** - * The configuration target - */ -export enum ConfigurationTarget { - /** - * Global configuration - */ - Global = 1, - - /** - * Workspace configuration - */ - Workspace = 2, - - /** - * Workspace folder configuration - */ - WorkspaceFolder = 3 -} - -/** - * Represents the alignment of status bar items. - */ -export enum StatusBarAlignment { - - /** - * Aligned to the left side. - */ - Left = 1, - - /** - * Aligned to the right side. - */ - Right = 2 -} - - -export interface StatusBarItem { - - /** - * The alignment of this item. - */ - readonly alignment: StatusBarAlignment; - - /** - * The priority of this item. Higher value means the item should - * be shown more to the left. - */ - readonly priority: number; - - /** - * The text to show for the entry. You can embed icons in the text by leveraging the syntax: - * - * `My text $(icon-name) contains icons like $(icon'name) this one.` - * - * Where the icon-name is taken from the [octicon](https://octicons.github.com) icon set, e.g. - * `light-bulb`, `thumbsup`, `zap` etc. - */ - text: string; - - /** - * The tooltip text when you hover over this entry. - */ - tooltip: string | undefined; - - /** - * The foreground color for this entry. - */ - color: string | undefined; - - /** - * The identifier of a command to run on click. The command must be - * [known](#commands.getCommands). - */ - command: string | undefined; - - /** - * Shows the entry in the status bar. - */ - show(): void; - - /** - * Hide the entry in the status bar. - */ - hide(): void; - - /** - * Dispose and free associated resources. Call - * [hide](#StatusBarItem.hide). - */ - dispose(): void; -} - -export interface Event { - /** - * A function that represents an event to which you subscribe by calling it with - * a listener function as argument. - * - * @param listener The listener function will be called when the event happens. - * @param thisArgs The `this`-argument which will be used when calling the event listener. - * @param disposables An array to which a [disposable](#Disposable) will be added. - * @return A disposable which unsubscribes the event listener. - */ - (listener: (e: T) => any, thisArgs?: any, disposables?: Disposable[]): Disposable; -} - -export interface Disposable { - /** - * Dispose this object. - */ - dispose(): any; -} - - -export interface CancellationToken { - - /** - * Is `true` when the token has been cancelled, `false` otherwise. - */ - isCancellationRequested: boolean; - - /** - * An [event](#Event) which fires upon cancellation. - */ - onCancellationRequested: Event; -} - - -export interface DocumentFilter { - - /** - * A language id, like `typescript`. - */ - language?: string; - - /** - * A Uri [scheme](#Uri.scheme), like `file` or `untitled`. - */ - scheme?: string; - - /** - * A [glob pattern](#GlobPattern) that is matched on the absolute path of the document. Use a [relative pattern](#RelativePattern) - * to filter documents to a [workspace folder](#WorkspaceFolder). - */ - pattern?: GlobPattern; -} - -export type GlobPattern = string; - -export type DocumentSelector = string | DocumentFilter | (string | DocumentFilter)[]; - -export interface MessageOptions { - - /** - * Indicates that this message should be modal. - */ - modal?: boolean; -} - -export interface TextEditor { - - /** - * The document associated with this text editor. The document will be the same for the entire lifetime of this text editor. - */ - document: TextDocument; -} - -/** - * A universal resource identifier representing either a file on disk - * or another resource, like untitled resources. - */ -export interface Uri { - - /** - * Create an URI from a file system path. The [scheme](#Uri.scheme) - * will be `file`. - * - * @param path A file system or UNC path. - * @return A new Uri instance. - */ - - /** - * Create an URI from a string. Will throw if the given value is not - * valid. - * - * @param value The string value of an Uri. - * @return A new Uri instance. - */ - /** - * Scheme is the `http` part of `http://www.msft.com/some/path?query#fragment`. - * The part before the first colon. - */ - readonly scheme: string; - - /** - * Authority is the `www.msft.com` part of `http://www.msft.com/some/path?query#fragment`. - * The part between the first double slashes and the next slash. - */ - readonly authority: string; - - /** - * Path is the `/some/path` part of `http://www.msft.com/some/path?query#fragment`. - */ - readonly path: string; - - /** - * Query is the `query` part of `http://www.msft.com/some/path?query#fragment`. - */ - readonly query: string; - - /** - * Fragment is the `fragment` part of `http://www.msft.com/some/path?query#fragment`. - */ - readonly fragment: string; - - /** - * The string representing the corresponding file system path of this Uri. - * - * Will handle UNC paths and normalize windows drive letters to lower-case. Also - * uses the platform specific path separator. Will *not* validate the path for - * invalid characters and semantics. Will *not* look at the scheme of this Uri. - */ - readonly fsPath: string; - - /** - * Derive a new Uri from this Uri. - * - * ```ts - * let file = Uri.parse('before:some/file/path'); - * let other = file.with({ scheme: 'after' }); - * assert.ok(other.toString() === 'after:some/file/path'); - * ``` - * - * @param change An object that describes a change to this Uri. To unset components use `null` or - * the empty string. - * @return A new Uri that reflects the given change. Will return `this` Uri if the change - * is not changing anything. - */ - with(change: { scheme?: string; authority?: string; path?: string; query?: string; fragment?: string }): Uri; - - /** - * Returns a string representation of this Uri. The representation and normalization - * of a URI depends on the scheme. The resulting string can be safely used with - * [Uri.parse](#Uri.parse). - * - * @param skipEncoding Do not percentage-encode the result, defaults to `false`. Note that - * the `#` and `?` characters occurring in the path will always be encoded. - * @returns A string representation of this Uri. - */ - toString(skipEncoding?: boolean): string; - - /** - * Returns a JSON representation of this Uri. - * - * @return An object. - */ - toJSON(): any; -} - -export interface MessageItem { - - /** - * A short title like 'Retry', 'Open Log' etc. - */ - title: string; - - /** - * Indicates that this item replaces the default - * 'Close' action. - */ - isCloseAffordance?: boolean; -} - -/** - * Represents a text document, such as a source file. Text documents have - * [lines](#TextLine) and knowledge about an underlying resource like a file. - */ -export interface TextDocument { - - /** - * The associated URI for this document. Most documents have the __file__-scheme, indicating that they - * represent files on disk. However, some documents may have other schemes indicating that they are not - * available on disk. - */ - readonly uri: Uri; - - /** - * The file system path of the associated resource. Shorthand - * notation for [TextDocument.uri.fsPath](#TextDocument.uri). Independent of the uri scheme. - */ - readonly fileName: string; - - /** - * Is this document representing an untitled file. - */ - readonly isUntitled: boolean; - - /** - * The identifier of the language associated with this document. - */ - readonly languageId: string; - - /** - * The version number of this document (it will strictly increase after each - * change, including undo/redo). - */ - readonly version: number; - - /** - * `true` if there are unpersisted changes. - */ - readonly isDirty: boolean; - - /** - * `true` if the document have been closed. A closed document isn't synchronized anymore - * and won't be re-used when the same resource is opened again. - */ - readonly isClosed: boolean; - - /** - * Save the underlying file. - * - * @return A promise that will resolve to true when the file - * has been saved. If the file was not dirty or the save failed, - * will return false. - */ - save(): Thenable; - - /** - * The [end of line](#EndOfLine) sequence that is predominately - * used in this document. - */ - readonly eol: EndOfLine; - - /** - * The number of lines in this document. - */ - readonly lineCount: number; - - /** - * Returns a text line denoted by the line number. Note - * that the returned object is *not* live and changes to the - * document are not reflected. - * - * @param line A line number in [0, lineCount). - * @return A [line](#TextLine). - */ - lineAt(line: number): TextLine; - - /** - * Returns a text line denoted by the position. Note - * that the returned object is *not* live and changes to the - * document are not reflected. - * - * The position will be [adjusted](#TextDocument.validatePosition). - * - * @see [TextDocument.lineAt](#TextDocument.lineAt) - * @param position A position. - * @return A [line](#TextLine). - */ - lineAt(position: Position): TextLine; - - /** - * Converts the position to a zero-based offset. - * - * The position will be [adjusted](#TextDocument.validatePosition). - * - * @param position A position. - * @return A valid zero-based offset. - */ - offsetAt(position: Position): number; - - /** - * Converts a zero-based offset to a position. - * - * @param offset A zero-based offset. - * @return A valid [position](#Position). - */ - positionAt(offset: number): Position; - - /** - * Get the text of this document. A substring can be retrieved by providing - * a range. The range will be [adjusted](#TextDocument.validateRange). - * - * @param range Include only the text included by the range. - * @return The text inside the provided range or the entire text. - */ - getText(range?: Range): string; - - /** - * Get a word-range at the given position. By default words are defined by - * common separators, like space, -, _, etc. In addition, per language custom - * [word definitions](#LanguageConfiguration.wordPattern) can be defined. It - * is also possible to provide a custom regular expression. - * - * * *Note 1:* A custom regular expression must not match the empty string and - * if it does, it will be ignored. - * * *Note 2:* A custom regular expression will fail to match multiline strings - * and in the name of speed regular expressions should not match words with - * spaces. Use [`TextLine.text`](#TextLine.text) for more complex, non-wordy, scenarios. - * - * The position will be [adjusted](#TextDocument.validatePosition). - * - * @param position A position. - * @param regex Optional regular expression that describes what a word is. - * @return A range spanning a word, or `undefined`. - */ - getWordRangeAtPosition(position: Position, regex?: RegExp): Range | undefined; - - /** - * Ensure a range is completely contained in this document. - * - * @param range A range. - * @return The given range or a new, adjusted range. - */ - validateRange(range: Range): Range; - - /** - * Ensure a position is contained in the range of this document. - * - * @param position A position. - * @return The given position or a new, adjusted position. - */ - validatePosition(position: Position): Position; -} - -/** - * Represents an end of line character sequence in a [document](#TextDocument). - */ -export enum EndOfLine { - /** - * The line feed `\n` character. - */ - LF = 1, - /** - * The carriage return line feed `\r\n` sequence. - */ - CRLF = 2 -} - -/** - * Represents a line and character position, such as - * the position of the cursor. - * - * Position objects are __immutable__. Use the [with](#Position.with) or - * [translate](#Position.translate) methods to derive new positions - * from an existing position. - */ -export interface Position { - - /** - * The zero-based line value. - */ - readonly line: number; - - /** - * The zero-based character value. - */ - readonly character: number; - - /** - * @param line A zero-based line value. - * @param character A zero-based character value. - */ - - /** - * Check if `other` is before this position. - * - * @param other A position. - * @return `true` if position is on a smaller line - * or on the same line on a smaller character. - */ - isBefore(other: Position): boolean; - - /** - * Check if `other` is before or equal to this position. - * - * @param other A position. - * @return `true` if position is on a smaller line - * or on the same line on a smaller or equal character. - */ - isBeforeOrEqual(other: Position): boolean; - - /** - * Check if `other` is after this position. - * - * @param other A position. - * @return `true` if position is on a greater line - * or on the same line on a greater character. - */ - isAfter(other: Position): boolean; - - /** - * Check if `other` is after or equal to this position. - * - * @param other A position. - * @return `true` if position is on a greater line - * or on the same line on a greater or equal character. - */ - isAfterOrEqual(other: Position): boolean; - - /** - * Check if `other` equals this position. - * - * @param other A position. - * @return `true` if the line and character of the given position are equal to - * the line and character of this position. - */ - isEqual(other: Position): boolean; - - /** - * Compare this to `other`. - * - * @param other A position. - * @return A number smaller than zero if this position is before the given position, - * a number greater than zero if this position is after the given position, or zero when - * this and the given position are equal. - */ - compareTo(other: Position): number; - - /** - * Create a new position relative to this position. - * - * @param lineDelta Delta value for the line value, default is `0`. - * @param characterDelta Delta value for the character value, default is `0`. - * @return A position which line and character is the sum of the current line and - * character and the corresponding deltas. - */ - translate(lineDelta?: number, characterDelta?: number): Position; - - /** - * Derived a new position relative to this position. - * - * @param change An object that describes a delta to this position. - * @return A position that reflects the given delta. Will return `this` position if the change - * is not changing anything. - */ - translate(change: { lineDelta?: number; characterDelta?: number; }): Position; - - /** - * Create a new position derived from this position. - * - * @param line Value that should be used as line value, default is the [existing value](#Position.line) - * @param character Value that should be used as character value, default is the [existing value](#Position.character) - * @return A position where line and character are replaced by the given values. - */ - with(line?: number, character?: number): Position; - - /** - * Derived a new position from this position. - * - * @param change An object that describes a change to this position. - * @return A position that reflects the given change. Will return `this` position if the change - * is not changing anything. - */ - with(change: { line?: number; character?: number; }): Position; -} - -export interface Range { - - /** - * The start position. It is before or equal to [end](#Range.end). - */ - readonly start: Position; - - /** - * The end position. It is after or equal to [start](#Range.start). - */ - readonly end: Position; - - /** - * `true` if `start` and `end` are equal. - */ - isEmpty: boolean; - - /** - * `true` if `start.line` and `end.line` are equal. - */ - isSingleLine: boolean; - - /** - * Check if a position or a range is contained in this range. - * - * @param positionOrRange A position or a range. - * @return `true` if the position or range is inside or equal - * to this range. - */ - contains(positionOrRange: Position | Range): boolean; - - /** - * Check if `other` equals this range. - * - * @param other A range. - * @return `true` when start and end are [equal](#Position.isEqual) to - * start and end of this range. - */ - isEqual(other: Range): boolean; - - /** - * Intersect `range` with this range and returns a new range or `undefined` - * if the ranges have no overlap. - * - * @param range A range. - * @return A range of the greater start and smaller end positions. Will - * return undefined when there is no overlap. - */ - intersection(range: Range): Range | undefined; - - /** - * Compute the union of `other` with this range. - * - * @param other A range. - * @return A range of smaller start position and the greater end position. - */ - union(other: Range): Range; - - /** - * Derived a new range from this range. - * - * @param start A position that should be used as start. The default value is the [current start](#Range.start). - * @param end A position that should be used as end. The default value is the [current end](#Range.end). - * @return A range derived from this range with the given start and end position. - * If start and end are not different `this` range will be returned. - */ - with(start?: Position, end?: Position): Range; - - /** - * Derived a new range from this range. - * - * @param change An object that describes a change to this range. - * @return A range that reflects the given change. Will return `this` range if the change - * is not changing anything. - */ - with(change: { start?: Position, end?: Position }): Range; -} - -/** - * Represents a line of text, such as a line of source code. - * - * TextLine objects are __immutable__. When a [document](#TextDocument) changes, - * previously retrieved lines will not represent the latest state. - */ -export interface TextLine { - - /** - * The zero-based line number. - */ - readonly lineNumber: number; - - /** - * The text of this line without the line separator characters. - */ - readonly text: string; - - /** - * The range this line covers without the line separator characters. - */ - readonly range: Range; - - /** - * The range this line covers with the line separator characters. - */ - readonly rangeIncludingLineBreak: Range; - - /** - * The offset of the first character which is not a whitespace character as defined - * by `/\s/`. **Note** that if a line is all whitespace the length of the line is returned. - */ - readonly firstNonWhitespaceCharacterIndex: number; - - /** - * Whether this line is whitespace only, shorthand - * for [TextLine.firstNonWhitespaceCharacterIndex](#TextLine.firstNonWhitespaceCharacterIndex) === [TextLine.text.length](#TextLine.text). - */ - readonly isEmptyOrWhitespace: boolean; -} - -export interface FileSystemWatcher extends Disposable { - - /** - * true if this file system watcher has been created such that - * it ignores creation file system events. - */ - ignoreCreateEvents: boolean; - - /** - * true if this file system watcher has been created such that - * it ignores change file system events. - */ - ignoreChangeEvents: boolean; - - /** - * true if this file system watcher has been created such that - * it ignores delete file system events. - */ - ignoreDeleteEvents: boolean; - - /** - * An event which fires on file/folder creation. - */ - onDidCreate: Event; - - /** - * An event which fires on file/folder change. - */ - onDidChange: Event; - - /** - * An event which fires on file/folder deletion. - */ - onDidDelete: Event; -} - -export interface ConfigurationChangeEvent { - - /** - * Returns `true` if the given section for the given resource (if provided) is affected. - * - * @param section Configuration name, supports _dotted_ names. - * @param resource A resource Uri. - * @return `true` if the given section for the given resource (if provided) is affected. - */ - affectsConfiguration(section: string, resource?: Uri): boolean; -} - -export interface WebviewPanelSerializer { - /** - * Restore a webview panel from its serialized `state`. - * - * Called when a serialized webview first becomes visible. - * - * @param webviewPanel Webview panel to restore. The serializer should take ownership of this panel. The - * serializer must restore the webview's `.html` and hook up all webview events. - * @param state Persisted state from the webview content. - * - * @return Thenable indicating that the webview has been fully restored. - */ - deserializeWebviewPanel(webviewPanel: WebviewPanel, state: any): Thenable; -} - -/** - * Content settings for a webview panel. - */ -export interface WebviewPanelOptions { - /** - * Controls if the find widget is enabled in the panel. - * - * Defaults to false. - */ - readonly enableFindWidget?: boolean; - - /** - * Controls if the webview panel's content (iframe) is kept around even when the panel - * is no longer visible. - * - * Normally the webview panel's html context is created when the panel becomes visible - * and destroyed when it is is hidden. Extensions that have complex state - * or UI can set the `retainContextWhenHidden` to make VS Code keep the webview - * context around, even when the webview moves to a background tab. When a webview using - * `retainContextWhenHidden` becomes hidden, its scripts and other dynamic content are suspended. - * When the panel becomes visible again, the context is automatically restored - * in the exact same state it was in originally. You cannot send messages to a - * hidden webview, even with `retainContextWhenHidden` enabled. - * - * `retainContextWhenHidden` has a high memory overhead and should only be used if - * your panel's context cannot be quickly saved and restored. - */ - readonly retainContextWhenHidden?: boolean; -} - -/** - * A panel that contains a webview. - */ -export interface WebviewPanel { - /** - * Identifies the type of the webview panel, such as `'markdown.preview'`. - */ - readonly viewType: string; - - /** - * Title of the panel shown in UI. - */ - title: string; - - /** - * Webview belonging to the panel. - */ - readonly webview: Webview; - - /** - * Content settings for the webview panel. - */ - readonly options: WebviewPanelOptions; - - /** - * Editor position of the panel. This property is only set if the webview is in - * one of the editor view columns. - * - * @deprecated - */ - readonly viewColumn: ViewColumn; - - /** - * Whether the panel is active (focused by the user). - */ - readonly active: boolean; - - /** - * Whether the panel is visible. - */ - readonly visible: boolean; - - /** - * Fired when the panel's view state changes. - */ - readonly onDidChangeViewState: Event; - - /** - * Fired when the panel is disposed. - * - * This may be because the user closed the panel or because `.dispose()` was - * called on it. - * - * Trying to use the panel after it has been disposed throws an exception. - */ - readonly onDidDispose: Event; - - /** - * Show the webview panel in a given column. - * - * A webview panel may only show in a single column at a time. If it is already showing, this - * method moves it to a new column. - * - * @param viewColumn View column to show the panel in. Shows in the current `viewColumn` if undefined. - * @param preserveFocus When `true`, the webview will not take focus. - */ - reveal(viewColumn?: ViewColumn, preserveFocus?: boolean): void; - - /** - * Dispose of the webview panel. - * - * This closes the panel if it showing and disposes of the resources owned by the webview. - * Webview panels are also disposed when the user closes the webview panel. Both cases - * fire the `onDispose` event. - */ - dispose(): any; -} - -/** - * Event fired when a webview panel's view state changes. - */ -export interface WebviewPanelOnDidChangeViewStateEvent { - /** - * Webview panel whose view state changed. - */ - readonly webviewPanel: WebviewPanel; -} - -/** - * A webview displays html content, like an iframe. - */ -export interface Webview { - /** - * Content settings for the webview. - */ - options: WebviewOptions; - - /** - * Contents of the webview. - * - * Should be a complete html document. - */ - html: string; - - /** - * Fired when the webview content posts a message. - */ - readonly onDidReceiveMessage: Event; - - /** - * Post a message to the webview content. - * - * Messages are only delivered if the webview is visible. - * - * @param message Body of the message. - */ - postMessage(message: any): Thenable; - - /** - * Convert a uri for the local file system to one that can be used inside webviews. - * - * Webviews cannot directly load resources from the workspace or local file system using `file:` uris. The - * `asWebviewUri` function takes a local `file:` uri and converts it into a uri that can be used inside of - * a webview to load the same resource: - * - * ```ts - * webview.html = `` - * ``` - */ - asWebviewUri(localResource: Uri): Uri; - - /** - * Content security policy source for webview resources. - * - * This is the origin that should be used in a content security policy rule: - * - * ``` - * img-src https: ${webview.cspSource} ...; - * ``` - */ - readonly cspSource: string; -} - -/** - * Content settings for a webview. - */ -export interface WebviewOptions { - /** - * Controls whether scripts are enabled in the webview content or not. - * - * Defaults to false (scripts-disabled). - */ - readonly enableScripts?: boolean; - - /** - * Controls whether command uris are enabled in webview content or not. - * - * Defaults to false. - */ - readonly enableCommandUris?: boolean; - - /** - * Root paths from which the webview can load local (filesystem) resources using the `vscode-resource:` scheme. - * - * Default to the root folders of the current workspace plus the extension's install directory. - * - * Pass in an empty array to disallow access to any local resources. - */ - readonly localResourceRoots?: ReadonlyArray; -} - -/** - * Thenable is a common denominator between ES6 promises, Q, jquery.Deferred, WinJS.Promise, - * and others. This API makes no assumption about what promise library is being used which - * enables reusing existing code without migrating to a specific promise implementation. Still, - * we recommend the use of native promises which are available in this editor. - */ -export interface Thenable { - /** - * Attaches callbacks for the resolution and/or rejection of the Promise. - * @param onfulfilled The callback to execute when the Promise is resolved. - * @param onrejected The callback to execute when the Promise is rejected. - * @returns A Promise for the completion of which ever callback is executed. - */ - then(onfulfilled?: (value: T) => TResult | Thenable, onrejected?: (reason: any) => TResult | Thenable): Thenable; - then(onfulfilled?: (value: T) => TResult | Thenable, onrejected?: (reason: any) => void): Thenable; -} - -export interface Extension { - readonly id: string; - readonly packageJSON: any; -} - -/** - * Represents semantic tokens, either in a range or in an entire document. - * @see [provideDocumentSemanticTokens](#DocumentSemanticTokensProvider.provideDocumentSemanticTokens) for an explanation of the format. - * @see [SemanticTokensBuilder](#SemanticTokensBuilder) for a helper to create an instance. - */ -export class SemanticTokens { - /** - * The result id of the tokens. - * - * This is the id that will be passed to `DocumentSemanticTokensProvider.provideDocumentSemanticTokensEdits` (if implemented). - */ - readonly resultId?: string; - /** - * The actual tokens data. - * @see [provideDocumentSemanticTokens](#DocumentSemanticTokensProvider.provideDocumentSemanticTokens) for an explanation of the format. - */ - readonly data: Uint32Array; - - constructor(data: Uint32Array, resultId?: string) { - this.data = data; - this.resultId = resultId; - } -} - -/** - * Represents edits to semantic tokens. - * @see [provideDocumentSemanticTokensEdits](#DocumentSemanticTokensProvider.provideDocumentSemanticTokensEdits) for an explanation of the format. - */ -export class SemanticTokensEdits { - /** - * The result id of the tokens. - * - * This is the id that will be passed to `DocumentSemanticTokensProvider.provideDocumentSemanticTokensEdits` (if implemented). - */ - readonly resultId?: string; - /** - * The edits to the tokens data. - * All edits refer to the initial data state. - */ - readonly edits: SemanticTokensEdit[]; - - constructor(edits: SemanticTokensEdit[], resultId?: string) { - this.edits = edits; - this.resultId = resultId; - } -} - -/** - * Represents an edit to semantic tokens. - * @see [provideDocumentSemanticTokensEdits](#DocumentSemanticTokensProvider.provideDocumentSemanticTokensEdits) for an explanation of the format. - */ -export class SemanticTokensEdit { - /** - * The start offset of the edit. - */ - readonly start: number; - /** - * The count of elements to remove. - */ - readonly deleteCount: number; - /** - * The elements to insert. - */ - readonly data?: Uint32Array; - - constructor(start: number, deleteCount: number, data?: Uint32Array) { - this.start = start; - this.deleteCount = deleteCount; - this.data = data; - } -} - -export interface SemanticTokensLegend { - readonly tokenTypes: string[]; - readonly tokenModifiers: string[]; -} - -/** - * The document semantic tokens provider interface defines the contract between extensions and - * semantic tokens. - */ -export interface DocumentSemanticTokensProvider { - /** - * An optional event to signal that the semantic tokens from this provider have changed. - */ - onDidChangeSemanticTokens?: Event; - - /** - * Tokens in a file are represented as an array of integers. The position of each token is expressed relative to - * the token before it, because most tokens remain stable relative to each other when edits are made in a file. - * - * --- - * In short, each token takes 5 integers to represent, so a specific token `i` in the file consists of the following array indices: - * - at index `5*i` - `deltaLine`: token line number, relative to the previous token - * - at index `5*i+1` - `deltaStart`: token start character, relative to the previous token (relative to 0 or the previous token's start if they are on the same line) - * - at index `5*i+2` - `length`: the length of the token. A token cannot be multiline. - * - at index `5*i+3` - `tokenType`: will be looked up in `SemanticTokensLegend.tokenTypes`. We currently ask that `tokenType` < 65536. - * - at index `5*i+4` - `tokenModifiers`: each set bit will be looked up in `SemanticTokensLegend.tokenModifiers` - * - * --- - * ### How to encode tokens - * - * Here is an example for encoding a file with 3 tokens in a uint32 array: - * ``` - * { line: 2, startChar: 5, length: 3, tokenType: "property", tokenModifiers: ["private", "static"] }, - * { line: 2, startChar: 10, length: 4, tokenType: "type", tokenModifiers: [] }, - * { line: 5, startChar: 2, length: 7, tokenType: "class", tokenModifiers: [] } - * ``` - * - * 1. First of all, a legend must be devised. This legend must be provided up-front and capture all possible token types. - * For this example, we will choose the following legend which must be passed in when registering the provider: - * ``` - * tokenTypes: ['property', 'type', 'class'], - * tokenModifiers: ['private', 'static'] - * ``` - * - * 2. The first transformation step is to encode `tokenType` and `tokenModifiers` as integers using the legend. Token types are looked - * up by index, so a `tokenType` value of `1` means `tokenTypes[1]`. Multiple token modifiers can be set by using bit flags, - * so a `tokenModifier` value of `3` is first viewed as binary `0b00000011`, which means `[tokenModifiers[0], tokenModifiers[1]]` because - * bits 0 and 1 are set. Using this legend, the tokens now are: - * ``` - * { line: 2, startChar: 5, length: 3, tokenType: 0, tokenModifiers: 3 }, - * { line: 2, startChar: 10, length: 4, tokenType: 1, tokenModifiers: 0 }, - * { line: 5, startChar: 2, length: 7, tokenType: 2, tokenModifiers: 0 } - * ``` - * - * 3. The next step is to represent each token relative to the previous token in the file. In this case, the second token - * is on the same line as the first token, so the `startChar` of the second token is made relative to the `startChar` - * of the first token, so it will be `10 - 5`. The third token is on a different line than the second token, so the - * `startChar` of the third token will not be altered: - * ``` - * { deltaLine: 2, deltaStartChar: 5, length: 3, tokenType: 0, tokenModifiers: 3 }, - * { deltaLine: 0, deltaStartChar: 5, length: 4, tokenType: 1, tokenModifiers: 0 }, - * { deltaLine: 3, deltaStartChar: 2, length: 7, tokenType: 2, tokenModifiers: 0 } - * ``` - * - * 4. Finally, the last step is to inline each of the 5 fields for a token in a single array, which is a memory friendly representation: - * ``` - * // 1st token, 2nd token, 3rd token - * [ 2,5,3,0,3, 0,5,4,1,0, 3,2,7,2,0 ] - * ``` - * - * @see [SemanticTokensBuilder](#SemanticTokensBuilder) for a helper to encode tokens as integers. - * *NOTE*: When doing edits, it is possible that multiple edits occur until VS Code decides to invoke the semantic tokens provider. - * *NOTE*: If the provider cannot temporarily compute semantic tokens, it can indicate this by throwing an error with the message 'Busy'. - */ - provideDocumentSemanticTokens(document: TextDocument, token: CancellationToken): ProviderResult; - - /** - * Instead of always returning all the tokens in a file, it is possible for a `DocumentSemanticTokensProvider` to implement - * this method (`provideDocumentSemanticTokensEdits`) and then return incremental updates to the previously provided semantic tokens. - * - * --- - * ### How tokens change when the document changes - * - * Suppose that `provideDocumentSemanticTokens` has previously returned the following semantic tokens: - * ``` - * // 1st token, 2nd token, 3rd token - * [ 2,5,3,0,3, 0,5,4,1,0, 3,2,7,2,0 ] - * ``` - * - * Also suppose that after some edits, the new semantic tokens in a file are: - * ``` - * // 1st token, 2nd token, 3rd token - * [ 3,5,3,0,3, 0,5,4,1,0, 3,2,7,2,0 ] - * ``` - * It is possible to express these new tokens in terms of an edit applied to the previous tokens: - * ``` - * [ 2,5,3,0,3, 0,5,4,1,0, 3,2,7,2,0 ] // old tokens - * [ 3,5,3,0,3, 0,5,4,1,0, 3,2,7,2,0 ] // new tokens - * - * edit: { start: 0, deleteCount: 1, data: [3] } // replace integer at offset 0 with 3 - * ``` - * - * *NOTE*: If the provider cannot compute `SemanticTokensEdits`, it can "give up" and return all the tokens in the document again. - * *NOTE*: All edits in `SemanticTokensEdits` contain indices in the old integers array, so they all refer to the previous result state. - */ - provideDocumentSemanticTokensEdits?(document: TextDocument, previousResultId: string, token: CancellationToken): ProviderResult; -} - -/** - * The document range semantic tokens provider interface defines the contract between extensions and - * semantic tokens. - */ -export interface DocumentRangeSemanticTokensProvider { - /** - * @see [provideDocumentSemanticTokens](#DocumentSemanticTokensProvider.provideDocumentSemanticTokens). - */ - provideDocumentRangeSemanticTokens(document: TextDocument, range: Range, token: CancellationToken): ProviderResult; -} - -export interface api { - commands: { - executeCommand: (command: string, ...rest: any[]) => Thenable; - registerCommand(command: string, callback: (...args: any[]) => any, thisArg?: any): Disposable; - }; - languages: { - match: (selector: DocumentSelector, document: TextDocument) => number; - /** - * Register a semantic tokens provider for a whole document. - * - * Multiple providers can be registered for a language. In that case providers are sorted - * by their [score](#languages.match) and the best-matching provider is used. Failure - * of the selected provider will cause a failure of the whole operation. - * - * @param selector A selector that defines the documents this provider is applicable to. - * @param provider A document semantic tokens provider. - * @return A [disposable](#Disposable) that unregisters this provider when being disposed. - */ - registerDocumentSemanticTokensProvider(selector: DocumentSelector, provider: DocumentSemanticTokensProvider, legend: SemanticTokensLegend): Disposable; - - /** - * Register a semantic tokens provider for a document range. - * - * *Note:* If a document has both a `DocumentSemanticTokensProvider` and a `DocumentRangeSemanticTokensProvider`, - * the range provider will be invoked only initially, for the time in which the full document provider takes - * to resolve the first request. Once the full document provider resolves the first request, the semantic tokens - * provided via the range provider will be discarded and from that point forward, only the document provider - * will be used. - * - * Multiple providers can be registered for a language. In that case providers are sorted - * by their [score](#languages.match) and the best-matching provider is used. Failure - * of the selected provider will cause a failure of the whole operation. - * - * @param selector A selector that defines the documents this provider is applicable to. - * @param provider A document range semantic tokens provider. - * @return A [disposable](#Disposable) that unregisters this provider when being disposed. - */ - registerDocumentRangeSemanticTokensProvider(selector: DocumentSelector, provider: DocumentRangeSemanticTokensProvider, legend: SemanticTokensLegend): Disposable; - - }; - window: { - activeTextEditor: TextEditor | undefined; - showInformationMessage: (message: string, ...items: T[]) => Thenable; - showWarningMessage: (message: string, ...items: T[]) => Thenable; - showErrorMessage(message: string, ...items: string[]): Thenable; - createOutputChannel(name: string): OutputChannel; - registerWebviewPanelSerializer(viewType: string, serializer: WebviewPanelSerializer): Disposable; - }; - workspace: { - openTextDocument: (uri: Uri) => Thenable; - getConfiguration: (section?: string, resource?: Uri) => WorkspaceConfiguration; - asRelativePath: (pathOrUri: string | Uri, includeWorkspaceFolder?: boolean) => string; - createFileSystemWatcher(globPattern: GlobPattern, ignoreCreateEvents?: boolean, ignoreChangeEvents?: boolean, ignoreDeleteEvents?: boolean): FileSystemWatcher; - onDidChangeConfiguration: Event; - }; - extensions: { - getExtension(extensionId: string): Extension | undefined; - all: ReadonlyArray>; - }; - Uri: { - parse(value: string): Uri; - }; - Disposable: { - from(...disposableLikes: { dispose: () => any }[]): Disposable; - }; - - version: string; -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/tsconfig.json b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/tsconfig.json deleted file mode 100644 index 17f0209c07b..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/tsconfig.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "extends": "../../tsconfig.json", - "compilerOptions": { - "outDir": "dist" - }, - "include": [ - "./src/**/*" - ] -} \ No newline at end of file diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/tslint.json b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/tslint.json deleted file mode 100644 index 40a18cdec2d..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/tslint.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": "../../tslint.json" -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/yarn.lock b/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/yarn.lock deleted file mode 100644 index 5e20c8cca11..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.VSCode/yarn.lock +++ /dev/null @@ -1,376 +0,0 @@ -# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. -# yarn lockfile v1 - - -"@babel/code-frame@^7.0.0": - version "7.16.0" - resolved "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.16.0.tgz" - integrity sha512-IF4EOMEV+bfYwOmNxGzSnjR2EmQod7f1UXOpZM3l4i4o4QNwzjtJAu/HxdjHq0aYBvdqMuQEY1eg0nqW9ZPORA== - dependencies: - "@babel/highlight" "^7.16.0" - -"@babel/helper-validator-identifier@^7.15.7": - version "7.15.7" - resolved "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.15.7.tgz" - integrity sha512-K4JvCtQqad9OY2+yTU8w+E82ywk/fe+ELNlt1G8z3bVGlZfn/hOcQQsUhGhW/N+tb3fxK800wLtKOE/aM0m72w== - -"@babel/highlight@^7.16.0": - version "7.16.0" - resolved "https://registry.npmjs.org/@babel/highlight/-/highlight-7.16.0.tgz" - integrity sha512-t8MH41kUQylBtu2+4IQA3atqevA2lRgqA2wyVB/YiWmsDSuylZZuXOUy9ric30hfzauEFfdsuk/eXTRrGrfd0g== - dependencies: - "@babel/helper-validator-identifier" "^7.15.7" - chalk "^2.0.0" - js-tokens "^4.0.0" - -"@types/node@^10.9.4": - version "10.17.60" - resolved "https://registry.npmjs.org/@types/node/-/node-10.17.60.tgz" - integrity sha512-F0KIgDJfy2nA3zMLmWGKxcH2ZVEtCZXHHdOQs2gSaQ27+lNeEfGxzkIw90aXswATX7AZ33tahPbzy6KAfUreVw== - -"@types/vscode@1.69.0": - version "1.69.0" - resolved "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-public-npm/npm/registry/@types/vscode/-/vscode-1.69.0.tgz" - integrity sha1-pHIBGvOS+8+Cy7gvYLTCOcIbkhw= - -ansi-styles@^3.2.1: - version "3.2.1" - resolved "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz" - integrity sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA== - dependencies: - color-convert "^1.9.0" - -argparse@^1.0.7: - version "1.0.10" - resolved "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz" - integrity sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg== - dependencies: - sprintf-js "~1.0.2" - -argparse@^2.0.1: - version "2.0.1" - resolved "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz" - integrity sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q== - -balanced-match@^1.0.0: - version "1.0.2" - resolved "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz" - integrity sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw== - -brace-expansion@^1.1.7: - version "1.1.11" - resolved "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz" - integrity sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA== - dependencies: - balanced-match "^1.0.0" - concat-map "0.0.1" - -builtin-modules@^1.1.1: - version "1.1.1" - resolved "https://registry.npmjs.org/builtin-modules/-/builtin-modules-1.1.1.tgz" - integrity sha1-Jw8HbFpywC9bZaR9+Uxf46J4iS8= - -chalk@^2.0.0, chalk@^2.3.0: - version "2.4.2" - resolved "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz" - integrity sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ== - dependencies: - ansi-styles "^3.2.1" - escape-string-regexp "^1.0.5" - supports-color "^5.3.0" - -color-convert@^1.9.0: - version "1.9.3" - resolved "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz" - integrity sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg== - dependencies: - color-name "1.1.3" - -color-name@1.1.3: - version "1.1.3" - resolved "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz" - integrity sha1-p9BVi9icQveV3UIyj3QIMcpTvCU= - -commander@^2.12.1: - version "2.20.3" - resolved "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz" - integrity sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ== - -concat-map@0.0.1: - version "0.0.1" - resolved "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz" - integrity sha1-2Klr13/Wjfd5OnMDajug1UBdR3s= - -diff@^4.0.1: - version "4.0.2" - resolved "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz" - integrity sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A== - -escape-string-regexp@^1.0.5: - version "1.0.5" - resolved "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz" - integrity sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ= - -esprima@^4.0.0: - version "4.0.1" - resolved "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz" - integrity sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A== - -fs.realpath@^1.0.0: - version "1.0.0" - resolved "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz" - integrity sha1-FQStJSMVjKpA20onh8sBQRmU6k8= - -function-bind@^1.1.1: - version "1.1.1" - resolved "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz" - integrity sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A== - -glob@^7.1.1, glob@^7.1.3: - version "7.2.0" - resolved "https://registry.npmjs.org/glob/-/glob-7.2.0.tgz" - integrity sha512-lmLf6gtyrPq8tTjSmrO94wBeQbFR3HbLHbuyD69wuyQkImp2hWqMGB47OX65FBkPffO641IP9jWa1z4ivqG26Q== - dependencies: - fs.realpath "^1.0.0" - inflight "^1.0.4" - inherits "2" - minimatch "^3.0.4" - once "^1.3.0" - path-is-absolute "^1.0.0" - -has-flag@^3.0.0: - version "3.0.0" - resolved "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz" - integrity sha1-tdRU3CGZriJWmfNGfloH87lVuv0= - -has@^1.0.3: - version "1.0.3" - resolved "https://registry.npmjs.org/has/-/has-1.0.3.tgz" - integrity sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw== - dependencies: - function-bind "^1.1.1" - -inflight@^1.0.4: - version "1.0.6" - resolved "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz" - integrity sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk= - dependencies: - once "^1.3.0" - wrappy "1" - -inherits@2: - version "2.0.4" - resolved "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz" - integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ== - -is-core-module@^2.2.0: - version "2.8.0" - resolved "https://registry.npmjs.org/is-core-module/-/is-core-module-2.8.0.tgz" - integrity sha512-vd15qHsaqrRL7dtH6QNuy0ndJmRDrS9HAM1CAiSifNUFv4x1a0CCVsj18hJ1mShxIG6T2i1sO78MkP56r0nYRw== - dependencies: - has "^1.0.3" - -js-tokens@^4.0.0: - version "4.0.0" - resolved "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz" - integrity sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ== - -js-yaml@>=3.13.1: - version "4.1.0" - resolved "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz" - integrity sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA== - dependencies: - argparse "^2.0.1" - -js-yaml@^3.13.1: - version "3.14.1" - resolved "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz" - integrity sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g== - dependencies: - argparse "^1.0.7" - esprima "^4.0.0" - -minimatch@3.0.5: - version "3.0.5" - resolved "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-public-npm/npm/registry/minimatch/-/minimatch-3.0.5.tgz#4da8f1290ee0f0f8e83d60ca69f8f134068604a3" - integrity sha1-TajxKQ7g8PjoPWDKafjxNAaGBKM= - dependencies: - brace-expansion "^1.1.7" - -minimatch@^3.0.4: - version "3.0.4" - resolved "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz" - integrity sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA== - dependencies: - brace-expansion "^1.1.7" - -minimist@^1.2.5: - version "1.2.6" - resolved "https://registry.npmjs.org/minimist/-/minimist-1.2.6.tgz" - integrity sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q== - -mkdirp@^0.5.1: - version "0.5.5" - resolved "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.5.tgz" - integrity sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ== - dependencies: - minimist "^1.2.5" - -once@^1.3.0: - version "1.4.0" - resolved "https://registry.npmjs.org/once/-/once-1.4.0.tgz" - integrity sha1-WDsap3WWHUsROsF9nFC6753Xa9E= - dependencies: - wrappy "1" - -path-is-absolute@^1.0.0: - version "1.0.1" - resolved "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz" - integrity sha1-F0uSaHNVNP+8es5r9TpanhtcX18= - -path-parse@^1.0.6: - version "1.0.7" - resolved "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz" - integrity sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw== - -ps-list@7.2.0: - version "7.2.0" - resolved "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-public-npm/npm/registry/ps-list/-/ps-list-7.2.0.tgz" - integrity sha1-PREOHegkmksXjJsc8qIV0eTkL8A= - -resolve@^1.3.2: - version "1.20.0" - resolved "https://registry.npmjs.org/resolve/-/resolve-1.20.0.tgz" - integrity sha512-wENBPt4ySzg4ybFQW2TT1zMQucPK95HSh/nq2CFTZVOGut2+pQvSsgtda4d26YrYcr067wjbmzOG8byDPBX63A== - dependencies: - is-core-module "^2.2.0" - path-parse "^1.0.6" - -rimraf@2.6.3: - version "2.6.3" - resolved "https://registry.npmjs.org/rimraf/-/rimraf-2.6.3.tgz" - integrity sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA== - dependencies: - glob "^7.1.3" - -semver@^5.3.0: - version "5.7.1" - resolved "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz" - integrity sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ== - -semver@^7.3.5: - version "7.3.7" - resolved "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-public-npm/npm/registry/semver/-/semver-7.3.7.tgz" - integrity sha1-EsW2Sa/b+QSXB3luIqQCiBTOUj8= - dependencies: - lru-cache "^6.0.0" - -sprintf-js@~1.0.2: - version "1.0.3" - resolved "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz" - integrity sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw= - -supports-color@^5.3.0: - version "5.5.0" - resolved "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz" - integrity sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow== - dependencies: - has-flag "^3.0.0" - -tslib@^1.8.0, tslib@^1.8.1: - version "1.14.1" - resolved "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz" - integrity sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg== - -tslint@^5.11.0: - version "5.20.1" - resolved "https://registry.npmjs.org/tslint/-/tslint-5.20.1.tgz" - integrity sha512-EcMxhzCFt8k+/UP5r8waCf/lzmeSyVlqxqMEDQE7rWYiQky8KpIBz1JAoYXfROHrPZ1XXd43q8yQnULOLiBRQg== - dependencies: - "@babel/code-frame" "^7.0.0" - builtin-modules "^1.1.1" - chalk "^2.3.0" - commander "^2.12.1" - diff "^4.0.1" - glob "^7.1.1" - js-yaml "^3.13.1" - minimatch "^3.0.4" - mkdirp "^0.5.1" - resolve "^1.3.2" - semver "^5.3.0" - tslib "^1.8.0" - tsutils "^2.29.0" - -tsutils@^2.29.0: - version "2.29.0" - resolved "https://registry.npmjs.org/tsutils/-/tsutils-2.29.0.tgz" - integrity sha512-g5JVHCIJwzfISaXpXE1qvNalca5Jwob6FjI4AoPlqMusJ6ftFE7IkkFoMhVLRgK+4Kx3gkzb8UZK5t5yTTvEmA== - dependencies: - tslib "^1.8.1" - -typescript@~4.5.4: - version "4.5.5" - resolved "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-public-npm/npm/registry/typescript/-/typescript-4.5.5.tgz#d8c953832d28924a9e3d37c73d729c846c5896f3" - integrity sha1-2MlTgy0okkqePTfHPXKchGxYlvM= - -vscode-html-languageservice@^5.0.1: - version "5.0.1" - resolved "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-public-npm/npm/registry/vscode-html-languageservice/-/vscode-html-languageservice-5.0.1.tgz" - integrity sha1-vfeEfSekU6npiuKDbq11lHhMXBw= - dependencies: - vscode-languageserver-textdocument "^1.0.4" - vscode-languageserver-types "^3.17.1" - vscode-nls "^5.0.1" - vscode-uri "^3.0.3" - -vscode-jsonrpc@8.0.2: - version "8.0.2" - resolved "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-public-npm/npm/registry/vscode-jsonrpc/-/vscode-jsonrpc-8.0.2.tgz" - integrity sha1-8jntLNYAQCG2VQr5/Z0+R+7jysk= - -vscode-languageclient@8.0.2: - version "8.0.2" - resolved "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-public-npm/npm/registry/vscode-languageclient/-/vscode-languageclient-8.0.2.tgz" - integrity sha1-8fI86MhISqEeS337JEN9Plm7YcY= - dependencies: - minimatch "^3.0.4" - semver "^7.3.5" - vscode-languageserver-protocol "3.17.2" - -vscode-languageserver-protocol@3.17.2: - version "3.17.2" - resolved "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-public-npm/npm/registry/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.17.2.tgz" - integrity sha1-vqpGrqBu0GFXZYbF4RNoqa/B03g= - dependencies: - vscode-jsonrpc "8.0.2" - vscode-languageserver-types "3.17.2" - -vscode-languageserver-textdocument@^1.0.4, vscode-languageserver-textdocument@^1.0.5: - version "1.0.7" - resolved "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-public-npm/npm/registry/vscode-languageserver-textdocument/-/vscode-languageserver-textdocument-1.0.7.tgz" - integrity sha1-Ft9GjVwmBhA8kFVK4F+fPTNbdxs= - -vscode-languageserver-types@3.17.2, vscode-languageserver-types@^3.17.1: - version "3.17.2" - resolved "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-public-npm/npm/registry/vscode-languageserver-types/-/vscode-languageserver-types-3.17.2.tgz" - integrity sha1-ssLn3kBa09c6iD6RmJuFAXD/xPI= - -vscode-nls@^5.0.1: - version "5.2.0" - resolved "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-public-npm/npm/registry/vscode-nls/-/vscode-nls-5.2.0.tgz" - integrity sha1-PLaJPdm9aVJE2KAkvfdG7qZlzD8= - -vscode-uri@^3.0.3: - version "3.0.3" - resolved "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-public-npm/npm/registry/vscode-uri/-/vscode-uri-3.0.3.tgz" - integrity sha1-qVwc4ub0G3VJ+GJ50Z9HlR5PTYQ= - -wrappy@1: - version "1.0.2" - resolved "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz" - integrity sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8= - -yallist@^4.0.0: - version "4.0.0" - resolved "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-public-npm/npm/registry/yallist/-/yallist-4.0.0.tgz" - integrity sha1-m7knkNnA7/7GO+c1GeEaNQGaOnI= diff --git a/src/Razor/src/rzls/rzls.csproj b/src/Razor/src/rzls/rzls.csproj index 2e2fedc53e2..2128b080778 100644 --- a/src/Razor/src/rzls/rzls.csproj +++ b/src/Razor/src/rzls/rzls.csproj @@ -23,14 +23,6 @@ - - - $(PublishDir)\OmniSharpPlugin - - - - -