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

MDRefactoringScript.cs « MonoDevelop.CSharp.Refactoring.CodeActions « CSharpBinding « addins « src « main - github.com/mono/monodevelop.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 02e35f0e04dee9633dc7cd933332b881c3cb5b84 (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
// 
// MDRefactoringScript.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.Linq;
using ICSharpCode.NRefactory.CSharp.Refactoring;
using MonoDevelop.Ide.Gui;
using ICSharpCode.NRefactory.CSharp;
using Mono.TextEditor;
using MonoDevelop.Ide.TypeSystem;
using MonoDevelop.Core;
using System.Collections.Generic;
using ICSharpCode.NRefactory.TypeSystem;
using MonoDevelop.Refactoring.Rename;
using ICSharpCode.NRefactory.CSharp.Resolver;
using System.IO;
using MonoDevelop.CSharp.Formatting;
using MonoDevelop.Ide;
using System.Threading.Tasks;
using MonoDevelop.Ide.FindInFiles;
using MonoDevelop.Projects;
using ICSharpCode.NRefactory.CSharp.TypeSystem;
using MonoDevelop.Ide.Gui.Content;

namespace MonoDevelop.CSharp.Refactoring.CodeActions
{
	class MDRefactoringScript : DocumentScript
	{
		readonly MDRefactoringContext context;
		readonly IDisposable undoGroup;
		readonly ICSharpCode.NRefactory.Editor.ITextSourceVersion startVersion;
		int operationsRunning;

		public MDRefactoringScript (MDRefactoringContext context, CSharpFormattingOptions formattingOptions) : base(context.TextEditor.Document, formattingOptions, context.TextEditor.CreateNRefactoryTextEditorOptions ())
		{
			this.context = context;
			undoGroup  = this.context.TextEditor.OpenUndoGroup ();
			this.startVersion = this.context.TextEditor.Version;

		}

		void Rollback ()
		{
			DisposeOnClose (true);
			foreach (var ver in context.TextEditor.Version.GetChangesTo (startVersion)) {
				context.TextEditor.Document.Replace (ver.Offset, ver.RemovalLength, ver.InsertedText.Text);
			}
		}

		public override void Select (AstNode node)
		{
			var seg = GetSegment (node);
			var startOffset = seg.Offset;
			var endOffset   = seg.EndOffset;
			while (startOffset < endOffset) {
				char ch = context.TextEditor.GetCharAt (startOffset);
				if (!char.IsWhiteSpace (ch))
					break;
				startOffset++;
			}
			while (startOffset < endOffset && endOffset > 0) {
				char ch = context.TextEditor.GetCharAt (endOffset - 1);
				if (!char.IsWhiteSpace (ch))
					break;
				endOffset--;
			}

			context.TextEditor.Caret.Offset = endOffset;
			context.TextEditor.SelectionRange = new TextSegment (startOffset, endOffset - startOffset);
		}

		public override Task<Script> InsertWithCursor (string operation, InsertPosition defaultPosition, IList<AstNode> nodes)
		{
			var tcs = new TaskCompletionSource<Script> ();
			var editor = context.TextEditor;
			DocumentLocation loc = context.TextEditor.Caret.Location;
			var declaringType = context.ParsedDocument.GetInnermostTypeDefinition (loc);
			var mode = new InsertionCursorEditMode (
				editor.Parent,
				MonoDevelop.Ide.TypeSystem.CodeGenerationService.GetInsertionPoints (context.TextEditor, context.ParsedDocument, declaringType));
			if (mode.InsertionPoints.Count == 0) {
				MessageService.ShowError (
					GettextCatalog.GetString ("No valid insertion point can be found in type '{0}'.", declaringType.Name)
				);
				return tcs.Task;
			}
			var helpWindow = new Mono.TextEditor.PopupWindow.InsertionCursorLayoutModeHelpWindow ();
			helpWindow.TitleText = operation;
			mode.HelpWindow = helpWindow;
			
			switch (defaultPosition) {
			case InsertPosition.Start:
				mode.CurIndex = 0;
				break;
			case InsertPosition.End:
				mode.CurIndex = mode.InsertionPoints.Count - 1;
				break;
			case InsertPosition.Before:
				for (int i = 0; i < mode.InsertionPoints.Count; i++) {
					if (mode.InsertionPoints [i].Location < loc)
						mode.CurIndex = i;
				}
				break;
			case InsertPosition.After:
				for (int i = 0; i < mode.InsertionPoints.Count; i++) {
					if (mode.InsertionPoints [i].Location > loc) {
						mode.CurIndex = i;
						break;
					}
				}
				break;
			}
			operationsRunning++;
			mode.StartMode ();
			mode.Exited += delegate(object s, InsertionCursorEventArgs iCArgs) {
				if (iCArgs.Success) {
					if (iCArgs.InsertionPoint.LineAfter == NewLineInsertion.None && 
					    iCArgs.InsertionPoint.LineBefore == NewLineInsertion.None && nodes.Count () > 1) {
						iCArgs.InsertionPoint.LineAfter = NewLineInsertion.BlankLine;
					}
					foreach (var node in nodes.Reverse ()) {
						var output = OutputNode (MonoDevelop.Ide.TypeSystem.CodeGenerationService.CalculateBodyIndentLevel (declaringType), node);
						var offset = context.TextEditor.LocationToOffset (iCArgs.InsertionPoint.Location);
						var delta = iCArgs.InsertionPoint.Insert (editor, output.Text);
						output.RegisterTrackedSegments (this, delta + offset);
					}
					tcs.SetResult (this);
				} else {
					Rollback ();
				}
				DisposeOnClose (); 
			};
			return tcs.Task;
		}

		readonly List<Script> startedScripts = new List<Script> ();

		public override Task<Script> InsertWithCursor (string operation, ITypeDefinition parentType, Func<Script, RefactoringContext, IList<AstNode>> nodeCallback)
		{
			var tcs = new TaskCompletionSource<Script>();
			if (parentType == null)
				return tcs.Task;
			var part = parentType.Parts.FirstOrDefault ();
			if (part == null)
				return tcs.Task;

			var loadedDocument = IdeApp.Workbench.OpenDocument (new FileOpenInformation (part.Region.FileName, null));
			loadedDocument.RunWhenLoaded (delegate {
				var editor = loadedDocument.Editor;
				var loc = part.Region.Begin;
				var parsedDocument = loadedDocument.UpdateParseDocument ();
				var declaringType = parsedDocument.GetInnermostTypeDefinition (loc);
				MDRefactoringScript script;

				if (loadedDocument.Editor != context.TextEditor) {
					script = new MDRefactoringScript (MDRefactoringContext.Create (loadedDocument, loc, context.CancellationToken).Result, FormattingOptions);
					startedScripts.Add (script);
				} else {
					script = this;
				}
				var nodes = nodeCallback (script, script.context);
				var mode = new InsertionCursorEditMode (
					editor.Parent,
					MonoDevelop.Ide.TypeSystem.CodeGenerationService.GetInsertionPoints (loadedDocument, declaringType));
				if (mode.InsertionPoints.Count == 0) {
					MessageService.ShowError (
						GettextCatalog.GetString ("No valid insertion point can be found in type '{0}'.", declaringType.Name)
					);
					return;
				}
				if (declaringType.Kind == TypeKind.Enum) {
					foreach (var node in nodes.Reverse ()) {
						var output = OutputNode (MonoDevelop.Ide.TypeSystem.CodeGenerationService.CalculateBodyIndentLevel (declaringType), node);
						var point = mode.InsertionPoints.First ();
						var offset = loadedDocument.Editor.LocationToOffset (point.Location);
						var text = output.Text + ",";
						var delta = point.Insert (editor, text);
						output.RegisterTrackedSegments (script, delta + offset);
					}
					tcs.SetResult (script);
					return;
				}

				var helpWindow = new Mono.TextEditor.PopupWindow.InsertionCursorLayoutModeHelpWindow ();
				helpWindow.TitleText = operation;
				mode.HelpWindow = helpWindow;
				
				mode.CurIndex = 0;
				operationsRunning++;
				mode.StartMode ();
				mode.Exited += delegate(object s, InsertionCursorEventArgs iCArgs) {
					if (iCArgs.Success) {
						if (iCArgs.InsertionPoint.LineAfter == NewLineInsertion.None && 
						    iCArgs.InsertionPoint.LineBefore == NewLineInsertion.None && nodes.Count > 1) {
							iCArgs.InsertionPoint.LineAfter = NewLineInsertion.BlankLine;
						}
						foreach (var node in nodes.Reverse ()) {
							var output = OutputNode (MonoDevelop.Ide.TypeSystem.CodeGenerationService.CalculateBodyIndentLevel (declaringType), node);
							var offset = loadedDocument.Editor.LocationToOffset (iCArgs.InsertionPoint.Location);
							var text = output.Text;
							var delta = iCArgs.InsertionPoint.Insert (editor, text);
							output.RegisterTrackedSegments (script, delta + offset);
						}
						tcs.SetResult (script);
					} else {
						Rollback ();
					}
					DisposeOnClose (); 
				};
			});
		
			return tcs.Task;
		}

		public override Task Link (params AstNode[] nodes)
		{
			var tcs = new TaskCompletionSource<object> ();
			var segments = new List<TextSegment> (nodes.Select (node => new TextSegment (GetSegment (node))).OrderBy (s => s.Offset));
			
			var link = new TextLink ("name");
			segments.ForEach (link.AddLink);
			var links = new List<TextLink> ();
			links.Add (link);
			var tle = new TextLinkEditMode (context.TextEditor.Parent, 0, links);
			tle.SetCaretPosition = false;
			if (tle.ShouldStartTextLinkMode) {
				operationsRunning++;
				context.TextEditor.Caret.Offset = segments [0].EndOffset;
				tle.OldMode = context.TextEditor.CurrentMode;
				tle.Cancel += (sender, e) => Rollback ();
				tle.Exited += (sender, e) => DisposeOnClose (); 
				tle.StartMode ();
				context.TextEditor.CurrentMode = tle;
				if (IdeApp.Workbench.ActiveDocument != null)
					IdeApp.Workbench.ActiveDocument.ReparseDocument ();
			}
			return tcs.Task;
		}

		bool isDisposed;
		void DisposeOnClose (bool force = false)
		{
			if (isDisposed)
				return;
			if (force)
				operationsRunning = 0;
			if (operationsRunning-- == 0) {
				isDisposed = true;
				undoGroup.Dispose ();
				try {
					base.Dispose ();
				} catch (Exception e) {
					LoggingService.LogError ("Error while disposing refactoring script", e);
				}
			}
			foreach (var script in startedScripts)
				script.Dispose ();
		}
		
		public override void Dispose ()
		{
			DisposeOnClose ();
		}

		public override void Rename (ISymbol symbol, string name = null)
		{
			if (symbol is IEntity) {
				RenameRefactoring.Rename ((IEntity)symbol, name);
			} else if (symbol is IVariable) {
				RenameRefactoring.RenameVariable ((IVariable)symbol, name);
			} else if (symbol is INamespace) {
				RenameRefactoring.RenameNamespace ((INamespace)symbol, name);
			} else if (symbol is ITypeParameter) {
				RenameRefactoring.RenameTypeParameter ((ITypeParameter)symbol, name);
			}
		}

		public override void DoGlobalOperationOn (IEnumerable<IEntity> entities, Action<RefactoringContext, Script, IEnumerable<AstNode>> callback, string operationName = null)
		{
			using (var monitor = IdeApp.Workbench.ProgressMonitors.GetBackgroundProgressMonitor (operationName ?? GettextCatalog.GetString ("Performing refactoring task..."), null)) {
				var col = entities.SelectMany (entity => ReferenceFinder.FindReferences (entity, true, monitor)).OfType<CSharpReferenceFinder.CSharpMemberReference> ().GroupBy(reference => reference.FileName);

				foreach (var r in col) {
					string filename = r.Key;

					bool isOpen;
					System.Text.Encoding encoding;
					bool hadBom;

					var data = TextFileProvider.Instance.GetTextEditorData (filename, out hadBom, out encoding, out isOpen);

					var firstReference = r.First ();

					var project = firstReference.Project;

					ParsedDocument parsedDocument;
					using (var reader = new StreamReader (data.OpenStream ()))
						parsedDocument = new MonoDevelop.CSharp.Parser.TypeSystemParser ().Parse (true, filename, reader, project);

					var resolver = new CSharpAstResolver (TypeSystemService.GetCompilation (project), firstReference.SyntaxTree, parsedDocument.ParsedFile as CSharpUnresolvedFile);

					var ctx = new MDRefactoringContext (project as DotNetProject, data, parsedDocument, resolver, firstReference.AstNode.StartLocation, context.CancellationToken);
					var script = new MDRefactoringScript (ctx, FormattingOptions);

					callback (ctx, script, r.Select (reference => reference.AstNode));

					if (!isOpen) {
						script.Dispose ();
						Mono.TextEditor.Utils.TextFileUtility.WriteText (filename, data.Text, encoding, hadBom);
					}
				}
			}
		}

		public override void CreateNewType (AstNode newType, NewTypeContext ntctx = NewTypeContext.CurrentNamespace)
		{
			if (newType == null)
				throw new ArgumentNullException ("newType");
			var correctFileName = MoveTypeToFile.GetCorrectFileName (context, (EntityDeclaration)newType);
			
			var content = context.TextEditor.Text;
			
			var types = new List<EntityDeclaration> (context.Unit.GetTypes ());
			types.Sort ((x, y) => y.StartLocation.CompareTo (x.StartLocation));

			foreach (var removeType in types) {
				var start = context.GetOffset (removeType.StartLocation);
				var end = context.GetOffset (removeType.EndLocation);
				content = content.Remove (start, end - start);
			}
			
			var insertLocation = types.Count > 0 ? context.GetOffset (types.Last ().StartLocation) : -1;
			if (insertLocation < 0 || insertLocation > content.Length)
				insertLocation = content.Length;
			content = content.Substring (0, insertLocation) + newType.ToString (FormattingOptions) + content.Substring (insertLocation);

			var project = context.FileContainerProject;
			if (project != null) {
				var policy = project.Policies.Get<CSharpFormattingPolicy> ();
				var textPolicy = project.Policies.Get<TextStylePolicy> ();
				content = MonoDevelop.CSharp.Formatting.CSharpFormatter.FormatText (policy, textPolicy, MonoDevelop.CSharp.Formatting.CSharpFormatter.MimeType, content, 0, content.Length);
			}

			File.WriteAllText (correctFileName, content);

			if (project != null) {
				project.AddFile (correctFileName);
				IdeApp.ProjectOperations.SaveAsync (project);
			}
			IdeApp.Workbench.OpenDocument (correctFileName, project);
		}

	}
}