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

Remove waiting for background task from more command handlers #63571

Merged
merged 4 commits into from
Aug 25, 2022
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
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,7 @@ protected override void ModifySelectedNode(
CancellationToken cancellationToken)
{
var root = document.GetRequiredSyntaxRootSynchronously(cancellationToken);
var formattingOptions = document.GetSyntaxFormattingOptionsAsync(EditorOptionsService.GlobalOptions, cancellationToken).AsTask().WaitAndGetResult(cancellationToken);
var formattingOptions = args.SubjectBuffer.GetSyntaxFormattingOptions(EditorOptionsService, document.Project.Services, explicitFormat: false);

// Add braces for the selected node
if (addBrace)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
// See the LICENSE file in the project root for more information.

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Reflection.Metadata;
Expand All @@ -22,6 +24,7 @@
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
Expand Down Expand Up @@ -189,10 +192,11 @@ private async Task ExecuteWorkerAsync(

var cleanupOptions = await document.GetCodeCleanupOptionsAsync(_globalOptions, cancellationToken).ConfigureAwait(false);
var (formattedDocument, methodNameAtInvocation) = await result.GetFormattedDocumentAsync(cleanupOptions, cancellationToken).ConfigureAwait(false);
var changes = await formattedDocument.GetTextChangesAsync(document, cancellationToken).ConfigureAwait(false);

await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

ApplyChange_OnUIThread(formattedDocument, textBuffer, waitContext);
ApplyChange_OnUIThread(textBuffer, changes, waitContext);

// start inline rename to allow the user to change the name if they want.
var textSnapshot = textBuffer.CurrentSnapshot;
Expand All @@ -206,17 +210,15 @@ private async Task ExecuteWorkerAsync(
}

private void ApplyChange_OnUIThread(
Document formattedDocument, ITextBuffer textBuffer, IBackgroundWorkIndicatorContext waitContext)
ITextBuffer textBuffer, IEnumerable<TextChange> changes, IBackgroundWorkIndicatorContext waitContext)
{
_threadingContext.ThrowIfNotOnUIThread();

var cancellationToken = waitContext.UserCancellationToken;

using var undoTransaction = _undoManager.GetTextBufferUndoManager(textBuffer).TextBufferUndoHistory.CreateTransaction("Extract Method");

// We're about to make an edit ourselves. so disable the cancellation that happens on editing.
waitContext.CancelOnEdit = false;
formattedDocument.Project.Solution.Workspace.ApplyDocumentChanges(formattedDocument, cancellationToken);
textBuffer.ApplyChanges(changes);

// apply changes
undoTransaction.Complete();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.QuickInfo;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.LanguageService;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
Expand Down Expand Up @@ -153,7 +154,7 @@ private bool ShouldTriggerCompletion(
SourceText sourceText,
Document document,
CompletionService completionService,
in CompletionOptions options)
CompletionOptions options)
{
// The trigger reason guarantees that user wants a completion.
if (trigger.Reason is AsyncCompletionData.CompletionTriggerReason.Invoke or
Expand All @@ -173,7 +174,7 @@ private bool ShouldTriggerCompletion(
// Otherwise, tab should not be a completion trigger.
if (trigger.Reason == AsyncCompletionData.CompletionTriggerReason.Insertion && trigger.Character == '\t')
{
return TryInvokeSnippetCompletion(completionService, document, sourceText, triggerLocation.Position, options);
return TryInvokeSnippetCompletion(triggerLocation.Snapshot.TextBuffer, triggerLocation.Position, sourceText, document.Project.Services, completionService.GetRules(options));
}

var roslynTrigger = Helpers.GetRoslynTrigger(trigger, triggerLocation);
Expand All @@ -184,16 +185,15 @@ private bool ShouldTriggerCompletion(
}

private bool TryInvokeSnippetCompletion(
CompletionService completionService, Document document, SourceText text, int caretPoint, in CompletionOptions options)
ITextBuffer buffer, int caretPoint, SourceText text, LanguageServices services, CompletionRules rules)
{
var rules = completionService.GetRules(options);
// Do not invoke snippet if the corresponding rule is not set in options.
if (rules.SnippetsRule != SnippetsRule.IncludeAfterTypingIdentifierQuestionTab)
{
return false;
}

var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
var syntaxFacts = services.GetService<ISyntaxFactsService>();
// Snippets are included if the user types: <quesiton><tab>
// If at least one condition for snippets do not hold, bail out.
if (syntaxFacts == null ||
Expand All @@ -206,8 +206,7 @@ private bool TryInvokeSnippetCompletion(

// Because <question><tab> is actually a command to bring up snippets,
// we delete the last <question> that was typed.
var textChange = new TextChange(TextSpan.FromBounds(caretPoint - 2, caretPoint), string.Empty);
document.Project.Solution.Workspace.ApplyTextChanges(document.Id, textChange, CancellationToken.None);
buffer.ApplyChange(new TextChange(TextSpan.FromBounds(caretPoint - 2, caretPoint), string.Empty));

_snippetCompletionTriggeredIndirectly = true;
return true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using System.ComponentModel.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Commanding.Commands;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
Expand Down Expand Up @@ -64,7 +65,8 @@ public bool ExecuteCommand(OrganizeDocumentCommandArgs args, CommandExecutionCon
var newDocument = OrganizingService.OrganizeAsync(document, cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken);
if (document != newDocument)
{
ApplyTextChange(document, newDocument);
var changes = newDocument.GetTextChangesAsync(document, cancellationToken).WaitAndGetResult(cancellationToken);
args.SubjectBuffer.ApplyChanges(changes);
}
}
}
Expand Down Expand Up @@ -144,7 +146,8 @@ private void SortImports(ITextBuffer subjectBuffer, IUIThreadOperationContext op
var newDocument = organizeImportsService.OrganizeImportsAsync(document, options, cancellationToken).WaitAndGetResult(cancellationToken);
if (document != newDocument)
{
ApplyTextChange(document, newDocument);
var changes = newDocument.GetTextChangesAsync(document, cancellationToken).WaitAndGetResult(cancellationToken);
subjectBuffer.ApplyChanges(changes);
}
}
}
Expand All @@ -163,12 +166,10 @@ private void SortAndRemoveUnusedImports(ITextBuffer subjectBuffer, IUIThreadOper
newDocument = organizeImportsService.OrganizeImportsAsync(newDocument, options, cancellationToken).WaitAndGetResult(cancellationToken);
if (document != newDocument)
{
ApplyTextChange(document, newDocument);
var changes = newDocument.GetTextChangesAsync(document, cancellationToken).WaitAndGetResult(cancellationToken);
subjectBuffer.ApplyChanges(changes);
}
}
}

protected static void ApplyTextChange(Document oldDocument, Document newDocument)
=> oldDocument.Project.Solution.Workspace.ApplyDocumentChanges(newDocument, CancellationToken.None);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,7 @@ internal static void ApplyTextChanges(this Workspace workspace, DocumentId id, I
workspace.TryApplyChanges(newSolution);
}

/// <summary>
/// Update the solution so that the document with the Id has the text changes
/// </summary>
internal static void ApplyTextChanges(this Workspace workspace, DocumentId id, TextChange textChange, CancellationToken cancellationToken)
=> workspace.ApplyTextChanges(id, SpecializedCollections.SingletonEnumerable(textChange), cancellationToken);

internal static Solution UpdateDocument(this Solution solution, DocumentId id, IEnumerable<TextChange> textChanges, CancellationToken cancellationToken)
private static Solution UpdateDocument(this Solution solution, DocumentId id, IEnumerable<TextChange> textChanges, CancellationToken cancellationToken)
{
var oldDocument = solution.GetRequiredDocument(id);
var oldText = oldDocument.GetTextSynchronously(cancellationToken);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,11 +141,11 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.EndConstructGeneration

Dim options = document.GetCodeCleanupOptionsAsync(_globalOptions, cancellationToken).AsTask().WaitAndGetResult(cancellationToken)
Dim cleanDocument = CodeCleaner.CleanupAsync(document, GetSpanToCleanup(statement), Options, codeCleanups, cancellationToken:=cancellationToken).WaitAndGetResult(cancellationToken)
Dim changes = cleanDocument.GetTextChangesAsync(document, cancellationToken).WaitAndGetResult(cancellationToken)

Using transaction = New CaretPreservingEditTransaction(VBEditorResources.End_Construct, view, _undoHistoryRegistry, _editorOperationsFactoryService)
transaction.MergePolicy = AutomaticCodeChangeMergePolicy.Instance

cleanDocument.Project.Solution.Workspace.ApplyDocumentChanges(cleanDocument, cancellationToken)
buffer.ApplyChanges(changes)
transaction.Complete()
End Using
End Sub
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,7 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.EndConstructGeneration
Return
End If

Dim oldSolution = document.Project.Solution.Workspace.CurrentSolution
Dim newSolution = oldSolution.UpdateDocument(
document.Id, SpecializedCollections.SingletonEnumerable(
New TextChange(_snapshotSpan.TranslateTo(current, SpanTrackingMode.EdgeExclusive).Span.ToTextSpan(), _replacementText)), CancellationToken.None)

oldSolution.Workspace.TryApplyChanges(newSolution)
subjectBuffer.ApplyChange(New TextChange(_snapshotSpan.TranslateTo(current, SpanTrackingMode.EdgeExclusive).Span.ToTextSpan(), _replacementText))

Dim startPoint = _snapshotSpan.Start.TranslateTo(subjectBuffer.CurrentSnapshot, PointTrackingMode.Negative)
If _newCaretPosition IsNot Nothing Then
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit
baseSnapshot,
baseTree,
dirtyRegion,
document.GetSyntaxTreeSynchronously(cancellationToken),
tree,
cancellationToken)

Dim codeCleanups = CodeCleaner.GetDefaultProviders(document).
Expand Down Expand Up @@ -126,7 +126,8 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit
End If
End If

finalDocument.Project.Solution.Workspace.ApplyDocumentChanges(finalDocument, cancellationToken)
Dim changes = finalDocument.GetTextChangesAsync(document, cancellationToken).WaitAndGetResult(cancellationToken)
buffer.ApplyChanges(changes)
End Using
End Sub

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,8 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.Utilities.CommandHandlers
newDocument = Simplifier.ReduceAsync(newDocument, Simplifier.Annotation, cleanupOptions.SimplifierOptions, cancellationToken).WaitAndGetResult(cancellationToken)
newDocument = Formatter.FormatAsync(newDocument, Formatter.Annotation, cleanupOptions.FormattingOptions, cancellationToken).WaitAndGetResult(cancellationToken)

newDocument.Project.Solution.Workspace.ApplyDocumentChanges(newDocument, cancellationToken)
Dim changes = newDocument.GetTextChangesAsync(document, cancellationToken).WaitAndGetResult(cancellationToken)
args.SubjectBuffer.ApplyChanges(changes)

' Place the cursor back to where it logically was after this
token = newDocument.GetSyntaxRootSynchronously(cancellationToken).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CaseCorrecting

Private Shared Async Function TestAsync(expected As String, workspace As TestWorkspace) As Task
Dim hostDocument = workspace.Documents.First()
Dim buffer = hostDocument.GetTextBuffer()
Dim document = workspace.CurrentSolution.GetDocument(hostDocument.Id)
Dim span = (Await document.GetSyntaxRootAsync()).FullSpan

Expand All @@ -42,9 +41,7 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CaseCorrecting
ImmutableArray.Create(Of ICodeCleanupProvider)(New CaseCorrectionCodeCleanupProvider()),
CancellationToken.None)

newDocument.Project.Solution.Workspace.ApplyDocumentChanges(newDocument, CancellationToken.None)

Dim actual = buffer.CurrentSnapshot.GetText()
Dim actual = newDocument.GetTextSynchronously(CancellationToken.None).ToString()
Assert.Equal(expected, actual)
End Function

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,7 @@ private int FormatWorker(IVsTextLayer textLayer, TextSpan[] selections, Cancella
return VSConstants.S_OK;
}

// create new formatted document
var formattedDocument = document.WithText(text.WithChanges(formattedChanges));
Workspace.ApplyDocumentChanges(formattedDocument, cancellationToken);
textBuffer.ApplyChanges(formattedChanges);

return VSConstants.S_OK;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using EnvDTE;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
Expand Down Expand Up @@ -50,7 +51,12 @@ public async Task UpdaterService()
workspace.AddSolution(SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default));
var project = workspace.AddProject("proj", LanguageNames.CSharp);
var document = workspace.AddDocument(project.Id, "doc.cs", SourceText.From("code"));
workspace.ApplyTextChanges(document.Id, new[] { new TextChange(new TextSpan(0, 1), "abc") }, CancellationToken.None);

var oldText = document.GetTextSynchronously(CancellationToken.None);
var newText = oldText.WithChanges(new[] { new TextChange(new TextSpan(0, 1), "abc") });
var newSolution = document.Project.Solution.WithDocumentText(document.Id, newText, PreservationMode.PreserveIdentity);

workspace.TryApplyChanges(newSolution);

// wait for listener
var workspaceListener = listenerProvider.GetWaiter(FeatureAttribute.Workspace);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,10 +117,7 @@ Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Snippets
Dim currentSnapshot = subjectBuffer.CurrentSnapshot
Dim document = currentSnapshot.GetOpenDocumentInCurrentContextWithChanges()
If document IsNot Nothing Then
Dim editorWorkspace = document.Project.Solution.Workspace
Dim text = currentSnapshot.AsText()
Dim change = New TextChange(Microsoft.CodeAnalysis.Text.TextSpan.FromBounds(caretPosition - 1, caretPosition), String.Empty)
editorWorkspace.ApplyTextChanges(document.Id, change, CancellationToken.None)
subjectBuffer.ApplyChange(New TextChange(Microsoft.CodeAnalysis.Text.TextSpan.FromBounds(caretPosition - 1, caretPosition), String.Empty))
End If
End Sub
End Class
Expand Down