protected override void Run(RefactoringOptions options)
 {
     RefactoringOperation operation = new CreateIVarOperation ();
     if (operation.IsValid (options)) {
         operation.Run (options);
     }
 }
Пример #2
0
		//FIXME: why is this invalid on the parseddocuments loaded when the doc is first loaded?
		//maybe the item's type's SourceProject is null?
		public IEnumerable<IAnalysisFixAction> GetFixes (MonoDevelop.Ide.Gui.Document doc, object fix)
		{
			var renameFix = (RenameMemberFix) fix;
			var refactoring = new RenameRefactoring ();
			var options = new RefactoringOptions () {
				Document = doc,
				Dom = doc.Dom,
				SelectedItem = renameFix.Item,
			};
			if (!refactoring.IsValid (options))
				yield break;
			
			var prop = new RenameRefactoring.RenameProperties () {
				NewName = renameFix.NewName,
			};
			
			yield return new RenameFixAction () {
				Label = GettextCatalog.GetString ("Rename '{0}' to '{1}'", renameFix.Item.Name, renameFix.NewName),
				Refactoring = refactoring,
				Options = options,
				Properties = prop,
				Preview = false,
			};
				
			yield return new RenameFixAction () {
				Label = GettextCatalog.GetString ("Rename '{0}' to '{1}' with preview",
					renameFix.Item.Name, renameFix.NewName),
				Refactoring = refactoring,
				Options = options,
				Properties = prop,
				Preview = true,
			};
		}
		bool AnalyzeTargetExpression (RefactoringOptions options, MonoDevelop.CSharp.Ast.CompilationUnit unit)
		{
			var data = options.GetTextEditorData ();
			var target = unit.GetNodeAt (data.Caret.Line, data.Caret.Column);
			if (target == null)
				return false;
			if (target.Parent is MemberReferenceExpression && ((MemberReferenceExpression)target.Parent).GetChildByRole (MemberReferenceExpression.Roles.Identifier) == target) {
				var memberReference = (MemberReferenceExpression)target.Parent;
				target = memberReference.Target;
				var targetResult = options.GetResolver ().Resolve (new ExpressionResult (data.GetTextBetween (target.StartLocation.Line, target.StartLocation.Column, target.EndLocation.Line, target.EndLocation.Column)), resolvePosition);
				if (targetResult.StaticResolve)
					modifiers = MonoDevelop.Projects.Dom.Modifiers.Static;
				declaringType = options.Dom.GetType (targetResult.ResolvedType);
				methodName = memberReference.MemberName;
			} else if (target is Identifier) {
				declaringType = options.ResolveResult.CallingType;
				methodName = data.GetTextBetween (target.StartLocation.Line, target.StartLocation.Column, target.EndLocation.Line, target.EndLocation.Column);
			}
			
			if (declaringType != null && !HasCompatibleMethod (declaringType, methodName, invocation)) {
				if (declaringType.HasParts)
					declaringType = declaringType.Parts.FirstOrDefault (t => t.CompilationUnit.FileName == options.Document.FileName) ?? declaringType;
				var doc = ProjectDomService.GetParsedDocument (declaringType.SourceProjectDom, declaringType.CompilationUnit.FileName);
				declaringType = doc.CompilationUnit.GetTypeAt (declaringType.Location) ?? declaringType;
				return true;
			}
			return false;
		}
Пример #4
0
        public DRenameNameDialog(RefactoringOptions options,DRenameRefactoring rename)
        {
            this.rename = rename;
            this.options = options;

            this.Build ();
            var ds = (INode)options.SelectedItem;

            #region Adjust dialog title
            var app = "Renaming ";

            if (ds is DClassLike)
            {
                var dc = (DClassLike)ds;
                app+=dc.ClassType.ToString();
            }
            else if (ds is DMethod)
                app += "method";
            else if (ds is DVariable)
                app += ((DVariable)ds).IsAlias ? "alias" : "variable";
            else
                app += "item";

            Title = app;
            #endregion

            text_NewId.Text = ds.Name;

            buttonPreview.Sensitive = buttonOk.Sensitive = false;

            buttonOk.Clicked += OnOKClicked;
            buttonPreview.Clicked += OnPreviewClicked;
            text_NewId.Changed += delegate { setNotifyIcon(buttonPreview.Sensitive = buttonOk.Sensitive = ValidateName()); };
            ValidateName();
        }
Пример #5
0
 protected override void Run(RefactoringOptions options)
 {
     if (renameRefactoring.IsValid (options))
     {
         renameRefactoring.Run (options);
     }
 }
Пример #6
0
        public override List<Change> PerformChanges(RefactoringOptions options, object properties)
        {
            List<Change> changes = new List<Change>();
            var resolveResult = options.ResolveResult;
            if (resolveResult == null) throw new InvalidOperationException("Cannot generate class here");
            var resType = resolveResult.ResolvedType;

            var doc = options.Document;
            var editor = doc.Editor;
            var currentDir = doc.FileName.ParentDirectory;
            var nspace = resType.Namespace;
            string typeName = resolveResult.ResolvedExpression.Expression;
            var body = resType.Type.BodyRegion;
            var content = editor.GetTextBetween(body.Start.Line, 1, body.End.Line, body.End.Column);
            var contentLength = content.Length;
            content = fileFormatResolver.GetNewTypeFileContent(content, nspace, editor.EolMarker);
            CreateFileChange createFileChange = new CreateFileChange(@"{0}\{1}.cs".ToFormat(currentDir, typeName), content);
            changes.Add(createFileChange);

            TextReplaceChange textReplaceChange = new TextReplaceChange();
            textReplaceChange.FileName = context.GetCurrentFilePath();
            textReplaceChange.RemovedChars = contentLength + 1;
            int num = editor.Document.LocationToOffset(body.Start.Line, 1);
            textReplaceChange.Offset = num - 1;
            textReplaceChange.InsertedText = string.Empty;
            changes.Add (textReplaceChange);

            return changes;
        }
Пример #7
0
        public override List<Change> PerformChanges(RefactoringOptions options, object prop)
        {
            #region Init
            var renameProperties = prop as RenameProperties;
            if (renameProperties == null) return null;

            var changes = new List<Change>();

            var doc = options.Document;
            if (doc == null)	return null;

            var ddoc = doc.ParsedDocument as ParsedDModule;
            if (ddoc == null)	return null;

            var n = options.SelectedItem as INode;
            if (n == null) return null;

            var project = doc.HasProject ? doc.Project as DProject : null;

            var parseCache = project != null ?
                project.ParseCache :
                ParseCacheList.Create(DCompilerService.Instance.GetDefaultCompiler().ParseCache);

            var modules = project == null ?
                (IEnumerable<DModule>)new[] { (Ide.IdeApp.Workbench.ActiveDocument.ParsedDocument as ParsedDModule).DDom } :
                project.LocalFileCache;

            var ctxt = ResolutionContext.Create(parseCache, null,null);
            #endregion

            // Enumerate references
            foreach (var mod in modules)
            {
                if (mod == null)
                    continue;

                var references = D_Parser.Refactoring.ReferencesFinder.Scan(mod, n, ctxt).ToList();

                if (((DModule)n.NodeRoot).FileName == mod.FileName)
                    references.Insert(0, new IdentifierDeclaration(n.Name) { Location = n.NameLocation });

                if (references.Count < 1)
                    continue;

                var txt = TextFileProvider.Instance.GetEditableTextFile(new FilePath(mod.FileName));
                foreach (ISyntaxRegion reference in references)
                {
                    changes.Add(new TextReplaceChange {
                        FileName = mod.FileName,
                        InsertedText = renameProperties.NewName,
                        RemovedChars = n.Name.Length,
                        Description = string.Format (GettextCatalog.GetString ("Replace '{0}' with '{1}'"), n.Name, renameProperties.NewName),
                        Offset = txt.GetPositionFromLineColumn(reference.Location.Line, reference.Location.Column)
                    });
                }
            }

            return changes;
        }
Пример #8
0
 public void ProcessSelection(IEnumerable<IRefactorTask> tasks, RefactoringOptions options)
 {
     Options = options;
     var displayableTasks = tasks.ToList();
     displayableTasks.Add(new CancelRefactoring());
     displayableTasks.Reverse ();
     selectionDisplay.GetSelectedFix(displayableTasks);
 }
Пример #9
0
        public override bool IsValid(RefactoringOptions options)
        {
            if (options == null)
                return false;

            var n = options.SelectedItem as INode;
            //TODO: Any further node types that cannot be renamed?
            return n != null && CanRenameNode(n);
        }
		public override bool IsValid (RefactoringOptions options)
		{
			try {
				return Analyze (options);
			} catch (Exception e) {
				LoggingService.LogError ("Exception while create method analyzation", e);
				return false;
			}
		}
		protected override void Run (RefactoringOptions options)
		{
			RemoveUnusedImportsRefactoring removeUnusedImportsRefactoring = new RemoveUnusedImportsRefactoring ();
			SortImportsRefactoring sortImportsRefactoring = new SortImportsRefactoring ();
			if (removeUnusedImportsRefactoring.IsValid (options) && sortImportsRefactoring.IsValid (options)) {
				sortImportsRefactoring.Run (options);
				removeUnusedImportsRefactoring.Run (options);
			}
		}
Пример #12
0
 public override bool IsValid(RefactoringOptions options)
 {
     if (context.IsCurrentPositionTypeDeclarationUnmatchingFileName()) {
         var types = context.GetTypes ();
         if (types == null)
             return false;
         return types.Count () > 1;
     }
     return false;
 }
Пример #13
0
 public QuickFixDialog(RefactoringOptions options, RefactoringOperation refactoring)
 {
     this.refactoring = refactoring;
     this.options = options;
     this.Build ();
     buttonOk.Clicked += OnOKClicked;
     this.Title = "Quick Fix";
     this.label1.Text = "Are you sure you want to move this type to a new file?";
     this.GdkWindow.Opacity = 0.75;
 }
Пример #14
0
		public override void Run (RefactoringOptions options)
		{
			ExtractMethodParameters param = CreateParameters (options);
			if (param == null)
				return;
			if (!Analyze (options, param, false)) {
				MessageService.ShowError (GettextCatalog.GetString ("Invalid selection for method extraction."));
				return;
			}
			MessageService.ShowCustomDialog (new ExtractMethodDialog (options, this, param));
		}
        public CreateIVarDialog(RefactoringOperation refactoring, RefactoringOptions options, MonobjcProject project)
            : base(refactoring, options, project)
        {
            this.Build ();

            this.buttonOk.Sensitive = false;
            this.entryName.Changed += delegate { this.buttonOk.Sensitive = this.Validate (); };
            this.entryType.Changed += delegate { this.buttonOk.Sensitive = this.Validate (); };
            this.Validate ();

            this.buttonOk.Clicked += OnOKClicked;
        }
Пример #16
0
		void HandleVisitorUsingDeclarationVisited (UsingDeclaration node, InspectionData data)
		{
			if (!data.Graph.UsedUsings.Contains (node.Namespace)) {
				AddResult (data,
					new DomRegion (node.StartLocation.Line, node.StartLocation.Column, node.EndLocation.Line, node.EndLocation.Column),
					GettextCatalog.GetString ("Remove unused usings"),
					delegate {
						RefactoringOptions options = new RefactoringOptions () { Document = data.Document, Dom = data.Document.Dom};
						new RemoveUnusedImportsRefactoring ().Run (options);
					}
				);
			}
		}
Пример #17
0
		//FIXME: why is this invalid on the parseddocuments loaded when the doc is first loaded?
		//maybe the item's type's SourceProject is null?
		public IEnumerable<IAnalysisFixAction> GetFixes (MonoDevelop.Ide.Gui.Document doc, object fix)
		{
			var renameFix = (RenameMemberFix)fix;
			var refactoring = new RenameRefactoring ();
			var options = new RefactoringOptions () {
				Document = doc,
				Dom = doc.Dom,
				SelectedItem = renameFix.Item,
			};
			
			if (renameFix.Item == null) {
				INode item;
				ResolveResult resolveResult;
				var editor = options.Document.GetContent<MonoDevelop.Ide.Gui.Content.ITextBuffer> ();
				CurrentRefactoryOperationsHandler.GetItem (options.Dom, options.Document, editor, out resolveResult, out item);
				options.SelectedItem = item;
			}
			
			if (!refactoring.IsValid (options))
				yield break;
			
			var prop = new RenameRefactoring.RenameProperties () {
				NewName = renameFix.NewName,
			};
			if (string.IsNullOrEmpty (renameFix.NewName)) {
				yield return new RenameFixAction () {
					Label = GettextCatalog.GetString ("Rename '{0}'...", renameFix.OldName),
					Refactoring = refactoring,
					Options = options,
					Properties = prop,
					Preview = false,
				};
				yield break;
			}
			yield return new RenameFixAction () {
				Label = GettextCatalog.GetString ("Rename '{0}' to '{1}'", renameFix.OldName, renameFix.NewName),
				Refactoring = refactoring,
				Options = options,
				Properties = prop,
				Preview = false,
			};
			
			yield return new RenameFixAction () {
				Label = GettextCatalog.GetString ("Rename '{0}' to '{1}' with preview",
					renameFix.OldName, renameFix.NewName),
				Refactoring = refactoring,
				Options = options,
				Properties = prop,
				Preview = true,
			};
		}
Пример #18
0
		public override bool IsValid (RefactoringOptions options)
		{
//			if (options.SelectedItem != null)
//				return false;
			var buffer = options.Document.Editor;
			if (buffer.IsSomethingSelected) {
				ParsedDocument doc = options.ParseDocument ();
				if (doc != null && doc.CompilationUnit != null) {
					if (doc.CompilationUnit.GetMemberAt (buffer.Caret.Line, buffer.Caret.Column) == null)
						return false;
					return true;
				}
			}
			return false;
		}
        public override bool IsValid(RefactoringOptions options)
        {
            if (options.ResolveResult == null) {
                return false;
            }

            if (!IsProjectValid(options)) {
                return false;
            }

            if (!IsClass(options)) {
                return false;
            }

            return true;
        }
		//FIXME: why is this invalid on the parseddocuments loaded when the doc is first loaded?
		//maybe the item's type's SourceProject is null?
		public IEnumerable<IAnalysisFixAction> GetFixes (TextEditor editor, DocumentContext doc, object fix)
		{
			var renameFix = (RenameMemberFix)fix;
			var refactoring = new RenameRefactoring ();
			var options = new RefactoringOptions (editor, doc) {
			//	SelectedItem = renameFix.Item,
			};
			
//			if (renameFix.Item == null) {
//				ResolveResult resolveResult;
//				options.SelectedItem = CurrentRefactoryOperationsHandler.GetItem (options.Editor, options.DocumentContext, out resolveResult);
//			}
//			
//			if (!refactoring.IsValid (options))
//				yield break;
//			
			var prop = new RenameRefactoring.RenameProperties () {
				NewName = renameFix.NewName,
			};
			if (string.IsNullOrEmpty (renameFix.NewName)) {
				yield return new RenameFixAction () {
					Label = GettextCatalog.GetString ("Rename '{0}'...", renameFix.OldName),
					Refactoring = refactoring,
					Options = options,
					Properties = prop,
					Preview = false,
				};
				yield break;
			}
			yield return new RenameFixAction () {
				Label = GettextCatalog.GetString ("Rename '{0}' to '{1}'", renameFix.OldName, renameFix.NewName),
				Refactoring = refactoring,
				Options = options,
				Properties = prop,
				Preview = false,
			};
			
			yield return new RenameFixAction () {
				Label = GettextCatalog.GetString ("Rename '{0}' to '{1}' with preview",
					renameFix.OldName, renameFix.NewName),
				Refactoring = refactoring,
				Options = options,
				Properties = prop,
				Preview = true,
			};
		}
Пример #21
0
		public static List<string> GetResolveableNamespaces (RefactoringOptions options, out bool resolveDirect)
		{
			IReturnType returnType = null; 
			INRefactoryASTProvider astProvider = RefactoringService.GetASTProvider (DesktopService.GetMimeTypeForUri (options.Document.FileName));
			
			if (options.ResolveResult != null && options.ResolveResult.ResolvedExpression != null) {
				if (astProvider != null) 
					returnType = astProvider.ParseTypeReference (options.ResolveResult.ResolvedExpression.Expression).ConvertToReturnType ();
				if (returnType == null)
					returnType = DomReturnType.GetSharedReturnType (options.ResolveResult.ResolvedExpression.Expression);
			}
			
			List<string> namespaces;
			if (options.ResolveResult is UnresolvedMemberResolveResult) {
				namespaces = new List<string> ();
				UnresolvedMemberResolveResult unresolvedMemberResolveResult = options.ResolveResult as UnresolvedMemberResolveResult;
				IType type = unresolvedMemberResolveResult.TargetResolveResult != null ? options.Dom.GetType (unresolvedMemberResolveResult.TargetResolveResult.ResolvedType) : null;
				if (type != null) {
					List<IType> allExtTypes = DomType.GetAccessibleExtensionTypes (options.Dom, null);
					List<IMethod> extensionMethods = type.GetExtensionMethods (allExtTypes);
					foreach (ExtensionMethod method in extensionMethods) {
						if (method.Name == unresolvedMemberResolveResult.MemberName) {
							string ns = method.OriginalMethod.DeclaringType.Namespace;
							if (!namespaces.Contains (ns) && !options.Document.CompilationUnit.Usings.Any (u => u.Namespaces.Contains (ns)))
								namespaces.Add (ns);
						}
					}
				}
				resolveDirect = false;
			} else {
				namespaces = new List<string> (options.Dom.ResolvePossibleNamespaces (returnType));
				resolveDirect = true;
			}
			for (int i = 0; i < namespaces.Count; i++) {
				for (int j = i + 1; j < namespaces.Count; j++) {
					if (namespaces[j] == namespaces[i]) {
						namespaces.RemoveAt (j);
						j--;
					}
				}
			}
			return namespaces;
		}
Пример #22
0
		protected override void Run (RefactoringOptions options)
		{
			Gtk.Menu menu = new Gtk.Menu ();
			
			bool resolveDirect;
			List<string> namespaces = GetResolveableNamespaces (options, out resolveDirect);
			
			foreach (string ns in namespaces) {
				// remove used namespaces for conflict resolving.
				if (options.Document.CompilationUnit.IsNamespaceUsedAt (ns, options.ResolveResult.ResolvedExpression.Region.Start))
					continue;
				Gtk.MenuItem menuItem = new Gtk.MenuItem (string.Format (GettextCatalog.GetString ("Add using '{0}'"), ns));
				CurrentRefactoryOperationsHandler.ResolveNameOperation resolveNameOperation = new CurrentRefactoryOperationsHandler.ResolveNameOperation (options.Dom, options.Document, options.ResolveResult, ns);
				menuItem.Activated += delegate {
					resolveNameOperation.AddImport ();
				};
				menu.Add (menuItem);
			}
			if (resolveDirect) {
				foreach (string ns in namespaces) {
					Gtk.MenuItem menuItem = new Gtk.MenuItem (string.Format (GettextCatalog.GetString ("Add '{0}'"), ns));
					CurrentRefactoryOperationsHandler.ResolveNameOperation resolveNameOperation = new CurrentRefactoryOperationsHandler.ResolveNameOperation (options.Dom, options.Document, options.ResolveResult, ns);
					menuItem.Activated += delegate {
						resolveNameOperation.ResolveName ();
					};
					menu.Add (menuItem);
				}
			}
			
			if (menu.Children != null && menu.Children.Length > 0) {
				menu.ShowAll ();
				
				ICompletionWidget widget = options.Document.GetContent<ICompletionWidget> ();
				CodeCompletionContext codeCompletionContext = widget.CreateCodeCompletionContext (options.GetTextEditorData ().Caret.Offset);

				menu.Popup (null, null, delegate (Gtk.Menu menu2, out int x, out int y, out bool pushIn) {
					x = codeCompletionContext.TriggerXCoord; 
					y = codeCompletionContext.TriggerYCoord; 
					pushIn = false;
				}, 0, Gtk.Global.CurrentEventTime);
				menu.SelectFirst (true);
			}
		}
Пример #23
0
        public RenameNamespaceItemDialog(RefactoringOptions options, RenameRefactoring rename)
        {
            this.options = options;
            this.rename = rename;
            Initialize();

            this.Title = GettextCatalog.GetString ("Rename Namespace");

            entry.SelectRegion (0, -1);

            buttonPreview.Sensitive = buttonOk.Sensitive = false;
            entry.Changed += OnEntryChanged;
            entry.Activated += OnEntryActivated;

            buttonOk.Clicked += OnOKClicked;
            buttonPreview.Clicked += OnPreviewClicked;
            entry.Changed += delegate { buttonPreview.Sensitive = buttonOk.Sensitive = ValidateName (); };
            ValidateName ();
        }
		public override bool IsValid (RefactoringOptions options)
		{
//			if (options.SelectedItem != null)
//				return false;
			var buffer = options.Document.Editor;
			if (buffer.Document.MimeType != CSharpFormatter.MimeType)
				return false;
			if (buffer.IsSomethingSelected) {
				ParsedDocument doc = options.ParseDocument ();
				if (doc != null && doc.CompilationUnit != null) {
					var member = doc.CompilationUnit.GetMemberAt (buffer.Caret.Line, buffer.Caret.Column);
					if (member == null)
						return false;
					if (!member.BodyRegion.Contains (buffer.Caret.Line, buffer.Caret.Column))
						return false;
					return true;
				}
			}
			return false;
		}
		bool AnalyzeTargetExpression (RefactoringOptions options, MonoDevelop.CSharp.Dom.CompilationUnit unit)
		{
			var data = options.GetTextEditorData ();
			var target = unit.GetNodeAt (data.Caret.Line, data.Caret.Column);
			if (target == null)
				return false;
			if (target.Parent is MemberReferenceExpression && ((MemberReferenceExpression)target.Parent).Identifier == target) {
				var memberReference = (MemberReferenceExpression)target.Parent;
				target = memberReference.Target;
				var targetResult = options.GetResolver ().Resolve (new ExpressionResult (data.GetTextBetween (target.StartLocation.Line, target.StartLocation.Column, target.EndLocation.Line, target.EndLocation.Column)), resolvePosition);
				if (targetResult.StaticResolve)
					modifiers = MonoDevelop.Projects.Dom.Modifiers.Static;
				declaringType = options.Dom.GetType (targetResult.ResolvedType);
				methodName = memberReference.Identifier.Name;
			} else if (target is Identifier) {
				declaringType = options.ResolveResult.CallingType;
				methodName = data.GetTextBetween (target.StartLocation.Line, target.StartLocation.Column, target.EndLocation.Line, target.EndLocation.Column);
			}
			return declaringType != null && !HasCompatibleMethod (declaringType, methodName, invocation);
		}
Пример #26
0
 public override List<Change> PerformChanges(RefactoringOptions options, object prop)
 {
     string newName = (string) prop;
     List<Change> changes = new List<Change>();
     using (var dialogProgressMonitor = new MessageDialogProgressMonitor(true, false, false, true)) {
         var references = finder.FindReferences((NamespaceResolveResult)options.ResolveResult, dialogProgressMonitor);
         if (references == null)
           return changes;
         foreach (MemberReference memberReference in references)
         {
             TextReplaceChange textReplaceChange = new TextReplaceChange();
             textReplaceChange.FileName = (string) memberReference.FileName;
             textReplaceChange.Offset = memberReference.Position;
             textReplaceChange.RemovedChars = memberReference.Name.Length;
             textReplaceChange.InsertedText = newName;
             textReplaceChange.Description = string.Format(GettextCatalog.GetString("Replace '{0}' with '{1}'"), (object) memberReference.Name, (object) newName);
             changes.Add((Change) textReplaceChange);
         }
     }
     return changes;
 }
		protected override void Run (object data)
		{
			Document doc = IdeApp.Workbench.ActiveDocument;
			if (doc == null)
				return;
			
			ITextBuffer editor = doc.GetContent<ITextBuffer> ();
			if (editor == null)
				return;
			
			ProjectDom dom = doc.Dom;
			
			ResolveResult result;
			INode item;
			CurrentRefactoryOperationsHandler.GetItem (dom, doc, editor, out result, out item);
			
			RefactoringOptions options = new RefactoringOptions () {
				Document = doc,
				Dom = dom,
				ResolveResult = result,
				SelectedItem = item is InstantiatedType ? ((InstantiatedType)item).UninstantiatedType : item
			};
			Run (options);
		}
Пример #28
0
        public override List<Change> PerformChanges(RefactoringOptions options, object properties)
        {
            List<Change> changes = new List<Change>();
            var textReplaceChange = new TextReplaceChange();
            textReplaceChange.FileName = context.GetCurrentFilePath();
            textReplaceChange.RemovedChars = 0;
            int num = data.Document.LocationToOffset(insertionPoint.Location);
            textReplaceChange.Offset = num;

            var resolveResult = context.GetResolvedTypeNameResult ();
            if (resolveResult == null) throw new InvalidOperationException("Cannot generate class here");
            var nspace = resolveResult.CallingType.Namespace;
            string newTypeName = resolveResult.ResolvedExpression.Expression;
            StringBuilder contentBuilder = new StringBuilder();
            if (insertionPoint.LineBefore == NewLineInsertion.Eol) contentBuilder.Append(data.EolMarker);
            contentBuilder.Append(data.EolMarker);
            contentBuilder.Append(data.EolMarker);
            var content = fileFormatResolver.GetNewTypeContent(newTypeName, indent, data.EolMarker);
            contentBuilder.Append(content);
            if (insertionPoint.LineAfter == NewLineInsertion.None) contentBuilder.Append(data.EolMarker);
            textReplaceChange.InsertedText = contentBuilder.ToString();

            changes.Add(textReplaceChange);
            return changes;
        }
Пример #29
0
 public override bool IsValid(RefactoringOptions options)
 {
     return IsValid ();
 }
Пример #30
0
 public override string GetMenuDescription(RefactoringOptions options)
 {
     return "Generate new _type";
 }
 public virtual List <Change> PerformChanges(RefactoringOptions options, object properties)
 {
     throw new System.NotImplementedException();
 }
 public override void PerformChange(IProgressMonitor monitor, RefactoringOptions rctx)
 {
     IdeApp.Workbench.OpenDocument(FileName);
 }
Пример #33
0
 public override void PerformChange(ProgressMonitor monitor, RefactoringOptions rctx)
 {
     File.WriteAllText(FileName, Content);
     rctx.DocumentContext.Project.AddFile(FileName);
     IdeApp.ProjectOperations.SaveAsync(rctx.DocumentContext.Project);
 }
Пример #34
0
 public override void PerformChange(ProgressMonitor monitor, RefactoringOptions rctx)
 {
     IdeApp.ProjectOperations.SaveAsync(this.Project);
 }
Пример #35
0
 public abstract void PerformChange(ProgressMonitor monitor, RefactoringOptions rctx);
Пример #36
0
        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;
            }

            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)
            {
                if (QuickTaskStrip.EnableFancyFeatures)
                {
                    var ext = doc.GetContent <CodeActionEditorExtension> ();
                    refactoringInfo.validActions = ext != null?ext.GetCurrentFixes() : null;
                }
                else
                {
                    refactoringInfo.validActions = RefactoringService.GetValidActions(doc, loc).Result;
                }

                lastLocation = loc;
                refactoringInfo.lastDocument = doc.ParsedDocument;
            }
            if (refactoringInfo.validActions != null)
            {
                var context = refactoringInfo.lastDocument.CreateRefactoringContext(doc, CancellationToken.None);
                foreach (var fix_ in refactoringInfo.validActions)
                {
                    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 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;
                if (member.IsVirtual || member.IsAbstract || member.DeclaringType.Kind == TypeKind.Interface)
                {
                    ainfo.Add(GettextCatalog.GetString("Find Derived Symbols"), new System.Action(new FindDerivedSymbolsHandler(doc, member).Run));
                    added = true;
                }
            }
            if (item is IMember)
            {
                var member = (IMember)item;
                if (member.SymbolKind == SymbolKind.Method || member.SymbolKind == SymbolKind.Indexer)
                {
                    ainfo.Add(GettextCatalog.GetString("Find Member Overloads"), new System.Action(new FindMemberOverloadsHandler(doc, member).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)
                {
                    ainfo.Add(cls.Kind != TypeKind.Interface ? GettextCatalog.GetString("Find _derived classes") : GettextCatalog.GetString("Find _implementor classes"), new System.Action(new FindDerivedClasses(cls).Run));
                }
                ainfo.Add(GettextCatalog.GetString("Find Extension Methods"), new System.Action(new FindExtensionMethodHandler(doc, cls).Run));
                added = true;
            }

            if (added)
            {
                ainfo.AddSeparator();
            }
        }
 public virtual bool IsValid(RefactoringOptions options)
 {
     return(true);
 }
Пример #38
0
 public RefactoringOperationWrapper(RefactoringOperation refactoring, RefactoringOptions options)
 {
     this.refactoring = refactoring;
     this.options     = options;
 }
Пример #39
0
        public static void AcceptChanges(ProgressMonitor monitor, IList <Change> changes, MonoDevelop.Ide.ITextFileProvider fileProvider)
        {
            var rctx    = new RefactoringOptions(null, null);
            var handler = new RenameHandler(changes);

            FileService.FileRenamed += handler.FileRename;
            var    fileNames = new HashSet <FilePath> ();
            var    ws        = TypeSystemService.Workspace as MonoDevelopWorkspace;
            string originalName;
            int    originalOffset;

            try {
                for (int i = 0; i < changes.Count; i++)
                {
                    var change = changes [i] as TextReplaceChange;
                    if (change == null)
                    {
                        continue;
                    }

                    if (ws.TryGetOriginalFileFromProjection(change.FileName, change.Offset, out originalName, out originalOffset))
                    {
                        fileNames.Add(change.FileName);
                        change.FileName = originalName;
                        change.Offset   = originalOffset;
                    }
                }
                if (changes.All(x => x is TextReplaceChange))
                {
                    List <Change> newChanges = new List <Change> (changes);
                    newChanges.Sort((Change x, Change y) => ((TextReplaceChange)x).Offset.CompareTo(((TextReplaceChange)y).Offset));
                    changes = newChanges;
                }


                for (int i = 0; i < changes.Count; i++)
                {
                    changes [i].PerformChange(monitor, rctx);
                    var replaceChange = changes [i] as TextReplaceChange;
                    if (replaceChange == null)
                    {
                        continue;
                    }

                    for (int j = i + 1; j < changes.Count; j++)
                    {
                        var change = changes [j] as TextReplaceChange;
                        if (change == null)
                        {
                            continue;
                        }

                        fileNames.Add(change.FileName);

                        if (replaceChange.Offset >= 0 && change.Offset >= 0 && replaceChange.FileName == change.FileName)
                        {
                            if (replaceChange.Offset < change.Offset)
                            {
                                change.Offset -= replaceChange.RemovedChars;
                                if (!string.IsNullOrEmpty(replaceChange.InsertedText))
                                {
                                    change.Offset += replaceChange.InsertedText.Length;
                                }
                            }
                            else if (replaceChange.Offset < change.Offset + change.RemovedChars)
                            {
                                change.RemovedChars = Math.Max(0, change.RemovedChars - replaceChange.RemovedChars);
                                change.Offset       = replaceChange.Offset + (!string.IsNullOrEmpty(replaceChange.InsertedText) ? replaceChange.InsertedText.Length : 0);
                            }
                        }
                    }
                }

                foreach (var renameChange in changes.OfType <RenameFileChange> ())
                {
                    if (fileNames.Contains(renameChange.OldName))
                    {
                        fileNames.Remove(renameChange.OldName);
                        fileNames.Add(renameChange.NewName);
                    }
                }

                foreach (var doc in IdeApp.Workbench.Documents)
                {
                    fileNames.Remove(doc.FileName);
                }
            } catch (Exception e) {
                LoggingService.LogError("Error while applying refactoring changes", e);
            } finally {
                FileService.NotifyFilesChanged(fileNames);
                FileService.FileRenamed -= handler.FileRename;
                TextReplaceChange.FinishRefactoringOperation();
            }
        }
 public virtual string GetMenuDescription(RefactoringOptions options)
 {
     return(Name);
 }