Exemple #1
0
        private void PreviewBrowserOnLoadCompleted(object sender, NavigationEventArgs e)
        {
            string url = e.Uri.ToString();

            if (!url.Contains("_MarkdownMonster_Preview"))
            {
                return;
            }

            bool shouldScrollToEditor = WebBrowser.Tag != null && WebBrowser.Tag.ToString() == "EDITORSCROLL";

            WebBrowser.Tag = null;

            dynamic window = null;
            MarkdownDocumentEditor editor = null;

            try
            {
                editor = Window.GetActiveMarkdownEditor();
                dynamic dom = WebBrowser.Document;
                window = dom.parentWindow;
                dom.documentElement.scrollTop = editor.MarkdownDocument.LastEditorLineNumber;

                window.initializeinterop(editor);

                if (shouldScrollToEditor)
                {
                    try
                    {
                        // scroll preview to selected line
                        if (mmApp.Configuration.PreviewSyncMode == PreviewSyncMode.EditorAndPreview ||
                            mmApp.Configuration.PreviewSyncMode == PreviewSyncMode.EditorToPreview)
                        {
                            int lineno = editor.GetLineNumber();
                            if (lineno > -1)
                            {
                                window.scrollToPragmaLine(lineno);
                            }
                        }
                    }
                    catch
                    {
                        /* ignore scroll error */
                    }
                }
            }
            catch
            {
                // try again
                Task.Delay(500).ContinueWith(t =>
                {
                    try
                    {
                        window.initializeinterop(editor);
                    }
                    catch
                    {
                        //mmApp.Log("Preview InitializeInterop failed: " + url, ex);
                    }
                });
            }
        }
 public void InitializeInterop(MarkdownDocumentEditor editor)
 {
     Invoke("initializeinterop", editor);
 }
        public void PreviewMarkdown(MarkdownDocumentEditor editor = null, bool keepScrollPosition = false, bool showInBrowser = false)
        {
            if (!Model.IsPreviewBrowserVisible && !showInBrowser)
            {
                return;
            }

            if (editor == null)
            {
                editor = GetActiveMarkdownEditor();
            }

            if (editor == null)
            {
                return;
            }

            var doc = editor.MarkdownDocument;
            var ext = Path.GetExtension(editor.MarkdownDocument.Filename).ToLower().Replace(".", "");


            int     lastPos = 0;
            dynamic dom     = null;

            if (string.IsNullOrEmpty(ext) || ext == "md" || ext == "html" || ext == "htm")
            {
                this.ShowPreviewBrowser();

                if (keepScrollPosition)
                {
                    dom = PreviewBrowser.Document;
                    editor.MarkdownDocument.LastBrowserScrollPosition = dom.documentElement.scrollTop;
                }
                else
                {
                    editor.MarkdownDocument.LastBrowserScrollPosition = 0;
                }


                if (ext == "html" || ext == "htm")
                {
                    File.WriteAllText(editor.MarkdownDocument.HtmlRenderFilename, editor.MarkdownDocument.CurrentText);
                }
                else
                {
                    editor.MarkdownDocument.RenderHtmlToFile();
                }

                if (showInBrowser)
                {
                    ShellUtils.GoUrl(editor.MarkdownDocument.HtmlRenderFilename);
                }
                else
                {
                    PreviewBrowser.Cursor      = Cursors.None;
                    PreviewBrowser.ForceCursor = true;
                    if (keepScrollPosition &&
                        PreviewBrowser.Source.ToString() == editor.MarkdownDocument.HtmlRenderFilename)
                    {
                        PreviewBrowser.Refresh(true);
                    }
                    else
                    {
                        PreviewBrowser.Navigate(editor.MarkdownDocument.HtmlRenderFilename);
                    }
                }
            }
            else
            {
                ShowPreviewBrowser(true);
            }
        }
        public TabItem OpenTab(string mdFile = null, MarkdownDocumentEditor editor = null, bool showPreviewIfActive = false, string syntax = "markdown", bool selectTab = true)
        {
            if (mdFile != null && mdFile != "untitled" && (!File.Exists(mdFile) ||
                                                           !AddinManager.Current.RaiseOnBeforeOpenDocument(mdFile)))
            {
                return(null);
            }

            var tab = new TabItem();

            tab.Margin      = new Thickness(0, 0, 3, 0);
            tab.Padding     = new Thickness(2, 0, 7, 2);
            tab.Background  = this.Background;
            tab.ContextMenu = this.Resources["TabItemContextMenu"] as ContextMenu;


            ControlsHelper.SetHeaderFontSize(tab, 13F);

            var wb = new WebBrowser
            {
                AllowDrop  = false,
                Visibility = Visibility.Hidden
            };

            tab.Content = wb;

            if (editor == null)
            {
                dynamic dom = wb.Document;
                editor = new MarkdownDocumentEditor(wb)
                {
                    Window       = this,
                    EditorSyntax = syntax
                };

                var doc = new MarkdownDocument
                {
                    Filename = mdFile ?? @"c:\temp\readme.md"
                };
                if (FileName != "untitled")
                {
                    doc.Load();
                }

                doc.PropertyChanged += (sender, e) =>
                {
                    if (e.PropertyName == "IsDirty")
                    {
                        CommandManager.InvalidateRequerySuggested();
                    }
                };
                editor.MarkdownDocument = doc;

                var headerBinding = new Binding
                {
                    Source = doc,
                    Path   = new PropertyPath("FilenameWithIndicator"),
                    Mode   = BindingMode.OneWay
                };
                BindingOperations.SetBinding(tab, TabItem.HeaderProperty, headerBinding);

                tab.ToolTip = doc.Filename;
            }


            var filename = Path.GetFileName(editor.MarkdownDocument.Filename);

            tab.Tag = editor;

            Title = filename;

            editor.LoadDocument();

            TabItem existingTab = null;

            if (filename != "untitled")
            {
                foreach (TabItem tb in TabControl.Items)
                {
                    var lEditor = tb.Tag as MarkdownDocumentEditor;
                    if (lEditor.MarkdownDocument.Filename == editor.MarkdownDocument.Filename)
                    {
                        existingTab = tb;
                        break;
                    }
                }
            }
            Model.OpenDocuments.Add(editor.MarkdownDocument);
            Model.ActiveDocument = editor.MarkdownDocument;

            if (existingTab != null)
            {
                TabControl.Items.Remove(existingTab);
            }

            tab.IsSelected = false;

            TabControl.Items.Insert(0, tab);

            // Get Tabablz control to insert at the top of the head
            //if (TabControl.Items.Count > 0)
            //    TabablzControl.AddItem(tab, TabControl.Items[0] as TabItem, AddLocationHint.First);
            //else
            //    TabControl.AddToSource(tab);

            if (selectTab)
            {
                TabControl.SelectedItem = tab;

                if (showPreviewIfActive && PreviewBrowser.Width > 5)
                {
                    PreviewMarkdown(); //Model.PreviewBrowserCommand.Execute(ButtonHtmlPreview);
                }
            }

            AddinManager.Current.RaiseOnAfterOpenDocument(editor.MarkdownDocument);

            return(tab);
        }
        public void PreviewMarkdown(MarkdownDocumentEditor editor = null, bool keepScrollPosition = false, bool showInBrowser = false)
        {
            // only render if the preview is actually visible and rendering in Preview Browser
            if (!Model.IsPreviewBrowserVisible && !showInBrowser)
            {
                return;
            }

            if (editor == null)
            {
                editor = GetActiveMarkdownEditor();
            }

            if (editor == null)
            {
                return;
            }

            var doc = editor.MarkdownDocument;
            var ext = Path.GetExtension(doc.Filename).ToLower().Replace(".", "");

            string renderedHtml = null;

            if (string.IsNullOrEmpty(ext) || ext == "md" || ext == "html" || ext == "htm")
            {
                dynamic dom = null;
                if (keepScrollPosition)
                {
                    dom = PreviewBrowser.Document;
                    editor.MarkdownDocument.LastBrowserScrollPosition = dom.documentElement.scrollTop;
                }
                else
                {
                    ShowPreviewBrowser(false, false);
                    editor.MarkdownDocument.LastBrowserScrollPosition = 0;
                }

                if (ext == "html" || ext == "htm")
                {
                    editor.MarkdownDocument.WriteFile(editor.MarkdownDocument.HtmlRenderFilename, editor.MarkdownDocument.CurrentText);
                }
                else
                {
                    renderedHtml = editor.MarkdownDocument.RenderHtmlToFile();
                }

                if (showInBrowser)
                {
                    ShellUtils.GoUrl(editor.MarkdownDocument.HtmlRenderFilename);
                }
                else
                {
                    PreviewBrowser.Cursor      = Cursors.None;
                    PreviewBrowser.ForceCursor = true;
                    if (keepScrollPosition)
                    {
                        string browserUrl   = PreviewBrowser.Source.ToString().ToLower();
                        string documentFile = "file:///" + editor.MarkdownDocument.HtmlRenderFilename.Replace('\\', '/').ToLower();
                        if (browserUrl == documentFile)
                        {
                            dom = PreviewBrowser.Document;
                            //var content = dom.getElementById("MainContent");


                            renderedHtml = StringUtils.ExtractString(renderedHtml,
                                                                     "<!-- Markdown Monster Content -->",
                                                                     "<!-- End Markdown Monster Content -->");

                            if (string.IsNullOrEmpty(renderedHtml))
                            {
                                PreviewMarkdown(editor, false, false); // fully reload document
                            }
                            else
                            {
                                try
                                {
                                    // explicitly update the document with JavaScript code
                                    // much more efficient and non-jumpy and no wait cursor
                                    var window = dom.parentWindow;
                                    window.updateDocumentContent(renderedHtml);
                                }
                                catch
                                {
                                    PreviewBrowser.Refresh(true);
                                }
                            }

                            return;
                        }
                    }

                    PreviewBrowser.Navigate(editor.MarkdownDocument.HtmlRenderFilename);
                    return;
                }
            }

            ShowPreviewBrowser(true, keepScrollPosition);
        }
        public void PreviewMarkdown(MarkdownDocumentEditor editor = null,
                                    bool keepScrollPosition       = false,
                                    bool showInBrowser            = false,
                                    string renderedHtml           = null)
        {
            try
            {
                // only render if the preview is actually visible and rendering in Preview Browser
                if (!Model.IsPreviewBrowserVisible && !showInBrowser)
                {
                    return;
                }

                if (editor == null)
                {
                    editor = Window.GetActiveMarkdownEditor();
                }

                if (editor == null)
                {
                    return;
                }

                var doc = editor.MarkdownDocument;
                var ext = Path.GetExtension(doc.Filename).ToLower().Replace(".", "");

                string mappedTo = "markdown";
                if (!string.IsNullOrEmpty(renderedHtml))
                {
                    mappedTo = "html";
                    ext      = null;
                }
                else
                {
                    // only show preview for Markdown and HTML documents
                    Model.Configuration.EditorExtensionMappings.TryGetValue(ext, out mappedTo);
                    mappedTo = mappedTo ?? string.Empty;
                }

                if (string.IsNullOrEmpty(ext) || mappedTo == "markdown" || mappedTo == "html")
                {
                    dynamic dom = null;
                    if (!showInBrowser)
                    {
                        if (keepScrollPosition)
                        {
                            dom = WebBrowser.Document;
                            editor.MarkdownDocument.LastEditorLineNumber = dom.documentElement.scrollTop;
                        }
                        else
                        {
                            Window.ShowPreviewBrowser(false, false);
                            editor.MarkdownDocument.LastEditorLineNumber = 0;
                        }
                    }

                    if (mappedTo == "html")
                    {
                        if (string.IsNullOrEmpty(renderedHtml))
                        {
                            renderedHtml = editor.MarkdownDocument.CurrentText;
                        }

                        if (!editor.MarkdownDocument.WriteFile(editor.MarkdownDocument.HtmlRenderFilename, renderedHtml))
                        {
                            // need a way to clear browser window
                            return;
                        }
                    }
                    else
                    {
                        bool usePragma = !showInBrowser && mmApp.Configuration.PreviewSyncMode != PreviewSyncMode.None;
                        if (string.IsNullOrEmpty(renderedHtml))
                        {
                            renderedHtml = editor.MarkdownDocument.RenderHtmlToFile(usePragmaLines: usePragma,
                                                                                    renderLinksExternal: mmApp.Configuration.MarkdownOptions.RenderLinksAsExternal);
                        }

                        if (renderedHtml == null)
                        {
                            Window.SetStatusIcon(FontAwesomeIcon.Warning, Colors.Red, false);
                            Window.ShowStatus($"Access denied: {Path.GetFileName(editor.MarkdownDocument.Filename)}",
                                              5000);
                            // need a way to clear browser window

                            return;
                        }

                        renderedHtml = StringUtils.ExtractString(renderedHtml,
                                                                 "<!-- Markdown Monster Content -->",
                                                                 "<!-- End Markdown Monster Content -->");
                    }

                    if (showInBrowser)
                    {
                        var url = editor.MarkdownDocument.HtmlRenderFilename;
                        mmFileUtils.ShowExternalBrowser(url);
                        return;
                    }

                    WebBrowser.Cursor      = Cursors.None;
                    WebBrowser.ForceCursor = true;

                    // if content contains <script> tags we must do a full page refresh
                    bool forceRefresh = renderedHtml != null && renderedHtml.Contains("<script ");


                    if (keepScrollPosition && !mmApp.Configuration.AlwaysUsePreviewRefresh && !forceRefresh)
                    {
                        string browserUrl   = WebBrowser.Source.ToString().ToLower();
                        string documentFile = "file:///" +
                                              editor.MarkdownDocument.HtmlRenderFilename.Replace('\\', '/')
                                              .ToLower();
                        if (browserUrl == documentFile)
                        {
                            dom = WebBrowser.Document;
                            //var content = dom.getElementById("MainContent");


                            if (string.IsNullOrEmpty(renderedHtml))
                            {
                                PreviewMarkdown(editor, false, false); // fully reload document
                            }
                            else
                            {
                                try
                                {
                                    // explicitly update the document with JavaScript code
                                    // much more efficient and non-jumpy and no wait cursor
                                    var window = dom.parentWindow;
                                    window.updateDocumentContent(renderedHtml);

                                    try
                                    {
                                        // scroll preview to selected line
                                        if (mmApp.Configuration.PreviewSyncMode ==
                                            PreviewSyncMode.EditorAndPreview ||
                                            mmApp.Configuration.PreviewSyncMode == PreviewSyncMode.EditorToPreview)
                                        {
                                            int lineno = editor.GetLineNumber();
                                            if (lineno > -1)
                                            {
                                                window.scrollToPragmaLine(lineno);
                                            }
                                        }
                                    }
                                    catch
                                    {
                                        /* ignore scroll error */
                                    }
                                }
                                catch
                                {
                                    // Refresh doesn't fire Navigate event again so
                                    // the page is not getting initiallized properly
                                    //PreviewBrowser.Refresh(true);
                                    WebBrowser.Tag = "EDITORSCROLL";


                                    WebBrowser.Navigate(new Uri(editor.MarkdownDocument.HtmlRenderFilename));
                                }
                            }

                            return;
                        }
                    }

                    WebBrowser.Tag = "EDITORSCROLL";
                    WebBrowser.Navigate(new Uri(editor.MarkdownDocument.HtmlRenderFilename));
                    return;
                }

                // not a markdown or HTML document to preview
                Window.ShowPreviewBrowser(true, keepScrollPosition);
            }
            catch (Exception ex)
            {
                //mmApp.Log("PreviewMarkdown failed (Exception captured - continuing)", ex);
                Debug.WriteLine("PreviewMarkdown failed (Exception captured - continuing)", ex);
            }
        }