Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Fix crashes; AddTrackedWorkspace #61

Merged
merged 4 commits into from
Mar 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 32 additions & 4 deletions CodeiumVS/LanguageServer/LanguageServer.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using CodeiumVS.Packets;
using EnvDTE;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.Shell.Interop;
Expand All @@ -25,10 +26,11 @@ namespace CodeiumVS;
public class LanguageServer
{
private string _languageServerURL;
private string _languageServerVersion = "1.8.0";
private string _languageServerVersion = "1.8.14";

private int _port = 0;
private Process _process;
private System.Diagnostics.Process _process;
private bool _intializedWorkspace = false;

private readonly Metadata _metadata;
private readonly HttpClient _httpClient;
Expand Down Expand Up @@ -379,7 +381,7 @@ private void ThreadDownloadLanguageServer(IVsThreadedWaitDialog4 progressDialog)

// wait until the download is completed
while (webClient.IsBusy)
Thread.Sleep(100);
System.Threading.Thread.Sleep(100);

webClient.Dispose();
}
Expand Down Expand Up @@ -416,7 +418,7 @@ await _package.LogAsync(
false,
true);

Thread trd =
System.Threading.Thread trd =
new(() => ThreadDownloadLanguageServer(progressDialog)) { IsBackground = true };

trd.Start();
Expand Down Expand Up @@ -724,6 +726,18 @@ await _package.LogAsync(
return default;
}

private async Task IntializeTrackedWorkspaceAsync()
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
EnvDTE.DTE dte = (DTE)ServiceProvider.GlobalProvider.GetService(typeof(DTE));
string solutionDir = System.IO.Path.GetDirectoryName(dte.Solution.FullName);
AddTrackedWorkspaceResponse response = await AddTrackedWorkspaceAsync(solutionDir);
if (response != null)
{
_intializedWorkspace = true;
}
}

private async Task<T?> RequestCommandAsync<T>(string command, object data,
CancellationToken cancellationToken = default)
{
Expand All @@ -737,6 +751,10 @@ public async Task<IList<CompletionItem>?>
int cursorPosition, string lineEnding, int tabSize, bool insertSpaces,
CancellationToken token)
{
if (!_intializedWorkspace)
{
await IntializeTrackedWorkspaceAsync();
}
GetCompletionsRequest data =
new() { metadata = GetMetadata(),
document = new() { text = text,
Expand Down Expand Up @@ -768,9 +786,19 @@ public async Task AcceptCompletionAsync(string completionId)

public async Task<GetProcessesResponse?> GetProcessesAsync()
{
if (!_intializedWorkspace)
{
await IntializeTrackedWorkspaceAsync();
}
return await RequestCommandAsync<GetProcessesResponse>("GetProcesses", new {});
}

public async Task<AddTrackedWorkspaceResponse?> AddTrackedWorkspaceAsync(string workspacePath)
{
AddTrackedWorkspaceRequest data = new() { workspace = workspacePath };
return await RequestCommandAsync<AddTrackedWorkspaceResponse>("AddTrackedWorkspace", data);
}

public Metadata GetMetadata()
{
return new() { request_id = _metadata.request_id++,
Expand Down
22 changes: 22 additions & 0 deletions CodeiumVS/LanguageServer/Packets.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2568,6 +2568,28 @@ public partial class AcceptCompletionResponse : global::ProtoBuf.IExtensible
global::ProtoBuf.Extensible.GetExtensionObject(ref __pbn__extensionData, createIfMissing);
}

[global::ProtoBuf.ProtoContract()]
public partial class AddTrackedWorkspaceRequest : 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.ProtoMember(1)]
[global::System.ComponentModel.DefaultValue("")]
public string workspace { get; set; }
}

[global::ProtoBuf.ProtoContract()]
public partial class AddTrackedWorkspaceResponse : 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.ProtoContract()]
public enum Language
{
Expand Down
23 changes: 15 additions & 8 deletions CodeiumVS/SuggestionUI/InlineGreyTextTagger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
Expand Down Expand Up @@ -61,17 +62,23 @@ public void FormatText(TextRunProperties props)

public void MarkDirty()
{
var changeStart = view.TextViewLines.FirstVisibleLine.Start;
var changeEnd = view.TextViewLines.LastVisibleLine.Start;
try
{
var changeStart = view.TextViewLines.FirstVisibleLine.Start;
var changeEnd = view.TextViewLines.LastVisibleLine.Start;

var startLine = view.TextSnapshot.GetLineFromPosition(changeStart);
var endLine = view.TextSnapshot.GetLineFromPosition(changeEnd);
var startLine = view.TextSnapshot.GetLineFromPosition(changeStart);
var endLine = view.TextSnapshot.GetLineFromPosition(changeEnd);

var span = new SnapshotSpan(startLine.Start, endLine.EndIncludingLineBreak)
.TranslateTo(targetSnapshot: view.TextBuffer.CurrentSnapshot,
SpanTrackingMode.EdgePositive);
var span = new SnapshotSpan(startLine.Start, endLine.EndIncludingLineBreak)
.TranslateTo(targetSnapshot: view.TextBuffer.CurrentSnapshot,
SpanTrackingMode.EdgePositive);

TagsChanged(this, new SnapshotSpanEventArgs(new SnapshotSpan(span.Start, span.End)));
TagsChanged(this, new SnapshotSpanEventArgs(new SnapshotSpan(span.Start, span.End)));
} catch (Exception e)
{
Debug.Write(e);
}
}

// Produces tags on the snapshot that the tag consumer asked for.
Expand Down
22 changes: 16 additions & 6 deletions CodeiumVS/SuggestionUI/SuggestionTagger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -246,10 +246,16 @@ void AddSuffixTextBlocks(int start, string line, string userText)
void AddInsertionTextBlock(int start, int end, string line)
{
if (line.Length <= suggestionIndex) return;

string remainder = line.Substring(start, end - start);
var textBlock = CreateTextBox(remainder, greyBrush);
GetTagger().UpdateAdornment(textBlock);
try
{
string remainder = line.Substring(start, end - start);
var textBlock = CreateTextBox(remainder, greyBrush);
GetTagger().UpdateAdornment(textBlock);
}
catch (ArgumentOutOfRangeException)
{
return;
}
}

// Updates the grey text
Expand All @@ -267,7 +273,7 @@ public void UpdateAdornment(IWpfTextView view, string userText, int suggestionSt

if (isTextInsertion && suggestionIndex < userIndex)
{
if (suggestionIndex > 0 && 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]))
{
Expand Down Expand Up @@ -317,7 +323,7 @@ public void UpdateAdornment(IWpfTextView view, string userText, int suggestionSt
this.adornmentLayer.AddAdornment(
AdornmentPositioningBehavior.TextRelative, span, null, stackPanel, null);
}
catch (ArgumentOutOfRangeException e)
catch (Exception e)
{
Debug.Write(e);
}
Expand Down Expand Up @@ -440,6 +446,10 @@ public bool CompleteText()
// replaces text in the editor
void ReplaceText(string text, int lineN)
{
if (view.Options.GetOptionValue(DefaultOptions.NewLineCharacterOptionId) == "\r\n")
{
text = text.Replace("\n", "\r\n");
}
var oldLineN = lineN + suggestion.Item2.Length - 1;
bool insertion = isTextInsertion && suggestion.Item2.Length == 1;
var oldUserIndex = userIndex;
Expand Down
23 changes: 17 additions & 6 deletions CodeiumVS/SuggestionUI/TextViewListener.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,6 @@ public async void GetCompletion()
if (!caretPoint.HasValue) { return; }

var caretPosition = caretPoint.Value.Position;
await package.LogAsync(
$"RequestProposalsAsync - Language: {_language.Name}; Caret: {caretPosition}; ASCII: {_document.Encoding.IsSingleByte}");

string text = _document.TextBuffer.CurrentSnapshot.GetText();
int cursorPosition = _document.Encoding.IsSingleByte
Expand Down Expand Up @@ -106,8 +104,17 @@ await package.LogAsync(
Debug.Print("completions " + list.Count.ToString());

string prefix = line.Substring(0, Math.Min(characterN, line.Length));
List<Tuple<String, String>> suggestions =
ParseCompletion(list, text, line, prefix, characterN);

List<Tuple<String, String>> suggestions;
try
{
suggestions = ParseCompletion(list, text, line, prefix, characterN);
}
catch (Exception ex)
{
await package.LogAsync("Exception: " + ex.ToString());
return;
}

SuggestionTagger tagger = GetTagger();
if (suggestions != null && suggestions.Count > 0 && tagger != null)
Expand Down Expand Up @@ -143,6 +150,7 @@ List<Tuple<String, String>> ParseCompletion(IList<Packets.CompletionItem> comple
endOffset = Utf8OffsetToUtf16Offset(text, endOffset);
insertionStart = Utf8OffsetToUtf16Offset(text, insertionStart);
}
if (endOffset > text.Length) { endOffset = text.Length; }
string end = text.Substring(endOffset);
String completionText = completionItems[i].completion.text;
if (!String.IsNullOrEmpty(end))
Expand All @@ -154,7 +162,7 @@ List<Tuple<String, String>> ParseCompletion(IList<Packets.CompletionItem> comple
completionText = completionText + end.Substring(0, endNewline);
}
int offset = StringCompare.CheckSuggestion(completionText, prefix);
if (offset < 0) { continue; }
if (offset < 0 || offset > completionText.Length) { continue; }

completionText = completionText.Substring(offset);
string completionID = completionItem.completion.completionId;
Expand All @@ -164,9 +172,12 @@ List<Tuple<String, String>> ParseCompletion(IList<Packets.CompletionItem> comple
ICompletionSession session = m_provider.CompletionBroker.GetSessions(_view).FirstOrDefault();
if (session != null && session.SelectedCompletionSet != null)
{
string intellisenseSuggestion = session.SelectedCompletionSet.SelectionStatus.Completion.InsertionText;
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);
if (span.Length > intellisenseSuggestion.Length) { continue; }
string intellisenseInsertion = intellisenseSuggestion.Substring(span.Length);
if (!completionText.StartsWith(intellisenseInsertion))
{
Expand Down
21 changes: 10 additions & 11 deletions CodeiumVS/source.extension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,14 @@
// ------------------------------------------------------------------------------
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.0";
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.14";
public const string Author = "Codeium";
public const string Tags = "";
}
}
2 changes: 1 addition & 1 deletion CodeiumVS/source.extension.vsixmanifest
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<PackageManifest Version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2011" xmlns:d="http://schemas.microsoft.com/developer/vsx-schema-design/2011">
<Metadata>
<Identity Id="Codeium.VisualStudio" Version="1.8.0" Language="en-US" Publisher="Codeium" />
<Identity Id="Codeium.VisualStudio" Version="1.8.14" Language="en-US" Publisher="Codeium" />
<DisplayName>Codeium</DisplayName>
<Description xml:space="preserve">The modern coding superpower: free AI code acceleration plugin for your favorite languages. Type less. Code more. Ship faster.</Description>
<MoreInfo>https://www.codeium.com</MoreInfo>
Expand Down
Loading