diff --git a/CodeiumVS/CodeLensConnection/CodeLensConnectionHandler.cs b/CodeiumVS/CodeLensConnection/CodeLensConnectionHandler.cs index c8b4d8d..280b005 100644 --- a/CodeiumVS/CodeLensConnection/CodeLensConnectionHandler.cs +++ b/CodeiumVS/CodeLensConnection/CodeLensConnectionHandler.cs @@ -5,94 +5,97 @@ namespace CodeiumVS { - using System; - using System.Diagnostics; - using System.IO.Pipes; - using System.Linq; - using System.Threading.Tasks; +using System; +using System.Diagnostics; +using System.IO.Pipes; +using System.Linq; +using System.Threading.Tasks; - using StreamJsonRpc; +using StreamJsonRpc; - using CodeLensConnections = System.Collections.Concurrent.ConcurrentDictionary; - using CodeLensDetails = System.Collections.Concurrent.ConcurrentDictionary; +using CodeLensConnections = + System.Collections.Concurrent.ConcurrentDictionary; +using CodeLensDetails = + System.Collections.Concurrent.ConcurrentDictionary; - public class CodeLensConnectionHandler : IRemoteVisualStudio, IDisposable - { - private static readonly CodeLensConnections connections = new CodeLensConnections(); - private static readonly CodeLensDetails detailsData = new CodeLensDetails(); +public class CodeLensConnectionHandler : IRemoteVisualStudio, IDisposable +{ + private static readonly CodeLensConnections connections = new CodeLensConnections(); + private static readonly CodeLensDetails detailsData = new CodeLensDetails(); - private JsonRpc? rpc; - private Guid? dataPointId; + private JsonRpc? rpc; + private Guid? dataPointId; - public static async Task AcceptCodeLensConnections() + public static async Task AcceptCodeLensConnections() + { + try { - try - { - while (true) - { - var stream = new NamedPipeServerStream( - PipeName.Get(Process.GetCurrentProcess().Id), - PipeDirection.InOut, - NamedPipeServerStream.MaxAllowedServerInstances, - PipeTransmissionMode.Byte, - PipeOptions.Asynchronous); - await stream.WaitForConnectionAsync().Caf(); - _ = HandleConnection(stream); - } - } - catch (Exception ex) + while (true) { - throw; - } - - static async Task HandleConnection(NamedPipeServerStream stream) - { - try - { - var handler = new CodeLensConnectionHandler(); - var rpc = JsonRpc.Attach(stream, handler); - handler.rpc = rpc; - await rpc.Completion; - handler.Dispose(); - stream.Dispose(); - } - catch (Exception ex) - { - CodeiumVSPackage.Instance.LogAsync("Handle Connection Error"); - } + var stream = + new NamedPipeServerStream(PipeName.Get(Process.GetCurrentProcess().Id), + PipeDirection.InOut, + NamedPipeServerStream.MaxAllowedServerInstances, + PipeTransmissionMode.Byte, + PipeOptions.Asynchronous); + await stream.WaitForConnectionAsync().Caf(); + _ = HandleConnection(stream); } } + catch (Exception ex) + { + throw; + } - public void Dispose() + static async Task HandleConnection(NamedPipeServerStream stream) { - if (dataPointId.HasValue) + try { - _ = connections.TryRemove(dataPointId.Value, out var _); - _ = detailsData.TryRemove(dataPointId.Value, out var _); + var handler = new CodeLensConnectionHandler(); + var rpc = JsonRpc.Attach(stream, handler); + handler.rpc = rpc; + await rpc.Completion; + handler.Dispose(); + stream.Dispose(); + } + catch (Exception ex) + { + CodeiumVSPackage.Instance.LogAsync("Handle Connection Error"); } } + } - // Called from each CodeLensDataPoint via JSON RPC. - public void RegisterCodeLensDataPoint(Guid id) + public void Dispose() + { + if (dataPointId.HasValue) { - dataPointId = id; - connections[id] = this; + _ = connections.TryRemove(dataPointId.Value, out var _); + _ = detailsData.TryRemove(dataPointId.Value, out var _); } + } - public static void StoreDetailsData(Guid id, FunctionInfo closestFunction) => detailsData[id] = closestFunction; + // Called from each CodeLensDataPoint via JSON RPC. + public void RegisterCodeLensDataPoint(Guid id) + { + dataPointId = id; + connections[id] = this; + } - public static FunctionInfo GetDetailsData(Guid id) => detailsData[id]; + public static void + StoreDetailsData(Guid id, FunctionInfo closestFunction) => detailsData[id] = closestFunction; - public static async Task RefreshCodeLensDataPoint(Guid id) - { - if (!connections.TryGetValue(id, out var conn)) - throw new InvalidOperationException($"CodeLens data point {id} was not registered."); + public static FunctionInfo GetDetailsData(Guid id) => detailsData[id]; - Debug.Assert(conn.rpc != null); - await conn.rpc!.InvokeAsync(nameof(IRemoteCodeLens.Refresh)).Caf(); - } + public static async Task RefreshCodeLensDataPoint(Guid id) + { + if (!connections.TryGetValue(id, out var conn)) + throw new InvalidOperationException($"CodeLens data point {id} was not registered."); - public static async Task RefreshAllCodeLensDataPoints() - => await Task.WhenAll(connections.Keys.Select(RefreshCodeLensDataPoint)).Caf(); + Debug.Assert(conn.rpc != null); + await conn.rpc!.InvokeAsync(nameof(IRemoteCodeLens.Refresh)).Caf(); } + + public static async Task RefreshAllCodeLensDataPoints() => + await Task.WhenAll(connections.Keys.Select(RefreshCodeLensDataPoint)).Caf(); +} } diff --git a/CodeiumVS/CodeLensConnection/CodeLensListener.cs b/CodeiumVS/CodeLensConnection/CodeLensListener.cs index eb94053..9f8cd81 100644 --- a/CodeiumVS/CodeLensConnection/CodeLensListener.cs +++ b/CodeiumVS/CodeLensConnection/CodeLensListener.cs @@ -17,89 +17,87 @@ namespace CodeiumVS { - [Export(typeof(ICodeLensCallbackListener))] - [ContentType("C/C++")] - [ContentType("CSharp")] - [ContentType("Basic")] - [ContentType("vbscript")] - [ContentType("TypeScript")] - [ContentType("JavaScript")] - [ContentType("html")] - [ContentType("HTMLX")] - [ContentType("Razor")] - public class CodeLensListener : ICodeLensCallbackListener, ICodeLensListener - { +[Export(typeof(ICodeLensCallbackListener))] +[ContentType("C/C++")] +[ContentType("CSharp")] +[ContentType("Basic")] +[ContentType("vbscript")] +[ContentType("TypeScript")] +[ContentType("JavaScript")] +[ContentType("html")] +[ContentType("HTMLX")] +[ContentType("Razor")] +public class CodeLensListener : ICodeLensCallbackListener, ICodeLensListener +{ - public int GetVisualStudioPid() => Process.GetCurrentProcess().Id; + public int GetVisualStudioPid() => Process.GetCurrentProcess().Id; - public bool IsCodeiumCodeLensActive() => CodeiumVSPackage.Instance != null && CodeiumVSPackage.Instance.SettingsPage.EnableCodeLens; - FunctionInfo GetClosestFunction(IList? functions, int line) + public bool + IsCodeiumCodeLensActive() => CodeiumVSPackage.Instance != null + && CodeiumVSPackage.Instance.SettingsPage.EnableCodeLens; + FunctionInfo GetClosestFunction(IList? functions, int line) + { + + FunctionInfo minFunction = null; + int minDistance = int.MaxValue; + foreach (var f in functions) { - - FunctionInfo minFunction = null; - int minDistance = int.MaxValue; - foreach (var f in functions) + var distance = Math.Abs(f.DefinitionLine - line); + if (distance < minDistance) { - var distance = Math.Abs(f.DefinitionLine - line); - if (distance < minDistance) - { - minDistance = distance; - minFunction = f; - } + minDistance = distance; + minFunction = f; } - - return minFunction; } - public async Task LoadInstructions( - Guid dataPointId, - Guid projGuid, - string filePath, - int textStart, - int textLen, - CancellationToken ct) - { - try - { - - ITextDocument _document; - TextViewListener.Instance.documentDictionary.TryGetValue(filePath.ToLower(), out _document); - var key = typeof(CodeiumCompletionHandler); - var props = _document.TextBuffer.Properties; - CodeiumCompletionHandler handler; - if (props.ContainsProperty(key)) - { - handler = props.GetProperty(key); - } - else - { - handler = null; - return null; - } - - IList? functions = - await CodeiumVSPackage.Instance.LanguageServer.GetFunctionsAsync( - _document.FilePath, - _document.TextBuffer.CurrentSnapshot.GetText(), - handler.GetLanguage(), - 0, - ct); + return minFunction; + } - var line = new Span(textStart, textLen); - var snapshotLine = _document.TextBuffer.CurrentSnapshot.GetLineFromPosition(line.Start); - var lineN = snapshotLine.LineNumber; - FunctionInfo closestFunction = GetClosestFunction(functions, lineN); - CodeLensConnectionHandler.StoreDetailsData(dataPointId, closestFunction); + public async Task LoadInstructions(Guid dataPointId, Guid projGuid, + string filePath, int textStart, int textLen, + CancellationToken ct) + { + try + { - return closestFunction; + ITextDocument _document; + TextViewListener.Instance.documentDictionary.TryGetValue(filePath.ToLower(), + out _document); + var key = typeof(CodeiumCompletionHandler); + var props = _document.TextBuffer.Properties; + CodeiumCompletionHandler handler; + if (props.ContainsProperty(key)) + { + handler = props.GetProperty(key); } - catch (Exception ex) + else { - CodeiumVSPackage.Instance.LogAsync(ex.ToString()); - + handler = null; return null; } + + IList? functions = + await CodeiumVSPackage.Instance.LanguageServer.GetFunctionsAsync( + _document.FilePath, + _document.TextBuffer.CurrentSnapshot.GetText(), + handler.GetLanguage(), + 0, + ct); + + var line = new Span(textStart, textLen); + var snapshotLine = _document.TextBuffer.CurrentSnapshot.GetLineFromPosition(line.Start); + var lineN = snapshotLine.LineNumber; + FunctionInfo closestFunction = GetClosestFunction(functions, lineN); + CodeLensConnectionHandler.StoreDetailsData(dataPointId, closestFunction); + + return closestFunction; } + catch (Exception ex) + { + CodeiumVSPackage.Instance.LogAsync(ex.ToString()); + return null; + } } } +} diff --git a/CodeiumVS/CodeiumVS.csproj b/CodeiumVS/CodeiumVS.csproj index 2e3a60f..98c1c7e 100644 --- a/CodeiumVS/CodeiumVS.csproj +++ b/CodeiumVS/CodeiumVS.csproj @@ -239,4 +239,4 @@ --> - \ No newline at end of file + diff --git a/CodeiumVS/CodeiumVSPackage.cs b/CodeiumVS/CodeiumVSPackage.cs index 668e4ce..0a8b8e6 100644 --- a/CodeiumVS/CodeiumVSPackage.cs +++ b/CodeiumVS/CodeiumVSPackage.cs @@ -76,9 +76,9 @@ await LogAsync( { await LogAsync( $"CodeiumVSPackage.InitializeAsync: Failed to register commands; Exception {ex}"); - await VS.MessageBox.ShowErrorAsync( - "Windsurf: Failed to register commands.", - "Windsurf might not work correctly. Please check the output window for more details."); + await VS.MessageBox.ShowErrorAsync("Windsurf: Failed to register commands.", + "Windsurf might not work correctly. Please check " + + "the output window for more details."); } try @@ -226,9 +226,7 @@ public static void OpenInBrowser(string url) { Action[] methods = [ (_url) => - { - Process.Start(new ProcessStartInfo { FileName = _url, UseShellExecute = true }); - }, + { Process.Start(new ProcessStartInfo { FileName = _url, UseShellExecute = true }); }, (_url) => { Process.Start("explorer.exe", _url); }, (_url) => diff --git a/CodeiumVS/Commands.cs b/CodeiumVS/Commands.cs index 826be0c..2d70b52 100644 --- a/CodeiumVS/Commands.cs +++ b/CodeiumVS/Commands.cs @@ -50,13 +50,14 @@ protected override async Task ExecuteAsync(OleMenuCmdEventArgs e) } [Command(PackageIds.CompleteSuggestion)] -internal sealed class CommandCompleteSuggestion : BaseCommandCompletionHandler +internal sealed class CommandCompleteSuggestion + : BaseCommandCompletionHandler { protected override async Task ExecuteAsync(OleMenuCmdEventArgs e) { try { - if(completionHandler == null) return; + if (completionHandler == null) return; completionHandler.CompleteSuggestion(); } catch (Exception ex) @@ -68,7 +69,8 @@ await CodeiumVSPackage.Instance.LogAsync( } [Command(PackageIds.ShowNextSuggestion)] -internal sealed class CommandShowNextSuggestion : BaseCommandCompletionHandler +internal sealed class CommandShowNextSuggestion + : BaseCommandCompletionHandler { protected override async Task ExecuteAsync(OleMenuCmdEventArgs e) { @@ -99,8 +101,7 @@ protected override void BeforeQueryStatus(EventArgs e) if (lastQuery != 0 && timeStamp - lastQuery < 500) return; lastQuery = timeStamp; - ThreadHelper.JoinableTaskFactory.Run(async delegate - { + ThreadHelper.JoinableTaskFactory.Run(async delegate { // any interactions with the `IVsTextView` should be done on the main thread await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); @@ -336,7 +337,6 @@ protected override async Task ExecuteAsync(OleMenuCmdEventArgs e) if (functionInfo != null) await controller.RefactorFunctionAsync( prompt, docView.Document.FilePath, functionInfo); - } else { @@ -366,7 +366,6 @@ protected override void BeforeQueryStatus(EventArgs e) lastQuery = timeStamp; ThreadHelper.JoinableTaskFactory.Run(async delegate { - // any interactions with the `IVsTextView` should be done on the main thread await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); @@ -395,20 +394,17 @@ protected async Task ResolveCodeBlock(int startLine) CancellationTokenSource cts = new CancellationTokenSource(); IList? functions = await CodeiumVSPackage.Instance.LanguageServer.GetFunctionsAsync( + docView.FilePath, text, languageInfo, 0, cts.Token); + + IList? classes = + await CodeiumVSPackage.Instance.LanguageServer.GetClassInfosAsync( docView.FilePath, text, languageInfo, 0, + docView.TextView.Options.GetOptionValue(DefaultOptions.NewLineCharacterOptionId), cts.Token); - IList? classes = await CodeiumVSPackage.Instance.LanguageServer.GetClassInfosAsync( - docView.FilePath, - text, - languageInfo, - 0, - docView.TextView.Options.GetOptionValue(DefaultOptions.NewLineCharacterOptionId), - cts.Token); - FunctionInfo minFunction = null; int minDistance = int.MaxValue; foreach (var f in functions) @@ -439,8 +435,10 @@ protected CodeBlockInfo ClassToCodeBlock(ClassInfo c) CodeBlockInfo codeBlockInfo = null; try { - var snapshotLineStart = docView.TextBuffer.CurrentSnapshot.GetLineFromLineNumber(c.StartLine); - var snapShotLineEnd = docView.TextBuffer.CurrentSnapshot.GetLineFromLineNumber(c.EndLine); + var snapshotLineStart = + docView.TextBuffer.CurrentSnapshot.GetLineFromLineNumber(c.StartLine); + var snapShotLineEnd = + docView.TextBuffer.CurrentSnapshot.GetLineFromLineNumber(c.EndLine); var start_position = snapshotLineStart.Start; var end_position = snapShotLineEnd.End; @@ -451,10 +449,9 @@ protected CodeBlockInfo ClassToCodeBlock(ClassInfo c) var end_col = end_position - snapShotLineEnd.Start.Position + 1; text = docView.TextBuffer.CurrentSnapshot.GetText(start_position, - end_position - start_position); + end_position - start_position); - codeBlockInfo = new() - { + codeBlockInfo = new() { raw_source = text, start_line = start_line, end_line = end_line, @@ -465,18 +462,15 @@ protected CodeBlockInfo ClassToCodeBlock(ClassInfo c) catch (Exception ex) { Task.Run(async () => - { - return CodeiumVSPackage.Instance.LogAsync(ex.ToString()); - }); + { return CodeiumVSPackage.Instance.LogAsync(ex.ToString()); }); } return codeBlockInfo; } - } - [Command(PackageIds.RefactorSelectionCodeBlock)] -internal class CommandRefactorSelectionCodeBlock : BaseCommandCodeLens +internal class CommandRefactorSelectionCodeBlock + : BaseCommandCodeLens { protected override async Task ExecuteAsync(OleMenuCmdEventArgs e) { @@ -496,10 +490,11 @@ protected override async Task ExecuteAsync(OleMenuCmdEventArgs e) startPos = ctx.ApplicableSpan.Value.Start; snapshotLine = docView.TextBuffer.CurrentSnapshot.GetLineFromPosition(startPos); int startLine = snapshotLine.LineNumber; - TextBounds selectionLine = docView.TextView.TextViewLines.GetCharacterBounds(snapshotLine.Start); + TextBounds selectionLine = + docView.TextView.TextViewLines.GetCharacterBounds(snapshotLine.Start); Point selectionScreenPos = docView.TextView.VisualElement.PointToScreen( new Point(selectionLine.Left - docView.TextView.ViewportLeft, - selectionLine.Top - docView.TextView.ViewportTop)); + selectionLine.Top - docView.TextView.ViewportTop)); var start = docView.TextView.TextViewLines.GetCharacterBounds(snapshotLine.Start); @@ -508,8 +503,8 @@ protected override async Task ExecuteAsync(OleMenuCmdEventArgs e) highlighter?.AddHighlight(snapshotLine.Extent); var dialog = RefactorCodeDialogWindow.GetOrCreate(); - string? prompt = - await dialog.ShowAndGetPromptAsync(languageInfo, selectionScreenPos.X, selectionScreenPos.Y); + string? prompt = await dialog.ShowAndGetPromptAsync( + languageInfo, selectionScreenPos.X, selectionScreenPos.Y); highlighter?.ClearAll(); @@ -518,8 +513,7 @@ protected override async Task ExecuteAsync(OleMenuCmdEventArgs e) if (prompt == null) return; if (functionInfo != null) { - controller.RefactorFunctionAsync( - prompt, docView.FilePath, functionInfo); + controller.RefactorFunctionAsync(prompt, docView.FilePath, functionInfo); } else { @@ -554,7 +548,8 @@ protected override async Task ExecuteAsync(OleMenuCmdEventArgs e) await CodeiumVSPackage.Instance.LogAsync(e.InValue.ToString()); var ctx = e.InValue as CodeLensDescriptorContext; int startPos = ctx.ApplicableSpan.Value.Start; - ITextSnapshotLine line = docView.TextBuffer.CurrentSnapshot.GetLineFromPosition(startPos); + ITextSnapshotLine line = + docView.TextBuffer.CurrentSnapshot.GetLineFromPosition(startPos); int startLine = line.LineNumber; await ResolveCodeBlock(startLine); @@ -578,9 +573,9 @@ protected override async Task ExecuteAsync(OleMenuCmdEventArgs e) } } - [Command(PackageIds.GenerateSelectionFunctionDocstring)] -internal class GenerateSelectionFunctionDocstring : BaseCommandCodeLens +internal class GenerateSelectionFunctionDocstring + : BaseCommandCodeLens { protected override async Task ExecuteAsync(OleMenuCmdEventArgs e) { @@ -595,7 +590,8 @@ protected override async Task ExecuteAsync(OleMenuCmdEventArgs e) await CodeiumVSPackage.Instance.LogAsync(e.InValue.ToString()); var ctx = e.InValue as CodeLensDescriptorContext; int startPos = ctx.ApplicableSpan.Value.Start; - ITextSnapshotLine line = docView.TextBuffer.CurrentSnapshot.GetLineFromPosition(startPos); + ITextSnapshotLine line = + docView.TextBuffer.CurrentSnapshot.GetLineFromPosition(startPos); int startLine = line.LineNumber; await ResolveCodeBlock(startLine); diff --git a/CodeiumVS/InlineDiff/InlineDiffAdornment.cs b/CodeiumVS/InlineDiff/InlineDiffAdornment.cs index 0744e3a..5750877 100644 --- a/CodeiumVS/InlineDiff/InlineDiffAdornment.cs +++ b/CodeiumVS/InlineDiff/InlineDiffAdornment.cs @@ -132,10 +132,10 @@ public async Task CreateDiffAsync(int position, int length, string replacement) Assumes.True(position > 0 && length > 0 && (position + length) <= _hostView.TextSnapshot.Length, "InlineDiffAdornment.CreateDiff: Invalid position and length parameter"); - Assumes.True( - MefProvider.Instance.TextDocumentFactoryService.TryGetTextDocument( - _hostView.TextDataModel.DocumentBuffer, out var textDocument), - "InlineDiffAdornment.CreateDiff: Could not get text document for the current host view"); + Assumes.True(MefProvider.Instance.TextDocumentFactoryService.TryGetTextDocument( + _hostView.TextDataModel.DocumentBuffer, out var textDocument), + "InlineDiffAdornment.CreateDiff: Could not get text document for the " + + "current host view"); // create a temporary file to store the diff string rightFileName = Path.GetTempFileName() + Path.GetExtension(textDocument.FilePath); @@ -335,9 +335,9 @@ private void CreateRightProjectionBuffer(string tempFileName, int position, int int openingResult = MefProvider.Instance.DocumentOpeningService.OpenDocumentViaProject( tempFileName, Guid.Empty, out var _, out var _, out var _, out _rightWindowFrame); - Assumes.True( - ErrorHandler.Succeeded(openingResult), - "InlineDiffAdornment.CreateRightProjectionBuffer: Could not open the document for temporary file"); + Assumes.True(ErrorHandler.Succeeded(openingResult), + "InlineDiffAdornment.CreateRightProjectionBuffer: Could not open the " + + "document for temporary file"); VsShellUtilities.GetTextView(_rightWindowFrame).GetBuffer(out var sourceTextLines); Assumes.True( @@ -351,10 +351,10 @@ private void CreateRightProjectionBuffer(string tempFileName, int position, int _rightSourceBuffer != null, "InlineDiffAdornment.CreateRightProjectionBuffer: Could not create source buffer"); - Assumes.True( - MefProvider.Instance.TextDocumentFactoryService.TryGetTextDocument( - _rightSourceBuffer, out _rightTextDocument), - "InlineDiffAdornment.CreateRightProjectionBuffer: Could not get text document for the temp file"); + Assumes.True(MefProvider.Instance.TextDocumentFactoryService.TryGetTextDocument( + _rightSourceBuffer, out _rightTextDocument), + "InlineDiffAdornment.CreateRightProjectionBuffer: Could not get text " + + "document for the temp file"); // apply the diff using ITextEdit textEdit = _rightSourceBuffer.CreateEdit(); diff --git a/CodeiumVS/InlineDiff/InlineDiffView.cs b/CodeiumVS/InlineDiff/InlineDiffView.cs index d10b941..64720d2 100644 --- a/CodeiumVS/InlineDiff/InlineDiffView.cs +++ b/CodeiumVS/InlineDiff/InlineDiffView.cs @@ -184,8 +184,8 @@ private void CreateTextViewHostCallback(IDifferenceTextViewModel textViewModel, // should not happen if (vsTextView is not IVsUserData codeWindowData) - throw new InvalidOperationException( - "Creating DifferenceViewerWithAdapters failed: Unable to cast IVsTextView to IVsUserData."); + throw new InvalidOperationException("Creating DifferenceViewerWithAdapters failed: " + + "Unable to cast IVsTextView to IVsUserData."); // set the roles and text view model for it SetRolesAndModel(codeWindowData, textViewModel, roles); diff --git a/CodeiumVS/LanguageServer/LanguageServer.cs b/CodeiumVS/LanguageServer/LanguageServer.cs index ff24e3e..3376e1e 100644 --- a/CodeiumVS/LanguageServer/LanguageServer.cs +++ b/CodeiumVS/LanguageServer/LanguageServer.cs @@ -40,10 +40,8 @@ public class LanguageServer private readonly HttpClient _httpClient; private readonly CodeiumVSPackage _package; - public readonly LanguageServerController Controller; - public LanguageServer() { _package = CodeiumVSPackage.Instance; @@ -73,10 +71,7 @@ public async Task InitializeAsync() _metadata.request_id = 0; string ideName = "visual_studio"; - if (_languageServerVersion == "1.16.0") - { - ideName = "vscode"; - } + if (_languageServerVersion == "1.16.0") { ideName = "vscode"; } _metadata.ide_name = ideName; _metadata.ide_version = ideVersion; _metadata.extension_name = Vsix.Name; @@ -157,20 +152,21 @@ public async Task SignInWithAuthTokenAsync(string authToken) public async Task SignInAsync() { // this will block until the sign in process has finished - async Task WaitForAuthTokenAsync() + async Task < string ? > WaitForAuthTokenAsync() { // wait until we got the actual port of the LSP await WaitReadyAsync(); // TODO: should we use timeout = Timeout.InfiniteTimeSpan? default value is 100s (1m40s) GetAuthTokenResponse? result = - await RequestCommandAsync("GetAuthToken", new { }); + await RequestCommandAsync("GetAuthToken", new {}); if (result == null) { // show an error message box var msgboxResult = await VS.MessageBox.ShowAsync( - "Windsurf: Failed to get the Authentication Token. Please check the output window for more details.", + "Windsurf: Failed to get the Authentication Token. Please check the output " + + "window for more details.", "Do you want to retry?", OLEMSGICON.OLEMSGICON_WARNING, OLEMSGBUTTON.OLEMSGBUTTON_RETRYCANCEL, @@ -226,7 +222,8 @@ private async Task GetLanguageServerInfoAsync() { string portalUrl = _package.SettingsPage.PortalUrl.TrimEnd('/'); extensionBaseUrl = portalUrl; - string version = await new HttpClient().GetStringAsync(portalUrl + "/api/version"); + string version = + await new HttpClient().GetStringAsync(portalUrl + ("/api/" + "version")); if (version.Equals("test", StringComparison.OrdinalIgnoreCase) || Regex.IsMatch(version, @"^\d+\.\d+\.\d+$")) { @@ -308,12 +305,12 @@ await _package.LogAsync( }), ]; - errorBar.Show( - "[Windsurf] Critical Error: Failed to download the language server. Do you want to retry?", - KnownMonikers.StatusError, - true, - null, - [.. actions, .. NotificationInfoBar.SupportActions]); + errorBar.Show("[Windsurf] Critical Error: Failed to download the language server. Do " + + "you want to retry?", + KnownMonikers.StatusError, + true, + null, + [..actions, ..NotificationInfoBar.SupportActions]); } else { @@ -384,8 +381,7 @@ private void ThreadDownloadLanguageServer(IVsThreadedWaitDialog4 progressDialog) webClient.DownloadFileCompleted += (s, e) => { ThreadHelper.JoinableTaskFactory - .RunAsync(async delegate - { + .RunAsync(async delegate { await ThreadDownload_OnCompletedAsync(e, progressDialog, downloadDest); }) .FireAndForget(); @@ -461,8 +457,8 @@ private async Task VerifyLanguageServerSignatureAsync() { } - await _package.LogAsync( - "LanguageServer.VerifyLanguageServerSignatureAsync: Failed to verify the language server digital signature"); + await _package.LogAsync("LanguageServer.VerifyLanguageServerSignatureAsync: Failed to " + + "verify the language server digital signature"); NotificationInfoBar errorBar = new(); KeyValuePair[] actions = [ @@ -493,12 +489,12 @@ await _package.LogAsync( ]; await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); - errorBar.Show( - "[Windsurf] Failed to verify the language server digital signature. The executable might be corrupted.", - KnownMonikers.IntellisenseWarning, - true, - null, - actions); + errorBar.Show("[Windsurf] Failed to verify the language server digital signature. The " + + "executable might be corrupted.", + KnownMonikers.IntellisenseWarning, + true, + null, + actions); return false; } @@ -531,7 +527,8 @@ await _package.LogAsync( $"LanguageServer.StartAsync: Failed to create directories; Exception: {ex}"); new NotificationInfoBar().Show( - "[Windsurf] Critical error: Failed to create language server directories. Please check the output window for more details.", + "[Windsurf] Critical error: Failed to create language server directories. Please " + + "check the output window for more details.", KnownMonikers.StatusError, true, null, @@ -598,12 +595,12 @@ await _package.LogAsync( ]; await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); - errorBar.Show( - "[Windsurf] Critical Error: Failed to start the language server. Do you want to retry?", - KnownMonikers.StatusError, - true, - null, - [.. actions, .. NotificationInfoBar.SupportActions]); + errorBar.Show("[Windsurf] Critical Error: Failed to start the language server. Do " + + "you want to retry?", + KnownMonikers.StatusError, + true, + null, + [..actions, ..NotificationInfoBar.SupportActions]); return; } @@ -620,12 +617,12 @@ await _package.LogAsync( // warn the user about the issue await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); - new NotificationInfoBar().Show( - "[Windsurf] Failed to read output from the language server, Windsurf might not work properly.", - KnownMonikers.IntellisenseWarning, - true, - null, - NotificationInfoBar.SupportActions); + new NotificationInfoBar().Show("[Windsurf] Failed to read output from the language " + + "server, Windsurf might not work properly.", + KnownMonikers.IntellisenseWarning, + true, + null, + NotificationInfoBar.SupportActions); // fall back to reading the port file var timeoutSec = 120; @@ -655,7 +652,8 @@ await _package.LogAsync( else { new NotificationInfoBar().Show( - "[Windsurf] Critical Error: Failed to get the language server port. Please check the output window for more details.", + "[Windsurf] Critical Error: Failed to get the language server port. Please " + + "check the output window for more details.", KnownMonikers.StatusError, true, null, @@ -808,66 +806,72 @@ private async Task InitializeTrackedWorkspaceAsync() List projectsToIndex = new List(inputDirectoriesToIndex); int maxToIndex = 10; - projectsToIndex.AddRange(await GetDirectoriesToIndex(inputDirectoriesToIndex, openFileProjects, maxToIndex - projectsToIndex.Count, dte)); + projectsToIndex.AddRange(await GetDirectoriesToIndex( + inputDirectoriesToIndex, openFileProjects, maxToIndex - projectsToIndex.Count, dte)); await _package.LogAsync($"Number of projects to index: {projectsToIndex.Count}"); for (int i = 0; i < Math.Min(maxToIndex, projectsToIndex.Count); i++) { try { - await _package.LogAsync($"Processing Project {i + 1} of {projectsToIndex.Count}: {projectsToIndex[i]}"); - AddTrackedWorkspaceResponse response = await AddTrackedWorkspaceAsync(projectsToIndex[i]); - if (response != null) - { - _initializedWorkspace = true; - } + await _package.LogAsync( + $"Processing Project {i + 1} of {projectsToIndex.Count}: {projectsToIndex[i]}"); + AddTrackedWorkspaceResponse response = + await AddTrackedWorkspaceAsync(projectsToIndex[i]); + if (response != null) { _initializedWorkspace = true; } } catch (Exception ex) { - await _package.LogAsync($"Error processing project {i + 1} of {projectsToIndex.Count}: {ex.Message}"); + await _package.LogAsync( + $"Error processing project {i + 1} of {projectsToIndex.Count}: {ex.Message}"); } } } - private async Task> GetDirectoriesToIndex(HashSet processedProjects, HashSet openFileProjects, int remainingToFind, DTE dte) + private async Task> GetDirectoriesToIndex(HashSet processedProjects, + HashSet openFileProjects, + int remainingToFind, DTE dte) { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); HashSet remainingProjectsToIndexPath = new HashSet(); async Task AddFilesToIndexLists(EnvDTE.Project project) { - if (remainingToFind <= 0) - { - return; - } + if (remainingToFind <= 0) { return; } string projectFullName = project.FullName; await _package.LogAsync($"Adding files to index of project: {projectFullName}"); - if (!string.IsNullOrEmpty(projectFullName) && !processedProjects.Any(p => projectFullName.StartsWith(p))) + if (!string.IsNullOrEmpty(projectFullName) && + !processedProjects.Any(p => projectFullName.StartsWith(p))) { string projectName = Path.GetFileNameWithoutExtension(projectFullName); IEnumerable commonDirs = Enumerable.Empty(); string projectDir = Path.GetDirectoryName(projectFullName); // Parse the proj file to find all source directories - if (File.Exists(projectFullName) && (projectFullName.EndsWith(".csproj", StringComparison.OrdinalIgnoreCase) || projectFullName.EndsWith(".vcxproj", StringComparison.OrdinalIgnoreCase))) + if (File.Exists(projectFullName) && + (projectFullName.EndsWith(".csproj", StringComparison.OrdinalIgnoreCase) || + projectFullName.EndsWith(".vcxproj", StringComparison.OrdinalIgnoreCase))) { try { XDocument projDoc = XDocument.Load(projectFullName); IEnumerable compileItems; - if (projectFullName.EndsWith(".vcxproj", StringComparison.OrdinalIgnoreCase)) + if (projectFullName.EndsWith(".vcxproj", + StringComparison.OrdinalIgnoreCase)) { // Handle C++ project files compileItems = projDoc.Descendants() - .Where(x => x.Name.LocalName == "ClCompile" || x.Name.LocalName == "ClInclude") - .Select(x => x.Attribute("Include")?.Value) - .Where(x => !string.IsNullOrEmpty(x)); + .Where(x => x.Name.LocalName == "ClCompile" || + x.Name.LocalName == "ClInclude") + .Select(x => x.Attribute("Include")?.Value) + .Where(x => !string.IsNullOrEmpty(x)); } else { // Handle C# project files compileItems = projDoc.Descendants() - .Where(x => x.Name.LocalName == "Compile" || x.Name.LocalName == "Content") - .Select(x => x.Attribute("Include")?.Value) - .Where(x => !string.IsNullOrEmpty(x)); + .Where(x => x.Name.LocalName == "Compile" || + x.Name.LocalName == "Content") + .Select(x => x.Attribute("Include")?.Value) + .Where(x => !string.IsNullOrEmpty(x)); } var fullPaths = new List(); @@ -877,20 +881,20 @@ async Task AddFilesToIndexLists(EnvDTE.Project project) fullPaths.Add(fullPath); } - commonDirs = Utilities.FileUtilities.FindMinimumEncompassingDirectories(fullPaths); + commonDirs = + Utilities.FileUtilities.FindMinimumEncompassingDirectories(fullPaths); } catch (Exception ex) { - await _package.LogAsync($"Failed to parse project file {projectFullName}: {ex.Message}"); + await _package.LogAsync( + $"Failed to parse project file {projectFullName}: {ex.Message}"); } } - if (commonDirs.Count() == 0) - { - commonDirs = new[] { projectDir }; - } + if (commonDirs.Count() == 0) { commonDirs = new[] { projectDir }; } - await _package.LogAsync($"Found set-covering directories for {projectName}: {commonDirs.Count()}"); + await _package.LogAsync( + $"Found set-covering directories for {projectName}: {commonDirs.Count()}"); foreach (var dir in commonDirs) { remainingToFind -= 1; @@ -904,10 +908,7 @@ async Task AddFilesToIndexLists(EnvDTE.Project project) { try { - if (item.SubProject != null) - { - await AddFilesToIndexLists(item.SubProject); - } + if (item.SubProject != null) { await AddFilesToIndexLists(item.SubProject); } } catch (Exception ex) { @@ -931,10 +932,7 @@ async Task AddFilesToIndexLists(EnvDTE.Project project) } foreach (EnvDTE.Project project in dte.Solution.Projects) { - if (openFileProjects.Contains(project)) - { - continue; - } + if (openFileProjects.Contains(project)) { continue; } try { await AddFilesToIndexLists(project); @@ -944,15 +942,11 @@ async Task AddFilesToIndexLists(EnvDTE.Project project) await _package.LogAsync($"Failed to process remaining project: {ex.Message}"); continue; } - if (remainingToFind <= 0) - { - break; - } + if (remainingToFind <= 0) { break; } } return remainingProjectsToIndexPath.ToList(); } - private async Task RequestCommandAsync(string command, object data, CancellationToken cancellationToken = default) { @@ -966,35 +960,25 @@ public async Task?> int cursorPosition, string lineEnding, int tabSize, bool insertSpaces, CancellationToken token) { - if (!_initializedWorkspace) - { - await InitializeTrackedWorkspaceAsync(); - } + if (!_initializedWorkspace) { await InitializeTrackedWorkspaceAsync(); } var uri = new System.Uri(absolutePath); var absoluteUri = uri.AbsoluteUri; GetCompletionsRequest data = - new() - { - metadata = GetMetadata(), - document = new() - { - text = text, - editor_language = language.Name, - language = language.Type, - cursor_offset = (ulong)cursorPosition, - line_ending = lineEnding, - absolute_path = absolutePath, - absolute_uri = absoluteUri, - relative_path = Path.GetFileName(absolutePath) - }, - editor_options = new() - { - tab_size = (ulong)tabSize, - insert_spaces = insertSpaces, - disable_autocomplete_in_comments = + new() { metadata = GetMetadata(), + document = new() { text = text, + editor_language = language.Name, + language = language.Type, + cursor_offset = (ulong)cursorPosition, + line_ending = lineEnding, + absolute_path = absolutePath, + absolute_uri = absoluteUri, + relative_path = Path.GetFileName(absolutePath) }, + editor_options = new() { + tab_size = (ulong)tabSize, + insert_spaces = insertSpaces, + disable_autocomplete_in_comments = !_package.SettingsPage.EnableCommentCompletion, - } - }; + } }; GetCompletionsResponse? result = await RequestCommandAsync("GetCompletions", data, token); @@ -1011,7 +995,7 @@ public async Task AcceptCompletionAsync(string completionId) public async Task GetProcessesAsync() { - return await RequestCommandAsync("GetProcesses", new { }); + return await RequestCommandAsync("GetProcesses", new {}); } public async Task AddTrackedWorkspaceAsync(string workspacePath) @@ -1022,77 +1006,60 @@ public async Task AcceptCompletionAsync(string completionId) public Metadata GetMetadata() { - return new() - { - request_id = _metadata.request_id++, - api_key = _metadata.api_key, - ide_name = _metadata.ide_name, - ide_version = _metadata.ide_version, - - extension_name = _metadata.extension_name, - extension_version = _metadata.extension_version, - session_id = _metadata.session_id, - locale = _metadata.locale, - disable_telemetry = _metadata.disable_telemetry - }; + return new() { request_id = _metadata.request_id++, + api_key = _metadata.api_key, + ide_name = _metadata.ide_name, + ide_version = _metadata.ide_version, + + extension_name = _metadata.extension_name, + extension_version = _metadata.extension_version, + session_id = _metadata.session_id, + locale = _metadata.locale, + disable_telemetry = _metadata.disable_telemetry }; } - public async Task?> - GetFunctionsAsync(string absolutePath, string text, Languages.LangInfo language, - int cursorPosition, CancellationToken token) + public async Task?> GetFunctionsAsync(string absolutePath, string text, + Languages.LangInfo language, + int cursorPosition, + CancellationToken token) { - if (!_initializedWorkspace) - { - await InitializeTrackedWorkspaceAsync(); - } + if (!_initializedWorkspace) { await InitializeTrackedWorkspaceAsync(); } var uri = new System.Uri(absolutePath); var absoluteUri = uri.AbsoluteUri; - GetFunctionsRequest data = - new() - { - document = new() - { - text = text.Replace("\r", ""), - editor_language = language.Name, - language = language.Type, - cursor_offset = (ulong)cursorPosition, - line_ending = "\n", - absolute_path = absolutePath, - absolute_uri = absoluteUri, - relative_path = Path.GetFileName(absolutePath) - }, - }; + GetFunctionsRequest data = new() { + document = new() { text = text.Replace("\r", ""), + editor_language = language.Name, + language = language.Type, + cursor_offset = (ulong)cursorPosition, + line_ending = "\n", + absolute_path = absolutePath, + absolute_uri = absoluteUri, + relative_path = Path.GetFileName(absolutePath) }, + }; GetFunctionsResponse? result = await RequestCommandAsync("GetFunctions", data, token); return result != null ? result.FunctionCaptures : []; } - public async Task?> - GetClassInfosAsync(string absolutePath, string text, Languages.LangInfo language, - int cursorPosition, string lineEnding, CancellationToken token) + public async Task?> GetClassInfosAsync(string absolutePath, string text, + Languages.LangInfo language, + int cursorPosition, string lineEnding, + CancellationToken token) { - if (!_initializedWorkspace) - { - await InitializeTrackedWorkspaceAsync(); - } + if (!_initializedWorkspace) { await InitializeTrackedWorkspaceAsync(); } var uri = new System.Uri(absolutePath); var absoluteUri = uri.AbsoluteUri; - GetClassInfosRequest data = - new() - { - document = new() - { - text = text.Replace("\r", ""), - editor_language = language.Name, - language = language.Type, - cursor_offset = (ulong)cursorPosition, - line_ending = "\n", - absolute_path = absolutePath, - absolute_uri = absoluteUri, - relative_path = Path.GetFileName(absolutePath) - }, - }; + GetClassInfosRequest data = new() { + document = new() { text = text.Replace("\r", ""), + editor_language = language.Name, + language = language.Type, + cursor_offset = (ulong)cursorPosition, + line_ending = "\n", + absolute_path = absolutePath, + absolute_uri = absoluteUri, + relative_path = Path.GetFileName(absolutePath) }, + }; GetClassInfosResponse? result = await RequestCommandAsync("GetClassInfos", data, token); diff --git a/CodeiumVS/LanguageServer/LanguageServerController.cs b/CodeiumVS/LanguageServer/LanguageServerController.cs index f2f6d7a..4491492 100644 --- a/CodeiumVS/LanguageServer/LanguageServerController.cs +++ b/CodeiumVS/LanguageServer/LanguageServerController.cs @@ -41,8 +41,11 @@ void OnMessage(object sender, MessageEventArgs msg) if (request.ShouldSerializeopen_file_pointer()) { var data = request.open_file_pointer; - OpenSelection( - data.file_uri.IsNullOrEmpty() ? data.file_path : data.file_uri, data.start_line, data.start_col, data.end_line, data.end_col); + OpenSelection(data.file_uri.IsNullOrEmpty() ? data.file_path : data.file_uri, + data.start_line, + data.start_col, + data.end_line, + data.end_col); } else if (request.ShouldSerializeinsert_at_cursor()) { @@ -63,7 +66,10 @@ void OnMessage(object sender, MessageEventArgs msg) replacement += line.text + "\n"; } } - ApplyDiff(data.uri.IsNullOrEmpty() ? data.file_path : data.uri, data.diff.start_line, data.diff.end_line, replacement); + ApplyDiff(data.uri.IsNullOrEmpty() ? data.file_path : data.uri, + data.diff.start_line, + data.diff.end_line, + replacement); } } @@ -350,8 +356,8 @@ internal static bool Send(this WebServerRequest request, WebSocket ws) { if (ws == null || !ws.IsAlive) { - CodeiumVSPackage.Instance.Log( - "Language Server Controller: Unable to send the request because the connection is closed."); + CodeiumVSPackage.Instance.Log("Language Server Controller: Unable to send the " + + "request because the connection is closed."); return false; } diff --git a/CodeiumVS/LanguageServer/Packets.cs b/CodeiumVS/LanguageServer/Packets.cs index 5f5d847..48a1dff 100644 --- a/CodeiumVS/LanguageServer/Packets.cs +++ b/CodeiumVS/LanguageServer/Packets.cs @@ -185,12 +185,13 @@ public partial class Document : global::ProtoBuf.IExtensible [global::ProtoBuf.ProtoMember(12)] [global::System.ComponentModel.DefaultValue("")] - public string absolute_uri { get; set; } = ""; + public string absolute_uri { + get; set; + } = ""; [global::ProtoBuf.ProtoMember(2)] [global::System.ComponentModel.DefaultValue("")] - public string relative_path - { + public string relative_path { get; set; } = ""; @@ -417,7 +418,9 @@ public partial class CodeContextItem : global::ProtoBuf.IExtensible [global::ProtoBuf.ProtoMember(16)] [global::System.ComponentModel.DefaultValue("")] - public string absolute_uri { get; set; } = ""; + public string absolute_uri { + get; set; + } = ""; [global::ProtoBuf.ProtoMember(2)] public global::System.Collections.Generic.List workspace_paths { @@ -497,7 +500,9 @@ public partial class WorkspacePath : global::ProtoBuf.IExtensible [global::ProtoBuf.ProtoMember(3)] [global::System.ComponentModel.DefaultValue("")] - public string workspace_uri { get; set; } = ""; + public string workspace_uri { + get; set; + } = ""; [global::ProtoBuf.ProtoMember(2)] [global::System.ComponentModel.DefaultValue("")] @@ -771,8 +776,7 @@ public string prompt { [global::ProtoBuf.ProtoMember(21)] [global::System.ComponentModel.DefaultValue("")] - public string context_prompt - { + public string context_prompt { get; set; } = ""; @@ -798,8 +802,7 @@ public ulong prompt_latency_ms { } = new global::System.Collections.Generic.List(); [global::ProtoBuf.ProtoMember(20)] - public ulong num_tokenized_bytes - { + public ulong num_tokenized_bytes { get; set; } @@ -816,8 +819,7 @@ public Language language { [global::ProtoBuf.ProtoMember(5)] [global::System.ComponentModel.DefaultValue("")] - public string absolute_path - { + public string absolute_path { get; set; } = ""; @@ -829,8 +831,7 @@ public string absolute_path_uri_for_telemetry { [global::ProtoBuf.ProtoMember(6)] [global::System.ComponentModel.DefaultValue("")] - public string relative_path - { + public string relative_path { get; set; } = ""; @@ -842,8 +843,7 @@ public string relative_path_for_telemetry { [global::ProtoBuf.ProtoMember(13)] [global::System.ComponentModel.DefaultValue("")] - public string workspace - { + public string workspace { get; set; } = ""; @@ -861,15 +861,13 @@ public string experiment_features_json { [global::ProtoBuf.ProtoMember(19)] [global::System.ComponentModel.DefaultValue("")] - public string experiment_variant_json - { + public string experiment_variant_json { get; set; } = ""; [global::ProtoBuf.ProtoMember(10)] [global::System.ComponentModel.DefaultValue("")] - public string model - { + public string model { get; set; } = ""; @@ -901,11 +899,9 @@ public string model_tag { [global::ProtoBuf.ProtoMember(22)] [global::System.ComponentModel.DefaultValue("")] - public string eval_suffix - { + public string eval_suffix { get; set; } = ""; - } [global::ProtoBuf.ProtoContract()] @@ -1327,8 +1323,7 @@ public Document active_document { } [global::ProtoBuf.ProtoMember(6)] - public global::System.Collections.Generic.List open_document_paths - { + public global::System.Collections.Generic.List open_document_paths { get; } = new global::System.Collections.Generic.List(); @@ -1338,8 +1333,7 @@ public Document active_document { } = new global::System.Collections.Generic.List(); [global::ProtoBuf.ProtoMember(7)] - public global::System.Collections.Generic.List workspace_paths - { + public global::System.Collections.Generic.List workspace_paths { get; } = new global::System.Collections.Generic.List(); @@ -1573,8 +1567,7 @@ public Language language { [global::ProtoBuf.ProtoMember(3)] [global::System.ComponentModel.DefaultValue("")] - public string file_path - { + public string file_path { get; set; } = ""; @@ -1589,8 +1582,9 @@ public string uri { public partial class FunctionInfo : global::ProtoBuf.IExtensible { private global::ProtoBuf.IExtension __pbn__extensionData; - global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing) - => global::ProtoBuf.Extensible.GetExtensionObject(ref __pbn__extensionData, createIfMissing); + global::ProtoBuf.IExtension + global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing) => + global::ProtoBuf.Extensible.GetExtensionObject(ref __pbn__extensionData, createIfMissing); [global::ProtoBuf.ProtoMember(1, Name = @"raw_source")] [global::System.ComponentModel.DefaultValue("")] @@ -1598,45 +1592,65 @@ public partial class FunctionInfo : global::ProtoBuf.IExtensible [global::ProtoBuf.ProtoMember(2, Name = @"clean_function")] [global::System.ComponentModel.DefaultValue("")] - public string CleanFunction { get; set; } = ""; + public string CleanFunction { + get; set; + } = ""; [global::ProtoBuf.ProtoMember(3, Name = @"docstring")] [global::System.ComponentModel.DefaultValue("")] - public string Docstring { get; set; } = ""; + public string Docstring { + get; set; + } = ""; [global::ProtoBuf.ProtoMember(4, Name = @"node_name")] [global::System.ComponentModel.DefaultValue("")] - public string NodeName { get; set; } = ""; + public string NodeName { + get; set; + } = ""; [global::ProtoBuf.ProtoMember(5, Name = @"params")] [global::System.ComponentModel.DefaultValue("")] - public string Params { get; set; } = ""; + public string Params { + get; set; + } = ""; [global::ProtoBuf.ProtoMember(6, Name = @"definition_line")] - public int DefinitionLine { get; set; } + public int DefinitionLine { + get; set; + } [global::ProtoBuf.ProtoMember(7, Name = @"start_line")] - public int StartLine { get; set; } + public int StartLine { + get; set; + } [global::ProtoBuf.ProtoMember(8, Name = @"end_line")] - public int EndLine { get; set; } + public int EndLine { + get; set; + } [global::ProtoBuf.ProtoMember(9, Name = @"start_col")] - public int StartCol { get; set; } + public int StartCol { + get; set; + } [global::ProtoBuf.ProtoMember(10, Name = @"end_col")] - public int EndCol { get; set; } + public int EndCol { + get; set; + } [global::ProtoBuf.ProtoMember(11, Name = @"leading_whitespace")] [global::System.ComponentModel.DefaultValue("")] - public string LeadingWhitespace { get; set; } = ""; + public string LeadingWhitespace { + get; set; + } = ""; [global::ProtoBuf.ProtoMember(12, Name = @"language")] - public Language Language { get; set; } - + public Language Language { + get; set; + } } - [global::ProtoBuf.ProtoContract()] public partial class IntentFunctionDocstring : global::ProtoBuf.IExtensible { @@ -1655,8 +1669,7 @@ public Language language { [global::ProtoBuf.ProtoMember(3)] [global::System.ComponentModel.DefaultValue("")] - public string file_path - { + public string file_path { get; set; } = ""; @@ -1685,8 +1698,7 @@ public Language language { [global::ProtoBuf.ProtoMember(3)] [global::System.ComponentModel.DefaultValue("")] - public string file_path - { + public string file_path { get; set; } = ""; @@ -1721,8 +1733,7 @@ public Language language { [global::ProtoBuf.ProtoMember(3)] [global::System.ComponentModel.DefaultValue("")] - public string file_path - { + public string file_path { get; set; } = ""; @@ -1784,8 +1795,7 @@ public Language language { [global::ProtoBuf.ProtoMember(3)] [global::System.ComponentModel.DefaultValue("")] - public string file_path - { + public string file_path { get; set; } = ""; @@ -1867,8 +1877,7 @@ public Language language { [global::ProtoBuf.ProtoMember(5)] [global::System.ComponentModel.DefaultValue("")] - public string file_path - { + public string file_path { get; set; } = ""; @@ -1903,8 +1912,7 @@ public Language language { [global::ProtoBuf.ProtoMember(3)] [global::System.ComponentModel.DefaultValue("")] - public string file_path - { + public string file_path { get; set; } = ""; @@ -1938,8 +1946,7 @@ public Language language { [global::ProtoBuf.ProtoMember(3)] [global::System.ComponentModel.DefaultValue("")] - public string file_path - { + public string file_path { get; set; } = ""; @@ -1954,55 +1961,81 @@ public string uri { public partial class ClassInfo : global::ProtoBuf.IExtensible { private global::ProtoBuf.IExtension __pbn__extensionData; - global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing) - => global::ProtoBuf.Extensible.GetExtensionObject(ref __pbn__extensionData, createIfMissing); + global::ProtoBuf.IExtension + global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing) => + global::ProtoBuf.Extensible.GetExtensionObject(ref __pbn__extensionData, createIfMissing); [global::ProtoBuf.ProtoMember(1, Name = @"raw_source")] [global::System.ComponentModel.DefaultValue("")] public string RawSource { get; set; } = ""; [global::ProtoBuf.ProtoMember(2, Name = @"start_line")] - public int StartLine { get; set; } + public int StartLine { + get; set; + } [global::ProtoBuf.ProtoMember(3, Name = @"end_line")] - public int EndLine { get; set; } + public int EndLine { + get; set; + } [global::ProtoBuf.ProtoMember(4, Name = @"start_col")] - public int StartCol { get; set; } + public int StartCol { + get; set; + } [global::ProtoBuf.ProtoMember(5, Name = @"end_col")] - public int EndCol { get; set; } + public int EndCol { + get; set; + } [global::ProtoBuf.ProtoMember(6, Name = @"leading_whitespace")] [global::System.ComponentModel.DefaultValue("")] - public string LeadingWhitespace { get; set; } = ""; + public string LeadingWhitespace { + get; set; + } = ""; [global::ProtoBuf.ProtoMember(7, Name = @"fields_and_constructors")] - public global::System.Collections.Generic.List FieldsAndConstructors { get; } = new global::System.Collections.Generic.List(); + public global::System.Collections.Generic.List FieldsAndConstructors { + get; + } = new global::System.Collections.Generic.List(); [global::ProtoBuf.ProtoMember(8, Name = @"docstring")] [global::System.ComponentModel.DefaultValue("")] - public string Docstring { get; set; } = ""; + public string Docstring { + get; set; + } = ""; [global::ProtoBuf.ProtoMember(9, Name = @"node_name")] [global::System.ComponentModel.DefaultValue("")] - public string NodeName { get; set; } = ""; + public string NodeName { + get; set; + } = ""; [global::ProtoBuf.ProtoMember(10, Name = @"methods")] - public global::System.Collections.Generic.List Methods { get; } = new global::System.Collections.Generic.List(); + public global::System.Collections.Generic.List Methods { + get; + } = new global::System.Collections.Generic.List(); [global::ProtoBuf.ProtoMember(11, Name = @"node_lineage")] - public global::System.Collections.Generic.List NodeLineages { get; } = new global::System.Collections.Generic.List(); + public global::System.Collections.Generic.List NodeLineages { + get; + } = new global::System.Collections.Generic.List(); [global::ProtoBuf.ProtoMember(12, Name = @"is_exported")] - public bool IsExported { get; set; } + public bool IsExported { + get; set; + } [global::ProtoBuf.ProtoMember(13, Name = @"language")] - public Language Language { get; set; } + public Language Language { + get; set; + } [global::ProtoBuf.ProtoMember(14, Name = @"definition_line")] - public int DefinitionLine { get; set; } - + public int DefinitionLine { + get; set; + } } [global::ProtoBuf.ProtoContract()] @@ -2067,14 +2100,13 @@ public partial class ChatMessageActionEdit : global::ProtoBuf.IExtensible [global::ProtoBuf.ProtoMember(1)] [global::System.ComponentModel.DefaultValue("")] - public string file_path - { - get; set; - } = ""; + public string file_path { get; set; } = ""; [global::ProtoBuf.ProtoMember(6)] [global::System.ComponentModel.DefaultValue("")] - public string uri { get; set; } = ""; + public string uri { + get; set; + } = ""; [global::ProtoBuf.ProtoMember(2)] public DiffBlock diff { @@ -2273,7 +2305,9 @@ public partial class OpenFilePointer : global::ProtoBuf.IExtensible [global::ProtoBuf.ProtoMember(6)] [global::System.ComponentModel.DefaultValue("")] - public string file_uri { get; set; } = ""; + public string file_uri { + get; set; + } = ""; [global::ProtoBuf.ProtoMember(2)] public int start_line { @@ -2341,8 +2375,7 @@ public partial class ApplyDiff : global::ProtoBuf.IExtensible [global::ProtoBuf.ProtoMember(2)] [global::System.ComponentModel.DefaultValue("")] - public string file_path - { + public string file_path { get; set; } = ""; @@ -2714,49 +2747,52 @@ public partial class AddTrackedWorkspaceResponse : global::ProtoBuf.IExtensible public partial class GetFunctionsRequest : global::ProtoBuf.IExtensible { private global::ProtoBuf.IExtension __pbn__extensionData; - global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing) - => global::ProtoBuf.Extensible.GetExtensionObject(ref __pbn__extensionData, createIfMissing); + global::ProtoBuf.IExtension + global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing) => + global::ProtoBuf.Extensible.GetExtensionObject(ref __pbn__extensionData, createIfMissing); [global::ProtoBuf.ProtoMember(1, Name = @"document")] public Document document { get; set; } - } [global::ProtoBuf.ProtoContract()] public partial class GetFunctionsResponse : global::ProtoBuf.IExtensible { private global::ProtoBuf.IExtension __pbn__extensionData; - global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing) - => global::ProtoBuf.Extensible.GetExtensionObject(ref __pbn__extensionData, createIfMissing); + global::ProtoBuf.IExtension + global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing) => + global::ProtoBuf.Extensible.GetExtensionObject(ref __pbn__extensionData, createIfMissing); [global::ProtoBuf.ProtoMember(1, Name = @"function_captures")] - public global::System.Collections.Generic.List FunctionCaptures { get; } = new global::System.Collections.Generic.List(); - + public global::System.Collections.Generic.List FunctionCaptures { + get; + } = new global::System.Collections.Generic.List(); } - [global::ProtoBuf.ProtoContract()] public partial class GetClassInfosRequest : global::ProtoBuf.IExtensible { private global::ProtoBuf.IExtension __pbn__extensionData; - global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing) - => global::ProtoBuf.Extensible.GetExtensionObject(ref __pbn__extensionData, createIfMissing); + global::ProtoBuf.IExtension + global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing) => + global::ProtoBuf.Extensible.GetExtensionObject(ref __pbn__extensionData, createIfMissing); [global::ProtoBuf.ProtoMember(1, Name = @"document")] public Document document { get; set; } - } [global::ProtoBuf.ProtoContract()] public partial class GetClassInfosResponse : global::ProtoBuf.IExtensible { private global::ProtoBuf.IExtension __pbn__extensionData; - global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing) - => global::ProtoBuf.Extensible.GetExtensionObject(ref __pbn__extensionData, createIfMissing); + global::ProtoBuf.IExtension + global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing) => + global::ProtoBuf.Extensible.GetExtensionObject(ref __pbn__extensionData, createIfMissing); [global::ProtoBuf.ProtoMember(1, Name = @"class_captures")] - public global::System.Collections.Generic.List ClassCaptures { get; } = new global::System.Collections.Generic.List(); - + public global::System.Collections.Generic.List ClassCaptures { + get; + } = new global::System.Collections.Generic.List(); } [global::ProtoBuf.ProtoContract()] diff --git a/CodeiumVS/SettingsPage.cs b/CodeiumVS/SettingsPage.cs index 257d214..ac0ec64 100644 --- a/CodeiumVS/SettingsPage.cs +++ b/CodeiumVS/SettingsPage.cs @@ -48,7 +48,9 @@ public string PortalUrl [Category("Windsurf")] [DisplayName("Language Server Download URL")] [Description( - "If you're experiencing network issues with GitHub and can't download the language server, please change this to a GitHub Mirror URL instead. For example: https://gh.api.99988866.xyz/https://github.com/Exafunction/codeium/releases/download")] + "If you're experiencing network issues with GitHub and can't download the language " + + "server, please change this to a GitHub Mirror URL instead. For example: " + + "https://gh.api.99988866.xyz/https://github.com/Exafunction/codeium/releases/download")] public string ExtensionBaseUrl { get { @@ -90,20 +92,18 @@ public bool EnableCommentCompletion [Description("AI-powered inline action buttons in your editor. (Reload Required)")] public bool EnableCodeLens { - get - { + get { return enableCodeLens; } - set - { + set { enableCodeLens = value; } } [Category("Windsurf")] [DisplayName("Enable language server proxy")] - [Description( - "If you're experiencing network issues with the language server, we recommend enabling this option and using a VPN to resolve the issue. Requires restart.")] + [Description("If you're experiencing network issues with the language server, we recommend " + + "enabling this option and using a VPN to resolve the issue. Requires restart.")] public bool EnableLanguageServerProxy { get { @@ -117,7 +117,8 @@ public bool EnableLanguageServerProxy [Category("Windsurf")] [DisplayName("Enable Windsurf Indexing")] [Description( - "Allows Windsurf to index your current repository and provide better chat and autocomplete responses based on relevant parts of your codebase. Requires restart.")] + "Allows Windsurf to index your current repository and provide better chat and " + + "autocomplete responses based on relevant parts of your codebase. Requires restart.")] public bool EnableIndexing { get { @@ -130,8 +131,8 @@ public bool EnableIndexing [Category("Windsurf")] [DisplayName("Indexing Max Workspace Size (File Count)")] - [Description( - "If indexing is enabled, we will only attempt to index workspaces that have up to this many files. This file count ignores .gitignore and binary files.")] + [Description("If indexing is enabled, we will only attempt to index workspaces that have up " + + "to this many files. This file count ignores .gitignore and binary files.")] public int IndexingMaxWorkspaceSize { get { @@ -144,8 +145,8 @@ public int IndexingMaxWorkspaceSize [Category("Windsurf")] [DisplayName("Directories to Index List Path")] - [Description( - "Absolute path to a .txt file that contains a line separated list of absolute paths of directories to index. Requires restart.")] + [Description("Absolute path to a .txt file that contains a line separated list of absolute " + + "paths of directories to index. Requires restart.")] public string IndexingFilesListPath { get { @@ -157,16 +158,14 @@ public string IndexingFilesListPath } [Category("Windsurf")] [DisplayName("Index Open Files")] - [Description( - "Windsurf will attempt to parse the project files that the files open upon IDE startup belong to. Requires restart.")] + [Description("Windsurf will attempt to parse the project files that the files open upon IDE " + + "startup belong to. Requires restart.")] public bool IndexOpenFiles { - get - { + get { return indexOpenFiles; } - set - { + set { indexOpenFiles = value; } } diff --git a/CodeiumVS/SuggestionUI/InlineGreyTextTagger.cs b/CodeiumVS/SuggestionUI/InlineGreyTextTagger.cs index 53082f4..f6ff915 100644 --- a/CodeiumVS/SuggestionUI/InlineGreyTextTagger.cs +++ b/CodeiumVS/SuggestionUI/InlineGreyTextTagger.cs @@ -72,11 +72,12 @@ public void MarkDirty() var endLine = view.TextSnapshot.GetLineFromPosition(changeEnd); var span = new SnapshotSpan(startLine.Start, endLine.EndIncludingLineBreak) - .TranslateTo(targetSnapshot: view.TextBuffer.CurrentSnapshot, + .TranslateTo(targetSnapshot: view.TextBuffer.CurrentSnapshot, SpanTrackingMode.EdgePositive); TagsChanged(this, new SnapshotSpanEventArgs(new SnapshotSpan(span.Start, span.End))); - } catch (Exception e) + } + catch (Exception e) { Debug.Write(e); } diff --git a/CodeiumVS/SuggestionUI/StringCompare.cs b/CodeiumVS/SuggestionUI/StringCompare.cs index 7511ca2..d9971d0 100644 --- a/CodeiumVS/SuggestionUI/StringCompare.cs +++ b/CodeiumVS/SuggestionUI/StringCompare.cs @@ -88,9 +88,11 @@ public static int CheckSuggestion(String suggestion, String line, bool isTextIns return res.Item1 >= endPoint ? res.Item2 : -1; } } - - private static readonly System.Text.RegularExpressions.Regex newLineMatcher = new System.Text.RegularExpressions.Regex(@"(?:\r\n|\n|\r)", - System.Text.RegularExpressions.RegexOptions.Compiled | System.Text.RegularExpressions.RegexOptions.Singleline); + + private static readonly System.Text.RegularExpressions.Regex newLineMatcher = + new System.Text.RegularExpressions.Regex( + @"(?:\r\n|\n|\r)", System.Text.RegularExpressions.RegexOptions.Compiled | + System.Text.RegularExpressions.RegexOptions.Singleline); /// /// Returns the index of the first new line in the string, or -1 if not found @@ -100,10 +102,9 @@ public static int IndexOfNewLine(string text) { System.Text.RegularExpressions.Match newLineMatch = newLineMatcher.Match(text); - if (newLineMatch.Success) - return newLineMatch.Index; + if (newLineMatch.Success) return newLineMatch.Index; return -1; } - } +} } diff --git a/CodeiumVS/SuggestionUI/SuggestionTagger.cs b/CodeiumVS/SuggestionUI/SuggestionTagger.cs index 220a5bc..eaa3c36 100644 --- a/CodeiumVS/SuggestionUI/SuggestionTagger.cs +++ b/CodeiumVS/SuggestionUI/SuggestionTagger.cs @@ -70,7 +70,8 @@ public bool SetSuggestion(String newSuggestion, int caretPoint) { try { - // If this isn't the most up-to-date version of the buffer, then ignore it for now (we'll + // If this isn't the most up-to-date version of the buffer, then ignore it for now + // (we'll newSuggestion = newSuggestion.TrimEnd(); newSuggestion = newSuggestion.Replace("\r", ""); ClearSuggestion(); @@ -110,7 +111,8 @@ public bool SetSuggestion(String newSuggestion, int caretPoint) var suggestionLines = combineSuggestion.Split('\n'); suggestion = new Tuple(combineSuggestion, suggestionLines); return Update(); - }catch (Exception ex) + } + catch (Exception ex) { CodeiumVSPackage.Instance?.LogAsync("Exception: " + ex.ToString()); return false; @@ -194,8 +196,8 @@ void BufferChanged(object sender, TextContentChangedEventArgs e) { try { - // If this isn't the most up-to-date version of the buffer, then ignore it for now (we'll - // eventually get another change event). + // If this isn't the most up-to-date version of the buffer, then ignore it for now + // (we'll eventually get another change event). if (e.After != buffer.CurrentSnapshot) return; this.Update(); } @@ -281,7 +283,7 @@ void AddInsertionTextBlock(int start, int end, string line) public void UpdateAdornment(IWpfTextView view, string userText, int suggestionStart) { try - { + { stackPanel.Children.Clear(); var inlineTagger = GetTagger(); if (inlineTagger == null) { return; } @@ -296,7 +298,8 @@ public void UpdateAdornment(IWpfTextView view, string userText, int suggestionSt if (isTextInsertion && suggestionIndex < userIndex) { - if (suggestionIndex > 0 && suggestionIndex < line.Length && char.IsWhiteSpace(line[suggestionIndex - 1]) && + if (suggestionIndex > 0 && suggestionIndex < line.Length && + char.IsWhiteSpace(line[suggestionIndex - 1]) && userText.Length > insertionPoint + 1 && !char.IsWhiteSpace(userText[userText.Length - insertionPoint - 1])) { @@ -331,21 +334,23 @@ public void UpdateAdornment(IWpfTextView view, string userText, int suggestionSt this.adornmentLayer.RemoveAllAdornments(); - // usually only happens the moment a bunch of text has rentered such as an undo operation - ITextSnapshotLine snapshotLine = - view.TextSnapshot.GetLineFromLineNumber(currentTextLineN); - var start = view.TextViewLines.GetCharacterBounds(snapshotLine.Start); + // usually only happens the moment a bunch of text has rentered such as an undo + // operation + ITextSnapshotLine snapshotLine = + view.TextSnapshot.GetLineFromLineNumber(currentTextLineN); + var start = view.TextViewLines.GetCharacterBounds(snapshotLine.Start); - // Place the image in the top left hand corner of the line - Canvas.SetLeft(stackPanel, start.Left); - Canvas.SetTop(stackPanel, start.TextTop); - var span = snapshotLine.Extent; - // Add the image to the adornment layer and make it relative to the viewport - this.adornmentLayer.AddAdornment( - AdornmentPositioningBehavior.TextRelative, span, null, stackPanel, null); + // Place the image in the top left hand corner of the line + Canvas.SetLeft(stackPanel, start.Left); + Canvas.SetTop(stackPanel, start.TextTop); + var span = snapshotLine.Extent; + // Add the image to the adornment layer and make it relative to the viewport + this.adornmentLayer.AddAdornment( + AdornmentPositioningBehavior.TextRelative, span, null, stackPanel, null); } catch (Exception e) - { Debug.Write(e); + { + Debug.Write(e); } } @@ -362,7 +367,8 @@ private void OnSizeChanged(object sender, EventArgs e) FormatText(block); } - ITextSnapshotLine snapshotLine = view.TextSnapshot.GetLineFromLineNumber(currentTextLineN); + ITextSnapshotLine snapshotLine = + view.TextSnapshot.GetLineFromLineNumber(currentTextLineN); var start = view.TextViewLines.GetCharacterBounds(snapshotLine.Start); @@ -447,16 +453,13 @@ public bool CompleteText() { try { - if (!showSuggestion || suggestion == null) - { - return false; - } + if (!showSuggestion || suggestion == null) { return false; } String untrimLine = this.snapshot.GetLineFromLineNumber(currentTextLineN).GetText(); String line = untrimLine.Trim(); - int suggestionLineN = - StringCompare.CheckSuggestion(suggestion.Item1, line, isTextInsertion, insertionPoint); + int suggestionLineN = StringCompare.CheckSuggestion( + suggestion.Item1, line, isTextInsertion, insertionPoint); if (suggestionLineN >= 0) { int diff = untrimLine.Length - untrimLine.TrimStart().Length; @@ -465,7 +468,6 @@ public bool CompleteText() ReplaceText(whitespace + suggestion.Item1, currentTextLineN); return true; } - } catch (Exception e) { @@ -529,11 +531,9 @@ public void ClearSuggestion() showSuggestion = false; MarkDirty(); - } catch (Exception ex) { - } } @@ -558,12 +558,16 @@ void MarkDirty() var endLine = view.TextSnapshot.GetLineFromPosition(changeEnd); var span = new SnapshotSpan(startLine.Start, endLine.EndIncludingLineBreak) - .TranslateTo(targetSnapshot: newSnapshot, SpanTrackingMode.EdgePositive); + .TranslateTo(targetSnapshot: newSnapshot, SpanTrackingMode.EdgePositive); // lines we are marking dirty // currently all of them for simplicity if (this.TagsChanged != null) { TagsChanged(this, new SnapshotSpanEventArgs(span)); } - } catch (Exception e) { Debug.Write(e); } + } + catch (Exception e) + { + Debug.Write(e); + } } } diff --git a/CodeiumVS/SuggestionUI/TextViewListener.cs b/CodeiumVS/SuggestionUI/TextViewListener.cs index 61bc2bf..7e8f988 100644 --- a/CodeiumVS/SuggestionUI/TextViewListener.cs +++ b/CodeiumVS/SuggestionUI/TextViewListener.cs @@ -48,34 +48,28 @@ internal class CodeiumCompletionHandler : IOleCommandTarget, IDisposable private List> suggestions; private int suggestionIndex; private Command CompleteSuggestionCommand; - [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)] + [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)] public static extern short GetAsyncKeyState(Int32 keyCode); public async void GetCompletion() { try { - if (_document == null || !package.IsSignedIn()) - { - return; - } + if (_document == null || !package.IsSignedIn()) { return; } UpdateRequestTokenSource(new CancellationTokenSource()); SnapshotPoint? caretPoint = _view.Caret.Position.Point.GetPoint( textBuffer => (!textBuffer.ContentType.IsOfType("projection")), PositionAffinity.Successor); - if (!caretPoint.HasValue) - { - return; - } + if (!caretPoint.HasValue) { return; } var caretPosition = caretPoint.Value.Position; string text = _document.TextBuffer.CurrentSnapshot.GetText(); int cursorPosition = _document.Encoding.IsSingleByte - ? caretPosition - : Utf16OffsetToUtf8Offset(text, caretPosition); + ? caretPosition + : Utf16OffsetToUtf8Offset(text, caretPosition); if (cursorPosition > text.Length) { @@ -100,10 +94,7 @@ public async void GetCompletion() String line = _view.TextBuffer.CurrentSnapshot.GetLineFromLineNumber(lineN).GetText(); Debug.Print("completions " + list.Count.ToString()); - if (res != VSConstants.S_OK) - { - return; - } + if (res != VSConstants.S_OK) { return; } if (list != null && list.Count > 0) { @@ -123,7 +114,6 @@ public async void GetCompletion() await package.LogAsync("Generated " + list.Count + $" proposals"); } - } catch (Exception ex) { @@ -159,8 +149,7 @@ List> ParseCompletion(IList comple { int endNewline = StringCompare.IndexOfNewLine(end); - if (endNewline <= -1) - endNewline = end.Length; + if (endNewline <= -1) endNewline = end.Length; completionText = completionText + end.Substring(0, endNewline); } @@ -172,20 +161,19 @@ List> ParseCompletion(IList comple var set = new Tuple(completionText, completionID); // Filter out completions that don't match the current intellisense prefix - ICompletionSession session = m_provider.CompletionBroker.GetSessions(_view).FirstOrDefault(); + ICompletionSession session = + m_provider.CompletionBroker.GetSessions(_view).FirstOrDefault(); if (session != null && session.SelectedCompletionSet != null) { var completion = session.SelectedCompletionSet.SelectionStatus.Completion; if (completion == null) { continue; } string intellisenseSuggestion = completion.InsertionText; ITrackingSpan intellisenseSpan = session.SelectedCompletionSet.ApplicableTo; - SnapshotSpan span = intellisenseSpan.GetSpan(intellisenseSpan.TextBuffer.CurrentSnapshot); + SnapshotSpan span = + intellisenseSpan.GetSpan(intellisenseSpan.TextBuffer.CurrentSnapshot); if (span.Length > intellisenseSuggestion.Length) { continue; } string intellisenseInsertion = intellisenseSuggestion.Substring(span.Length); - if (!completionText.StartsWith(intellisenseInsertion)) - { - continue; - } + if (!completionText.StartsWith(intellisenseInsertion)) { continue; } } list.Add(set); } @@ -205,10 +193,7 @@ public static async Task GetCommandsAsync(String name) foreach (Command command in dte.Commands) { - if (string.IsNullOrEmpty(command.Name)) - { - continue; - } + if (string.IsNullOrEmpty(command.Name)) { continue; } if (command.Name.Contains(name) && command.Bindings is object[] bindings) { @@ -216,10 +201,7 @@ public static async Task GetCommandsAsync(String name) } } - if (items.Count > 0) - { - return items[0]; - } + if (items.Count > 0) { return items[0]; } } catch (Exception ex) { @@ -241,10 +223,7 @@ private void OnSuggestionAccepted(String proposalId) .FireAndForget(true); } - public LangInfo GetLanguage() - { - return _language; - } + public LangInfo GetLanguage() { return _language; } private void UpdateRequestTokenSource(CancellationTokenSource newSource) { @@ -268,7 +247,7 @@ public static int Utf8OffsetToUtf16Offset(string str, int utf8Offset) } internal CodeiumCompletionHandler(IVsTextView textViewAdapter, ITextView view, - TextViewListener provider) + TextViewListener provider) { try { @@ -286,7 +265,8 @@ internal CodeiumCompletionHandler(IVsTextView textViewAdapter, ITextView view, if (_document != null) { - CodeiumVSPackage.Instance.LogAsync("CodeiumCompletionHandler filepath = " + _document.FilePath); + CodeiumVSPackage.Instance.LogAsync("CodeiumCompletionHandler filepath = " + + _document.FilePath); if (!provider.documentDictionary.ContainsKey(_document.FilePath.ToLower())) { @@ -306,17 +286,17 @@ internal CodeiumCompletionHandler(IVsTextView textViewAdapter, ITextView view, view.Caret.PositionChanged += CaretUpdate; _ = Task.Run(() => - { - try - { - CompleteSuggestionCommand = GetCommandsAsync("CodeiumAcceptCompletion").Result; - } - catch (Exception e) - { - Debug.Write(e); - } - }); - + { + try + { + CompleteSuggestionCommand = + GetCommandsAsync("CodeiumAcceptCompletion").Result; + } + catch (Exception e) + { + Debug.Write(e); + } + }); } catch (Exception ex) { @@ -329,32 +309,24 @@ private void CaretUpdate(object sender, CaretPositionChangedEventArgs e) try { var tagger = GetTagger(); - if (tagger == null) - { - return; - } + if (tagger == null) { return; } - if (CompleteSuggestionCommand != null && CompleteSuggestionCommand.Bindings is object[] bindings && - bindings.Length > 0) + if (CompleteSuggestionCommand != null && + CompleteSuggestionCommand.Bindings is object[] bindings && bindings.Length > 0) { tagger.ClearSuggestion(); return; } var key = GetAsyncKeyState(0x09); - if ((0x8000 & key) > 0) - { - CompleteSuggestion(false); - } - else if (!tagger.OnSameLine()) - { - tagger.ClearSuggestion(); - } + if ((0x8000 & key) > 0) { CompleteSuggestion(false); } + else if (!tagger.OnSameLine()) { tagger.ClearSuggestion(); } } catch (Exception ex) { ThreadHelper.JoinableTaskFactory - .RunAsync(async delegate { await CodeiumVSPackage.Instance.LogAsync(ex.ToString()); }) + .RunAsync( + async delegate { await CodeiumVSPackage.Instance.LogAsync(ex.ToString()); }) .FireAndForget(true); } } @@ -376,12 +348,11 @@ private void RefreshLanguage() if (_document != null) { _language = Mapper.GetLanguage(_document.TextBuffer.ContentType, - Path.GetExtension(_document.FilePath)?.Trim('.')); + Path.GetExtension(_document.FilePath)?.Trim('.')); } } catch (Exception ex) { - } } @@ -411,7 +382,8 @@ public async void ShowNextSuggestion() return; } - bool validSuggestion = tagger.SetSuggestion(suggestions[suggestionIndex].Item1, characterN); + bool validSuggestion = + tagger.SetSuggestion(suggestions[suggestionIndex].Item1, characterN); if (!validSuggestion) { suggestionIndex = oldSuggestion; @@ -424,10 +396,10 @@ public async void ShowNextSuggestion() catch (Exception ex) { ThreadHelper.JoinableTaskFactory - .RunAsync(async delegate { await CodeiumVSPackage.Instance.LogAsync(ex.ToString()); }) + .RunAsync( + async delegate { await CodeiumVSPackage.Instance.LogAsync(ex.ToString()); }) .FireAndForget(true); } - } public bool CompleteSuggestion(bool checkLine = true) @@ -435,7 +407,8 @@ public bool CompleteSuggestion(bool checkLine = true) var tagger = GetTagger(); if (tagger != null) { - if (tagger.IsSuggestionActive() && (tagger.OnSameLine() || !checkLine) && tagger.CompleteText()) + if (tagger.IsSuggestionActive() && (tagger.OnSameLine() || !checkLine) && + tagger.CompleteText()) { ClearCompletionSessions(); OnSuggestionAccepted(currentCompletionID); @@ -504,7 +477,8 @@ void ShowIntellicodeMsg() { VsShellUtilities.ShowMessageBox( this.package, - "Please disable IntelliCode to use Codeium. You can access Intellicode settings via Tools --> Options --> Intellicode.", + "Please disable IntelliCode to use Codeium. You can access Intellicode settings " + + "via Tools --> Options --> Intellicode.", "Disable IntelliCode", OLEMSGICON.OLEMSGICON_INFO, OLEMSGBUTTON.OLEMSGBUTTON_OK, @@ -513,18 +487,17 @@ void ShowIntellicodeMsg() } public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, - IntPtr pvaOut) - { + IntPtr pvaOut) + { _textViewAdapter.RemoveCommandFilter(this); _textViewAdapter.AddCommandFilter(this, out m_nextCommandHandler); - + // let the other handlers handle automation functions if (VsShellUtilities.IsInAutomationFunction(m_provider.ServiceProvider)) { return m_nextCommandHandler.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); } - // check for a commit character bool regenerateSuggestion = false; if (!hasCompletionUpdated && nCmdID == (uint)VSConstants.VSStd2KCmdID.TAB) @@ -535,18 +508,20 @@ public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pv if (bindings == null || bindings.Length <= 0) { var tagger = GetTagger(); - if (tagger == null) { return m_nextCommandHandler.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); } + if (tagger == null) + { + return m_nextCommandHandler.Exec( + ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); + } - ICompletionSession session = m_provider.CompletionBroker.GetSessions(_view).FirstOrDefault(); + ICompletionSession session = + m_provider.CompletionBroker.GetSessions(_view).FirstOrDefault(); if (session != null && session.SelectedCompletionSet != null) { tagger.ClearSuggestion(); regenerateSuggestion = true; } - else if (CompleteSuggestion()) - { - return VSConstants.S_OK; - } + else if (CompleteSuggestion()) { return VSConstants.S_OK; } } } } @@ -576,19 +551,20 @@ public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pv if (hasCompletionUpdated) { ClearSuggestion(); } // gets lsp completions on added character or deletions - if (!typedChar.Equals(char.MinValue) || commandID == (uint)VSConstants.VSStd2KCmdID.RETURN || regenerateSuggestion) + if (!typedChar.Equals(char.MinValue) || + commandID == (uint)VSConstants.VSStd2KCmdID.RETURN || regenerateSuggestion) { _ = Task.Run(() => - { - try - { - GetCompletion(); - } - catch (Exception e) - { - Debug.Write(e); - } - }); + { + try + { + GetCompletion(); + } + catch (Exception e) + { + Debug.Write(e); + } + }); handled = true; } else if (commandID == (uint)VSConstants.VSStd2KCmdID.BACKSPACE || @@ -597,16 +573,16 @@ public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pv ClearSuggestion(); _ = Task.Run(() => - { - try - { - GetCompletion(); - } - catch (Exception e) - { - Debug.Write(e); - } - }); + { + try + { + GetCompletion(); + } + catch (Exception e) + { + Debug.Write(e); + } + }); handled = true; } @@ -619,7 +595,8 @@ public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pv public int QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText) { - //package.LogAsync("QueeryStatus " + cCmds + " prgCmds = " + prgCmds + "pcmdText " + pCmdText); + // package.LogAsync("QueeryStatus " + cCmds + " prgCmds = " + prgCmds + "pcmdText " + + // pCmdText); return m_nextCommandHandler.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText); } @@ -665,7 +642,8 @@ internal ICompletionBroker CompletionBroker { internal static TextViewListener? Instance { get; private set; } - public Dictionary documentDictionary = new Dictionary(); + public Dictionary documentDictionary = + new Dictionary(); public void VsTextViewCreated(IVsTextView textViewAdapter) { Instance = this; @@ -676,7 +654,8 @@ public void VsTextViewCreated(IVsTextView textViewAdapter) { return new CodeiumCompletionHandler(textViewAdapter, textView, this); }; - textView.TextBuffer.Properties.GetOrCreateSingletonProperty(typeof(CodeiumCompletionHandler), createCommandHandler); + textView.TextBuffer.Properties.GetOrCreateSingletonProperty( + typeof(CodeiumCompletionHandler), createCommandHandler); } } } diff --git a/CodeiumVS/Utilities/FileUtilities.cs b/CodeiumVS/Utilities/FileUtilities.cs index 964f53f..6027c5e 100644 --- a/CodeiumVS/Utilities/FileUtilities.cs +++ b/CodeiumVS/Utilities/FileUtilities.cs @@ -53,31 +53,28 @@ internal static void DeleteSafe(string path) /// For example, given ["E:/a/b/c.txt", "E:/a/b/d/e.cpp"], returns ["E:/a/b"] /// /// List of absolute file paths - /// List of directory paths that collectively contain all input files with minimum redundancy + /// List of directory paths that collectively contain all input files with minimum + /// redundancy internal static List FindMinimumEncompassingDirectories(IEnumerable filePaths) { - if (filePaths == null || !filePaths.Any()) - return new List(); + if (filePaths == null || !filePaths.Any()) return new List(); // Get the directory paths of the file paths var directoryPaths = filePaths.Select(Path.GetDirectoryName).Distinct().ToList(); - CodeiumVSPackage.Instance?.Log($"Directories before minimization: {string.Join(", ", directoryPaths)}"); + CodeiumVSPackage.Instance?.Log( + $"Directories before minimization: {string.Join(", ", directoryPaths)}"); var result = GetMinimumDirectoryCover(directoryPaths); - CodeiumVSPackage.Instance?.Log($"Directories after minimization: {string.Join(", ", result)}"); + CodeiumVSPackage.Instance?.Log( + $"Directories after minimization: {string.Join(", ", result)}"); return result.Where(dir => CountPathSegments(dir) > 1).ToList(); } - public static List GetMinimumDirectoryCover(IEnumerable directories) { // 1. Normalize all paths to full/absolute paths and remove duplicates - var normalizedDirs = directories - .Select(d => NormalizePath(d)) - .Distinct() - .ToList(); + var normalizedDirs = directories.Select(d => NormalizePath(d)).Distinct().ToList(); // 2. Sort by ascending number of path segments (shallow first) - normalizedDirs.Sort((a, b) => - CountPathSegments(a).CompareTo(CountPathSegments(b))); + normalizedDirs.Sort((a, b) => CountPathSegments(a).CompareTo(CountPathSegments(b))); var coverSet = new List(); @@ -97,43 +94,41 @@ public static List GetMinimumDirectoryCover(IEnumerable director } // If not covered, add it to the cover set - if (!isCovered) - { - coverSet.Add(dir); - } + if (!isCovered) { coverSet.Add(dir); } } return coverSet; } - /// + /// /// Checks if 'child' is the same or a subdirectory of 'parent'. /// private static bool IsSubdirectoryOrSame(string parent, string child) { // 1. Normalize both directories to their full path (remove extra slashes, etc.). - string parentFull = Path.GetFullPath(parent) - .TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); - string childFull = Path.GetFullPath(child) - .TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); - - // 2. Append a directory separator at the end of each path to ensure - // that "C:\Folder" won’t incorrectly match "C:\Folder2". - // e.g. "C:\Folder" -> "C:\Folder\" - parentFull += Path.DirectorySeparatorChar; - childFull += Path.DirectorySeparatorChar; - - // 3. On Windows, paths are case-insensitive. Use OrdinalIgnoreCase - // to compare. On non-Windows systems, consider using Ordinal. - return childFull.StartsWith(parentFull, StringComparison.OrdinalIgnoreCase); -} + string parentFull = Path.GetFullPath(parent).TrimEnd(Path.DirectorySeparatorChar, + Path.AltDirectorySeparatorChar); + string childFull = Path.GetFullPath(child).TrimEnd(Path.DirectorySeparatorChar, + Path.AltDirectorySeparatorChar); + + // 2. Append a directory separator at the end of each path to ensure + // that "C:\Folder" won’t incorrectly match "C:\Folder2". + // e.g. "C:\Folder" -> "C:\Folder\" + parentFull += Path.DirectorySeparatorChar; + childFull += Path.DirectorySeparatorChar; + + // 3. On Windows, paths are case-insensitive. Use OrdinalIgnoreCase + // to compare. On non-Windows systems, consider using Ordinal. + return childFull.StartsWith(parentFull, StringComparison.OrdinalIgnoreCase); + } /// /// Normalize a directory path by getting its full path (removing trailing slash, etc). /// private static string NormalizePath(string path) { - return Path.GetFullPath(path).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); + return Path.GetFullPath(path).TrimEnd(Path.DirectorySeparatorChar, + Path.AltDirectorySeparatorChar); } /// @@ -143,6 +138,6 @@ private static string NormalizePath(string path) private static int CountPathSegments(string path) { return path.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) - .Count(segment => !string.IsNullOrEmpty(segment)); + .Count(segment => !string.IsNullOrEmpty(segment)); } } diff --git a/CodeiumVS/VSCommandTable.cs b/CodeiumVS/VSCommandTable.cs index 6e3afc2..6bc0c2d 100644 --- a/CodeiumVS/VSCommandTable.cs +++ b/CodeiumVS/VSCommandTable.cs @@ -40,6 +40,5 @@ internal sealed partial class PackageIds public const int ExplainSelectionCodeBlock = 0x0111; public const int GenerateSelectionFunctionDocstring = 0x0112; public const int DebugButton = 0x0600; - } } diff --git a/CodeiumVS/Windows/ChatToolWindow.cs b/CodeiumVS/Windows/ChatToolWindow.cs index 9dc70b1..af0765d 100644 --- a/CodeiumVS/Windows/ChatToolWindow.cs +++ b/CodeiumVS/Windows/ChatToolWindow.cs @@ -88,11 +88,9 @@ await VS.MessageBox.ShowErrorAsync( // add the info bar to notify the user when the webview failed to load var model = new InfoBarModel( - new[] { - new InfoBarTextSpan( - "It looks like Windsurf Chat is taking too long to load, do you want to reload? "), - new InfoBarHyperlink("Reload") - }, + new[] { new InfoBarTextSpan("It looks like Windsurf Chat is taking too long to load, " + + "do you want to reload? "), + new InfoBarHyperlink("Reload") }, KnownMonikers.IntellisenseWarning, true); @@ -160,7 +158,7 @@ public async Task ReloadAsync() string uriString = clientUrl + "?" + string.Join("&", data.Select((pair) => $"{pair.Key}={pair.Value}")); - + await package.LogAsync($"Chat page URL: {uriString}"); try @@ -207,7 +205,8 @@ private void WebView_OnGotFocus(object sender, System.Windows.RoutedEventArgs e) // focus the text input await webView.ExecuteScriptAsync( - "const editor = document.getElementsByClassName('ql-editor')[0]; if(editor) editor.focus()"); + "const editor = document.getElementsByClassName('ql-editor')[0]; if(editor) " + + "editor.focus()"); }) .FireAndForget(); } diff --git a/CodeiumVS/Windows/RefactorCodeDialogWindow.cs b/CodeiumVS/Windows/RefactorCodeDialogWindow.cs index 90ad99a..475ccbb 100644 --- a/CodeiumVS/Windows/RefactorCodeDialogWindow.cs +++ b/CodeiumVS/Windows/RefactorCodeDialogWindow.cs @@ -70,29 +70,30 @@ private void NewContext(Languages.LangInfo languageInfo) new RefactorData("Add logging statements so that it can be easily debugged", KnownMonikers.StartLogging), - new RefactorData( - "Add type annotations to the code", - KnownMonikers.NewType, - "Add type annotations to this code block, including the function arguments and return type." + - " Modify the docstring to reflect the types.", - [ - Packets.Language.LANGUAGE_CSHARP, - Packets.Language.LANGUAGE_TYPESCRIPT, - Packets.Language.LANGUAGE_PYTHON - ]), + new RefactorData("Add type annotations to the code", + KnownMonikers.NewType, + "Add type annotations to this code block, including the function " + + "arguments and return type." + + " Modify the docstring to reflect the types.", + [ + Packets.Language.LANGUAGE_CSHARP, + Packets.Language.LANGUAGE_TYPESCRIPT, + Packets.Language.LANGUAGE_PYTHON + ]), - new RefactorData( - "Clean up this code", - KnownMonikers.CleanData, - "Clean up this code by standardizing variable names, removing debugging statements, " + - "improving readability, and more. Explain what you did to clean it up in a short and concise way."), + new RefactorData("Clean up this code", + KnownMonikers.CleanData, + "Clean up this code by standardizing variable names, removing " + + "debugging statements, " + + "improving readability, and more. Explain what you did to clean " + + "it up in a short and concise way."), new RefactorData( "Check for bugs and null pointers", KnownMonikers.Spy, "Check for bugs such as null pointer references, unhandled exceptions, and more." + - " If you don't see anything obvious, reply that things look good and that the user" + - " can reply with a stack trace to get more information."), + " If you don't see anything obvious, reply that things look good and that " + + "the user" + " can reply with a stack trace to get more information."), new RefactorData("Implement the code for the TODO comment", KnownMonikers.ImplementInterface), diff --git a/CodeiumVS/codelensoop/CodeLensLogger.cs b/CodeiumVS/codelensoop/CodeLensLogger.cs index 39941f9..f75cc9d 100644 --- a/CodeiumVS/codelensoop/CodeLensLogger.cs +++ b/CodeiumVS/codelensoop/CodeLensLogger.cs @@ -9,35 +9,29 @@ namespace CodeiumVS { - public static class CodelensLogger - { - private static readonly object @lock = new object(); +public static class CodelensLogger +{ + private static readonly object @lock = new object(); - // Logs go to: C:\Users\\AppData\Local\Temp\codeium.codelens.log - private static readonly string clLogFile = $"{Path.GetTempPath()}/codeium.codelens.log"; + // Logs go to: C:\Users\\AppData\Local\Temp\codeium.codelens.log + private static readonly string clLogFile = $"{Path.GetTempPath()}/codeium.codelens.log"; - public static void LogCL( - object? data = null, - [CallerFilePath] string? file = null, - [CallerMemberName] string? method = null) - => Log(clLogFile, file!, method!, data); + public static void LogCL(object? data = null, [CallerFilePath] string? file = null, + [CallerMemberName] string? method = null) => Log(clLogFile, file!, + method!, data); - public static void Log( - string logFile, - string callingFile, - string callingMethod, - object? data = null) + public static void Log(string logFile, string callingFile, string callingMethod, + object? data = null) + { + lock (@lock) { - lock (@lock) - { - File.AppendAllText( - logFile, - $"{DateTime.Now:HH:mm:ss.fff} " - + $"{Process.GetCurrentProcess().Id,5} " - + $"{Thread.CurrentThread.ManagedThreadId,3} " - + $"{Path.GetFileNameWithoutExtension(callingFile)}.{callingMethod}()" - + $"{(data == null ? "" : $": {data}")}\n"); - } + File.AppendAllText( + logFile, + $"{DateTime.Now:HH:mm:ss.fff} " + $"{Process.GetCurrentProcess().Id,5} " + + $"{Thread.CurrentThread.ManagedThreadId,3} " + + $"{Path.GetFileNameWithoutExtension(callingFile)}.{callingMethod}()" + + $"{(data == null ? "" : $": {data}")}\n"); } } } +} diff --git a/CodeiumVS/codelensoop/CodeiumCodeLensProvider.cs b/CodeiumVS/codelensoop/CodeiumCodeLensProvider.cs index 071bea7..4fd64e1 100644 --- a/CodeiumVS/codelensoop/CodeiumCodeLensProvider.cs +++ b/CodeiumVS/codelensoop/CodeiumCodeLensProvider.cs @@ -16,183 +16,131 @@ namespace CodeiumVS { - [Export(typeof(IAsyncCodeLensDataPointProvider))] - [Name(Id)] - [ContentType("text")] - [LocalizedName(typeof(Resources), "CodeiumCodeLensProvider")] - [Priority(200)] +[Export(typeof(IAsyncCodeLensDataPointProvider))] +[Name(Id)] +[ContentType("text")] +[LocalizedName(typeof(Resources), "CodeiumCodeLensProvider")] +[Priority(200)] - internal class CodeiumCodeLensProvider : IAsyncCodeLensDataPointProvider +internal class CodeiumCodeLensProvider : IAsyncCodeLensDataPointProvider +{ + internal const string Id = "CodeiumCodeLens"; + ITextDocument _document; + CodeiumCompletionHandler handler; + private readonly Lazy callbackService; + + [ImportingConstructor] + public CodeiumCodeLensProvider(Lazy callbackService) { - internal const string Id = "CodeiumCodeLens"; - ITextDocument _document; - CodeiumCompletionHandler handler; - private readonly Lazy callbackService; + this.callbackService = callbackService; + } - [ImportingConstructor] - public CodeiumCodeLensProvider(Lazy callbackService) - { - this.callbackService = callbackService; - } + public async Task CanCreateDataPointAsync(CodeLensDescriptor descriptor, + CodeLensDescriptorContext context, + CancellationToken token) + { - public async Task CanCreateDataPointAsync(CodeLensDescriptor descriptor, CodeLensDescriptorContext context, - CancellationToken token) + try { + var callback = callbackService.Value; + var name = nameof(ICodeLensListener.IsCodeiumCodeLensActive); - try - { - var callback = callbackService.Value; - var name = nameof(ICodeLensListener.IsCodeiumCodeLensActive); - - var res = await callback - .InvokeAsync(this, name).Caf(); + var res = await callback.InvokeAsync(this, name).Caf(); - return res; - - } - catch (Exception ex) - { - return false; - } + return res; } - - public async Task CreateDataPointAsync(CodeLensDescriptor descriptor, - CodeLensDescriptorContext context, CancellationToken token) + catch (Exception ex) { - CodeiumDataPoint dp = null; - try - { - dp = new CodeiumDataPoint(callbackService.Value, descriptor); - } - catch (Exception ex) - { - return null; - } - - try - { - var callback = callbackService.Value; - var name =nameof(ICodeLensListener.GetVisualStudioPid); - - var vspid = await callback - .InvokeAsync(this, name).Caf(); - - await dp.ConnectToVisualStudio(vspid).Caf(); - } - catch (Exception ex) - { - CodelensLogger.LogCL(ex.ToString()); - } - - return dp; + return false; } - } - public class CodeiumDataPoint : IAsyncCodeLensDataPoint + public async Task + CreateDataPointAsync(CodeLensDescriptor descriptor, CodeLensDescriptorContext context, + CancellationToken token) { - private static readonly CodeLensDetailEntryCommand refactorCommand = new CodeLensDetailEntryCommand - { - CommandSet = PackageGuids.CodeiumVS, - CommandId = 0x0110, - CommandName = "Codeium.RefactorSelectionCodeBlock" - }; - - private static readonly CodeLensDetailEntryCommand explainCommand = new CodeLensDetailEntryCommand - { - CommandSet = PackageGuids.CodeiumVS, - CommandId = 0x0111, - CommandName = "Codeium.ExplainSelectionCodeBlock" - }; - private static readonly CodeLensDetailEntryCommand goDocCommand = new CodeLensDetailEntryCommand + CodeiumDataPoint dp = null; + try { - CommandSet = PackageGuids.CodeiumVS, - CommandId = 0x0112, - CommandName = "Codeium.GenerateSelectionFunctionDocstring" - }; - - private VisualStudioConnectionHandler? visualStudioConnection; - - private readonly ManualResetEventSlim dataLoaded = new ManualResetEventSlim(initialState: false); - - private readonly CodeLensDescriptor descriptor; - private readonly CodeiumCompletionHandler codeiumCompletionHandler; - private bool needsGoDoc; - private ITextDocument _document; - public readonly Guid id = Guid.NewGuid(); - private readonly ICodeLensCallbackService callbackService; - private volatile FunctionInfo data; - - public CodeiumDataPoint(ICodeLensCallbackService callbackService, CodeLensDescriptor descriptor) + dp = new CodeiumDataPoint(callbackService.Value, descriptor); + } + catch (Exception ex) { - this.descriptor = descriptor; - this.callbackService = callbackService; + return null; } - public event AsyncEventHandler InvalidatedAsync; - - public CodeLensDescriptor Descriptor => this.descriptor; + try + { + var callback = callbackService.Value; + var name = nameof(ICodeLensListener.GetVisualStudioPid); - public async Task ConnectToVisualStudio(int vspid) => - visualStudioConnection = await VisualStudioConnectionHandler.Create(owner: this, vspid).Caf(); + var vspid = await callback.InvokeAsync(this, name).Caf(); - public async Task GetDataAsync(CodeLensDescriptorContext context, - CancellationToken token) + await dp.ConnectToVisualStudio(vspid).Caf(); + } + catch (Exception ex) { - try - { - - if (DoesNeedGoDocData()) - { - try - { - data = await LoadInstructions(context, token).Caf(); - } - catch (Exception ex) - { - CodelensLogger.LogCL(ex.ToString()); - } + CodelensLogger.LogCL(ex.ToString()); + } - } + return dp; + } +} - CodeLensDataPointDescriptor response = new CodeLensDataPointDescriptor() - { - Description = "Invoke Windsurf", - TooltipText = "Windsurf", - IntValue = null, // no int value - }; +public class CodeiumDataPoint : IAsyncCodeLensDataPoint +{ + private static readonly CodeLensDetailEntryCommand refactorCommand = + new CodeLensDetailEntryCommand { CommandSet = PackageGuids.CodeiumVS, + CommandId = 0x0110, + CommandName = "Codeium.RefactorSelectionCodeBlock" }; + + private static readonly CodeLensDetailEntryCommand explainCommand = + new CodeLensDetailEntryCommand { CommandSet = PackageGuids.CodeiumVS, + CommandId = 0x0111, + CommandName = "Codeium.ExplainSelectionCodeBlock" }; + private static readonly CodeLensDetailEntryCommand goDocCommand = + new CodeLensDetailEntryCommand { CommandSet = PackageGuids.CodeiumVS, + CommandId = 0x0112, + CommandName = + "Codeium.GenerateSelectionFunctionDocstring" }; + + private VisualStudioConnectionHandler? visualStudioConnection; + + private readonly ManualResetEventSlim dataLoaded = + new ManualResetEventSlim(initialState: false); + + private readonly CodeLensDescriptor descriptor; + private readonly CodeiumCompletionHandler codeiumCompletionHandler; + private bool needsGoDoc; + private ITextDocument _document; + public readonly Guid id = Guid.NewGuid(); + private readonly ICodeLensCallbackService callbackService; + private volatile FunctionInfo data; + + public CodeiumDataPoint(ICodeLensCallbackService callbackService, CodeLensDescriptor descriptor) + { + this.descriptor = descriptor; + this.callbackService = callbackService; + } - return response; - } - catch (Exception ex) - { - CodelensLogger.LogCL(ex.ToString()); + public event AsyncEventHandler InvalidatedAsync; - return null; - } - } + public CodeLensDescriptor Descriptor => this.descriptor; - // Called from VS via JSON RPC. - public void Refresh() => _ = InvalidatedAsync?.InvokeAsync(this, EventArgs.Empty); + public async Task ConnectToVisualStudio(int vspid) => visualStudioConnection = + await VisualStudioConnectionHandler.Create(owner: this, vspid).Caf(); - bool DoesNeedGoDocData() + public async Task GetDataAsync(CodeLensDescriptorContext context, + CancellationToken token) + { + try { - if (descriptor == null) return false; - - return (descriptor.Kind is CodeElementKinds.Function || descriptor.Kind is CodeElementKinds.Method); - } - public async Task GetDetailsAsync(CodeLensDescriptorContext context, - CancellationToken token) - { if (DoesNeedGoDocData()) { try { - if (!dataLoaded.Wait(timeout: TimeSpan.FromSeconds(.5), token)) - { - data = await LoadInstructions(context, token).Caf(); - } + data = await LoadInstructions(context, token).Caf(); } catch (Exception ex) { @@ -200,85 +148,115 @@ public async Task GetDetailsAsync(CodeLensDescriptorC } } + CodeLensDataPointDescriptor response = new CodeLensDataPointDescriptor() { + Description = "Invoke Windsurf", + TooltipText = "Windsurf", + IntValue = null, // no int value + }; + + return response; + } + catch (Exception ex) + { + CodelensLogger.LogCL(ex.ToString()); + + return null; + } + } + + // Called from VS via JSON RPC. + public void Refresh() => _ = InvalidatedAsync?.InvokeAsync(this, EventArgs.Empty); + + bool DoesNeedGoDocData() + { + if (descriptor == null) return false; + + return (descriptor.Kind is CodeElementKinds.Function || + descriptor.Kind is CodeElementKinds.Method); + } + + public async Task GetDetailsAsync(CodeLensDescriptorContext context, + CancellationToken token) + { + if (DoesNeedGoDocData()) + { try { - var l = new List() - { - new CodeLensDetailPaneCommand() - { - CommandId = refactorCommand, - CommandDisplayName = "Refactor", - CommandArgs = new object[] { context} - }, - new CodeLensDetailPaneCommand() - { - CommandId = explainCommand, - CommandDisplayName = "Explain", - CommandArgs = new object[] { context } - }, - }; - - if (data != null) - { - if (data.Docstring.IsNullOrEmpty()) - { - l.Add(new CodeLensDetailPaneCommand() - { - CommandId = goDocCommand, - CommandDisplayName = "Generate Docstring", - CommandArgs = new object[] { context } - }); - } - else - { - CodelensLogger.LogCL("GetDetailsAsync Docstring" + data.Docstring); - } - } - - var result = new CodeLensDetailsDescriptor() - { - PaneNavigationCommands = l, - }; - - return result; + if (!dataLoaded.Wait(timeout: TimeSpan.FromSeconds(.5), token)) + { + data = await LoadInstructions(context, token).Caf(); + } } catch (Exception ex) { CodelensLogger.LogCL(ex.ToString()); - return null; } } - private async Task LoadInstructions(CodeLensDescriptorContext ctx, CancellationToken ct) - => await callbackService - .InvokeAsync( - this, - nameof(ICodeLensListener.LoadInstructions), - new object[] { - id, - Descriptor.ProjectGuid, - Descriptor.FilePath, - ctx.ApplicableSpan != null - ? ctx.ApplicableSpan.Value.Start - : throw new InvalidOperationException($"No ApplicableSpan."), - ctx.ApplicableSpan!.Value.Length - }, - ct).Caf(); - - - /// - /// Raises event. - /// - /// - /// This is not part of the IAsyncCodeLensDataPoint interface. - /// The data point source can call this method to notify the client proxy that data for this data point has changed. - /// - public void Invalidate() + try { - this.InvalidatedAsync?.Invoke(this, EventArgs.Empty).ConfigureAwait(false); - } + var l = new List() { + new CodeLensDetailPaneCommand() { CommandId = refactorCommand, + CommandDisplayName = "Refactor", + CommandArgs = new object[] { context } }, + new CodeLensDetailPaneCommand() { CommandId = explainCommand, + CommandDisplayName = "Explain", + CommandArgs = new object[] { context } }, + }; + + if (data != null) + { + if (data.Docstring.IsNullOrEmpty()) + { + l.Add( + new CodeLensDetailPaneCommand() { CommandId = goDocCommand, + CommandDisplayName = "Generate Docstring", + CommandArgs = new object[] { context } }); + } + else { CodelensLogger.LogCL("GetDetailsAsync Docstring" + data.Docstring); } + } + + var result = new CodeLensDetailsDescriptor() { + PaneNavigationCommands = l, + }; + return result; + } + catch (Exception ex) + { + CodelensLogger.LogCL(ex.ToString()); + return null; + } } + private async Task LoadInstructions(CodeLensDescriptorContext ctx, + CancellationToken ct) => + await callbackService + .InvokeAsync( + this, nameof(ICodeLensListener.LoadInstructions), new object[] { + id, + Descriptor.ProjectGuid, + Descriptor.FilePath, + ctx.ApplicableSpan != + null? ctx.ApplicableSpan.Value.Start : throw new InvalidOperationException( + $"No ApplicableSpan."), + ctx.ApplicableSpan!.Value.Length + }, + ct) + .Caf(); + + /// + /// Raises event. + /// + /// + /// This is not part of the IAsyncCodeLensDataPoint interface. + /// The data point source can call this method to notify the client proxy that data for this + /// data point has changed. + /// + public void Invalidate() + { + this.InvalidatedAsync?.Invoke(this, EventArgs.Empty).ConfigureAwait(false); + } } +} diff --git a/CodeiumVS/codelensoop/SharedCodeLens.cs b/CodeiumVS/codelensoop/SharedCodeLens.cs index 0fc0152..6f46b24 100644 --- a/CodeiumVS/codelensoop/SharedCodeLens.cs +++ b/CodeiumVS/codelensoop/SharedCodeLens.cs @@ -5,41 +5,42 @@ namespace CodeiumVS { - using System; - using System.Runtime.CompilerServices; - using System.Threading; - using System.Threading.Tasks; - - public static class PipeName - { - // Pipe needs to be scoped by PID so multiple VS instances don't compete for connecting CodeLenses. - public static string Get(int pid) => $@"codeium\{pid}"; - } - public static class ConfigureAwaitAlias - { - /// Alias for `ConfigureAwait(false)`. - public static ConfiguredTaskAwaitable Caf(this Task t) => t.ConfigureAwait(false); - - /// Alias for `ConfigureAwait(false)`. - public static ConfiguredTaskAwaitable Caf(this Task t) => t.ConfigureAwait(false); - } - - public interface IRemoteCodeLens - { - void Refresh(); - } - - public interface IRemoteVisualStudio - { - void RegisterCodeLensDataPoint(Guid id); - } - - public interface ICodeLensListener - { - int GetVisualStudioPid(); - bool IsCodeiumCodeLensActive(); - Task LoadInstructions(Guid dataPointId, Guid projGuid, string filePath, int textStart, int textLen, CancellationToken ct); - - } - -} \ No newline at end of file +using System; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Threading.Tasks; + +public static class PipeName +{ + // Pipe needs to be scoped by PID so multiple VS instances don't compete for connecting + // CodeLenses. + public static string Get(int pid) => $@"codeium\{pid}"; +} +public static class ConfigureAwaitAlias +{ + /// Alias for `ConfigureAwait(false)`. + public static ConfiguredTaskAwaitable Caf(this Task t) => t.ConfigureAwait(false); + + /// Alias for `ConfigureAwait(false)`. + public static ConfiguredTaskAwaitable Caf(this Task t) => t.ConfigureAwait(false); +} + +public interface IRemoteCodeLens +{ + void Refresh(); +} + +public interface IRemoteVisualStudio +{ + void RegisterCodeLensDataPoint(Guid id); +} + +public interface ICodeLensListener +{ + int GetVisualStudioPid(); + bool IsCodeiumCodeLensActive(); + Task LoadInstructions(Guid dataPointId, Guid projGuid, string filePath, + int textStart, int textLen, CancellationToken ct); +} + +} diff --git a/CodeiumVS/codelensoop/VisualStudioConnectionHandler.cs b/CodeiumVS/codelensoop/VisualStudioConnectionHandler.cs index dabf31f..482a22a 100644 --- a/CodeiumVS/codelensoop/VisualStudioConnectionHandler.cs +++ b/CodeiumVS/codelensoop/VisualStudioConnectionHandler.cs @@ -7,38 +7,37 @@ namespace CodeiumVS { - public class VisualStudioConnectionHandler : IRemoteCodeLens, IDisposable +public class VisualStudioConnectionHandler : IRemoteCodeLens, IDisposable +{ + private readonly CodeiumDataPoint dataPoint; + private readonly NamedPipeClientStream stream; + private JsonRpc? rpc; + + public async static Task Create(CodeiumDataPoint owner, + int vspid) + { + var handler = new VisualStudioConnectionHandler(owner, vspid); + await handler.Connect().Caf(); + return handler; + } + + public VisualStudioConnectionHandler(CodeiumDataPoint dataPoint, int vspid) { - private readonly CodeiumDataPoint dataPoint; - private readonly NamedPipeClientStream stream; - private JsonRpc? rpc; - - public async static Task Create(CodeiumDataPoint owner, int vspid) - { - var handler = new VisualStudioConnectionHandler(owner, vspid); - await handler.Connect().Caf(); - return handler; - } - - public VisualStudioConnectionHandler(CodeiumDataPoint dataPoint, int vspid) - { - this.dataPoint = dataPoint; - stream = new NamedPipeClientStream( - serverName: ".", - PipeName.Get(vspid), - PipeDirection.InOut, - PipeOptions.Asynchronous); - } - - public void Dispose() => stream.Dispose(); - - public async Task Connect() - { - await stream.ConnectAsync().Caf(); - rpc = JsonRpc.Attach(stream, this); - await rpc.InvokeAsync(nameof(IRemoteVisualStudio.RegisterCodeLensDataPoint), dataPoint.id).Caf(); - } - - public void Refresh() => dataPoint.Refresh(); + this.dataPoint = dataPoint; + stream = new NamedPipeClientStream( + serverName: ".", PipeName.Get(vspid), PipeDirection.InOut, PipeOptions.Asynchronous); } -} \ No newline at end of file + + public void Dispose() => stream.Dispose(); + + public async Task Connect() + { + await stream.ConnectAsync().Caf(); + rpc = JsonRpc.Attach(stream, this); + await rpc.InvokeAsync(nameof(IRemoteVisualStudio.RegisterCodeLensDataPoint), dataPoint.id) + .Caf(); + } + + public void Refresh() => dataPoint.Refresh(); +} +} diff --git a/CodeiumVS/source.extension.cs b/CodeiumVS/source.extension.cs index 51eaf9b..1574578 100644 --- a/CodeiumVS/source.extension.cs +++ b/CodeiumVS/source.extension.cs @@ -5,14 +5,16 @@ // ------------------------------------------------------------------------------ namespace CodeiumVS { - internal sealed partial class Vsix - { - public const string Id = "Codeium.VisualStudio"; - public const string Name = "Codeium"; - public const string Description = @"The modern coding superpower: free AI code acceleration plugin for your favorite languages. Type less. Code more. Ship faster."; - public const string Language = "en-US"; - public const string Version = "1.8.82"; - public const string Author = "Codeium"; - public const string Tags = ""; - } +internal sealed partial class Vsix +{ + public const string Id = "Codeium.VisualStudio"; + public const string Name = "Codeium"; + public const string Description = + @"The modern coding superpower: free AI code acceleration plugin for your favorite " + + @"languages. Type less. Code more. Ship faster."; + public const string Language = "en-US"; + public const string Version = "1.8.82"; + public const string Author = "Codeium"; + public const string Tags = ""; +} } diff --git a/codeium.svg b/codeium.svg new file mode 100644 index 0000000..7df5eb2 --- /dev/null +++ b/codeium.svg @@ -0,0 +1,9 @@ + + + + + + + + +