public void OnSetBuildActionUpdate(CommandArrayInfo info)
        {
            var     toggledActions = new Set <string> ();
            Project proj           = null;

            foreach (var node in CurrentNodes)
            {
                var finfo = (ProjectFile)node.DataItem;

                //disallow multi-slect on more than one project, since available build actions may differ
                if (proj == null && finfo.Project != null)
                {
                    proj = finfo.Project;
                }
                else if (proj == null || proj != finfo.Project)
                {
                    info.Clear();
                    return;
                }
                toggledActions.Add(finfo.BuildAction);
            }

            if (proj == null)
            {
                return;
            }

            foreach (string action in proj.GetBuildActions())
            {
                if (action == "--")
                {
                    info.AddSeparator();
                }
                else
                {
                    CommandInfo ci = info.Add(action, action);
                    ci.Checked = toggledActions.Contains(action);
                    if (ci.Checked)
                    {
                        ci.CheckedInconsistent = toggledActions.Count > 1;
                    }
                }
            }
        }
        protected override async Task UpdateAsync(CommandArrayInfo info, CancellationToken cancelToken)
        {
            var languageClient = GetLanguageClientExtension();

            if (languageClient == null)
            {
                return;
            }

            try {
                await AddQuickFixCommands(info, languageClient, cancelToken);
            } catch (OperationCanceledException) {
                // Ignore.
            } catch (Exception ex) {
                LoggingService.LogError("Error creating quick fix menu.", ex);
                info.Clear();
                AddNoFixesAvailableCommand(info);
            }
        }
        protected override void Update(CommandArrayInfo info)
        {
            var project = IdeApp.ProjectOperations.CurrentSelectedProject as DnxProject;

            if (project == null)
            {
                info.Bypass = true;
                return;
            }

            foreach (DnxFramework framework in project.GetFrameworks())
            {
                CommandInfo item = info.Add(framework.FriendlyName, framework);
                if (framework.Name == project.CurrentFramework)
                {
                    item.Checked = true;
                }
            }
        }
Пример #4
0
        protected override void Update(CommandArrayInfo info)
        {
            if (IdeApp.Workbench.Documents.Count < 10)
            {
                return;
            }

            int i = 0;

            foreach (Document document in IdeApp.Workbench.Documents)
            {
                if (i < 9)
                {
                    i++;
                    continue;
                }

                //Create CommandInfo object
                CommandInfo commandInfo = new CommandInfo();
                commandInfo.Text = document.Window.Title.Replace("_", "__");
                if (document == IdeApp.Workbench.ActiveDocument)
                {
                    commandInfo.Checked = true;
                }
                commandInfo.Description = GettextCatalog.GetString("Activate document '{0}'", commandInfo.Text);
                if (document.Window.ShowNotification)
                {
                    commandInfo.UseMarkup = true;
                    commandInfo.Text      = "<span foreground=" + '"' + "blue" + '"' + ">" + commandInfo.Text + "</span>";
                }

                //Add AccelKey
                if (IdeApp.Workbench.Documents.Count + i < 10)
                {
                    commandInfo.AccelKey = ((Platform.IsMac) ? "Meta" : "Alt") + "|" + ((i + 1) % 10).ToString();
                }

                //Add menu item
                info.Add(commandInfo, document);

                i++;
            }
        }
Пример #5
0
        protected override void Update(CommandArrayInfo info)
        {
            IConfigurationTarget ce = IdeApp.ProjectOperations.CurrentSelectedBuildTarget as IConfigurationTarget;

            if (ce != null)
            {
                ItemConfiguration conf = ce.DefaultConfiguration;
                if (conf != null)
                {
                    foreach (CustomCommand cmd in conf.CustomCommands)
                    {
                        if (cmd.Type == CustomCommandType.Custom)
                        {
                            info.Add(cmd.Name, cmd);
                        }
                    }
                }
            }
        }
        public void OnAddSpecialDirectoryUpdate(CommandArrayInfo info)
        {
            var proj = CurrentNode.DataItem as DotNetProject;

            if (proj == null)
            {
                return;
            }

            var asp = proj.GetFlavor <AspNetAppProjectFlavor> ();

            if (asp == null)
            {
                return;
            }

            List <string> dirs = new List <string> (asp.GetSpecialDirectories());

            dirs.Sort();
            List <FilePath> fullPaths = new List <FilePath> (dirs.Count);

            foreach (string s in dirs)
            {
                fullPaths.Add(proj.BaseDirectory.Combine(s));
            }
            RemoveDirsNotInProject(fullPaths, proj);

            if (fullPaths.Count == 0)
            {
                return;
            }

            foreach (string dir in dirs)
            {
                if (!fullPaths.Contains(proj.BaseDirectory.Combine(dir)))
                {
                    continue;
                }
                info.Add(dir.Replace("_", "__"), dir);
            }
        }
Пример #7
0
        void PopulateArrayItems(CommandArrayInfo infos, NSMenu parent, ref NSMenuItem lastSeparator, ref int index)
        {
            if (infos == null)
            {
                return;
            }

            foreach (CommandInfo ci in infos)
            {
                if (ci.IsArraySeparator)
                {
                    var n = NSMenuItem.SeparatorItem;
                    n.Hidden      = true;
                    n.Target      = this;
                    lastSeparator = n;
                    parent.InsertItem(n, index++);
                    continue;
                }

                var item = new MDExpandedArrayItem {
                    Info   = ci,
                    Target = this,
                    Action = ActionSel,
                };

                if (ci is CommandInfoSet)
                {
                    item.Submenu = new NSMenu();
                    int        i   = 0;
                    NSMenuItem sep = null;
                    PopulateArrayItems(((CommandInfoSet)ci).CommandInfos, item.Submenu, ref sep, ref i);
                }
                SetItemValues(item, ci);

                if (!item.Hidden)
                {
                    MDMenu.ShowLastSeparator(ref lastSeparator);
                }
                parent.InsertItem(item, index++);
            }
        }
Пример #8
0
        protected override void Update(CommandArrayInfo info)
        {
            int i = 0;

            foreach (Gtk.Window window in IdeApp.CommandService.TopLevelWindowStack)
            {
                //Create CommandInfo object
                CommandInfo commandInfo = new CommandInfo();
                commandInfo.Text = window.Title.Replace("_", "__");
                if (window.HasToplevelFocus)
                {
                    commandInfo.Checked = true;
                }
                commandInfo.Description = GettextCatalog.GetString("Activate window '{0}'", commandInfo.Text);

                //Add menu item
                info.Add(commandInfo, window);

                i++;
            }
        }
Пример #9
0
        protected override void Update(CommandArrayInfo info)
        {
            var proj = DefaultUploadToDeviceHandler.GetActiveExecutableMonoDroidProject();

            if (proj == null || !MonoDroidFramework.HasAndroidJavaSdks)
            {
                return;
            }

            var conf        = (MonoDroidProjectConfiguration)proj.GetConfiguration(IdeApp.Workspace.ActiveConfiguration);
            var projSetting = proj.GetDeviceTarget(conf);

            foreach (var st in MonoDroidFramework.DeviceManager.Devices)
            {
                var i = info.Add(st.ID, st);
                if (projSetting != null && projSetting.Equals(st))
                {
                    i.Checked = true;
                }
            }
        }
Пример #10
0
        protected override async Task UpdateAsync(CommandArrayInfo info, CancellationToken cancelToken)
        {
            var editor = IdeApp.Workbench.ActiveDocument?.Editor;
            var ext    = editor?.GetContent <CodeActionEditorExtension> ();

            if (ext == null)
            {
                return;
            }

            var metadata = new Counters.FixesMenuMetadata();

            using (var timer = Counters.FixesMenu.BeginTiming("Quick Fix menu", metadata)) {
                try {
                    info.Add(new CommandInfo(GettextCatalog.GetString("Loading..."), false, false), null);
                    var currentFixes = await ext.GetCurrentFixesAsync(cancelToken);

                    var menu = CodeFixMenuService.CreateFixMenu(editor, currentFixes, cancelToken);
                    info.Clear();
                    foreach (var item in menu.Items)
                    {
                        AddItem(info, item);
                    }
                    if (menu.Items.Count == 0)
                    {
                        info.Add(new CommandInfo(GettextCatalog.GetString("No code fixes available"), false, false), null);
                    }
                    metadata.SetSuccess();
                    info.NotifyChanged();
                } catch (OperationCanceledException) {
                    metadata.SetUserCancel();
                } catch (Exception e) {
                    metadata.SetFailure();
                    LoggingService.LogError("Error while creating quick fix menu.", e);
                    info.Clear();
                    info.Add(new CommandInfo(GettextCatalog.GetString("No code fixes available"), false, false), null);
                    info.NotifyChanged();
                }
            }
        }
Пример #11
0
        protected override void Update(CommandArrayInfo info)
        {
            int currentIndex;
            IList <NavigationHistoryItem> points = IdeServices.NavigationHistoryService.GetNavigationList(15, out currentIndex);

            if (points.Count < 1)
            {
                Document doc = IdeApp.Workbench.ActiveDocument;
                if (doc != null)
                {
                    CommandInfo item = info.Add(doc.Window.Title, null);
                    item.Checked = true;
                }
                return;
            }

            for (int i = points.Count - 1; i >= 0; i--)
            {
                CommandInfo item = info.Add(points[i].DisplayName, points[i]);
                item.Checked = (i == currentIndex);
            }
        }
Пример #12
0
        protected override void Update(CommandArrayInfo info)
        {
            RecentOpen recentOpen = IdeApp.Workbench.RecentOpen;

            if (recentOpen.RecentFilesCount > 0)
            {
                int i = 0;
                foreach (RecentItem ri in recentOpen.RecentFiles)
                {
                    string      accelaratorKeyPrefix = i < 10 ? "_" + ((i + 1) % 10).ToString() + " " : "";
                    string      label = ((ri.Private == null || ri.Private.Length < 1) ? Path.GetFileName(ri.ToString()) : ri.Private);
                    CommandInfo cmd   = new CommandInfo(accelaratorKeyPrefix + label.Replace("_", "__"));
                    cmd.Description = GettextCatalog.GetString("Open {0}", ri.ToString());
                    Gdk.Pixbuf icon = DesktopService.GetPixbufForFile(ri.ToString(), IconSize.Menu);
                    if (icon != null)
                    {
                        cmd.Icon = ImageService.GetStockId(icon, IconSize.Menu);
                    }
                    info.Add(cmd, ri);
                    i++;
                }
            }
        }
Пример #13
0
        internal static void PopulateOpenWithViewers(CommandArrayInfo info, Project project, string filePath)
        {
            var viewers = DisplayBindingService.GetFileViewers(filePath, project).ToList();

            //show the default viewer first
            var def = viewers.FirstOrDefault(v => v.CanUseAsDefault) ?? viewers.FirstOrDefault(v => v.IsExternal);

            if (def != null)
            {
                CommandInfo ci = info.Add(def.Title, def);

                ci.Description = GettextCatalog.GetString("Open with '{0}'", def.Title);
                if (viewers.Count > 1)
                {
                    info.AddSeparator();
                }
            }

            //then the builtins, followed by externals
            FileViewer prev = null;

            foreach (FileViewer fv in viewers)
            {
                if (def != null && fv.Equals(def))
                {
                    continue;
                }
                if (prev != null && fv.IsExternal != prev.IsExternal)
                {
                    info.AddSeparator();
                }
                CommandInfo ci = info.Add(fv.Title, fv);
                ci.Description = GettextCatalog.GetString("Open with '{0}'", fv.Title);
                prev           = fv;
            }
        }
Пример #14
0
 protected override void Update(CommandArrayInfo info)
 {
     /*
      * var doc = IdeApp.Workbench.ActiveDocument;
      * if (doc == null || doc.FileName == FilePath.Null || doc.DocumentContext.ParsedDocument == null)
      *      return;
      *
      * var msbuildEditor = doc.GetContent<MSBuildTextEditorExtension> ();
      * if (msbuildEditor == null) {
      *      return;
      * }
      *
      * CommandInfo goToDeclarationCommand = IdeApp.CommandService.GetCommandInfo (RefactoryCommands.GotoDeclaration);
      * CommandInfo findReferenceCommand = IdeApp.CommandService.GetCommandInfo (RefactoryCommands.FindReferences);
      *
      * if (goToDeclarationCommand.Enabled) {
      *      info.Add (goToDeclarationCommand, new Action (() => IdeApp.CommandService.DispatchCommand (RefactoryCommands.GotoDeclaration)));
      * }
      *
      * if (findReferenceCommand.Enabled) {
      *      info.Add (findReferenceCommand, new Action (() => IdeApp.CommandService.DispatchCommand (RefactoryCommands.FindReferences)));
      * }
      */
 }
Пример #15
0
        // If multiple nodes are selected and the method does not have the AllowMultiSelectionAttribute
        // attribute, disable the command.

        protected override void CommandUpdate(object target, CommandArrayInfo cinfo)
        {
            NodeCommandHandler nc = (NodeCommandHandler)target;

            base.CommandUpdate(target, cinfo);
            if (nc.MultipleSelectedNodes)
            {
                bool allowMultiArray         = false;
                ICommandArrayUpdateHandler h = ((ICommandArrayUpdateHandler)this).Next;
                while (h != null)
                {
                    if (h is AllowMultiSelectionAttribute)
                    {
                        allowMultiArray = true;
                        break;
                    }
                    h = h.Next;
                }
                if (!allowMultiArray)
                {
                    cinfo.Clear();
                }
            }
        }
Пример #16
0
        public async Task OnOpenWithUpdate(CommandArrayInfo info, CancellationToken cancellationToken)
        {
            var pf = (ProjectFile)CurrentNode.DataItem;

            await PopulateOpenWithViewers(info, pf.Project, pf.FilePath);
        }
Пример #17
0
        public static void GenerateExecutionModeCommands(SolutionItem project, CanExecuteDelegate runCheckDelegate, CommandArrayInfo info)
        {
            CommandExecutionContext ctx   = new CommandExecutionContext(project, runCheckDelegate);
            bool supportsParameterization = false;

            foreach (List <IExecutionMode> modes in GetExecutionModeCommands(ctx, false, true))
            {
                foreach (IExecutionMode mode in modes)
                {
                    CommandInfo ci = info.Add(mode.Name, new CommandItem(ctx, mode));
                    if ((mode.ExecutionHandler is ParameterizedExecutionHandler) || ((mode is CustomExecutionMode) && ((CustomExecutionMode)mode).PromptForParameters))
                    {
                        // It will prompt parameters, so we need command to end with '..'.
                        // However, some commands may end with '...' already and we don't want to break
                        // already-translated strings by altering them
                        if (!ci.Text.EndsWith("..."))
                        {
                            ci.Text += "...";
                        }
                        supportsParameterization = true;
                    }
                    else
                    {
                        // The parameters window will be shown if ctrl is pressed
                        ci.Description = GettextCatalog.GetString("Run With: {0}", ci.Text);
                        if (SupportsParameterization(mode, ctx))
                        {
                            ci.Description          += " - " + GettextCatalog.GetString("Hold Control key to display the execution parameters dialog.");
                            supportsParameterization = true;
                        }
                    }
                }
                if (info.Count > 0)
                {
                    info.AddSeparator();
                }
            }

            var targets = new List <ExecutionTarget> ();

            if (project != null)
            {
                FlattenExecutionTargets(targets, project.GetExecutionTargets(IdeApp.Workspace.ActiveConfiguration));
            }

            if (targets.Count > 1)
            {
                foreach (var t in targets)
                {
                    var         h  = new TargetedExecutionHandler(Runtime.ProcessService.DefaultExecutionHandler, t);
                    CommandInfo ci = info.Add(t.FullName, new CommandItem(ctx, new ExecutionMode(t.Id, t.FullName, h)));
                    ci.Description = GettextCatalog.GetString("Run With: {0}", ci.Text);
                }
                info.AddSeparator();
            }

            if (supportsParameterization)
            {
                info.AddSeparator();
                info.Add(GettextCatalog.GetString("Edit Custom Modes..."), new CommandItem(ctx, null));
            }
        }
Пример #18
0
 internal MenuArrayInfo(CommandInfo cmdInfo)
 {
     this.cmdArrayInfo = new CommandArrayInfo(cmdInfo);
 }
Пример #19
0
 public void OnOpenWithUpdate(CommandArrayInfo info)
 {
     ProjectFileNodeCommandHandler.PopulateOpenWithViewers(info, null, ((SystemFile)CurrentNode.DataItem).Path);
 }
Пример #20
0
        protected override async Task UpdateAsync(CommandArrayInfo ainfo, CancellationToken cancelToken)
        {
            if (!TryGetDocument(out var analysisDocument, out var doc))
            {
                return;
            }
            var semanticModel = await analysisDocument.GetSemanticModelAsync(cancelToken);

            if (semanticModel == null)
            {
                return;
            }
            var info = await RefactoringSymbolInfo.GetSymbolInfoAsync(doc.DocumentContext, doc.Editor, cancelToken);

            var ext = doc.GetContent <CodeActionEditorExtension> ();

            bool canRename = RenameHandler.CanRename(info.Symbol ?? info.DeclaredSymbol);

            if (canRename)
            {
                ainfo.Add(IdeApp.CommandService.GetCommandInfo(MonoDevelop.Ide.Commands.EditCommands.Rename), new Action(async delegate {
                    await new MonoDevelop.Refactoring.Rename.RenameRefactoring().Rename(info.Symbol ?? info.DeclaredSymbol);
                }));
            }

            bool isSortAndRemoveUsingsSupported = RemoveAndSortUsingsHandler.IsSortAndRemoveImportsSupported(analysisDocument, doc.GetContent <Microsoft.VisualStudio.Text.ITextBuffer>());

            if (isSortAndRemoveUsingsSupported)
            {
                var sortAndRemoveImportsInfo = IdeApp.CommandService.GetCommandInfo(Commands.SortAndRemoveImports);
                sortAndRemoveImportsInfo.Enabled = true;
                ainfo.Add(sortAndRemoveImportsInfo, new Action(async delegate {
                    await RemoveAndSortUsingsHandler.SortAndRemoveUnusedImports(analysisDocument, cancelToken);
                }));
            }

            var gotoDeclarationSymbol = info.Symbol;

            if (gotoDeclarationSymbol == null && info.DeclaredSymbol != null && info.DeclaredSymbol.Locations.Length > 1)
            {
                gotoDeclarationSymbol = info.DeclaredSymbol;
            }
            if (IdeApp.ProjectOperations.CanJumpToDeclaration(gotoDeclarationSymbol) || gotoDeclarationSymbol == null && IdeApp.ProjectOperations.CanJumpToDeclaration(info.CandidateSymbols.FirstOrDefault()))
            {
                var type = (gotoDeclarationSymbol ?? info.CandidateSymbols.FirstOrDefault()) as INamedTypeSymbol;
                if (type != null && type.Locations.Length > 1)
                {
                    var declSet = new CommandInfoSet();
                    declSet.Text = GettextCatalog.GetString("_Go to Declaration");
                    foreach (var part in type.Locations)
                    {
                        var loc = part.GetLineSpan();
                        declSet.CommandInfos.Add(string.Format(GettextCatalog.GetString("{0}, Line {1}"), FormatFileName(part.SourceTree.FilePath), loc.StartLinePosition.Line + 1), new Action(() => IdeApp.ProjectOperations.JumpTo(type, part, doc.Owner)));
                    }
                    ainfo.Add(declSet);
                }
                else
                {
                    ainfo.Add(IdeApp.CommandService.GetCommandInfo(RefactoryCommands.GotoDeclaration), new Action(() => GotoDeclarationHandler.Run(doc)));
                }
            }


            if (info.DeclaredSymbol != null && GotoBaseDeclarationHandler.CanGotoBase(info.DeclaredSymbol))
            {
                ainfo.Add(GotoBaseDeclarationHandler.GetDescription(info.DeclaredSymbol), new Action(() => GotoBaseDeclarationHandler.GotoBase(doc, info.DeclaredSymbol).Ignore()));
            }

            var sym = info.Symbol ?? info.DeclaredSymbol;

            if (doc.DocumentContext.HasProject && sym != null)
            {
                ainfo.Add(IdeApp.CommandService.GetCommandInfo(RefactoryCommands.FindReferences), new System.Action(() => {
                    if (sym.Kind == SymbolKind.Local || sym.Kind == SymbolKind.Parameter || sym.Kind == SymbolKind.TypeParameter)
                    {
                        FindReferencesHandler.FindRefs(new [] { SymbolAndProjectId.Create(sym, analysisDocument.Project.Id) }, analysisDocument.Project.Solution).Ignore();
                    }
                    else
                    {
                        RefactoringService.FindReferencesAsync(FindReferencesHandler.FilterSymbolForFindReferences(sym).GetDocumentationCommentId()).Ignore();
                    }
                }));
                try {
                    if (Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindSimilarSymbols(sym, semanticModel.Compilation).Count() > 1)
                    {
                        ainfo.Add(IdeApp.CommandService.GetCommandInfo(RefactoryCommands.FindAllReferences), new System.Action(() => RefactoringService.FindAllReferencesAsync(FindReferencesHandler.FilterSymbolForFindReferences(sym).GetDocumentationCommentId())));
                    }
                } catch (Exception) {
                    // silently ignore roslyn bug.
                }
            }
        }
Пример #21
0
        protected override void Update(CommandArrayInfo ainfo)
        {
            var doc = IdeApp.Workbench.ActiveDocument;

            if (doc == null || doc.FileName == FilePath.Null || doc.ParsedDocument == null)
            {
                return;
            }

            ResolveResult resolveResult;
            AstNode       node;

            if (!ResolveAt(doc, out resolveResult, out node))
            {
                var location = RefactoringService.GetCorrectResolveLocation(doc, doc.Editor.Caret.Location);
                resolveResult = GetHeuristicResult(doc, location, ref node);
                if (resolveResult == null)
                {
                    return;
                }
            }
            var resolveMenu = new CommandInfoSet();

            resolveMenu.Text = GettextCatalog.GetString("Resolve");

            var possibleNamespaces = GetPossibleNamespaces(doc, node, ref resolveResult);

            bool addUsing = !(resolveResult is AmbiguousTypeResolveResult);

            if (addUsing)
            {
                foreach (var t in possibleNamespaces.Where(tp => tp.IsAccessibleWithGlobalUsing))
                {
                    string ns        = t.Namespace;
                    var    reference = t.Reference;
                    var    info      = resolveMenu.CommandInfos.Add(
                        t.GetImportText(),
                        new System.Action(new AddImport(doc, resolveResult, ns, reference, true, node).Run)
                        );
                    info.Icon = MonoDevelop.Ide.Gui.Stock.AddNamespace;
                }
            }

            bool resolveDirect = !(resolveResult is UnknownMemberResolveResult);

            if (resolveDirect)
            {
                if (resolveMenu.CommandInfos.Count > 0)
                {
                    resolveMenu.CommandInfos.AddSeparator();
                }
                if (node is ObjectCreateExpression)
                {
                    node = ((ObjectCreateExpression)node).Type;
                }
                foreach (var t in possibleNamespaces)
                {
                    string ns        = t.Namespace;
                    var    reference = t.Reference;
                    resolveMenu.CommandInfos.Add(t.GetInsertNamespaceText(doc.Editor.GetTextBetween(node.StartLocation, node.EndLocation)), new System.Action(new AddImport(doc, resolveResult, ns, reference, false, node).Run));
                }
            }

            if (resolveMenu.CommandInfos.Count > 0)
            {
                ainfo.Insert(0, resolveMenu);
            }
        }
Пример #22
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 && 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;
                if (member.IsVirtual || member.IsAbstract || member.DeclaringType.Kind == TypeKind.Interface)
                {
                    var handler = new FindDerivedSymbolsHandler(doc, member);
                    if (handler.IsValid)
                    {
                        ainfo.Add(GettextCatalog.GetString("Find Derived Symbols"), new System.Action(handler.Run));
                        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)
                {
                    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();
            }
        }
Пример #23
0
 internal CommandArrayUpdateArgs(CommandArrayInfo cmdArrayInfo)
 {
     this.Info = new MenuArrayInfo(cmdArrayInfo);
 }
Пример #24
0
        public static void PopulateInfos(CommandArrayInfo infos, Document doc, IEnumerable <FixableResult> results)
        {
            //FIXME: ellipsize long messages
            int mnemonic = 1;

            var codeActionExtension = doc.GetContent <CodeActionEditorExtension> ();
            var fixes = codeActionExtension.GetCurrentFixes();

            if (fixes != null)
            {
                foreach (var _fix in fixes.Where(CodeActionWidget.IsAnalysisOrErrorFix))
                {
                    var fix = _fix;
                    if (fix is AnalysisContextActionProvider.AnalysisCodeAction)
                    {
                        continue;
                    }
                    var escapedLabel = fix.Title.Replace("_", "__");
                    var label        = (mnemonic <= 10)
                                                ? "_" + (mnemonic++ % 10).ToString() + " " + escapedLabel
                                                        : "  " + escapedLabel;
                    infos.Add(label, fix);
                }
            }

            foreach (var result in results)
            {
                bool firstAction = true;
                foreach (var action in GetActions(doc, result))
                {
                    if (firstAction)
                    {
                        //FIXME: make this header item insensitive but not greyed out
                        infos.Add(new CommandInfo(result.Message.Replace("_", "__"), false, false)
                        {
                            Icon = GetIcon(result.Level)
                        }, null);
                        firstAction = false;
                    }
                    var escapedLabel = action.Label.Replace("_", "__");
                    var label        = (mnemonic <= 10)
                                                ? "_" + (mnemonic++ % 10).ToString() + " " + escapedLabel
                                                : "  " + escapedLabel;
                    infos.Add(label, action);
                }
                if (result.HasOptionsDialog)
                {
                    var declSet = new CommandInfoSet();
                    declSet.Text = GettextCatalog.GetString("_Options for \"{0}\"", result.OptionsTitle);

                    bool hasBatchFix = false;
                    foreach (var fix in result.Fixes.OfType <IAnalysisFixAction> ().Where(f => f.SupportsBatchFix))
                    {
                        hasBatchFix = true;
                        var title = string.Format(GettextCatalog.GetString("Apply in file: {0}"), fix.Label);
                        declSet.CommandInfos.Add(title, new System.Action(fix.BatchFix));
                    }
                    if (hasBatchFix)
                    {
                        declSet.CommandInfos.AddSeparator();
                    }

                    var ir = result as InspectorResults;
                    if (ir != null)
                    {
                        var inspector = ir.Inspector;

                        if (inspector.CanSuppressWithAttribute)
                        {
                            declSet.CommandInfos.Add(GettextCatalog.GetString("_Suppress with attribute"), new System.Action(delegate {
                                inspector.SuppressWithAttribute(doc, ir.Region);
                            }));
                        }

                        if (inspector.CanDisableWithPragma)
                        {
                            declSet.CommandInfos.Add(GettextCatalog.GetString("_Suppress with #pragma"), new System.Action(delegate {
                                inspector.DisableWithPragma(doc, ir.Region);
                            }));
                        }

                        if (inspector.CanDisableOnce)
                        {
                            declSet.CommandInfos.Add(GettextCatalog.GetString("_Disable once with comment"), new System.Action(delegate {
                                inspector.DisableOnce(doc, ir.Region);
                            }));
                        }

                        if (inspector.CanDisableAndRestore)
                        {
                            declSet.CommandInfos.Add(GettextCatalog.GetString("Disable _and restore with comments"), new System.Action(delegate {
                                inspector.DisableAndRestore(doc, ir.Region);
                            }));
                        }
                    }

                    declSet.CommandInfos.Add(GettextCatalog.GetString("_Configure inspection"), result);

                    infos.Add(declSet);
                }
            }
        }
Пример #25
0
        public void OnOpenWithUpdate(CommandArrayInfo info)
        {
            var pf = (SolutionFolderFileNode)CurrentNode.DataItem;

            ProjectFileNodeCommandHandler.PopulateOpenWithViewers(info, null, pf.FileName);
        }
Пример #26
0
        public static void PopulateInfos(CommandArrayInfo infos, Document doc, IEnumerable <FixableResult> results)
        {
            //FIXME: ellipsize long messages
            int mnemonic = 1;

            foreach (var result in results)
            {
                bool firstAction = true;
                foreach (var action in GetActions(doc, result))
                {
                    if (firstAction)
                    {
                        //FIXME: make this header item insensitive but not greyed out
                        infos.Add(new CommandInfo(result.Message.Replace("_", "__"), false, false)
                        {
                            Icon = GetIcon(result.Level)
                        }, null);
                        firstAction = false;
                    }
                    var escapedLabel = action.Label.Replace("_", "__");
                    var label        = (mnemonic <= 10)
                                                ? "_" + (mnemonic++ % 10).ToString() + " " + escapedLabel
                                                : "  " + escapedLabel;
                    infos.Add(label, action);
                }
                if (result.HasOptionsDialog)
                {
                    var declSet = new CommandInfoSet();
                    declSet.Text = GettextCatalog.GetString("_Options for \"{0}\"", result.OptionsTitle);

                    var ir = result as InspectorResults;
                    if (ir != null)
                    {
                        var inspector = ir.Inspector;

                        if (inspector.CanSuppressWithAttribute)
                        {
                            declSet.CommandInfos.Add(GettextCatalog.GetString("_Suppress with attribute"), new System.Action(delegate {
                                inspector.SuppressWithAttribute(doc, ir.Region);
                            }));
                        }

                        if (inspector.CanDisableWithPragma)
                        {
                            declSet.CommandInfos.Add(GettextCatalog.GetString("_Suppress with #pragma"), new System.Action(delegate {
                                inspector.DisableWithPragma(doc, ir.Region);
                            }));
                        }

                        if (inspector.CanDisableOnce)
                        {
                            declSet.CommandInfos.Add(GettextCatalog.GetString("_Disable once with comment"), new System.Action(delegate {
                                inspector.DisableOnce(doc, ir.Region);
                            }));
                        }

                        if (inspector.CanDisableAndRestore)
                        {
                            declSet.CommandInfos.Add(GettextCatalog.GetString("Disable _and restore with comments"), new System.Action(delegate {
                                inspector.DisableAndRestore(doc, ir.Region);
                            }));
                        }
                    }

                    declSet.CommandInfos.Add(GettextCatalog.GetString("_Configure inspection severity"), result);

                    infos.Add(declSet);
                }
            }
        }
Пример #27
0
        protected override void Update(CommandArrayInfo info)
        {
            string group;
            var    lastListGroup = new Dictionary <CommandArrayInfo, string>();
            var    descFormat    = GettextCatalog.GetString("Show {0}");

            foreach (Pad pad in IdeApp.Workbench.Pads.OrderBy(p => p.Group, StringComparer.InvariantCultureIgnoreCase))
            {
                CommandInfo ci = new CommandInfo(pad.Title);
                ci.Icon        = pad.Icon;
                ci.UseMarkup   = true;
                ci.Description = string.Format(descFormat, pad.Title);
                // We only want these commands enabled if the main window is visible
                ci.Enabled = IdeApp.Workbench.RootWindow.Visible;

                ActionCommand cmd = IdeApp.CommandService.GetActionCommand("Pad|" + pad.Id);
                if (cmd != null)
                {
                    ci.AccelKey = cmd.AccelKey;
                }

                CommandArrayInfo list = info;
                if (pad.Categories != null)
                {
                    for (int j = 0; j < pad.Categories.Length; j++)
                    {
                        bool found = false;
                        for (int k = list.Count - 1; k >= 0; k--)
                        {
                            if (list[k].Text == pad.Categories[j] && list[k] is CommandInfoSet)
                            {
                                list  = ((CommandInfoSet)list[k]).CommandInfos;
                                found = true;
                                break;
                            }
                        }
                        if (!found)
                        {
                            CommandInfoSet set = new CommandInfoSet();
                            set.Text        = pad.Categories[j];
                            set.Description = string.Format(descFormat, set.Text);
                            list.Add(set);
                            list = set.CommandInfos;
                        }
                    }
                }

                int atIndex = 0;
                for (int j = list.Count - 1; j >= 0; j--)
                {
                    if (!(list [j] is CommandInfoSet))
                    {
                        atIndex = j + 1;
                        break;
                    }
                }

                list.Insert(atIndex, ci, pad);
                lastListGroup.TryGetValue(list, out group);
                if (group != pad.Group)
                {
                    lastListGroup [list] = pad.Group;
                    if (atIndex > 0)
                    {
                        CommandInfo sep = new CommandInfo("-");
                        sep.IsArraySeparator = true;
                        list.Insert(atIndex, sep, null);
                    }
                }
            }
        }
Пример #28
0
        protected override void Update(CommandArrayInfo info)
        {
            if (caps.Update())
            {
                if (caps.resultResolutionAttempt != LooseResolution.NodeResolutionAttempt.RawSymbolLookup)
                {
                    var refactoringMenu = new CommandInfoSet {
                        Text = GettextCatalog.GetString("Refactoring")
                    };

                    if (caps.lastResults.Any(t => t is DSymbol && DRenameRefactoring.CanRenameNode((t as DSymbol).Definition)))
                    {
                        refactoringMenu.CommandInfos.Add(IdeApp.CommandService.GetCommandInfo(EditCommands.Rename), new Action(caps.RenameSymbol));
                    }

                    if (refactoringMenu.CommandInfos.Count > 0)
                    {
                        info.Add(refactoringMenu);
                    }

                    info.Add(IdeApp.CommandService.GetCommandInfo(RefactoryCommands.GotoDeclaration), new Action(caps.GotoDeclaration));
                    info.Add(IdeApp.CommandService.GetCommandInfo(RefactoryCommands.FindReferences), new Action(() => caps.FindReferences(false)));

                    if (caps.lastResults.Any(t => t is DSymbol && (t as DSymbol).Definition.Parent is DClassLike))
                    {
                        info.Add(IdeApp.CommandService.GetCommandInfo(RefactoryCommands.FindAllReferences), new Action(() => caps.FindReferences(true)));
                    }

                    if (caps.lastResults.Any(t => {
                        var ds = DResolver.StripMemberSymbols(t);
                        return(ds is ClassType || ds is InterfaceType);
                    }))
                    {
                        info.Add(IdeApp.CommandService.GetCommandInfo(RefactoryCommands.FindDerivedClasses), new Action(caps.FindDerivedClasses));
                    }
                }
                else
                {
                    var importSymbolMenu = new CommandInfoSet {
                        Text = GettextCatalog.GetString("Resolve")
                    };

                    foreach (var m in caps.GetImportableModulesForLastResults())
                    {
                        importSymbolMenu.CommandInfos.Add(new CommandInfo {
                            Text = "import " + AbstractNode.GetNodePath(m, true) + ";",
                            Icon = MonoDevelop.Ide.Gui.Stock.AddNamespace
                        }, new object[] { RefactoryCommands.ImportSymbol, m });
                    }

                    if (importSymbolMenu.CommandInfos.Count > 0)
                    {
                        importSymbolMenu.CommandInfos.AddSeparator();

                        var alreadyAddedItems = new List <DModule> ();
                        foreach (var t in caps.lastResults)
                        {
                            var n = DResolver.GetResultMember(t, true);
                            if (n == null)
                            {
                                continue;
                            }
                            var m = n.NodeRoot as DModule;
                            if (m != null && !alreadyAddedItems.Contains(m))
                            {
                                alreadyAddedItems.Add(m);

                                importSymbolMenu.CommandInfos.Add(new CommandInfo {
                                    Text = AbstractNode.GetNodePath(n, true)
                                }, new object[] { RefactoryCommands.QuickFix, n });
                            }
                        }


                        // To explicitly show the Ctrl+Alt+Space hint.
                        importSymbolMenu.CommandInfos.AddSeparator();
                        importSymbolMenu.CommandInfos.Add(IdeApp.CommandService.GetCommandInfo(RefactoryCommands.ImportSymbol), new Action(caps.TryImportMissingSymbol));

                        info.Add(importSymbolMenu);
                    }
                }
            }

            if (SortImportsCommandHandler.CanSortImports(caps.lastDoc))
            {
                info.Add(IdeApp.CommandService.GetCommandInfo(RefactoryCommands.SortImports), new Action(() => SortImportsCommandHandler.SortImports(caps.lastDoc)));
            }
        }
Пример #29
0
        public void OnOpenWithUpdate(CommandArrayInfo info)
        {
            var pf = (ProjectFile)CurrentNode.DataItem;

            PopulateOpenWithViewers(info, pf.Project, pf.FilePath);
        }
Пример #30
0
        protected override void Update(CommandArrayInfo ainfo)
        {
            var doc = IdeApp.Workbench.ActiveDocument;

            if (doc == null || doc.FileName == FilePath.Null || doc.ParsedDocument == null)
            {
                return;
            }
            var semanticModel = doc.ParsedDocument.GetAst <SemanticModel> ();

            if (semanticModel == null)
            {
                return;
            }
            var task = RefactoringSymbolInfo.GetSymbolInfoAsync(doc, doc.Editor);

            if (!task.Wait(2000))
            {
                return;
            }
            var  info  = task.Result;
            bool added = false;

            var ext = doc.GetContent <CodeActionEditorExtension> ();

            //if (ext != null) {
            //	var fixMenu = CreateFixMenu (doc.Editor, doc, semanticModel, ext.GetCurrentFixes ());
            //	if (fixMenu.CommandInfos.Count > 0) {
            //		ainfo.Add (fixMenu, null);
            //		added = true;
            //	}
            //}
            var ciset = new CommandInfoSet();

            ciset.Text = GettextCatalog.GetString("Refactor");

            bool canRename = RenameHandler.CanRename(info.Symbol ?? info.DeclaredSymbol);

            if (canRename)
            {
                ciset.CommandInfos.Add(IdeApp.CommandService.GetCommandInfo(MonoDevelop.Ide.Commands.EditCommands.Rename), new Action(async delegate {
                    await new MonoDevelop.Refactoring.Rename.RenameRefactoring().Rename(info.Symbol ?? info.DeclaredSymbol);
                }));
                added = true;
            }
            bool first = true;

            //if (ext != null) {
            //	foreach (var fix in ext.GetCurrentFixes ().CodeRefactoringActions) {
            //		if (added & first && ciset.CommandInfos.Count > 0)
            //			ciset.CommandInfos.AddSeparator ();
            //		var info2 = new CommandInfo (fix.CodeAction.Title);
            //		ciset.CommandInfos.Add (info2, new Action (async () => await new CodeActionEditorExtension.ContextActionRunner (fix.CodeAction, doc.Editor, doc).Run ()));
            //		added = true;
            //		first = false;
            //	}
            //}

            if (ciset.CommandInfos.Count > 0)
            {
                ainfo.Add(ciset, null);
                added = true;
            }

            var gotoDeclarationSymbol = info.Symbol;

            if (gotoDeclarationSymbol == null && info.DeclaredSymbol != null && info.DeclaredSymbol.Locations.Length > 1)
            {
                gotoDeclarationSymbol = info.DeclaredSymbol;
            }
            if (IdeApp.ProjectOperations.CanJumpToDeclaration(gotoDeclarationSymbol) || gotoDeclarationSymbol == null && IdeApp.ProjectOperations.CanJumpToDeclaration(info.CandidateSymbols.FirstOrDefault()))
            {
                var type = (gotoDeclarationSymbol ?? info.CandidateSymbols.FirstOrDefault()) as INamedTypeSymbol;
                if (type != null && type.Locations.Length > 1)
                {
                    var declSet = new CommandInfoSet();
                    declSet.Text = GettextCatalog.GetString("_Go to Declaration");
                    foreach (var part in type.Locations)
                    {
                        var loc = part.GetLineSpan();
                        declSet.CommandInfos.Add(string.Format(GettextCatalog.GetString("{0}, Line {1}"), FormatFileName(part.SourceTree.FilePath), loc.StartLinePosition.Line + 1), new Action(() => IdeApp.ProjectOperations.JumpTo(type, part, doc.Project)));
                    }
                    ainfo.Add(declSet);
                }
                else
                {
                    ainfo.Add(IdeApp.CommandService.GetCommandInfo(RefactoryCommands.GotoDeclaration), new Action(() => GotoDeclarationHandler.Run(doc)));
                }
                added = true;
            }


            if (info.DeclaredSymbol != null && GotoBaseDeclarationHandler.CanGotoBase(info.DeclaredSymbol))
            {
                ainfo.Add(GotoBaseDeclarationHandler.GetDescription(info.DeclaredSymbol), new Action(() => GotoBaseDeclarationHandler.GotoBase(doc, info.DeclaredSymbol)));
                added = true;
            }

            var sym = info.Symbol ?? info.DeclaredSymbol;

            if (doc.HasProject && sym != null)
            {
                ainfo.Add(IdeApp.CommandService.GetCommandInfo(RefactoryCommands.FindReferences), new System.Action(() => {
                    if (sym.Kind == SymbolKind.Local || sym.Kind == SymbolKind.Parameter || sym.Kind == SymbolKind.TypeParameter)
                    {
                        FindReferencesHandler.FindRefs(sym);
                    }
                    else
                    {
                        RefactoringService.FindReferencesAsync(FindReferencesHandler.FilterSymbolForFindReferences(sym).GetDocumentationCommentId());
                    }
                }));
                try {
                    if (Microsoft.CodeAnalysis.FindSymbols.SymbolFinder.FindSimilarSymbols(sym, semanticModel.Compilation).Count() > 1)
                    {
                        ainfo.Add(IdeApp.CommandService.GetCommandInfo(RefactoryCommands.FindAllReferences), new System.Action(() => RefactoringService.FindAllReferencesAsync(FindReferencesHandler.FilterSymbolForFindReferences(sym).GetDocumentationCommentId())));
                    }
                } catch (Exception) {
                    // silently ignore roslyn bug.
                }
            }
            added = true;
        }