This repository was archived by the owner on Mar 17, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathPackageCompletionSource.cs
379 lines (327 loc) · 16 KB
/
PackageCompletionSource.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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Xml.Linq;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.Imaging.Interop;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
using ProjectFileTools.Helpers;
using ProjectFileTools.NuGetSearch;
using ProjectFileTools.NuGetSearch.Contracts;
using ProjectFileTools.NuGetSearch.Feeds;
namespace ProjectFileTools.Completion
{
internal class PackageCompletionSource : ICompletionSource
{
private static readonly IReadOnlyDictionary<string, string> AttributeToCompletionTypeMap = new Dictionary<string, string>(StringComparer.Ordinal)
{
{"Include", "Name" },
{"Update", "Name" },
{"Exclude", "Name" },
{"Remove", "Name" },
{"Version", "Version" }
};
private readonly IClassifier _classifier;
private readonly ICompletionBroker _completionBroker;
private readonly IPackageSearchManager _searchManager;
private readonly ITextBuffer _textBuffer;
private PackageCompletionSet _currentCompletionSet;
private ICompletionSession _currentSession;
private bool _isSelfTrigger;
private IPackageFeedSearchJob<Tuple<string, FeedKind>> _nameSearchJob;
private int _pos;
private IPackageFeedSearchJob<Tuple<string, FeedKind>> _versionSearchJob;
public static PackageCompletionSource GetOrAddCompletionSource(ITextBuffer textBuffer, ICompletionBroker completionBroker, IClassifierAggregatorService classifier, IPackageSearchManager searchManager)
{
if (textBuffer.Properties.TryGetProperty(typeof(PackageCompletionSource), out PackageCompletionSource source))
{
return source;
}
return new PackageCompletionSource(textBuffer, completionBroker, classifier, searchManager);
}
private PackageCompletionSource(ITextBuffer textBuffer, ICompletionBroker completionBroker, IClassifierAggregatorService classifier, IPackageSearchManager searchManager)
{
_classifier = classifier.GetClassifier(textBuffer);
_searchManager = searchManager;
_textBuffer = textBuffer;
_completionBroker = completionBroker;
if (textBuffer.Properties.ContainsProperty(typeof(PackageCompletionSource)))
{
textBuffer.Properties.RemoveProperty(typeof(PackageCompletionSource));
}
textBuffer.Properties.AddProperty(typeof(PackageCompletionSource), this);
}
public static bool IsInRangeForPackageCompletion(ITextSnapshot snapshot, int pos, out Span span, out string packageName, out string packageVersion, out string completionType)
{
XmlInfo info = XmlTools.GetXmlInfo(snapshot, pos);
if (info?.AttributeName != null && TryGetPackageInfoFromXml(info, out packageName, out packageVersion) && AttributeToCompletionTypeMap.TryGetValue(info.AttributeName, out completionType))
{
span = new Span(info.AttributeValueStart, info.AttributeValueLength);
return true;
}
completionType = null;
packageName = null;
packageVersion = null;
span = default(Span);
return false;
}
public static bool TryGetPackageInfoFromXml(XmlInfo info, out string packageName, out string packageVersion)
{
if (info?.AttributeName != null
&& (info.TagName == "PackageReference" || info.TagName == "DotNetCliToolReference")
&& info.AttributeName != null && AttributeToCompletionTypeMap.ContainsKey(info.AttributeName)
&& info.TryGetElement(out XElement element))
{
XAttribute name = element.Attribute(XName.Get("Include"))
?? element.Attribute(XName.Get("Update"))
?? element.Attribute(XName.Get("Exclude"))
?? element.Attribute(XName.Get("Remove"));
XAttribute version = element.Attribute(XName.Get("Version"));
packageName = name?.Value;
packageVersion = version?.Value;
return true;
}
packageName = null;
packageVersion = null;
return false;
}
public static bool TryHealOrAdvanceAttributeSelection(ITextSnapshot snapshot, ref int pos, out Span targetSpan, out string newText, out bool isHealingRequired)
{
XmlInfo info = XmlTools.GetXmlInfo(snapshot, pos);
if (info?.AttributeName == null || !info.TryGetElement(out XElement element) || info.TagName != "PackageReference" && info.TagName != "DotNetCliToolReference")
{
isHealingRequired = false;
newText = null;
targetSpan = default(Span);
return false;
}
XAttribute version = element.Attribute(XName.Get("Version"));
if (version == null)
{
isHealingRequired = true;
element.SetAttributeValue(XName.Get("Version"), "");
newText = element.ToString();
string versionString = "Version=\"";
pos = newText.IndexOf(versionString) + versionString.Length + info.TagStart;
targetSpan = new Span(info.TagStart, info.RealDocumentLength);
return true;
}
newText = info.ElementText;
isHealingRequired = info.IsModified;
int versionIndex = info.ElementText.IndexOf("Version");
int quoteIndex = info.ElementText.IndexOf('"', versionIndex);
int proposedPos = info.TagStart + quoteIndex + 1;
bool move = info.AttributeName != "Version";
pos = proposedPos;
targetSpan = new Span(info.TagStart, info.RealDocumentLength);
return move;
}
public void AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets)
{
_currentSession = session;
ITextSnapshot snapshot = _textBuffer.CurrentSnapshot;
ITrackingPoint point = session.GetTriggerPoint(_textBuffer);
int pos = point.GetPosition(snapshot);
if (pos < snapshot.Length && _classifier.GetClassificationSpans(new SnapshotSpan(snapshot, new Span(pos, 1))).Any(x => (x.ClassificationType.Classification?.IndexOf("comment", StringComparison.OrdinalIgnoreCase) ?? -1) > -1))
{
return;
}
_pos = pos;
if (!IsInRangeForPackageCompletion(snapshot, pos, out Span span, out string name, out string version, out string completionType))
{
_nameSearchJob?.Cancel();
_versionSearchJob?.Cancel();
_nameSearchJob = null;
_versionSearchJob = null;
return;
}
if (_isSelfTrigger)
{
_isSelfTrigger = false;
if (_currentCompletionSet != null)
{
completionSets.Add(_currentCompletionSet);
}
return;
}
string text = snapshot.GetText();
int targetFrameworkElementStartIndex = text.IndexOf("<TargetFramework>", StringComparison.OrdinalIgnoreCase);
int targetFrameworksElementStartIndex = text.IndexOf("<TargetFrameworks>", StringComparison.OrdinalIgnoreCase);
string tfm = "netcoreapp1.0";
if (targetFrameworksElementStartIndex > -1)
{
int closeTfms = text.IndexOf("</TargetFrameworks>", targetFrameworksElementStartIndex);
int realStart = targetFrameworksElementStartIndex + "<TargetFrameworks>".Length;
string allTfms = text.Substring(realStart, closeTfms - realStart);
tfm = allTfms.Split(';')[0];
}
else if (targetFrameworkElementStartIndex > -1)
{
int closeTfm = text.IndexOf("</TargetFramework>", targetFrameworkElementStartIndex);
int realStart = targetFrameworkElementStartIndex + "<TargetFramework>".Length;
tfm = text.Substring(realStart, closeTfm - realStart);
}
bool showLoading = false;
switch (completionType)
{
case "Name":
if (_nameSearchJob != null)
{
_nameSearchJob.Cancel();
_nameSearchJob.Updated -= UpdateCompletions;
}
_versionSearchJob?.Cancel();
_versionSearchJob = null;
_nameSearchJob = _searchManager.SearchPackageNames(name, tfm);
_nameSearchJob.Updated += UpdateCompletions;
showLoading = _nameSearchJob.RemainingFeeds.Count > 0;
break;
case "Version":
if (_versionSearchJob != null)
{
_versionSearchJob.Cancel();
_versionSearchJob.Updated -= UpdateCompletions;
}
_nameSearchJob?.Cancel();
_nameSearchJob = null;
_versionSearchJob = _searchManager.SearchPackageVersions(name, tfm);
_versionSearchJob.Updated += UpdateCompletions;
showLoading = _versionSearchJob.RemainingFeeds.Count > 0;
break;
}
_currentCompletionSet = _currentSession.IsDismissed ? null : _currentSession.CompletionSets.FirstOrDefault(x => x is PackageCompletionSet) as PackageCompletionSet;
bool newCompletionSet = _currentCompletionSet == null;
if (newCompletionSet)
{
_currentCompletionSet = new PackageCompletionSet("PackageCompletion", "Package Completion", _textBuffer.CurrentSnapshot.CreateTrackingSpan(span, SpanTrackingMode.EdgeInclusive));
}
if (_nameSearchJob != null)
{
ProduceNameCompletionSet();
}
else if (_versionSearchJob != null)
{
ProduceVersionCompletionSet();
}
//If we're not part of an existing session & the results have already been
// finalized and those results assert that no packages match, show that
// there is no such package/version
if (!session.IsDismissed && !session.CompletionSets.Any(x => x is PackageCompletionSet))
{
if (((_nameSearchJob != null && _nameSearchJob.RemainingFeeds.Count == 0)
|| (_versionSearchJob != null && _versionSearchJob.RemainingFeeds.Count == 0))
&& _currentCompletionSet.Completions.Count == 0)
{
_currentCompletionSet.AccessibleCompletions.Add(new Microsoft.VisualStudio.Language.Intellisense.Completion("(No Results)"));
}
completionSets.Add(_currentCompletionSet);
}
}
public void Dispose()
{
}
private void ProduceNameCompletionSet()
{
List<Microsoft.VisualStudio.Language.Intellisense.Completion> completions = new List<Microsoft.VisualStudio.Language.Intellisense.Completion>();
Dictionary<string, FeedKind> packageLookup = new Dictionary<string, FeedKind>();
foreach (Tuple<string, FeedKind> info in _nameSearchJob.Results)
{
if (!packageLookup.TryGetValue(info.Item1, out FeedKind existingInfo) || info.Item2 == FeedKind.Local)
{
packageLookup[info.Item1] = info.Item2;
}
}
foreach (KeyValuePair<string, FeedKind> entry in packageLookup.OrderBy(x => x.Key))
{
ImageMoniker moniker = KnownMonikers.NuGet;
switch (entry.Value)
{
case FeedKind.Local:
moniker = KnownMonikers.FolderClosed;
break;
//TODO: Add different icons for MyGet/network/etc
}
completions.Add(new PackageCompletion(entry.Key, entry.Key, entry.Key, moniker, entry.Key));
}
_currentCompletionSet.AccessibleCompletions.Clear();
_currentCompletionSet.AccessibleCompletions.AddRange(completions);
}
private void ProduceVersionCompletionSet()
{
List<Microsoft.VisualStudio.Language.Intellisense.Completion> completions = new List<Microsoft.VisualStudio.Language.Intellisense.Completion>();
Dictionary<string, FeedKind> iconMap = new Dictionary<string, FeedKind>();
foreach (Tuple<string, FeedKind> info in _versionSearchJob.Results)
{
if (!iconMap.TryGetValue(info.Item1, out FeedKind existing) || existing != FeedKind.Local)
{
iconMap[info.Item1] = info.Item2;
}
}
foreach (KeyValuePair<string, FeedKind> entry in iconMap.OrderByDescending(x => SemanticVersion.Parse(x.Key)))
{
ImageMoniker moniker = KnownMonikers.NuGet;
switch (entry.Value)
{
case FeedKind.Local:
moniker = KnownMonikers.FolderClosed;
break;
//TODO: Add different icons for MyGet/network/etc
}
completions.Add(new VersionCompletion(entry.Key, entry.Key, null, moniker, entry.Key));
}
_currentCompletionSet.AccessibleCompletions.Clear();
_currentCompletionSet.AccessibleCompletions.AddRange(completions);
}
private async void UpdateCompletions(object sender, EventArgs e)
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
try
{
if (_currentCompletionSet == null || _currentSession == null)
{
return;
}
string displayText = _currentCompletionSet?.SelectionStatus?.Completion?.DisplayText;
if (_nameSearchJob != null)
{
ProduceNameCompletionSet();
}
else if (_versionSearchJob != null)
{
ProduceVersionCompletionSet();
}
if (!_currentSession.IsStarted && _currentCompletionSet.Completions.Count > 0)
{
_isSelfTrigger = true;
_currentSession = _completionBroker.CreateCompletionSession(_currentSession.TextView, _currentSession.GetTriggerPoint(_textBuffer), true);
_currentSession.Start();
}
if (!_currentSession.IsDismissed)
{
_currentSession.Filter();
if (displayText != null)
{
foreach (Microsoft.VisualStudio.Language.Intellisense.Completion completion in _currentSession.SelectedCompletionSet.Completions)
{
if (completion.DisplayText == displayText)
{
_currentCompletionSet.SelectionStatus = new CompletionSelectionStatus(completion, true, true);
break;
}
}
}
//_currentSession.Dismiss();
//_currentSession = _completionBroker.TriggerCompletion(_currentSession.TextView);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
}
}
}