コード例 #1
0
ファイル: AppModel.cs プロジェクト: Chukanof/MarkdownMonster
        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((parameter, e) =>
            {
                bool isEncrypted = parameter != null && parameter.ToString() == "Secure";

                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 (!isEncrypted)
                {
                    doc.MarkdownDocument.Password = null;
                }
                else
                {
                    var pwdDialog = new FilePasswordDialog(doc.MarkdownDocument, false)
                    {
                        Owner = Window
                    };
                    bool?pwdResult = pwdDialog.ShowDialog();
                }

                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)
                {
                    // TODO: Check AddRecentFile and make sure Tab Selection works
                    Window.OpenTab(file, rebindTabHeaders: true);
                    //Window.AddRecentFile(file);
                }
            });

            // CLOSE ACTIVE DOCUMENT COMMAND
            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);
                }
            }, null)
            {
                Caption = "_Close Document",
                ToolTip = "Closes the active tab and asks to save the document."
            };


            // COMMIT TO GIT Command
            CommitToGitCommand = new CommandBase(async(s, e) =>
            {
                string file = ActiveDocument?.Filename;
                if (string.IsNullOrEmpty(file))
                {
                    return;
                }

                Window.ShowStatus("Committing and pushing to Git...");
                WindowUtilities.DoEvents();

                string error = null;

                bool pushToGit = mmApp.Configuration.GitCommitBehavior == GitCommitBehaviors.CommitAndPush;
                bool result    = await Task.Run(() => mmFileUtils.CommitFileToGit(file, pushToGit, out error));

                if (result)
                {
                    Window.ShowStatus($"File {Path.GetFileName(file)} committed and pushed.", 6000);
                }
                else
                {
                    Window.ShowStatus(error, 7000);
                    Window.SetStatusIcon(FontAwesomeIcon.Warning, Colors.Red);
                }
            }, (s, e) => IsEditorActive);


            // 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);

            // SHOW FILE BROWSER COMMAND
            ShowFolderBrowserCommand = new CommandBase((s, e) =>
            {
                mmApp.Configuration.FolderBrowser.Visible = !mmApp.Configuration.FolderBrowser.Visible;

                mmApp.Model.Window.ShowFolderBrowser(!mmApp.Configuration.FolderBrowser.Visible);
            });

            // 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);

                GridLength glFileBrowser = new GridLength(0);



                if (Window.WindowGrid.RowDefinitions[1].Height == glToolbar)
                {
                    Window.SaveSettings();

                    glToolbar = GridLength.Auto;
                    glMenu    = GridLength.Auto;
                    glStatus  = GridLength.Auto;

                    //mmApp.Configuration.WindowPosition.IsTabHeaderPanelVisible = true;
                    Window.TabControl.IsHeaderPanelVisible = true;

                    IsPreviewBrowserVisible = true;
                    Window.PreviewMarkdown();

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

                    IsFullScreen = false;

                    Window.ShowFolderBrowser(!mmApp.Configuration.FolderBrowser.Visible);
                }
                else
                {
                    var tokens = mmApp.Configuration.DistractionFreeModeHideOptions.ToLower().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);


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

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

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

                    if (tokens.Any(d => d == "tabs"))
                    {
                        Window.TabControl.IsHeaderPanelVisible = false;
                    }

                    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;
                    }

                    Window.ShowFolderBrowser(true);

                    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 = GridLength.Auto; // 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();

                    Window.ShowFolderBrowser(!mmApp.Configuration.FolderBrowser.Visible);

                    IsPresentationMode = false;
                }
                else
                {
                    Window.SaveSettings();

                    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.ShowFolderBrowser(true);

                    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);

            // PDF GENERATION PREVIEW
            GeneratePdfCommand = new CommandBase((s, e) =>
            {
                var form = new GeneratePdfWindow()
                {
                    Owner = mmApp.Model.Window
                };
                form.Show();
            }, (s, e) => IsPreviewBrowserVisible);

            // F1 Help Command - Pass option CommandParameter="TopicId"
            HelpCommand = new CommandBase((topicId, e) =>
            {
                string url = mmApp.Urls.DocumentationBaseUrl;

                if (topicId != null)
                {
                    url = mmApp.GetDocumentionUrl(topicId as string);
                }

                ShellUtils.GoUrl(url);
            }, (s, e) => IsPreviewBrowserVisible);
        }
コード例 #2
0
        private async void Button_DownloadPosts_Click(object sender, RoutedEventArgs e)
        {
            WeblogInfo weblogInfo = Model.ActiveWeblogInfo;

            var wrapper = new MetaWeblogWrapper(weblogInfo.ApiUrl,
                                                weblogInfo.Username,
                                                weblogInfo.DecryptPassword(weblogInfo.Password),
                                                weblogInfo.BlogId);


            Model.Configuration.LastWeblogAccessed = weblogInfo.Name;

            Dispatcher.Invoke(() =>
            {
                Model.PostList = new List <Post>();
                SetStatusIcon(FontAwesomeIcon.Download, Colors.Orange, true);
                ShowStatus("Downloading last " + Model.NumberOfPostsToRetrieve + " posts...");
            });

            WindowUtilities.DoEvents();

            List <Post> posts = null;

            try
            {
                bool result = await Task.Run(() =>
                {
                    posts = wrapper.GetRecentPosts(Model.NumberOfPostsToRetrieve).ToList();
                    return(false);
                });
            }
            catch (XmlRpcException ex)
            {
                string message = ex.Message;
                if (message == "Not Found")
                {
                    message = "Invalid Blog API Url:\r\n" + weblogInfo.ApiUrl;
                }
                MessageBox.Show("Unable to download posts:\r\n" + message, mmApp.ApplicationName,
                                MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unable to download posts:\r\n" + ex.Message, mmApp.ApplicationName,
                                MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }


            for (int i = 0; i < posts.Count; i++)
            {
                var post = posts[i];
                post.mt_excerpt = StringUtils.TextAbstract(post.mt_excerpt, 220);
            }

            WindowUtilities.DoEvents();

            Dispatcher.Invoke(() =>
            {
                ShowStatus(posts.Count + " posts downloaded.", 5000);
                SetStatusIcon();
                Model.PostList = posts;
            });
        }
コード例 #3
0
        void StartCapture()
        {
            Hide();
            ExternalWindow?.Hide();

            StatusImageSize.Text = "";

            // make sure windows actually hides before we wait
            WindowUtilities.DoEvents();

            // Display counter
            if (CaptureDelaySeconds > 0)
            {
                IsPreviewCapturing = true;
                Cancelled          = false;

                var counterForm = new ScreenOverlayCounter();

                try
                {
                    counterForm.Show();
                    counterForm.Topmost = true;
                    counterForm.SetWindowText("1");

                    for (int i = CaptureDelaySeconds; i > 0; i--)
                    {
                        counterForm.SetWindowText(i.ToString());
                        WindowUtilities.DoEvents();

                        for (int j = 0; j < 100; j++)
                        {
                            Thread.Sleep(10);
                            WindowUtilities.DoEvents();
                        }
                        if (Cancelled)
                        {
                            CancelCapture();
                            return;
                        }
                    }
                }
                finally
                {
                    counterForm.Close();
                    IsPreviewCapturing = false;
                    Cancelled          = true;
                }
            }

            IsMouseClickCapturing = true;

            Desktop = new ScreenOverlayDesktop(this);
            Desktop.SetDesktop(IncludeCursor);
            Desktop.Show();

            WindowUtilities.DoEvents();

            Overlay = new ScreenClickOverlay(this)
            {
                Width  = 0,
                Height = 0
            };
            Overlay.Show();

            LastWindow   = null;
            CaptureTimer = new Timer(Capture, null, 0, 100);
        }
コード例 #4
0
        public string EditorSelectionOperation(string action, string text)
        {
            if (action == "image")
            {
                string label = StringUtils.ExtractString(text, "![", "]");
                string link  = StringUtils.ExtractString(text, "](", ")");

                var form = new PasteImageWindow(Window)
                {
                    Image     = link,
                    ImageText = label
                };
                form.SetImagePreview();

                bool?  res  = form.ShowDialog();
                string html = null;

                if (res != null && res.Value)
                {
                    var image = form.Image;
                    if (!image.StartsWith("data:image/"))
                    {
                        html = $"![{form.ImageText}]({form.Image})";
                    }
                    else
                    {
                        var id = "image_ref_" + DataUtils.GenerateUniqueId();

                        dynamic pos    = AceEditor.getCursorPosition(false);
                        dynamic scroll = AceEditor.getscrolltop(false);

                        // the ID tag
                        html = $"\r\n\r\n[{id}]: {image}\r\n";

                        // set selction position to bottom of document
                        AceEditor.gotoBottom(false);
                        SetSelection(html);

                        // reset the selection point
                        AceEditor.setcursorposition(pos); //pos.column,pos.row);

                        if (scroll != null)
                        {
                            AceEditor.setscrolltop(scroll);
                        }

                        WindowUtilities.DoEvents();
                        html = $"![{form.ImageText}][{id}]";
                    }

                    if (!string.IsNullOrEmpty(html))
                    {
                        SetSelection(html);
                        PreviewMarkdownCallback();
                    }
                }
            }
            else if (action == "link")
            {
                MessageBox.Show("Link to Edit", text);
            }
            else if (action == "code")
            {
                MessageBox.Show("Link to Edit", text);
            }
            return(null);
        }
コード例 #5
0
        /// <summary>
        /// Takes action on the selected string in the editor using
        /// predefined commands.
        /// </summary>
        /// <param name="action"></param>
        /// <param name="input"></param>
        /// <param name="style"></param>
        /// <returns></returns>
        public string MarkupMarkdown(string action, string input, string style = null)
        {
            if (string.IsNullOrEmpty(action))
            {
                return(input);
            }

            action = action.ToLower();

            // check for insert actions that don't require a pre selection
            if (string.IsNullOrEmpty(input) && !StringUtils.Inlist(action, new string[] { "image", "href", "code", "emoji" }))
            {
                return(null);
            }

            string html = input;

            if (action == "bold")
            {
                html = "**" + input + "**";
            }
            else if (action == "italic")
            {
                html = "*" + input + "*";
            }
            else if (action == "small")
            {
                html = "<small>" + input + "</small>";
            }
            else if (action == "underline")
            {
                html = "<u>" + input + "</u>";
            }
            else if (action == "strikethrough")
            {
                html = "~~" + input + "~~";
            }
            else if (action == "inlinecode")
            {
                html = "`" + input + "`";
            }
            else if (action == "h1")
            {
                html = "# " + input;
            }
            else if (action == "h2")
            {
                html = "## " + input;
            }
            else if (action == "h3")
            {
                html = "### " + input;
            }
            else if (action == "h4")
            {
                html = "#### " + input;
            }
            else if (action == "h5")
            {
                html = "##### " + input;
            }

            else if (action == "quote")
            {
                StringBuilder sb    = new StringBuilder();
                var           lines = StringUtils.GetLines(input);
                foreach (var line in lines)
                {
                    sb.AppendLine("> " + line);
                }
                html = sb.ToString();
            }
            else if (action == "list")
            {
                StringBuilder sb    = new StringBuilder();
                var           lines = StringUtils.GetLines(input);
                foreach (var line in lines)
                {
                    sb.AppendLine("* " + line);
                }
                html = sb.ToString();
            }
            else if (action == "numberlist")
            {
                StringBuilder sb    = new StringBuilder();
                var           lines = StringUtils.GetLines(input);
                int           ct    = 0;
                foreach (var line in lines)
                {
                    ct++;
                    sb.AppendLine($"{ct}. " + line);
                }
                html = sb.ToString();
            }
            else if (action == "emoji")
            {
                var form = new EmojiWindow();
                form.Owner = Window;
                form.ShowDialog();

                if (form.Cancelled)
                {
                    return(input);
                }

                html = form.EmojiString;
            }
            else if (action == "href")
            {
                var form = new PasteHref()
                {
                    Owner        = Window,
                    LinkText     = input,
                    MarkdownFile = MarkdownDocument.Filename
                };

                // check for links in input or on clipboard
                string link = input;
                if (string.IsNullOrEmpty(link))
                {
                    link = Clipboard.GetText();
                }

                if (!(input.StartsWith("http:") || input.StartsWith("https:") || input.StartsWith("mailto:") || input.StartsWith("ftp:")))
                {
                    link = string.Empty;
                }
                form.Link = link;

                bool?res = form.ShowDialog();
                if (res != null && res.Value)
                {
                    if (form.IsExternal)
                    {
                        html = $"<a href=\"{form.Link}\" target=\"_blank\">{form.LinkText}</a>";
                    }
                    else
                    {
                        html = $"[{form.LinkText}]({form.Link})";
                    }
                }
            }
            else if (action == "image")
            {
                var form = new PasteImageWindow(Window)
                {
                    ImageText    = input,
                    MarkdownFile = MarkdownDocument.Filename
                };


                // check for links in input or on clipboard
                string link = input;
                if (string.IsNullOrEmpty(link))
                {
                    link = Clipboard.GetText();
                }

                if (!(input.StartsWith("http:") || input.StartsWith("https:") || input.StartsWith("mailto:") || input.StartsWith("ftp:")))
                {
                    link = string.Empty;
                }

                if (input.Contains(".png") || input.Contains(".jpg") || input.Contains(".gif"))
                {
                    link = input;
                }

                form.Image = link;

                bool?res = form.ShowDialog();
                if (res != null && res.Value)
                {
                    var image = form.Image;
                    if (!image.StartsWith("data:image/"))
                    {
                        html = $"![{form.ImageText}]({form.Image})";
                    }
                    else
                    {
                        var id = "image_ref_" + DataUtils.GenerateUniqueId();

                        dynamic pos    = AceEditor.getCursorPosition(false);
                        dynamic scroll = AceEditor.getscrolltop(false);

                        // the ID tag
                        html = $"\r\n\r\n[{id}]: {image}\r\n";

                        // set selction position to bottom of document
                        AceEditor.gotoBottom(false);
                        SetSelection(html);

                        // reset the selection point
                        AceEditor.setcursorposition(pos); //pos.column,pos.row);

                        if (scroll != null)
                        {
                            AceEditor.setscrolltop(scroll);
                        }

                        WindowUtilities.DoEvents();
                        html = $"![{form.ImageText}][{id}]";
                    }
                }
            }
            else if (action == "code")
            {
                var form = new PasteCode();
                form.Owner        = Window;
                form.Code         = input;
                form.CodeLanguage = "csharp";
                bool?res = form.ShowDialog();

                if (res != null && res.Value)
                {
                    html = "```" + form.CodeLanguage + "\r\n" +
                           form.Code.Trim() + "\r\n" +
                           "```\r\n";
                }
            }
            else
            {
                // allow addins to handle custom actions
                string addinAction = AddinManager.Current.RaiseOnEditorCommand(action, input);
                if (!string.IsNullOrEmpty(addinAction))
                {
                    html = addinAction;
                }
            }

            return(html);
        }
コード例 #6
0
        public void RunCommand(CommanderCommand command)
        {
            if (AddinModel.AppModel == null)
            {
                InitializeAddinModel();
            }

            string code = command.CommandText;

            bool showConsole = commanderWindow != null && commanderWindow.Visibility == Visibility.Visible;

            if (showConsole)
            {
                var tbox = commanderWindow.TextConsole;
                tbox.Clear();

                WindowUtilities.DoEvents();

                Console.SetOut(new ConsoleTextWriter()
                {
                    tbox = tbox
                });
            }

            var parser = new ScriptParser();

            if (!parser.EvaluateScript(code, AddinModel))
            {
                if (!showConsole)
                {
                    AddinModel.Window.ShowStatus("*** Addin execution failed: " + parser.ErrorMessage, 6000);
                    AddinModel.Window.SetStatusIcon(FontAwesomeIcon.Warning, Colors.Red);
                }
                else
                {
                    Console.WriteLine($"*** Error running Script code:\r\n{parser.ErrorMessage}");
                }

                if (CommanderAddinConfiguration.Current.OpenSourceInEditorOnErrors)
                {
                    string fname = Path.Combine(Path.GetTempPath(), "Commander_Compiled_Code.cs");
                    File.WriteAllText(fname, parser.ScriptInstance.SourceCode);

                    var tab = OpenTab(fname);
                    File.Delete(fname);

                    if (tab != null)
                    {
                        var editor = tab.Tag as MarkdownDocumentEditor;
                        editor.SetEditorSyntax("csharp");
                        editor.SetMarkdown(parser.ScriptInstance.SourceCode);

                        Dispatcher.CurrentDispatcher.InvokeAsync(() =>
                        {
                            if (editor.AceEditor == null)
                            {
                                Task.Delay(400);
                            }
                            editor.AceEditor.setshowlinenumbers(true);

                            if (commanderWindow == null)
                            {
                                commanderWindow = new CommanderWindow(this);
                                commanderWindow.Show();
                            }
                            else
                            {
                                commanderWindow.Activate();
                            }
                        }, DispatcherPriority.ApplicationIdle);
                    }
                }
            }
            else
            {
                AddinModel.Window.ShowStatus("Command execution for " + command.Name + " completed successfully", 6000);
            }


            if (showConsole)
            {
                commanderWindow.TextConsole.ScrollToHome();
                StreamWriter standardOutput = new StreamWriter(Console.OpenStandardOutput());
                standardOutput.AutoFlush = true;
                Console.SetOut(standardOutput);
            }
        }
コード例 #7
0
        private void ButtonWindowResize_Click(object sender, RoutedEventArgs e)
        {
            var model = Window.Model;

            var size   = ((MenuItem)sender).Header as string;
            var tokens = size.Split('x');

            Window.Width  = double.Parse(tokens[0].Trim());
            Window.Height = double.Parse(tokens[1].Trim());

            if (model.ActiveEditor?.EditorPreviewPane != null)
            {
                var width = model.ActiveEditor.EditorPreviewPane.ActualWidth;

                if (width < 2000 && width > 800)
                {
                    model.ActiveEditor.EditorPreviewPane.EditorWebBrowserEditorColumn.Width = GridLengthHelper.Star;
                    if (model.Configuration.IsPreviewVisible)
                    {
                        model.ActiveEditor.EditorPreviewPane.EditorWebBrowserPreviewColumn.Width =
                            new GridLength(width * 0.45);
                    }
                }
                else if (width > 2000)
                {
                    Window.ShowLeftSidebar();
                    if (model.ActiveEditor.EditorPreviewPane.EditorWebBrowserPreviewColumn.Width.Value < 750 &&
                        model.Configuration.IsPreviewVisible)
                    {
                        model.ActiveEditor.EditorPreviewPane.EditorWebBrowserPreviewColumn.Width = new GridLength(750);
                    }
                }
                else if (width <= 900)
                {
                    Window.ShowLeftSidebar(hide: true);
                    WindowUtilities.DoEvents();

                    width = model.ActiveEditor.EditorPreviewPane.ActualWidth;
                    model.ActiveEditor.EditorPreviewPane.EditorWebBrowserEditorColumn.Width = GridLengthHelper.Star;
                    if (model.Configuration.IsPreviewVisible)
                    {
                        model.ActiveEditor.EditorPreviewPane.EditorWebBrowserPreviewColumn.Width =
                            new GridLength(width * 0.45);
                    }
                }
            }

            var screen       = Screen.FromHandle(Window.Hwnd);
            var ratio        = (double)WindowUtilities.GetDpiRatio(Window.Hwnd);
            var windowWidth  = screen.Bounds.Width * ratio;
            var windowHeight = screen.Bounds.Height * ratio;

            if (windowWidth < Window.Width || windowHeight < Window.Height)
            {
                Window.Top    = screen.Bounds.Y * ratio;
                Window.Left   = screen.Bounds.X * ratio;
                Window.Width  = windowWidth - 20;
                Window.Height = windowHeight - 40;
            }

            if (windowWidth < Window.Width + Window.Left ||
                windowHeight < Window.Height + Window.Top)
            {
                WindowUtilities.CenterWindow(Window);
            }
        }
コード例 #8
0
        /// <summary>
        /// Captures an image to file
        /// </summary>
        /// <returns></returns>
        public bool CaptureImageToClipboard()
        {
            var OldState = WindowState.Minimized;

            if (ActiveForm != null)
            {
                OldState = ActiveForm.WindowState;
                ActiveForm.WindowState = WindowState.Minimized;
            }

            object snagIt = SnagItCom;

            try
            {
                ReflectionUtils.SetPropertyCom(snagIt, "Input", CaptureMode);
            }
            catch
            {
                SetError("SnagIt isn't installed - COM Access failed.\r\nPlease install SnagIt from Techsmith Corporation (www.techsmith.com\\snagit).");
                return(false);
            }

            ReflectionUtils.SetPropertyCom(snagIt, "Input", CaptureMode);
            ReflectionUtils.SetPropertyCom(snagIt, "Output", 4);           // clipboard
            ReflectionUtils.SetPropertyCom(snagIt, "EnablePreviewWindow", ShowPreviewWindow);
            ReflectionUtils.SetPropertyCom(snagIt, "IncludeCursor", IncludeCursor);

            if (DelayInSeconds > 0)
            {
                ReflectionUtils.SetPropertyExCom(snagIt, "DelayOptions.EnableDelayedCapture", true);
                ReflectionUtils.SetPropertyExCom(snagIt, "DelayOptions.DelaySeconds", DelayInSeconds);
            }


            if (ActiveForm != null)
            {
                // *** Need to delay a little here so that the form has properly minimized first
                // *** especially under Vista/Win7
                for (int i = 0; i < 20; i++)
                {
                    WindowUtilities.DoEvents();
                    Thread.Sleep(5);
                }
            }

            // Works but doesn't really add anything. Won't work in .NET Core due to dynamic not working with COM
            //((dynamic) snagIt).OnStateChange += new Action<CaptureState>(SnagImg_OnStateChange);

            Clipboard.Clear();

            try
            {
                IsDone = false;
                ReflectionUtils.CallMethodCom(snagIt, "Capture");

                while (!IsDone && !HasError)
                {
                    IsDone = (bool)ReflectionUtils.GetPropertyCom(snagIt, "IsCaptureDone");
                    if (IsDone)
                    {
                        break;
                    }

                    WindowUtilities.DoEvents();
                    Thread.Sleep(5);
                }
            }
            catch (Exception ex)
            {
                ErrorMessage = "An error occurred during the image capture: " + ex.Message;
                return(false);
            }
            // *** No catch let it throw
            finally
            {
                if (ActiveForm != null)
                {
                    // Reactivate Editor
                    ActiveForm.WindowState = OldState;

                    // Make sure it pops on top of SnagIt Editors
                    ActiveForm.Topmost = true;
                    WindowUtilities.DoEvents();
                    Thread.Sleep(5);
                    ActiveForm.Topmost = false;
                }

                Marshal.ReleaseComObject(SnagItCom);
            }

            return(ClipboardHelper.ContainsImage());
        }
コード例 #9
0
        /// <summary>
        /// Captures an image to file
        /// </summary>
        /// <returns></returns>
        public string CaptureImageToFile()
        {
            var OldState = WindowState.Minimized;

            if (ActiveForm != null)
            {
                OldState = ActiveForm.WindowState;
                ActiveForm.WindowState = WindowState.Minimized;
            }

            object snagIt = SnagItCom;

            try
            {
                ReflectionUtils.SetPropertyCom(snagIt, "Input", CaptureMode);
            }
            catch
            {
                SetError("SnagIt isn't installed - COM Access failed.\r\nPlease install SnagIt from Techsmith Corporation (www.techsmith.com\\snagit).");
                return(null);
            }

            ReflectionUtils.SetPropertyCom(snagIt, "Input", CaptureMode);
            ReflectionUtils.SetPropertyCom(snagIt, "Output", 2);           // file
            ReflectionUtils.SetPropertyCom(snagIt, "EnablePreviewWindow", ShowPreviewWindow);

            ReflectionUtils.SetPropertyExCom(snagIt, "OutputImageFile.Directory", CapturePath);
            ReflectionUtils.SetPropertyExCom(snagIt, "OutputImageFile.Filename", OutputCaptureFile);
            ReflectionUtils.SetPropertyExCom(snagIt, "OutputImageFile.Quality", 86); //86% quality
            int type = (int)OutputFileCaptureFormat;

            ReflectionUtils.SetPropertyExCom(snagIt, "OutputImageFile.FileType", type);
            ReflectionUtils.SetPropertyExCom(snagIt, "OutputImageFile.ColorDepth", ColorDepth);

            ReflectionUtils.SetPropertyCom(snagIt, "IncludeCursor", IncludeCursor);

            if (DelayInSeconds > 0)
            {
                ReflectionUtils.SetPropertyExCom(snagIt, "DelayOptions.EnableDelayedCapture", true);
                ReflectionUtils.SetPropertyExCom(snagIt, "DelayOptions.DelaySeconds", DelayInSeconds);
            }


            if (ActiveForm != null)
            {
                // *** Need to delay a little here so that the form has properly minimized first
                // *** especially under Vista/Win7
                for (int i = 0; i < 20; i++)
                {
                    WindowUtilities.DoEvents();
                    Thread.Sleep(5);
                }
            }

            // Works but doesn't really add anything. Won't work in .NET Core due to dynamic not working with COM
            //((dynamic) snagIt).OnStateChange += new Action<CaptureState>(SnagImg_OnStateChange);

            try
            {
                IsDone = false;
                ReflectionUtils.CallMethodCom(snagIt, "Capture");

                while (!IsDone && !HasError)
                {
                    IsDone = (bool)ReflectionUtils.GetPropertyCom(snagIt, "IsCaptureDone");
                    if (IsDone)
                    {
                        break;
                    }

                    WindowUtilities.DoEvents();
                    Thread.Sleep(5);
                }
            }
            catch (Exception ex)
            {
                ErrorMessage = "An error occurred during the image capture: " + ex.Message;
            }
            // *** No catch let it throw
            finally
            {
                if (IsDone)
                {
                    _outputCaptureFile = ReflectionUtils.GetPropertyCom(snagIt, "LastFileWritten") as string;
                }
                else
                {
                    _outputCaptureFile = null;
                    ErrorMessage       = "Image capture failed.";
                }

                if (ActiveForm != null)
                {
                    // Reactivate Editor
                    ActiveForm.WindowState = OldState;

                    // Make sure it pops on top of SnagIt Editors
                    ActiveForm.Topmost = true;
                    WindowUtilities.DoEvents();
                    Thread.Sleep(5);
                    ActiveForm.Topmost = false;
                }

                Marshal.ReleaseComObject(SnagItCom);
            }


            // If deleting the file we'll fire on a new thread and then delay by
            // a few seconds until Writer has picked up the image.
            if ((DeleteImageFromDisk))
            {
                new Timer(
                    (imgFile) =>
                {
                    var image = imgFile as string;
                    if (image == null)
                    {
                        return;
                    }
                    try
                    {
                        File.Delete(image);
                    }
                    catch {}
                }, _outputCaptureFile, 10000, Timeout.Infinite);
            }

            return(OutputCaptureFile);
        }
コード例 #10
0
        void CreateMoveTopicCommand()
        {
            MoveTopicCommand = new CommandBase((parameter, command) =>
            {
                _dragContextMenu.Visibility = Visibility.Collapsed;
                WindowUtilities.DoEvents();

                var dragResult = parameter as DragMoveResult;
                if (dragResult == null)
                {
                    return;
                }

                if (dragResult.TargetTopic == dragResult.SourceTopic)
                {
                    return;
                }

                var targetTopics = dragResult.TargetTopic?.Topics;
                if (targetTopics == null)
                {
                    targetTopics = Model.KavaDocsModel.ActiveProject.Topics;
                }

                var targetParentTopics = dragResult.TargetTopic.Parent?.Topics;
                if (targetParentTopics == null)
                {
                    targetParentTopics = Model.KavaDocsModel.ActiveProject.Topics;
                }

                var sourceTopics = dragResult.SourceTopic?.Parent?.Topics;
                if (sourceTopics == null)
                {
                    sourceTopics = Model.KavaDocsModel.ActiveProject.Topics;
                }

                if (dragResult.DropLocation == DropLocations.Below)
                {
                    sourceTopics.Remove(dragResult.SourceTopic);

                    // run out of band
                    targetTopics.Add(dragResult.SourceTopic);

                    dragResult.TargetTopic.IsExpanded = true;

                    dragResult.SourceTopic.Parent   = dragResult.TargetTopic;
                    dragResult.SourceTopic.ParentId = dragResult.TargetTopic.Id;

                    var so = targetTopics.Count * 10;
                    foreach (var topic in targetTopics)
                    {
                        so -= 10;
                        topic.SortOrder = so;
                    }

                    UpdateMovedTopic(dragResult.SourceTopic);
                }
                else if (dragResult.DropLocation == DropLocations.Before)
                {
                    sourceTopics.Remove(dragResult.SourceTopic);

                    var idx = targetParentTopics.IndexOf(dragResult.TargetTopic);
                    if (idx < 0)
                    {
                        sourceTopics.Add(dragResult.SourceTopic);
                        return;
                    }

                    // required to ensure items get removed before adding
                    targetParentTopics.Insert(idx, dragResult.SourceTopic);

                    dragResult.SourceTopic.Parent   = dragResult.TargetTopic.Parent;
                    dragResult.SourceTopic.ParentId = dragResult.TargetTopic.ParentId;

                    var so = targetParentTopics.Count * 10;
                    foreach (var topic in targetParentTopics)
                    {
                        so -= 10;
                        topic.SortOrder = so;
                    }
                    UpdateMovedTopic(dragResult.SourceTopic);
                }
                else if (dragResult.DropLocation == DropLocations.After)
                {
                    sourceTopics.Remove(dragResult.SourceTopic);

                    var idx = targetParentTopics.IndexOf(dragResult.TargetTopic);
                    if (idx < 0)
                    {
                        sourceTopics.Add(dragResult.SourceTopic);
                        return;
                    }

                    idx++;
                    targetParentTopics.Insert(idx, dragResult.SourceTopic);


                    dragResult.SourceTopic.Parent   = dragResult.TargetTopic.Parent;
                    dragResult.SourceTopic.ParentId = dragResult.TargetTopic.ParentId;

                    var so = targetParentTopics.Count * 10;
                    foreach (var docTopic in targetParentTopics)
                    {
                        so -= 10;
                        docTopic.SortOrder = so;
                    }
                    UpdateMovedTopic(dragResult.SourceTopic);
                }

                Model.KavaDocsModel.ActiveProject.SaveProject();
            }, (p, c) => true);
        }
コード例 #11
0
        /// <summary>
        /// Parses each of the images in the document and posts them to the server.
        /// Updates the HTML with the returned Image Urls
        /// </summary>
        /// <param name="html">HTML that contains images</param>
        /// <param name="basePath">image file name</param>
        /// <param name="wrapper">blog wrapper instance that sends</param>
        /// <param name="metaData">metadata containing post info</param>
        /// <returns>update HTML string for the document with updated images</returns>
        private string SendImages(string html, string basePath,
                                  MetaWeblogWrapper wrapper)
        {
            // base folder name for uploads - just the folder name of the image
            var baseName = Path.GetFileName(basePath);

            baseName = FileUtils.SafeFilename(baseName).Replace(" ", "-");

            var doc = new HtmlDocument();

            doc.LoadHtml(html);
            try
            {
                // send up normalized path images as separate media items
                var images = doc.DocumentNode.SelectNodes("//img");
                if (images != null)
                {
                    foreach (HtmlNode img in images)
                    {
                        string origImageLink = img.Attributes["src"]?.Value;
                        string imgFile       = StringUtils.UrlDecode(origImageLink);

                        if (imgFile == null)
                        {
                            continue;
                        }

                        // local image that needs uploading
                        if (!imgFile.StartsWith("http://") && !imgFile.StartsWith("https://"))
                        {
                            if (!imgFile.Contains(":\\"))
                            {
                                imgFile = Path.Combine(basePath, imgFile.Replace("/", "\\"));
                            }


                            if (System.IO.File.Exists(imgFile))
                            {
                                var uploadFilename = Path.GetFileName(imgFile);
                                var media          = new MediaObject()
                                {
                                    Type = ImageUtils.GetImageMediaTypeFromFilename(imgFile),
                                    Bits = System.IO.File.ReadAllBytes(imgFile),
                                    Name = baseName + "/" + uploadFilename
                                };

                                var mediaResult = wrapper.NewMediaObject(media);
                                img.Attributes["src"].Value = mediaResult.URL;

                                // use first image as featured image
                                if (!DontInferFeaturedImage)
                                {
                                    if (string.IsNullOrEmpty(FeaturedImageUrl))
                                    {
                                        FeaturedImageUrl = mediaResult.URL;
                                    }
                                    if (string.IsNullOrEmpty(FeatureImageId))
                                    {
                                        FeatureImageId = mediaResult.Id;
                                    }
                                }

                                if (WeblogAddinConfiguration.Current.ReplacePostImagesWithOnlineUrls)
                                {
                                    mmApp.Model.ActiveDocument.CurrentText =
                                        mmApp.Model.ActiveDocument.CurrentText
                                        .Replace($"]({origImageLink})", $"]({mediaResult.URL})")
                                        .Replace($"=\"{origImageLink}\"", $"=\"{mediaResult.URL}\"");
                                }
                            }
                        }
                        // https:// online image link
                        else
                        {
                            if (!DontInferFeaturedImage && string.IsNullOrEmpty(FeaturedImageUrl))
                            {
                                FeaturedImageUrl = imgFile;
                            }
                        }

                        WindowUtilities.DoEvents();
                    }

                    html = doc.DocumentNode.OuterHtml;
                }
            }
            catch (Exception ex)
            {
                ErrorMessage = "Error posting images to Weblog: " + ex.GetBaseException().Message;
                mmApp.Log("Failed to post image to Weblog", ex);
                return(null);
            }

            return(html);
        }
コード例 #12
0
        private void TreeViewItem_Drop(object sender, DragEventArgs e)
        {
            if (!e.Data.GetDataPresent(typeof(DocTopic)))
            {
                return;
            }

            DocTopic sourceTopic = (DocTopic)e.Data.GetData(typeof(DocTopic));

            if (sourceTopic == null)
            {
                return;
            }

            var tvItem = WindowUtilities.FindAnchestor <TreeViewItem>((DependencyObject)e.OriginalSource);

            if (tvItem == null)
            {
                return;
            }
            var targetTopic = tvItem.DataContext as DocTopic;

            if (targetTopic == null)
            {
                return;
            }

            if (sourceTopic == targetTopic)
            {
                return;
            }

            if (MoveTopicCommand == null)
            {
                CreateMoveTopicCommand();
            }

            _dragContextMenu = new ContextMenu()
            {
                DataContext = DragMoveResult
            };

            var mi = new MenuItem
            {
                Header           = "Move underneath this item",
                Tag              = _dragContextMenu,
                Command          = MoveTopicCommand,
                CommandParameter = new DragMoveResult
                {
                    SourceTopic  = sourceTopic,
                    TargetTopic  = targetTopic,
                    DropLocation = DropLocations.Below
                }
            };

            _dragContextMenu.Items.Add(mi);
            _dragContextMenu.Items.Add(new Separator());
            _dragContextMenu.Items.Add(new MenuItem
            {
                Header           = "Move before this item",
                Tag              = _dragContextMenu,
                Command          = MoveTopicCommand,
                CommandParameter = new DragMoveResult
                {
                    SourceTopic  = sourceTopic,
                    TargetTopic  = targetTopic,
                    DropLocation = DropLocations.Before
                }
            });
            _dragContextMenu.Items.Add(new MenuItem
            {
                Header           = "Move after this item",
                Tag              = _dragContextMenu,
                Command          = MoveTopicCommand,
                CommandParameter = new DragMoveResult
                {
                    SourceTopic  = sourceTopic,
                    TargetTopic  = targetTopic,
                    DropLocation = DropLocations.After
                }
            });
            _dragContextMenu.Items.Add(new Separator());
            _dragContextMenu.Items.Add(new MenuItem
            {
                Header           = "Cancel topic move",
                Tag              = _dragContextMenu,
                Command          = MoveTopicCommand,
                CommandParameter = null
            });

            WindowUtilities.DoEvents();
            _dragContextMenu.Placement       = System.Windows.Controls.Primitives.PlacementMode.Mouse;
            _dragContextMenu.PlacementTarget = tvItem;
            _dragContextMenu.Visibility      = Visibility.Visible;
            _dragContextMenu.IsOpen          = true;
            WindowUtilities.DoEvents();
        }
コード例 #13
0
        public async Task RunCommand(CommanderCommand command)
        {
            if (AddinModel.AppModel == null)
            {
                InitializeAddinModel();
            }

            string            code          = command.CommandText;
            ConsoleTextWriter consoleWriter = null;

            bool showConsole = commanderWindow != null && commanderWindow.Visibility == Visibility.Visible;

            if (showConsole)
            {
                var tbox = commanderWindow.TextConsole;
                tbox.Clear();

                WindowUtilities.DoEvents();

                consoleWriter = new ConsoleTextWriter()
                {
                    tbox = tbox
                };
                Console.SetOut(consoleWriter);
            }

            AddinModel.AppModel.Window.ShowStatusProgress("Executing Command '" + command.Name + "' started...");

            var  parser = new ScriptParser();
            bool result = await parser.EvaluateScriptAsync(code, AddinModel);

            if (!result)
            {
                var msg = parser.ErrorMessage;
                if (parser.ScriptInstance.ErrorType == Westwind.Scripting.ExecutionErrorTypes.Compilation)
                {
                    msg = "Script compilation error.";
                }

                AddinModel.AppModel.Window.ShowStatusError("Command '" + command.Name + "' execution failed: " + msg);
                if (showConsole)
                {
                    if (parser.ScriptInstance.ErrorType == Westwind.Scripting.ExecutionErrorTypes.Compilation)
                    {
                        var adjusted = ScriptParser.FixupLineNumbersAndErrors(parser.ScriptInstance);
                        parser.ErrorMessage = adjusted.UpdatedErrorMessage;
                        Console.WriteLine($"*** Script Compilation  Errors:\n{parser.ErrorMessage}\n");

                        Console.WriteLine("\n*** Generated Code:");
                        Console.WriteLine(parser.ScriptInstance.GeneratedClassCode);
                    }
                    else
                    {
                        Console.WriteLine($"*** Runtime Execution Error:\n{parser.ErrorMessage}\n");
                    }
                }
            }
            else
            {
                if (mmApp.Model.Window.StatusText.Text.StartsWith("Executing Command "))
                {
                    AddinModel.AppModel.Window.ShowStatusSuccess("Command '" + command.Name + "' executed successfully");
                }
            }


            if (showConsole)
            {
                consoleWriter.Close();
                commanderWindow.TextConsole.ScrollToHome();
                StreamWriter standardOutput = new StreamWriter(Console.OpenStandardOutput());
                standardOutput.AutoFlush = true;
                Console.SetOut(standardOutput);
            }
        }
コード例 #14
0
 public override void Write(string value)
 {
     base.Write(value);
     WindowUtilities.DoEvents();
     tbox.ScrollToEnd();
 }
コード例 #15
0
        /// <summary>
        /// Parses each of the images in the document and posts them to the server.
        /// Updates the HTML with the returned Image Urls
        /// </summary>
        /// <param name="html">HTML that contains images</param>
        /// <param name="basePath">image file name</param>
        /// <param name="wrapper">blog wrapper instance that sends</param>
        /// <param name="metaData">metadata containing post info</param>
        /// <returns>update HTML string for the document with updated images</returns>
        private string SendImages(string html, string basePath,
                                  MetaWeblogWrapper wrapper)
        {
            // base folder name for uploads - just the folder name of the image
            var baseName = Path.GetFileName(basePath);

            baseName = FileUtils.SafeFilename(baseName).Replace(" ", "-");

            var doc = new HtmlDocument();

            doc.LoadHtml(html);
            try
            {
                // send up normalized path images as separate media items
                var images = doc.DocumentNode.SelectNodes("//img");
                if (images != null)
                {
                    foreach (HtmlNode img in images)
                    {
                        string imgFile = img.Attributes["src"]?.Value;
                        imgFile = StringUtils.UrlDecode(imgFile);

                        if (imgFile == null)
                        {
                            continue;
                        }

                        if (!imgFile.StartsWith("http://") && !imgFile.StartsWith("https://"))
                        {
                            if (!imgFile.Contains(":\\"))
                            {
                                imgFile = Path.Combine(basePath, imgFile.Replace("/", "\\"));
                            }

                            if (System.IO.File.Exists(imgFile))
                            {
                                var uploadFilename = Path.GetFileName(imgFile);
                                var media          = new MediaObject()
                                {
                                    Type = ImageUtils.GetImageMediaTypeFromFilename(imgFile),
                                    Bits = System.IO.File.ReadAllBytes(imgFile),
                                    Name = baseName + "/" + uploadFilename
                                };
                                var mediaResult = wrapper.NewMediaObject(media);
                                img.Attributes["src"].Value = mediaResult.URL;

                                // use first image as featured image
                                if (!DontInferFeaturedImage)
                                {
                                    if (string.IsNullOrEmpty(FeaturedImageUrl))
                                    {
                                        FeaturedImageUrl = mediaResult.URL;
                                    }
                                    if (string.IsNullOrEmpty(FeatureImageId))
                                    {
                                        FeatureImageId = mediaResult.Id;
                                    }
                                }
                            }
                        }
                        WindowUtilities.DoEvents();
                    }

                    html = doc.DocumentNode.OuterHtml;
                }
            }
            catch (Exception ex)
            {
                ErrorMessage = "Error posting images to Weblog: " + ex.Message;
                return(null);
            }

            return(html);
        }
コード例 #16
0
        private void DropDownButton_Click(object sender, RoutedEventArgs e)
        {
            ShowStatus("Getting Blog listing information from service...");
            WindowUtilities.DoEvents();

            var context = Resources["BlogsContextMenu"] as ContextMenu;

            context.Items.Clear();

            IEnumerable <UserBlog> blogs = null;

            try
            {
                if (Model.ActiveWeblogInfo.Type == WeblogTypes.Medium)
                {
                    var client = new MediumApiClient(Model.ActiveWeblogInfo);
                    blogs = client.GetBlogs();
                    if (blogs == null)
                    {
                        ShowStatus("Failed to get blog listing: " + client.ErrorMessage, 6000);
                    }
                }
                else if (Model.ActiveWeblogInfo.Type == WeblogTypes.MetaWeblogApi ||
                         Model.ActiveWeblogInfo.Type == WeblogTypes.Wordpress)
                {
                    var client = new MetaWebLogWordpressApiClient(Model.ActiveWeblogInfo);
                    blogs = client.GetBlogs();
                    if (blogs == null)
                    {
                        ShowStatus("Failed to get blog listing: " + client.ErrorMessage, 6000);
                    }
                }
            }
            catch (Exception ex)
            {
                ShowStatus("Failed to get blogs: " + ex.Message, 6000);
                return;
            }

            ShowStatus("Blogs retrieved...", 2000);

            if (blogs == null)
            {
                return;
            }

            string blogId = Model.ActiveWeblogInfo.BlogId as string;

            if (!string.IsNullOrEmpty(blogId) && !blogs.Any(b => blogId == b.BlogId as string))
            {
                context.Items.Add(new MenuItem {
                    Header = blogId, Tag = blogId
                });
            }

            foreach (var blog in blogs)
            {
                var item = new MenuItem()
                {
                    Header = blog.BlogName,
                    Tag    = blog.BlogId,
                };
                item.Click += (s, ea) =>
                {
                    var mitem = s as MenuItem;
                    if (mitem == null)
                    {
                        return;
                    }

                    Model.ActiveWeblogInfo.BlogId = mitem.Tag as string;
                    context.Items.Clear();
                };
                context.Items.Add(item);
            }
        }
コード例 #17
0
        /// <summary>
        /// Captures an image to file
        /// </summary>
        /// <returns></returns>
        public string CaptureImageToFile()
        {
            var OldState = WindowState.Minimized;

            if (ActiveForm != null)
            {
                OldState = ActiveForm.WindowState;
                ActiveForm.WindowState = WindowState.Minimized;
            }

            dynamic snagIt = SnagItCom;

            try
            {
                snagIt.OutputImageFile.Directory = CapturePath;
            }
            catch
            {
                SetError("SnagIt isn't installed - COM Access failed.\r\nPlease install SnagIt from Techsmith Corporation (www.techsmith.com\\snagit).");
                return(null);
            }


            snagIt.Input = CaptureMode;
            snagIt.EnablePreviewWindow = ShowPreviewWindow;

            snagIt.OutputImageFile.Filename   = OutputCaptureFile;
            snagIt.OutputImageFile.Quality    = 86; //86% quality
            snagIt.OutputImageFile.FileType   = (int)OutputFileCaptureFormat;
            snagIt.OutputImageFile.ColorDepth = ColorDepth;

            snagIt.IncludeCursor = IncludeCursor;

            if (DelayInSeconds > 0)
            {
                snagIt.DelayOptions.EnableDelayedCapture = true;
                snagIt.DelayOptions.DelaySeconds         = DelayInSeconds;
            }


            if (ActiveForm != null)
            {
                // *** Need to delay a little here so that the form has properly minimized first
                // *** especially under Vista/Win7
                for (int i = 0; i < 20; i++)
                {
                    WindowUtilities.DoEvents();
                    Thread.Sleep(5);
                }
            }

            snagIt.OnStateChange += new Action <CaptureState>(SnagImg_OnStateChange);

            try
            {
                IsDone = false;
                snagIt.Capture();

                while (!IsDone && !HasError)
                {
                    WindowUtilities.DoEvents();
                    Thread.Sleep(20);
                }
            }
            catch (Exception ex)
            {
                ErrorMessage = "An error occurred during the image capture: " + ex.Message;
            }
            // *** No catch let it throw
            finally
            {
                if (IsDone)
                {
                    _outputCaptureFile = snagIt.LastFileWritten;
                }
                else
                {
                    _outputCaptureFile = null;
                    ErrorMessage       = "Image capture failed.";
                }

                if (ActiveForm != null)
                {
                    // Reactivate Editor
                    ActiveForm.WindowState = OldState;

                    // Make sure it pops on top of SnagIt Editors
                    ActiveForm.Topmost = true;
                    WindowUtilities.DoEvents();
                    Thread.Sleep(5);
                    ActiveForm.Topmost = false;
                }

                Marshal.ReleaseComObject(SnagItCom);
            }


            // If deleting the file we'll fire on a new thread and then delay by
            // a few seconds until Writer has picked up the image.
            if ((DeleteImageFromDisk))
            {
                new Timer(
                    (imgFile) =>
                {
                    var image = imgFile as string;
                    if (image == null)
                    {
                        return;
                    }
                    try
                    {
                        File.Delete(image);
                    }
                    catch {}
                }, _outputCaptureFile, 10000, Timeout.Infinite);
            }

            return(OutputCaptureFile);
        }
コード例 #18
0
        /// <summary>
        /// Opens files from the command line or from an array of strings
        /// </summary>
        /// <param name="args">
        /// Array of file names and command line arguments.
        /// If null Command Line Args are used.
        /// </param>
        public void OpenFilesFromCommandLine(string[] args = null)
        {
            if (args == null)
            {
                // read fixed up command line args
                args = App.CommandArgs;

                if (args == null || args.Length == 0) // no args, only command line
                {
                    return;
                }
            }

            var     autoSave      = App.CommandArgs.Any(a => a.Equals("-autosave", StringComparison.InvariantCultureIgnoreCase));
            bool    isFirstFile   = true;
            TabItem tabToActivate = null;

            bool closeNextFile = false;

            foreach (var fileArgs in args)
            {
                var file = fileArgs;
                if (string.IsNullOrEmpty(file))
                {
                    continue;
                }

                // handle file closing
                if (file == "-close")
                {
                    closeNextFile = true;
                    continue;
                }

                if (closeNextFile)
                {
                    closeNextFile = false;
                    var tab = Window.GetTabFromFilename(file);
                    if (tab != null)
                    {
                        if (tab.Tag is MarkdownDocumentEditor editor)
                        {
                            if (editor.IsDirty())
                            {
                                editor.SaveDocument();
                            }
                            Window.CloseTab(tab, dontPromptForSave: true);

                            if (Window.TabControl.Items.Count < 1)
                            {
                                WindowUtilities.DoEvents();
                                Window.Close();
                                return;
                            }
                        }
                    }

                    continue;
                }


                string ext = string.Empty;
                file = file.TrimEnd('\\');

                // file monikers - just strip first
                if (file.StartsWith("markdownmonster:webserver"))
                {
                    if (Window.WebServer == null)
                    {
                        WebServerLauncher.StartMarkdownMonsterWebServer();
                    }
                    else
                    {
                        WebServerLauncher.StopMarkdownMonsterWebServer();
                    }

                    continue;
                }
                if (file.Equals("-startwebserver", StringComparison.OrdinalIgnoreCase))
                {
                    WebServerLauncher.StartMarkdownMonsterWebServer();
                    continue;
                }
                if (file.Equals("-stopwebserver", StringComparison.OrdinalIgnoreCase))
                {
                    WebServerLauncher.StopMarkdownMonsterWebServer();
                    continue;
                }

                if (file.StartsWith("markdownmonster:"))
                {
                    file = WebUtility.UrlDecode(file.Replace("markdownmonster:", String.Empty));
                }
                else if (file.StartsWith("markdown:"))
                {
                    file = WebUtility.UrlDecode(file.Replace("markdown:", String.Empty));
                }

                bool isUntitled = file.Equals("untitled", StringComparison.OrdinalIgnoreCase);
                if (file.StartsWith("untitled."))
                {
                    isUntitled = true;
                }


                if (!isUntitled)
                {
                    if (FileUtils.HasInvalidPathCharacters(file))
                    {
                        Window.ShowStatusError($"Can't open file: {file}");
                        continue;
                    }

                    try
                    {
                        // FAIL: This fails at runtime not in debugger when value is .\ trimmed to . VERY WEIRD
                        file = Path.GetFullPath(file);
                        ext  = Path.GetExtension(file);
                    }
                    catch (Exception ex)
                    {
                        Window.ShowStatusError($"Can't open file: {file}");
                        mmApp.Log($"CommandLine file path resolution failed: {file}", ex);
                    }
                }

                // open an empty doc or new doc with preset text from base64 (untitled.base64text)
                if (isUntitled)
                {
                    string docText = null;

                    // untitled.base64text will decode the base64 text
                    if (file.StartsWith("untitled."))
                    {
                        docText = CommandLineTextEncoder.ParseUntitledString(file);
                    }

                    // open empty document, or fill with App.StartupText is set
                    Window.Model.Commands.NewDocumentCommand.Execute(docText);
                }

                else if (File.Exists(file))
                {
                    // open file which may or may not open a tab (like a project)
                    var tab = Window.OpenFile(filename: file, batchOpen: true,
                                              noShellNavigation: true,
                                              initialLineNumber: MarkdownMonster.App.LineToOpen, noFocus: true);
                    App.LineToOpen = 0;

                    //var tab = OpenTab(mdFile: file, batchOpen: true);
                    if (tab?.Tag is MarkdownDocumentEditor editor)
                    {
                        editor.MarkdownDocument.AutoSaveBackup   = Model.Configuration.AutoSaveBackups;
                        editor.MarkdownDocument.AutoSaveDocument = autoSave || Model.Configuration.AutoSaveDocuments;
                    }

                    if (isFirstFile)
                    {
                        tabToActivate = tab;
                        isFirstFile   = false;
                    }
                }
                else if (Directory.Exists(file))
                {
                    Window.ShowFolderBrowser(false, file);
                }
                // file is an .md file but doesn't exist but folder exists - create it
                else if ((ext.Equals(".md", StringComparison.InvariantCultureIgnoreCase) ||
                          ext.Equals(".mkdown", StringComparison.InvariantCultureIgnoreCase) ||
                          ext.Equals(".markdown", StringComparison.InvariantCultureIgnoreCase) ||
                          ext.Equals(".mdcrypt", StringComparison.InvariantCultureIgnoreCase)
                          ) &&
                         Directory.Exists(Path.GetDirectoryName(file)))
                {
                    File.WriteAllText(file, "");
                    var tab = Window.OpenTab(mdFile: file, batchOpen: true, noFocus: true);
                    if (tab?.Tag is MarkdownDocumentEditor editor)
                    {
                        editor.MarkdownDocument.AutoSaveBackup   = Model.Configuration.AutoSaveBackups;
                        editor.MarkdownDocument.AutoSaveDocument = autoSave || Model.Configuration.AutoSaveDocuments;
                    }

                    // delete the file if we abort
                    Window.Dispatcher.Delay(1000, p => File.Delete(file), null);

                    if (isFirstFile)
                    {
                        tabToActivate = tab;
                        isFirstFile   = false;
                    }
                }
                else
                {
                    file = Path.Combine(App.InitialStartDirectory, file);
                    file = Path.GetFullPath(file);
                    if (File.Exists(file))
                    {
                        var tab = Window.OpenTab(mdFile: file, batchOpen: true);
                        if (tab.Tag is MarkdownDocumentEditor editor)
                        {
                            editor.MarkdownDocument.AutoSaveBackup   = Model.Configuration.AutoSaveBackups;
                            editor.MarkdownDocument.AutoSaveDocument =
                                autoSave || Model.Configuration.AutoSaveDocuments;
                        }
                    }
                    else if (Directory.Exists(file))
                    {
                        Window.ShowFolderBrowser(false, file);
                    }
                }


                if (tabToActivate != null)
                {
                    Window.Dispatcher.InvokeAsync(() =>
                    {
                        // Forces the Window to be active - note simple Activate()/Focus() doesn't
                        // work here due to cross thread activation when called from named pipe - even with Dispatcher
                        WindowUtilities.ActivateWindow(Window);
                        Window.ActivateTab(tabToActivate, true);
                    }, DispatcherPriority.ApplicationIdle);
                }
            }
        }