// Copyright (c) Microsoft Corporation // The Microsoft Corporation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Drawing; using System.IO; using System.Text.RegularExpressions; using System.Windows.Forms; using Common; using Markdig; using Microsoft.PowerToys.PreviewHandler.Markdown.Properties; using Microsoft.PowerToys.PreviewHandler.Markdown.Telemetry.Events; using Microsoft.PowerToys.Telemetry; using PreviewHandlerCommon; namespace Microsoft.PowerToys.PreviewHandler.Markdown { /// /// Win Form Implementation for Markdown Preview Handler. /// public class MarkdownPreviewHandlerControl : FormHandlerControl { /// /// Extension to modify markdown AST. /// private readonly HTMLParsingExtension _extension; /// /// Markdig Pipeline builder. /// private readonly MarkdownPipelineBuilder _pipelineBuilder; /// /// Markdown HTML header. /// private readonly string htmlHeader = "
"; /// /// Markdown HTML footer. /// private readonly string htmlFooter = "
"; /// /// RichTextBox control to display if external images are blocked. /// private RichTextBox _infoBar; /// /// Extended Browser Control to display markdown html. /// private WebBrowserExt _browser; /// /// True if external image is blocked, false otherwise. /// private bool _infoBarDisplayed; /// /// Initializes a new instance of the class. /// public MarkdownPreviewHandlerControl() { _extension = new HTMLParsingExtension(ImagesBlockedCallBack); _pipelineBuilder = new MarkdownPipelineBuilder().UseAdvancedExtensions().UseEmojiAndSmiley(); _pipelineBuilder.Extensions.Add(_extension); } /// /// Start the preview on the Control. /// /// Path to the file. public override void DoPreview(T dataSource) { _infoBarDisplayed = false; try { if (!(dataSource is string filePath)) { throw new ArgumentException($"{nameof(dataSource)} for {nameof(MarkdownPreviewHandler)} must be a string but was a '{typeof(T)}'"); } string fileText = File.ReadAllText(filePath); Regex imageTagRegex = new Regex(@"<[ ]*img.*>"); if (imageTagRegex.IsMatch(fileText)) { _infoBarDisplayed = true; } _extension.FilePath = Path.GetDirectoryName(filePath); MarkdownPipeline pipeline = _pipelineBuilder.Build(); string parsedMarkdown = Markdig.Markdown.ToHtml(fileText, pipeline); string markdownHTML = $"{htmlHeader}{parsedMarkdown}{htmlFooter}"; InvokeOnControlThread(() => { _browser = new WebBrowserExt { DocumentText = markdownHTML, Dock = DockStyle.Fill, IsWebBrowserContextMenuEnabled = false, ScriptErrorsSuppressed = true, ScrollBarsEnabled = true, AllowNavigation = false, }; Controls.Add(_browser); if (_infoBarDisplayed) { _infoBar = GetTextBoxControl(Resources.BlockedImageInfoText); Resize += FormResized; Controls.Add(_infoBar); } }); PowerToysTelemetry.Log.WriteEvent(new MarkdownFilePreviewed()); } #pragma warning disable CA1031 // Do not catch general exception types catch (Exception ex) #pragma warning restore CA1031 // Do not catch general exception types { PowerToysTelemetry.Log.WriteEvent(new MarkdownFilePreviewError { Message = ex.Message }); InvokeOnControlThread(() => { Controls.Clear(); _infoBarDisplayed = true; _infoBar = GetTextBoxControl(Resources.MarkdownNotPreviewedError); Resize += FormResized; Controls.Add(_infoBar); }); } finally { base.DoPreview(dataSource); } } /// /// Gets a textbox control. /// /// Message to be displayed in textbox. /// An object of type . private RichTextBox GetTextBoxControl(string message) { RichTextBox richTextBox = new RichTextBox { Text = message, BackColor = Color.LightYellow, Multiline = true, Dock = DockStyle.Top, ReadOnly = true, }; richTextBox.ContentsResized += RTBContentsResized; richTextBox.ScrollBars = RichTextBoxScrollBars.None; richTextBox.BorderStyle = BorderStyle.None; return richTextBox; } /// /// Callback when RichTextBox is resized. /// /// Reference to resized control. /// Provides data for the resize event. private void RTBContentsResized(object sender, ContentsResizedEventArgs e) { RichTextBox richTextBox = (RichTextBox)sender; richTextBox.Height = e.NewRectangle.Height + 5; } /// /// Callback when form is resized. /// /// Reference to resized control. /// Provides data for the event. private void FormResized(object sender, EventArgs e) { if (_infoBarDisplayed) { _infoBar.Width = Width; } } /// /// Callback when image is blocked by extension. /// private void ImagesBlockedCallBack() { _infoBarDisplayed = true; } } }