示例#1
0
        /// <summary>
        /// Identifies documents that are open from a serialized list
        /// </summary>
        /// <param name="docs"></param>
        /// <returns>List of DocumentViewModels</returns>
        private static List <DocumentViewModel> LoadVisibleDocuments(string[] paths)
        {
            List <DocumentViewModel> documents = new List <DocumentViewModel>();

            if (paths == null)
            {
                return(documents);
            }

            foreach (string s in paths)
            {
                FileDeclaration d = MacroUI.GetInstance().GetDeclarationFromFullname(s);
                if (d != null)
                {
                    DocumentModel model = DocumentModel.Create(d);

                    if (model != null)
                    {
                        DocumentViewModel viewModel = DocumentViewModel.Create(model);
                        documents.Add(viewModel);
                    }
                }
            }

            return(documents);
        }
示例#2
0
        /// <summary>
        /// Creates a new file at the specified location
        /// </summary>
        /// <param name="info">The macro file</param>
        /// <returns>The id of the newly created macro</returns>
        public static FileDeclaration CreateFile(FileInfo info)
        {
            try
            {
                if (info.Exists)
                {
                    throw new ArgumentException("File with name '" + info.FullName + "' already exists.");
                }

                if (!info.Directory.Exists)
                {
                    info.Directory.Create();
                }

                using (StreamWriter sw = info.CreateText())
                    sw.Write("\n");

                FileDeclaration declaration = new FileDeclaration(info, "\n");

                //MacroEngine.GetInstance().AddMacro(declaration);
                return(declaration);
            }
            catch (Exception e)
            {
                Messages.DisplayOkMessage("Could not create the macro file: " + info.Name + "\n" + e.Message, "Creation error");
            }

            return(null);
        }
示例#3
0
        public void Destroy()
        {
            FileDeclaration activeDoc = MainWindowViewModel.GetInstance().DockManager.GetActiveDocumentDeclaration();

            if (activeDoc != null)
            {
                Properties.Settings.Default.ActiveDocument = activeDoc.Info.FullName;
            }

            Properties.Settings.Default.IncludedLibraries = GetAssemblies().ToArray <AssemblyDeclaration>();

            if (MainWindowViewModel.GetInstance() != null)
            {
                MainWindowViewModel.GetInstance().SaveAll();
                List <DocumentViewModel> unsaved = MainWindowViewModel.GetInstance().DockManager.GetUnsavedDocuments();

                if (unsaved.Count > 0)
                {
                    Task <bool> save = GetInstance().DisplayYesNoMessageReturn("You have unsaved documents. Would you like to save them?", "Unsaved Documents");

                    save.Wait();
                    if (save.Result)
                    {
                        foreach (DocumentViewModel document in unsaved)
                        {
                            if (document is TextualEditorViewModel)
                            {
                                document.Save(null);
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Removes a macro from the hashset
        /// </summary>
        /// <param name="declaration">The macro the be removed</param>
        public void RemoveFile(FileDeclaration d)
        {
            m_Files.Remove(d);
            d.Remove();

            Events.InvokeEvent("OnMacroCountChanged");
        }
        /// <summary>
        /// Imports a macro
        /// </summary>
        /// <param name="parent">The parent item to which it'll be added</param>
        /// <param name="info">The directory in which to import it</param>
        public async void ImportMacro(DisplayableTreeViewItem parent, DirectoryInfo info)
        {
            FileDeclaration d = await MainWindowViewModel.GetInstance().ImportMacro(info);

            if (d == null)
            {
                return;
            }

            DisplayableTreeViewItem item = new DisplayableTreeViewItem();

            item.Header      = d.Name;
            item.IsFolder    = false;
            item.Declaration = d;

            item.RightClickEvent = TreeViewItem_OnPreviewMouseRightButtonDown;

            item.SelectedEvent    = delegate(object sender, RoutedEventArgs args) { SelectedItem = item; };
            item.DoubleClickEvent = delegate(object sender, MouseButtonEventArgs args) { OpenMacro(d); args.Handled = true; };

            if (parent == null)
            {
                item.Root = "/";
            }
            else
            {
                item.Root = parent.Root + "/" + parent.Header + "/";
            }

            Add(parent, item);

            OpenMacro(d);
        }
        /// <summary>
        /// Renames a macro
        /// </summary>
        /// <param name="declaration">The macro</param>
        /// <param name="newname">The macro's new name</param>
        public void RenameFile(FileDeclaration d, string newname)
        {
            d.Save();
            d.Rename(newname);
            d.Save();

            Events.InvokeEvent("OnMacroRenamed", d);
        }
        /// <summary>
        /// Identifies the type of macro and creates the respective document model
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static DocumentModel Create(FileDeclaration d)
        {
            if (d == null)
            {
                return(null);
            }

            return(new TextualEditorModel(d));
        }
示例#8
0
        /// <summary>
        /// Close the document associated with a macro ID
        /// </summary>
        /// <param name="d">The file declaration</param>
        public void CloseMacro(FileDeclaration d)
        {
            DocumentViewModel dvm = DockManager.GetDocument(d);

            if (dvm != null)
            {
                dvm.IsClosed = true;
            }
        }
        /// <summary>
        /// Gets an approp
        /// </summary>
        /// <param name="d">The file declaration</param>
        /// <returns>Default runtime for the file</returns>
        public string GetDefaultRuntime(FileDeclaration d)
        {
            HashSet <string> runtimes = GetRuntimes(GetLangaugeFromFileExt(d.Info.Extension));

            if (runtimes.Count > 0)
            {
                return(runtimes.First <string>());
            }

            return(GetDefaultRuntime());
        }
 /// <summary>
 /// Executes a macro, either directly or through the editor
 /// </summary>
 /// <param name="d">The file delcaration</param>
 /// <param name="async">Bool which indicates whether the execution should be asynchronous or not (synchronous)</param>
 public void ExecuteMacro(FileDeclaration d, bool async)
 {
     if (MainWindow.GetInstance().IsActive)
     {
         OpenMacro(d);
         MainWindowViewModel.GetInstance().ExecuteMacro(async);
     }
     else
     {
         MacroUI.GetInstance().TryExecuteFile(d, async);
     }
 }
示例#11
0
        /// <summary>
        /// Renames a macro and applies changes to UI
        /// </summary>
        /// <param name="d">The file declaration</param>
        /// <param name="newName">The new name of the macro</param>
        public void RenameMacro(FileDeclaration d, string newName)
        {
            MacroUI.GetInstance().RenameFile(d, newName);

            DocumentViewModel dvm = DockManager.GetDocument(d);

            if (dvm != null)
            {
                dvm.Title     = d.Info.Name;
                dvm.ContentId = d.Info.FullName;
            }
        }
示例#12
0
        /// <summary>
        /// Gets a document based on the macro id
        /// </summary>
        /// <param name="d">The file's declaration</param>
        /// <returns>DocumentViewModel of the macro</returns>
        public DocumentViewModel GetDocument(FileDeclaration d)
        {
            foreach (DocumentViewModel document in Documents)
            {
                if (document.Declaration == d)
                {
                    return(document);
                }
            }

            return(null);
        }
示例#13
0
        /// <summary>
        /// Export a macro
        /// </summary>
        private void ExportEvent()
        {
            if (DockManager.ActiveDocument == null)
            {
                return;
            }

            FileDeclaration macro = DockManager.ActiveDocument.Declaration;

            if (macro == null)
            {
                return;
            }

            macro.Export();
        }
示例#14
0
        /// <summary>
        /// Instantiation of TextualEditorModel
        /// </summary>
        /// <param name="id">The id of the editor's macro</param>
        public TextualEditorModel(FileDeclaration d)
        {
            if (d != null)
            {
                Title       = d.Info.Name;
                ToolTip     = d.Info.Name;
                ContentId   = d.Info.FullName;
                Declaration = d;
                IsClosed    = false;
                Source      = new TextDocument(d.Content);
                IsSaved     = true;
                return;
            }

            Source  = new TextDocument();
            IsSaved = false;
        }
        /// <summary>
        /// Deletes a macro and its displayable item
        /// </summary>
        /// <param name="item">The item to be deleted</param>
        /// <param name="macro">The macro attached to the item, to be deleted</param>
        public async void DeleteMacro(DisplayableTreeViewItem item, FileDeclaration macro)
        {
            bool result = await macro.Delete();

            if (result)
            {
                if (item.Parent is DisplayableTreeViewItem)
                {
                    Remove((item.Parent as DisplayableTreeViewItem), item);
                }
                else
                {
                    Remove(null, item);
                }

                CloseItemMacro(item);
            }
        }
示例#16
0
        //TODO: check if types match
        protected override void visitFileDeclaration(FileDeclaration declaration)
        {
            FileObject file = declaration.Objects[0];

            writer.Append(KeywordEnum.FILE.ToString()).Append(' ');
            writer.AppendIdentifiers(declaration.Objects, ", ");
            writer.Append(" : ");
            output.writeSubtypeIndication(file.Type);
            if (file.OpenKind != null)
            {
                writer.Append(' ').Append(KeywordEnum.OPEN.ToString()).Append(' ');
                output.writeExpression(file.OpenKind);
            }
            if (file.LogicalName != null)
            {
                writer.Append(' ').Append(KeywordEnum.IS.ToString()).Append(' ');
                output.writeExpression(file.LogicalName);
            }
            writer.Append(";").NewLine();
        }
示例#17
0
        /// <summary>
        /// Change which runtime is selected
        /// </summary>
        private void ActiveMacroChanged()
        {
            FileDeclaration d = DockManager.GetActiveDocumentDeclaration();

            if (d == null)
            {
                SelectedRuntime = RuntimeItems.FirstOrDefault <ComboBoxItem>();
                return;
            }

            string runtime = MacroUI.GetInstance().GetDefaultRuntime(d);

            foreach (ComboBoxItem item in RuntimeItems)
            {
                if (string.Equals((string)item.Tag, runtime, StringComparison.OrdinalIgnoreCase))
                {
                    SelectedRuntime = item;
                    return;
                }
            }
        }
示例#18
0
        /// <summary>
        /// Load avalondock layout, desearlize it and apply it
        /// </summary>
        private void LoadAvalonDockLayout()
        {
            if (MainWindow.GetInstance() == null)
            {
                return;
            }

            XmlLayoutSerializer serializer = new XmlLayoutSerializer(MainWindow.GetInstance().GetDockingManager());

            serializer.LayoutSerializationCallback += (s, args) => { args.Content = args.Content; };

            string layout = Properties.Settings.Default.AvalonLayout;

            if (String.IsNullOrEmpty(layout.Trim()))
            {
                return;
            }

            StringReader stringReader = new StringReader(layout);
            XmlReader    xmlReader    = XmlReader.Create(stringReader);

            serializer.Deserialize(xmlReader);

            xmlReader.Close();
            stringReader.Close();

            FileDeclaration d = MacroUI.GetInstance().GetDeclarationFromFullname(Properties.Settings.Default.ActiveDocument);

            if (d == null)
            {
                return;
            }

            DocumentViewModel dvm = DockManager.GetDocument(d);

            if (d != null)
            {
                ChangeActiveDocument(dvm);
            }
        }
示例#19
0
        /// <summary>
        /// Prompts the user to select an external macro and imports it into the local workspace
        /// </summary>
        /// <param name="info">The directory which the macro will be copied to</param>
        public static async Task <FileDeclaration> ImportFile(DirectoryInfo info)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                //MacroEngine.FireShowFocusEvent();
                Events.InvokeEvent("ShowFocusEvent");

                string fullpath = Files.FullPath(info.FullName, ofd.SafeFileName);

                FileInfo fi = new FileInfo(fullpath);

                if (fi.Exists)
                {
                    bool result = await Messages.DisplayYesNoMessage("This file already exists, would you like to replace it?", "File Overwrite");

                    if (!result)
                    {
                        return(null);
                    }
                }

                if (!fi.Directory.Exists)
                {
                    fi.Directory.Create();
                }

                File.Copy(ofd.FileName, fullpath, true);

                FileDeclaration declaration = new FileDeclaration(fi, LoadFile(fi));

                //MacroEngine.GetInstance().AddMacro(declaration);
                return(declaration);
            }

            //MacroEngine.FireShowFocusEvent();
            Events.InvokeEvent("ShowFocusEvent");
            return(null);
        }
        /// <summary>
        /// Execute the macro using the source saved in macro
        /// </summary>
        /// <param name="async">Bool identifying if the macro should be execute asynchronously or not (synchronous)</param>
        /// <param name="runtime">Runtime tag identifying which execution engine to use, if empty, a default will be chosen</param>
        public async Task <bool> TryExecuteFile(FileDeclaration d, bool async, string runtime = "")
        {
            d.Save();

            if (string.IsNullOrEmpty(runtime))
            {
                runtime = GetDefaultRuntime();
            }

            IExecutionEngine engine = GetExecutionEngine(runtime);

            if (engine == null)
            {
                engine = GetExecutionEngine(GetDefaultRuntime());
            }

            if (engine == null)
            {
                return(false);
            }

            return(await engine.ExecuteMacro(d.Content, async, d.Info != null?d.Info.Directory.FullName : ""));
        }
示例#21
0
        /// <summary>
        /// Opens a document for editing from the id of a macro
        /// </summary>
        /// <param name="d">The file declaration</param>
        public void OpenMacroForEditing(FileDeclaration d)
        {
            if (d == null)
            {
                return;
            }

            DocumentViewModel dvm = DockManager.GetDocument(d);

            if (dvm != null)
            {
                DockManager.ActiveContent = dvm;
                return;
            }

            DocumentModel model = DocumentModel.Create(d);

            if (model != null)
            {
                DocumentViewModel viewModel = DocumentViewModel.Create(model);
                DockManager.AddDocument(viewModel);
                ChangeActiveDocument(viewModel);
            }
        }
示例#22
0
 public string GetDefaultRuntime(FileDeclaration d)
 {
     return(MacroEngine.GetDefaultRuntime(d));
 }
示例#23
0
 public void RenameFile(FileDeclaration d, string newName)
 {
     MacroEngine.RenameFile(d, newName);
 }
示例#24
0
 public override void Visit(FileDeclaration node) { this.action(node); }
示例#25
0
            public List <object> GetLocalListOfObjects()
            {
                List <object> res = new List <object>();

                foreach (E declaration in this)
                {
                    if (declaration is EnumerationType)
                    {
                        EnumerationType type = declaration as EnumerationType;
                        res.Add(type);


                        //TODO: support overloading
                        foreach (EnumerationLiteral literal in type.Literals)
                        {
                            res.Add(literal);
                        }
                    }
                    else if (declaration is RecordType)
                    {
                        RecordType type = declaration as RecordType;
                        res.Add(type);
                        foreach (VHDL.type.RecordType.ElementDeclaration el in type.Elements)
                        {
                            foreach (string name in el.Identifiers)
                            {
                                res.Add(name);
                            }
                        }
                    }
                    else if (declaration is PhysicalType)
                    {
                        PhysicalType type = declaration as PhysicalType;
                        res.Add(type);
                        res.Add(new PhysicalLiteral(null, type.PrimaryUnit, declaration as PhysicalType));

                        foreach (PhysicalType.Unit unit in type.Units)
                        {
                            res.Add(unit.Identifier);
                        }
                    }
                    else if (declaration is NamedEntity)
                    {
                        INamedEntity identElement = (NamedEntity)declaration;
                        res.Add(declaration);
                    }
                    else if (declaration is SignalDeclaration)
                    {
                        SignalDeclaration objDecl = declaration as SignalDeclaration;
                        foreach (var o in objDecl.Objects)
                        {
                            res.Add(o);
                        }
                    }
                    else if (declaration is ConstantDeclaration)
                    {
                        ConstantDeclaration objDecl = declaration as ConstantDeclaration;
                        foreach (var o in objDecl.Objects)
                        {
                            res.Add(o);
                        }
                    }
                    else if (declaration is VariableDeclaration)
                    {
                        VariableDeclaration objDecl = declaration as VariableDeclaration;
                        foreach (var o in objDecl.Objects)
                        {
                            res.Add(o);
                        }
                    }
                    else if (declaration is FileDeclaration)
                    {
                        FileDeclaration objDecl = declaration as FileDeclaration;
                        foreach (var o in objDecl.Objects)
                        {
                            res.Add(o);
                        }
                    }
                    else if (declaration is Alias)
                    {
                        res.Add(declaration);
                    }
                    else if (declaration is Subtype)
                    {
                        res.Add(declaration);
                    }
                    else if (declaration is UseClause)
                    {
                        UseClause use = declaration as UseClause;
                        res.AddRange(use.Scope.GetLocalListOfObjects());
                    }
                    else if (declaration.GetType().BaseType == typeof(ObjectDeclaration <>))
                    {
                        ObjectDeclaration <VhdlObject> objDecl = declaration as ObjectDeclaration <VhdlObject>;
                        foreach (VhdlObject o in objDecl.Objects)
                        {
                            res.Add(o);
                        }
                    }
                }
                return(res);
            }
示例#26
0
            public object Resolve(string identifier)
            {
                foreach (E declaration in this)
                {
                    if (declaration is EnumerationType)
                    {
                        EnumerationType type = declaration as EnumerationType;
                        if (identifier.EqualsIdentifier(type.Identifier))
                        {
                            return(type);
                        }

                        //TODO: support overloading
                        foreach (EnumerationLiteral literal in type.Literals)
                        {
                            if (identifier.EqualsIdentifier(literal.ToString()))
                            {
                                return(literal);
                            }
                        }
                    }
                    else if (declaration is RecordType)
                    {
                        RecordType type = declaration as RecordType;
                        if (identifier.EqualsIdentifier(type.Identifier))
                        {
                            return(type);
                        }
                        foreach (VHDL.type.RecordType.ElementDeclaration el in type.Elements)
                        {
                            foreach (string name in el.Identifiers)
                            {
                                if (identifier.EqualsIdentifier(name))
                                {
                                    return(new Variable(name, el.Type));
                                }
                            }
                        }
                    }
                    else if (declaration is PhysicalType)
                    {
                        PhysicalType type = declaration as PhysicalType;
                        if (identifier.EqualsIdentifier(type.Identifier))
                        {
                            return(type);
                        }

                        //TODO: don't use strings for the physical literals
                        if (identifier.EqualsIdentifier(type.PrimaryUnit))
                        {
                            return(new PhysicalLiteral(null, type.PrimaryUnit, declaration as PhysicalType));
                        }

                        foreach (PhysicalType.Unit unit in type.Units)
                        {
                            if (identifier.EqualsIdentifier(unit.Identifier))
                            {
                                return(new PhysicalLiteral(null, unit.Identifier, declaration as PhysicalType));
                            }
                        }
                    }
                    else if (declaration is NamedEntity)
                    {
                        INamedEntity identElement = (NamedEntity)declaration;
                        if (identifier.EqualsIdentifier(identElement.Identifier))
                        {
                            return(declaration);
                        }
                    }
                    else if (declaration is SignalDeclaration)
                    {
                        SignalDeclaration objDecl = declaration as SignalDeclaration;
                        foreach (var o in objDecl.Objects)
                        {
                            if (o.Identifier.EqualsIdentifier(identifier))
                            {
                                return(o);
                            }
                        }
                    }
                    else if (declaration is ConstantDeclaration)
                    {
                        ConstantDeclaration objDecl = declaration as ConstantDeclaration;
                        foreach (var o in objDecl.Objects)
                        {
                            if (o.Identifier.EqualsIdentifier(identifier))
                            {
                                return(o);
                            }
                        }
                    }
                    else if (declaration is VariableDeclaration)
                    {
                        VariableDeclaration objDecl = declaration as VariableDeclaration;
                        foreach (var o in objDecl.Objects)
                        {
                            if (o.Identifier.EqualsIdentifier(identifier))
                            {
                                return(o);
                            }
                        }
                    }
                    else if (declaration is FileDeclaration)
                    {
                        FileDeclaration objDecl = declaration as FileDeclaration;
                        foreach (var o in objDecl.Objects)
                        {
                            if (o.Identifier.EqualsIdentifier(identifier))
                            {
                                return(o);
                            }
                        }
                    }
                    else if (declaration is Alias)
                    {
                        Alias objDecl = declaration as Alias;
                        if (objDecl.Designator.EqualsIdentifier(identifier))
                        {
                            return(objDecl.Aliased);//new Variable(objDecl.Aliased, objDecl.SubtypeIndication);
                        }
                    }
                    else if (declaration is Subtype)
                    {
                        Subtype objDecl = declaration as Subtype;
                        if (objDecl.Identifier.EqualsIdentifier(identifier))
                        {
                            return(objDecl);
                        }
                    }
                    else if (declaration is UseClause)
                    {
                        UseClause use = declaration as UseClause;
                        object    res = use.Scope.resolve(identifier);
                        if (res != null)
                        {
                            return(res);
                        }
                    }
                    else if (declaration.GetType().BaseType == typeof(ObjectDeclaration <>))
                    {
                        ObjectDeclaration <VhdlObject> objDecl = declaration as ObjectDeclaration <VhdlObject>;
                        foreach (VhdlObject o in objDecl.Objects)
                        {
                            if (o.Identifier.EqualsIdentifier(identifier))
                            {
                                return(o);
                            }
                        }
                    }
                }

                return(null);
            }
 public override void ExplicitVisit(FileDeclaration fragment)
 {
     _fragments.Add(fragment);
 }
示例#28
0
 public async Task <bool> TryExecuteFile(FileDeclaration d, bool async, string runtime = "")
 {
     return(await MacroEngine.TryExecuteFile(d, async, runtime));
 }
        /// <summary>
        /// Creates a contextmenu for a tree view item file
        /// </summary>
        /// <param name="item">The item for which the context menu is being made</param>
        /// <param name="name">The name of the macro</param>
        /// <param name="id">The id of the macro</param>
        /// <returns>File TreeViewItem ContextMenu</returns>
        private ContextMenu CreateContextMenuMacro(DisplayableTreeViewItem item, string name, FileDeclaration d)
        {
            Style ContextMenuStyle = MainWindow.GetInstance().GetResource("MetroContextMenuStyle") as Style;
            Style MenuItemStyle    = MainWindow.GetInstance().GetResource("MetroMenuItemStyle") as Style;
            Style SeparatorStyle   = MainWindow.GetInstance().GetResource("MertoMenuSeparatorStyle") as Style;

            ContextMenu cm = new ContextMenu();

            cm.Resources.MergedDictionaries.Add(MainWindow.GetInstance().GetResources());
            cm.Style = ContextMenuStyle;

            DisplayableTreeViewItem parentitem = item.Parent;

            if (d == null)
            {
                MacroUI.GetInstance().DisplayOkMessage("Could not get the macro (when attempting to create a context menu): " + name, "Macro Error");
                return(null);
            }

            MenuItem mi_edit = new MenuItem();

            mi_edit.Header = "Edit";
            mi_edit.Click += delegate(object sender, RoutedEventArgs args)
            {
                OpenMacro(d);
                args.Handled = true;
                cm.IsOpen    = false;
            };
            mi_edit.Style = MenuItemStyle as Style;
            cm.Items.Add(mi_edit);

            MenuItem mi_execute = new MenuItem();

            mi_execute.Header  = "Synchronous Execute";
            mi_execute.ToolTip = "Synchronous executions cannot be terminated.";
            mi_execute.Click  += delegate(object sender, RoutedEventArgs args)
            {
                ExecuteMacro(d, false);
                args.Handled = true;
                cm.IsOpen    = false;
            };
            mi_execute.Style = MenuItemStyle as Style;
            cm.Items.Add(mi_execute);

            MenuItem mi_executea = new MenuItem();

            mi_executea.Header  = "Asynchronous Execute";
            mi_executea.ToolTip = "Asynchronous executions can be terminated.";
            mi_executea.Click  += delegate(object sender, RoutedEventArgs args)
            {
                ExecuteMacro(d, true);
                args.Handled = true;
                cm.IsOpen    = false;
            };
            mi_executea.Style = MenuItemStyle as Style;
            cm.Items.Add(mi_executea);

            Separator sep1 = new Separator();

            sep1.Style = SeparatorStyle as Style;
            cm.Items.Add(sep1);

            MenuItem mi_export = new MenuItem();

            mi_export.Header = "Export";
            mi_export.Click += delegate(object sender, RoutedEventArgs args)
            {
                d.Export();
                args.Handled = true;
                cm.IsOpen    = false;
            };
            mi_export.Style = MenuItemStyle as Style;
            cm.Items.Add(mi_export);

            MenuItem mi_del = new MenuItem();

            mi_del.Header = "Delete";
            mi_del.Click += delegate(object sender, RoutedEventArgs args)
            {
                DeleteMacro(item, d);

                args.Handled = true;
                cm.IsOpen    = false;
            };
            mi_del.Style = MenuItemStyle as Style;
            cm.Items.Add(mi_del);

            MenuItem mi_rename = new MenuItem();

            mi_rename.Header = "Rename";
            mi_rename.Click += delegate(object sender, RoutedEventArgs args)
            {
                args.Handled = true;
                cm.IsOpen    = false;

                string previousname = item.Header;

                item.KeyUpEvent = delegate(object s, KeyEventArgs a)
                {
                    if (a.Key == Key.Return)
                    {
                        Focus();
                        Keyboard.ClearFocus();
                    }
                    else if (a.Key == Key.Escape)
                    {
                        item.Header = previousname;
                        Focus();
                        Keyboard.ClearFocus();
                    }
                };

                item.FocusLostEvent = delegate(object s, RoutedEventArgs a)
                {
                    if (item.Header == previousname)
                    {
                        item.IsInputting = false;
                        return;
                    }

                    if (String.IsNullOrEmpty(item.Header))
                    {
                        MacroUI.GetInstance().DisplayOkMessage("Please enter a valid name.", "Invalid Name");
                        item.IsInputting = true;
                        return;
                    }

                    if (!Path.HasExtension(item.Header))
                    {
                        item.Header += MacroUI.GetInstance().GetDefaultFileExtension();
                    }


                    MainWindowViewModel.GetInstance().RenameMacro(d, item.Header);
                    Rename(parentitem, item);

                    item.IsInputting = false;
                };

                item.IsInputting = true;
            };
            mi_rename.Style = MenuItemStyle as Style;
            cm.Items.Add(mi_rename);

            Separator sep2 = new Separator();

            sep2.Style = SeparatorStyle;
            cm.Items.Add(sep2);

            return(cm);
        }
        /// <summary>
        /// Adds a macro to the hashset
        /// </summary>
        /// <param name="declaration">The macro to be added</param>
        public void AddFile(FileDeclaration d)
        {
            m_Files.Add(d);

            Events.InvokeEvent("OnMacroCountChanged");
        }
 /// <summary>
 /// Opens a macro in the document for editing
 /// </summary>
 /// <param name="d">The file declaration</param>
 public void OpenMacro(FileDeclaration d)
 {
     MainWindowViewModel.GetInstance().OpenMacroForEditing(d);
 }
        /// <summary>
        /// Creates macro
        /// </summary>
        /// <param name="parent">The parent item to which it'll be added</param>
        /// <param name="root">The root of the item's relative future directory</param>
        /// <param name="OnReturn">The Action, and resulting file declaration of the created macro, to be fired when the task is completed</param>
        public void CreateMacro(DisplayableTreeViewItem parent, string root, Action <FileDeclaration> OnReturn)
        {
            if (m_IsCreating)
            {
                return;
            }

            m_IsCreating = true;

            DisplayableTreeViewItem item = new DisplayableTreeViewItem();

            item.KeyUpEvent = delegate(object s, KeyEventArgs a)
            {
                if (a.Key == Key.Return)
                {
                    Focus();
                    Keyboard.ClearFocus();
                }
                else if (a.Key == Key.Escape)
                {
                    m_IsCreating     = false;
                    item.IsInputting = false;
                }
            };

            item.FocusLostEvent = delegate(object s, RoutedEventArgs a)
            {
                if (String.IsNullOrEmpty(item.Header) || (!item.IsInputting))
                {
                    Remove(parent, item);
                    m_IsCreating = false;
                    return;
                }

                if (!Path.HasExtension(item.Header))
                {
                    item.Header += MacroUI.GetInstance().GetDefaultFileExtension();
                }

                item.Header = Regex.Replace(item.Header, "[^0-9a-zA-Z ._-]", "");

                FileInfo        info = new FileInfo(Files.FullPathMacro(Files.FullPath(root, item.Header)));
                FileDeclaration d    = MainWindowViewModel.GetInstance().CreateMacro(info);

                Rename(parent, item);

                if (d == null)
                {
                    Remove(parent, item);
                    m_IsCreating = false;
                    return;
                }

                item.Header      = d.Name;
                item.Declaration = d;
                item.Root        = root;
                item.Parent      = parent;
                item.IsFolder    = false;

                item.RightClickEvent = TreeViewItem_OnPreviewMouseRightButtonDown;

                item.SelectedEvent    = delegate(object sender, RoutedEventArgs args) { SelectedItem = item; };
                item.DoubleClickEvent = delegate(object sender, MouseButtonEventArgs args) { OpenMacro(d); args.Handled = true; };

                item.IsInputting = false;

                m_IsCreating = false;
                OnReturn?.Invoke(d);
                OpenMacro(d);
            };

            Add(parent, item);

            item.IsInputting = true;
        }