|
| 1 | +#nullable enable |
| 2 | + |
| 3 | +using System.Collections.Concurrent; |
| 4 | +using System.Collections.Immutable; |
| 5 | +using System.Threading; |
| 6 | +using ChinesePinyinIntelliSenseExtender.Options; |
| 7 | +using ChinesePinyinIntelliSenseExtender.Util; |
| 8 | +using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; |
| 9 | +using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; |
| 10 | +using Microsoft.VisualStudio.Text; |
| 11 | +using Microsoft.VisualStudio.Text.PatternMatching; |
| 12 | + |
| 13 | +namespace ChinesePinyinIntelliSenseExtender.Intellisense.AsyncCompletion; |
| 14 | + |
| 15 | +internal class IdeographAsyncCompletionItemManager(IPatternMatcherFactory _patternMatcherFactory) : IAsyncCompletionItemManager |
| 16 | +{ |
| 17 | + //private void write(TimeSpan t, string msg = "", [CallerMemberName] string n = "") |
| 18 | + //{ |
| 19 | + // using var s = File.AppendText("D:\\time.txt"); |
| 20 | + // s.WriteLine($"[{DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond}] {n}: {t.TotalMilliseconds}ms ({msg})"); |
| 21 | + //} |
| 22 | + |
| 23 | + private InputMethodDictionaryGroup? _inputMethodDictionaryGroup; |
| 24 | + private readonly ConcurrentDictionary<(PreMatchType, StringPreCheckRule, string), string> _filterTextCache = []; |
| 25 | + private GeneralOptions? _options; |
| 26 | + |
| 27 | + private async Task<InputMethodDictionaryGroup> GetInputMethodDictionaryGroupAsync() |
| 28 | + { |
| 29 | + if (_inputMethodDictionaryGroup is null |
| 30 | + || _inputMethodDictionaryGroup.IsDisposed) |
| 31 | + { |
| 32 | + _inputMethodDictionaryGroup = await InputMethodDictionaryGroupProvider.GetAsync(); |
| 33 | + } |
| 34 | + return _inputMethodDictionaryGroup; |
| 35 | + } |
| 36 | + |
| 37 | + private static IReadOnlyList<CompletionItem> SortCompletionItem(IReadOnlyList<CompletionItem> items) |
| 38 | + { |
| 39 | + bool CheckShouldSort() |
| 40 | + { |
| 41 | + return !(Parallel.For(1, items.Count, (i, p) => |
| 42 | + { |
| 43 | + if (items[i - 1].SortText.CompareTo(items[i].SortText) > 0) p.Stop(); |
| 44 | + }).IsCompleted); |
| 45 | + } |
| 46 | + |
| 47 | + if (CheckShouldSort()) { return items.AsParallel().OrderBy(i => i.SortText).ToArray(); } |
| 48 | + return items; |
| 49 | + } |
| 50 | + |
| 51 | + public Task<ImmutableArray<CompletionItem>> SortCompletionListAsync(IAsyncCompletionSession session, AsyncCompletionSessionInitialDataSnapshot data, CancellationToken token) |
| 52 | + { |
| 53 | + //var st = ValueStopwatch.StartNew(); |
| 54 | + var sortedItems = SortCompletionItem(data.InitialList).ToImmutableArray(); |
| 55 | + //var t = st.Elapsed; |
| 56 | + //write(t); |
| 57 | + return Task.FromResult(sortedItems); |
| 58 | + } |
| 59 | + |
| 60 | + public async Task<FilteredCompletionModel> UpdateCompletionListAsync(IAsyncCompletionSession session, AsyncCompletionSessionDataSnapshot data, CancellationToken token) |
| 61 | + { |
| 62 | + //var st = ValueStopwatch.StartNew(); |
| 63 | + //TimeSpan t; |
| 64 | + |
| 65 | + var view = session.TextView; |
| 66 | + // Filter by text |
| 67 | + var filterText = session.ApplicableToSpan.GetText(data.Snapshot); |
| 68 | + if (string.IsNullOrWhiteSpace(filterText) |
| 69 | + // 光标在 F# 的特殊标志符之后: ``aaa!`` | |
| 70 | + || char.IsWhiteSpace(filterText[filterText.Length - 1])) |
| 71 | + { |
| 72 | + // There is no text filtering. Just apply user filters, sort alphabetically and return. |
| 73 | + IReadOnlyList<CompletionItem> listFiltered = data.InitialSortedList; |
| 74 | + if (data.SelectedFilters.Any(n => n.IsSelected)) |
| 75 | + { |
| 76 | + listFiltered = listFiltered.ParallelWhere(n => ShouldBeInCompletionList(n, data.SelectedFilters)); |
| 77 | + } |
| 78 | + var listSorted = SortCompletionItem(listFiltered); |
| 79 | + var listHighlighted = listSorted.ParallelSelect(n => new CompletionItemWithHighlight(n)).ToImmutableArray(); |
| 80 | + |
| 81 | + //t = st.Elapsed; |
| 82 | + //write(t, "short"); |
| 83 | + return new FilteredCompletionModel(listHighlighted, 0, data.SelectedFilters); |
| 84 | + } |
| 85 | + |
| 86 | + _options ??= await GeneralOptions.GetLiveInstanceAsync(); |
| 87 | + var shouldProcessChecker = StringPreMatchUtil.GetPreCheckPredicate(_options.PreMatchType, _options.PreCheckRule); |
| 88 | + var inputMethodDictionaryGroup = await GetInputMethodDictionaryGroupAsync(); |
| 89 | + |
| 90 | + string GetFilterText(string t) |
| 91 | + { |
| 92 | + var key = (_options.PreMatchType, _options.PreCheckRule, t); |
| 93 | + |
| 94 | + if (_filterTextCache.TryGetValue(key, out var r)) return r; |
| 95 | + if (!shouldProcessChecker.Check(t)) return AddToCacheAndReturn(t); |
| 96 | + |
| 97 | + var spellings = inputMethodDictionaryGroup.FindAll(t); |
| 98 | + var res = _options.EnableMultipleSpellings ? string.Join("/", spellings) : spellings[0]; |
| 99 | + return AddToCacheAndReturn($"{t}/{res}"); |
| 100 | + |
| 101 | + string AddToCacheAndReturn(string v) |
| 102 | + { |
| 103 | + _filterTextCache.TryAdd(key, v); |
| 104 | + return v; |
| 105 | + } |
| 106 | + } |
| 107 | + |
| 108 | + // Pattern matcher not only filters, but also provides a way to order the results by their match quality. |
| 109 | + // The relevant CompletionItem is match.Item1, its PatternMatch is match.Item2 |
| 110 | + var patternMatcher = _patternMatcherFactory.CreatePatternMatcher( |
| 111 | + filterText, |
| 112 | + new PatternMatcherCreationOptions(System.Globalization.CultureInfo.CurrentCulture, PatternMatcherCreationFlags.IncludeMatchedSpans)); |
| 113 | + |
| 114 | + var matches = data.InitialSortedList |
| 115 | + // Perform pattern matching |
| 116 | + .ParallelChoose(completionItem => |
| 117 | + { |
| 118 | + var match = patternMatcher.TryMatch(GetFilterText(completionItem.FilterText)); |
| 119 | + // Pick only items that were matched, unless length of filter text is 1 |
| 120 | + return (filterText.Length == 1 || match.HasValue, (completionItem, match)); |
| 121 | + }); |
| 122 | + |
| 123 | + // See which filters might be enabled based on the typed code |
| 124 | + var textFilteredFilters = matches.SelectMany(n => n.completionItem.Filters).Distinct(); |
| 125 | + |
| 126 | + // When no items are available for a given filter, it becomes unavailable |
| 127 | + var updatedFilters = ImmutableArray.CreateRange(data.SelectedFilters.Select(n => n.WithAvailability(textFilteredFilters.Contains(n.Filter)))); |
| 128 | + |
| 129 | + // Filter by user-selected filters. The value on availableFiltersWithSelectionState conveys whether the filter is selected. |
| 130 | + var filterFilteredList = matches; |
| 131 | + if (data.SelectedFilters.Any(n => n.IsSelected)) |
| 132 | + { |
| 133 | + filterFilteredList = matches.Where(n => ShouldBeInCompletionList(n.completionItem, data.SelectedFilters)).ToArray(); |
| 134 | + } |
| 135 | + |
| 136 | + var bestMatch = filterFilteredList.OrderByDescending(n => n.match.HasValue).ThenBy(n => n.match).FirstOrDefault(); |
| 137 | + var listWithHighlights = filterFilteredList.Select(n => |
| 138 | + { |
| 139 | + ImmutableArray<Span> safeMatchedSpans = ImmutableArray<Span>.Empty; |
| 140 | + |
| 141 | + if (n.completionItem.DisplayText == n.completionItem.FilterText) |
| 142 | + { |
| 143 | + if (n.match.HasValue) |
| 144 | + { |
| 145 | + safeMatchedSpans = n.match.Value.MatchedSpans; |
| 146 | + } |
| 147 | + } |
| 148 | + else |
| 149 | + { |
| 150 | + // Matches were made against FilterText. We are displaying DisplayText. To avoid issues, re-apply matches for these items |
| 151 | + var newMatchedSpans = patternMatcher.TryMatch(n.completionItem.DisplayText); |
| 152 | + if (newMatchedSpans.HasValue) |
| 153 | + { |
| 154 | + safeMatchedSpans = newMatchedSpans.Value.MatchedSpans; |
| 155 | + } |
| 156 | + } |
| 157 | + |
| 158 | + if (safeMatchedSpans.IsDefaultOrEmpty) |
| 159 | + { |
| 160 | + return new CompletionItemWithHighlight(n.completionItem); |
| 161 | + } |
| 162 | + else |
| 163 | + { |
| 164 | + return new CompletionItemWithHighlight(n.completionItem, safeMatchedSpans); |
| 165 | + } |
| 166 | + }).ToImmutableArray(); |
| 167 | + |
| 168 | + int selectedItemIndex = 0; |
| 169 | + if (data.DisplaySuggestionItem) |
| 170 | + { |
| 171 | + selectedItemIndex = -1; |
| 172 | + } |
| 173 | + else |
| 174 | + { |
| 175 | + for (int i = 0; i < listWithHighlights.Length; i++) |
| 176 | + { |
| 177 | + if (listWithHighlights[i].CompletionItem == bestMatch.completionItem) |
| 178 | + { |
| 179 | + selectedItemIndex = i; |
| 180 | + break; |
| 181 | + } |
| 182 | + } |
| 183 | + } |
| 184 | + |
| 185 | + //t = st.Elapsed; |
| 186 | + //write(t, "end"); |
| 187 | + return new FilteredCompletionModel(listWithHighlights, selectedItemIndex, updatedFilters); |
| 188 | + } |
| 189 | + |
| 190 | + private static bool ShouldBeInCompletionList( |
| 191 | + CompletionItem item, |
| 192 | + ImmutableArray<CompletionFilterWithState> filtersWithState) |
| 193 | + { |
| 194 | + foreach (var filterWithState in filtersWithState.Where(n => n.IsSelected)) |
| 195 | + { |
| 196 | + if (item.Filters.Any(n => n == filterWithState.Filter)) |
| 197 | + { |
| 198 | + return true; |
| 199 | + } |
| 200 | + } |
| 201 | + return false; |
| 202 | + } |
| 203 | +} |
0 commit comments