コード例 #1
0
        public ChangeSetView()
        {
            ShadowType = Gtk.ShadowType.In;
            filelist   = new FileTreeView();
            filelist.Selection.Mode = SelectionMode.Multiple;

            Add(filelist);
            HscrollbarPolicy            = PolicyType.Automatic;
            VscrollbarPolicy            = PolicyType.Automatic;
            filelist.RowActivated      += OnRowActivated;
            filelist.DiffLineActivated += OnDiffLineActivated;

            CellRendererToggle cellToggle = new CellRendererToggle();
//			cellToggle.Toggled += new ToggledHandler(OnCommitToggledHandler);
            var crc = new CellRendererImage();

            crc.StockId       = "vc-comment";
            colCommit         = new TreeViewColumn();
            colCommit.Spacing = 2;
            colCommit.Widget  = new Xwt.ImageView(Xwt.Drawing.Image.FromResource("commit-16.png")).ToGtkWidget();
            colCommit.Widget.Show();
            colCommit.PackStart(cellToggle, false);
            colCommit.PackStart(crc, false);
            colCommit.AddAttribute(cellToggle, "active", ColCommit);
            colCommit.AddAttribute(cellToggle, "visible", ColShowToggle);
            colCommit.AddAttribute(crc, "visible", ColShowComment);
            colCommit.Visible = false;

            CellRendererText crt     = new CellRendererText();
            var            crp       = new CellRendererImage();
            TreeViewColumn colStatus = new TreeViewColumn();

            colStatus.Title = GettextCatalog.GetString("Status");
            colStatus.PackStart(crp, false);
            colStatus.PackStart(crt, true);
            colStatus.AddAttribute(crp, "image", ColIcon);
            colStatus.AddAttribute(crp, "visible", ColShowStatus);
            colStatus.AddAttribute(crt, "text", ColStatus);
            colStatus.AddAttribute(crt, "foreground", ColStatusColor);

            TreeViewColumn colFile = new TreeViewColumn();

            colFile.Title   = GettextCatalog.GetString("File");
            colFile.Spacing = 2;
            crp             = new CellRendererImage();
            diffRenderer    = new CellRendererDiff();
            colFile.PackStart(crp, false);
            colFile.PackStart(diffRenderer, true);
            colFile.AddAttribute(crp, "image", ColIconFile);
            colFile.AddAttribute(crp, "visible", ColShowStatus);
            colFile.SetCellDataFunc(diffRenderer, new TreeCellDataFunc(SetDiffCellData));

            filelist.AppendColumn(colStatus);
            filelist.AppendColumn(colCommit);
            filelist.AppendColumn(colFile);

            filestore               = new TreeStore(typeof(Xwt.Drawing.Image), typeof(string), typeof(string[]), typeof(bool), typeof(bool), typeof(string), typeof(bool), typeof(bool), typeof(Xwt.Drawing.Image), typeof(bool), typeof(string));
            filelist.Model          = filestore;
            filelist.TestExpandRow += new Gtk.TestExpandRowHandler(OnTestExpandRow);

            ShowAll();

            filelist.Selection.Changed += new EventHandler(OnCursorChanged);

            filelist.HeadersClickable = true;
            filestore.SetSortFunc(0, CompareNodes);
            colStatus.SortColumnId = 0;
            filestore.SetSortFunc(1, CompareNodes);
            colCommit.SortColumnId = 1;
            filestore.SetSortFunc(2, CompareNodes);
            colFile.SortColumnId = 2;

            filestore.SetSortColumnId(2, Gtk.SortType.Ascending);
        }
コード例 #2
0
		protected override void Run ()
		{
			if (MessageService.Confirm (GettextCatalog.GetString ("Do you want to detach from the process being debugged?"), new AlertButton (GettextCatalog.GetString ("Detach")), true)) {
				DebuggingService.DebuggerSession.Detach ();
			}
		}
コード例 #3
0
        private EncapsulateFieldDialog(MonoDevelop.Ide.Gui.Document editor, IType declaringType, IField field)
        {
            this.editor        = editor;
            this.declaringType = declaringType;
            this.Build();

            Title = GettextCatalog.GetString("Encapsulate Fields");
            buttonOk.Sensitive = true;
            store           = new ListStore(typeof(bool), typeof(string), typeof(string), typeof(string), typeof(bool), typeof(IField));
            visibilityStore = new ListStore(typeof(string));

            // Column #1
            CellRendererToggle cbRenderer = new CellRendererToggle();

            cbRenderer.Activatable = true;
            cbRenderer.Toggled    += OnSelectedToggled;
            TreeViewColumn cbCol = new TreeViewColumn();

            cbCol.Title = "";
            cbCol.PackStart(cbRenderer, false);
            cbCol.AddAttribute(cbRenderer, "active", colCheckedIndex);
            treeview.AppendColumn(cbCol);

            // Column #2
            CellRendererText fieldRenderer = new CellRendererText();

            fieldRenderer.Weight = (int)Pango.Weight.Bold;
            TreeViewColumn fieldCol = new TreeViewColumn();

            fieldCol.Title  = GettextCatalog.GetString("Field");
            fieldCol.Expand = true;
            fieldCol.PackStart(fieldRenderer, true);
            fieldCol.AddAttribute(fieldRenderer, "text", colFieldNameIndex);
            treeview.AppendColumn(fieldCol);

            // Column #3
            CellRendererText propertyRenderer = new CellRendererText();

            propertyRenderer.Editable = true;
            propertyRenderer.Edited  += new EditedHandler(OnPropertyEdited);
            TreeViewColumn propertyCol = new TreeViewColumn();

            propertyCol.Title  = GettextCatalog.GetString("Property");
            propertyCol.Expand = true;
            propertyCol.PackStart(propertyRenderer, true);
            propertyCol.AddAttribute(propertyRenderer, "text", colPropertyNameIndex);
            propertyCol.SetCellDataFunc(propertyRenderer, new TreeCellDataFunc(RenderPropertyName));
            treeview.AppendColumn(propertyCol);

            // Column #4
            CellRendererCombo visiComboRenderer = new CellRendererCombo();

            visiComboRenderer.Model      = visibilityStore;
            visiComboRenderer.Editable   = true;
            visiComboRenderer.Edited    += new EditedHandler(OnVisibilityEdited);
            visiComboRenderer.HasEntry   = false;
            visiComboRenderer.TextColumn = 0;

            TreeViewColumn visiCol = new TreeViewColumn();

            visiCol.Title = GettextCatalog.GetString("Visibility");
            visiCol.PackStart(visiComboRenderer, false);
            visiCol.AddAttribute(visiComboRenderer, "text", colVisibilityIndex);
            treeview.AppendColumn(visiCol);

            // Column #5
            CellRendererToggle roRenderer = new CellRendererToggle();

            roRenderer.Activatable = true;
            roRenderer.Xalign      = 0.0f;
            roRenderer.Toggled    += new ToggledHandler(OnReadOnlyToggled);
            TreeViewColumn roCol = new TreeViewColumn();

            roCol.Title = GettextCatalog.GetString("Read only");
            roCol.PackStart(roRenderer, false);
            roCol.AddAttribute(roRenderer, "active", colReadOnlyIndex);
            treeview.AppendColumn(roCol);

            visibilityStore.AppendValues("Public");
            visibilityStore.AppendValues("Private");
            visibilityStore.AppendValues("Protected");
            visibilityStore.AppendValues("Internal");

            treeview.Model = store;

            foreach (IField ifield in declaringType.Fields)
            {
                bool   enabled      = field != null && (field.Name == ifield.Name);
                string propertyName = GeneratePropertyName(ifield.Name);
                store.AppendValues(enabled, ifield.Name, propertyName,
                                   "Public", ifield.IsReadonly || ifield.IsLiteral, ifield);

                if (enabled)
                {
                    CheckAndUpdateConflictMessage(propertyName, false);
                }
            }

            store.SetSortColumnId(colFieldNameIndex, SortType.Ascending);
            buttonSelectAll.Clicked   += OnSelectAllClicked;
            buttonUnselectAll.Clicked += OnUnselectAllClicked;
            buttonOk.Clicked          += OnOKClicked;
            buttonCancel.Clicked      += OnCancelClicked;

            UpdateOKButton();
        }
コード例 #4
0
 public FileSearchCategory() : base(GettextCatalog.GetString("Files"))
 {
 }
コード例 #5
0
        public override async Task <Annotation []> GetAnnotationsAsync(FilePath repositoryPath, Revision since, CancellationToken cancellationToken)
        {
            SvnRevision       sinceRev    = since != null ? (SvnRevision)since : null;
            List <Annotation> annotations = new List <Annotation> (Svn.GetAnnotations(this, repositoryPath, SvnRevision.First, sinceRev ?? SvnRevision.Base));
            Annotation        nextRev     = new Annotation(null, GettextCatalog.GetString("<uncommitted>"), DateTime.MinValue, null, GettextCatalog.GetString("working copy"));
            var baseDocument    = Mono.TextEditor.TextDocument.CreateImmutableDocument(await GetBaseTextAsync(repositoryPath, cancellationToken).ConfigureAwait(false));
            var workingDocument = Mono.TextEditor.TextDocument.CreateImmutableDocument(File.ReadAllText(repositoryPath));

            // "SubversionException: blame of the WORKING revision is not supported"
            if (sinceRev == null)
            {
                foreach (var hunk in baseDocument.Diff(workingDocument, includeEol: false))
                {
                    annotations.RemoveRange(hunk.RemoveStart - 1, hunk.Removed);
                    for (int i = 0; i < hunk.Inserted; ++i)
                    {
                        if (hunk.InsertStart + i >= annotations.Count)
                        {
                            annotations.Add(nextRev);
                        }
                        else
                        {
                            annotations.Insert(hunk.InsertStart - 1, nextRev);
                        }
                    }
                }
            }

            return(annotations.ToArray());
        }
コード例 #6
0
        public DocumentSwitcher(Gtk.Window parent, bool startWithNext) : base(Gtk.WindowType.Toplevel)
        {
            IdeApp.CommandService.IsEnabled = false;
            this.documents = new List <MonoDevelop.Ide.Gui.Document> (
                IdeApp.Workbench.Documents.OrderByDescending(d => d.LastTimeActive));
            this.TransientFor = parent;

            this.Decorated         = false;
            this.DestroyWithParent = true;
            this.CanDefault        = true;

            this.Modal          = true;
            this.WindowPosition = Gtk.WindowPosition.CenterOnParent;
            this.TypeHint       = WindowTypeHint.Dialog;

            this.ModifyBg(StateType.Normal, this.Style.Base(StateType.Normal));

            VBox vBox = new VBox();
            HBox hBox = new HBox();

            var hBox2 = new HBox();

            hBox2.PackStart(hBox, false, false, 8);

            hBox.PackStart(imageTitle, true, false, 2);
            labelTitle.Xalign        = 0;
            labelTitle.HeightRequest = 24;
            hBox.PackStart(labelTitle, true, true, 2);
            vBox.PackStart(hBox2, false, false, 6);

            labelType.Xalign        = 0;
            labelType.HeightRequest = 16;
            hBox = new HBox();
            hBox.PackStart(labelType, false, false, 8);
            vBox.PackStart(hBox, false, false, 2);

            hBox = new HBox();
            hBox.PackStart(documentList, true, true, 1);
            vBox.PackStart(hBox, false, false, 0);

            labelFileName.Xalign    = 0;
            labelFileName.Ellipsize = Pango.EllipsizeMode.Start;
            hBox = new HBox();
            hBox.PackStart(labelFileName, true, true, 8);
            vBox.PackEnd(hBox, false, false, 6);

            Add(vBox);

            var padCategory = new  DocumentList.Category(GettextCatalog.GetString("Pads"));

            DocumentList.Item activeItem = null;

            foreach (Pad pad in IdeApp.Workbench.Pads)
            {
                if (!pad.Visible)
                {
                    continue;
                }
                var item = new DocumentList.Item()
                {
                    Icon  = ImageService.GetPixbuf(pad.Icon.Name ?? MonoDevelop.Ide.Gui.Stock.MiscFiles, IconSize.Menu),
                    Title = pad.Title,
                    Tag   = pad
                };
                if (pad.Window.Content.Control.HasFocus)
                {
                    activeItem = item;
                }
                padCategory.AddItem(item);
            }
            documentList.AddCategory(padCategory);

            var documentCategory = new  DocumentList.Category(GettextCatalog.GetString("Documents"));

            foreach (var doc in documents)
            {
                var item = new DocumentList.Item()
                {
                    Icon        = GetIconForDocument(doc, IconSize.Menu),
                    Title       = System.IO.Path.GetFileName(doc.Name),
                    ListTitle   = doc.Window.Title,
                    Description = doc.Window.DocumentType,
                    Path        = doc.Name,
                    Tag         = doc
                };
                if (doc.Window.ActiveViewContent.Control.HasFocus)
                {
                    activeItem = item;
                }
                documentCategory.AddItem(item);
            }
            documentList.AddCategory(documentCategory);

            documentList.ActiveItemChanged += delegate {
                if (documentList.ActiveItem == null)
                {
                    labelFileName.Text = labelType.Text = labelTitle.Text = "";
                    return;
                }
                imageTitle.Pixbuf  = documentList.ActiveItem.Icon;
                labelFileName.Text = documentList.ActiveItem.Path;
                labelType.Markup   = "<span size=\"small\">" + documentList.ActiveItem.Description + "</span>";
                labelTitle.Markup  = "<span size=\"xx-large\" weight=\"bold\">" + documentList.ActiveItem.Title + "</span>";
            };

            if (activeItem == null)
            {
                if (documentCategory.Items.Count > 0)
                {
                    activeItem = documentCategory.Items [0];
                }
                else if (padCategory.Items.Count > 0)
                {
                    activeItem = padCategory.Items [0];
                }
                else
                {
                    DestroyWindow();
                    return;
                }
            }

            documentList.ActiveItem = activeItem;
            documentList.NextItem(true);
            documentList.RequestClose += delegate(object sender, DocumentList.RequestActionEventArgs e) {
                try {
                    if (e.SelectItem)
                    {
                        if (documentList.ActiveItem.Tag is Pad)
                        {
                            ((Pad)documentList.ActiveItem.Tag).BringToFront(true);
                        }
                        else
                        {
                            ((MonoDevelop.Ide.Gui.Document)documentList.ActiveItem.Tag).Select();
                        }
                    }
                } finally {
                    DestroyWindow();
                }
            };

            this.ShowAll();
            documentList.GrabFocus();
            this.GrabDefault();
        }
コード例 #7
0
ファイル: Document.cs プロジェクト: czf/monodevelop
        public void SaveAs(string filename)
        {
            if (Window.ViewContent.IsViewOnly || !Window.ViewContent.IsFile)
            {
                return;
            }


            Encoding encoding = null;

            IEncodedTextContent tbuffer = GetContent <IEncodedTextContent> ();

            if (tbuffer != null)
            {
                encoding = tbuffer.SourceEncoding;
                if (encoding == null)
                {
                    encoding = Encoding.Default;
                }
            }

            if (filename == null)
            {
                var dlg = new OpenFileDialog(GettextCatalog.GetString("Save as..."), FileChooserAction.Save)
                {
                    TransientFor         = IdeApp.Workbench.RootWindow,
                    Encoding             = encoding,
                    ShowEncodingSelector = (tbuffer != null),
                };
                if (Window.ViewContent.IsUntitled)
                {
                    dlg.InitialFileName = Window.ViewContent.UntitledName;
                }
                else
                {
                    dlg.CurrentFolder   = Path.GetDirectoryName(Window.ViewContent.ContentName);
                    dlg.InitialFileName = Path.GetFileName(Window.ViewContent.ContentName);
                }

                if (!dlg.Run())
                {
                    return;
                }

                filename = dlg.SelectedFile;
                encoding = dlg.Encoding;
            }

            if (!FileService.IsValidPath(filename))
            {
                MessageService.ShowMessage(GettextCatalog.GetString("File name {0} is invalid", filename));
                return;
            }
            // detect preexisting file
            if (File.Exists(filename))
            {
                if (!MessageService.Confirm(GettextCatalog.GetString("File {0} already exists. Overwrite?", filename), AlertButton.OverwriteFile))
                {
                    return;
                }
            }

            // save backup first
            if ((bool)PropertyService.Get("SharpDevelop.CreateBackupCopy", false))
            {
                if (tbuffer != null && encoding != null)
                {
                    tbuffer.Save(filename + "~", encoding);
                }
                else
                {
                    Window.ViewContent.Save(filename + "~");
                }
            }
            TypeSystemService.RemoveSkippedfile(FileName);
            // do actual save
            if (tbuffer != null && encoding != null)
            {
                tbuffer.Save(filename, encoding);
            }
            else
            {
                Window.ViewContent.Save(filename);
            }

            FileService.NotifyFileChanged(filename);
            DesktopService.RecentFiles.AddFile(filename, (Project)null);

            OnSaved(EventArgs.Empty);
            UpdateParseDocument();
        }
コード例 #8
0
        void Update()
        {
            if (DocumentContext == null)
            {
                return;
            }
            var parsedDocument = DocumentContext.ParsedDocument;

            if (parsedDocument == null)
            {
                return;
            }
            var caretOffset = Editor.CaretOffset;
            var model       = parsedDocument.GetAst <SemanticModel>();

            if (model == null)
            {
                return;
            }
            CancelUpdatePath();
            var cancellationToken = src.Token;

            amb = new AstAmbience(TypeSystemService.Workspace.Options);
            var loc = Editor.CaretLocation;

            Task.Run(async delegate {
                var unit = model.SyntaxTree;
                SyntaxNode root;
                SyntaxNode node;
                try {
                    root = await unit.GetRootAsync(cancellationToken).ConfigureAwait(false);
                    if (root.FullSpan.Length <= caretOffset)
                    {
                        return;
                    }
                    node = root.FindNode(TextSpan.FromBounds(caretOffset, caretOffset));
                    if (node.SpanStart != caretOffset)
                    {
                        node = root.SyntaxTree.FindTokenOnLeftOfPosition(caretOffset, cancellationToken).Parent;
                    }
                } catch (Exception ex) {
                    Console.WriteLine(ex);
                    return;
                }

                var curMember = node != null ? node.AncestorsAndSelf().FirstOrDefault(m => m is VariableDeclaratorSyntax && m.Parent != null && !(m.Parent.Parent is LocalDeclarationStatementSyntax) || (m is MemberDeclarationSyntax && !(m is NamespaceDeclarationSyntax))) : null;
                var curType   = node != null ? node.AncestorsAndSelf().FirstOrDefault(IsType) : null;

                var curProject = ownerProjects != null && ownerProjects.Count > 1 ? DocumentContext.Project : null;

                if (curType == curMember || curType is DelegateDeclarationSyntax)
                {
                    curMember = null;
                }
                if (isPathSet && curType == lastType && curMember == lastMember && curProject == lastProject)
                {
                    return;
                }
                var curTypeMakeup   = GetEntityMarkup(curType);
                var curMemberMarkup = GetEntityMarkup(curMember);
                if (isPathSet && curType != null && lastType != null && curTypeMakeup == lastTypeMarkup &&
                    curMember != null && lastMember != null && curMemberMarkup == lastMemberMarkup && curProject == lastProject)
                {
                    return;
                }


                var result = new List <PathEntry>();

                if (curProject != null)
                {
                    // Current project if there is more than one
                    result.Add(new PathEntry(ImageService.GetIcon(curProject.StockIcon, Gtk.IconSize.Menu), GLib.Markup.EscapeText(curProject.Name))
                    {
                        Tag = curProject
                    });
                }

                if (curType == null)
                {
                    if (CurrentPath != null && CurrentPath.Length == 1 && CurrentPath [0]?.Tag is CSharpSyntaxTree)
                    {
                        return;
                    }
                    if (CurrentPath != null && CurrentPath.Length == 2 && CurrentPath [1]?.Tag is CSharpSyntaxTree)
                    {
                        return;
                    }
                    var prevPath = CurrentPath;
                    result.Add(new PathEntry(GettextCatalog.GetString("No selection"))
                    {
                        Tag = unit
                    });
                    Gtk.Application.Invoke(delegate {
                        if (cancellationToken.IsCancellationRequested)
                        {
                            return;
                        }

                        CurrentPath    = result.ToArray();
                        lastType       = curType;
                        lastTypeMarkup = curTypeMakeup;

                        lastMember       = curMember;
                        lastMemberMarkup = curMemberMarkup;

                        lastProject = curProject;
                        OnPathChanged(new DocumentPathChangedEventArgs(prevPath));
                    });
                    return;
                }
                var regionEntry = await GetRegionEntry(DocumentContext.ParsedDocument, loc).ConfigureAwait(false);

                Gtk.Application.Invoke(delegate {
                    if (curType != null)
                    {
                        var type = curType;
                        var pos  = result.Count;
                        while (type != null)
                        {
                            if (!(type is BaseTypeDeclarationSyntax))
                            {
                                break;
                            }
                            var tag = (object)type.Ancestors().FirstOrDefault(IsType) ?? unit;
                            result.Insert(pos, new PathEntry(ImageService.GetIcon(type.GetStockIcon(), Gtk.IconSize.Menu), GetEntityMarkup(type))
                            {
                                Tag = tag
                            });
                            type = type.Parent;
                        }
                    }
                    if (curMember != null)
                    {
                        result.Add(new PathEntry(ImageService.GetIcon(curMember.GetStockIcon(), Gtk.IconSize.Menu), curMemberMarkup)
                        {
                            Tag = curMember
                        });
                        if (curMember.Kind() == SyntaxKind.GetAccessorDeclaration ||
                            curMember.Kind() == SyntaxKind.SetAccessorDeclaration ||
                            curMember.Kind() == SyntaxKind.AddAccessorDeclaration ||
                            curMember.Kind() == SyntaxKind.RemoveAccessorDeclaration)
                        {
                            var parent = curMember.Parent;
                            if (parent != null)
                            {
                                result.Insert(result.Count - 1, new PathEntry(ImageService.GetIcon(parent.GetStockIcon(), Gtk.IconSize.Menu), GetEntityMarkup(parent))
                                {
                                    Tag = parent
                                });
                            }
                        }
                    }

                    if (regionEntry != null)
                    {
                        result.Add(regionEntry);
                    }

                    PathEntry noSelection = null;
                    if (curType == null)
                    {
                        noSelection = new PathEntry(GettextCatalog.GetString("No selection"))
                        {
                            Tag = unit
                        };
                    }
                    else if (curMember == null && !(curType is DelegateDeclarationSyntax))
                    {
                        noSelection = new PathEntry(GettextCatalog.GetString("No selection"))
                        {
                            Tag = curType
                        };
                    }

                    if (noSelection != null)
                    {
                        result.Add(noSelection);
                    }
                    var prev = CurrentPath;
                    if (prev != null && prev.Length == result.Count)
                    {
                        bool equals = true;
                        for (int i = 0; i < prev.Length; i++)
                        {
                            if (prev [i].Markup != result [i].Markup)
                            {
                                equals = false;
                                break;
                            }
                        }
                        if (equals)
                        {
                            return;
                        }
                    }
                    if (cancellationToken.IsCancellationRequested)
                    {
                        return;
                    }
                    CurrentPath    = result.ToArray();
                    lastType       = curType;
                    lastTypeMarkup = curTypeMakeup;

                    lastMember       = curMember;
                    lastMemberMarkup = curMemberMarkup;

                    lastProject = curProject;

                    OnPathChanged(new DocumentPathChangedEventArgs(prev));
                });
            });
        }
コード例 #9
0
ファイル: TranslationProject.cs プロジェクト: wjohnke/CSS18
        public void UpdateTranslations(ProgressMonitor monitor, bool sort, params Translation[] translations)
        {
            monitor.BeginTask(null, Translations.Count + 1);

            try {
                List <Project> projects = new List <Project> ();
                foreach (Project p in ParentSolution.GetAllProjects())
                {
                    if (IsIncluded(p))
                    {
                        projects.Add(p);
                    }
                }
                monitor.BeginTask(GettextCatalog.GetString("Updating message catalog"), projects.Count);
                CreateDefaultCatalog(monitor);
                monitor.Log.WriteLine(GettextCatalog.GetString("Done"));
            } finally {
                monitor.EndTask();
                monitor.Step(1);
            }
            if (monitor.CancellationToken.IsCancellationRequested)
            {
                monitor.Log.WriteLine(GettextCatalog.GetString("Operation cancelled."));
                return;
            }

            Dictionary <string, bool> isIncluded = new Dictionary <string, bool> ();

            foreach (Translation translation in translations)
            {
                isIncluded[translation.IsoCode] = true;
            }
            foreach (Translation translation in this.Translations)
            {
                if (!isIncluded.ContainsKey(translation.IsoCode))
                {
                    continue;
                }
                string poFileName = translation.PoFile;
                monitor.BeginTask(GettextCatalog.GetString("Updating {0}", translation.PoFile), 1);
                try {
                    var pb = new ProcessArgumentBuilder();
                    pb.Add("--update");
                    pb.AddQuoted(poFileName);
                    pb.Add("--verbose");
                    if (sort)
                    {
                        pb.Add("--sort-output");
                    }
                    pb.AddQuoted(this.BaseDirectory.Combine("messages.po"));

                    var process = Runtime.ProcessService.StartProcess(Translation.GetTool("msgmerge"),
                                                                      pb.ToString(), this.BaseDirectory, monitor.Log, monitor.Log, null);
                    process.WaitForOutput();
                }
                catch (System.ComponentModel.Win32Exception) {
                    var msg = GettextCatalog.GetString("Did not find msgmerge. Please ensure that gettext tools are installed.");
                    monitor.ReportError(msg, null);
                }
                catch (Exception ex) {
                    monitor.ReportError(GettextCatalog.GetString("Could not update file {0}", translation.PoFile), ex);
                }
                finally {
                    monitor.EndTask();
                    monitor.Step(1);
                }
                if (monitor.CancellationToken.IsCancellationRequested)
                {
                    monitor.Log.WriteLine(GettextCatalog.GetString("Operation cancelled."));
                    return;
                }
            }
        }
コード例 #10
0
        public static ProjectDescriptor CreateProjectDescriptor(XmlElement xmlElement, FilePath baseDirectory)
        {
            ProjectDescriptor projectDescriptor = new ProjectDescriptor();

            projectDescriptor.name            = xmlElement.GetAttribute("name");
            projectDescriptor.directory       = xmlElement.GetAttribute("directory");
            projectDescriptor.createCondition = xmlElement.GetAttribute("if");

            projectDescriptor.type = xmlElement.GetAttribute("type");

            if (xmlElement ["Files"] != null)
            {
                foreach (XmlNode xmlNode in xmlElement["Files"].ChildNodes)
                {
                    if (xmlNode is XmlElement)
                    {
                        projectDescriptor.files.Add(
                            FileDescriptionTemplate.CreateTemplate((XmlElement)xmlNode, baseDirectory));
                    }
                }
            }

            if (xmlElement ["Resources"] != null)
            {
                foreach (XmlNode xmlNode in xmlElement["Resources"].ChildNodes)
                {
                    if (xmlNode is XmlElement)
                    {
                        var fileTemplate = FileDescriptionTemplate.CreateTemplate((XmlElement)xmlNode, baseDirectory);
                        if (fileTemplate is SingleFileDescriptionTemplate)
                        {
                            projectDescriptor.resources.Add((SingleFileDescriptionTemplate)fileTemplate);
                        }
                        else
                        {
                            MessageService.ShowError(GettextCatalog.GetString("Only single-file templates allowed to generate resource files"));
                        }
                    }
                }
            }

            if (xmlElement ["References"] != null)
            {
                foreach (XmlNode xmlNode in xmlElement["References"].ChildNodes)
                {
                    projectDescriptor.references.Add(new ProjectReferenceDescription((XmlElement)xmlNode));
                }
            }

            projectDescriptor.projectOptions = xmlElement ["Options"];
            if (projectDescriptor.projectOptions == null)
            {
                projectDescriptor.projectOptions = xmlElement.OwnerDocument.CreateElement("Options");
            }

            if (xmlElement ["Packages"] != null)
            {
                foreach (XmlNode xmlNode in xmlElement["Packages"].ChildNodes)
                {
                    if (xmlNode is XmlElement)
                    {
                        var packageReference = ProjectTemplatePackageReference.Create((XmlElement)xmlNode);
                        projectDescriptor.packageReferences.Add(packageReference);
                    }
                }
            }

            return(projectDescriptor);
        }
コード例 #11
0
        internal static async void Execute()
        {
            var workspace = TypeSystemService.Workspace;

            try {
                using (var monitor = IdeApp.Workbench.ProgressMonitors.GetStatusProgressMonitor(GettextCatalog.GetString("Analyzing solution"), null, false, true, false, null, true)) {
                    CancellationToken token = monitor.CancellationToken;
                    var solution            = IdeApp.ProjectOperations.CurrentSelectedSolution;
                    var allDiagnostics      = await Task.Run(async delegate {
                        var diagnosticList = new List <Diagnostic> ();
                        monitor.BeginTask("Analyzing solution", workspace.CurrentSolution.Projects.Count());
                        foreach (var project in workspace.CurrentSolution.Projects)
                        {
                            var providers = await GetProviders(project);
                            monitor.BeginStep(GettextCatalog.GetString("Analyzing {0}", project.Name), 1);
                            diagnosticList.AddRange(await GetDiagnostics(project, providers, token));
                            monitor.EndStep();
                        }
                        monitor.EndTask();
                        return(diagnosticList);
                    }).ConfigureAwait(false);

                    await Runtime.RunInMainThread(delegate {
                        Report(monitor, allDiagnostics, solution);
                    }).ConfigureAwait(false);
                }
            } catch (OperationCanceledException) {
            } catch (AggregateException ae) {
                ae.Flatten().Handle(ix => ix is OperationCanceledException);
            } catch (Exception e) {
                LoggingService.LogError("Error while running diagnostics.", e);
            }
        }
コード例 #12
0
        public void InitializeItem(SolutionFolderItem policyParent, ProjectCreateInformation projectCreateInformation, string defaultLanguage, SolutionItem item)
        {
            MonoDevelop.Projects.Project project = item as MonoDevelop.Projects.Project;

            if (project == null)
            {
                MessageService.ShowError(GettextCatalog.GetString("Can't create project with type: {0}", type));
                return;
            }

            // Set the file before setting the name, to make sure the file extension is kept
            project.FileName = Path.Combine(projectCreateInformation.ProjectBasePath, projectCreateInformation.ProjectName);
            project.Name     = projectCreateInformation.ProjectName;

            var dnp = project as DotNetProject;

            if (dnp != null)
            {
                if (policyParent.ParentSolution != null && !policyParent.ParentSolution.FileFormat.SupportsFramework(dnp.TargetFramework))
                {
                    SetClosestSupportedTargetFramework(policyParent.ParentSolution.FileFormat, dnp);
                }
                var substitution = new string[, ] {
                    { "ProjectName", GetProjectNameForSubstitution(projectCreateInformation) }
                };
                foreach (var desc in references)
                {
                    if (!projectCreateInformation.ShouldCreate(desc.CreateCondition))
                    {
                        continue;
                    }
                    var pr = desc.Create();
                    if (pr.ReferenceType == ReferenceType.Project)
                    {
                        string referencedProjectName = ReplaceParameters(pr.Reference, substitution, projectCreateInformation);
                        var    parsedReference       = ProjectReference.RenameReference(pr, referencedProjectName);
                        dnp.References.Add(parsedReference);
                    }
                    else
                    {
                        dnp.References.Add(pr);
                    }
                }
            }

            foreach (SingleFileDescriptionTemplate resourceTemplate in resources)
            {
                try {
                    if (!projectCreateInformation.ShouldCreate(resourceTemplate.CreateCondition))
                    {
                        continue;
                    }
                    var projectFile = new ProjectFile(resourceTemplate.SaveFile(policyParent, project, defaultLanguage, project.BaseDirectory, null));
                    projectFile.BuildAction = BuildAction.EmbeddedResource;
                    project.Files.Add(projectFile);
                } catch (Exception ex) {
                    if (!IdeApp.IsInitialized)
                    {
                        throw;
                    }
                    MessageService.ShowError(GettextCatalog.GetString("File {0} could not be written.", resourceTemplate.Name), ex);
                }
            }

            foreach (FileDescriptionTemplate fileTemplate in files)
            {
                try {
                    if (!projectCreateInformation.ShouldCreate(fileTemplate.CreateCondition))
                    {
                        continue;
                    }
                    fileTemplate.SetProjectTagModel(projectCreateInformation.Parameters);
                    fileTemplate.AddToProject(policyParent, project, defaultLanguage, project.BaseDirectory, null);
                } catch (Exception ex) {
                    if (!IdeApp.IsInitialized)
                    {
                        throw;
                    }
                    MessageService.ShowError(GettextCatalog.GetString("File {0} could not be written.", fileTemplate.Name), ex);
                } finally {
                    fileTemplate.SetProjectTagModel(null);
                }
            }
        }
コード例 #13
0
        internal static async Task RunTest(UnitTest test, MonoDevelop.Projects.ExecutionContext context, bool buildOwnerObject, bool checkCurrentRunOperation, CancellationTokenSource cs)
        {
            string testName = test.FullName;

            if (buildOwnerObject)
            {
                IBuildTarget bt = test.OwnerObject as IBuildTarget;
                if (bt != null)
                {
                    if (!IdeApp.ProjectOperations.CurrentRunOperation.IsCompleted)
                    {
                        MonoDevelop.Ide.Commands.StopHandler.StopBuildOperations();
                        await IdeApp.ProjectOperations.CurrentRunOperation.Task;
                    }

                    var res = await IdeApp.ProjectOperations.Build(bt, cs.Token).Task;

                    if (res.HasErrors)
                    {
                        return;
                    }

                    await RefreshTests(cs.Token);

                    test = SearchTest(testName);
                    if (test != null)
                    {
                        await RunTest(test, context, false, checkCurrentRunOperation, cs);
                    }
                    return;
                }
            }

            if (checkCurrentRunOperation && !IdeApp.ProjectOperations.ConfirmExecutionOperation())
            {
                return;
            }

            Pad resultsPad = IdeApp.Workbench.GetPad <TestResultsPad>();

            if (resultsPad == null)
            {
                resultsPad = IdeApp.Workbench.ShowPad(new TestResultsPad(), "MonoDevelop.UnitTesting.TestResultsPad", GettextCatalog.GetString("Test results"), "Bottom", "md-solution");
            }

            // Make the pad sticky while the tests are runnig, so the results pad is always visible (even if minimized)
            // That's required since when running in debug mode, the layout is automatically switched to debug.

            resultsPad.Sticky = true;
            resultsPad.BringToFront();

            TestSession session = new TestSession(test, context, (TestResultsPad)resultsPad.Content, cs);

            OnTestSessionStarting(new TestSessionEventArgs {
                Session = session, Test = test
            });

            if (checkCurrentRunOperation)
            {
                IdeApp.ProjectOperations.AddRunOperation(session);
            }

            try {
                await session.Start();
            } finally {
                resultsPad.Sticky = false;
            }
        }
コード例 #14
0
        void CreatePageWidget(SectionPage page)
        {
            List <PanelInstance> boxPanels = new List <PanelInstance> ();
            List <PanelInstance> tabPanels = new List <PanelInstance> ();

            foreach (PanelInstance pi in page.Panels)
            {
                if (pi.Widget == null)
                {
                    pi.Widget = pi.Panel.CreatePanelWidget();
                    if (pi.Widget == null)
                    {
                        continue;
                    }

                    //HACK: work around bug 469427 - broken themes match on widget names
                    if (pi.Widget.Name.IndexOf("Panel") > 0)
                    {
                        pi.Widget.Name = pi.Widget.Name.Replace("Panel", "_");
                    }
                }
                else if (pi.Widget.Parent != null)
                {
                    ((Gtk.Container)pi.Widget.Parent).Remove(pi.Widget);
                }

                if (pi.Node.Grouping == PanelGrouping.Tab)
                {
                    tabPanels.Add(pi);
                }
                else
                {
                    boxPanels.Add(pi);
                }
            }

            // Try to fit panels with grouping=box or auto in the main page.
            // If they don't fit. Move auto panels to its own tab page.

            int  mainPageSize;
            bool fits;

            do
            {
                PanelInstance lastAuto = null;
                mainPageSize = 0;
                foreach (PanelInstance pi in boxPanels)
                {
                    if (pi.Node.Grouping == PanelGrouping.Auto)
                    {
                        lastAuto = pi;
                    }
                    // HACK: This we are parenting/unparenting the widget here as a workaround
                    // for a layout issue. To properly calculate the size of the widget, the widget
                    // needs to have the style that it will have when added to the window.
                    pi.Widget.Parent = this;
                    mainPageSize    += pi.Widget.SizeRequest().Height + 6;
                    pi.Widget.Unparent();
                }
                fits = mainPageSize <= pageFrame.Allocation.Height;
                if (!fits)
                {
                    if (lastAuto != null && boxPanels.Count > 1)
                    {
                        boxPanels.Remove(lastAuto);
                        tabPanels.Insert(0, lastAuto);
                    }
                    else
                    {
                        fits = true;
                    }
                }
            } while (!fits);

            Gtk.VBox box = new VBox(false, 12);
            box.Show();
            for (int n = 0; n < boxPanels.Count; n++)
            {
                if (n != 0)
                {
                    HSeparator sep = new HSeparator();
                    sep.Show();
                    box.PackStart(sep, false, false, 0);
                }
                PanelInstance pi = boxPanels [n];
                box.PackStart(pi.Widget, pi.Node.Fill, pi.Node.Fill, 0);
                pi.Widget.Show();
            }

            box.BorderWidth = 12;

            if (tabPanels.Count > 0)
            {
                /*				SquaredNotebook nb = new SquaredNotebook ();
                 * nb.Show ();
                 * nb.AddTab (box, GettextCatalog.GetString ("General"));
                 * foreach (PanelInstance pi in tabPanels) {
                 *      Gtk.Alignment a = new Alignment (0, 0, 1, 1);
                 *      a.BorderWidth = 9;
                 *      a.Show ();
                 *      a.Add (pi.Widget);
                 *      nb.AddTab (a, GettextCatalog.GetString (pi.Node.Label));
                 *      pi.Widget.Show ();
                 * }*/
                Gtk.Notebook nb = new Notebook();
                nb.Show();
                if (box.Children.Length > 0)
                {
                    Gtk.Label blab = new Gtk.Label(GettextCatalog.GetString("General"));
                    blab.Show();
                    box.BorderWidth = 9;
                    nb.InsertPage(box, blab, -1);
                }
                foreach (PanelInstance pi in tabPanels)
                {
                    Gtk.Label lab = new Gtk.Label(GettextCatalog.GetString(pi.Node.Label));
                    lab.Show();
                    Gtk.Alignment a = new Alignment(0, 0, 1, 1);
                    a.BorderWidth = 9;
                    a.Show();
                    a.Add(pi.Widget);
                    nb.InsertPage(a, lab, -1);
                    pi.Widget.Show();
                }
                page.Widget    = nb;
                nb.BorderWidth = 12;
            }
            else
            {
                page.Widget = box;
            }
        }
コード例 #15
0
ファイル: LogWidget.cs プロジェクト: thild/monodevelop
        void HandleTreeviewFilesTestExpandRow(object o, TestExpandRowArgs args)
        {
            string[] diff = changedpathstore.GetValue(args.Iter, colDiff) as string[];
            if (diff != null)
            {
                return;
            }
            TreeIter iter;

            if (changedpathstore.IterChildren(out iter, args.Iter))
            {
                string path = (string)changedpathstore.GetValue(args.Iter, colPath);
                changedpathstore.SetValue(iter, colDiff, new string[] { GettextCatalog.GetString("Loading data...") });
                var rev = SelectedRevision;
                ThreadPool.QueueUserWorkItem(delegate {
                    string text;
                    try {
                        text = info.Repository.GetTextAtRevision(path, rev);
                    } catch (Exception e) {
                        Application.Invoke(delegate {
                            LoggingService.LogError("Error while getting revision text", e);
                            MessageService.ShowError("Error while getting revision text.", "The file may not be part of the working copy.");
                        });
                        return;
                    }
                    Revision prevRev = null;
                    try {
                        prevRev = rev.GetPrevious();
                    } catch (Exception e) {
                        Application.Invoke(delegate {
                            LoggingService.LogError("Error while getting previous revision", e);
                            MessageService.ShowException(e, "Error while getting previous revision.");
                        });
                        return;
                    }
                    string[] lines;
                    var changedDocument = new Mono.TextEditor.Document(text);
                    if (prevRev == null)
                    {
                        lines = new string[changedDocument.LineCount];
                        for (int i = 0; i < changedDocument.LineCount; i++)
                        {
                            lines[i] = "+ " + changedDocument.GetLineText(i + 1).TrimEnd('\r', '\n');
                        }
                    }
                    else
                    {
                        string prevRevisionText;
                        try {
                            prevRevisionText = info.Repository.GetTextAtRevision(path, prevRev);
                        } catch (Exception e) {
                            Application.Invoke(delegate {
                                LoggingService.LogError("Error while getting revision text", e);
                                MessageService.ShowError("Error while getting revision text.", "The file may not be part of the working copy.");
                            });
                            return;
                        }

                        var originalDocument      = new Mono.TextEditor.Document(prevRevisionText);
                        originalDocument.FileName = "Revision " + prevRev.ToString();
                        changedDocument.FileName  = "Revision " + rev.ToString();
                        lines = Mono.TextEditor.Utils.Diff.GetDiffString(originalDocument, changedDocument).Split('\n');
                    }
                    Application.Invoke(delegate {
                        changedpathstore.SetValue(iter, colDiff, lines);
                    });
                });
            }
        }
コード例 #16
0
 protected override void Update(CommandInfo info)
 {
     info.Text = UIThreadMonitor.Instance.IsListening ? GettextCatalog.GetString("Stop monitoring UIThread hangs") : GettextCatalog.GetString("Start monitoring UIThread hangs");
     base.Update(info);
 }
コード例 #17
0
ファイル: LogWidget.cs プロジェクト: thild/monodevelop
        void TreeSelectionChanged(object o, EventArgs args)
        {
            Revision d = SelectedRevision;

            changedpathstore.Clear();
            textviewDetails.Buffer.Clear();

            if (d == null)
            {
                return;
            }
            Gtk.TreeIter selectIter = Gtk.TreeIter.Zero;
            bool         select     = false;

            foreach (RevisionPath rp in info.Repository.GetRevisionChanges(d))
            {
                Gdk.Pixbuf actionIcon;
                string     action = null;
                if (rp.Action == RevisionAction.Add)
                {
                    action     = GettextCatalog.GetString("Add");
                    actionIcon = ImageService.GetPixbuf(Gtk.Stock.Add, Gtk.IconSize.Menu);
                }
                else if (rp.Action == RevisionAction.Delete)
                {
                    action     = GettextCatalog.GetString("Delete");
                    actionIcon = ImageService.GetPixbuf(Gtk.Stock.Remove, Gtk.IconSize.Menu);
                }
                else if (rp.Action == RevisionAction.Modify)
                {
                    action     = GettextCatalog.GetString("Modify");
                    actionIcon = ImageService.GetPixbuf("gtk-edit", Gtk.IconSize.Menu);
                }
                else if (rp.Action == RevisionAction.Replace)
                {
                    action     = GettextCatalog.GetString("Replace");
                    actionIcon = ImageService.GetPixbuf("gtk-edit", Gtk.IconSize.Menu);
                }
                else
                {
                    action     = rp.ActionDescription;
                    actionIcon = ImageService.GetPixbuf(MonoDevelop.Ide.Gui.Stock.Empty, Gtk.IconSize.Menu);
                }
                Gdk.Pixbuf fileIcon = DesktopService.GetPixbufForFile(rp.Path, Gtk.IconSize.Menu);
                var        iter     = changedpathstore.AppendValues(actionIcon, action, fileIcon, System.IO.Path.GetFileName(rp.Path), System.IO.Path.GetDirectoryName(rp.Path), rp.Path, null);
                changedpathstore.AppendValues(iter, null, null, null, null, null, rp.Path, null);
                if (rp.Path == preselectFile)
                {
                    selectIter = iter;
                    select     = true;
                }
            }
            if (!string.IsNullOrEmpty(d.Email))
            {
                imageUser.Show();
                imageUser.LoadUserIcon(d.Email, 32);
            }
            else
            {
                imageUser.Hide();
            }

            labelAuthor.Text = d.Author;
            labelDate.Text   = d.Time.ToString();
            string rev = d.Name;

            if (rev.Length > 15)
            {
                currentRevisionShortened = true;
                rev = d.ShortName;
            }
            else
            {
                currentRevisionShortened = false;
            }

            labelRevision.Text          = GettextCatalog.GetString("revision: {0}", rev);
            textviewDetails.Buffer.Text = d.Message;

            if (select)
            {
                treeviewFiles.Selection.SelectIter(selectIter);
            }
        }
コード例 #18
0
        public TemplateResult FillVariables(TemplateContext context)
        {
            var    expansion  = CodeTemplateService.GetExpansionObject(this);
            var    result     = new TemplateResult();
            var    sb         = new StringBuilder();
            int    lastOffset = 0;
            string code       = context.Editor.FormatString(context.InsertPosition, context.TemplateCode);

            result.TextLinks = new List <TextLink> ();
            foreach (System.Text.RegularExpressions.Match match in variableRegEx.Matches(code))
            {
                string name = match.Groups [1].Value;
                sb.Append(code, lastOffset, match.Index - lastOffset);
                lastOffset = match.Index + match.Length;
                if (string.IsNullOrEmpty(name))                    // $$ is interpreted as $
                {
                    sb.Append("$");
                }
                else
                {
                    switch (name)
                    {
                    case "end":
                        result.CaretEndOffset = sb.Length;
                        break;

                    case "selected":
                        if (!string.IsNullOrEmpty(context.SelectedText))
                        {
                            string indent    = GetIndent(sb);
                            string selection = Reindent(context.SelectedText, indent);
                            sb.Append(selection);
                        }
                        break;

                    case "TM_CURRENT_LINE":
                        sb.Append(context.Editor.CaretLine);
                        break;

                    case "TM_CURRENT_WORD":
                        sb.Append("");
                        break;

                    case "TM_FILENAME":
                        sb.Append(context.Editor.FileName);
                        break;

                    case "TM_FILEPATH":
                        sb.Append(Path.GetDirectoryName(context.Editor.FileName));
                        break;

                    case "TM_FULLNAME":
                        sb.Append(AuthorInformation.Default.Name);
                        break;

                    case "TM_LINE_INDEX":
                        sb.Append(context.Editor.CaretColumn - 1);
                        break;

                    case "TM_LINE_NUMBER":
                        sb.Append(context.Editor.CaretLine);
                        break;

                    case "TM_SOFT_TABS":
                        sb.Append(context.Editor.Options.TabsToSpaces ? "YES" : "NO");                          // Note: these strings need no translation.
                        break;

                    case "TM_TAB_SIZE":
                        sb.Append(context.Editor.Options.TabSize);
                        break;
                    }
                }
                if (!variableDecarations.ContainsKey(name))
                {
                    continue;
                }
                var  link  = result.TextLinks.Find(l => l.Name == name);
                bool isNew = link == null;
                if (isNew)
                {
                    link = new TextLink(name);
                    if (!string.IsNullOrEmpty(variableDecarations [name].ToolTip))
                    {
                        link.Tooltip = GettextCatalog.GetString(variableDecarations [name].ToolTip);
                    }
                    link.Values = new CodeTemplateListDataProvider(variableDecarations [name].Values);
                    if (!string.IsNullOrEmpty(variableDecarations [name].Function))
                    {
                        link.Values = expansion.RunFunction(context, null, variableDecarations [name].Function);
                    }
                    result.TextLinks.Add(link);
                }
                link.IsEditable   = variableDecarations [name].IsEditable;
                link.IsIdentifier = variableDecarations [name].IsIdentifier;
                if (!string.IsNullOrEmpty(variableDecarations [name].Function))
                {
                    var functionResult = expansion.RunFunction(context, null, variableDecarations [name].Function);
                    if (functionResult != null && functionResult.Count > 0)
                    {
                        string s = (string)functionResult [functionResult.Count - 1];
                        if (s == null)
                        {
                            if (variableDecarations.ContainsKey(name))
                            {
                                s = variableDecarations [name].Default;
                            }
                        }
                        if (s != null)
                        {
                            link.AddLink(new TextSegment(sb.Length, s.Length));
                            if (isNew)
                            {
                                link.GetStringFunc = delegate(Func <string, string> callback) {
                                    return(expansion.RunFunction(context, callback, variableDecarations [name].Function));
                                };
                            }
                            sb.Append(s);
                        }
                    }
                    else
                    {
                        AddDefaultValue(sb, link, name);
                    }
                }
                else
                {
                    AddDefaultValue(sb, link, name);
                }
            }
            sb.Append(code, lastOffset, code.Length - lastOffset);

            // format & indent template code
            var data = TextEditorFactory.CreateNewDocument();

            data.Text         = sb.ToString();
            data.TextChanged += delegate(object sender, MonoDevelop.Core.Text.TextChangeEventArgs e) {
                for (int i = 0; i < e.TextChanges.Count; ++i)
                {
                    var change = e.TextChanges[i];
                    int delta  = change.InsertionLength - change.RemovalLength;

                    foreach (var link in result.TextLinks)
                    {
                        link.Links = link.Links.AdjustSegments(e).ToList();
                    }
                    if (result.CaretEndOffset > change.Offset)
                    {
                        result.CaretEndOffset += delta;
                    }
                }
            };

            IndentCode(data, context.LineIndent);
            result.Code = data.Text;
            return(result);
        }
コード例 #19
0
ファイル: Document.cs プロジェクト: czf/monodevelop
        public void Save()
        {
            // suspend type service "check all file loop" since we have already a parsed document.
            // Or at least one that updates "soon".
            TypeSystemService.TrackFileChanges = false;
            try {
                if (Window.ViewContent.IsViewOnly || !Window.ViewContent.IsDirty)
                {
                    return;
                }

                if (!Window.ViewContent.IsFile)
                {
                    Window.ViewContent.Save();
                    return;
                }

                if (Window.ViewContent.ContentName == null)
                {
                    SaveAs();
                }
                else
                {
                    try {
                        FileService.RequestFileEdit(Window.ViewContent.ContentName, true);
                    } catch (Exception ex) {
                        MessageService.ShowException(ex, GettextCatalog.GetString("The file could not be saved."));
                    }

                    FileAttributes attr = FileAttributes.ReadOnly | FileAttributes.Directory | FileAttributes.Offline | FileAttributes.System;

                    if (!File.Exists(Window.ViewContent.ContentName) || (File.GetAttributes(window.ViewContent.ContentName) & attr) != 0)
                    {
                        SaveAs();
                    }
                    else
                    {
                        string fileName = Window.ViewContent.ContentName;
                        // save backup first
                        if ((bool)PropertyService.Get("SharpDevelop.CreateBackupCopy", false))
                        {
                            Window.ViewContent.Save(fileName + "~");
                            FileService.NotifyFileChanged(fileName);
                        }
                        Window.ViewContent.Save(fileName);
                        FileService.NotifyFileChanged(fileName);
                        OnSaved(EventArgs.Empty);
                    }
                }
            } finally {
                // Set the file time of the current document after the file time of the written file, to prevent double file updates.
                // Note that the parsed document may be overwritten by a background thread to a more recent one.
                var doc = parsedDocument;
                if (doc != null && doc.ParsedFile != null)
                {
                    string fileName = Window.ViewContent.ContentName;
                    try {
                        doc.ParsedFile.LastWriteTime = File.GetLastWriteTimeUtc(fileName);
                    } catch (Exception e) {
                        doc.ParsedFile.LastWriteTime = DateTime.UtcNow;
                        LoggingService.LogWarning("Exception while getting the write time from " + fileName, e);
                    }
                }
                TypeSystemService.TrackFileChanges = true;
            }
        }
コード例 #20
0
        private void Build()
        {
            VBox vbContent = new VBox
            {
                Name    = "content",
                Spacing = 6
            };

            {
                Label lblHeader = new Label
                {
                    Name      = "headerDebug",
                    Xalign    = 0F,
                    LabelProp = GettextCatalog.GetString("<b>Engine settings</b>"),
                    UseMarkup = true
                };

                vbContent.Add(lblHeader);
                Gtk.Box.BoxChild c1 = (Gtk.Box.BoxChild)vbContent[lblHeader];
                c1.Position = 0;
                c1.Expand   = false;
                c1.Fill     = false;

                HBox hbIdent = new HBox
                {
                    Name = "identDebug"
                };
                Label lblBlank = new Label
                {
                    Name         = "blankDebug",
                    WidthRequest = 18
                };

                hbIdent.Add(lblBlank);
                Gtk.Box.BoxChild c2 = (Gtk.Box.BoxChild)hbIdent[lblBlank];
                c2.Position = 0;
                c2.Expand   = false;
                c2.Fill     = false;
                VBox vbTable = new VBox
                {
                    Name    = "table_boxDebug",
                    Spacing = 6
                };
                Table table = new Table(3, 2, false)
                {
                    Name          = "tableDebug",
                    RowSpacing    = 6,
                    ColumnSpacing = 6
                };

                // debug command
                {
                    Label lblLauncher = new Label
                    {
                        Name         = "debugCommand",
                        Xalign       = 0F,
                        LabelProp    = GettextCatalog.GetString("Launcher path:"),
                        UseUnderline = true
                    };
                    table.Add(lblLauncher);
                    Gtk.Table.TableChild cLblLauncher = (Gtk.Table.TableChild)table[lblLauncher];
                    cLblLauncher.XOptions = AttachOptions.Fill;
                    cLblLauncher.YOptions = (AttachOptions)0;

                    table.Add(_launcherPath);
                    Gtk.Table.TableChild cLauncher = (Gtk.Table.TableChild)table[_launcherPath];
                    cLauncher.LeftAttach  = 1;
                    cLauncher.RightAttach = 2;
                    cLauncher.YOptions    = (AttachOptions)0;
                }

                //debug command arguments
                {
                    Label lblProject = new Label
                    {
                        Name         = "debugCommandArguments",
                        Xalign       = 0F,
                        LabelProp    = GettextCatalog.GetString("Project path:"),
                        UseUnderline = true
                    };
                    table.Add(lblProject);
                    Gtk.Table.TableChild c5 = (Gtk.Table.TableChild)table[lblProject];
                    c5.TopAttach    = 2;
                    c5.BottomAttach = 3;
                    c5.XOptions     = AttachOptions.Fill;
                    c5.YOptions     = (AttachOptions)0;

                    table.Add(_projectPath);
                    Gtk.Table.TableChild c6 = (Gtk.Table.TableChild)table[_projectPath];
                    c6.TopAttach    = 2;
                    c6.BottomAttach = 3;
                    c6.LeftAttach   = 1;
                    c6.RightAttach  = 2;
                    c6.XOptions     = (AttachOptions)4;
                    c6.YOptions     = (AttachOptions)4;
                }

                //debug working directory
                {
                    Label lblArguments = new Label
                    {
                        Name         = "debugWorkingDirectory",
                        Xalign       = 0F,
                        LabelProp    = GettextCatalog.GetString("Command arguments:"),
                        UseUnderline = true
                    };
                    table.Add(lblArguments);
                    Gtk.Table.TableChild c5 = (Gtk.Table.TableChild)table[lblArguments];
                    c5.TopAttach    = 3;
                    c5.BottomAttach = 4;
                    c5.XOptions     = AttachOptions.Fill;
                    c5.YOptions     = (AttachOptions)0;

                    table.Add(_commandArguments);
                    Gtk.Table.TableChild c6 = (Gtk.Table.TableChild)table[_commandArguments];
                    c6.TopAttach    = 3;
                    c6.BottomAttach = 4;
                    c6.LeftAttach   = 1;
                    c6.RightAttach  = 2;
                    c6.XOptions     = (AttachOptions)4;
                    c6.YOptions     = (AttachOptions)4;
                }

                vbTable.Add(table);
                Gtk.Box.BoxChild c7 = (Gtk.Box.BoxChild)vbTable[table];
                c7.Position = 0;
                c7.Expand   = false;
                c7.Expand   = false;
                hbIdent.Add(vbTable);
                Gtk.Box.BoxChild c8 = (Gtk.Box.BoxChild)hbIdent[vbTable];
                c8.Position = 1;
                vbContent.Add(hbIdent);
                Gtk.Box.BoxChild c9 = (Gtk.Box.BoxChild)vbContent[hbIdent];
                c9.Position = 1;
                Add(vbContent);
                Gtk.Box.BoxChild c10 = (Gtk.Box.BoxChild) this[vbContent];
                c10.Position = 0;
                c10.Expand   = false;
                c10.Fill     = false;
            }

            ShowAll();
        }
        public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
        {
            var document = context.Document;

            if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
            {
                return;
            }
            var span = context.Span;

            if (!span.IsEmpty)
            {
                return;
            }
            var cancellationToken = context.CancellationToken;

            if (cancellationToken.IsCancellationRequested)
            {
                return;
            }
            var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            if (model.IsFromGeneratedCode(cancellationToken))
            {
                return;
            }
            var root = await model.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);

            var node = root.FindNode(span);

            while (node != null && !(node is MemberDeclarationSyntax))
            {
                node = node.Parent;
            }
            if (node == null)
            {
                return;
            }

            if (!node.IsKind(SyntaxKind.MethodDeclaration) &&
                !node.IsKind(SyntaxKind.PropertyDeclaration) &&
                !node.IsKind(SyntaxKind.IndexerDeclaration) &&
                !node.IsKind(SyntaxKind.EventDeclaration))
            {
                return;
            }

            var memberDeclaration = node as MemberDeclarationSyntax;
            var explicitSyntax    = memberDeclaration.GetExplicitInterfaceSpecifierSyntax();

            if (explicitSyntax == null || !explicitSyntax.Span.Contains(span))
            {
                return;
            }

            var enclosingSymbol = model.GetDeclaredSymbol(memberDeclaration, cancellationToken);

            if (enclosingSymbol == null)
            {
                return;
            }
            var containingType = enclosingSymbol.ContainingType;


            foreach (var member in containingType.GetMembers())
            {
                if (member == enclosingSymbol ||
                    member.Kind != enclosingSymbol.Kind)
                {
                    continue;
                }

                switch (member.Kind)
                {
                case SymbolKind.Property:
                    var property1 = (IPropertySymbol)enclosingSymbol;
                    var property2 = (IPropertySymbol)member;

                    foreach (var explictProperty in property1.ExplicitInterfaceImplementations)
                    {
                        if (explictProperty.Name == property2.Name)
                        {
                            if (SignatureComparer.HaveSameSignature(property1.Parameters, property2.Parameters))
                            {
                                return;
                            }
                        }
                    }
                    break;

                case SymbolKind.Method:
                    var method1 = (IMethodSymbol)enclosingSymbol;
                    var method2 = (IMethodSymbol)member;
                    foreach (var explictMethod in method1.ExplicitInterfaceImplementations)
                    {
                        if (explictMethod.Name == method2.Name)
                        {
                            if (SignatureComparer.HaveSameSignature(method1.Parameters, method2.Parameters))
                            {
                                return;
                            }
                        }
                    }
                    break;

                case SymbolKind.Event:
                    var evt1 = (IEventSymbol)enclosingSymbol;
                    var evt2 = (IEventSymbol)member;
                    foreach (var explictProperty in evt1.ExplicitInterfaceImplementations)
                    {
                        if (explictProperty.Name == evt2.Name)
                        {
                            return;
                        }
                    }
                    break;
                }
            }

            context.RegisterRefactoring(
                CodeActionFactory.Create(
                    span,
                    DiagnosticSeverity.Info,
                    GettextCatalog.GetString("To implicit implementation"),
                    t2 =>
            {
                var newNode = memberDeclaration;
                switch (newNode.Kind())
                {
                case SyntaxKind.MethodDeclaration:
                    var method = (MethodDeclarationSyntax)memberDeclaration.WithoutLeadingTrivia();
                    newNode    = method
                                 .WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword)))
                                 .WithExplicitInterfaceSpecifier(null);
                    break;

                case SyntaxKind.PropertyDeclaration:
                    var property = (PropertyDeclarationSyntax)memberDeclaration.WithoutLeadingTrivia();
                    newNode      = property
                                   .WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword)))
                                   .WithExplicitInterfaceSpecifier(null);
                    break;

                case SyntaxKind.IndexerDeclaration:
                    var indexer = (IndexerDeclarationSyntax)memberDeclaration.WithoutLeadingTrivia();
                    newNode     = indexer
                                  .WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword)))
                                  .WithExplicitInterfaceSpecifier(null);
                    break;

                case SyntaxKind.EventDeclaration:
                    var evt = (EventDeclarationSyntax)memberDeclaration.WithoutLeadingTrivia();
                    newNode = evt
                              .WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword)))
                              .WithExplicitInterfaceSpecifier(null);
                    break;
                }
                var newRoot = root.ReplaceNode((SyntaxNode)
                                               memberDeclaration,
                                               newNode.WithAdditionalAnnotations(Formatter.Annotation).WithLeadingTrivia(memberDeclaration.GetLeadingTrivia())
                                               );
                return(Task.FromResult(document.WithSyntaxRoot(newRoot)));
            }
                    )
                );
        }
コード例 #22
0
        public StackTracePad()
        {
            this.ShadowType = ShadowType.None;

            ActionCommand evalCmd = new ActionCommand("StackTracePad.EvaluateMethodParams", GettextCatalog.GetString("Evaluate Method Parameters"));
            ActionCommand gotoCmd = new ActionCommand("StackTracePad.ActivateFrame", GettextCatalog.GetString("Activate Stack Frame"));

            menuSet = new CommandEntrySet();
            menuSet.Add(evalCmd);
            menuSet.Add(gotoCmd);
            menuSet.AddSeparator();
            menuSet.AddItem(EditCommands.SelectAll);
            menuSet.AddItem(EditCommands.Copy);

            store = new ListStore(typeof(string), typeof(string), typeof(string), typeof(string), typeof(string), typeof(string), typeof(Pango.Style), typeof(object), typeof(bool));

            tree                   = new PadTreeView(store);
            tree.RulesHint         = true;
            tree.HeadersVisible    = true;
            tree.Selection.Mode    = SelectionMode.Multiple;
            tree.SearchEqualFunc   = Search;
            tree.EnableSearch      = true;
            tree.SearchColumn      = 1;
            tree.ButtonPressEvent += HandleButtonPressEvent;
            tree.DoPopupMenu       = ShowPopup;

            TreeViewColumn col = new TreeViewColumn();
            CellRenderer   crp = new CellRendererIcon();

            col.PackStart(crp, false);
            col.AddAttribute(crp, "stock_id", 0);
            tree.AppendColumn(col);

            TreeViewColumn FrameCol = new TreeViewColumn();

            FrameCol.Title = GettextCatalog.GetString("Name");
            refresh        = new CellRendererIcon();
            refresh.Pixbuf = ImageService.GetPixbuf(Gtk.Stock.Refresh).ScaleSimple(12, 12, Gdk.InterpType.Hyper);
            FrameCol.PackStart(refresh, false);
            FrameCol.AddAttribute(refresh, "visible", 8);
            FrameCol.PackStart(tree.TextRenderer, true);
            FrameCol.AddAttribute(tree.TextRenderer, "text", 1);
            FrameCol.AddAttribute(tree.TextRenderer, "foreground", 5);
            FrameCol.AddAttribute(tree.TextRenderer, "style", 6);
            FrameCol.Resizable = true;
            FrameCol.Alignment = 0.0f;
            tree.AppendColumn(FrameCol);

            col       = new TreeViewColumn();
            col.Title = GettextCatalog.GetString("File");
            col.PackStart(tree.TextRenderer, false);
            col.AddAttribute(tree.TextRenderer, "text", 2);
            col.AddAttribute(tree.TextRenderer, "foreground", 5);
            tree.AppendColumn(col);

            col       = new TreeViewColumn();
            col.Title = GettextCatalog.GetString("Language");
            col.PackStart(tree.TextRenderer, false);
            col.AddAttribute(tree.TextRenderer, "text", 3);
            col.AddAttribute(tree.TextRenderer, "foreground", 5);
            tree.AppendColumn(col);

            col       = new TreeViewColumn();
            col.Title = GettextCatalog.GetString("Address");
            col.PackStart(tree.TextRenderer, false);
            col.AddAttribute(tree.TextRenderer, "text", 4);
            col.AddAttribute(tree.TextRenderer, "foreground", 5);
            tree.AppendColumn(col);

            Add(tree);
            ShowAll();

            current_backtrace = DebuggingService.CurrentCallStack;
            UpdateDisplay();

            DebuggingService.CallStackChanged    += (EventHandler)DispatchService.GuiDispatch(new EventHandler(OnClassStackChanged));
            DebuggingService.CurrentFrameChanged += (EventHandler)DispatchService.GuiDispatch(new EventHandler(OnFrameChanged));
            tree.RowActivated += OnRowActivated;
        }
コード例 #23
0
        protected override async Task OnAddAsync(FilePath[] localPaths, bool recurse, ProgressMonitor monitor)
        {
            foreach (FilePath path in localPaths)
            {
                if (await IsVersionedAsync(path, monitor.CancellationToken).ConfigureAwait(false) && File.Exists(path) && !Directory.Exists(path))
                {
                    if (RootPath.IsNull)
                    {
                        throw new UserException(GettextCatalog.GetString("Project publishing failed. There is a stale .svn folder in the path '{0}'", path.ParentDirectory));
                    }
                    VersionInfo srcInfo = await GetVersionInfoAsync(path, VersionInfoQueryFlags.IgnoreCache).ConfigureAwait(false);

                    if (srcInfo.HasLocalChange(VersionStatus.ScheduledDelete))
                    {
                        // It is a file that was deleted. It can be restored now since it's going
                        // to be added again.
                        // First of all, make a copy of the file
                        string tmp = Path.GetTempFileName();
                        File.Copy(path, tmp, true);

                        // Now revert the status of the file
                        await RevertAsync(path, false, monitor).ConfigureAwait(false);

                        // Copy the file over the old one and clean up
                        File.Copy(tmp, path, true);
                        File.Delete(tmp);
                        continue;
                    }
                }
                else
                {
                    if (!await IsVersionedAsync(path.ParentDirectory, monitor.CancellationToken).ConfigureAwait(false))
                    {
                        // The file/folder belongs to an unversioned folder. We can add it by versioning the parent
                        // folders up to the root of the repository

                        if (!path.IsChildPathOf(RootPath))
                        {
                            throw new InvalidOperationException("File outside the repository directory");
                        }

                        List <FilePath> dirChain  = new List <FilePath> ();
                        FilePath        parentDir = path.CanonicalPath;
                        do
                        {
                            parentDir = parentDir.ParentDirectory;
                            if (await IsVersionedAsync(parentDir, monitor.CancellationToken).ConfigureAwait(false))
                            {
                                break;
                            }
                            dirChain.Add(parentDir);
                        }while (parentDir != RootPath);

                        // Found all parent unversioned dirs. Versin them now.
                        dirChain.Reverse();
                        FileUpdateEventArgs args = new FileUpdateEventArgs();
                        foreach (var d in dirChain)
                        {
                            Svn.Add(d, false, monitor);
                            args.Add(new FileUpdateEventInfo(this, d, true));
                        }
                        VersionControlService.NotifyFileStatusChanged(args);
                    }
                }
                Svn.Add(path, recurse, monitor);
            }
        }
        public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
        {
            var document = context.Document;

            if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
            {
                return;
            }
            var span = context.Span;

            if (!span.IsEmpty)
            {
                return;
            }
            var cancellationToken = context.CancellationToken;

            if (cancellationToken.IsCancellationRequested)
            {
                return;
            }
            var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            if (model.IsFromGeneratedCode(cancellationToken))
            {
                return;
            }
            var root = await model.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);

            var token = root.FindToken(span.Start);

            var node = token.Parent as AssignmentExpressionSyntax;

            if (node == null || !node.OperatorToken.Span.Contains(span))
            {
                return;
            }

            var updatedNode = ReplaceWithOperatorAssignmentCodeRefactoringProvider.CreateAssignment(node) ?? node;

            if ((!updatedNode.IsKind(SyntaxKind.AddAssignmentExpression) && !updatedNode.IsKind(SyntaxKind.SubtractAssignmentExpression)))
            {
                return;
            }

            var rightLiteral = updatedNode.Right as LiteralExpressionSyntax;

            if (rightLiteral == null || ((int)rightLiteral.Token.Value) != 1)
            {
                return;
            }

            context.RegisterRefactoring(
                CodeActionFactory.Create(
                    token.Span,
                    DiagnosticSeverity.Info,
                    updatedNode.IsKind(SyntaxKind.AddAssignmentExpression) ? GettextCatalog.GetString("To '{0}++'") : GettextCatalog.GetString("To '{0}--'"),
                    t2 =>
            {
                var newNode = SyntaxFactory.PostfixUnaryExpression(updatedNode.IsKind(SyntaxKind.AddAssignmentExpression) ? SyntaxKind.PostIncrementExpression : SyntaxKind.PostDecrementExpression, updatedNode.Left);
                var newRoot = root.ReplaceNode((SyntaxNode)node, newNode.WithAdditionalAnnotations(Formatter.Annotation).WithLeadingTrivia(node.GetLeadingTrivia()));
                return(Task.FromResult(document.WithSyntaxRoot(newRoot)));
            }
                    )
                );
        }
コード例 #25
0
        void SetupAccessibility()
        {
            label76.Accessible.Role = Atk.Role.Filler;
            compileTargetCombo.SetCommonAccessibilityAttributes("CodeGeneration.CompileTarget", label86,
                                                                GettextCatalog.GetString("Select the compile target for the code generation"));

            mainClassEntry.SetCommonAccessibilityAttributes("CodeGeneration.MainClass", label88,
                                                            GettextCatalog.GetString("Enter the main class for the code generation"));

            iconEntry.SetEntryAccessibilityAttributes("CodeGeneration.WinIcon", "",
                                                      GettextCatalog.GetString("Enter the file to use as the icon on Windows"));
            iconEntry.SetAccessibilityLabelRelationship(label3);

            codepageEntry.SetCommonAccessibilityAttributes("CodeGeneration.CodePage", label1,
                                                           GettextCatalog.GetString("Select the compiler code page"));

            noStdLibCheckButton.SetCommonAccessibilityAttributes("CodeGeneration.NoStdLib", "", GettextCatalog.GetString("Whether or not to include a reference to mscorlib.dll"));

            langVerCombo.SetCommonAccessibilityAttributes("CodeGeneration.LanguageVersion", label2,
                                                          GettextCatalog.GetString("Select the version of C# to use"));

            allowUnsafeCodeCheckButton.SetCommonAccessibilityAttributes("CodeGeneration.AllowUnsafe", "",
                                                                        GettextCatalog.GetString("Check to allow 'unsafe' code"));
        }
コード例 #26
0
        static IEnumerable <SearchCollector.FileList> GetFileNames(Solution solution, object node, RefactoryScope scope,
                                                                   IProgressMonitor monitor, IEnumerable <object> searchNodes)
        {
            if (!(node is IField) && node is IVariable || scope == RefactoryScope.File)
            {
                string fileName;
                if (node is IEntity)
                {
                    fileName = ((IEntity)node).Region.FileName;
                }
                else if (node is ITypeParameter)
                {
                    fileName = ((ITypeParameter)node).Region.FileName;
                }
                else
                {
                    fileName = ((IVariable)node).Region.FileName;
                }
                var fileList = GetFileList(fileName);
                if (fileList != null)
                {
                    yield return(fileList);
                }
                yield break;
            }

            if (node is ITypeParameter)
            {
                var typeParameter = node as ITypeParameter;
                if (typeParameter.Owner != null)
                {
                    yield return(SearchCollector.CollectDeclaringFiles(typeParameter.Owner));

                    yield break;
                }
                var fileList = GetFileList(typeParameter.Region.FileName);
                if (fileList != null)
                {
                    yield return(fileList);
                }
                yield break;
            }

            var entity = (IEntity)node;

            switch (scope)
            {
            case RefactoryScope.DeclaringType:
                if (entity.DeclaringTypeDefinition != null)
                {
                    yield return(SearchCollector.CollectDeclaringFiles(entity.DeclaringTypeDefinition));
                }
                else
                {
                    yield return(SearchCollector.CollectDeclaringFiles(entity));
                }
                break;

            case RefactoryScope.Project:
                var sourceProject = TypeSystemService.GetProject(entity.Compilation.MainAssembly.UnresolvedAssembly.Location);
                foreach (var file in SearchCollector.CollectFiles(sourceProject, searchNodes.Cast <IEntity> ()))
                {
                    yield return(file);
                }
                break;

            default:
                var files = SearchCollector.CollectFiles(solution, searchNodes.Cast <IEntity> ()).ToList();
                if (monitor != null)
                {
                    monitor.BeginTask(GettextCatalog.GetString("Searching for references in solution..."), files.Count);
                }
                foreach (var file in files)
                {
                    if (monitor != null && monitor.IsCancelRequested)
                    {
                        yield break;
                    }
                    yield return(file);

                    if (monitor != null)
                    {
                        monitor.Step(1);
                    }
                }
                if (monitor != null)
                {
                    monitor.EndTask();
                }
                break;
            }
        }
コード例 #27
0
        void OnOKClicked(object sender, EventArgs e)
        {
            TreeIter iter;

            if (!store.GetIterFirst(out iter))
            {
                return;
            }

            List <FieldData> data = new List <FieldData> ();

            do
            {
                bool selected = (bool)store.GetValue(iter, colCheckedIndex);
                if (!selected)
                {
                    continue;
                }

                string    propertyName = (string)store.GetValue(iter, colPropertyNameIndex);
                string    visibility   = (string)store.GetValue(iter, colVisibilityIndex);
                bool      read_only    = (bool)store.GetValue(iter, colReadOnlyIndex);
                IField    field        = (IField)store.GetValue(iter, colFieldIndex);
                Modifiers mod          = Modifiers.None;
                if (visibility.ToUpper() == "PUBLIC")
                {
                    mod = Modifiers.Public;
                }
                if (visibility.ToUpper() == "PRIVATE")
                {
                    mod = Modifiers.Private;
                }
                if (visibility.ToUpper() == "PROTECTED")
                {
                    mod = Modifiers.Protected;
                }
                if (visibility.ToUpper() == "INTERNAL")
                {
                    mod = Modifiers.Internal;
                }
                data.Add(new FieldData(field, propertyName, read_only, mod));
            } while (store.IterNext(ref iter));

            InsertionCursorEditMode mode       = new InsertionCursorEditMode(editor.Editor.Parent, CodeGenerationService.GetInsertionPoints(editor, declaringType));
            ModeHelpWindow          helpWindow = new ModeHelpWindow();

            helpWindow.TransientFor = IdeApp.Workbench.RootWindow;
            helpWindow.TitleText    = GettextCatalog.GetString("<b>Encapsulate Field -- Targeting</b>");
            helpWindow.Items.Add(new KeyValuePair <string, string> (GettextCatalog.GetString("<b>Key</b>"), GettextCatalog.GetString("<b>Behavior</b>")));
            helpWindow.Items.Add(new KeyValuePair <string, string> (GettextCatalog.GetString("<b>Up</b>"), GettextCatalog.GetString("Move to <b>previous</b> target point.")));
            helpWindow.Items.Add(new KeyValuePair <string, string> (GettextCatalog.GetString("<b>Down</b>"), GettextCatalog.GetString("Move to <b>next</b> target point.")));
            helpWindow.Items.Add(new KeyValuePair <string, string> (GettextCatalog.GetString("<b>Enter</b>"), GettextCatalog.GetString("<b>Declare new property</b> at target point.")));
            helpWindow.Items.Add(new KeyValuePair <string, string> (GettextCatalog.GetString("<b>Esc</b>"), GettextCatalog.GetString("<b>Cancel</b> this refactoring.")));
            mode.HelpWindow = helpWindow;
            mode.CurIndex   = mode.InsertionPoints.Count - 1;
            int          idx = -1, i = 0;
            TextLocation lTextLocation = TextLocation.Empty;

            foreach (IMember member in declaringType.Members)
            {
                if (lTextLocation != member.Location && data.Any(d => d.Field.Location == member.Location))
                {
                    idx = i;
                }
                lTextLocation = member.Location;
                i++;
            }
            if (idx >= 0)
            {
                mode.CurIndex = idx + 1;
            }
            mode.StartMode();
            mode.Exited += delegate(object s, InsertionCursorEventArgs args) {
                if (args.Success)
                {
                    CodeGenerator generator = CodeGenerator.CreateGenerator(editor.Editor.Document.MimeType, editor.Editor.TabsToSpaces, editor.Editor.Options.TabSize, editor.Editor.EolMarker);
                    StringBuilder code      = new StringBuilder();
                    for (int j = 0; j < data.Count; j++)
                    {
                        if (j > 0)
                        {
                            code.AppendLine();
                            code.AppendLine();
                        }
                        var f = data[j];
                        code.Append(generator.CreateFieldEncapsulation(declaringType, f.Field, f.PropertyName, f.Modifiers, f.ReadOnly));
                    }
                    args.InsertionPoint.Insert(editor.Editor, code.ToString());
                }
            };
            ((Widget)this).Destroy();
        }
コード例 #28
0
ファイル: LogWidget.cs プロジェクト: thild/monodevelop
        public LogWidget(VersionControlDocumentInfo info)
        {
            this.Build();
            this.info = info;
            if (info.Document != null)
            {
                this.preselectFile = info.Document.FileName;
            }

            revertButton             = new Gtk.ToolButton(new Gtk.Image("vc-revert-command", Gtk.IconSize.Menu), GettextCatalog.GetString("Revert changes from this revision"));
            revertButton.IsImportant = true;
//			revertButton.Sensitive = false;
            revertButton.Clicked += new EventHandler(RevertRevisionClicked);
            CommandBar.Insert(revertButton, -1);

            revertToButton             = new Gtk.ToolButton(new Gtk.Image("vc-revert-command", Gtk.IconSize.Menu), GettextCatalog.GetString("Revert to this revision"));
            revertToButton.IsImportant = true;
//			revertToButton.Sensitive = false;
            revertToButton.Clicked += new EventHandler(RevertToRevisionClicked);
            CommandBar.Insert(revertToButton, -1);

            Gtk.ToolItem item = new Gtk.ToolItem();
            Gtk.HBox     a    = new Gtk.HBox();
            item.Add(a);
            searchEntry = new SearchEntry();
            searchEntry.WidthRequest             = 200;
            searchEntry.ForceFilterButtonVisible = true;
            searchEntry.EmptyMessage             = GettextCatalog.GetString("Search");
            searchEntry.Changed += HandleSearchEntryFilterChanged;
            searchEntry.Ready    = true;
            searchEntry.Show();
            a.PackEnd(searchEntry, false, false, 0);
            CommandBar.Insert(item, -1);
            ((Gtk.Toolbar.ToolbarChild)CommandBar[item]).Expand = true;

            CommandBar.ShowAll();

            messageRenderer.Ellipsize = Pango.EllipsizeMode.End;
            TreeViewColumn colRevMessage = new TreeViewColumn();

            colRevMessage.Title = GettextCatalog.GetString("Message");
            var graphRenderer = new RevisionGraphCellRenderer();

            colRevMessage.PackStart(graphRenderer, false);
            colRevMessage.SetCellDataFunc(graphRenderer, GraphFunc);

            colRevMessage.PackStart(messageRenderer, true);
            colRevMessage.SetCellDataFunc(messageRenderer, MessageFunc);
            colRevMessage.Sizing = TreeViewColumnSizing.Autosize;

            treeviewLog.AppendColumn(colRevMessage);
            colRevMessage.MinWidth  = 350;
            colRevMessage.Resizable = true;


            TreeViewColumn colRevDate = new TreeViewColumn(GettextCatalog.GetString("Date"), textRenderer);

            colRevDate.SetCellDataFunc(textRenderer, DateFunc);
            colRevDate.Resizable = true;
            treeviewLog.AppendColumn(colRevDate);

            TreeViewColumn colRevAuthor = new TreeViewColumn();

            colRevAuthor.Title = GettextCatalog.GetString("Author");
            colRevAuthor.PackStart(pixRenderer, false);
            colRevAuthor.PackStart(textRenderer, true);
            colRevAuthor.SetCellDataFunc(textRenderer, AuthorFunc);
            colRevAuthor.SetCellDataFunc(pixRenderer, AuthorIconFunc);
            colRevAuthor.Resizable = true;
            treeviewLog.AppendColumn(colRevAuthor);

            TreeViewColumn colRevNum = new TreeViewColumn(GettextCatalog.GetString("Revision"), textRenderer);

            colRevNum.SetCellDataFunc(textRenderer, RevisionFunc);
            colRevNum.Resizable = true;
            treeviewLog.AppendColumn(colRevNum);

            treeviewLog.Model              = logstore;
            treeviewLog.Selection.Changed += TreeSelectionChanged;

            treeviewFiles = new FileTreeView();
            treeviewFiles.DiffLineActivated += HandleTreeviewFilesDiffLineActivated;
            scrolledwindowFiles.Child        = treeviewFiles;
            scrolledwindowFiles.ShowAll();

            changedpathstore = new TreeStore(typeof(Gdk.Pixbuf), typeof(string), // icon/file name
                                             typeof(Gdk.Pixbuf), typeof(string), // icon/operation
                                             typeof(string),                     // path
                                             typeof(string),                     // revision path (invisible)
                                             typeof(string[])                    // diff
                                             );

            TreeViewColumn colChangedFile = new TreeViewColumn();
            var            crp            = new CellRendererPixbuf();
            var            crt            = new CellRendererText();

            colChangedFile.Title = GettextCatalog.GetString("File");
            colChangedFile.PackStart(crp, false);
            colChangedFile.PackStart(crt, true);
            colChangedFile.AddAttribute(crp, "pixbuf", 2);
            colChangedFile.AddAttribute(crt, "text", 3);
            treeviewFiles.AppendColumn(colChangedFile);

            TreeViewColumn colOperation = new TreeViewColumn();

            colOperation.Title = GettextCatalog.GetString("Operation");
            colOperation.PackStart(crp, false);
            colOperation.PackStart(crt, true);
            colOperation.AddAttribute(crp, "pixbuf", 0);
            colOperation.AddAttribute(crt, "text", 1);
            treeviewFiles.AppendColumn(colOperation);

            TreeViewColumn colChangedPath = new TreeViewColumn();

            colChangedPath.Title = GettextCatalog.GetString("Path");

            diffRenderer.DrawLeft = true;
            colChangedPath.PackStart(diffRenderer, true);
            colChangedPath.SetCellDataFunc(diffRenderer, SetDiffCellData);
            treeviewFiles.AppendColumn(colChangedPath);
            treeviewFiles.Model          = changedpathstore;
            treeviewFiles.TestExpandRow += HandleTreeviewFilesTestExpandRow;
            treeviewFiles.Events        |= Gdk.EventMask.PointerMotionMask;

            textviewDetails.WrapMode = Gtk.WrapMode.Word;

            labelAuthor.Text   = "";
            labelDate.Text     = "";
            labelRevision.Text = "";
        }
コード例 #29
0
        public override void DeleteMultipleItems()
        {
            var projects = new Set <SolutionItem> ();
            var folders  = new List <ProjectFolder> ();

            foreach (ITreeNavigator node in CurrentNodes)
            {
                folders.Add((ProjectFolder)node.DataItem);
            }

            var removeButton = new AlertButton(GettextCatalog.GetString("_Remove from Project"), Gtk.Stock.Remove);
            var question     = new QuestionMessage()
            {
                AllowApplyToAll = folders.Count > 1,
                SecondaryText   = GettextCatalog.GetString(
                    "The Delete option permanently removes the directory and any files it contains from your hard disk. " +
                    "Click Remove from Project if you only want to remove it from your current solution.")
            };

            question.Buttons.Add(AlertButton.Delete);
            question.Buttons.Add(removeButton);
            question.Buttons.Add(AlertButton.Cancel);

            var deleteOnlyQuestion = new QuestionMessage()
            {
                AllowApplyToAll = folders.Count > 1,
                SecondaryText   = GettextCatalog.GetString("The directory and any files it contains will be permanently removed from your hard disk. ")
            };

            deleteOnlyQuestion.Buttons.Add(AlertButton.Delete);
            deleteOnlyQuestion.Buttons.Add(AlertButton.Cancel);

            foreach (var folder in folders)
            {
                var project = folder.Project;

                AlertButton result;

                if (project == null)
                {
                    deleteOnlyQuestion.Text = GettextCatalog.GetString("Are you sure you want to remove directory {0}?", folder.Name);
                    result = MessageService.AskQuestion(deleteOnlyQuestion);
                    if (result == AlertButton.Delete)
                    {
                        DeleteFolder(folder);
                        continue;
                    }
                    else
                    {
                        break;
                    }
                }

                var  folderRelativePath = folder.Path.ToRelative(project.BaseDirectory);
                var  files           = project.Files.GetFilesInVirtualPath(folderRelativePath).ToList();
                var  folderPf        = project.Files.GetFileWithVirtualPath(folderRelativePath);
                bool isProjectFolder = files.Count == 0 && folderPf == null;

                //if the parent directory has already been removed, there may be nothing to do
                if (isProjectFolder)
                {
                    deleteOnlyQuestion.Text = GettextCatalog.GetString("Are you sure you want to remove directory {0}?", folder.Name);
                    result = MessageService.AskQuestion(deleteOnlyQuestion);
                    if (result != AlertButton.Delete)
                    {
                        break;
                    }
                }
                else
                {
                    question.Text = GettextCatalog.GetString("Are you sure you want to remove directory {0} from project {1}?",
                                                             folder.Name, project.Name);
                    result = MessageService.AskQuestion(question);
                    if (result != removeButton && result != AlertButton.Delete)
                    {
                        break;
                    }

                    projects.Add(project);

                    //remove the files and link files in the directory
                    foreach (var f in files)
                    {
                        project.Files.Remove(f);
                    }

                    // also remove the folder's own ProjectFile, if it exists
                    // FIXME: it probably was already in the files list
                    if (folderPf != null)
                    {
                        project.Files.Remove(folderPf);
                    }
                }

                if (result == AlertButton.Delete)
                {
                    DeleteFolder(folder);
                }
                else
                {
                    //explictly remove the node from the tree, since it currently only tracks real folder deletions
                    folder.Remove();
                }

                if (isProjectFolder && folder.Path.ParentDirectory != project.BaseDirectory)
                {
                    // If it's the last item in the parent folder, make sure we keep a reference to the parent
                    // folder, so it is not deleted from the tree.
                    var inParentFolder = project.Files.GetFilesInVirtualPath(folderRelativePath.ParentDirectory);
                    if (!inParentFolder.Skip(1).Any())
                    {
                        project.Files.Add(new ProjectFile(folder.Path.ParentDirectory)
                        {
                            Subtype = Subtype.Directory,
                        });
                    }
                }
            }
            IdeApp.ProjectOperations.SaveAsync(projects);
        }
コード例 #30
0
 protected override string GetDescription()
 {
     return(GettextCatalog.GetString("Reverting ..."));
 }