AbstractRenderer.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. using com.insanitydesign.MarkdownViewerPlusPlus.Properties;
  2. using com.insanitydesign.MarkdownViewerPlusPlus.Windows;
  3. using Kbg.NppPluginNET;
  4. using Kbg.NppPluginNET.PluginInfrastructure;
  5. using System;
  6. using System.Diagnostics;
  7. using System.Drawing;
  8. using System.Drawing.Imaging;
  9. using System.Reflection;
  10. using System.Runtime.InteropServices;
  11. using System.Windows.Forms;
  12. using static com.insanitydesign.MarkdownViewerPlusPlus.Windows.WindowsMessage;
  13. using System.Drawing.Printing;
  14. using TheArtOfDev.HtmlRenderer.PdfSharp;
  15. using System.Xml.Linq;
  16. using PdfSharp.Pdf;
  17. using System.IO;
  18. using System.Net;
  19. using com.insanitydesign.MarkdownViewerPlusPlus.Helper;
  20. using static com.insanitydesign.MarkdownViewerPlusPlus.MarkdownViewer;
  21. using Markdig;
  22. using System.Text.RegularExpressions;
  23. using System.Linq;
  24. using System.Collections.Generic;
  25. /// <summary>
  26. ///
  27. /// </summary>
  28. namespace com.insanitydesign.MarkdownViewerPlusPlus.Forms
  29. {
  30. /// <summary>
  31. ///
  32. /// </summary>
  33. public abstract partial class AbstractRenderer : Form
  34. {
  35. /// <summary>
  36. ///
  37. /// </summary>
  38. protected Icon toolbarIcon;
  39. /// <summary>
  40. ///
  41. /// </summary>
  42. protected MarkdownViewer markdownViewer;
  43. /// <summary>
  44. ///
  45. /// </summary>
  46. protected string assemblyTitle;
  47. /// <summary>
  48. ///
  49. /// </summary>
  50. protected virtual string RawText { get; set; }
  51. /// <summary>
  52. ///
  53. /// </summary>
  54. protected virtual string ConvertedText { get; set; }
  55. /// <summary>
  56. ///
  57. /// </summary>
  58. protected virtual FileInformation FileInfo { get; set; }
  59. /// <summary>
  60. ///
  61. /// </summary>
  62. protected MarkdownPipeline markdownPipeline = new MarkdownPipelineBuilder().UseAdvancedExtensions().Build();
  63. /// <summary>
  64. ///
  65. /// </summary>
  66. protected string patternCSSImportStatements = "(@import\\s.+;)";
  67. /// <summary>
  68. ///
  69. /// </summary>
  70. /// <param name="markdownViewer"></param>
  71. public AbstractRenderer(MarkdownViewer markdownViewer)
  72. {
  73. this.markdownViewer = markdownViewer;
  74. InitializeComponent();
  75. Init();
  76. }
  77. /// <summary>
  78. ///
  79. /// </summary>
  80. protected virtual void Init()
  81. {
  82. //
  83. using (Bitmap newBmp = new Bitmap(16, 16))
  84. {
  85. Graphics g = Graphics.FromImage(newBmp);
  86. ColorMap[] colorMap = new ColorMap[1];
  87. colorMap[0] = new ColorMap();
  88. colorMap[0].OldColor = Color.Fuchsia;
  89. colorMap[0].NewColor = Color.FromKnownColor(KnownColor.ButtonFace);
  90. ImageAttributes attr = new ImageAttributes();
  91. attr.SetRemapTable(colorMap);
  92. g.DrawImage(Resources.markdown_16x16_solid_bmp, new Rectangle(0, 0, 16, 16), 0, 0, 16, 16, GraphicsUnit.Pixel, attr);
  93. toolbarIcon = Icon.FromHandle(newBmp.GetHicon());
  94. }
  95. //Get the AssemblyTitle
  96. this.assemblyTitle = ((AssemblyTitleAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(AssemblyTitleAttribute), false)).Title;
  97. //
  98. NppTbData _nppTbData = new NppTbData();
  99. _nppTbData.hClient = this.Handle;
  100. _nppTbData.pszName = this.assemblyTitle;
  101. _nppTbData.dlgID = this.markdownViewer.commandId;
  102. _nppTbData.uMask = NppTbMsg.DWS_DF_CONT_RIGHT | NppTbMsg.DWS_ICONTAB | NppTbMsg.DWS_ICONBAR;
  103. _nppTbData.hIconTab = (uint)toolbarIcon.Handle;
  104. _nppTbData.pszModuleName = Main.PluginName;
  105. IntPtr _ptrNppTbData = Marshal.AllocHGlobal(Marshal.SizeOf(_nppTbData));
  106. Marshal.StructureToPtr(_nppTbData, _ptrNppTbData, false);
  107. //Register dockable window and hide initially
  108. Win32.SendMessage(PluginBase.nppData._nppHandle, (uint)NppMsg.NPPM_DMMREGASDCKDLG, 0, _ptrNppTbData);
  109. Win32.SendMessage(PluginBase.nppData._nppHandle, (uint)NppMsg.NPPM_DMMHIDE, 0, this.Handle);
  110. //Hide the E-mail items if Outlook is not installed
  111. this.sendAsTextMail.Visible = IsOutlookInstalled();
  112. this.sendAsHTMLMail.Visible = IsOutlookInstalled();
  113. }
  114. /// <summary>
  115. ///
  116. /// </summary>
  117. /// <param name="m"></param>
  118. protected override void WndProc(ref Message m)
  119. {
  120. //Listen for the closing of the dockable panel to toggle the toolbar icon
  121. switch (m.Msg)
  122. {
  123. case (int)WM_NOTIFY:
  124. var notify = (NMHDR)Marshal.PtrToStructure(m.LParam, typeof(NMHDR));
  125. if (notify.code == (int)DockMgrMsg.DMN_CLOSE)
  126. {
  127. this.markdownViewer.ToggleToolbarIcon(false);
  128. }
  129. break;
  130. }
  131. //Continue the processing, as we only toggle
  132. base.WndProc(ref m);
  133. }
  134. /// <summary>
  135. ///
  136. /// </summary>
  137. /// <param name="text"></param>
  138. /// <param name="fileInfo"></param>
  139. public virtual void Render(string text, FileInformation fileInfo)
  140. {
  141. FileInfo = fileInfo;
  142. RawText = text;
  143. ConvertedText = Markdown.ToHtml(text, this.markdownPipeline);
  144. }
  145. /// <summary>
  146. ///
  147. /// </summary>
  148. /// <param name="sender"></param>
  149. /// <param name="e"></param>
  150. protected void refreshToolStripMenuItem_Click(object sender, EventArgs e)
  151. {
  152. this.markdownViewer.Update();
  153. }
  154. /// <summary>
  155. /// Scroll the rendered panel vertically based on the given ration
  156. /// taken from Notepad++
  157. /// </summary>
  158. /// <param name="scrollRatio"></param>
  159. public abstract void ScrollByRatioVertically(double scrollRatio);
  160. /// <summary>
  161. ///
  162. /// </summary>
  163. /// <param name="html"></param>
  164. /// <param name="title"></param>
  165. /// <returns></returns>
  166. protected string BuildHtml(string html = "", string title = "")
  167. {
  168. //
  169. if (title == "") title = this.assemblyTitle;
  170. //
  171. return $@"
  172. <!DOCTYPE html>
  173. <html>
  174. <head>
  175. <meta charset=""UTF-8"" />
  176. <meta name=""author"" content=""{this.assemblyTitle}"" />
  177. <title>{title}</title>
  178. <style type=""text/css"">
  179. {this.getCSS()}
  180. </style>
  181. </head>
  182. <body>
  183. {html}
  184. </body>
  185. </html>
  186. ";
  187. }
  188. /// <summary>
  189. ///
  190. /// </summary>
  191. /// <param name="sender"></param>
  192. /// <param name="e"></param>
  193. protected virtual void sendAsTextMail_Click(object sender, EventArgs e)
  194. {
  195. //Double-check
  196. if (IsOutlookInstalled())
  197. {
  198. //Outlook.Application outlook = new Outlook.Application();
  199. //Outlook.MailItem message = (Outlook.MailItem)outlook.CreateItem(Outlook.OlItemType.olMailItem);
  200. ////
  201. //message.Subject = this.FileInfo.FileName;
  202. //message.BodyFormat = Outlook.OlBodyFormat.olFormatPlain;
  203. //message.Body = RawText;
  204. //message.Display();
  205. }
  206. }
  207. /// <summary>
  208. ///
  209. /// </summary>
  210. /// <param name="sender"></param>
  211. /// <param name="e"></param>
  212. protected virtual void sendAsHTMLMail_Click(object sender, EventArgs e)
  213. {
  214. //Double-check
  215. if (IsOutlookInstalled())
  216. {
  217. //Outlook.Application outlook = new Outlook.Application();
  218. //Outlook.MailItem message = (Outlook.MailItem)outlook.CreateItem(Outlook.OlItemType.olMailItem);
  219. ////
  220. //message.Subject = this.FileInfo.FileName;
  221. //message.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;
  222. //message.HTMLBody = BuildHtml(ConvertedText, this.FileInfo.FileName);
  223. //message.Display(true);
  224. }
  225. }
  226. /// <summary>
  227. ///
  228. /// </summary>
  229. /// <param name="sender"></param>
  230. /// <param name="e"></param>
  231. protected virtual void exportAsHTMLMenuItem_Click(object sender, EventArgs e)
  232. {
  233. //Save!
  234. SaveFileDialog saveFileDialog = new SaveFileDialog();
  235. //Default name of the file is the editor file name
  236. saveFileDialog.FileName = Path.GetFileNameWithoutExtension(this.FileInfo.FileName) + ".html";
  237. //The current path
  238. saveFileDialog.InitialDirectory = this.markdownViewer.Notepad.GetCurrentDirectory();
  239. //
  240. saveFileDialog.Filter = "HTML files (*.html)|*.html|All files (*.*)|*.*";
  241. //
  242. if (saveFileDialog.ShowDialog() == DialogResult.OK)
  243. {
  244. using (StreamWriter sw = new StreamWriter(saveFileDialog.FileName))
  245. {
  246. string html = BuildHtml(ConvertedText, this.FileInfo.FileName);
  247. try
  248. {
  249. html = XDocument.Parse(html).ToString();
  250. }
  251. catch { }
  252. sw.WriteLine(html);
  253. }
  254. //Open if requested
  255. if (this.markdownViewer.Options.htmlOpenExport)
  256. {
  257. Process.Start(saveFileDialog.FileName);
  258. }
  259. }
  260. }
  261. /// <summary>
  262. ///
  263. /// </summary>
  264. /// <param name="sender"></param>
  265. /// <param name="e"></param>
  266. protected virtual void exportAsPDFMenuItem_Click(object sender, EventArgs e)
  267. {
  268. //Save!
  269. SaveFileDialog saveFileDialog = new SaveFileDialog();
  270. //Default name of the file is the editor file name
  271. saveFileDialog.FileName = Path.GetFileNameWithoutExtension(this.FileInfo.FileName) + ".pdf";
  272. //The current path
  273. saveFileDialog.InitialDirectory = this.markdownViewer.Notepad.GetCurrentDirectory();
  274. //
  275. saveFileDialog.Filter = "PDF files (*.pdf)|*.pdf|All files (*.*)|*.*";
  276. //
  277. if (saveFileDialog.ShowDialog() == DialogResult.OK)
  278. {
  279. //Build a config based on made settings
  280. PdfGenerateConfig pdfConfig = new PdfGenerateConfig();
  281. pdfConfig.PageOrientation = this.markdownViewer.Options.pdfOrientation;
  282. pdfConfig.PageSize = this.markdownViewer.Options.pdfPageSize;
  283. //Set margins
  284. int[] margins = this.markdownViewer.Options.GetMargins();
  285. pdfConfig.MarginLeft = MilimiterToPoint(margins[0]);
  286. pdfConfig.MarginTop = MilimiterToPoint(margins[1]);
  287. pdfConfig.MarginRight = MilimiterToPoint(margins[2]);
  288. pdfConfig.MarginBottom = MilimiterToPoint(margins[3]);
  289. //Generate PDF and save
  290. PdfDocument pdf = PdfGenerator.GeneratePdf(BuildHtml(ConvertedText, this.FileInfo.FileName), pdfConfig, PdfGenerator.ParseStyleSheet(this.getCSS()));
  291. pdf.Save(saveFileDialog.FileName);
  292. //Open if requested
  293. if (this.markdownViewer.Options.pdfOpenExport)
  294. {
  295. Process.Start(saveFileDialog.FileName);
  296. }
  297. }
  298. }
  299. /// <summary>
  300. ///
  301. /// </summary>
  302. /// <param name="sender"></param>
  303. /// <param name="e"></param>
  304. protected virtual void sendToPrinter_Click(object sender, EventArgs e)
  305. {
  306. //
  307. WebBrowser webBrowser = new WebBrowser();
  308. webBrowser.Parent = this;
  309. webBrowser.DocumentCompleted += (browser, webBrowserEvent) =>
  310. {
  311. ((WebBrowser)browser).Size = webBrowser.MaximumSize;
  312. ((WebBrowser)browser).ShowPrintPreviewDialog();
  313. };
  314. webBrowser.DocumentText = BuildHtml(ConvertedText, this.FileInfo.FileName);
  315. }
  316. /// <summary>
  317. ///
  318. /// </summary>
  319. /// <param name="sender"></param>
  320. /// <param name="e"></param>
  321. protected void sendToClipboard_Click(object sender, EventArgs e)
  322. {
  323. ClipboardHelper.CopyToClipboard(BuildHtml(ConvertedText, this.FileInfo.FileName), ConvertedText);
  324. }
  325. /// <summary>
  326. ///
  327. /// </summary>
  328. /// <returns></returns>
  329. protected virtual String getCSS()
  330. {
  331. string cssImportStatements = "";
  332. //Get all @import statements from the custom CSS
  333. List<Match> matches = Regex.Matches(this.markdownViewer.Options.HtmlCssStyle, this.patternCSSImportStatements).Cast<Match>().ToList();
  334. matches.ForEach(match => match.Captures.Cast<Capture>().ToList().ForEach(capture => cssImportStatements += capture.Value + Environment.NewLine));
  335. //Return a CSS with the @import statements in front, the base MarkdownViewer++ CSS and the rest of the custom CSS from the user
  336. return cssImportStatements + Environment.NewLine + Resources.MarkdownViewerHTML + Environment.NewLine + Regex.Replace(this.markdownViewer.Options.HtmlCssStyle, this.patternCSSImportStatements, "").Trim();
  337. }
  338. /// <summary>
  339. ///
  340. /// </summary>
  341. /// <param name="mm"></param>
  342. /// <returns></returns>
  343. protected int MilimiterToPoint(int mm)
  344. {
  345. return (int)(mm * 2.834646);
  346. }
  347. /// <summary>
  348. ///
  349. /// </summary>
  350. /// <returns></returns>
  351. public bool IsOutlookInstalled()
  352. {
  353. try
  354. {
  355. if (Type.GetTypeFromProgID("Outlook.Application") != null)
  356. {
  357. return true;
  358. }
  359. }
  360. catch { }
  361. return false;
  362. }
  363. /// <summary>
  364. ///
  365. /// </summary>
  366. /// <param name="sender"></param>
  367. /// <param name="e"></param>
  368. private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
  369. {
  370. this.markdownViewer.OptionsCommand();
  371. }
  372. /// <summary>
  373. ///
  374. /// </summary>
  375. /// <param name="sender"></param>
  376. /// <param name="e"></param>
  377. private void aboutToolStripMenuItem1_Click(object sender, EventArgs e)
  378. {
  379. this.markdownViewer.AboutCommand();
  380. }
  381. }
  382. }