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

RefactoryCommands.cs « MonoDevelop.Refactoring « MonoDevelop.Refactoring « addins « src « main - github.com/mono/monodevelop.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: d89a7c408161a6bfe1e194b463cd3858ae57340b (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
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
//
// RefactoryCommands.cs
//
// Author:
//   Lluis Sanchez Gual
//
// Copyright (C) 2006 Novell, Inc (http://www.novell.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.Collections.Generic;

using MonoDevelop.Core;
using MonoDevelop.Ide.Gui;
using MonoDevelop.Components.Commands;
using MonoDevelop.Ide.Gui.Content;
using MonoDevelop.Ide.FindInFiles;
using MonoDevelop.Ide;
using System.Linq;
using ICSharpCode.NRefactory.CSharp.Resolver;
using ICSharpCode.NRefactory.TypeSystem;
using Mono.TextEditor;
using ICSharpCode.NRefactory.Semantics;
using MonoDevelop.CodeActions;
using MonoDevelop.SourceEditor.QuickTasks;
using MonoDevelop.Projects;
using MonoDevelop.Ide.Gui.Components;
using System.Threading;
using System.Threading.Tasks;

namespace MonoDevelop.Refactoring
{
	public enum RefactoryCommands
	{
		CurrentRefactoryOperations,
		GotoDeclaration, // in 'referenced' in IdeViMode.cs as string
		FindReferences,
		FindAllReferences,
		FindDerivedClasses,
		DeclareLocal,
		RemoveUnusedImports,
		SortImports,
		RemoveSortImports,
		ExtractMethod,
		CreateMethod,
		IntroduceConstant,
		IntegrateTemporaryVariable,
		ImportSymbol,
		QuickFix,
		Resolve
	}
	
	public class CurrentRefactoryOperationsHandler : CommandHandler
	{
		protected override void Run (object data)
		{
			var del = (System.Action) data;
			if (del != null)
				del ();
		}
		
		public static ResolveResult GetResolveResult (MonoDevelop.Ide.Gui.Document doc)
		{
			ITextEditorResolver textEditorResolver = doc.GetContent<ITextEditorResolver> ();
			if (textEditorResolver != null)
				return textEditorResolver.GetLanguageItem (doc.Editor.IsSomethingSelected ? doc.Editor.SelectionRange.Offset : doc.Editor.Caret.Offset);
			return null;
		}
		
		public static object GetItem (MonoDevelop.Ide.Gui.Document doc, out ResolveResult resolveResult)
		{
			resolveResult = GetResolveResult (doc);
			if (resolveResult is LocalResolveResult) 
				return ((LocalResolveResult)resolveResult).Variable;
			if (resolveResult is MemberResolveResult)
				return ((MemberResolveResult)resolveResult).Member;
			if (resolveResult is MethodGroupResolveResult) {
				var mg = ((MethodGroupResolveResult)resolveResult);
				var method = mg.Methods.FirstOrDefault ();
				if (method == null && mg.GetExtensionMethods ().Any ()) 
					method = mg.GetExtensionMethods ().First ().FirstOrDefault ();
				return method;
			}
			if (resolveResult is TypeResolveResult)
				return resolveResult.Type;
			if (resolveResult is NamespaceResolveResult)
				return ((NamespaceResolveResult)resolveResult).Namespace;
			if (resolveResult is OperatorResolveResult)
				return ((OperatorResolveResult)resolveResult).UserDefinedOperatorMethod;
			return null;
		}

		class JumpTo
		{
			object el;
			
			public JumpTo (object el)
			{
				this.el = el;
			}
			
			public void Run ()
			{
				if (el is IUnresolvedEntity) {
					var e = (IUnresolvedEntity)el;
					IdeApp.Workbench.OpenDocument (e.Region.FileName, e.Region.BeginLine, e.Region.BeginColumn);
					return;
				} 
				if (el is IVariable)
					IdeApp.ProjectOperations.JumpToDeclaration ((IVariable)el);
				if (el is INamedElement)
					IdeApp.ProjectOperations.JumpToDeclaration ((INamedElement)el);
			}
		}

		
		class GotoBase 
		{
			IEntity item;
			
			public GotoBase (IEntity item)
			{
				this.item = item;
			}
			
			public void Run ()
			{
				var cls = item as ITypeDefinition;
				if (cls != null && cls.DirectBaseTypes != null) {
					foreach (var bt in cls.DirectBaseTypes) {
						var def = bt.GetDefinition ();
						if (def != null && def.Kind != TypeKind.Interface) {
							IdeApp.ProjectOperations.JumpToDeclaration (def); 
							return;
						}
					}
				}
				
				var method = item as IMember;
				if (method != null) {
					var baseMethod = InheritanceHelper.GetBaseMember (method); 
					if (baseMethod != null) {
						IdeApp.ProjectOperations.JumpToDeclaration (baseMethod); 
					}
					return;
				}
			}
		}
		
		class FindRefs 
		{
			object obj;
			bool allOverloads;
			public FindRefs (object obj, bool all)
			{
				this.obj = obj;
				this.allOverloads = all;
			}
			
			public void Run ()
			{
				if (allOverloads) {
					FindAllReferencesHandler.FindRefs (obj);
				} else {
					FindReferencesHandler.FindRefs (obj);
				}
			}
		}
		
		class FindDerivedClasses
		{
			ITypeDefinition type;
			
			public FindDerivedClasses (ITypeDefinition type)
			{
				this.type = type;
			}
			
			public void Run ()
			{
				FindDerivedClassesHandler.FindDerivedClasses (type);
			}
		}

		class RefactoringDocumentInfo
		{
			public IEnumerable<CodeAction> validActions;
			public MonoDevelop.Ide.TypeSystem.ParsedDocument lastDocument;

			public override string ToString ()
			{
				return string.Format ("[RefactoringDocumentInfo: #validActions={0}, lastDocument={1}]", validActions != null ? validActions.Count ().ToString () : "null", lastDocument);
			}
		}


		DocumentLocation lastLocation;

		static bool HasOverloads (Solution solution, object item)
		{
			var member = item as IMember;
			if (member != null && member.ImplementedInterfaceMembers.Any ())
				return true;
			var method = item as IMethod;
			if (method == null)
				return false;
			return method.DeclaringType.GetMethods (m => m.Name == method.Name).Count () > 1;
		}


		protected override void Update (CommandArrayInfo ainfo)
		{
			var doc = IdeApp.Workbench.ActiveDocument;
			if (doc == null || doc.FileName == FilePath.Null)
				return;
			
			var parsedDocument = doc.ParsedDocument;
			if (parsedDocument == null || parsedDocument.IsInvalid)
				return;
			
			ResolveResult resolveResult;
			object item = GetItem (doc, out resolveResult);
			bool added = false;

			var options = new RefactoringOptions (doc) {
				ResolveResult = resolveResult,
				SelectedItem = item
			};
			
			var ciset = new CommandInfoSet ();
			ciset.Text = GettextCatalog.GetString ("Refactor");

			bool canRename;
			if (item is IVariable || item is IParameter) {
				canRename = true; 
			} else if (item is ITypeDefinition) { 
				canRename = !((ITypeDefinition)item).Region.IsEmpty;
			} else if (item is IType) { 
				canRename = ((IType)item).Kind == TypeKind.TypeParameter;
			} else if (item is IMember) {
				canRename = !((IMember)item).Region.IsEmpty;
			} else if (item is INamespace) {
				canRename = true;
			} else {
				canRename = false;
			}
			if (canRename) {
				ciset.CommandInfos.Add (IdeApp.CommandService.GetCommandInfo (MonoDevelop.Ide.Commands.EditCommands.Rename), new Action (delegate {
					new MonoDevelop.Refactoring.Rename.RenameHandler ().Start (null);
				}));
				added = true;
			}
			if (RefactoringService.ShowFixes) {
				foreach (var refactoring in RefactoringService.Refactorings) {
					if (refactoring.IsValid (options)) {
						CommandInfo info = new CommandInfo (refactoring.GetMenuDescription (options));
						info.AccelKey = refactoring.AccelKey;
						ciset.CommandInfos.Add (info, new Action (new RefactoringOperationWrapper (refactoring, options).Operation));
					}
				}
				var refactoringInfo = doc.Annotation<RefactoringDocumentInfo> ();
				if (refactoringInfo == null) {
					refactoringInfo = new RefactoringDocumentInfo ();
					doc.AddAnnotation (refactoringInfo);
				}
				var loc = doc.Editor.Caret.Location;
				bool first = true;
				if (refactoringInfo.lastDocument != doc.ParsedDocument || loc != lastLocation) {
					try {
						refactoringInfo.validActions = RefactoringService.GetValidActions (doc, loc, new CancellationTokenSource (500).Token);
					} catch (TaskCanceledException) {
					} catch (AggregateException ae) {
						ae.Flatten ().Handle (x => x is TaskCanceledException); 
					}
	
					lastLocation = loc;
					refactoringInfo.lastDocument = doc.ParsedDocument;
				}
				if (refactoringInfo.validActions != null && refactoringInfo.lastDocument != null && refactoringInfo.lastDocument.CreateRefactoringContext != null) {
					var context = refactoringInfo.lastDocument.CreateRefactoringContext (doc, CancellationToken.None);

					foreach (var fix_ in refactoringInfo.validActions.OrderByDescending (i => Tuple.Create (CodeActionEditorExtension.IsAnalysisOrErrorFix(i), (int)i.Severity, CodeActionEditorExtension.GetUsage (i.IdString)))) {
						if (CodeActionEditorExtension.IsAnalysisOrErrorFix (fix_))
							continue;
						var fix = fix_;
						if (first) {
							first = false;
							if (ciset.CommandInfos.Count > 0)
								ciset.CommandInfos.AddSeparator ();
						}

						ciset.CommandInfos.Add (fix.Title, new Action (() => RefactoringService.ApplyFix (fix, context)));
					}
				}
			}
			if (ciset.CommandInfos.Count > 0) {
				ainfo.Add (ciset, null);
				added = true;
			}
			
			if (IdeApp.ProjectOperations.CanJumpToDeclaration (item)) {
				var type = item as IType;
				if (type != null && type.GetDefinition ().Parts.Count > 1) {
					var declSet = new CommandInfoSet ();
					declSet.Text = GettextCatalog.GetString ("_Go to Declaration");
					var ct = type.GetDefinition ();
					foreach (var part in ct.Parts)
						declSet.CommandInfos.Add (string.Format (GettextCatalog.GetString ("{0}, Line {1}"), FormatFileName (part.Region.FileName), part.Region.BeginLine), new System.Action (new JumpTo (part).Run));
					ainfo.Add (declSet);
				} else {
					ainfo.Add (IdeApp.CommandService.GetCommandInfo (RefactoryCommands.GotoDeclaration), new System.Action (new JumpTo (item).Run));
				}
				added = true;
			}

			if (item is IMember) {
				var member = (IMember)item;
				if (member.IsOverride || member.ImplementedInterfaceMembers.Any ()) {
					ainfo.Add (GettextCatalog.GetString ("Go to _Base Symbol"), new System.Action (new GotoBase (member).Run));
					added = true;
				}
			}

			if (!(item is IMethod && ((IMethod)item).SymbolKind == SymbolKind.Operator) && (item is IEntity || item is ITypeParameter || item is IVariable || item is INamespace)) {

				ainfo.Add (IdeApp.CommandService.GetCommandInfo (RefactoryCommands.FindReferences), new System.Action (new FindRefs (item, false).Run));
				if (doc.HasProject && HasOverloads (doc.Project.ParentSolution, item))
					ainfo.Add (IdeApp.CommandService.GetCommandInfo (RefactoryCommands.FindAllReferences), new System.Action (new FindRefs (item, true).Run));
				added = true;
			}

			if (item is IMember) {
				var member = (IMember)item;
				var handler = new FindDerivedSymbolsHandler (member);
				if (handler.IsValid) {
					var a = ainfo.Add (GettextCatalog.GetString ("Find Derived Symbols"), new Action (handler.Run));
					a.AccelKey = IdeApp.CommandService.GetCommandInfo (RefactoryCommands.FindDerivedClasses).AccelKey;
					added = true;
				}
			}
			if (item is IMember) {
				var member = (IMember)item;
				if (member.SymbolKind == SymbolKind.Method || member.SymbolKind == SymbolKind.Indexer) {
					var findMemberOverloadsHandler = new FindMemberOverloadsHandler (doc, member);
					if (findMemberOverloadsHandler.IsValid) {
						ainfo.Add (GettextCatalog.GetString ("Find Member Overloads"), new System.Action (findMemberOverloadsHandler.Run));
						added = true;
					}
				}
			}

			if (item is ITypeDefinition) {
				ITypeDefinition cls = (ITypeDefinition)item;
				foreach (var bc in cls.DirectBaseTypes) {
					if (bc != null && bc.GetDefinition () != null && bc.GetDefinition ().Kind != TypeKind.Interface/* TODO: && IdeApp.ProjectOperations.CanJumpToDeclaration (bc)*/) {
						ainfo.Add (GettextCatalog.GetString ("Go to _Base"), new System.Action (new GotoBase ((ITypeDefinition)item).Run));
						break;
					}
				}
				if ((cls.Kind == TypeKind.Class && !cls.IsSealed) || cls.Kind == TypeKind.Interface) {
					var label = cls.Kind != TypeKind.Interface ? GettextCatalog.GetString ("Find _derived classes") : GettextCatalog.GetString ("Find _implementor classes");
					var a = ainfo.Add (label, new System.Action (new FindDerivedClasses (cls).Run));
					a.AccelKey = IdeApp.CommandService.GetCommandInfo (RefactoryCommands.FindDerivedClasses).AccelKey;
				}
				ainfo.Add (GettextCatalog.GetString ("Find Extension Methods"), new System.Action (new FindExtensionMethodHandler (doc, cls).Run));
				added = true;

			}

			if (added)
				ainfo.AddSeparator ();
		}
		

		class RefactoringOperationWrapper
		{
			RefactoringOperation refactoring;
			RefactoringOptions options;
			
			public RefactoringOperationWrapper (RefactoringOperation refactoring, RefactoringOptions options)
			{
				this.refactoring = refactoring;
				this.options = options;
			}
			
			public void Operation ()
			{
				refactoring.Run (options);
			}
		}

		bool IsModifiable (object member)
		{
			IType t = member as IType;
			if (t != null) 
				return t.GetDefinition ().Region.FileName == IdeApp.Workbench.ActiveDocument.FileName;
			if (member is IMember)
				return ((IMember)member).DeclaringTypeDefinition.Region.FileName == IdeApp.Workbench.ActiveDocument.FileName;
			return false;
		}

		static string FormatFileName (string fileName)
		{
			if (fileName == null)
				return null;
			char[] seperators = { System.IO.Path.DirectorySeparatorChar, System.IO.Path.AltDirectorySeparatorChar };
			int idx = fileName.LastIndexOfAny (seperators);
			if (idx > 0) 
				idx = fileName.LastIndexOfAny (seperators, idx - 1);
			if (idx > 0) 
				return "..." + fileName.Substring (idx);
			return fileName;
		}

		public static bool ContainsAbstractMembers (IType cls)
		{
			if (cls == null)
				return false;
			return cls.GetMembers ().Any (m => m.IsAbstract);
		}
	}
}