示例#1
0
        void SaveAs()
        {
            SaveAsCommand = new CommandBase((parameter, e) =>
            {
                bool isEncrypted = parameter != null && parameter.ToString() == "Secure";

                var tab = Model.Window.TabControl?.SelectedItem as TabItem;
                if (tab == null)
                {
                    return;
                }
                var doc = tab.Tag as MarkdownDocumentEditor;
                if (doc == null)
                {
                    return;
                }

                var filename = doc.MarkdownDocument.Filename;
                var folder   = Path.GetDirectoryName(doc.MarkdownDocument.Filename);

                if (filename == "untitled")
                {
                    folder = mmApp.Configuration.LastFolder;

                    var match = Regex.Match(doc.GetMarkdown(), @"^# (\ *)(?<Header>.+)", RegexOptions.Multiline);

                    if (match.Success)
                    {
                        filename = match.Groups["Header"].Value;
                        if (!string.IsNullOrEmpty(filename))
                        {
                            filename = FileUtils.SafeFilename(filename);
                        }
                    }
                }

                if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder))
                {
                    folder = mmApp.Configuration.LastFolder;
                    if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder))
                    {
                        folder = KnownFolders.GetPath(KnownFolder.Libraries);
                    }
                }


                SaveFileDialog sd = new SaveFileDialog
                {
                    FilterIndex      = 1,
                    InitialDirectory = folder,
                    FileName         = filename,
                    CheckFileExists  = false,
                    OverwritePrompt  = true,
                    CheckPathExists  = true,
                    RestoreDirectory = true
                };

                var mdcryptExt = string.Empty;
                if (isEncrypted)
                {
                    mdcryptExt = "Secure Markdown files (*.mdcrypt)|*.mdcrypt|";
                }

                sd.Filter =
                    $"{mdcryptExt}Markdown files (*.md)|*.md|Markdown files (*.markdown)|*.markdown|All files (*.*)|*.*";

                bool?result = null;
                try
                {
                    result = sd.ShowDialog();
                }
                catch (Exception ex)
                {
                    mmApp.Log("Unable to save file: " + doc.MarkdownDocument.Filename, ex);
                    MessageBox.Show(
                        $@"Unable to open file:\r\n\r\n" + ex.Message,
                        "An error occurred trying to open a file",
                        MessageBoxButton.OK,
                        MessageBoxImage.Error);
                }

                if (!isEncrypted)
                {
                    doc.MarkdownDocument.Password = null;
                }
                else
                {
                    var pwdDialog = new FilePasswordDialog(doc.MarkdownDocument, false)
                    {
                        Owner = Model.Window
                    };
                    bool?pwdResult = pwdDialog.ShowDialog();
                }

                if (result != null && result.Value)
                {
                    doc.MarkdownDocument.Filename = sd.FileName;
                    if (!doc.SaveDocument())
                    {
                        MessageBox.Show(Model.Window,
                                        $"{sd.FileName}\r\n\r\nThis document can't be saved in this location. The file is either locked or you don't have permissions to save it. Please choose another location to save the file.",
                                        "Unable to save Document", MessageBoxButton.OK, MessageBoxImage.Warning);
                        SaveAsCommand.Execute(tab);
                        return;
                    }
                    mmApp.Configuration.LastFolder = Path.GetDirectoryName(sd.FileName);
                }

                Model.Window.SetWindowTitle();
                Model.Window.PreviewMarkdown(doc, keepScrollPosition: true);
            }, (s, e) =>
            {
                if (Model.ActiveDocument == null)
                {
                    return(false);
                }

                return(true);
            });
        }
示例#2
0
        private void CreateCommands()
        {
            // SAVE COMMAND
            SaveCommand = new CommandBase((s, e) =>
            {
                var tab = Window.TabControl?.SelectedItem as TabItem;
                if (tab == null)
                {
                    return;
                }
                var doc = tab.Tag as MarkdownDocumentEditor;

                if (doc.MarkdownDocument.Filename == "untitled")
                {
                    SaveAsCommand.Execute(tab);
                }
                else if (!doc.SaveDocument())
                {
                    SaveAsCommand.Execute(tab);
                }

                Window.PreviewMarkdown(doc, keepScrollPosition: true);
            }, (s, e) =>
            {
                if (ActiveDocument == null)
                {
                    return(false);
                }

                return(this.ActiveDocument.IsDirty);
            });

            // SAVEAS COMMAND
            SaveAsCommand = new CommandBase((s, e) =>
            {
                var tab = Window.TabControl?.SelectedItem as TabItem;
                if (tab == null)
                {
                    return;
                }
                var doc = tab.Tag as MarkdownDocumentEditor;
                if (doc == null)
                {
                    return;
                }

                var filename = doc.MarkdownDocument.Filename;

                var folder = Path.GetDirectoryName(doc.MarkdownDocument.Filename);
                if (filename == "untitled")
                {
                    folder = mmApp.Configuration.LastFolder;

                    var match = Regex.Match(doc.GetMarkdown(), @"^# (\ *)(?<Header>.+)", RegexOptions.Multiline);

                    if (match.Success)
                    {
                        filename = match.Groups["Header"].Value;
                        if (!string.IsNullOrEmpty(filename))
                        {
                            filename = mmFileUtils.SafeFilename(filename);
                        }
                    }
                }

                if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder))
                {
                    folder = mmApp.Configuration.LastFolder;
                    if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder))
                    {
                        folder = KnownFolders.GetPath(KnownFolder.Libraries);
                    }
                }

                SaveFileDialog sd = new SaveFileDialog
                {
                    Filter           = "Markdown files (*.md)|*.md|Markdown files (*.markdown)|*.markdown|All files (*.*)|*.*",
                    FilterIndex      = 1,
                    InitialDirectory = folder,
                    FileName         = filename,
                    CheckFileExists  = false,
                    OverwritePrompt  = false,
                    CheckPathExists  = true,
                    RestoreDirectory = true
                };

                bool?result = null;
                try
                {
                    result = sd.ShowDialog();
                }
                catch (Exception ex)
                {
                    mmApp.Log("Unable to save file: " + doc.MarkdownDocument.Filename, ex);
                    MessageBox.Show(
                        $@"Unable to open file:\r\n\r\n" + ex.Message,
                        "An error occurred trying to open a file",
                        MessageBoxButton.OK,
                        MessageBoxImage.Error);
                }


                if (result != null && result.Value)
                {
                    doc.MarkdownDocument.Filename = sd.FileName;
                    if (!doc.SaveDocument())
                    {
                        MessageBox.Show(Window, $"{sd.FileName}\r\n\r\nThis document can't be saved in this location. The file is either locked or you don't have permissions to save it. Please choose another location to save the file.",
                                        "Unable to save Document", MessageBoxButton.OK, MessageBoxImage.Warning);
                        SaveAsCommand.Execute(tab);
                        return;
                    }
                }

                mmApp.Configuration.LastFolder = folder;

                Window.SetWindowTitle();
                Window.PreviewMarkdown(doc, keepScrollPosition: true);
            }, (s, e) =>
            {
                if (ActiveDocument == null)
                {
                    return(false);
                }

                return(true);
            });

            // SAVEASHTML COMMAND
            SaveAsHtmlCommand = new CommandBase((s, e) =>
            {
                var tab = Window.TabControl?.SelectedItem as TabItem;
                var doc = tab?.Tag as MarkdownDocumentEditor;
                if (doc == null)
                {
                    return;
                }

                var folder = Path.GetDirectoryName(doc.MarkdownDocument.Filename);

                SaveFileDialog sd = new SaveFileDialog
                {
                    Filter           = "Html files (Html only) (*.html)|*.html|Html files (Html and dependencies in a folder)|*.html",
                    FilterIndex      = 1,
                    InitialDirectory = folder,
                    FileName         = Path.ChangeExtension(doc.MarkdownDocument.Filename, "html"),
                    CheckFileExists  = false,
                    OverwritePrompt  = false,
                    CheckPathExists  = true,
                    RestoreDirectory = true
                };

                bool?result = null;
                try
                {
                    result = sd.ShowDialog();
                }catch (Exception ex)
                {
                    mmApp.Log("Unable to save html file: " + doc.MarkdownDocument.Filename, ex);
                    MessageBox.Show(
                        $@"Unable to open file:\r\n\r\n" + ex.Message,
                        "An error occurred trying to open a file",
                        MessageBoxButton.OK,
                        MessageBoxImage.Error);
                }

                if (result != null && result.Value)
                {
                    if (sd.FilterIndex != 2)
                    {
                        var html = doc.RenderMarkdown(doc.GetMarkdown(), mmApp.Configuration.MarkdownOptions.RenderLinksAsExternal);

                        if (!doc.MarkdownDocument.WriteFile(sd.FileName, html))
                        {
                            MessageBox.Show(Window,
                                            $"{sd.FileName}\r\n\r\nThis document can't be saved in this location. The file is either locked or you don't have permissions to save it. Please choose another location to save the file.",
                                            "Unable to save Document", MessageBoxButton.OK, MessageBoxImage.Warning);
                            SaveAsHtmlCommand.Execute(null);
                            return;
                        }
                    }
                    else
                    {
                        string msg   = @"This feature is not available yet.

For now, you can use 'View in Web Browser' to view the document in your favorite Web Browser and use 'Save As...' to save the Html document with all CSS and Image dependencies.

Do you want to View in Browser now?
";
                        var mbResult = MessageBox.Show(msg,
                                                       mmApp.ApplicationName,
                                                       MessageBoxButton.YesNo,
                                                       MessageBoxImage.Asterisk,
                                                       MessageBoxResult.Yes);

                        if (mbResult == MessageBoxResult.Yes)
                        {
                            Window.ButtonViewInBrowser_Click(Window, null);
                        }
                    }
                }

                Window.PreviewMarkdown(doc, keepScrollPosition: true);
            }, (s, e) =>
            {
                if (ActiveDocument == null || ActiveEditor == null)
                {
                    return(false);
                }
                if (ActiveDocument.Filename == "untitled")
                {
                    return(true);
                }
                if (ActiveEditor.EditorSyntax != "markdown")
                {
                    return(false);
                }

                return(true);
            });

            // NEW DOCUMENT COMMAND (ctrl-n)
            NewDocumentCommand = new CommandBase((s, e) =>
            {
                Window.OpenTab("untitled");
            });

            // OPEN DOCUMENT COMMAND
            OpenDocumentCommand = new CommandBase((s, e) =>
            {
                var fd = new OpenFileDialog
                {
                    DefaultExt = ".md",
                    Filter     = "Markdown files (*.md,*.markdown)|*.md;*.markdown|" +
                                 "Html files (*.htm,*.html)|*.htm;*.html|" +
                                 "Javascript files (*.js)|*.js|" +
                                 "Typescript files (*.ts)|*.ts|" +
                                 "Json files (*.json)|*.json|" +
                                 "Css files (*.css)|*.css|" +
                                 "Xml files (*.xml,*.config)|*.xml;*.config|" +
                                 "C# files (*.cs)|*.cs|" +
                                 "C# Razor files (*.cshtml)|*.cshtml|" +
                                 "Foxpro files (*.prg)|*.prg|" +
                                 "Powershell files (*.ps1)|*.ps1|" +
                                 "Php files (*.php)|*.php|" +
                                 "Python files (*.py)|*.py|" +
                                 "All files (*.*)|*.*",
                    CheckFileExists  = true,
                    RestoreDirectory = true,
                    Multiselect      = true,
                    Title            = "Open Markdown File"
                };

                if (!string.IsNullOrEmpty(mmApp.Configuration.LastFolder))
                {
                    fd.InitialDirectory = mmApp.Configuration.LastFolder;
                }

                bool?res = null;
                try
                {
                    res = fd.ShowDialog();
                }
                catch (Exception ex)
                {
                    mmApp.Log("Unable to open file.", ex);
                    MessageBox.Show(
                        $@"Unable to open file:\r\n\r\n" + ex.Message,
                        "An error occurred trying to open a file",
                        MessageBoxButton.OK,
                        MessageBoxImage.Error);
                    return;
                }
                if (res == null || !res.Value)
                {
                    return;
                }

                foreach (var file in fd.FileNames)
                {
                    Window.OpenTab(file, rebindTabHeaders: true);
                    Window.AddRecentFile(file);
                }
            });

            CloseActiveDocumentCommand = new CommandBase((s, e) =>
            {
                var tab = Window.TabControl.SelectedItem as TabItem;
                if (tab == null)
                {
                    return;
                }

                if (Window.CloseTab(tab))
                {
                    Window.TabControl.Items.Remove(tab);
                }
            }, (s, e) => IsEditorActive)
            {
                Caption = "_Close Document",
                ToolTip = "Closes the active tab and asks to save the document."
            };


            // PREVIEW BUTTON COMMAND
            PreviewBrowserCommand = new CommandBase((s, e) =>
            {
                var tab = Window.TabControl.SelectedItem as TabItem;
                if (tab == null)
                {
                    return;
                }

                var editor = tab.Tag as MarkdownDocumentEditor;

                Configuration.IsPreviewVisible = IsPreviewBrowserVisible;

                if (!IsPreviewBrowserVisible && IsPresentationMode)
                {
                    PresentationModeCommand.Execute(null);
                }


                Window.ShowPreviewBrowser(!IsPreviewBrowserVisible);
                if (IsPreviewBrowserVisible)
                {
                    Window.PreviewMarkdown(editor);
                }
            }, null);

            // MARKDOWN EDIT COMMANDS TOOLBAR COMMAND
            ToolbarInsertMarkdownCommand = new CommandBase((s, e) =>
            {
                string action = s as string;

                var editor = Window.GetActiveMarkdownEditor();
                editor?.ProcessEditorUpdateCommand(action);
            }, null);

            // Settings
            SettingsCommand = new CommandBase((s, e) =>
            {
                var file = Path.Combine(mmApp.Configuration.CommonFolder, "MarkdownMonster.json");

                // save settings first so we're looking at current setting
                Configuration.Write();

                string fileText = File.ReadAllText(file);
                if (!fileText.StartsWith("//"))
                {
                    fileText = "// Reference: http://markdownmonster.west-wind.com/docs/_4nk01yq6q.htm\r\n" +
                               fileText;
                    File.WriteAllText(file, fileText);
                }

                Window.OpenTab(file, syntax: "json");
            }, null);

            // DISTRACTION FREE MODE
            DistractionFreeModeCommand = new CommandBase((s, e) =>
            {
                GridLength glToolbar = new GridLength(0);
                GridLength glMenu    = new GridLength(0);
                GridLength glStatus  = new GridLength(0);

                if (Window.WindowGrid.RowDefinitions[1].Height == glToolbar)
                {
                    glToolbar = new GridLength(30);
                    glMenu    = new GridLength(25);
                    glStatus  = new GridLength(30);

                    mmApp.Configuration.WindowPosition.TabHeadersVisible = Visibility.Visible;

                    IsPreviewBrowserVisible = true;
                    Window.PreviewMarkdown();

                    Window.WindowState = mmApp.Configuration.WindowPosition.WindowState;

                    IsFullScreen = false;
                }
                else
                {
                    var tokens = mmApp.Configuration.DistractionFreeModeHideOptions.ToLower().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);


                    if (tokens.All(d => d != "menu"))
                    {
                        glMenu = new GridLength(25);
                    }

                    if (tokens.All(d => d != "toolbar"))
                    {
                        glToolbar = new GridLength(30);
                    }

                    if (tokens.All(d => d != "statusbar"))
                    {
                        glStatus = new GridLength(30);
                    }

                    if (tokens.Any(d => d == "tabs"))
                    {
                        mmApp.Configuration.WindowPosition.TabHeadersVisible = Visibility.Hidden;
                    }

                    if (tokens.Any(d => d == "preview"))
                    {
                        IsPreviewBrowserVisible = false;
                        Window.ShowPreviewBrowser(hide: true);
                    }

                    mmApp.Configuration.WindowPosition.WindowState = Window.WindowState;
                    if (tokens.Any(d => d == "maximized"))
                    {
                        Window.WindowState = WindowState.Maximized;
                    }

                    IsFullScreen = true;
                }

                // toolbar
                Window.WindowGrid.RowDefinitions[0].Height = glMenu;
                Window.WindowGrid.RowDefinitions[1].Height = glToolbar;
                Window.WindowGrid.RowDefinitions[3].Height = glStatus;
            }, null);

            // PRESENTATION MODE
            PresentationModeCommand = new CommandBase((s, e) =>
            {
                if (IsFullScreen)
                {
                    DistractionFreeModeCommand.Execute(null);
                }

                GridLength gl = new GridLength(0);
                if (Window.WindowGrid.RowDefinitions[1].Height == gl)
                {
                    gl = new GridLength(30); // toolbar height

                    Window.MainWindowEditorColumn.Width    = new GridLength(1, GridUnitType.Star);
                    Window.MainWindowSeparatorColumn.Width = new GridLength(0);
                    Window.MainWindowPreviewColumn.Width   = new GridLength(mmApp.Configuration.WindowPosition.SplitterPosition);

                    Window.PreviewMarkdown();
                    IsPresentationMode = false;
                }
                else
                {
                    mmApp.Configuration.WindowPosition.SplitterPosition =
                        Convert.ToInt32(Window.MainWindowPreviewColumn.Width.Value);

                    // don't allow presentation mode for non-Markdown documents
                    var editor = Window.GetActiveMarkdownEditor();
                    if (editor != null)
                    {
                        var file = editor.MarkdownDocument.Filename.ToLower();
                        var ext  = Path.GetExtension(file);
                        if (file != "untitled" && ext != ".md" && ext != ".htm" && ext != ".html")
                        {
                            // don't allow presentation mode for non markdown files
                            IsPresentationMode      = false;
                            IsPreviewBrowserVisible = false;
                            Window.ShowPreviewBrowser(true);
                            return;
                        }
                    }

                    Window.ShowPreviewBrowser();

                    Window.MainWindowEditorColumn.Width    = gl;
                    Window.MainWindowSeparatorColumn.Width = gl;
                    Window.MainWindowPreviewColumn.Width   = new GridLength(1, GridUnitType.Star);

                    IsPresentationMode      = true;
                    IsPreviewBrowserVisible = true;
                }

                Window.WindowGrid.RowDefinitions[1].Height = gl;
                //Window.WindowGrid.RowDefinitions[3].Height = gl;
            }, null);

            // PRINT PREVIEW
            PrintPreviewCommand = new CommandBase((s, e) =>
            {
                dynamic dom = Window.PreviewBrowser.Document;
                dom.execCommand("print", true, null);
            }, (s, e) => IsPreviewBrowserVisible);
        }