PageRenderTime 63ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/MarkDownSharpEditor/Form1.cs

https://github.com/asanoesw/MarkDownSharpEditor
C# | 3551 lines | 2262 code | 325 blank | 964 comment | 525 complexity | c88aa535553c02d781cd86a947e9b9dd MD5 | raw file
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Windows.Forms;
  9. using System.IO;
  10. using System.Collections;
  11. using System.Security.Cryptography;
  12. using System.Text.RegularExpressions;
  13. using System.Diagnostics;
  14. using System.Runtime.InteropServices;
  15. using System.Windows.Documents;
  16. using MarkDownSharpEditor.Properties;
  17. using mshtml;
  18. namespace MarkDownSharpEditor
  19. {
  20. public partial class Form1 : Form
  21. {
  22. //-----------------------------------
  23. // WebBrowserコンポーネントプレビューの更新音(クリック音)をOFFにする
  24. // Click sound off when webBrowser component preview
  25. const int FEATURE_DISABLE_NAVIGATION_SOUNDS = 21;
  26. const int SET_FEATURE_ON_PROCESS = 0x00000002;
  27. [DllImport("urlmon.dll")]
  28. [PreserveSig]
  29. [return: MarshalAs(UnmanagedType.Error)]
  30. static extern int CoInternetSetFeatureEnabled(int FeatureEntry, [MarshalAs(UnmanagedType.U4)] int dwFlags, bool fEnable);
  31. //-----------------------------------
  32. int undoCounter = 0; // Undo buffer counter
  33. List<string> UndoBuffer = new List<string>();
  34. private bool _fSearchStart = false; //検索を開始したか ( Start search flag )
  35. private int _richEditBoxInternalHeight; //richTextBox1の内部的な高さ ( internal height of richTextBox1 component )
  36. private int _WebBrowserInternalHeight; //webBrowser1の内部的な高さ(body)( internal height of webBrowser1 component )
  37. private Point _preFormPos; //フォームサイズ変更前の位置を一時保存 ( Temporary form position before resizing form )
  38. private Size _preFormSize; //フォームサイズ変更前のサイズを一時保存 ( Temporay form size before resizing form )
  39. private bool _fNoTitle = true; //無題のまま編集中かどうか ( no name of file flag )
  40. private string _MarkDownTextFilePath = ""; //編集中のMDファイルパス ( Editing .MD file path )
  41. private string _TemporaryHtmlFilePath = ""; //プレビュー用のテンポラリHTMLファイルパス ( Temporary HTML file path for preview )
  42. private string _SelectedCssFilePath = ""; //選択中のCSSファイルパス ( Applying CSS file path )
  43. private Encoding _EditingFileEncoding = Encoding.UTF8; //編集中MDファイルの文字エンコーディング ( Character encoding of MD file editing )
  44. private bool _fConstraintChange = true; //更新状態の抑制 ( Constraint changing flag )
  45. private List<MarkdownSyntaxKeyword> _MarkdownSyntaxKeywordAarray = new List<MarkdownSyntaxKeyword>(); // Array of MarkdownSyntaxKeyword Class
  46. private ArrayList _SyntaxArrayList = new ArrayList();
  47. //-----------------------------------
  48. // コンストラクタ ( Constructor )
  49. //-----------------------------------
  50. public Form1()
  51. {
  52. InitializeComponent();
  53. //IME Handler On/Off
  54. if (MarkDownSharpEditor.AppSettings.Instance.Lang == "ja")
  55. {
  56. richTextBox1.IMEWorkaroundEnabled = true;
  57. }
  58. else
  59. {
  60. richTextBox1.IMEWorkaroundEnabled = false;
  61. }
  62. this.richTextBox1.DragEnter += new System.Windows.Forms.DragEventHandler(this.richTextBox1_DragEnter);
  63. this.richTextBox1.DragDrop += new System.Windows.Forms.DragEventHandler(this.richTextBox1_DragDrop);
  64. richTextBox1.AllowDrop = true;
  65. //設定を読み込む ( Read options )
  66. //Program.csで読み込むようにした ( Load in "Program.cs" )
  67. //MarkDownSharpEditor.AppSettings.Instance.ReadFromXMLFile();
  68. //WebBrowserClickSoundOFF();
  69. CoInternetSetFeatureEnabled(FEATURE_DISABLE_NAVIGATION_SOUNDS, SET_FEATURE_ON_PROCESS, true);
  70. }
  71. //----------------------------------------------------------------------
  72. // フォームをロード ( Load main form )
  73. //----------------------------------------------------------------------
  74. private void Form1_Load(object sender, EventArgs e)
  75. {
  76. var obj = MarkDownSharpEditor.AppSettings.Instance;
  77. //-----------------------------------
  78. //フォーム位置・サイズ ( Form position & size )
  79. //-----------------------------------
  80. this.Location = obj.FormPos;
  81. this.Size = obj.FormSize;
  82. this.richTextBox1.Width = obj.richEditWidth;
  83. //ウィンドウ位置の調整(へんなところに行かないように戻す)
  84. // Ajust window position ( Set position into Desktop range )
  85. if (this.Left < 0 || this.Left > Screen.PrimaryScreen.Bounds.Width)
  86. {
  87. this.Left = 0;
  88. }
  89. if (this.Top < 0 || this.Top > Screen.PrimaryScreen.Bounds.Height)
  90. {
  91. this.Top = 0;
  92. }
  93. if (obj.FormState == 1)
  94. { //最小化 ( Minimize )
  95. this.WindowState = FormWindowState.Minimized;
  96. }
  97. else if (obj.FormState == 2)
  98. { //最大化 ( Maximize )
  99. this.WindowState = FormWindowState.Maximized;
  100. }
  101. //メインメニュー表示
  102. //View main menu
  103. this.menuViewToolBar.Checked = obj.fViewToolBar;
  104. this.toolStrip1.Visible = obj.fViewToolBar;
  105. this.menuViewStatusBar.Checked = obj.fViewStatusBar;
  106. this.statusStrip1.Visible = obj.fViewStatusBar;
  107. this.menuViewWidthEvenly.Checked = obj.fSplitBarWidthEvenly;
  108. //言語 ( Language )
  109. if (obj.Lang == "ja")
  110. {
  111. menuViewJapanese.Checked = true;
  112. menuViewEnglish.Checked = false;
  113. }
  114. else
  115. {
  116. menuViewJapanese.Checked = false;
  117. menuViewEnglish.Checked = true;
  118. }
  119. //ブラウザープレビューまでの間隔
  120. //Interval time of browser preview
  121. if (obj.AutoBrowserPreviewInterval > 0)
  122. {
  123. timer1.Interval = obj.AutoBrowserPreviewInterval;
  124. }
  125. //-----------------------------------
  126. //RichEditBox font
  127. FontConverter fc = new FontConverter();
  128. try { richTextBox1.Font = (Font)fc.ConvertFromString(obj.FontFormat); }
  129. catch { }
  130. //RichEditBox font color
  131. richTextBox1.ForeColor = Color.FromArgb(obj.richEditForeColor);
  132. //ステータスバーに表示
  133. //View in statusbar
  134. toolStripStatusLabelFontInfo.Text =
  135. richTextBox1.Font.Name + "," + richTextBox1.Font.Size.ToString() + "pt";
  136. //エディターのシンタックスハイライター設定の反映
  137. //Syntax highlighter of editor window is enabled
  138. _MarkdownSyntaxKeywordAarray = MarkdownSyntaxKeyword.CreateKeywordList();
  139. //-----------------------------------
  140. //選択中のエンコーディングを表示
  141. //View selected character encoding name
  142. foreach (EncodingInfo ei in Encoding.GetEncodings())
  143. {
  144. if (ei.GetEncoding().IsBrowserDisplay == true)
  145. {
  146. if (ei.CodePage == obj.CodePageNumber)
  147. {
  148. toolStripStatusLabelHtmlEncoding.Text = ei.DisplayName;
  149. break;
  150. }
  151. }
  152. }
  153. //-----------------------------------
  154. //指定されたCSSファイル名を表示
  155. //View selected CSS file name
  156. toolStripStatusLabelCssFileName.Text = Resources.toolTipCssFileName; //"CSSファイル指定なし"; ( No CSS file )
  157. if (obj.ArrayCssFileList.Count > 0)
  158. {
  159. string FilePath = (string)obj.ArrayCssFileList[0];
  160. if (File.Exists(FilePath) == true)
  161. {
  162. toolStripStatusLabelCssFileName.Text = Path.GetFileName(FilePath);
  163. _SelectedCssFilePath = FilePath;
  164. }
  165. }
  166. //-----------------------------------
  167. //出力するHTMLエンコーディング表示
  168. //View HTML charcter encoding name for output
  169. if (obj.HtmlEncodingOption == 0)
  170. {
  171. // 編集中(RichEditBox側)のエンコーディング
  172. // 基本的にはテキストファイルが読み込まれたときに表示する
  173. // View encoding name of editor window
  174. toolStripStatusLabelHtmlEncoding.Text = _EditingFileEncoding.EncodingName;
  175. }
  176. else
  177. {
  178. //エンコーディングを指定する(&C)
  179. //Select encoding
  180. Encoding enc = Encoding.GetEncoding(obj.CodePageNumber);
  181. toolStripStatusLabelHtmlEncoding.Text = enc.EncodingName;
  182. }
  183. //-----------------------------------
  184. //検索フォーム・オプション
  185. //Search form options
  186. chkOptionCase.Checked = obj.fSearchOptionIgnoreCase ? false : true;
  187. }
  188. //----------------------------------------------------------------------
  189. // フォームを表示
  190. // View Main form
  191. //----------------------------------------------------------------------
  192. private void Form1_Shown(object sender, EventArgs e)
  193. {
  194. string DirPath = MarkDownSharpEditor.AppSettings.GetAppDataLocalPath();
  195. ArrayList FileArray = new ArrayList();
  196. //TODO: 「新しいウィンドウで開く」="/new"などの引数も含まれるので、
  197. // その辺りの処理も将来的に入れる。
  198. //コマンドラインでファイルが投げ込まれてきている
  199. //Launch with arguments
  200. string[] cmds = System.Environment.GetCommandLineArgs();
  201. for (int i = 1; i < cmds.Count(); i++)
  202. {
  203. if (File.Exists(cmds[i]) == true)
  204. {
  205. FileArray.Add(cmds[i]);
  206. }
  207. }
  208. try
  209. {
  210. if (FileArray.Count > 1)
  211. { //"問い合わせ"
  212. //"複数のファイルが読み込まれました。\n現在の設定内容でHTMLファイルへの一括変換を行いますか?
  213. //「いいえ」を選択するとそのまますべてのファイル開きます。"
  214. //"Question"
  215. //"More than one were read.\nDo you wish to convert all files to HTML files on this options?\n
  216. // if you select 'No', all files will be opend without converting."
  217. DialogResult ret = MessageBox.Show(Resources.MsgConvertAllFilesToHTML,
  218. Resources.DialogTitleQuestion, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information);
  219. if (ret == DialogResult.Yes)
  220. { //一括でHTMLファイル出力
  221. //Output HTML files in batch process
  222. BatchOutputToHtmlFiles((String[])FileArray.ToArray(typeof(string)));
  223. return;
  224. }
  225. else if (ret == DialogResult.Cancel)
  226. { //キャンセル
  227. //Cancel
  228. return;
  229. }
  230. else
  231. { //「いいえ」
  232. // "NO" button
  233. bool fOpen = false;
  234. foreach (string FilePath in FileArray)
  235. { //最初のファイルだけ、このウィンドウだけ開く
  236. //First file open in this window
  237. if (fOpen == false)
  238. {
  239. richTextBox1.Modified = false;
  240. OpenFile(FilePath);
  241. fOpen = true;
  242. }
  243. else
  244. { //他の複数ファイルは順次新しいウィンドウで開く
  245. //Other files open in new windows
  246. System.Diagnostics.Process.Start(
  247. Application.ExecutablePath, string.Format("{0}", FilePath));
  248. }
  249. }
  250. }
  251. }
  252. else if (FileArray.Count == 1)
  253. {
  254. richTextBox1.Modified = false;
  255. OpenFile((string)FileArray[0]);
  256. }
  257. else
  258. { //前に編集していたファイルがあればそれを開く
  259. //Open it if there is editing file before
  260. if (MarkDownSharpEditor.AppSettings.Instance.fOpenEditFileBefore == true)
  261. {
  262. if (MarkDownSharpEditor.AppSettings.Instance.ArrayHistoryEditedFiles.Count > 0)
  263. {
  264. AppHistory EditedFilePath = new AppHistory();
  265. EditedFilePath = (AppHistory)MarkDownSharpEditor.AppSettings.Instance.ArrayHistoryEditedFiles[0];
  266. if (File.Exists(EditedFilePath.md) == true)
  267. {
  268. _TemporaryHtmlFilePath = "";
  269. richTextBox1.Modified = false;
  270. OpenFile(EditedFilePath.md);
  271. return;
  272. }
  273. }
  274. }
  275. if (_MarkDownTextFilePath == "")
  276. { //無ければ「無題」ファイル
  277. // "No title" if no file exists
  278. richTextBox1.Modified = false;
  279. OpenFile("");
  280. }
  281. }
  282. }
  283. finally
  284. {
  285. _fConstraintChange = false;
  286. //SyntaxHighlighter
  287. if (backgroundWorker2.IsBusy == false)
  288. {
  289. //backgroundWorker2.WorkerReportsProgress = true;
  290. backgroundWorker2.RunWorkerAsync(richTextBox1.Text);
  291. }
  292. richTextBox1.Modified = false;
  293. //フォームタイトル更新 / Refresh form caption
  294. FormTextChange();
  295. }
  296. }
  297. //----------------------------------------------------------------------
  298. // フォームタイトルの表示(更新)
  299. // Refresh form caption
  300. //----------------------------------------------------------------------
  301. private void FormTextChange()
  302. {
  303. string FileName;
  304. if (_fNoTitle == true)
  305. {
  306. FileName = Resources.NoFileName; //"(無題)" "(No title)"
  307. }
  308. else
  309. {
  310. //FileName = System.IO.Path.GetFileName(_MarkDownTextFilePath);
  311. FileName = _MarkDownTextFilePath;
  312. }
  313. if (richTextBox1.Modified == true)
  314. {
  315. FileName = FileName + Resources.FlagChanged; //"(更新)"; "(Changed)"
  316. }
  317. this.Text = FileName + " - " + Application.ProductName;
  318. }
  319. //----------------------------------------------------------------------
  320. // 見出しリストメニューの表示
  321. //----------------------------------------------------------------------
  322. private void mnuShowHeaderListMenu_Click(object sender, EventArgs e)
  323. {
  324. ShowHeaderListContextMenu();
  325. }
  326. //----------------------------------------------------------------------
  327. // 見出しリストメニューの表示
  328. //----------------------------------------------------------------------
  329. void ShowHeaderListContextMenu()
  330. {
  331. int retCode;
  332. //Markdown
  333. object[][] mkObject = {
  334. new object[2] { 1, @"^#[^#]*?$" }, //見出し1 (headline1)
  335. new object[2] { 1, @"^.*\n=+$" }, //見出し1 (headline1)
  336. new object[2] { 2, @"^##[^#]*?$" }, //見出し2 (headline2)
  337. new object[2] { 2, @"^.+\n-+$" }, //見出し2 (headline2)
  338. new object[2] { 3, @"^###[^#]*?$" }, //見出し3 (headline3)
  339. new object[2] { 4, @"^####[^#]*?$" }, //見出し4 (headline4)
  340. new object[2] { 5, @"^#####[^#]*?$" }, //見出し5 (headline5)
  341. new object[2] { 6, @"^######[^#]*?$"} //見出し6 (headline6)
  342. };
  343. //コンテキストメニュー項目を初期化(クリア)
  344. //Clear context menus
  345. contextMenu2.Items.Clear();
  346. bool fModify = richTextBox1.Modified;
  347. _fConstraintChange = true;
  348. //現在のカーソル位置
  349. //Current cursor position
  350. int selectStart = this.richTextBox1.SelectionStart;
  351. int selectEnd = richTextBox1.SelectionLength;
  352. Point CurrentOffset = richTextBox1.AutoScrollOffset;
  353. //現在のスクロール位置
  354. //Current scroll position
  355. int CurrentScrollPos = richTextBox1.VerticalPosition;
  356. //描画停止
  357. //Stop to update
  358. richTextBox1.BeginUpdate();
  359. for (int i = 0; i < mkObject.Length; i++)
  360. {
  361. Regex r = new Regex((string)mkObject[i][1], RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.Compiled);
  362. MatchCollection col = r.Matches(richTextBox1.Text, 0);
  363. if (col.Count > 0)
  364. {
  365. foreach (Match m in col)
  366. {
  367. int IndexNum = m.Groups[0].Index;
  368. string title = new String(' ', (int)mkObject[i][0]) + richTextBox1.Text.Substring(m.Groups[0].Index, m.Groups[0].Length);
  369. if ((retCode = title.LastIndexOf("\n")) > -1)
  370. {
  371. title = title.Substring(0, title.LastIndexOf("\n"));
  372. }
  373. //コンテキストメニューに登録
  374. //Regist item to context menus
  375. bool fAdd = false;
  376. ToolStripMenuItem item = new ToolStripMenuItem();
  377. for (int c = 0; c < contextMenu2.Items.Count; c++)
  378. {
  379. //登録されている項目よりも前の項目のときは挿入する
  380. //Insert item to registed items
  381. if (IndexNum < (int)contextMenu2.Items[c].Tag)
  382. {
  383. item.Text = title;
  384. item.Tag = IndexNum;
  385. contextMenu2.Items.Insert(c, item);
  386. fAdd = true;
  387. break;
  388. }
  389. }
  390. if (fAdd == false)
  391. {
  392. item.Text = title;
  393. item.Tag = IndexNum;
  394. contextMenu2.Items.Add(item);
  395. }
  396. }
  397. }
  398. }
  399. //カーソル位置を戻す
  400. //Restore cursor position
  401. richTextBox1.Select(selectStart, selectEnd);
  402. richTextBox1.AutoScrollOffset = CurrentOffset;
  403. //描画再開
  404. //Resume to update
  405. richTextBox1.EndUpdate();
  406. richTextBox1.Modified = fModify;
  407. _fConstraintChange = false;
  408. //richTextBox1のキャレット位置
  409. //Curret position in richTextBox1
  410. Point pt = richTextBox1.GetPositionFromCharIndex(richTextBox1.SelectionStart);
  411. //スクリーン座標に変換
  412. //Convert the position to screen position
  413. pt = richTextBox1.PointToScreen(pt);
  414. //コンテキストメニューを表示
  415. //View context menus
  416. contextMenu2.Show(pt);
  417. }
  418. //----------------------------------------------------------------------
  419. // 見出しメニュークリックイベント
  420. // Click event in context menus
  421. //----------------------------------------------------------------------
  422. private void contextMenu2_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
  423. {
  424. if ((int)e.ClickedItem.Tag > 0)
  425. {
  426. richTextBox1.SelectionStart = (int)e.ClickedItem.Tag;
  427. richTextBox1.ScrollToCaret();
  428. }
  429. }
  430. //----------------------------------------------------------------------
  431. // HACK: RichTextBox内容変更 [ シンタックス・ハイライター表示)]
  432. // Apply richTextBox1 to syntax highlight with changing
  433. //----------------------------------------------------------------------
  434. private void richTextBox1_TextChanged(object sender, EventArgs e)
  435. {
  436. if (_fConstraintChange == true)
  437. {
  438. return;
  439. }
  440. if (backgroundWorker2.IsBusy == false)
  441. {
  442. //バックグラウンドワーカーへパースを投げる / SyntaxHightlighter on BackgroundWorker
  443. backgroundWorker2.RunWorkerAsync(richTextBox1.Text);
  444. }
  445. //-----------------------------------
  446. //Formキャプション変更 / Change form caption
  447. FormTextChange();
  448. //-----------------------------------
  449. //ブラウザプレビュー制御 / Preview webBrowser component
  450. if (MarkDownSharpEditor.AppSettings.Instance.fAutoBrowserPreview == true)
  451. {
  452. timer1.Enabled = true;
  453. }
  454. }
  455. //----------------------------------------------------------------------
  456. // RichTextBox Key Press
  457. //----------------------------------------------------------------------
  458. private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
  459. {
  460. //-----------------------------------
  461. // Add undo buffer
  462. //-----------------------------------
  463. //現在のUndoCounterから先を削除
  464. //Remove first item of undo counter
  465. if (undoCounter < UndoBuffer.Count)
  466. {
  467. UndoBuffer.RemoveRange(undoCounter, UndoBuffer.Count - undoCounter);
  468. }
  469. UndoBuffer.Add(richTextBox1.Rtf);
  470. undoCounter = UndoBuffer.Count;
  471. //EnterやEscapeキーでビープ音が鳴らないようにする
  472. //Stop to beep in Enter & Escape key
  473. if (e.KeyChar == (char)Keys.Enter || e.KeyChar == (char)Keys.Escape)
  474. {
  475. e.Handled = true;
  476. }
  477. timer2.Enabled = true;
  478. }
  479. //----------------------------------------------------------------------
  480. // RichTextBox VScroll event
  481. //----------------------------------------------------------------------
  482. private void richTextBox1_VScroll(object sender, EventArgs e)
  483. {
  484. if (_fConstraintChange == false)
  485. {
  486. WebBrowserMoveCursor();
  487. }
  488. }
  489. //----------------------------------------------------------------------
  490. // RichTextBox Enter event
  491. //----------------------------------------------------------------------
  492. private void richTextBox1_Enter(object sender, EventArgs e)
  493. {
  494. //ブラウザプレビュー制御 / Preview webBrowser component
  495. if (MarkDownSharpEditor.AppSettings.Instance.fAutoBrowserPreview == true)
  496. {
  497. timer1.Enabled = true;
  498. }
  499. }
  500. //----------------------------------------------------------------------
  501. // RichTextBox Mouse click
  502. //----------------------------------------------------------------------
  503. private void richTextBox1_MouseClick(object sender, MouseEventArgs e)
  504. {
  505. //timer1.Enabled = true;
  506. }
  507. //----------------------------------------------------------------------
  508. // Form Closing event
  509. //----------------------------------------------------------------------
  510. private void Form1_FormClosing(object sender, FormClosingEventArgs e)
  511. {
  512. if (richTextBox1.Modified == true)
  513. {
  514. //"問い合わせ"
  515. //"編集中のファイルがあります。保存してから終了しますか?"
  516. //"Question"
  517. //"This file being edited. Do you wish to save before exiting?"
  518. DialogResult ret = MessageBox.Show(Resources.MsgSaveFileToEnd,
  519. Resources.DialogTitleQuestion, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
  520. if (ret == DialogResult.Yes)
  521. {
  522. if (SaveToEditingFile() == true)
  523. {
  524. _fNoTitle = false;
  525. }
  526. else
  527. {
  528. //キャンセルで抜けてきた
  529. //user cancel
  530. e.Cancel = true;
  531. return;
  532. }
  533. }
  534. else if (ret == DialogResult.Cancel)
  535. {
  536. e.Cancel = true;
  537. return;
  538. }
  539. }
  540. _fConstraintChange = true;
  541. //無題ファイルのまま編集しているのなら削除
  542. //Delete file if the file is no title
  543. if (_fNoTitle == true)
  544. {
  545. if (File.Exists(_MarkDownTextFilePath) == true)
  546. {
  547. try
  548. {
  549. File.Delete(_MarkDownTextFilePath);
  550. }
  551. catch
  552. {
  553. }
  554. }
  555. }
  556. //データバージョン
  557. //Data version
  558. System.Reflection.Assembly asmbly = System.Reflection.Assembly.GetExecutingAssembly();
  559. System.Version ver = asmbly.GetName().Version;
  560. MarkDownSharpEditor.AppSettings.Instance.Version = ver.Major * 1000 + ver.Minor * 100 + ver.Build * 10 + ver.Revision;
  561. //フォーム位置・サイズ ( Form position & size )
  562. if (this.WindowState == FormWindowState.Minimized)
  563. { //最小化 ( Minimize )
  564. MarkDownSharpEditor.AppSettings.Instance.FormState = 1;
  565. //一時記憶していた位置・サイズを保存 ( Save temporary position & size value )
  566. MarkDownSharpEditor.AppSettings.Instance.FormPos = new Point(_preFormPos.X, _preFormPos.Y);
  567. MarkDownSharpEditor.AppSettings.Instance.FormSize = new Size(_preFormSize.Width, _preFormSize.Height);
  568. }
  569. else if (this.WindowState == FormWindowState.Maximized)
  570. { //最大化 ( Maximize )
  571. MarkDownSharpEditor.AppSettings.Instance.FormState = 2;
  572. //一時記憶していた位置・サイズを保存 ( Save temporary position & size value )
  573. MarkDownSharpEditor.AppSettings.Instance.FormPos = new Point(_preFormPos.X, _preFormPos.Y);
  574. MarkDownSharpEditor.AppSettings.Instance.FormSize = new Size(_preFormSize.Width, _preFormSize.Height);
  575. }
  576. else
  577. { //通常 ( Normal window )
  578. MarkDownSharpEditor.AppSettings.Instance.FormState = 0;
  579. MarkDownSharpEditor.AppSettings.Instance.FormPos = new Point(this.Left, this.Top);
  580. MarkDownSharpEditor.AppSettings.Instance.FormSize = new Size(this.Width, this.Height);
  581. }
  582. MarkDownSharpEditor.AppSettings.Instance.richEditWidth = this.richTextBox1.Width;
  583. FontConverter fc = new FontConverter();
  584. MarkDownSharpEditor.AppSettings.Instance.FontFormat = fc.ConvertToString(richTextBox1.Font);
  585. MarkDownSharpEditor.AppSettings.Instance.richEditForeColor = richTextBox1.ForeColor.ToArgb();
  586. //表示オプションなど
  587. //Save view options etc
  588. MarkDownSharpEditor.AppSettings.Instance.fViewToolBar = this.menuViewToolBar.Checked;
  589. MarkDownSharpEditor.AppSettings.Instance.fViewStatusBar = this.menuViewStatusBar.Checked;
  590. MarkDownSharpEditor.AppSettings.Instance.fSplitBarWidthEvenly = this.menuViewWidthEvenly.Checked;
  591. //検索オプション
  592. //Save search options
  593. MarkDownSharpEditor.AppSettings.Instance.fSearchOptionIgnoreCase = chkOptionCase.Checked ? false : true;
  594. if (File.Exists(_MarkDownTextFilePath) == true)
  595. {
  596. //編集中のファイルパス
  597. //Save editing file path
  598. foreach (AppHistory data in MarkDownSharpEditor.AppSettings.Instance.ArrayHistoryEditedFiles)
  599. {
  600. if (data.md == _MarkDownTextFilePath)
  601. { //いったん削除して ( delete once ... )
  602. MarkDownSharpEditor.AppSettings.Instance.ArrayHistoryEditedFiles.Remove(data);
  603. break;
  604. }
  605. }
  606. AppHistory HistroyData = new AppHistory();
  607. HistroyData.md = _MarkDownTextFilePath;
  608. HistroyData.css = _SelectedCssFilePath;
  609. MarkDownSharpEditor.AppSettings.Instance.ArrayHistoryEditedFiles.Insert(0, HistroyData); //先頭に挿入 ( Insert at the top )
  610. }
  611. //設定の保存
  612. //Save settings
  613. MarkDownSharpEditor.AppSettings.Instance.SaveToXMLFile();
  614. //MarkDownSharpEditor.AppSettings.Instance.SaveToJsonFile();
  615. timer1.Enabled = false;
  616. //webBrowser1.Navigate("about:blank");
  617. //クリック音対策
  618. //Constraint click sounds
  619. if (webBrowser1.Document != null)
  620. {
  621. webBrowser1.Document.OpenNew(true);
  622. webBrowser1.Document.Write("");
  623. }
  624. }
  625. //-----------------------------------
  626. // Form closed event
  627. //-----------------------------------
  628. private void Form1_FormClosed(object sender, FormClosedEventArgs e)
  629. {
  630. //テンポラリファイルの削除
  631. //Delete temporary files
  632. Delete_TemporaryHtmlFilePath();
  633. }
  634. //-----------------------------------
  635. // Form resize begin event
  636. //-----------------------------------
  637. private void Form1_ResizeBegin(object sender, EventArgs e)
  638. {
  639. //リサイズ前の位置・サイズを一時記憶
  640. _preFormPos.X = this.Left;
  641. _preFormPos.Y = this.Top;
  642. _preFormSize.Width = this.Width;
  643. _preFormSize.Height = this.Height;
  644. }
  645. //-----------------------------------
  646. // Form resize end event
  647. //-----------------------------------
  648. private void Form1_ResizeEnd(object sender, EventArgs e)
  649. {
  650. //ソースウィンドウとビューウィンドウを均等にするか
  651. //Equalize width of source window and view window
  652. if (menuViewWidthEvenly.Checked == true)
  653. {
  654. this.richTextBox1.Width =
  655. (splitContainer1.Width - splitContainer1.SplitterWidth) / 2;
  656. }
  657. }
  658. //-----------------------------------
  659. // richTextBox1 DragEnter event
  660. //-----------------------------------
  661. private void richTextBox1_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
  662. {
  663. if (e.Data.GetDataPresent(DataFormats.FileDrop) == true)
  664. {
  665. e.Effect = DragDropEffects.Copy;
  666. }
  667. else
  668. {
  669. e.Effect = DragDropEffects.None;
  670. }
  671. }
  672. //-----------------------------------
  673. // richTextBox1 Drag and Drop event
  674. //-----------------------------------
  675. private void richTextBox1_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
  676. {
  677. string[] FileArray = (string[])e.Data.GetData(DataFormats.FileDrop, false);
  678. if (FileArray.Length > 1)
  679. {
  680. if (FileArray.Length > 0)
  681. {
  682. //"問い合わせ"
  683. //"複数のファイルが読み込まれました。\n現在の設定内容でHTMLファイルへの一括変換を行いますか?
  684. //「いいえ」を選択するとそのまますべてのファイル開きます。"
  685. //"Question"
  686. //"More than one were read.\nDo you wish to convert all files to HTML files on this options?\n
  687. // if you select 'No', all files will be opend without converting."
  688. DialogResult ret = MessageBox.Show("MsgConvertAllFilesToHTML",
  689. Resources.DialogTitleQuestion, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information);
  690. if (ret == DialogResult.Yes)
  691. {
  692. //一括でHTMLファイル出力
  693. //Output HTML files in batch process
  694. BatchOutputToHtmlFiles(FileArray);
  695. return;
  696. }
  697. else if (ret == DialogResult.Cancel)
  698. {
  699. //キャンセル
  700. //Cancel
  701. return;
  702. }
  703. else
  704. { //「いいえ」
  705. // "No" button
  706. bool fOpen = false;
  707. foreach (string FilePath in FileArray)
  708. {
  709. //最初のファイルだけ、このウィンドウだけ開く
  710. //First file open in this window
  711. if (fOpen == false)
  712. {
  713. OpenFile(FilePath);
  714. fOpen = true;
  715. }
  716. else
  717. {
  718. //他の複数ファイルは順次新しいウィンドウで開く
  719. //Other files open in new windows
  720. System.Diagnostics.Process.Start(
  721. Application.ExecutablePath, string.Format("{0}", FilePath));
  722. }
  723. }
  724. }
  725. }
  726. else
  727. {
  728. //前に編集していたファイルがあればそれを開く
  729. //Open it if there is editing file before
  730. if (MarkDownSharpEditor.AppSettings.Instance.fOpenEditFileBefore == true)
  731. {
  732. if (MarkDownSharpEditor.AppSettings.Instance.ArrayHistoryEditedFiles.Count > 0)
  733. {
  734. AppHistory EditedFilePath = new AppHistory();
  735. EditedFilePath = (AppHistory)MarkDownSharpEditor.AppSettings.Instance.ArrayHistoryEditedFiles[0];
  736. if (File.Exists(EditedFilePath.md) == true)
  737. {
  738. OpenFile(EditedFilePath.md);
  739. }
  740. }
  741. }
  742. }
  743. _fConstraintChange = false;
  744. //フォームタイトル更新
  745. //Refresh form caption
  746. FormTextChange();
  747. ArrayList ArrayFileList = new ArrayList();
  748. foreach (string FilePath in FileArray)
  749. {
  750. ArrayFileList.Add(FilePath);
  751. }
  752. BatchOutputToHtmlFiles((String[])ArrayFileList.ToArray(typeof(string)));
  753. }
  754. else if (FileArray.Count() == 1)
  755. {
  756. //ファイルが一個の場合は編集中のウィンドウで開く
  757. //Open it in this window if file is one
  758. OpenFile(FileArray[0]);
  759. }
  760. }
  761. //----------------------------------------------------------------------
  762. // OpenFile [ .mdファイルを開く ]
  763. //----------------------------------------------------------------------
  764. private bool OpenFile(string FilePath, bool fOpenDialog = false)
  765. {
  766. //引数 FilePath = "" の場合は「無題」編集で開始する
  767. // Argument "FilePath" = "" => Start editing in 'no title'
  768. if (FilePath == "")
  769. {
  770. _fNoTitle = true; // No title flag
  771. }
  772. else
  773. {
  774. _fNoTitle = false;
  775. }
  776. //-----------------------------------
  777. //編集中のファイルがある
  778. if (richTextBox1.Modified == true)
  779. {
  780. //"問い合わせ"
  781. //"編集中のファイルがあります。保存してから終了しますか?"
  782. //"Question"
  783. //"This file being edited. Do you wish to save before exiting?"
  784. DialogResult ret = MessageBox.Show(Resources.MsgSaveFileToEnd,
  785. Resources.DialogTitleQuestion, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
  786. if (ret == DialogResult.Yes)
  787. {
  788. if (SaveToEditingFile() == false)
  789. {
  790. //キャンセルで抜けてきた
  791. //Cancel
  792. return (false);
  793. }
  794. }
  795. else if (ret == DialogResult.Cancel)
  796. {
  797. return (false);
  798. }
  799. //編集履歴に残す
  800. //Save file path to editing history
  801. foreach (AppHistory data in MarkDownSharpEditor.AppSettings.Instance.ArrayHistoryEditedFiles)
  802. {
  803. if (data.md == _MarkDownTextFilePath)
  804. { //いったん削除して ( delete once ... )
  805. MarkDownSharpEditor.AppSettings.Instance.ArrayHistoryEditedFiles.Remove(data);
  806. break;
  807. }
  808. }
  809. AppHistory HistroyData = new AppHistory();
  810. HistroyData.md = _MarkDownTextFilePath;
  811. HistroyData.css = _SelectedCssFilePath;
  812. MarkDownSharpEditor.AppSettings.Instance.ArrayHistoryEditedFiles.Insert(0, HistroyData); //先頭に挿入 ( Insert at the top )
  813. }
  814. //-----------------------------------
  815. //オープンダイアログ表示
  816. //View open file dialog
  817. if (fOpenDialog == true)
  818. {
  819. if (File.Exists(_MarkDownTextFilePath) == true)
  820. { //編集中のファイルがあればそのディレクトリを初期フォルダーに
  821. //Set parent directory of editing file to initial folder
  822. openFileDialog1.InitialDirectory = Path.GetDirectoryName(_MarkDownTextFilePath);
  823. //テンポラリファイルがあればここで削除
  824. //Delete it if temporary file exists
  825. Delete_TemporaryHtmlFilePath();
  826. }
  827. openFileDialog1.FileName = "";
  828. if (openFileDialog1.ShowDialog() == DialogResult.OK)
  829. {
  830. FilePath = openFileDialog1.FileName;
  831. _fNoTitle = false;
  832. }
  833. else
  834. {
  835. return (false);
  836. }
  837. }
  838. //編集中のファイルパスとする
  839. //Set this file to 'editing file' path
  840. _MarkDownTextFilePath = FilePath;
  841. //-----------------------------------
  842. //文字コードを調査するためにテキストファイルを開く
  843. //Detect encoding
  844. if (_fNoTitle == false)
  845. {
  846. byte[] bs;
  847. using (FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read))
  848. {
  849. bs = new byte[fs.Length];
  850. fs.Read(bs, 0, bs.Length);
  851. }
  852. //文字コードを取得する
  853. //Get charcter encoding
  854. _EditingFileEncoding = GetCode(bs);
  855. }
  856. else
  857. {
  858. //「無題」はデフォルトのエンコーディング
  859. // Set this file to default encoding in 'No title'
  860. _EditingFileEncoding = Encoding.UTF8;
  861. }
  862. //ステータスバーに表示
  863. //View in statusbar
  864. toolStripStatusLabelTextEncoding.Text = _EditingFileEncoding.EncodingName;
  865. //編集中のエンコーディングを使用する(&D)か
  866. //Use encoding of editing file
  867. if (MarkDownSharpEditor.AppSettings.Instance.HtmlEncodingOption == 0)
  868. {
  869. toolStripStatusLabelHtmlEncoding.Text = _EditingFileEncoding.EncodingName;
  870. }
  871. //-----------------------------------
  872. //ペアとなるCSSファイルがあるか探索してあれば適用する
  873. //Apply that the pair CSS file to this file exists
  874. foreach (AppHistory data in MarkDownSharpEditor.AppSettings.Instance.ArrayHistoryEditedFiles)
  875. {
  876. if (data.md == _MarkDownTextFilePath)
  877. {
  878. if (File.Exists(data.css) == true)
  879. {
  880. _SelectedCssFilePath = data.css;
  881. break;
  882. }
  883. }
  884. }
  885. //選択中のCSSファイル名をステータスバーに表示
  886. //View selected CSS file name to stausbar
  887. if (File.Exists(_SelectedCssFilePath) == true)
  888. {
  889. toolStripStatusLabelCssFileName.Text = Path.GetFileName(_SelectedCssFilePath);
  890. }
  891. else
  892. {
  893. toolStripStatusLabelCssFileName.Text = Resources.toolTipCssFileName; //"CSSファイル指定なし"; ( not selected CSS file)
  894. }
  895. _fConstraintChange = true;
  896. richTextBox1.Clear();
  897. //RichEditBoxの「フォント」設定
  898. // richTextBox1 font name setting
  899. var obj = MarkDownSharpEditor.AppSettings.Instance;
  900. FontConverter fc = new FontConverter();
  901. try { richTextBox1.Font = (Font)fc.ConvertFromString(obj.FontFormat); }
  902. catch { }
  903. //RichEditBoxの「フォントカラー」設定
  904. // richTextBox1 font color setting
  905. richTextBox1.ForeColor = Color.FromArgb(obj.richEditForeColor);
  906. //View them in statusbar
  907. toolStripStatusLabelFontInfo.Text = richTextBox1.Font.Name + "," + richTextBox1.Font.Size.ToString() + "pt";
  908. //-----------------------------------
  909. //テキストファイルの読み込み
  910. //Read text file
  911. if (File.Exists(FilePath) == true)
  912. {
  913. richTextBox1.Text = File.ReadAllText(FilePath, _EditingFileEncoding);
  914. }
  915. richTextBox1.BeginUpdate();
  916. richTextBox1.SelectionStart = richTextBox1.Text.Length;
  917. richTextBox1.ScrollToCaret();
  918. //richTextBox1の全高さを求める
  919. //Get height of richTextBox1 ( for webBrowser sync )
  920. _richEditBoxInternalHeight = richTextBox1.VerticalPosition;
  921. //カーソル位置を戻す
  922. //Restore cursor position
  923. richTextBox1.SelectionStart = 0;
  924. richTextBox1.EndUpdate();
  925. //変更フラグOFF
  926. richTextBox1.Modified = false;
  927. //Undoバッファに追加
  928. //Add all text to undo buffer
  929. UndoBuffer.Clear();
  930. UndoBuffer.Add(richTextBox1.Rtf);
  931. undoCounter = UndoBuffer.Count;
  932. //プレビュー更新
  933. PreviewToBrowser();
  934. _fConstraintChange = false;
  935. FormTextChange();
  936. return (true);
  937. }
  938. //----------------------------------------------------------------------
  939. // 表示するHTMLのテンポラリファイルパスを取得する
  940. // Get temporary HTML file path
  941. //----------------------------------------------------------------------
  942. private string Get_TemporaryHtmlFilePath(string FilePath)
  943. {
  944. string DirPath = Path.GetDirectoryName(FilePath);
  945. string FileName = Path.GetFileNameWithoutExtension(FilePath);
  946. MD5 md5Hash = MD5.Create();
  947. byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(FileName));
  948. StringBuilder sBuilder = new StringBuilder();
  949. for (int i = 0; i < data.Length; i++)
  950. {
  951. sBuilder.Append(data[i].ToString("x2"));
  952. }
  953. return (Path.Combine(DirPath, FileName + "_" + sBuilder.ToString() + ".html"));
  954. }
  955. //----------------------------------------------------------------------
  956. // 表示しているHTMLのテンポラリファイルを削除する
  957. // Delete temporary HTML file
  958. //----------------------------------------------------------------------
  959. private void Delete_TemporaryHtmlFilePath()
  960. {
  961. string TempHtmlFilePath;
  962. if (_MarkDownTextFilePath == "")
  963. {
  964. return;
  965. }
  966. TempHtmlFilePath = Get_TemporaryHtmlFilePath(_MarkDownTextFilePath);
  967. //見つかったときだけ削除
  968. //Delete it if the file exists
  969. if (File.Exists(TempHtmlFilePath) == true)
  970. {
  971. try
  972. {
  973. File.Delete(TempHtmlFilePath);
  974. }
  975. catch
  976. {
  977. //"エラー"
  978. //"テンポラリファイルの削除に失敗しました。編集中の場所に残った可能性があります。
  979. //"このファイルは手動で削除していただいても問題ありません。
  980. //"Error"
  981. //"Error during deleting temporary file!\na temporary file may be left in the folder the file is edited.\n"
  982. // This file is not a problem even if you delete it manually.
  983. MessageBox.Show(Resources.MsgErrorDeleteTemporaryFile + TempHtmlFilePath,
  984. Resources.DialogTitleError, MessageBoxButtons.OK, MessageBoxIcon.Error);
  985. }
  986. }
  987. }
  988. //----------------------------------------------------------------------
  989. // ブラウザープレビューの間隔を調整
  990. // Ajust browser preview interval
  991. //----------------------------------------------------------------------
  992. private void timer1_Tick(object sender, EventArgs e)
  993. {
  994. PreviewToBrowser();
  995. timer1.Enabled = false;
  996. }
  997. private void timer2_Tick(object sender, EventArgs e)
  998. {
  999. timer2.Enabled = false;
  1000. }
  1001. //----------------------------------------------------------------------
  1002. // HACK: PreviewToBrowser [ ブラウザプレビュー ]
  1003. //----------------------------------------------------------------------
  1004. private void PreviewToBrowser()
  1005. {
  1006. //更新抑制中のときはプレビューしない
  1007. //Do not preview in constraint to change
  1008. if (_fConstraintChange == true)
  1009. {
  1010. return;
  1011. }
  1012. if (backgroundWorker1.IsBusy == true)
  1013. {
  1014. return;
  1015. }
  1016. string ResultText = "";
  1017. backgroundWorker1.WorkerReportsProgress = true;
  1018. //編集箇所にマーカーを挿入する
  1019. //Insert marker in editing
  1020. if (richTextBox1.SelectionStart > 0)
  1021. {
  1022. //int NextLineNum = richTextBox1.GetLineFromCharIndex(richTextBox1.SelectionStart) + 1;
  1023. int ParagraphStart = richTextBox1.GetFirstCharIndexOfCurrentLine();
  1024. //if (ParagraphStart == 0)
  1025. //{
  1026. // ParagraphStart = 1;
  1027. //}
  1028. ResultText =
  1029. richTextBox1.Text.Substring(0, ParagraphStart) + "<!-- edit -->" +
  1030. richTextBox1.Text.Substring(ParagraphStart);
  1031. }
  1032. else
  1033. {
  1034. ResultText = richTextBox1.Text;
  1035. }
  1036. backgroundWorker1.RunWorkerAsync(ResultText);
  1037. }
  1038. //----------------------------------------------------------------------
  1039. // BackgroundWorker ProgressChanged
  1040. //----------------------------------------------------------------------
  1041. private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
  1042. {
  1043. //ProgressBar1.Value = e.ProgressPercentage;
  1044. //Label1.Text = e.ProgressPercentage.ToString();
  1045. }
  1046. //----------------------------------------------------------------------
  1047. // BackgroundWorker browser preview
  1048. //----------------------------------------------------------------------
  1049. private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
  1050. {
  1051. string ResultText = (string)e.Argument;
  1052. string MkResultText = "";
  1053. string BackgroundColorString;
  1054. string EncodingName;
  1055. //編集中のファイル名
  1056. //Editing file name
  1057. string FileName = (_MarkDownTextFilePath == "" ? "" : Path.GetFileName(_MarkDownTextFilePath));
  1058. //DOCTYPE
  1059. HtmlHeader htmlHeader = new HtmlHeader();
  1060. string DocType = htmlHeader.GetHtmlHeader(MarkDownSharpEditor.AppSettings.Instance.HtmlDocType);
  1061. //マーキングの色づけ
  1062. //Marker's color
  1063. if (MarkDownSharpEditor.AppSettings.Instance.fHtmlHighLightColor == true)
  1064. {
  1065. Color ColorBackground = Color.FromArgb(MarkDownSharpEditor.AppSettings.Instance.HtmlHighLightColor);
  1066. BackgroundColorString = ColorTranslator.ToHtml(ColorBackground);
  1067. }
  1068. else
  1069. {
  1070. BackgroundColorString = "none";
  1071. }
  1072. //指定のエンコーディング
  1073. //Codepage
  1074. int CodePageNum = MarkDownSharpEditor.AppSettings.Instance.CodePageNumber;
  1075. try
  1076. {
  1077. Encoding enc = Encoding.GetEncoding(CodePageNum);
  1078. //ブラウザ表示に対応したエンコーディングか
  1079. //Is the encoding supported browser?
  1080. if (enc.IsBrowserDisplay == true)
  1081. {
  1082. EncodingName = enc.WebName;
  1083. }
  1084. else
  1085. {
  1086. EncodingName = "utf-8";
  1087. }
  1088. }
  1089. catch
  1090. {
  1091. //エンコーディングの取得に失敗した場合
  1092. //Default encoding if failing to get encoding
  1093. EncodingName = "utf-8";
  1094. }
  1095. //Header
  1096. string header = string.Format(
  1097. @"{0}
  1098. <html>
  1099. <head>
  1100. <meta http-equiv='Content-Type' content='text/html; charset={1}' />
  1101. <link rel='stylesheet' href='{2}' type='text/css' />
  1102. <style type='text/css'>
  1103. ._mk {{background-color:{3}}}
  1104. </style>
  1105. <title>{4}</title>
  1106. </head>
  1107. <body>
  1108. ",
  1109. DocType, //DOCTYPE
  1110. EncodingName, //エンコーディング ( encoding )
  1111. _SelectedCssFilePath, //適用中のCSSファイル ( Selected CSS file )
  1112. BackgroundColorString, //編集箇所の背景色 ( background color in Editing )
  1113. FileName); //タイトル(=ファイル名) ( title = file name )
  1114. //Footer
  1115. string footer = "</body>\n</html>";
  1116. //-----------------------------------
  1117. //Markdown parse ( default )
  1118. //Markdown mkdwn = new Markdown();
  1119. //-----------------------------------
  1120. //-----------------------------------
  1121. // MarkdownDeep
  1122. // Create an instance of Markdown
  1123. //-----------------------------------
  1124. var mkdwn = new MarkdownDeep.Markdown();
  1125. // Set options
  1126. mkdwn.ExtraMode = MarkDownSharpEditor.AppSettings.Instance.fMarkdownExtraMode;
  1127. mkdwn.SafeMode = false;
  1128. //-----------------------------------
  1129. ResultText = mkdwn.Transform(ResultText);
  1130. //表示するHTMLデータを作成
  1131. //Creat HTML data
  1132. ResultText = header + ResultText + footer;
  1133. //パースされた内容から編集行を探す
  1134. //Search editing line in parsed data
  1135. string OneLine;
  1136. StringReader sr = new StringReader(ResultText);
  1137. StringWriter sw = new StringWriter();
  1138. while ((OneLine = sr.ReadLine()) != null)
  1139. {
  1140. if (OneLine.IndexOf("<!-- edit -->") >= 0)
  1141. {
  1142. MkResultText += ("<div class='_mk'>" + OneLine + "</div>\n");
  1143. }
  1144. else
  1145. {
  1146. MkResultText += (OneLine + "\n");
  1147. }
  1148. }
  1149. //エンコーディングしつつbyte値に変換する(richEditBoxは基本的にutf-8 = 65001)
  1150. //Encode and convert it to 'byte' value ( richEditBox default encoding is utf-8 = 65001 )
  1151. byte[] bytesData = Encoding.GetEncoding(CodePageNum).GetBytes(MkResultText);
  1152. //-----------------------------------
  1153. // Write to temporay file
  1154. if (_fNoTitle == false)
  1155. {
  1156. //テンポラリファイルパスを取得する
  1157. //Get temporary file path
  1158. if (_TemporaryHtmlFilePath == "")
  1159. {
  1160. _TemporaryHtmlFilePath = Get_TemporaryHtmlFilePath(_MarkDownTextFilePath);
  1161. }
  1162. //他のプロセスからのテンポラリファイルの参照と削除を許可して開く(でないと飛ぶ)
  1163. //Open temporary file to allow references from other processes
  1164. using (FileStream fs = new FileStream(
  1165. _TemporaryHtmlFilePath,
  1166. FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read | FileShare.Delete))
  1167. {
  1168. fs.Write(bytesData, 0, bytesData.Length);
  1169. e.Result = _TemporaryHtmlFilePath;
  1170. }
  1171. }
  1172. //-----------------------------------
  1173. // Navigate and view in browser
  1174. else
  1175. {
  1176. //Write data as it is, if the editing data is no title
  1177. ResultText = Encoding.GetEncoding(CodePageNum).GetString(bytesData);
  1178. e.Result = ResultText;
  1179. }
  1180. }
  1181. private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
  1182. {
  1183. if (e.Error != null)
  1184. {
  1185. //Error!
  1186. }
  1187. else
  1188. {
  1189. if ((string)e.Result != "")
  1190. {
  1191. //-----------------------------------
  1192. //スクロールバーの位置を退避しておく
  1193. //Memorize scroll positions
  1194. HtmlDocument doc = webBrowser1.Document;
  1195. Point scrollpos = new Point(0, 0);
  1196. if (doc == null)
  1197. {
  1198. webBrowser1.Navigate("about:blank");
  1199. }
  1200. else
  1201. {
  1202. IHTMLDocument3 doc3 = (IHTMLDocument3)webBrowser1.Document.DomDocument;
  1203. IHTMLElement2 elm = (IHTMLElement2)doc3.documentElement;
  1204. scrollpos = new Point(elm.scrollLeft, elm.scrollTop);
  1205. }
  1206. //-----------------------------------
  1207. System.Threading.Tasks.Task waitTask;
  1208. if (_fNoTitle == false)
  1209. {
  1210. //ナビゲート
  1211. //Browser navigate
  1212. //webBrowser1.Navigate(@"file://" + (string)e.Result);
  1213. waitTask = WebBrowserNavigate(@"file://" + (string)e.Result);
  1214. richTextBox1.Focus();
  1215. toolStripButtonBrowserPreview.Enabled = true;
  1216. }
  1217. else
  1218. {
  1219. webBrowser1.Document.OpenNew(true);
  1220. //webBrowser1.Document.Write((string)e.Result);
  1221. waitTask = WebBrowserDocumentWrite((string)e.Result);
  1222. //ツールバーの「関連付けられたブラウザーを起動」を無効に
  1223. //"Associated web browser" in toolbar is invalid
  1224. toolStripButtonBrowserPreview.Enabled = false;
  1225. }
  1226. //-----------------------------------
  1227. //スクロールバーの位置を復帰する
  1228. //Restore scroll bar position
  1229. if (doc != null)
  1230. {
  1231. waitTask.ContinueWith((arg1) =>
  1232. {
  1233. this.BeginInvoke(new Action(() =>
  1234. {
  1235. doc.Window.ScrollTo(scrollpos);
  1236. this.webBrowser1.Document.Body.AttachEventHandler("onscroll", OnScrollEventHandler);
  1237. }));
  1238. });
  1239. }
  1240. }
  1241. }
  1242. }
  1243. /// <summary>
  1244. /// webBrowser コンポーネントにHTMLを出力して
  1245. /// DocumentComplate になるのを非同期で待ち合わせる
  1246. /// </summary>
  1247. /// <param name="html"></param>
  1248. /// <returns></returns>
  1249. System.Threading.Tasks.Task WebBrowserDocumentWrite(string html)
  1250. {
  1251. if (browserWaitTimer == null)
  1252. {
  1253. browserWaitTimer = new Timer();
  1254. browserWaitTimer.Tick += browserWaitTimer_Tick;
  1255. browserWaitTimer.Enabled = true;
  1256. }
  1257. var obj = waitObject;
  1258. if (obj != null)
  1259. {
  1260. obj.SetCanceled();
  1261. }
  1262. waitObject = new System.Threading.Tasks.TaskCompletionSource<string>();
  1263. timerCount = 0;
  1264. this.webBrowser1.DocumentText = html;
  1265. browserWaitTimer.Enabled = true;
  1266. return waitObject.Task;
  1267. }
  1268. /// <summary>
  1269. /// webBrowser コンポーネントにHTMLを出力して
  1270. /// DocumentComplate になるのを非同期で待ち合わせる
  1271. /// </summary>
  1272. /// <param name="html"></param>
  1273. /// <returns></returns>
  1274. System.Threading.Tasks.Task WebBrowserNavigate(string url)
  1275. {
  1276. if (browserWaitTimer == null)
  1277. {
  1278. browserWaitTimer = new Timer();
  1279. browserWaitTimer.Tick += browserWaitTimer_Tick;
  1280. browserWaitTimer.Enabled = true;
  1281. }
  1282. var obj = waitObject;
  1283. if (obj != null)
  1284. {
  1285. obj.SetCanceled();
  1286. }
  1287. waitObject = new System.Threading.Tasks.TaskCompletionSource<string>();
  1288. timerCount = 0;
  1289. this.webBrowser1.Navigate(url);
  1290. browserWaitTimer.Enabled = true;
  1291. return waitObject.Task;
  1292. }
  1293. void browserWaitTimer_Tick(object sender, EventArgs e)
  1294. {
  1295. if (waitObject == null)
  1296. {
  1297. browserWaitTimer.Enabled = false;
  1298. return;
  1299. }
  1300. timerCount++;
  1301. if (this.webBrowser1.ReadyState == WebBrowserReadyState.Complete)
  1302. {
  1303. waitObject.SetResult("OK");
  1304. waitObject = null;
  1305. browserWaitTimer.Enabled = false;
  1306. }
  1307. else if (timerCount > 20)
  1308. {
  1309. // 反応ないので終わりにする
  1310. waitObject.SetResult("OK");
  1311. waitObject = null;
  1312. browserWaitTimer.Enabled = false;
  1313. }
  1314. }
  1315. System.Threading.Tasks.TaskCompletionSource<string> waitObject = null;
  1316. int timerCount = 0;
  1317. Timer browserWaitTimer;
  1318. //----------------------------------------------------------------------
  1319. // BackgroundWorker Syntax hightlighter work
  1320. //----------------------------------------------------------------------
  1321. private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
  1322. {
  1323. var text = e.Argument as string;
  1324. if (string.IsNullOrEmpty(text))
  1325. {
  1326. e.Result = null;
  1327. return;
  1328. }
  1329. if (timer2.Enabled == true)
  1330. {
  1331. e.Result = null;
  1332. return;
  1333. }
  1334. var result = new List<SyntaxColorScheme>();
  1335. foreach (MarkdownSyntaxKeyword mk in _MarkdownSyntaxKeywordAarray)
  1336. {
  1337. MatchCollection col = mk.Regex.Matches(text, 0);
  1338. if (col.Count > 0)
  1339. {
  1340. foreach (Match m in col)
  1341. {
  1342. SyntaxColorScheme sytx = new SyntaxColorScheme();
  1343. sytx.SelectionStartIndex = m.Groups[0].Index;
  1344. sytx.SelectionLength = m.Groups[0].Length;
  1345. sytx.ForeColor = mk.ForeColor;
  1346. sytx.BackColor = mk.BackColor;
  1347. result.Add(sytx);
  1348. }
  1349. }
  1350. }
  1351. e.Result = result;
  1352. }
  1353. //----------------------------------------------------------------------
  1354. // BackgroundWorker Editor Syntax hightlighter progress changed
  1355. //----------------------------------------------------------------------
  1356. private void backgroundWorker2_ProgressChanged(object sender, ProgressChangedEventArgs e)
  1357. {
  1358. }
  1359. //----------------------------------------------------------------------
  1360. // BackgroundWorker Syntax hightlighter completed to work
  1361. //----------------------------------------------------------------------
  1362. private void backgroundWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
  1363. {
  1364. if (e.Error != null || e.Cancelled == true)
  1365. {
  1366. return;
  1367. }
  1368. var syntaxColorSchemeList = e.Result as List<SyntaxColorScheme>;
  1369. if (syntaxColorSchemeList == null)
  1370. {
  1371. return;
  1372. }
  1373. var obj = MarkDownSharpEditor.AppSettings.Instance;
  1374. Font fc = richTextBox1.Font; //現在のフォント設定 ( Font option )
  1375. bool fModify = richTextBox1.Modified; //現在の編集状況 ( Modified flag )
  1376. _fConstraintChange = true;
  1377. //現在のカーソル位置 / Current cursor position
  1378. int selectStart = this.richTextBox1.SelectionStart;
  1379. int selectEnd = richTextBox1.SelectionLength;
  1380. Point CurrentOffset = richTextBox1.AutoScrollOffset;
  1381. //現在のスクロール位置 / Current scroll position
  1382. int CurrentScrollPos = richTextBox1.VerticalPosition;
  1383. //描画停止 / Stop to paint
  1384. richTextBox1.BeginUpdate();
  1385. //RichTextBoxの書式をクリアする / Clear richTextBox1 format options
  1386. richTextBox1.ForeColor = Color.FromArgb(obj.ForeColor_MainText);
  1387. richTextBox1.BackColor = Color.FromArgb(obj.BackColor_MainText);
  1388. //裏でパースしていたシンタックスハイライターを反映。
  1389. foreach (var s in syntaxColorSchemeList)
  1390. {
  1391. richTextBox1.Select(s.SelectionStartIndex, s.SelectionLength);
  1392. richTextBox1.SelectionColor = s.ForeColor;
  1393. richTextBox1.SelectionBackColor = s.BackColor;
  1394. }
  1395. //カーソル位置を戻す / Restore cursor position
  1396. richTextBox1.Select(selectStart, selectEnd);
  1397. richTextBox1.AutoScrollOffset = CurrentOffset;
  1398. richTextBox1.VerticalPosition = CurrentScrollPos;
  1399. //描画再開 / Resume to paint
  1400. richTextBox1.EndUpdate();
  1401. richTextBox1.Modified = fModify;
  1402. _fConstraintChange = false;
  1403. if (MarkDownSharpEditor.AppSettings.Instance.AutoBrowserPreviewInterval < 0)
  1404. {
  1405. //手動更新 / Manual refresh
  1406. timer1.Enabled = false;
  1407. return;
  1408. }
  1409. else
  1410. {
  1411. timer1.Enabled = true;
  1412. }
  1413. }
  1414. //----------------------------------------------------------------------
  1415. // プレビューページが読み込まれたら編集中の箇所へ自動スクロールする
  1416. // Scroll to editing line when browser is loaded
  1417. //----------------------------------------------------------------------
  1418. private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
  1419. {
  1420. //更新抑制中のときは抜ける
  1421. //Constraint to change
  1422. if (_fConstraintChange == true)
  1423. {
  1424. return;
  1425. }
  1426. //読み込まれた表示領域の高さを取得
  1427. //Get viewing area to load in browser component
  1428. _WebBrowserInternalHeight = webBrowser1.Document.Body.ScrollRectangle.Height;
  1429. //ブラウザのスクロールイベントハンドラ
  1430. //Browser component event handler
  1431. webBrowser1.Document.Window.AttachEventHandler("onscroll", OnScrollEventHandler);
  1432. }
  1433. //----------------------------------------------------------------------
  1434. // Browser component scrolll event
  1435. //----------------------------------------------------------------------
  1436. public void OnScrollEventHandler(object sender, EventArgs e)
  1437. {
  1438. RichEditBoxMoveCursor();
  1439. }
  1440. //----------------------------------------------------------------------
  1441. // TODO: WebBrowserMoveCursor [RichEditBox → WebBrowser scroll follow]
  1442. //----------------------------------------------------------------------
  1443. private void WebBrowserMoveCursor()
  1444. {
  1445. if (webBrowser1.Document == null)
  1446. {
  1447. return;
  1448. }
  1449. if (richTextBox1.Focused == true)
  1450. {
  1451. //richEditBoxの内部的な高さから現在位置の割合を計算
  1452. //Calculate current position with internal height of richTextBox1
  1453. int LineHeight = Math.Abs(richTextBox1.GetPositionFromCharIndex(0).Y);
  1454. float perHeight = (float)LineHeight / _richEditBoxInternalHeight;
  1455. //その割合からwebBrowserのスクロール量を計算
  1456. //Calculate scroll amount with the ratio
  1457. _WebBrowserInternalHeight = webBrowser1.Document.Body.ScrollRectangle.Height;
  1458. int y = (int)(_WebBrowserInternalHeight * perHeight);
  1459. Point webScrollPos = new Point(0, y);
  1460. //Follow to scroll browser component
  1461. webBrowser1.Document.Window.ScrollTo(webScrollPos);
  1462. }
  1463. }
  1464. //----------------------------------------------------------------------
  1465. // HACK: RichEditBoxMoveCursor[ WebBrowser → RichEditBox scroll follow]
  1466. //----------------------------------------------------------------------
  1467. private void RichEditBoxMoveCursor()
  1468. {
  1469. //ブラウザでのスクロールバーの位置
  1470. //Position of scroll bar in browser component
  1471. if (richTextBox1.Focused == false && webBrowser1.Document != null)
  1472. {
  1473. IHTMLDocument3 doc3 = (IHTMLDocument3)webBrowser1.Document.DomDocument;
  1474. IHTMLElement2 elm = (IHTMLElement2)doc3.documentElement;
  1475. //全高さからの割合(位置)
  1476. //Ratio(Position) of height
  1477. float perHeight = (float)elm.scrollTop / _WebBrowserInternalHeight;
  1478. int y = (int)(_richEditBoxInternalHeight * perHeight);
  1479. richTextBox1.VerticalPosition = y;
  1480. }
  1481. }
  1482. //----------------------------------------------------------------------
  1483. // webBrowser1 Navigated event
  1484. //----------------------------------------------------------------------
  1485. private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
  1486. {
  1487. //ブラウザー操作ボタンの有効・無効化
  1488. toolStripButtonBack.Enabled = webBrowser1.CanGoBack;
  1489. toolStripButtonForward.Enabled = webBrowser1.CanGoForward;
  1490. }
  1491. //----------------------------------------------------------------------
  1492. // HTML形式出力 ( Output to HTML file )
  1493. //----------------------------------------------------------------------
  1494. private bool OutputToHtmlFile(string FilePath, string SaveToFilePath, bool fToClipboard = false)
  1495. {
  1496. if (File.Exists(FilePath) == false)
  1497. {
  1498. return (false);
  1499. }
  1500. //出力内容 ( Output data )
  1501. string ResultText = "";
  1502. //HTMLタグ ( HTML Header tag )
  1503. string HeaderString = "";
  1504. string FooterString = "";
  1505. //文字コード ( Character encoding )
  1506. string EncodingName;
  1507. Encoding encRead = Encoding.UTF8;
  1508. Encoding encHtml = Encoding.UTF8;
  1509. //-----------------------------------
  1510. //編集中のファイルパス or 投げ込まれたファイルパス
  1511. //Editing file path or Drag & Dropped files
  1512. string FileName = Path.GetFileName(FilePath);
  1513. //-----------------------------------
  1514. //DOCTYPE
  1515. HtmlHeader htmlHeader = new HtmlHeader();
  1516. string DocType = htmlHeader.GetHtmlHeader(MarkDownSharpEditor.AppSettings.Instance.HtmlDocType);
  1517. //Web用の相対パス
  1518. //Relative url
  1519. string CssPath = RerativeFilePath(FilePath, _SelectedCssFilePath);
  1520. //-----------------------------------
  1521. //指定のエンコーディング
  1522. //Codepage
  1523. int CodePageNum = MarkDownSharpEditor.AppSettings.Instance.CodePageNumber;
  1524. try
  1525. {
  1526. encHtml = Encoding.GetEncoding(CodePageNum);
  1527. //ブラウザ表示に対応したエンコーディングか
  1528. //Is the encoding supported browser?
  1529. if (encHtml.IsBrowserDisplay == true)
  1530. {
  1531. EncodingName = encHtml.WebName;
  1532. }
  1533. else
  1534. {
  1535. EncodingName = "utf-8";
  1536. encHtml = Encoding.UTF8;
  1537. }
  1538. }
  1539. catch
  1540. {
  1541. //エンコーディングの取得に失敗した場合はデフォルト
  1542. //Default encoding if failing to get encoding
  1543. EncodingName = "utf-8";
  1544. encHtml = Encoding.UTF8;
  1545. }
  1546. //HTMLのヘッダを挿入する
  1547. //Insert HTML Header
  1548. if (MarkDownSharpEditor.AppSettings.Instance.fHtmlOutputHeader == true)
  1549. {
  1550. //CSSファイルを埋め込む
  1551. //Embeding CSS file contents
  1552. if (MarkDownSharpEditor.AppSettings.Instance.HtmlCssFileOption == 0)
  1553. {
  1554. string CssContents = "";
  1555. if (File.Exists(_SelectedCssFilePath) == true)
  1556. {
  1557. using (StreamReader sr = new StreamReader(_SelectedCssFilePath, encHtml))
  1558. {
  1559. CssContents = sr.ReadToEnd();
  1560. }
  1561. }
  1562. //ヘッダ ( Header )
  1563. HeaderString = string.Format(
  1564. @"{0}
  1565. <html>
  1566. <head>
  1567. <meta http-equiv='Content-Type' content='text/html; charset={1}' />
  1568. <title>{2}</title>
  1569. <style>
  1570. <--
  1571. {3}
  1572. -->
  1573. </style>
  1574. </head>
  1575. <body>
  1576. ",
  1577. DocType, //DOCTYPE
  1578. EncodingName, //エンコーディング ( Encoding )
  1579. FileName, //タイトル(=ファイル名) ( Title = file name )
  1580. CssContents); //CSSの内容 ( Contents of CSS file )
  1581. }
  1582. //metaタグ(外部リンキング)(Meta tag: external linking )
  1583. else
  1584. {
  1585. //ヘッダ ( Header )
  1586. HeaderString = string.Format(
  1587. @"{0}
  1588. <html>
  1589. <head>
  1590. <meta http-equiv='Content-Type' content='text/html; charset={1}' />
  1591. <link rel='stylesheet' href='{2}' type='text/css' />
  1592. <title>{3}</title>
  1593. </head>
  1594. <body>
  1595. ",
  1596. DocType, //DOCTYPE
  1597. EncodingName, //エンコーディング ( Encoding )
  1598. CssPath, //CSSファイル(相対パス)( Relative url )
  1599. FileName); //タイトル(=ファイル名) ( Title = file name )
  1600. }
  1601. //フッタ ( Footer )
  1602. FooterString = "</body>\n</html>";
  1603. }
  1604. else
  1605. {
  1606. HeaderString = "";
  1607. FooterString = "";
  1608. }
  1609. //-----------------------------------
  1610. //Markdown parse ( default )
  1611. //Markdown mkdwn = new Markdown();
  1612. //-----------------------------------
  1613. //-----------------------------------
  1614. // MarkdownDeep
  1615. // Create an instance of Markdown
  1616. //-----------------------------------
  1617. var mkdwn = new MarkdownDeep.Markdown();
  1618. // Set options
  1619. mkdwn.ExtraMode = MarkDownSharpEditor.AppSettings.Instance.fMarkdownExtraMode;
  1620. mkdwn.SafeMode = false;
  1621. //-----------------------------------
  1622. //編集中のファイル(richEditBoxの内容)
  1623. //Editing file path
  1624. if (_MarkDownTextFilePath == FilePath)
  1625. {
  1626. ResultText = mkdwn.Transform(richTextBox1.Text);
  1627. //エンコーディング変換(richEditBoxは基本的にutf-8)
  1628. //Convert encoding ( richEditBox default encoding is utf-8 = 65001 )
  1629. ResultText = ConvertStringToEncoding(ResultText, Encoding.UTF8.CodePage, CodePageNum);
  1630. }
  1631. else
  1632. {
  1633. //テキストファイルを開いてその文字コードに従って読み込み
  1634. //Detect encoding in the text file
  1635. byte[] bs;
  1636. using (FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read))
  1637. {
  1638. bs = new byte[fs.Length];
  1639. fs.Read(bs, 0, bs.Length);
  1640. }
  1641. //文字コードを取得する
  1642. //Get charcter encoding
  1643. encRead = GetCode(bs);
  1644. //取得したバイト列を文字列に変換
  1645. //Convert byte values to character
  1646. ResultText = encRead.GetString(bs);
  1647. //UTF-8でないならいったん変換してパース
  1648. //Convert it if encoding is not utf-8
  1649. if (encRead != Encoding.UTF8)
  1650. {
  1651. ResultText = ConvertStringToEncoding(ResultText, encRead.CodePage, CodePageNum);
  1652. }
  1653. ResultText = mkdwn.Transform(ResultText);
  1654. }
  1655. //ヘッダ+本文+フッタ
  1656. //Header + Contents + Footer
  1657. ResultText = HeaderString + ResultText + FooterString;
  1658. //出力するHTMLファイルの文字コードに合わせる
  1659. //Ajust encoding to output HTML file
  1660. ResultText = ConvertStringToEncoding(ResultText, Encoding.UTF8.CodePage, CodePageNum);
  1661. if (fToClipboard == true)
  1662. { //クリップボードに書き込む
  1663. //Set data to clipbord
  1664. Clipboard.SetText(ResultText);
  1665. }
  1666. else
  1667. { //ファイルに書き込む
  1668. //Write file
  1669. using (StreamWriter sw = new StreamWriter(SaveToFilePath, false, encHtml))
  1670. {
  1671. sw.Write(ResultText);
  1672. }
  1673. }
  1674. return (true);
  1675. }
  1676. //----------------------------------------------------------------------
  1677. // HTML形式ファイルへのバッチ出力
  1678. // Output HTML files in batch
  1679. //----------------------------------------------------------------------
  1680. private bool BatchOutputToHtmlFiles(string[] ArrrayFileList)
  1681. {
  1682. string OutputFilePath;
  1683. foreach (string FilePath in ArrrayFileList)
  1684. {
  1685. OutputFilePath = Path.ChangeExtension(FilePath, ".html");
  1686. if (OutputToHtmlFile(FilePath, OutputFilePath, false) == false)
  1687. {
  1688. return (false);
  1689. }
  1690. }
  1691. return (true);
  1692. }
  1693. //----------------------------------------------------------------------
  1694. // 基本パスから相対パスを取得する
  1695. // Get relative file path from base file path
  1696. //----------------------------------------------------------------------
  1697. private string RerativeFilePath(string BaseFilePath, string TargetFilePath)
  1698. {
  1699. Uri u1 = new Uri(BaseFilePath);
  1700. Uri u2 = new Uri(u1, TargetFilePath);
  1701. string RelativeFilePath = u1.MakeRelativeUri(u2).ToString();
  1702. //URLデコードして、"/" を "\" に変更する
  1703. RelativeFilePath = System.Web.HttpUtility.UrlDecode(RelativeFilePath).Replace('/', '\\');
  1704. return (RelativeFilePath);
  1705. }
  1706. //----------------------------------------------------------------------
  1707. // テキストを指定のエンコーディング文字列に変換する
  1708. // Convert text data to user encoding characters
  1709. //----------------------------------------------------------------------
  1710. public string ConvertStringToEncoding(string source, int SrcCodePage, int DestCodePage)
  1711. {
  1712. Encoding srcEnc;
  1713. Encoding destEnc;
  1714. try
  1715. {
  1716. srcEnc = Encoding.GetEncoding(SrcCodePage);
  1717. destEnc = Encoding.GetEncoding(DestCodePage);
  1718. }
  1719. catch
  1720. {
  1721. //指定のコードページがおかしい(取得できない)
  1722. //Error: Codepage is incorrect
  1723. return (source);
  1724. }
  1725. //Byte配列で変換する
  1726. //Convert to byte values
  1727. byte[] srcByte = srcEnc.GetBytes(source);
  1728. byte[] destByte = Encoding.Convert(srcEnc, destEnc, srcByte);
  1729. char[] destChars = new char[destEnc.GetCharCount(destByte, 0, destByte.Length)];
  1730. destEnc.GetChars(destByte, 0, destByte.Length, destChars, 0);
  1731. return new string(destChars);
  1732. }
  1733. //======================================================================
  1734. #region ブラウザーのツールバーメニュー ( Toolbar on browser )
  1735. //======================================================================
  1736. //----------------------------------------------------------------------
  1737. // ブラウザの「戻る」 ( Browser back )
  1738. //----------------------------------------------------------------------
  1739. private void toolStripButtonBack_Click(object sender, EventArgs e)
  1740. {
  1741. if (webBrowser1.CanGoBack == true)
  1742. {
  1743. webBrowser1.GoBack();
  1744. }
  1745. }
  1746. //----------------------------------------------------------------------
  1747. // ブラウザの「進む」 ( Browser forward )
  1748. //----------------------------------------------------------------------
  1749. private void toolStripButtonForward_Click(object sender, EventArgs e)
  1750. {
  1751. if (webBrowser1.CanGoForward == true)
  1752. {
  1753. webBrowser1.GoForward();
  1754. }
  1755. }
  1756. //----------------------------------------------------------------------
  1757. // ブラウザの「更新」 ( Browser refresh )
  1758. //----------------------------------------------------------------------
  1759. private void toolStripButtonRefresh_Click(object sender, EventArgs e)
  1760. {
  1761. //手動更新設定
  1762. //Manual to refresh browser
  1763. if (MarkDownSharpEditor.AppSettings.Instance.fAutoBrowserPreview == false)
  1764. {
  1765. //プレビューしているのは編集中のファイルか
  1766. //Is previewing file the editing file?
  1767. if (webBrowser1.Url.AbsoluteUri == @"file://" + _TemporaryHtmlFilePath)
  1768. {
  1769. PreviewToBrowser();
  1770. }
  1771. }
  1772. webBrowser1.Refresh();
  1773. }
  1774. //----------------------------------------------------------------------
  1775. // ブラウザの「中止」 ( Browser stop )
  1776. //----------------------------------------------------------------------
  1777. private void toolStripButtonStop_Click(object sender, EventArgs e)
  1778. {
  1779. webBrowser1.Stop();
  1780. }
  1781. //----------------------------------------------------------------------
  1782. // 規定のブラウザーを関連付け起動してプレビュー
  1783. // Launch default web browser to preview
  1784. //----------------------------------------------------------------------
  1785. private void toolStripButtonBrowserPreview_Click(object sender, EventArgs e)
  1786. {
  1787. if (File.Exists(_TemporaryHtmlFilePath) == true)
  1788. {
  1789. System.Diagnostics.Process.Start(_TemporaryHtmlFilePath);
  1790. }
  1791. else
  1792. {
  1793. _TemporaryHtmlFilePath = "";
  1794. }
  1795. }
  1796. #endregion
  1797. //======================================================================
  1798. //======================================================================
  1799. #region メインメニューイベント ( Main menu events )
  1800. //======================================================================
  1801. //-----------------------------------
  1802. //「新しいファイルを開く」メニュー
  1803. // "New file" menu
  1804. //-----------------------------------
  1805. private void menuNewFile_Click(object sender, EventArgs e)
  1806. {
  1807. if (richTextBox1.Modified == true)
  1808. {
  1809. //"問い合わせ"
  1810. //"編集中のファイルがあります。保存してから新しいファイルを開きますか?"
  1811. //"Question"
  1812. //"This file being edited. Do you wish to save before starting new file?"
  1813. DialogResult ret = MessageBox.Show(Resources.MsgSaveFileToNewFile,
  1814. Resources.DialogTitleQuestion, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
  1815. if (ret == DialogResult.Yes)
  1816. {
  1817. if (SaveToEditingFile() == true)
  1818. {
  1819. _fNoTitle = false; //無題フラグOFF
  1820. }
  1821. else
  1822. {
  1823. //キャンセルで抜けてきた
  1824. //Cancel
  1825. return;
  1826. }
  1827. }
  1828. else if (ret == DialogResult.Cancel)
  1829. {
  1830. return;
  1831. }
  1832. }
  1833. //前の編集していたテンポラリを削除する
  1834. //Delete edited temporary file before
  1835. Delete_TemporaryHtmlFilePath();
  1836. //無題ファイルのまま編集しているのなら削除
  1837. //Delete it if the file is no title
  1838. if (_fNoTitle == true)
  1839. {
  1840. if (File.Exists(_MarkDownTextFilePath) == true)
  1841. {
  1842. try
  1843. {
  1844. File.Delete(_MarkDownTextFilePath);
  1845. }
  1846. catch
  1847. {
  1848. }
  1849. }
  1850. }
  1851. //編集履歴に残す
  1852. //Add editing history
  1853. if (File.Exists(_MarkDownTextFilePath) == true)
  1854. {
  1855. foreach (AppHistory data in MarkDownSharpEditor.AppSettings.Instance.ArrayHistoryEditedFiles)
  1856. {
  1857. if (data.md == _MarkDownTextFilePath)
  1858. { //いったん削除して ( delete once ... )
  1859. MarkDownSharpEditor.AppSettings.Instance.ArrayHistoryEditedFiles.Remove(data);
  1860. break;
  1861. }
  1862. }
  1863. AppHistory HistroyData = new AppHistory();
  1864. HistroyData.md = _MarkDownTextFilePath;
  1865. HistroyData.css = _SelectedCssFilePath;
  1866. MarkDownSharpEditor.AppSettings.Instance.ArrayHistoryEditedFiles.Insert(0, HistroyData); //先頭に挿入
  1867. }
  1868. _fConstraintChange = true;
  1869. //ブラウザを空白にする
  1870. //Be blank in browser
  1871. webBrowser1.Navigate("about:blank");
  1872. //テンポラリファイルがあれば削除
  1873. //Delete it if temporary file exists
  1874. Delete_TemporaryHtmlFilePath();
  1875. //編集中のファイル情報をクリア
  1876. //Clear the infomation of editing file
  1877. _MarkDownTextFilePath = "";
  1878. //「無題」編集開始
  1879. //Start to edit in no title
  1880. _fNoTitle = true;
  1881. richTextBox1.Text = "";
  1882. richTextBox1.Modified = false;
  1883. FormTextChange();
  1884. _fConstraintChange = false;
  1885. }
  1886. //-----------------------------------
  1887. //「新しいウィンドウを開く」メニュー
  1888. // "New window" menu
  1889. //-----------------------------------
  1890. private void menuNewWindow_Click(object sender, EventArgs e)
  1891. {
  1892. //自分自身を起動する
  1893. //Launch the self
  1894. System.Diagnostics.ProcessStartInfo pInfo = new System.Diagnostics.ProcessStartInfo(Application.ExecutablePath);
  1895. pInfo.Arguments = "/new";
  1896. System.Diagnostics.Process p = System.Diagnostics.Process.Start(pInfo);
  1897. }
  1898. //-----------------------------------
  1899. //「ファイルを開く」メニュー
  1900. // "Open File" menu
  1901. //-----------------------------------
  1902. private void menuOpenFile_Click(object sender, EventArgs e)
  1903. {
  1904. OpenFile("", true);
  1905. }
  1906. //-----------------------------------
  1907. //「ファイル」メニュー
  1908. // "File" menu
  1909. //-----------------------------------
  1910. private void menuFile_Click(object sender, EventArgs e)
  1911. {
  1912. //編集履歴のサブメニューをつくる
  1913. //Create submenu of editing history
  1914. for (int i = 0; i < MarkDownSharpEditor.AppSettings.Instance.ArrayHistoryEditedFiles.Count; i++)
  1915. {
  1916. AppHistory History = (AppHistory)MarkDownSharpEditor.AppSettings.Instance.ArrayHistoryEditedFiles[i];
  1917. ToolStripMenuItem m = new ToolStripMenuItem(History.md);
  1918. m.Tag = History.css;
  1919. m.Click += new EventHandler(HistorySubMenuItemClickHandler);
  1920. menuHistoryFiles.DropDownItems.Add(m);
  1921. }
  1922. }
  1923. //-----------------------------------
  1924. //各履歴メニューがクリックされたとき
  1925. //Click editing history menu event
  1926. private void HistorySubMenuItemClickHandler(object sender, EventArgs e)
  1927. {
  1928. ToolStripMenuItem clickItem = (ToolStripMenuItem)sender;
  1929. string FilePath = clickItem.Text;
  1930. if (File.Exists(FilePath) == true)
  1931. {
  1932. OpenFile(FilePath);
  1933. }
  1934. }
  1935. //-----------------------------------
  1936. //編集中のファイルを保存する
  1937. //Save to editing file
  1938. //-----------------------------------
  1939. private bool SaveToEditingFile(bool fSaveAs = false)
  1940. {
  1941. //名前が付けられていない、または別名保存指定なのでダイアログ表示
  1942. //The file is no title, or saving as oher name
  1943. if (_fNoTitle == true || fSaveAs == true)
  1944. {
  1945. if (saveFileDialog1.ShowDialog() == DialogResult.OK)
  1946. {
  1947. using (StreamWriter sw = new StreamWriter(saveFileDialog1.FileName, false, _EditingFileEncoding))
  1948. {
  1949. sw.Write(richTextBox1.Text);
  1950. _MarkDownTextFilePath = saveFileDialog1.FileName;
  1951. }
  1952. }
  1953. else
  1954. {
  1955. return (false);
  1956. }
  1957. }
  1958. else
  1959. {
  1960. //上書き保存
  1961. //Overwrite
  1962. using (StreamWriter sw = new StreamWriter(
  1963. _MarkDownTextFilePath,
  1964. false,
  1965. _EditingFileEncoding))
  1966. {
  1967. sw.Write(richTextBox1.Text);
  1968. }
  1969. }
  1970. //Undoバッファクリア
  1971. //Clear undo buffer
  1972. undoCounter = 0;
  1973. UndoBuffer.Clear();
  1974. _fNoTitle = false; //無題フラグOFF
  1975. richTextBox1.Modified = false;
  1976. FormTextChange();
  1977. return (true);
  1978. }
  1979. //-----------------------------------
  1980. //「ファイルを保存」メニュー
  1981. // "Save file" menu
  1982. //-----------------------------------
  1983. private void menuSaveFile_Click(object sender, EventArgs e)
  1984. {
  1985. SaveToEditingFile();
  1986. }
  1987. //-----------------------------------
  1988. //「名前を付けてファイルを保存」メニュー
  1989. // "Save As" menu
  1990. //-----------------------------------
  1991. private void menuSaveAsFile_Click(object sender, EventArgs e)
  1992. {
  1993. SaveToEditingFile(true);
  1994. }
  1995. //-----------------------------------
  1996. //「HTMLファイル出力(&P)」メニュー
  1997. // "Output to HTML file" menu
  1998. //-----------------------------------
  1999. private void menuOutputHtmlFile_Click(object sender, EventArgs e)
  2000. {
  2001. string OutputFilePath;
  2002. string DirPath = Path.GetDirectoryName(_MarkDownTextFilePath);
  2003. if (File.Exists(_MarkDownTextFilePath) == true)
  2004. {
  2005. saveFileDialog2.InitialDirectory = DirPath;
  2006. }
  2007. //保存ダイアログを表示する
  2008. //Show Save dialog
  2009. if (MarkDownSharpEditor.AppSettings.Instance.fShowHtmlSaveDialog == true)
  2010. {
  2011. if (saveFileDialog2.ShowDialog() == DialogResult.OK)
  2012. {
  2013. OutputToHtmlFile(_MarkDownTextFilePath, saveFileDialog2.FileName, false);
  2014. }
  2015. }
  2016. else
  2017. {
  2018. //ダイアログを抑制しているので編集中のファイルのディレクトリへ保存する
  2019. //Save to editing folder in constrainting dialog
  2020. OutputFilePath = Path.Combine(DirPath, Path.GetFileNameWithoutExtension(_MarkDownTextFilePath)) + ".html";
  2021. if (File.Exists(OutputFilePath) == true)
  2022. {
  2023. //"問い合わせ"
  2024. //"すでに同名のファイルが存在しています。上書きして出力しますか?"
  2025. //"Question"
  2026. //"Same file exists.\nContinue to overwrite?"
  2027. DialogResult ret = MessageBox.Show(
  2028. Resources.MsgSameFileOverwrite + "\n" + OutputFilePath,
  2029. Resources.DialogTitleQuestion, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question,
  2030. MessageBoxDefaultButton.Button1); // Yesがデフォルト
  2031. if (ret == DialogResult.Yes)
  2032. {
  2033. //上書きしてHTMLファイルへ出力
  2034. //Overwrite and output to HTML file
  2035. OutputToHtmlFile(_MarkDownTextFilePath, OutputFilePath, false);
  2036. }
  2037. else if (ret == DialogResult.No)
  2038. {
  2039. //設定されてないが一応保存ダイアログを出す
  2040. //It is no setting, but show save dialog
  2041. if (saveFileDialog2.ShowDialog() == DialogResult.OK)
  2042. {
  2043. //HTMLファイルへ出力
  2044. //Output to HTML file
  2045. OutputToHtmlFile(_MarkDownTextFilePath, saveFileDialog2.FileName, false);
  2046. }
  2047. }
  2048. else
  2049. {
  2050. //キャンセル
  2051. //Cancel
  2052. }
  2053. }
  2054. else
  2055. {
  2056. //HTMLファイルへ出力
  2057. //Output to HTML file
  2058. OutputToHtmlFile(_MarkDownTextFilePath, OutputFilePath, false);
  2059. }
  2060. }
  2061. }
  2062. //-----------------------------------
  2063. //「HTMLソースコードをクリップボードへコピー(&L)」メニュー
  2064. // "Set HTML source code to clipboard" menu
  2065. //-----------------------------------
  2066. private void menuOutputHtmlToClipboard_Click(object sender, EventArgs e)
  2067. {
  2068. //HTMLソースをクリップボードへ出力
  2069. //Output HTML source to clipboard
  2070. OutputToHtmlFile(_MarkDownTextFilePath, "", true);
  2071. //HTMLソースをクリップボードコピーしたときに確認メッセージを表示する(&M)
  2072. //Show message to confirm when HTML source data is setting to clipboard
  2073. if (MarkDownSharpEditor.AppSettings.Instance.fShowHtmlToClipboardMessage == true)
  2074. {
  2075. //"通知"
  2076. //"クリップボードに保存されました。"
  2077. //"Information"
  2078. //"This file has been output to the clipboard."
  2079. MessageBox.Show(Resources.MsgOutputToClipboard,
  2080. Resources.DialogTitleNotice, MessageBoxButtons.OK, MessageBoxIcon.Information);
  2081. }
  2082. }
  2083. //-----------------------------------
  2084. //「終了」メニュー
  2085. // "Exit" menu
  2086. //-----------------------------------
  2087. private void menuExit_Click(object sender, EventArgs e)
  2088. {
  2089. Close();
  2090. }
  2091. //-----------------------------------
  2092. //「編集」メニュー
  2093. // "Edit" menu
  2094. //-----------------------------------
  2095. private void menuEdit_Click(object sender, EventArgs e)
  2096. {
  2097. if (undoCounter > 0)
  2098. {
  2099. menuUndo.Enabled = true;
  2100. }
  2101. else
  2102. {
  2103. menuUndo.Enabled = false;
  2104. }
  2105. if (undoCounter < UndoBuffer.Count && undoCounter > 0)
  2106. {
  2107. menuRedo.Enabled = true;
  2108. }
  2109. else
  2110. {
  2111. menuRedo.Enabled = false;
  2112. }
  2113. if (richTextBox1.SelectionLength > 0)
  2114. {
  2115. menuCut.Enabled = true;
  2116. menuCopy.Enabled = true;
  2117. }
  2118. else
  2119. {
  2120. menuCut.Enabled = false;
  2121. menuCopy.Enabled = false;
  2122. }
  2123. }
  2124. //-----------------------------------
  2125. //「元に戻す」メニュー
  2126. // "Undo" menu
  2127. //-----------------------------------
  2128. private void menuUndo_Click(object sender, EventArgs e)
  2129. {
  2130. if (UndoBuffer.Count > 0 && undoCounter > 0)
  2131. { //現在のカーソル位置
  2132. //Current cursor position
  2133. int selectStart = this.richTextBox1.SelectionStart;
  2134. int selectEnd = richTextBox1.SelectionLength;
  2135. //現在のスクロール位置
  2136. //Current scroll position
  2137. int CurrentScrollpos = richTextBox1.VerticalPosition;
  2138. //描画停止
  2139. //Stop to paint
  2140. richTextBox1.BeginUpdate();
  2141. undoCounter--;
  2142. richTextBox1.Rtf = UndoBuffer[undoCounter];
  2143. //カーソル位置を戻す
  2144. //Restore cursor position
  2145. richTextBox1.Select(selectStart, selectEnd);
  2146. //スクロール位置を戻す
  2147. //Restore scroll position
  2148. richTextBox1.VerticalPosition = CurrentScrollpos;
  2149. //描画再開
  2150. //Resume to paint
  2151. richTextBox1.EndUpdate();
  2152. if (undoCounter == 0)
  2153. {
  2154. richTextBox1.Modified = false;
  2155. FormTextChange();
  2156. }
  2157. }
  2158. }
  2159. //-----------------------------------
  2160. //「やり直す」メニュー
  2161. // "Redo" menu
  2162. //-----------------------------------
  2163. private void menuRedo_Click(object sender, EventArgs e)
  2164. {
  2165. if (undoCounter < UndoBuffer.Count && undoCounter > 0)
  2166. {
  2167. undoCounter++;
  2168. richTextBox1.Rtf = UndoBuffer[undoCounter];
  2169. FormTextChange();
  2170. }
  2171. }
  2172. //-----------------------------------
  2173. //「切り取り」メニュー
  2174. // "Cut" to clipbord menu
  2175. //-----------------------------------
  2176. private void menuCut_Click(object sender, EventArgs e)
  2177. {
  2178. if (richTextBox1.SelectionLength > 0)
  2179. {
  2180. richTextBox1.Cut();
  2181. FormTextChange();
  2182. }
  2183. }
  2184. //-----------------------------------
  2185. //「コピー」メニュー
  2186. // "Copy" to clipboard menu
  2187. //-----------------------------------
  2188. private void menuCopy_Click(object sender, EventArgs e)
  2189. {
  2190. if (richTextBox1.SelectionLength > 0)
  2191. {
  2192. richTextBox1.Copy();
  2193. }
  2194. }
  2195. //-----------------------------------
  2196. //「貼り付け」メニュー
  2197. // "Paste" from clipboard menu
  2198. //-----------------------------------
  2199. private void menuPaste_Click(object sender, EventArgs e)
  2200. {
  2201. IDataObject data = Clipboard.GetDataObject();
  2202. if (data != null && data.GetDataPresent(DataFormats.Text) == true)
  2203. {
  2204. DataFormats.Format fmt = DataFormats.GetFormat(DataFormats.Text);
  2205. richTextBox1.Paste(fmt);
  2206. FormTextChange();
  2207. }
  2208. }
  2209. //-----------------------------------
  2210. //「すべてを選択」メニュー
  2211. // "Select all" menu
  2212. //-----------------------------------
  2213. private void menuSelectAll_Click(object sender, EventArgs e)
  2214. {
  2215. richTextBox1.SelectAll();
  2216. }
  2217. //-----------------------------------
  2218. //「検索」メニュー
  2219. // "Search" menu
  2220. //-----------------------------------
  2221. private void menuSearch_Click(object sender, EventArgs e)
  2222. {
  2223. _fSearchStart = false;
  2224. panelSearch.Visible = true;
  2225. panelSearch.Height = 58;
  2226. textBoxSearch.Focus();
  2227. labelReplace.Visible = false;
  2228. textBoxReplace.Visible = false;
  2229. cmdReplaceAll.Visible = false;
  2230. cmdSearchNext.Text = Resources.ButtonFindNext; //"次を検索する(&N)";
  2231. cmdSearchPrev.Text = Resources.ButtonFindPrev; // "前を検索する(&P)";
  2232. }
  2233. //-----------------------------------
  2234. //「置換」メニュー
  2235. // "Replace" menu
  2236. //-----------------------------------
  2237. private void menuReplace_Click(object sender, EventArgs e)
  2238. {
  2239. _fSearchStart = false;
  2240. panelSearch.Visible = true;
  2241. panelSearch.Height = 58;
  2242. textBoxSearch.Focus();
  2243. labelReplace.Visible = true;
  2244. textBoxReplace.Visible = true;
  2245. cmdReplaceAll.Visible = true;
  2246. cmdSearchNext.Text = Resources.ButtonReplaceNext; //"置換して次へ(&N)";
  2247. cmdSearchPrev.Text = Resources.ButtonReplacePrev; //"置換して前へ(&P)";
  2248. }
  2249. //-----------------------------------
  2250. // 表示の更新
  2251. // "Refresh preview" menu
  2252. //-----------------------------------
  2253. private void menuViewRefresh_Click(object sender, EventArgs e)
  2254. {
  2255. PreviewToBrowser();
  2256. }
  2257. //-----------------------------------
  2258. //「ソースとビューを均等表示する」メニュー
  2259. // "Editor and Browser Width evenly" menu
  2260. //-----------------------------------
  2261. private void menuViewWidthEvenly_Click(object sender, EventArgs e)
  2262. {
  2263. if (menuViewWidthEvenly.Checked == true)
  2264. {
  2265. menuViewWidthEvenly.Checked = false;
  2266. }
  2267. else
  2268. {
  2269. menuViewWidthEvenly.Checked = true;
  2270. }
  2271. MarkDownSharpEditor.AppSettings.Instance.fSplitBarWidthEvenly = menuViewWidthEvenly.Checked;
  2272. }
  2273. //-----------------------------------
  2274. //「言語」メニュー
  2275. // Change "Language" menu
  2276. //-----------------------------------
  2277. private void menuViewJapanese_Click(object sender, EventArgs e)
  2278. {
  2279. //"問い合わせ"
  2280. //"言語の変更を反映するには、アプリケーションの再起動が必要です。
  2281. //今すぐ再起動しますか?"
  2282. //"Question"
  2283. //"To change the setting of language, it is necessary to restart the application.
  2284. // Do you want to restart this application now?"
  2285. DialogResult result = MessageBox.Show(Resources.MsgRestartApplication,
  2286. Resources.DialogTitleQuestion, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
  2287. if (result == DialogResult.Yes)
  2288. {
  2289. MarkDownSharpEditor.AppSettings.Instance.Lang = "ja";
  2290. MarkDownSharpEditor.AppSettings.Instance.SaveToXMLFile();
  2291. Application.Restart();
  2292. }
  2293. else if (result == DialogResult.No)
  2294. {
  2295. MarkDownSharpEditor.AppSettings.Instance.Lang = "ja";
  2296. menuViewJapanese.Checked = true;
  2297. menuViewEnglish.Checked = false;
  2298. }
  2299. else
  2300. {
  2301. //Cancel
  2302. }
  2303. }
  2304. private void menuViewEnglish_Click(object sender, EventArgs e)
  2305. {
  2306. //"問い合わせ"
  2307. //"言語の変更を反映するには、アプリケーションの再起動が必要です。
  2308. //今すぐ再起動しますか?"
  2309. //"Question"
  2310. //"To change the setting of language, it is necessary to restart the application.
  2311. // Do you want to restart this application now?"
  2312. DialogResult result = MessageBox.Show(Resources.MsgRestartApplication,
  2313. Resources.DialogTitleQuestion, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
  2314. if (result == DialogResult.Yes)
  2315. {
  2316. MarkDownSharpEditor.AppSettings.Instance.Lang = "en";
  2317. MarkDownSharpEditor.AppSettings.Instance.SaveToXMLFile();
  2318. Application.Restart();
  2319. }
  2320. else if (result == DialogResult.No)
  2321. {
  2322. MarkDownSharpEditor.AppSettings.Instance.Lang = "en";
  2323. MarkDownSharpEditor.AppSettings.Instance.SaveToXMLFile();
  2324. menuViewJapanese.Checked = false;
  2325. menuViewEnglish.Checked = true;
  2326. }
  2327. else
  2328. {
  2329. //Cancel
  2330. }
  2331. }
  2332. //-----------------------------------
  2333. //「ツールバーを表示する」メニュー
  2334. // "View toolbar" menu
  2335. //-----------------------------------
  2336. private void menuViewToolBar_Click(object sender, EventArgs e)
  2337. {
  2338. if (menuViewToolBar.Checked == true)
  2339. {
  2340. menuViewToolBar.Checked = false;
  2341. toolStrip1.Visible = false;
  2342. }
  2343. else
  2344. {
  2345. menuViewToolBar.Checked = true;
  2346. toolStrip1.Visible = true;
  2347. }
  2348. MarkDownSharpEditor.AppSettings.Instance.fViewToolBar = toolStrip1.Visible;
  2349. }
  2350. //-----------------------------------
  2351. //「ステータスバーを表示する」メニュー
  2352. // "View statusbar" menu
  2353. //-----------------------------------
  2354. private void menuViewStatusBar_Click(object sender, EventArgs e)
  2355. {
  2356. if (menuViewStatusBar.Checked == true)
  2357. {
  2358. menuViewStatusBar.Checked = false;
  2359. statusStrip1.Visible = false;
  2360. }
  2361. else
  2362. {
  2363. menuViewStatusBar.Checked = true;
  2364. statusStrip1.Visible = true;
  2365. }
  2366. MarkDownSharpEditor.AppSettings.Instance.fViewStatusBar = statusStrip1.Visible;
  2367. }
  2368. //-----------------------------------
  2369. //「書式フォント」メニュー
  2370. // "Font" menu
  2371. //-----------------------------------
  2372. private void menuFont_Click(object sender, EventArgs e)
  2373. {
  2374. bool fModify = richTextBox1.Modified;
  2375. fontDialog1.Font = richTextBox1.Font;
  2376. fontDialog1.Color = richTextBox1.ForeColor;
  2377. //選択できるポイントサイズの最小・最大値
  2378. fontDialog1.MinSize = 6;
  2379. fontDialog1.MaxSize = 72;
  2380. fontDialog1.FontMustExist = true;
  2381. //横書きフォントだけを表示する
  2382. fontDialog1.AllowVerticalFonts = false;
  2383. //色を選択できるようにする
  2384. fontDialog1.ShowColor = true;
  2385. //取り消し線、下線、テキストの色などのオプションを指定不可
  2386. fontDialog1.ShowEffects = false;
  2387. //ダイアログを表示する
  2388. if (fontDialog1.ShowDialog() == DialogResult.OK)
  2389. {
  2390. UndoBuffer.Add(richTextBox1.Rtf);
  2391. undoCounter = UndoBuffer.Count;
  2392. this.richTextBox1.TextChanged -= new System.EventHandler(this.richTextBox1_TextChanged);
  2393. richTextBox1.Font = fontDialog1.Font;
  2394. richTextBox1.ForeColor = fontDialog1.Color;
  2395. //ステータスバーに表示
  2396. toolStripStatusLabelFontInfo.Text =
  2397. fontDialog1.Font.Name + "," + fontDialog1.Font.Size.ToString() + "pt";
  2398. this.richTextBox1.TextChanged += new System.EventHandler(this.richTextBox1_TextChanged);
  2399. }
  2400. //richTextBoxの書式を変えても「変更」となるので元のステータスへ戻す
  2401. richTextBox1.Modified = fModify;
  2402. }
  2403. //-----------------------------------
  2404. //「オプション」メニュー
  2405. // "Option" menu
  2406. //-----------------------------------
  2407. private void menuOption_Click(object sender, EventArgs e)
  2408. {
  2409. Form3 frm3 = new Form3();
  2410. frm3.ShowDialog();
  2411. frm3.Dispose();
  2412. _MarkdownSyntaxKeywordAarray = MarkdownSyntaxKeyword.CreateKeywordList(); //キーワードリストの更新
  2413. if (backgroundWorker2.IsBusy == false)
  2414. {
  2415. //SyntaxHightlighter on BackgroundWorker
  2416. backgroundWorker2.RunWorkerAsync(richTextBox1.Text);
  2417. }
  2418. //プレビュー間隔を更新
  2419. if (MarkDownSharpEditor.AppSettings.Instance.AutoBrowserPreviewInterval > 0)
  2420. {
  2421. timer1.Interval = MarkDownSharpEditor.AppSettings.Instance.AutoBrowserPreviewInterval;
  2422. }
  2423. }
  2424. //-----------------------------------
  2425. // ヘルプファイルの表示
  2426. // "Help contents" menu
  2427. //-----------------------------------
  2428. private void menuContents_Click(object sender, EventArgs e)
  2429. {
  2430. string HelpFilePath;
  2431. string DirPath = MarkDownSharpEditor.AppSettings.GetAppDataLocalPath();
  2432. if (MarkDownSharpEditor.AppSettings.Instance.Lang == "ja")
  2433. {
  2434. HelpFilePath = Path.Combine(DirPath, "help-ja.md");
  2435. }
  2436. else
  2437. {
  2438. HelpFilePath = Path.Combine(DirPath, "help.md");
  2439. }
  2440. if (File.Exists(HelpFilePath) == true)
  2441. { //別ウィンドウで開く
  2442. //Create a new ProcessStartInfo structure.
  2443. System.Diagnostics.ProcessStartInfo pInfo = new System.Diagnostics.ProcessStartInfo();
  2444. //Set the file name member.
  2445. pInfo.FileName = HelpFilePath;
  2446. //UseShellExecute is true by default. It is set here for illustration.
  2447. pInfo.UseShellExecute = true;
  2448. System.Diagnostics.Process p = System.Diagnostics.Process.Start(pInfo);
  2449. }
  2450. else
  2451. { //"エラー"
  2452. //"ヘルプファイルがありません。開くことができませんでした。"
  2453. //"Could not find Help file. Opening this file has failed."
  2454. MessageBox.Show(Resources.MsgNoHelpFile,
  2455. Resources.DialogTitleError, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  2456. }
  2457. }
  2458. //-----------------------------------
  2459. // 最新バージョンのチェック
  2460. // "Check for Update"
  2461. //-----------------------------------
  2462. private void mnuCheckForUpdate_Click(object sender, EventArgs e)
  2463. {
  2464. string MsgText = "";
  2465. Version newVersion = null;
  2466. string url = "";
  2467. string dt = "";
  2468. System.Xml.XmlTextReader reader;
  2469. /*
  2470. * <?xml version="1.0" encoding="utf-8"?>
  2471. * <markdownsharpeditor>
  2472. * <version>1.2.1.0</version>
  2473. * <date>2013/06/18</date>
  2474. * <url>http://hibara.org/software/markdownsharpeditor/</url>
  2475. * </markdownsharpeditor>
  2476. */
  2477. string xmlURL = "http://hibara.org/software/markdownsharpeditor/app_version.xml";
  2478. using (reader = new System.Xml.XmlTextReader(xmlURL))
  2479. {
  2480. reader.MoveToContent();
  2481. string elementName = "";
  2482. if ((reader.NodeType == System.Xml.XmlNodeType.Element) && (reader.Name == "markdownsharpeditor"))
  2483. {
  2484. while (reader.Read())
  2485. {
  2486. if (reader.NodeType == System.Xml.XmlNodeType.Element)
  2487. {
  2488. elementName = reader.Name;
  2489. }
  2490. else
  2491. {
  2492. if ((reader.NodeType == System.Xml.XmlNodeType.Text) && (reader.HasValue))
  2493. {
  2494. switch (elementName)
  2495. {
  2496. case "version":
  2497. newVersion = new Version(reader.Value);
  2498. break;
  2499. case "url":
  2500. url = reader.Value;
  2501. break;
  2502. case "date":
  2503. dt = reader.Value;
  2504. break;
  2505. }
  2506. }
  2507. }
  2508. }
  2509. }
  2510. }
  2511. if (newVersion == null)
  2512. {
  2513. //Failed to get the latest version information.
  2514. MsgText = Resources.ErrorGetNewVersion;
  2515. MessageBox.Show(MsgText, Resources.DialogTitleError, MessageBoxButtons.OK, MessageBoxIcon.Question);
  2516. return;
  2517. }
  2518. // get current version
  2519. Version curVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
  2520. if (curVersion.CompareTo(newVersion) < 0)
  2521. { //"New version was found! Do you open the download site?";
  2522. MsgText = "Update info: ver." + newVersion + " (" + dt + " ) \n" + Resources.NewVersionFound;
  2523. if (DialogResult.Yes == MessageBox.Show(this, MsgText, Resources.DialogTitleQuestion, MessageBoxButtons.YesNo, MessageBoxIcon.Question))
  2524. {
  2525. System.Diagnostics.Process.Start(url);
  2526. }
  2527. }
  2528. else
  2529. { // You already have the latest version of this application.
  2530. MsgText = Resources.AlreadyLatestVersion + "\nver." + newVersion + " ( " + dt + " ) ";
  2531. MessageBox.Show(MsgText, Resources.DialogTitleInfo, MessageBoxButtons.OK, MessageBoxIcon.Question);
  2532. }
  2533. }
  2534. //-----------------------------------
  2535. // サンプル表示
  2536. // "View Markdown sample file"
  2537. //-----------------------------------
  2538. private void menuViewSample_Click(object sender, EventArgs e)
  2539. {
  2540. string DirPath = MarkDownSharpEditor.AppSettings.GetAppDataLocalPath();
  2541. string SampleFilePath = Path.Combine(DirPath, "sample.md");
  2542. if (File.Exists(SampleFilePath) == true)
  2543. {
  2544. System.Diagnostics.ProcessStartInfo pInfo = new System.Diagnostics.ProcessStartInfo();
  2545. pInfo.FileName = SampleFilePath;
  2546. pInfo.UseShellExecute = true;
  2547. System.Diagnostics.Process p = System.Diagnostics.Process.Start(pInfo);
  2548. }
  2549. else
  2550. {
  2551. //"エラー"
  2552. //"サンプルファイルがありません。開くことができませんでした。"
  2553. //"Error"
  2554. //"Could not find sample MD file.\nOpening this file has failed."
  2555. MessageBox.Show(Resources.MsgNoSampleFile,
  2556. Resources.DialogTitleError, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  2557. }
  2558. }
  2559. //-----------------------------------
  2560. //「MarkDownSharpについて」メニュー
  2561. // "About" menu
  2562. //-----------------------------------
  2563. private void menuAbout_Click(object sender, EventArgs e)
  2564. {
  2565. Form2 frm2 = new Form2();
  2566. frm2.ShowDialog();
  2567. frm2.Dispose();
  2568. }
  2569. #endregion
  2570. //======================================================================
  2571. //======================================================================
  2572. #region ステータスバーイベント ( Statusbar event )
  2573. //======================================================================
  2574. //-----------------------------------
  2575. // ステータスバー(CSS)
  2576. //-----------------------------------
  2577. private void toolStripStatusLabelCssFileName_Click(object sender, EventArgs e)
  2578. {
  2579. //ポップアップメニューに登録する
  2580. //Regist item to popup menus
  2581. contextMenu1.Items.Clear();
  2582. foreach (string FilePath in MarkDownSharpEditor.AppSettings.Instance.ArrayCssFileList)
  2583. {
  2584. if (File.Exists(FilePath) == true)
  2585. {
  2586. ToolStripMenuItem item = new ToolStripMenuItem(Path.GetFileName(FilePath));
  2587. item.Tag = FilePath;
  2588. if (_SelectedCssFilePath == FilePath)
  2589. {
  2590. item.Checked = true;
  2591. }
  2592. contextMenu1.Items.Add(item);
  2593. }
  2594. }
  2595. if (contextMenu1.Items.Count > 0)
  2596. {
  2597. contextMenu1.Tag = "css";
  2598. contextMenu1.Show(Control.MousePosition);
  2599. }
  2600. }
  2601. //-----------------------------------
  2602. // ステータスバー(Encoding)
  2603. //-----------------------------------
  2604. private void toolStripStatusLabelEncoding_Click(object sender, EventArgs e)
  2605. {
  2606. //ポップアップメニューに登録する
  2607. //Regist item to popup menus
  2608. contextMenu1.Items.Clear();
  2609. foreach (EncodingInfo ei in Encoding.GetEncodings())
  2610. {
  2611. if (ei.GetEncoding().IsBrowserDisplay == true)
  2612. {
  2613. ToolStripMenuItem item = new ToolStripMenuItem(ei.DisplayName);
  2614. item.Tag = ei.CodePage;
  2615. if (ei.CodePage == MarkDownSharpEditor.AppSettings.Instance.CodePageNumber)
  2616. {
  2617. item.Checked = true;
  2618. }
  2619. contextMenu1.Items.Add(item);
  2620. }
  2621. }
  2622. contextMenu1.Tag = "encoding";
  2623. contextMenu1.Show(Control.MousePosition);
  2624. }
  2625. //-----------------------------------
  2626. // ステータスバー(共通のクリックイベント)
  2627. // Common item clicked event
  2628. //-----------------------------------
  2629. private void contextMenu1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
  2630. {
  2631. //-----------------------------------
  2632. // 適用するCSSファイル変更
  2633. // Change selected CSS file
  2634. //-----------------------------------
  2635. if ((string)contextMenu1.Tag == "css")
  2636. {
  2637. _SelectedCssFilePath = (string)e.ClickedItem.Tag;
  2638. toolStripStatusLabelCssFileName.Text = Path.GetFileName(_SelectedCssFilePath);
  2639. //プレビューも更新する
  2640. PreviewToBrowser();
  2641. }
  2642. //-----------------------------------
  2643. // 出力HTMLに適用する文字コードの変更
  2644. // Change encoding to output HTML file
  2645. //-----------------------------------
  2646. else if ((string)contextMenu1.Tag == "encoding")
  2647. {
  2648. MarkDownSharpEditor.AppSettings.Instance.CodePageNumber = (int)e.ClickedItem.Tag;
  2649. //プレビューも更新する
  2650. //Refresh previewing, too
  2651. PreviewToBrowser();
  2652. }
  2653. }
  2654. //----------------------------------------------------------------------
  2655. // 検索パネル ( Search panel )
  2656. //----------------------------------------------------------------------
  2657. private void imgSearchExit_Click(object sender, EventArgs e)
  2658. {
  2659. panelSearch.Visible = false;
  2660. }
  2661. //-----------------------------------
  2662. // 検索パネル「閉じる」ボタンイベント
  2663. // Search panel close button image event
  2664. //-----------------------------------
  2665. private void imgSearchExit_MouseEnter(object sender, EventArgs e)
  2666. {
  2667. imgSearchExit.Image = imgSearchExitEnabled.Image;
  2668. }
  2669. private void imgSearchExit_MouseLeave(object sender, EventArgs e)
  2670. {
  2671. imgSearchExit.Image = imgSearchExitUnabled.Image;
  2672. }
  2673. //-----------------------------------
  2674. // 検索テキストボックス
  2675. // Search text box TextChanged event
  2676. //-----------------------------------
  2677. private void textBoxSearch_TextChanged(object sender, EventArgs e)
  2678. {
  2679. //検索をやり直し
  2680. //Restart to search
  2681. _fSearchStart = false;
  2682. if (textBoxReplace.Visible == true)
  2683. {
  2684. if (textBoxSearch.Text == "")
  2685. {
  2686. cmdSearchNext.Enabled = false;
  2687. cmdSearchPrev.Enabled = false;
  2688. cmdReplaceAll.Enabled = false;
  2689. }
  2690. else
  2691. {
  2692. cmdSearchNext.Enabled = true;
  2693. cmdSearchPrev.Enabled = true;
  2694. cmdReplaceAll.Enabled = true;
  2695. }
  2696. }
  2697. else
  2698. {
  2699. cmdSearchNext.Enabled = true;
  2700. cmdSearchPrev.Enabled = true;
  2701. }
  2702. }
  2703. //-----------------------------------
  2704. // 検索テキストボックス
  2705. // Search text box KeyDown event
  2706. //-----------------------------------
  2707. private void textBoxSearch_KeyDown(object sender, KeyEventArgs e)
  2708. {
  2709. if (e.Shift && e.KeyCode == Keys.Enter)
  2710. { // Shitf + Enter で前へ
  2711. // Press Shift + Enter key to previous item
  2712. cmdSearchPrev_Click(sender, e);
  2713. }
  2714. else if (e.KeyCode == Keys.Enter)
  2715. {
  2716. cmdSearchNext_Click(sender, e);
  2717. }
  2718. else if (e.KeyCode == Keys.Escape)
  2719. {
  2720. panelSearch.Visible = false;
  2721. }
  2722. }
  2723. //-----------------------------------
  2724. // 検索テキストボックス
  2725. // Search text box KeyPress event
  2726. //-----------------------------------
  2727. private void textBoxSearch_KeyPress(object sender, KeyPressEventArgs e)
  2728. {
  2729. //EnterやEscapeキーでビープ音が鳴らないようにする
  2730. //Constraint to beep sound with Enter & Escape key
  2731. if (e.KeyChar == (char)Keys.Enter || e.KeyChar == (char)Keys.Escape)
  2732. {
  2733. e.Handled = true;
  2734. }
  2735. }
  2736. //-----------------------------------
  2737. // 置換テキストボックス
  2738. // Search text box KeyDown event
  2739. //-----------------------------------
  2740. private void textBoxReplace_KeyDown(object sender, KeyEventArgs e)
  2741. {
  2742. if (e.Shift && e.KeyCode == Keys.Enter)
  2743. { // Shitf + Enter で前へ
  2744. // Press Shift + Enter key to previous item
  2745. cmdSearchPrev_Click(sender, e);
  2746. }
  2747. else if (e.KeyCode == Keys.Enter)
  2748. {
  2749. cmdSearchNext_Click(sender, e);
  2750. }
  2751. else if (e.KeyCode == Keys.Escape)
  2752. {
  2753. panelSearch.Visible = false;
  2754. }
  2755. }
  2756. //-----------------------------------
  2757. // 置換テキストボックス(KeyPress)
  2758. //-----------------------------------
  2759. private void textBoxReplace_KeyPress(object sender, KeyPressEventArgs e)
  2760. {
  2761. //EnterやEscapeキーでビープ音が鳴らないようにする
  2762. //Constraint to beep sound with Enter & Escape key
  2763. if (e.KeyChar == (char)Keys.Enter || e.KeyChar == (char)Keys.Escape)
  2764. {
  2765. e.Handled = true;
  2766. }
  2767. }
  2768. //----------------------------------------------------------------------
  2769. // 次を検索(または、置換して次へ)ボタン
  2770. // Press next button
  2771. //----------------------------------------------------------------------
  2772. private void cmdSearchNext_Click(object sender, EventArgs e)
  2773. {
  2774. int StartPos;
  2775. StringComparison sc;
  2776. DialogResult result;
  2777. string MsgText = "";
  2778. if (textBoxSearch.Text != "")
  2779. {
  2780. //置換モードの場合は、置換してから次を検索する
  2781. //Replace the word to search next item in Replace mode
  2782. if (textBoxReplace.Visible == true && _fSearchStart == true)
  2783. {
  2784. if (richTextBox1.SelectionLength > 0)
  2785. {
  2786. richTextBox1.SelectedText = textBoxReplace.Text;
  2787. }
  2788. }
  2789. if (chkOptionCase.Checked == true)
  2790. {
  2791. sc = StringComparison.Ordinal;
  2792. }
  2793. else
  2794. { //大文字と小文字を区別しない
  2795. //Ignore case
  2796. sc = StringComparison.OrdinalIgnoreCase;
  2797. }
  2798. int CurrentPos = richTextBox1.SelectionStart + 1;
  2799. //-----------------------------------
  2800. // 検索ワードが見つからない
  2801. // Searching word is not found
  2802. //-----------------------------------
  2803. if ((StartPos = richTextBox1.Text.IndexOf(textBoxSearch.Text, CurrentPos, sc)) == -1)
  2804. {
  2805. //検索を開始した直後
  2806. //Start to search after
  2807. if (_fSearchStart == false)
  2808. {
  2809. //"ファイル末尾まで検索しましたが、見つかりませんでした。
  2810. // ファイルの先頭から検索を続けますか?"
  2811. //"The word could not find the word to the end of this file.
  2812. // Do you wish to continue searching from the beginning of this file?"
  2813. MsgText = Resources.MsgNotFoundToEnd;
  2814. _fSearchStart = true;
  2815. }
  2816. else
  2817. {
  2818. //"ファイル末尾までの検索が完了しました。
  2819. // ファイル先頭に戻って検索を続けますか?"
  2820. //"Searching completed to the end of this file.
  2821. // Do you wish to continue searching from the beginning of this file?"
  2822. MsgText = Resources.MsgFindCompleteToEnd;
  2823. }
  2824. result = MessageBox.Show(MsgText, Resources.DialogTitleNotice,
  2825. MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
  2826. if (result == DialogResult.Yes)
  2827. {
  2828. richTextBox1.SelectionStart = 0;
  2829. cmdSearchNext_Click(sender, e);
  2830. }
  2831. }
  2832. //-----------------------------------
  2833. // 検索ワードが見つかった
  2834. // Searching word were found
  2835. //-----------------------------------
  2836. else
  2837. {
  2838. //richTextBox1.HideSelection = false;
  2839. richTextBox1.Select(StartPos, textBoxSearch.Text.Length);
  2840. richTextBox1.ScrollToCaret();
  2841. _fSearchStart = true; //検索開始 ( Start to search )
  2842. }
  2843. }
  2844. }
  2845. //----------------------------------------------------------------------
  2846. // 前を検索(または、置換して前へ)ボタン
  2847. // Press previous button
  2848. //----------------------------------------------------------------------
  2849. private void cmdSearchPrev_Click(object sender, EventArgs e)
  2850. {
  2851. int StartPos;
  2852. StringComparison sc;
  2853. DialogResult result;
  2854. string MsgText = "";
  2855. if (textBoxSearch.Text != "")
  2856. {
  2857. //置換モードの場合は、置換してから前を検索する
  2858. //Replace the word to search previous item in Replace mode
  2859. if (textBoxReplace.Visible == true && _fSearchStart == true)
  2860. {
  2861. if (richTextBox1.SelectionLength > 0)
  2862. {
  2863. richTextBox1.SelectedText = textBoxReplace.Text;
  2864. }
  2865. }
  2866. if (chkOptionCase.Checked == true)
  2867. {
  2868. sc = StringComparison.Ordinal;
  2869. }
  2870. else
  2871. { //大文字と小文字を区別しない
  2872. //Ignore case
  2873. sc = StringComparison.OrdinalIgnoreCase;
  2874. }
  2875. int CurrentPos = richTextBox1.SelectionStart - 1;
  2876. if (CurrentPos < 0)
  2877. {
  2878. CurrentPos = 0;
  2879. }
  2880. //-----------------------------------
  2881. // 検索ワードが見つからない
  2882. // Searching word is not found
  2883. //-----------------------------------
  2884. if ((StartPos = richTextBox1.Text.LastIndexOf(textBoxSearch.Text, CurrentPos, sc)) == -1)
  2885. {
  2886. //検索を開始した直後
  2887. //Start to search after
  2888. if (_fSearchStart == false)
  2889. {
  2890. //"ファイル先頭まで検索しましたが、見つかりませんでした。
  2891. // ファイルの末尾から検索を続けますか?"
  2892. //"The word could not find to the beginning of this file.
  2893. // Do you wish to continue searching from the end of this file?"
  2894. MsgText = Resources.MsgNotFoundToBegining;
  2895. _fSearchStart = true;
  2896. }
  2897. else
  2898. {
  2899. //"ファイル先頭までの検索が完了しました。
  2900. // ファイル末尾から検索を続けますか?"
  2901. //"Searching completed to the beginning of this file.
  2902. // Do you wish to continue searching from the end of this file?"
  2903. MsgText = Resources.MsgFindCompleteToBegining;
  2904. }
  2905. result = MessageBox.Show(MsgText, Resources.DialogTitleNotice,
  2906. MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
  2907. if (result == DialogResult.Yes)
  2908. {
  2909. richTextBox1.SelectionStart = richTextBox1.Text.Length - 1;
  2910. cmdSearchPrev_Click(sender, e);
  2911. }
  2912. }
  2913. //-----------------------------------
  2914. // 検索ワードが見つかった
  2915. // Searching word were found
  2916. //-----------------------------------
  2917. else
  2918. {
  2919. //richTextBox1.HideSelection = false;
  2920. richTextBox1.Select(StartPos, textBoxSearch.Text.Length);
  2921. richTextBox1.ScrollToCaret();
  2922. _fSearchStart = true; //検索開始 ( Start to search )
  2923. }
  2924. }
  2925. }
  2926. //-----------------------------------
  2927. // すべてを置換ボタン
  2928. // "Replace All" button
  2929. //-----------------------------------
  2930. private void cmdReplaceAll_Click(object sender, EventArgs e)
  2931. {
  2932. int StartPos;
  2933. StringComparison sc;
  2934. string MsgText = "";
  2935. if (chkOptionCase.Checked == true)
  2936. {
  2937. sc = StringComparison.Ordinal;
  2938. }
  2939. else
  2940. { //大文字と小文字を区別しない
  2941. //Ignore case
  2942. sc = StringComparison.OrdinalIgnoreCase;
  2943. }
  2944. int CurrentPos = 0;
  2945. int ReplaceCount = 0;
  2946. while ((StartPos = richTextBox1.Text.IndexOf(textBoxSearch.Text, CurrentPos, sc)) > -1)
  2947. {
  2948. richTextBox1.Select(StartPos, textBoxSearch.Text.Length);
  2949. richTextBox1.ScrollToCaret();
  2950. if (richTextBox1.SelectionLength > 0)
  2951. {
  2952. richTextBox1.SelectedText = textBoxReplace.Text;
  2953. ReplaceCount++;
  2954. CurrentPos = StartPos + textBoxReplace.Text.Length;
  2955. }
  2956. }
  2957. if (ReplaceCount > 0)
  2958. {
  2959. //"以下のワードを" ~ "件置換しました。\n"
  2960. //"" ~ " of the word were replaced.\n"
  2961. MsgText = Resources.MsgThisWord + "\"" + ReplaceCount.ToString() + "\"" + Resources.MsgReplaced + "\n" +
  2962. textBoxSearch.Text + " -> " + textBoxReplace.Text;
  2963. }
  2964. else
  2965. {
  2966. //"ご指定の検索ワードは見つかりませんでした。"
  2967. //"The word was not found."
  2968. MsgText = Resources.MsgNotFound;
  2969. }
  2970. MessageBox.Show(MsgText, Resources.DialogTitleNotice, MessageBoxButtons.OK, MessageBoxIcon.Information);
  2971. _fSearchStart = true;
  2972. }
  2973. #endregion
  2974. //======================================================================
  2975. #region エンコーディングの判定 ( Detecting encoding )
  2976. //======================================================================
  2977. //
  2978. // ここのコードはまんま、以下のサイトのものを使わせていただきました。
  2979. // http://dobon.net/vb/dotnet/string/detectcode.html
  2980. //
  2981. // <summary>
  2982. // 文字コードを判別する
  2983. // </summary>
  2984. // <remarks>
  2985. // Jcode.pmのgetcodeメソッドを移植したものです。
  2986. // Jcode.pm(http://openlab.ring.gr.jp/Jcode/index-j.html)
  2987. // Jcode.pmのCopyright: Copyright 1999-2005 Dan Kogai
  2988. // </remarks>
  2989. // <param name="bytes">文字コードを調べるデータ</param>
  2990. // <returns>適当と思われるEncodingオブジェクト。
  2991. // 判断できなかった時はnull。</returns>
  2992. public static Encoding GetCode(byte[] bytes)
  2993. {
  2994. const byte bEscape = 0x1B;
  2995. const byte bAt = 0x40;
  2996. const byte bDollar = 0x24;
  2997. const byte bAnd = 0x26;
  2998. const byte bOpen = 0x28; //'('
  2999. const byte bB = 0x42;
  3000. const byte bD = 0x44;
  3001. const byte bJ = 0x4A;
  3002. const byte bI = 0x49;
  3003. int len = bytes.Length;
  3004. byte b1, b2, b3, b4;
  3005. //Encode::is_utf8 は無視
  3006. bool isBinary = false;
  3007. for (int i = 0; i < len; i++)
  3008. {
  3009. b1 = bytes[i];
  3010. if (b1 <= 0x06 || b1 == 0x7F || b1 == 0xFF)
  3011. {
  3012. //'binary'
  3013. isBinary = true;
  3014. if (b1 == 0x00 && i < len - 1 && bytes[i + 1] <= 0x7F)
  3015. {
  3016. //smells like raw unicode
  3017. return Encoding.Unicode;
  3018. }
  3019. }
  3020. }
  3021. if (isBinary)
  3022. {
  3023. return null;
  3024. }
  3025. //not Japanese
  3026. bool notJapanese = true;
  3027. for (int i = 0; i < len; i++)
  3028. {
  3029. b1 = bytes[i];
  3030. if (b1 == bEscape || 0x80 <= b1)
  3031. {
  3032. notJapanese = false;
  3033. break;
  3034. }
  3035. }
  3036. if (notJapanese)
  3037. {
  3038. return Encoding.ASCII;
  3039. }
  3040. for (int i = 0; i < len - 2; i++)
  3041. {
  3042. b1 = bytes[i];
  3043. b2 = bytes[i + 1];
  3044. b3 = bytes[i + 2];
  3045. if (b1 == bEscape)
  3046. {
  3047. if (b2 == bDollar && b3 == bAt)
  3048. {
  3049. //JIS_0208 1978
  3050. //JIS
  3051. return Encoding.GetEncoding(50220);
  3052. }
  3053. else if (b2 == bDollar && b3 == bB)
  3054. {
  3055. //JIS_0208 1983
  3056. //JIS
  3057. return Encoding.GetEncoding(50220);
  3058. }
  3059. else if (b2 == bOpen && (b3 == bB || b3 == bJ))
  3060. {
  3061. //JIS_ASC
  3062. //JIS
  3063. return Encoding.GetEncoding(50220);
  3064. }
  3065. else if (b2 == bOpen && b3 == bI)
  3066. {
  3067. //JIS_KANA
  3068. //JIS
  3069. return Encoding.GetEncoding(50220);
  3070. }
  3071. if (i < len - 3)
  3072. {
  3073. b4 = bytes[i + 3];
  3074. if (b2 == bDollar && b3 == bOpen && b4 == bD)
  3075. {
  3076. //JIS_0212
  3077. //JIS
  3078. return Encoding.GetEncoding(50220);
  3079. }
  3080. if (i < len - 5 &&
  3081. b2 == bAnd && b3 == bAt && b4 == bEscape &&
  3082. bytes[i + 4] == bDollar && bytes[i + 5] == bB)
  3083. {
  3084. //JIS_0208 1990
  3085. //JIS
  3086. return Encoding.GetEncoding(50220);
  3087. }
  3088. }
  3089. }
  3090. }
  3091. //should be euc|sjis|utf8
  3092. //use of (?:) by Hiroki Ohzaki <ohzaki@iod.ricoh.co.jp>
  3093. int sjis = 0;
  3094. int euc = 0;
  3095. int utf8 = 0;
  3096. for (int i = 0; i < len - 1; i++)
  3097. {
  3098. b1 = bytes[i];
  3099. b2 = bytes[i + 1];
  3100. if (((0x81 <= b1 && b1 <= 0x9F) || (0xE0 <= b1 && b1 <= 0xFC)) &&
  3101. ((0x40 <= b2 && b2 <= 0x7E) || (0x80 <= b2 && b2 <= 0xFC)))
  3102. {
  3103. //SJIS_C
  3104. sjis += 2;
  3105. i++;
  3106. }
  3107. }
  3108. for (int i = 0; i < len - 1; i++)
  3109. {
  3110. b1 = bytes[i];
  3111. b2 = bytes[i + 1];
  3112. if (((0xA1 <= b1 && b1 <= 0xFE) && (0xA1 <= b2 && b2 <= 0xFE)) ||
  3113. (b1 == 0x8E && (0xA1 <= b2 && b2 <= 0xDF)))
  3114. {
  3115. //EUC_C
  3116. //EUC_KANA
  3117. euc += 2;
  3118. i++;
  3119. }
  3120. else if (i < len - 2)
  3121. {
  3122. b3 = bytes[i + 2];
  3123. if (b1 == 0x8F && (0xA1 <= b2 && b2 <= 0xFE) &&
  3124. (0xA1 <= b3 && b3 <= 0xFE))
  3125. {
  3126. //EUC_0212
  3127. euc += 3;
  3128. i += 2;
  3129. }
  3130. }
  3131. }
  3132. for (int i = 0; i < len - 1; i++)
  3133. {
  3134. b1 = bytes[i];
  3135. b2 = bytes[i + 1];
  3136. if ((0xC0 <= b1 && b1 <= 0xDF) && (0x80 <= b2 && b2 <= 0xBF))
  3137. {
  3138. //UTF8
  3139. utf8 += 2;
  3140. i++;
  3141. }
  3142. else if (i < len - 2)
  3143. {
  3144. b3 = bytes[i + 2];
  3145. if ((0xE0 <= b1 && b1 <= 0xEF) && (0x80 <= b2 && b2 <= 0xBF) &&
  3146. (0x80 <= b3 && b3 <= 0xBF))
  3147. {
  3148. //UTF8
  3149. utf8 += 3;
  3150. i += 2;
  3151. }
  3152. }
  3153. }
  3154. //M. Takahashi's suggestion
  3155. //utf8 += utf8 / 2;
  3156. System.Diagnostics.Debug.WriteLine(
  3157. string.Format("sjis = {0}, euc = {1}, utf8 = {2}", sjis, euc, utf8));
  3158. if (euc > sjis && euc > utf8)
  3159. {
  3160. //EUC
  3161. return Encoding.GetEncoding(51932);
  3162. }
  3163. else if (sjis > euc && sjis > utf8)
  3164. {
  3165. //SJIS
  3166. return Encoding.GetEncoding(932);
  3167. }
  3168. else if (utf8 > euc && utf8 > sjis)
  3169. {
  3170. //UTF8
  3171. return Encoding.UTF8;
  3172. }
  3173. return null;
  3174. }
  3175. #endregion
  3176. //======================================================================
  3177. #region WebBrowserコンポーネントのカチカチ音制御
  3178. /*
  3179. // 以下のサイトのエントリーを参考にさせていただきました。
  3180. // http://www.moonmile.net/blog/archives/1465
  3181. private string keyCurrent = @"AppEvents\Schemes\Apps\Explorer\Navigating\.Current";
  3182. private string keyDefault = @"AppEvents\Schemes\Apps\Explorer\Navigating\.Default";
  3183. // <summary>
  3184. // クリック音をON
  3185. // </summary>
  3186. // <param name="sender"></param>
  3187. // <param name="e"></param>
  3188. private void WebBrowserClickSoundON()
  3189. {
  3190. //===================================
  3191. // Win8でKeyの取得ができないときがある?
  3192. //===================================
  3193. // .Defaultの値を読み込んで、.Currentに書き込み
  3194. Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser;
  3195. key = key.OpenSubKey(keyDefault);
  3196. string data = (string)key.GetValue(null);
  3197. key.Close();
  3198. key = Microsoft.Win32.Registry.CurrentUser;
  3199. key = key.OpenSubKey(keyCurrent, true);
  3200. key.SetValue(null, data);
  3201. key.Close();
  3202. }
  3203. // <summary>
  3204. // クリック音をOFF
  3205. // </summary>
  3206. // <param name="sender"></param>
  3207. // <param name="e"></param>
  3208. private void WebBrowserClickSoundOFF()
  3209. {
  3210. // .Currnetを @"" にする。
  3211. Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser;
  3212. key = key.OpenSubKey(keyCurrent, true);
  3213. key.SetValue(null, "");
  3214. key.Close();
  3215. }
  3216. */
  3217. #endregion
  3218. }
  3219. }