NavigationBarController_ModelComputation.cs 11.7 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 5 6 7 8 9

using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Internal.Log;
10
using Microsoft.CodeAnalysis.Shared.Extensions;
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigationBar
{
    internal partial class NavigationBarController
    {
        /// <summary>
        /// The computation of the last model.
        /// </summary>
        private Task<NavigationBarModel> _modelTask;
        private NavigationBarModel _lastCompletedModel;
        private CancellationTokenSource _modelTaskCancellationSource = new CancellationTokenSource();

        /// <summary>
        /// Starts a new task to compute the model based on the current text.
        /// </summary>
        private void StartModelUpdateAndSelectedItemUpdateTasks(int modelUpdateDelay, int selectedItemUpdateDelay, bool updateUIWhenDone)
        {
            AssertIsForeground();

            var textSnapshot = _subjectBuffer.CurrentSnapshot;
            var document = textSnapshot.GetOpenDocumentInCurrentContextWithChanges();
            if (document == null)
            {
                return;
            }

            // Cancel off any existing work
            _modelTaskCancellationSource.Cancel();

            _modelTaskCancellationSource = new CancellationTokenSource();
            var cancellationToken = _modelTaskCancellationSource.Token;

            // Enqueue a new computation for the model
            var asyncToken = _asyncListener.BeginAsyncOperation(GetType().Name + ".StartModelUpdateTask");
            _modelTask =
                Task.Delay(modelUpdateDelay, cancellationToken)
                    .SafeContinueWithFromAsync(
                        _ => ComputeModelAsync(document, textSnapshot, cancellationToken),
                        cancellationToken,
                        TaskContinuationOptions.OnlyOnRanToCompletion,
                        TaskScheduler.Default);
            _modelTask.CompletesAsyncOperation(asyncToken);

            StartSelectedItemUpdateTask(selectedItemUpdateDelay, updateUIWhenDone);
        }

        /// <summary>
        /// Computes a model for the given snapshot.
        /// </summary>
        private async Task<NavigationBarModel> ComputeModelAsync(Document document, ITextSnapshot snapshot, CancellationToken cancellationToken)
        {
            // TODO: remove .FirstOrDefault()
67
            var languageService = document.GetLanguageService<INavigationBarItemService>();
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 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
            if (languageService != null)
            {
                // check whether we can re-use lastCompletedModel. otherwise, update lastCompletedModel here.
                // the model should be only updated here
                if (_lastCompletedModel != null)
                {
                    var semanticVersion = await document.Project.GetDependentSemanticVersionAsync(CancellationToken.None).ConfigureAwait(false);
                    if (_lastCompletedModel.SemanticVersionStamp == semanticVersion && SpanStillValid(_lastCompletedModel, snapshot, cancellationToken))
                    {
                        // it looks like we can re-use previous model
                        return _lastCompletedModel;
                    }
                }

                using (Logger.LogBlock(FunctionId.NavigationBar_ComputeModelAsync, cancellationToken))
                {
                    var items = await languageService.GetItemsAsync(document, cancellationToken).ConfigureAwait(false);
                    if (items != null)
                    {
                        items.Do(i => i.InitializeTrackingSpans(snapshot));
                        var version = await document.Project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false);

                        _lastCompletedModel = new NavigationBarModel(items, version, languageService);
                        return _lastCompletedModel;
                    }
                }
            }

            _lastCompletedModel = _lastCompletedModel ??
                    new NavigationBarModel(SpecializedCollections.EmptyList<NavigationBarItem>(), new VersionStamp(), null);
            return _lastCompletedModel;
        }

        private Task<NavigationBarSelectedTypeAndMember> _selectedItemInfoTask;
        private CancellationTokenSource _selectedItemInfoTaskCancellationSource = new CancellationTokenSource();

        /// <summary>
        /// Starts a new task to compute what item should be selected.
        /// </summary>
        private void StartSelectedItemUpdateTask(int delay, bool updateUIWhenDone)
        {
            AssertIsForeground();

            var currentView = _presenter.TryGetCurrentView();
            if (currentView == null)
            {
                return;
            }

            // Cancel off any existing work
            _selectedItemInfoTaskCancellationSource.Cancel();
            _selectedItemInfoTaskCancellationSource = new CancellationTokenSource();

            var cancellationToken = _selectedItemInfoTaskCancellationSource.Token;
            var subjectBufferCaretPosition = currentView.GetCaretPoint(_subjectBuffer);

            if (!subjectBufferCaretPosition.HasValue)
            {
                return;
            }

            var asyncToken = _asyncListener.BeginAsyncOperation(GetType().Name + ".StartSelectedItemUpdateTask");

            // Enqueue a new computation for the selected item
            _selectedItemInfoTask = _modelTask.ContinueWithAfterDelay(
                t => t.IsCanceled ? new NavigationBarSelectedTypeAndMember(null, null)
                                  : ComputeSelectedTypeAndMember(t.Result, subjectBufferCaretPosition.Value, cancellationToken),
                cancellationToken,
                delay,
                TaskContinuationOptions.None,
                TaskScheduler.Default);
            _selectedItemInfoTask.CompletesAsyncOperation(asyncToken);

            if (updateUIWhenDone)
            {
                asyncToken = _asyncListener.BeginAsyncOperation(GetType().Name + ".StartSelectedItemUpdateTask.UpdateUI");
144 145 146 147
                _selectedItemInfoTask.SafeContinueWithFromAsync(
                    async t =>
                    {
                        await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true, cancellationToken);
148 149
                        cancellationToken.ThrowIfCancellationRequested();

150 151
                        PushSelectedItemsToPresenter(t.Result);
                    },
152
                    cancellationToken,
153 154
                    TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously,
                    TaskScheduler.Default).CompletesAsyncOperation(asyncToken);
155 156 157 158 159 160 161
            }
        }

        internal static NavigationBarSelectedTypeAndMember ComputeSelectedTypeAndMember(NavigationBarModel model, SnapshotPoint caretPosition, CancellationToken cancellationToken)
        {
            var leftItem = GetMatchingItem(model.Types, caretPosition, model.ItemService, cancellationToken);

C
CyrusNajmabadi 已提交
162
            if (leftItem.item == null)
163 164 165 166 167
            {
                // Nothing to show at all
                return new NavigationBarSelectedTypeAndMember(null, null);
            }

C
CyrusNajmabadi 已提交
168
            var rightItem = GetMatchingItem(leftItem.item.ChildItems, caretPosition, model.ItemService, cancellationToken);
169

C
CyrusNajmabadi 已提交
170
            return new NavigationBarSelectedTypeAndMember(leftItem.item, leftItem.gray, rightItem.item, rightItem.gray);
171 172 173 174 175 176 177
        }

        /// <summary>
        /// Finds the item that point is in, or if it's not in any items, gets the first item that's
        /// positioned after the cursor.
        /// </summary>
        /// <returns>A tuple of the matching item, and if it should be shown grayed.</returns>
C
CyrusNajmabadi 已提交
178
        private static (T item, bool gray) GetMatchingItem<T>(IEnumerable<T> items, SnapshotPoint point, INavigationBarItemService itemsService, CancellationToken cancellationToken) where T : NavigationBarItem
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
        {
            T exactItem = null;
            int exactItemStart = 0;
            T nextItem = null;
            int nextItemStart = int.MaxValue;

            foreach (var item in items)
            {
                foreach (var span in item.TrackingSpans.Select(s => s.GetSpan(point.Snapshot)))
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    if (span.Contains(point) || span.End == point)
                    {
                        // This is the item we should show normally. We'll continue looking at other
                        // items as there might be a nested type that we're actually in. If there
                        // are multiple items containing the point, choose whichever containing span
                        // starts later because that will be the most nested item.

                        if (exactItem == null || span.Start >= exactItemStart)
                        {
                            exactItem = item;
                            exactItemStart = span.Start;
                        }
                    }
                    else if (span.Start > point && span.Start <= nextItemStart)
                    {
                        nextItem = item;
                        nextItemStart = span.Start;
                    }
                }
            }

            if (exactItem != null)
            {
C
CyrusNajmabadi 已提交
214
                return (exactItem, gray: false);
215 216 217 218 219 220 221 222 223 224 225
            }
            else
            {
                // The second parameter is if we should show it grayed. We'll be nice and say false
                // unless we actually have an item
                var itemToGray = nextItem ?? items.LastOrDefault();
                if (itemToGray != null && !itemsService.ShowItemGrayedIfNear(itemToGray))
                {
                    itemToGray = null;
                }

C
CyrusNajmabadi 已提交
226
                return (itemToGray, gray: itemToGray != null);
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
            }
        }

        private static bool SpanStillValid(NavigationBarModel model, ITextSnapshot snapshot, CancellationToken cancellationToken)
        {
            // even if semantic version is same, portion of text could have been copied & pasted with 
            // exact same top level content.
            // go through spans to see whether this happened.
            // 
            // paying cost of moving spans forward shouldn't be matter since we need to pay that 
            // price soon or later to figure out selected item.
            foreach (var type in model.Types)
            {
                if (!SpanStillValid(type.TrackingSpans, snapshot))
                {
                    return false;
                }

                foreach (var member in type.ChildItems)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    if (!SpanStillValid(member.TrackingSpans, snapshot))
                    {
                        return false;
                    }
                }
            }

            return true;
        }

        private static bool SpanStillValid(IList<ITrackingSpan> spans, ITextSnapshot snapshot)
        {
            for (var i = 0; i < spans.Count; i++)
            {
                var span = spans[i];
                var currentSpan = span.GetSpan(snapshot);
                if (currentSpan.IsEmpty)
                {
                    return false;
                }
            }

            return true;
        }
    }
}