Welcome to mirror list, hosted at ThFree Co, Russian Federation.

ProjectSearchCategory.cs « MonoDevelop.Components.MainToolbar « MonoDevelop.Ide « core « src « main - github.com/mono/monodevelop.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 1731f082555efe388049f39547eb7eff5d048c09 (plain)
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
// 
// ProjectSearchCategory.cs
//  
// Author:
//       Mike Krüger <mkrueger@xamarin.com>
// 
// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com)
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Threading;
using System.Threading.Tasks;
using MonoDevelop.Core;
using System.Collections.Generic;
using MonoDevelop.Core.Instrumentation;
using MonoDevelop.Projects;
using MonoDevelop.Ide.Gui;
using MonoDevelop.Ide;
using MonoDevelop.Ide.TypeSystem;
using MonoDevelop.Core.Text;
using Gtk;
using System.Linq;
using ICSharpCode.NRefactory6.CSharp;
using Microsoft.CodeAnalysis;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Collections.Concurrent;

namespace MonoDevelop.Components.MainToolbar
{
	class ProjectSearchCategory : SearchCategory
	{
		static SearchPopupWindow widget;

		public ProjectSearchCategory (SearchPopupWindow widget) : base (GettextCatalog.GetString ("Solution"))
		{
			ProjectSearchCategory.widget = widget;
			lastResult = new WorkerResult (widget);
		}

		internal static Task<ImmutableList<DeclaredSymbolInfo>> SymbolInfoTask;

		static TimerCounter getMembersTimer = InstrumentationService.CreateTimerCounter ("Time to get all members", "NavigateToDialog");
		static TimerCounter getTypesTimer = InstrumentationService.CreateTimerCounter ("Time to get all types", "NavigateToDialog");

		static CancellationTokenSource symbolInfoTokenSrc = new CancellationTokenSource();
		public static void UpdateSymbolInfos ()
		{
			symbolInfoTokenSrc.Cancel ();
			symbolInfoTokenSrc = new CancellationTokenSource();
			CancellationToken token = symbolInfoTokenSrc.Token;
			lastResult = new WorkerResult (widget);
			SymbolInfoTask = Task.Run (delegate {
				return GetSymbolInfos (token);
			}, token);
		}

		static ImmutableList<DeclaredSymbolInfo> GetSymbolInfos (CancellationToken token)
		{
			getTypesTimer.BeginTiming ();
			try {
				var result = ImmutableList<DeclaredSymbolInfo>.Empty;
				Stopwatch sw = new Stopwatch();
				sw.Start ();
				foreach (var workspace in TypeSystemService.AllWorkspaces) {
					result = result.AddRange (workspace.CurrentSolution.Projects.Select (p => SearchAsync (p, token)).SelectMany (i => i));
				}
				sw.Stop ();
				return result;
			} catch (AggregateException ae) {
				ae.Flatten ().Handle (ex => ex is TaskCanceledException);
				return ImmutableList<DeclaredSymbolInfo>.Empty;
			} catch (TaskCanceledException) {
				return ImmutableList<DeclaredSymbolInfo>.Empty;
			} finally {
				getTypesTimer.EndTiming ();
			}
		}

		static IEnumerable<DeclaredSymbolInfo> SearchAsync(Microsoft.CodeAnalysis.Project project, CancellationToken cancellationToken)
		{
			var result = new ConcurrentBag<DeclaredSymbolInfo> ();
			Parallel.ForEach (project.Documents, async delegate (Microsoft.CodeAnalysis.Document document) {
				try {
					cancellationToken.ThrowIfCancellationRequested ();
					var root = await document.GetSyntaxRootAsync (cancellationToken).ConfigureAwait (false);
					foreach (var current in root.DescendantNodesAndSelf (CSharpSyntaxFactsService.DescentIntoSymbolForDeclarationSearch)) {
						DeclaredSymbolInfo declaredSymbolInfo;
						if (current.TryGetDeclaredSymbolInfo (out declaredSymbolInfo)) {
							result.Add (declaredSymbolInfo);
						}
					}
				} catch (OperationCanceledException) {
				}
			});
			return (IEnumerable<DeclaredSymbolInfo>)result;
		}

		static WorkerResult lastResult;
		string[] typeTags = new [] { "type", "c", "s", "i", "e", "d" };
		string[] memberTags = new [] { "member", "m", "p", "f", "evt" };

		public override bool IsValidTag (string tag)
		{
			return typeTags.Any (t => t == tag) || memberTags.Any (t => t == tag);
		}

		public override Task<ISearchDataSource> GetResults (SearchPopupSearchPattern searchPattern, int resultsCount, CancellationToken token)
		{
			return Task.Run (delegate {
				if (searchPattern.Tag != null && !(typeTags.Contains (searchPattern.Tag) || memberTags.Contains (searchPattern.Tag)) || searchPattern.HasLineNumber)
					return null;
				try {
					var newResult = new WorkerResult (widget);
					newResult.pattern = searchPattern.Pattern;
					newResult.IncludeFiles = true;
					newResult.Tag = searchPattern.Tag;
					newResult.IncludeTypes = searchPattern.Tag == null || typeTags.Contains (searchPattern.Tag);
					newResult.IncludeMembers = searchPattern.Tag == null || memberTags.Contains (searchPattern.Tag);
					ImmutableList<DeclaredSymbolInfo> allTypes;
					if (SymbolInfoTask == null)
						SymbolInfoTask = Task.FromResult(GetSymbolInfos (token));
					allTypes = SymbolInfoTask.Result;
					string toMatch = searchPattern.Pattern;
					newResult.matcher = StringMatcher.GetMatcher (toMatch, false);
					newResult.FullSearch = toMatch.IndexOf ('.') > 0;
					var oldLastResult = lastResult;
					if (newResult.FullSearch && oldLastResult != null && !oldLastResult.FullSearch)
						oldLastResult = new WorkerResult (widget);
//					var now = DateTime.Now;

					AllResults (oldLastResult, newResult, allTypes, token);
					newResult.results.SortUpToN (new DataItemComparer (token), resultsCount);
					lastResult = newResult;
//					Console.WriteLine ((now - DateTime.Now).TotalMilliseconds);
					return (ISearchDataSource)newResult.results;
				} catch {
					token.ThrowIfCancellationRequested ();
					throw;
				}
			}, token);
		}

		void AllResults (WorkerResult lastResult, WorkerResult newResult, IReadOnlyList<DeclaredSymbolInfo> completeTypeList, CancellationToken token)
		{
			if (newResult.isGotoFilePattern)
				return;
			uint x = 0;
			// Search Types
			if (newResult.IncludeTypes && (newResult.Tag == null || typeTags.Any (t => t == newResult.Tag))) {
				newResult.filteredSymbols = new List<DeclaredSymbolInfo> ();
				bool startsWithLastFilter = lastResult.pattern != null && newResult.pattern.StartsWith (lastResult.pattern, StringComparison.Ordinal) && lastResult.filteredSymbols != null;
				var allTypes = startsWithLastFilter ? lastResult.filteredSymbols : completeTypeList;
				foreach (var type in allTypes) {
					if (unchecked(x++) % 100 == 0 && token.IsCancellationRequested) {
						newResult.filteredSymbols = null;
						return;
					}

					if (type.Kind == DeclaredSymbolInfoKind.Constructor ||
					    type.Kind == DeclaredSymbolInfoKind.Module ||
					    type.Kind == DeclaredSymbolInfoKind.Indexer)
						continue;
					
					if (newResult.Tag != null) {
						if (newResult.Tag == "c" && type.Kind != DeclaredSymbolInfoKind.Class)
							continue;
						if (newResult.Tag == "s" && type.Kind != DeclaredSymbolInfoKind.Struct)
							continue;
						if (newResult.Tag == "i" && type.Kind != DeclaredSymbolInfoKind.Interface)
							continue;
						if (newResult.Tag == "e" && type.Kind != DeclaredSymbolInfoKind.Enum)
							continue;
						if (newResult.Tag == "d" && type.Kind != DeclaredSymbolInfoKind.Delegate)
							continue;

						if (newResult.Tag == "m" && type.Kind != DeclaredSymbolInfoKind.Method)
							continue;
						if (newResult.Tag == "p" && type.Kind != DeclaredSymbolInfoKind.Property)
							continue;
						if (newResult.Tag == "f" && type.Kind != DeclaredSymbolInfoKind.Field)
							continue;
						if (newResult.Tag == "evt" && type.Kind != DeclaredSymbolInfoKind.Event)
							continue;
						
					}
					SearchResult curResult = newResult.CheckType (type);
					if (curResult != null) {
						newResult.filteredSymbols.Add (type);
						newResult.results.AddResult (curResult);
					}
				}
			}
		}

		class WorkerResult
		{
			public string Tag {
				get;
				set;
			}

			public List<DeclaredSymbolInfo> filteredSymbols;

			string pattern2;
			char firstChar;
			char[] firstChars;

			public string pattern {
				get {
					return pattern2;
				}
				set {
					pattern2 = value;
					if (pattern2.Length == 1) {
						firstChar = pattern2 [0];
						firstChars = new [] { char.ToUpper (firstChar), char.ToLower (firstChar) };
					} else {
						firstChars = null;
					}
				}
			}

			public bool isGotoFilePattern;
			public ResultsDataSource results;
			public bool FullSearch;
			public bool IncludeFiles, IncludeTypes, IncludeMembers;
			public StringMatcher matcher;

			public WorkerResult (Widget widget)
			{
				results = new ResultsDataSource (widget);
			}

			internal SearchResult CheckType (DeclaredSymbolInfo symbol)
			{
				int rank;
				if (MatchName (symbol.Name, out rank)) {
//					if (type.ContainerDisplayName != null)
//						rank--;
					return new DeclaredSymbolInfoResult (pattern, symbol.Name, rank, symbol, false);
				}
				if (!FullSearch)
					return null;
				if (MatchName (symbol.FullyQualifiedContainerName, out rank)) {
//					if (type.ContainingType != null)
//						rank--;
					return new DeclaredSymbolInfoResult (pattern, symbol.FullyQualifiedContainerName, rank, symbol, true);
				}
				return null;
			}

			Dictionary<string, MatchResult> savedMatches = new Dictionary<string, MatchResult> (StringComparer.Ordinal);

			bool MatchName (string name, out int matchRank)
			{
				if (name == null) {
					matchRank = -1;
					return false;
				}

				bool doesMatch;
				if (firstChars != null) {
					int idx = name.IndexOfAny (firstChars);
					doesMatch = idx >= 0;
					if (doesMatch) {
						matchRank = int.MaxValue - (name.Length - 1) * 10 - idx;
						if (name [idx] != firstChar)
							matchRank /= 2;
						return true;
					} else {
						matchRank = -1;
					}
					return false;
				}
				MatchResult savedMatch;
				if (!savedMatches.TryGetValue (name, out savedMatch)) {
					doesMatch = matcher.CalcMatchRank (name, out matchRank);
					savedMatches [name] = savedMatch = new MatchResult (doesMatch, matchRank);
				}
				
				matchRank = savedMatch.Rank;
				return savedMatch.Match;
			}
		}
	}
}