InlineRenameSession.cs 33.2 KB
Newer Older
S
Sam Harwell 已提交
1
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.
2 3 4

using System;
using System.Collections.Generic;
5
using System.Collections.Immutable;
6
using System.Diagnostics;
7 8 9 10
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Threading;
11
using Microsoft.CodeAnalysis.Debugging;
12
using Microsoft.CodeAnalysis.Editor.Host;
13
using Microsoft.CodeAnalysis.Editor.Shared;
14 15 16
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Editor.Undo;
17
using Microsoft.CodeAnalysis.ErrorReporting;
18 19 20 21 22 23 24 25
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Rename;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
26
using Microsoft.VisualStudio.Threading;
27 28 29 30 31 32 33 34 35 36 37 38
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename
{
    internal partial class InlineRenameSession : ForegroundThreadAffinitizedObject, IInlineRenameSession
    {
        private readonly Workspace _workspace;
        private readonly InlineRenameService _renameService;
        private readonly IWaitIndicator _waitIndicator;
        private readonly ITextBufferAssociatedViewService _textBufferAssociatedViewService;
        private readonly ITextBufferFactoryService _textBufferFactoryService;
        private readonly IEnumerable<IRefactorNotifyService> _refactorNotifyServices;
39
        private readonly IDebuggingWorkspaceService _debuggingWorkspaceService;
40 41 42
        private readonly IAsynchronousOperationListener _asyncListener;
        private readonly Solution _baseSolution;
        private readonly Document _triggerDocument;
43
        private readonly ITextView _triggerView;
44 45 46 47
        private readonly IDisposable _inlineRenameSessionDurationLogBlock;

        private bool _dismissed;
        private bool _isApplyingEdit;
48
        private string _replacementText;
49 50 51 52 53 54 55
        private OptionSet _optionSet;
        private Dictionary<ITextBuffer, OpenTextBufferManager> _openTextBuffers = new Dictionary<ITextBuffer, OpenTextBufferManager>();

        /// <summary>
        /// If non-null, the current text of the replacement. Linked spans added will automatically be updated with this
        /// text.
        /// </summary>
56 57 58 59 60 61 62 63 64 65 66 67
        public string ReplacementText
        {
            get
            {
                return _replacementText;
            }
            private set
            {
                _replacementText = value;
                ReplacementTextChanged?.Invoke(this, EventArgs.Empty);
            }
        }
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94

        /// <summary>
        /// The task which computes the main rename locations against the original workspace
        /// snapshot.
        /// </summary>
        private Task<IInlineRenameLocationSet> _allRenameLocationsTask;

        /// <summary>
        /// The cancellation token for most work being done by the inline rename session. This
        /// includes the <see cref="_allRenameLocationsTask"/> tasks.
        /// </summary>
        private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();

        /// <summary>
        /// This task is a continuation of the allRenameLocationsTask that is the result of computing
        /// the resolutions of the rename spans for the current replacementText.
        /// </summary>
        private Task<IInlineRenameReplacementInfo> _conflictResolutionTask;

        /// <summary>
        /// The cancellation source for <see cref="_conflictResolutionTask"/>.
        /// </summary>
        private CancellationTokenSource _conflictResolutionTaskCancellationSource = new CancellationTokenSource();

        private readonly IInlineRenameInfo _renameInfo;

        public InlineRenameSession(
95
            IThreadingContext threadingContext,
96 97 98 99 100 101 102 103
            InlineRenameService renameService,
            Workspace workspace,
            SnapshotSpan triggerSpan,
            IInlineRenameInfo renameInfo,
            IWaitIndicator waitIndicator,
            ITextBufferAssociatedViewService textBufferAssociatedViewService,
            ITextBufferFactoryService textBufferFactoryService,
            IEnumerable<IRefactorNotifyService> refactorNotifyServices,
104 105
            IAsynchronousOperationListener asyncListener)
            : base(threadingContext, assertIsForeground: true)
106 107 108 109 110 111 112
        {
            // This should always be touching a symbol since we verified that upon invocation
            _renameInfo = renameInfo;

            _triggerDocument = triggerSpan.Snapshot.GetOpenDocumentInCurrentContextWithChanges();
            if (_triggerDocument == null)
            {
113
                throw new InvalidOperationException(EditorFeaturesResources.The_triggerSpan_is_not_included_in_the_given_workspace);
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
            }

            _inlineRenameSessionDurationLogBlock = Logger.LogBlock(FunctionId.Rename_InlineSession, CancellationToken.None);

            _workspace = workspace;
            _workspace.WorkspaceChanged += OnWorkspaceChanged;

            _textBufferFactoryService = textBufferFactoryService;
            _textBufferAssociatedViewService = textBufferAssociatedViewService;
            _textBufferAssociatedViewService.SubjectBuffersConnected += OnSubjectBuffersConnected;

            _renameService = renameService;
            _waitIndicator = waitIndicator;
            _refactorNotifyServices = refactorNotifyServices;
            _asyncListener = asyncListener;
            _triggerView = textBufferAssociatedViewService.GetAssociatedTextViews(triggerSpan.Snapshot.TextBuffer).FirstOrDefault(v => v.HasAggregateFocus) ??
                textBufferAssociatedViewService.GetAssociatedTextViews(triggerSpan.Snapshot.TextBuffer).First();

132 133 134
            _optionSet = renameInfo.ForceRenameOverloads
                ? workspace.Options.WithChangedOption(RenameOptions.RenameOverloads, true)
                : workspace.Options;
135 136 137 138 139 140

            this.ReplacementText = triggerSpan.GetText();

            _baseSolution = _triggerDocument.Project.Solution;
            this.UndoManager = workspace.Services.GetService<IInlineRenameUndoManager>();

141 142
            _debuggingWorkspaceService = workspace.Services.GetService<IDebuggingWorkspaceService>();
            _debuggingWorkspaceService.BeforeDebuggingStateChanged += OnBeforeDebuggingStateChanged;
143

144 145 146
            InitializeOpenBuffers(triggerSpan);
        }

147 148 149 150
        private void OnBeforeDebuggingStateChanged(object sender, DebuggingStateChangedEventArgs args)
        {
            if (args.After == DebuggingState.Run)
            {
151 152 153 154
                // It's too late for us to change anything, which means we can neither commit nor
                // rollback changes to cancel. End the rename session but keep all open buffers in
                // their current state.
                Cancel(rollbackTemporaryEdits: false);
155 156 157
            }
        }

C
CyrusNajmabadi 已提交
158
        public string OriginalSymbolName => _renameInfo.DisplayName;
159

160 161 162 163 164 165 166 167 168 169 170 171 172 173
        // Used to aid the investigation of https://github.com/dotnet/roslyn/issues/7364
        private class NullTextBufferException : Exception
        {
            private readonly Document _document;
            private readonly SourceText _text;

            public NullTextBufferException(Document document, SourceText text)
                : base("Cannot retrieve textbuffer from document.")
            {
                _document = document;
                _text = text;
            }
        }

174 175 176 177 178 179 180 181
        private void InitializeOpenBuffers(SnapshotSpan triggerSpan)
        {
            using (Logger.LogBlock(FunctionId.Rename_CreateOpenTextBufferManagerForAllOpenDocs, CancellationToken.None))
            {
                HashSet<ITextBuffer> openBuffers = new HashSet<ITextBuffer>();
                foreach (var d in _workspace.GetOpenDocumentIds())
                {
                    var document = _baseSolution.GetDocument(d);
C
CyrusNajmabadi 已提交
182
                    Contract.ThrowIfFalse(document.TryGetText(out var text));
183
                    Contract.ThrowIfNull(text);
184

185
                    var textSnapshot = text.FindCorrespondingEditorTextSnapshot();
186 187 188 189 190
                    if (textSnapshot == null)
                    {
                        FatalError.ReportWithoutCrash(new NullTextBufferException(document, text));
                        continue;
                    }
191 192 193
                    Contract.ThrowIfNull(textSnapshot.TextBuffer);

                    openBuffers.Add(textSnapshot.TextBuffer);
194 195 196 197
                }

                foreach (var buffer in openBuffers)
                {
198
                    TryPopulateOpenTextBufferManagerForBuffer(buffer, buffer.AsTextContainer().GetRelatedDocuments());
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
                }
            }

            var startingSpan = triggerSpan.Span;

            // Select this span if we didn't already have something selected
            var selections = _triggerView.Selection.GetSnapshotSpansOnBuffer(triggerSpan.Snapshot.TextBuffer);
            if (!selections.Any() ||
                selections.First().IsEmpty ||
                !startingSpan.Contains(selections.First()))
            {
                _triggerView.SetSelection(new SnapshotSpan(triggerSpan.Snapshot, startingSpan));
            }

            this.UndoManager.CreateInitialState(this.ReplacementText, _triggerView.Selection, new SnapshotSpan(triggerSpan.Snapshot, startingSpan));
            _openTextBuffers[triggerSpan.Snapshot.TextBuffer].SetReferenceSpans(SpecializedCollections.SingletonEnumerable(startingSpan.ToTextSpan()));

            UpdateReferenceLocationsTask(_renameInfo.FindRenameLocationsAsync(_optionSet, _cancellationTokenSource.Token));
            RenameTrackingDismisser.DismissRenameTracking(_workspace, _workspace.GetOpenDocumentIds());
        }

220
        private bool TryPopulateOpenTextBufferManagerForBuffer(ITextBuffer buffer, IEnumerable<Document> documents)
221 222 223 224
        {
            AssertIsForeground();
            VerifyNotDismissed();

225 226 227 228 229 230 231 232 233 234
            if (_workspace.Kind == WorkspaceKind.Interactive)
            {
                Debug.Assert(documents.Count() == 1); // No linked files.
                Debug.Assert(buffer.IsReadOnly(0) == buffer.IsReadOnly(Span.FromBounds(0, buffer.CurrentSnapshot.Length))); // All or nothing.
                if (buffer.IsReadOnly(0))
                {
                    return false;
                }
            }

235
            var documentSupportsFeatureService = _workspace.Services.GetService<IDocumentSupportsFeatureService>();
236

237
            if (!_openTextBuffers.ContainsKey(buffer) && documents.All(d => documentSupportsFeatureService.SupportsRename(d)))
238 239
            {
                _openTextBuffers[buffer] = new OpenTextBufferManager(this, buffer, _workspace, documents, _textBufferFactoryService);
240
                return true;
241
            }
242 243

            return _openTextBuffers.ContainsKey(buffer);
244 245 246 247 248 249 250 251 252 253
        }

        private void OnSubjectBuffersConnected(object sender, SubjectBuffersConnectedEventArgs e)
        {
            AssertIsForeground();
            foreach (var buffer in e.SubjectBuffers)
            {
                if (buffer.GetWorkspace() == _workspace)
                {
                    var documents = buffer.AsTextContainer().GetRelatedDocuments();
254
                    if (TryPopulateOpenTextBufferManagerForBuffer(buffer, documents))
255 256 257
                    {
                        _openTextBuffers[buffer].ConnectToView(e.TextView);
                    }
258 259 260 261 262 263 264 265 266 267
                }
            }
        }

        private void UpdateReferenceLocationsTask(Task<IInlineRenameLocationSet> allRenameLocationsTask)
        {
            AssertIsForeground();

            var asyncToken = _asyncListener.BeginAsyncOperation("UpdateReferencesTask");
            _allRenameLocationsTask = allRenameLocationsTask;
268 269 270 271
            allRenameLocationsTask.SafeContinueWithFromAsync(
                async t =>
                {
                    await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true, _cancellationTokenSource.Token);
272 273
                    _cancellationTokenSource.Token.ThrowIfCancellationRequested();

274 275
                    RaiseSessionSpansUpdated(t.Result.Locations.ToImmutableArray());
                },
276
                _cancellationTokenSource.Token,
277 278
                TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously,
                TaskScheduler.Default).CompletesAsyncOperation(asyncToken);
279 280

            UpdateConflictResolutionTask();
281
            QueueApplyReplacements();
282 283
        }

C
CyrusNajmabadi 已提交
284 285 286 287
        public Workspace Workspace => _workspace;
        public OptionSet OptionSet => _optionSet;
        public bool HasRenameOverloads => _renameInfo.HasOverloads;
        public bool ForceRenameOverloads => _renameInfo.ForceRenameOverloads;
288

C
Cyrus Najmabadi 已提交
289
        public IInlineRenameUndoManager UndoManager { get; }
290

291
        public event EventHandler<ImmutableArray<InlineRenameLocation>> ReferenceLocationsChanged;
292
        public event EventHandler<IInlineRenameReplacementInfo> ReplacementsComputed;
293
        public event EventHandler ReplacementTextChanged;
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322

        internal OpenTextBufferManager GetBufferManager(ITextBuffer buffer)
        {
            return _openTextBuffers[buffer];
        }

        internal bool TryGetBufferManager(ITextBuffer buffer, out OpenTextBufferManager bufferManager)
        {
            return _openTextBuffers.TryGetValue(buffer, out bufferManager);
        }

        public void RefreshRenameSessionWithOptionsChanged(Option<bool> renameOption, bool newValue)
        {
            AssertIsForeground();
            VerifyNotDismissed();

            // Recompute the result only if the previous result was computed with a different flag
            if (_optionSet.GetOption(renameOption) != newValue)
            {
                _optionSet = _optionSet.WithChangedOption(renameOption, newValue);

                var cancellationToken = _cancellationTokenSource.Token;

                UpdateReferenceLocationsTask(_allRenameLocationsTask.SafeContinueWithFromAsync(
                    t => _renameInfo.FindRenameLocationsAsync(_optionSet, cancellationToken),
                    cancellationToken, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Default));
            }
        }

323
        private void Dismiss(bool rollbackTemporaryEdits)
324 325 326 327 328 329 330 331 332 333 334
        {
            _dismissed = true;
            _workspace.WorkspaceChanged -= OnWorkspaceChanged;
            _textBufferAssociatedViewService.SubjectBuffersConnected -= OnSubjectBuffersConnected;

            foreach (var textBuffer in _openTextBuffers.Keys)
            {
                var document = textBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
                var isClosed = document == null;

                var openBuffer = _openTextBuffers[textBuffer];
335
                openBuffer.Disconnect(isClosed, rollbackTemporaryEdits);
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
            }

            this.UndoManager.Disconnect();

            if (_triggerView != null && !_triggerView.IsClosed)
            {
                _triggerView.Selection.Clear();
            }

            _renameService.ActiveSession = null;
        }

        private void VerifyNotDismissed()
        {
            if (_dismissed)
            {
352
                throw new InvalidOperationException(EditorFeaturesResources.This_session_has_already_been_dismissed);
353 354 355 356 357 358 359 360 361 362 363 364 365 366
            }
        }

        private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs args)
        {
            if (args.Kind != WorkspaceChangeKind.DocumentChanged)
            {
                if (!_dismissed)
                {
                    this.Cancel();
                }
            }
        }

367
        private void RaiseSessionSpansUpdated(ImmutableArray<InlineRenameLocation> locations)
368 369 370
        {
            AssertIsForeground();
            SetReferenceLocations(locations);
C
Cyrus Najmabadi 已提交
371
            ReferenceLocationsChanged?.Invoke(this, locations);
372 373
        }

374
        private void SetReferenceLocations(ImmutableArray<InlineRenameLocation> locations)
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
        {
            AssertIsForeground();

            var locationsByDocument = locations.ToLookup(l => l.Document.Id);

            _isApplyingEdit = true;
            foreach (var textBuffer in _openTextBuffers.Keys)
            {
                var documents = textBuffer.AsTextContainer().GetRelatedDocuments();

                if (!documents.Any(d => locationsByDocument.Contains(d.Id)))
                {
                    _openTextBuffers[textBuffer].SetReferenceSpans(SpecializedCollections.EmptyEnumerable<TextSpan>());
                }
                else
                {
                    var spans = documents.SelectMany(d => locationsByDocument[d.Id]).Select(l => l.TextSpan).Distinct();
                    _openTextBuffers[textBuffer].SetReferenceSpans(spans);
                }
            }

            _isApplyingEdit = false;
        }

        /// <summary>
        /// Updates the replacement text for the rename session and propagates it to all live buffers.
        /// </summary>
        internal void ApplyReplacementText(string replacementText, bool propagateEditImmediately)
        {
            AssertIsForeground();
            VerifyNotDismissed();
406
            this.ReplacementText = _renameInfo.GetFinalSymbolName(replacementText);
407

408 409
            var asyncToken = _asyncListener.BeginAsyncOperation(nameof(ApplyReplacementText));

410 411
            Action propagateEditAction = delegate
            {
412 413
                AssertIsForeground();

414 415
                if (_dismissed)
                {
416
                    asyncToken.Dispose();
417 418 419 420 421 422 423 424 425 426 427 428 429
                    return;
                }

                _isApplyingEdit = true;
                using (Logger.LogBlock(FunctionId.Rename_ApplyReplacementText, replacementText, _cancellationTokenSource.Token))
                {
                    foreach (var openBuffer in _openTextBuffers.Values)
                    {
                        openBuffer.ApplyReplacementText();
                    }
                }

                _isApplyingEdit = false;
430 431 432 433 434 435 436 437

                // We already kicked off UpdateConflictResolutionTask below (outside the delegate).
                // Now that we are certain the replacement text has been propagated to all of the
                // open buffers, it is safe to actually apply the replacements it has calculated.
                // See https://devdiv.visualstudio.com/DevDiv/_workitems?_a=edit&id=227513
                QueueApplyReplacements();

                asyncToken.Dispose();
438 439
            };

440 441 442 443 444 445 446 447 448 449 450 451 452
            // Start the conflict resolution task but do not apply the results immediately. The
            // buffer changes performed in propagateEditAction can cause source control modal
            // dialogs to show. Those dialogs pump, and yield the UI thread to whatever work is
            // waiting to be done there, including our ApplyReplacements work. If ApplyReplacements
            // starts running on the UI thread while propagateEditAction is still updating buffers
            // on the UI thread, we crash because we try to enumerate the undo stack while an undo
            // transaction is still in process. Therefore, we defer QueueApplyReplacements until
            // after the buffers have been edited, and any modal dialogs have been completed.
            // In addition to avoiding the crash, this also ensures that the resolved conflict text
            // is applied after the simple text change is propagated.
            // See https://devdiv.visualstudio.com/DevDiv/_workitems?_a=edit&id=227513
            UpdateConflictResolutionTask();

453 454 455 456 457 458 459
            if (propagateEditImmediately)
            {
                propagateEditAction();
            }
            else
            {
                // When responding to a text edit, we delay propagating the edit until the first transaction completes.
460 461 462 463 464
                ThreadingContext.JoinableTaskFactory.WithPriority(Dispatcher.CurrentDispatcher, DispatcherPriority.Send).RunAsync(async () =>
                {
                    await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true);
                    propagateEditAction();
                });
465 466 467 468 469 470 471 472 473 474
            }
        }

        private void UpdateConflictResolutionTask()
        {
            AssertIsForeground();

            _conflictResolutionTaskCancellationSource.Cancel();
            _conflictResolutionTaskCancellationSource = new CancellationTokenSource();

475 476
            // If the replacement text is empty, we do not update the results of the conflict
            // resolution task. We instead wait for a non-empty identifier.
477 478 479 480 481 482 483 484 485
            if (this.ReplacementText == string.Empty)
            {
                return;
            }

            var replacementText = this.ReplacementText;
            var optionSet = _optionSet;
            var cancellationToken = _conflictResolutionTaskCancellationSource.Token;

486 487
            var asyncToken = _asyncListener.BeginAsyncOperation(nameof(UpdateConflictResolutionTask));

488
            _conflictResolutionTask = _allRenameLocationsTask.SafeContinueWithFromAsync(
489
               t => t.Result.GetReplacementsAsync(replacementText, optionSet, cancellationToken),
490 491 492 493 494 495 496
               cancellationToken,
               TaskContinuationOptions.OnlyOnRanToCompletion,
               TaskScheduler.Default);

            _conflictResolutionTask.CompletesAsyncOperation(asyncToken);
        }

497
        private void QueueApplyReplacements()
498
        {
499 500 501 502 503 504 505 506
            // If the replacement text is empty, we do not update the results of the conflict
            // resolution task. We instead wait for a non-empty identifier.
            if (this.ReplacementText == string.Empty)
            {
                return;
            }

            var asyncToken = _asyncListener.BeginAsyncOperation(nameof(QueueApplyReplacements));
507 508 509 510 511 512 513
            _conflictResolutionTask
                .SafeContinueWith(
                    t => ComputeMergeResultAsync(t.Result, _conflictResolutionTaskCancellationSource.Token),
                    _conflictResolutionTaskCancellationSource.Token,
                    TaskContinuationOptions.OnlyOnRanToCompletion,
                    TaskScheduler.Default)
                .Unwrap()
514 515 516 517
                .SafeContinueWithFromAsync(
                    async t =>
                    {
                        await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true, _conflictResolutionTaskCancellationSource.Token);
518 519
                        _conflictResolutionTaskCancellationSource.Token.ThrowIfCancellationRequested();

520 521
                        ApplyReplacements(t.Result.replacementInfo, t.Result.mergeResult, _conflictResolutionTaskCancellationSource.Token);
                    },
522
                    _conflictResolutionTaskCancellationSource.Token,
523 524
                    TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously,
                    TaskScheduler.Default)
525 526 527 528 529 530 531 532
                .CompletesAsyncOperation(asyncToken);
        }

        private async Task<(IInlineRenameReplacementInfo replacementInfo, LinkedFileMergeSessionResult mergeResult)> ComputeMergeResultAsync(IInlineRenameReplacementInfo replacementInfo, CancellationToken cancellationToken)
        {
            var diffMergingSession = new LinkedFileDiffMergingSession(_baseSolution, replacementInfo.NewSolution, replacementInfo.NewSolution.GetChanges(_baseSolution), logSessionInfo: true);
            var mergeResult = await diffMergingSession.MergeDiffsAsync(mergeConflictHandler: null, cancellationToken: cancellationToken).ConfigureAwait(false);
            return (replacementInfo, mergeResult);
533 534
        }

535
        private void ApplyReplacements(IInlineRenameReplacementInfo replacementInfo, LinkedFileMergeSessionResult mergeResult, CancellationToken cancellationToken)
536 537 538 539 540 541 542 543 544 545 546 547 548
        {
            AssertIsForeground();
            cancellationToken.ThrowIfCancellationRequested();

            RaiseReplacementsComputed(replacementInfo);

            _isApplyingEdit = true;
            foreach (var textBuffer in _openTextBuffers.Keys)
            {
                var documents = textBuffer.CurrentSnapshot.GetRelatedDocumentsWithChanges();
                if (documents.Any())
                {
                    var textBufferManager = _openTextBuffers[textBuffer];
549
                    textBufferManager.ApplyConflictResolutionEdits(replacementInfo, mergeResult, documents, cancellationToken);
550 551 552 553 554 555 556 557 558
                }
            }

            _isApplyingEdit = false;
        }

        private void RaiseReplacementsComputed(IInlineRenameReplacementInfo resolution)
        {
            AssertIsForeground();
C
Cyrus Najmabadi 已提交
559
            ReplacementsComputed?.Invoke(this, resolution);
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
        }

        private void LogRenameSession(RenameLogMessage.UserActionOutcome outcome, bool previewChanges)
        {
            if (_conflictResolutionTask == null)
            {
                return;
            }

            var conflictResolutionFinishedComputing = _conflictResolutionTask.Status == TaskStatus.RanToCompletion;

            if (conflictResolutionFinishedComputing)
            {
                var result = _conflictResolutionTask.Result;
                var replacementKinds = result.GetAllReplacementKinds().ToList();

                Logger.Log(FunctionId.Rename_InlineSession_Session, RenameLogMessage.Create(
                    _optionSet,
                    outcome,
                    conflictResolutionFinishedComputing,
                    previewChanges,
                    replacementKinds));
            }
            else
            {
585
                Debug.Assert(outcome.HasFlag(RenameLogMessage.UserActionOutcome.Canceled));
586 587 588 589 590 591 592 593 594 595
                Logger.Log(FunctionId.Rename_InlineSession_Session, RenameLogMessage.Create(
                    _optionSet,
                    outcome,
                    conflictResolutionFinishedComputing,
                    previewChanges,
                    SpecializedCollections.EmptyList<InlineRenameReplacementKind>()));
            }
        }

        public void Cancel()
596 597 598 599 600
        {
            Cancel(rollbackTemporaryEdits: true);
        }

        private void Cancel(bool rollbackTemporaryEdits)
601 602 603 604 605
        {
            AssertIsForeground();
            VerifyNotDismissed();

            LogRenameSession(RenameLogMessage.UserActionOutcome.Canceled, previewChanges: false);
606
            Dismiss(rollbackTemporaryEdits);
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
            EndRenameSession();
        }

        public void Commit(bool previewChanges = false)
        {
            AssertIsForeground();
            VerifyNotDismissed();

            if (this.ReplacementText == string.Empty)
            {
                Cancel();
                return;
            }

            previewChanges = previewChanges || OptionSet.GetOption(RenameOptions.PreviewChanges);

            var result = _waitIndicator.Wait(
                title: EditorFeaturesResources.Rename,
625
                message: EditorFeaturesResources.Computing_Rename_information,
626 627 628 629 630 631
                allowCancel: true,
                action: waitContext => CommitCore(waitContext, previewChanges));

            if (result == WaitIndicatorResult.Canceled)
            {
                LogRenameSession(RenameLogMessage.UserActionOutcome.Canceled | RenameLogMessage.UserActionOutcome.Committed, previewChanges);
632
                Dismiss(rollbackTemporaryEdits: true);
633 634 635 636 637 638
                EndRenameSession();
            }
        }

        private void EndRenameSession()
        {
639
            _debuggingWorkspaceService.BeforeDebuggingStateChanged -= OnBeforeDebuggingStateChanged;
640 641 642 643 644 645 646 647 648 649 650 651 652
            CancelAllOpenDocumentTrackingTasks();
            RenameTrackingDismisser.DismissRenameTracking(_workspace, _workspace.GetOpenDocumentIds());
            _inlineRenameSessionDurationLogBlock.Dispose();
        }

        private void CancelAllOpenDocumentTrackingTasks()
        {
            _cancellationTokenSource.Cancel();
            _conflictResolutionTaskCancellationSource.Cancel();
        }

        private void CommitCore(IWaitContext waitContext, bool previewChanges)
        {
653 654
            var eventName = previewChanges ? FunctionId.Rename_CommitCoreWithPreview : FunctionId.Rename_CommitCore;
            using (Logger.LogBlock(eventName, KeyValueLogMessage.Create(LogType.UserAction), waitContext.CancellationToken))
655 656 657 658 659 660 661 662 663 664
            {
                _conflictResolutionTask.Wait(waitContext.CancellationToken);
                waitContext.AllowCancel = false;

                Solution newSolution = _conflictResolutionTask.Result.NewSolution;
                if (previewChanges)
                {
                    var previewService = _workspace.Services.GetService<IPreviewDialogService>();

                    newSolution = previewService.PreviewChanges(
665
                        string.Format(EditorFeaturesResources.Preview_Changes_0, EditorFeaturesResources.Rename),
666
                        "vs.csharp.refactoring.rename",
667
                        string.Format(EditorFeaturesResources.Rename_0_to_1_colon, this.OriginalSymbolName, this.ReplacementText),
668 669 670 671 672 673 674 675 676 677 678 679 680 681
                        _renameInfo.FullDisplayName,
                        _renameInfo.Glyph,
                        _conflictResolutionTask.Result.NewSolution,
                        _triggerDocument.Project.Solution);

                    if (newSolution == null)
                    {
                        // User clicked cancel.
                        return;
                    }
                }

                // The user hasn't cancelled by now, so we're done waiting for them. Off to
                // rename!
682
                waitContext.Message = EditorFeaturesResources.Updating_files;
683

684
                Dismiss(rollbackTemporaryEdits: true);
685 686 687 688 689 690
                CancelAllOpenDocumentTrackingTasks();

                ApplyRename(newSolution, waitContext);

                LogRenameSession(RenameLogMessage.UserActionOutcome.Committed, previewChanges);

691
                EndRenameSession();
692 693 694 695 696 697 698 699 700 701 702 703
            }
        }

        private void ApplyRename(Solution newSolution, IWaitContext waitContext)
        {
            var changes = _baseSolution.GetChanges(newSolution);
            var changedDocumentIDs = changes.GetProjectChanges().SelectMany(c => c.GetChangedDocuments()).ToList();

            if (!_renameInfo.TryOnBeforeGlobalSymbolRenamed(_workspace, changedDocumentIDs, this.ReplacementText))
            {
                var notificationService = _workspace.Services.GetService<INotificationService>();
                notificationService.SendNotification(
704 705
                    EditorFeaturesResources.Rename_operation_was_cancelled_or_is_not_valid,
                    EditorFeaturesResources.Rename_Symbol,
706 707 708 709
                    NotificationSeverity.Error);
                return;
            }

710
            using (var undoTransaction = _workspace.OpenGlobalUndoTransaction(EditorFeaturesResources.Inline_Rename))
711 712 713 714 715 716 717 718 719 720 721 722
            {
                var finalSolution = newSolution.Workspace.CurrentSolution;
                foreach (var id in changedDocumentIDs)
                {
                    // If the document supports syntax tree, then create the new solution from the
                    // updated syntax root.  This should ensure that annotations are preserved, and
                    // prevents the solution from having to reparse documents when we already have
                    // the trees for them.  If we don't support syntax, then just use the text of
                    // the document.
                    var newDocument = newSolution.GetDocument(id);
                    if (newDocument.SupportsSyntaxTree)
                    {
C
CyrusNajmabadi 已提交
723
                        var root = newDocument.GetSyntaxRootSynchronously(waitContext.CancellationToken);
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
                        finalSolution = finalSolution.WithDocumentSyntaxRoot(id, root);
                    }
                    else
                    {
                        var newText = newDocument.GetTextAsync(waitContext.CancellationToken).WaitAndGetResult(waitContext.CancellationToken);
                        finalSolution = finalSolution.WithDocumentText(id, newText);
                    }
                }

                if (_workspace.TryApplyChanges(finalSolution))
                {
                    if (!_renameInfo.TryOnAfterGlobalSymbolRenamed(_workspace, changedDocumentIDs, this.ReplacementText))
                    {
                        var notificationService = _workspace.Services.GetService<INotificationService>();
                        notificationService.SendNotification(
739 740
                            EditorFeaturesResources.Rename_operation_was_not_properly_completed_Some_file_might_not_have_been_updated,
                            EditorFeaturesResources.Rename_Symbol,
741 742 743 744 745 746 747 748 749 750
                            NotificationSeverity.Information);
                    }

                    undoTransaction.Commit();
                }
            }
        }

        internal bool TryGetContainingEditableSpan(SnapshotPoint point, out SnapshotSpan editableSpan)
        {
C
CyrusNajmabadi 已提交
751
            editableSpan = default;
C
CyrusNajmabadi 已提交
752
            if (!_openTextBuffers.TryGetValue(point.Snapshot.TextBuffer, out var bufferManager))
753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
            {
                return false;
            }

            foreach (var span in bufferManager.GetEditableSpansForSnapshot(point.Snapshot))
            {
                if (span.Contains(point) || span.End == point)
                {
                    editableSpan = span;
                    return true;
                }
            }

            return false;
        }
    }
}