-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
Copy pathDefinitionContextTracker.cs
209 lines (181 loc) · 10.7 KB
/
DefinitionContextTracker.cs
1
2
3
4
5
6
7
8
9
10
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
67
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.FindUsages;
using Microsoft.CodeAnalysis.GoToDefinition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.MetadataAsSource;
using Microsoft.CodeAnalysis.Navigation;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Threading;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeDefinitionWindow
{
/// <summary>
/// A type that tracks caret movements, and when you've been on an identifier for awhile, pushes the new
/// code definition window context to the <see cref="ICodeDefinitionWindowService"/>.
/// </summary>
[Export(typeof(ITextViewConnectionListener))]
[Export(typeof(DefinitionContextTracker))]
[ContentType(ContentTypeNames.RoslynContentType)]
[TextViewRole(PredefinedTextViewRoles.Interactive)]
[method: ImportingConstructor]
[method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
internal class DefinitionContextTracker(
IMetadataAsSourceFileService metadataAsSourceFileService,
ICodeDefinitionWindowService codeDefinitionWindowService,
IThreadingContext threadingContext,
IGlobalOptionService globalOptions,
IAsynchronousOperationListenerProvider listenerProvider) : ITextViewConnectionListener
{
private readonly HashSet<ITextView> _subscribedViews = new HashSet<ITextView>();
private readonly IMetadataAsSourceFileService _metadataAsSourceFileService = metadataAsSourceFileService;
private readonly ICodeDefinitionWindowService _codeDefinitionWindowService = codeDefinitionWindowService;
private readonly IThreadingContext _threadingContext = threadingContext;
private readonly IAsynchronousOperationListener _asyncListener = listenerProvider.GetListener(FeatureAttribute.CodeDefinitionWindow);
private readonly IGlobalOptionService _globalOptions = globalOptions;
private CancellationTokenSource? _currentUpdateCancellationToken;
void ITextViewConnectionListener.SubjectBuffersConnected(ITextView textView, ConnectionReason reason, IReadOnlyCollection<ITextBuffer> subjectBuffers)
{
Contract.ThrowIfFalse(_threadingContext.JoinableTaskContext.IsOnMainThread);
// We won't listen to caret changes in the code definition window itself, since navigations there would cause it to
// keep refreshing itself.
if (!_subscribedViews.Contains(textView) && !textView.Roles.Contains(PredefinedTextViewRoles.CodeDefinitionView))
{
_subscribedViews.Add(textView);
textView.Caret.PositionChanged += OnTextViewCaretPositionChanged;
QueueUpdateForCaretPosition(textView.Caret.Position);
}
}
void ITextViewConnectionListener.SubjectBuffersDisconnected(ITextView textView, ConnectionReason reason, IReadOnlyCollection<ITextBuffer> subjectBuffers)
{
Contract.ThrowIfFalse(_threadingContext.JoinableTaskContext.IsOnMainThread);
if (reason == ConnectionReason.TextViewLifetime ||
!textView.BufferGraph.GetTextBuffers(b => b.ContentType.IsOfType(ContentTypeNames.RoslynContentType)).Any())
{
if (_subscribedViews.Contains(textView))
{
_subscribedViews.Remove(textView);
textView.Caret.PositionChanged -= OnTextViewCaretPositionChanged;
}
}
}
private void OnTextViewCaretPositionChanged(object? sender, CaretPositionChangedEventArgs e)
{
Contract.ThrowIfFalse(_threadingContext.JoinableTaskContext.IsOnMainThread);
QueueUpdateForCaretPosition(e.NewPosition);
}
private void QueueUpdateForCaretPosition(CaretPosition caretPosition)
{
Contract.ThrowIfFalse(_threadingContext.JoinableTaskContext.IsOnMainThread);
// Cancel any pending update for this view
_currentUpdateCancellationToken?.Cancel();
// See if we moved somewhere else in a projection that we care about
var pointInRoslynSnapshot = caretPosition.Point.GetPoint(tb => tb.ContentType.IsOfType(ContentTypeNames.RoslynContentType), caretPosition.Affinity);
if (pointInRoslynSnapshot == null)
{
return;
}
_currentUpdateCancellationToken = new CancellationTokenSource();
var cancellationToken = _currentUpdateCancellationToken.Token;
var asyncToken = _asyncListener.BeginAsyncOperation(nameof(DefinitionContextTracker) + "." + nameof(QueueUpdateForCaretPosition));
UpdateForCaretPositionAsync(pointInRoslynSnapshot.Value, cancellationToken).CompletesAsyncOperation(asyncToken);
}
private async Task UpdateForCaretPositionAsync(SnapshotPoint pointInRoslynSnapshot, CancellationToken cancellationToken)
{
try
{
await _asyncListener.Delay(DelayTimeSpan.Short, cancellationToken).ConfigureAwait(false);
// If it's not open, don't do anything, since if we are going to show locations in metadata that might
// be expensive. This doesn't cause a functional issue, since opening the window clears whatever was previously there
// so the user won't notice we weren't doing anything when it was open.
if (!await _codeDefinitionWindowService.IsWindowOpenAsync(cancellationToken).ConfigureAwait(false))
return;
var snapshot = pointInRoslynSnapshot.Snapshot;
var workspace = snapshot.TextBuffer.GetWorkspace();
var document = snapshot.GetOpenDocumentInCurrentContextWithChanges();
if (workspace is null || document is null)
return;
// Ensure we're off the UI thread for the rest of this since we don't want to be computing locations on the UI thread.
await TaskScheduler.Default;
var locations = await GetContextFromPointAsync(workspace, document, pointInRoslynSnapshot, cancellationToken).ConfigureAwait(true);
await _codeDefinitionWindowService.SetContextAsync(locations, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
}
catch (Exception ex) when (FatalError.ReportAndCatch(ex))
{
}
}
/// <summary>
/// Internal for testing purposes.
/// </summary>
internal async Task<ImmutableArray<CodeDefinitionWindowLocation>> GetContextFromPointAsync(
Workspace workspace, Document document, int position, CancellationToken cancellationToken)
{
var navigableItems = await GoToDefinitionHelpers.GetDefinitionsAsync(document, position, cancellationToken).ConfigureAwait(false);
if (navigableItems?.Any() == true)
{
var navigationService = workspace.Services.GetRequiredService<IDocumentNavigationService>();
using var _ = PooledObjects.ArrayBuilder<CodeDefinitionWindowLocation>.GetInstance(out var builder);
foreach (var item in navigableItems)
{
if (await navigationService.CanNavigateToSpanAsync(workspace, item.Document.Id, item.SourceSpan, cancellationToken).ConfigureAwait(false))
{
var text = await item.Document.GetTextAsync(document.Project.Solution, cancellationToken).ConfigureAwait(false);
var linePositionSpan = text.Lines.GetLinePositionSpan(item.SourceSpan);
if (item.Document.FilePath != null)
{
builder.Add(new CodeDefinitionWindowLocation(item.DisplayTaggedParts.JoinText(), item.Document.FilePath, linePositionSpan.Start));
}
}
}
return builder.ToImmutable();
}
// We didn't have regular source references, but possibly:
// 1. Another language (like XAML) will take over via ISymbolNavigationService
// 2. There are no locations from source, so we'll try to generate a metadata as source file and use that
var symbol = await SymbolFinder.FindSymbolAtPositionAsync(
document,
position,
cancellationToken: cancellationToken).ConfigureAwait(false);
if (symbol == null)
{
return ImmutableArray<CodeDefinitionWindowLocation>.Empty;
}
var symbolNavigationService = workspace.Services.GetRequiredService<ISymbolNavigationService>();
var definitionItem = symbol.ToNonClassifiedDefinitionItem(document.Project.Solution, includeHiddenLocations: false);
var result = await symbolNavigationService.GetExternalNavigationSymbolLocationAsync(definitionItem, cancellationToken).ConfigureAwait(false);
if (result != null)
{
return ImmutableArray.Create(new CodeDefinitionWindowLocation(symbol.ToDisplayString(), result.Value.filePath, result.Value.linePosition));
}
else if (_metadataAsSourceFileService.IsNavigableMetadataSymbol(symbol))
{
var options = _globalOptions.GetMetadataAsSourceOptions(document.Project.Services);
var declarationFile = await _metadataAsSourceFileService.GetGeneratedFileAsync(workspace, document.Project, symbol, signaturesOnly: false, options, cancellationToken).ConfigureAwait(false);
var identifierSpan = declarationFile.IdentifierLocation.GetLineSpan().Span;
return ImmutableArray.Create(new CodeDefinitionWindowLocation(symbol.ToDisplayString(), declarationFile.FilePath, identifierSpan.Start));
}
return ImmutableArray<CodeDefinitionWindowLocation>.Empty;
}
}
}