EscSeqUtils.cs 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Management;
  6. using System.Runtime.InteropServices;
  7. using System.Threading.Tasks;
  8. using static Unix.Terminal.Curses;
  9. namespace Terminal.Gui;
  10. /// <summary>
  11. /// Provides a platform-independent API for managing ANSI escape sequences.
  12. /// </summary>
  13. /// <remarks>
  14. /// Useful resources:
  15. /// * https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences
  16. /// * https://invisible-island.net/xterm/ctlseqs/ctlseqs.html
  17. /// * https://vt100.net/
  18. /// </remarks>
  19. public static class EscSeqUtils {
  20. /// <summary>
  21. /// Escape key code (ASCII 27/0x1B).
  22. /// </summary>
  23. public static readonly char KeyEsc = (char)Key.Esc;
  24. /// <summary>
  25. /// ESC [ - The CSI (Control Sequence Introducer).
  26. /// </summary>
  27. public static readonly string CSI = $"{KeyEsc}[";
  28. /// <summary>
  29. /// ESC [ ? 1003 h - Enable mouse event tracking.
  30. /// </summary>
  31. public static readonly string CSI_EnableAnyEventMouse = CSI + "?1003h";
  32. /// <summary>
  33. /// ESC [ ? 1006 h - Enable SGR (Select Graphic Rendition).
  34. /// </summary>
  35. public static readonly string CSI_EnableSgrExtModeMouse = CSI + "?1006h";
  36. /// <summary>
  37. /// ESC [ ? 1015 h - Enable URXVT (Unicode Extended Virtual Terminal).
  38. /// </summary>
  39. public static readonly string CSI_EnableUrxvtExtModeMouse = CSI + "?1015h";
  40. /// <summary>
  41. /// ESC [ ? 1003 l - Disable any mouse event tracking.
  42. /// </summary>
  43. public static readonly string CSI_DisableAnyEventMouse = CSI + "?1003l";
  44. /// <summary>
  45. /// ESC [ ? 1006 l - Disable SGR (Select Graphic Rendition).
  46. /// </summary>
  47. public static readonly string CSI_DisableSgrExtModeMouse = CSI + "?1006l";
  48. /// <summary>
  49. /// ESC [ ? 1015 l - Disable URXVT (Unicode Extended Virtual Terminal).
  50. /// </summary>
  51. public static readonly string CSI_DisableUrxvtExtModeMouse = CSI + "?1015l";
  52. /// <summary>
  53. /// Control sequence for enabling mouse events.
  54. /// </summary>
  55. public static string CSI_EnableMouseEvents { get; set; } =
  56. CSI_EnableAnyEventMouse + CSI_EnableUrxvtExtModeMouse + CSI_EnableSgrExtModeMouse;
  57. /// <summary>
  58. /// Control sequence for disabling mouse events.
  59. /// </summary>
  60. public static string CSI_DisableMouseEvents { get; set; } =
  61. CSI_DisableAnyEventMouse + CSI_DisableUrxvtExtModeMouse + CSI_DisableSgrExtModeMouse;
  62. /// <summary>
  63. /// ESC [ ? 1047 h - Activate xterm alternative buffer (no backscroll)
  64. /// </summary>
  65. /// <remarks>
  66. /// From https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Functions-using-CSI-_-ordered-by-the-final-character_s_
  67. /// Use Alternate Screen Buffer, xterm.
  68. /// </remarks>
  69. public static readonly string CSI_ActivateAltBufferNoBackscroll = CSI + "?1047h";
  70. /// <summary>
  71. /// ESC [ ? 1047 l - Restore xterm working buffer (with backscroll)
  72. /// </summary>
  73. /// <remarks>
  74. /// From https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Functions-using-CSI-_-ordered-by-the-final-character_s_
  75. /// Use Normal Screen Buffer, xterm. Clear the screen first if in the Alternate Screen Buffer.
  76. /// </remarks>
  77. public static readonly string CSI_RestoreAltBufferWithBackscroll = CSI + "?1047l";
  78. /// <summary>
  79. /// ESC [ ? 1049 h - Save cursor position and activate xterm alternative buffer (no backscroll)
  80. /// </summary>
  81. /// <remarks>
  82. /// From https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Functions-using-CSI-_-ordered-by-the-final-character_s_
  83. /// Save cursor as in DECSC, xterm. After saving the cursor, switch to the Alternate Screen Buffer,
  84. /// clearing it first.
  85. /// This control combines the effects of the 1047 and 1048 modes.
  86. /// Use this with terminfo-based applications rather than the 47 mode.
  87. /// </remarks>
  88. public static readonly string CSI_SaveCursorAndActivateAltBufferNoBackscroll = CSI + "?1049h";
  89. /// <summary>
  90. /// ESC [ ? 1049 l - Restore cursor position and restore xterm working buffer (with backscroll)
  91. /// </summary>
  92. /// <remarks>
  93. /// From https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Functions-using-CSI-_-ordered-by-the-final-character_s_
  94. /// Use Normal Screen Buffer and restore cursor as in DECRC, xterm.
  95. /// resource.This combines the effects of the 1047 and 1048 modes.
  96. /// </remarks>
  97. public static readonly string CSI_RestoreCursorAndRestoreAltBufferWithBackscroll = CSI + "?1049l";
  98. /// <summary>
  99. /// Options for ANSI ESC "[xJ" - Clears part of the screen.
  100. /// </summary>
  101. public enum ClearScreenOptions {
  102. /// <summary>
  103. /// If n is 0 (or missing), clear from cursor to end of screen.
  104. /// </summary>
  105. CursorToEndOfScreen = 0,
  106. /// <summary>
  107. /// If n is 1, clear from cursor to beginning of the screen.
  108. /// </summary>
  109. CursorToBeginningOfScreen = 1,
  110. /// <summary>
  111. /// If n is 2, clear entire screen (and moves cursor to upper left on DOS ANSI.SYS).
  112. /// </summary>
  113. EntireScreen = 2,
  114. /// <summary>
  115. /// If n is 3, clear entire screen and delete all lines saved in the scrollback buffer
  116. /// </summary>
  117. EntireScreenAndScrollbackBuffer = 3
  118. }
  119. /// <summary>
  120. /// ESC [ x J - Clears part of the screen. See <see cref="ClearScreenOptions"/>.
  121. /// </summary>
  122. /// <param name="option"></param>
  123. /// <returns></returns>
  124. public static string CSI_ClearScreen (ClearScreenOptions option) => $"{CSI}{(int)option}J";
  125. #region Cursor
  126. //ESC [ M - RI Reverse Index – Performs the reverse operation of \n, moves cursor up one line, maintains horizontal position, scrolls buffer if necessary*
  127. /// <summary>
  128. /// ESC [ 7 - Save Cursor Position in Memory**
  129. /// </summary>
  130. public static readonly string CSI_SaveCursorPosition = CSI + "7";
  131. /// <summary>
  132. /// ESC [ 8 - DECSR Restore Cursor Position from Memory**
  133. /// </summary>
  134. public static readonly string CSI_RestoreCursorPosition = CSI + "8";
  135. /// <summary>
  136. /// ESC [ 8 ; height ; width t - Set Terminal Window Size
  137. /// https://terminalguide.namepad.de/seq/csi_st-8/
  138. /// </summary>
  139. public static string CSI_SetTerminalWindowSize (int height, int width) => $"{CSI}8;{height};{width}t";
  140. //ESC [ < n > A - CUU - Cursor Up Cursor up by < n >
  141. //ESC [ < n > B - CUD - Cursor Down Cursor down by < n >
  142. //ESC [ < n > C - CUF - Cursor Forward Cursor forward (Right) by < n >
  143. //ESC [ < n > D - CUB - Cursor Backward Cursor backward (Left) by < n >
  144. //ESC [ < n > E - CNL - Cursor Next Line - Cursor down < n > lines from current position
  145. //ESC [ < n > F - CPL - Cursor Previous Line Cursor up < n > lines from current position
  146. //ESC [ < n > G - CHA - Cursor Horizontal Absolute Cursor moves to < n > th position horizontally in the current line
  147. //ESC [ < n > d - VPA - Vertical Line Position Absolute Cursor moves to the < n > th position vertically in the current column
  148. /// <summary>
  149. /// ESC [ y ; x H - CUP Cursor Position - Cursor moves to x ; y coordinate within the viewport, where x is the column of the y line
  150. /// </summary>
  151. /// <param name="x"></param>
  152. /// <param name="y"></param>
  153. /// <returns></returns>
  154. public static string CSI_SetCursorPosition (int x, int y) => $"{CSI}{y};{x}H";
  155. //ESC [ <y> ; <x> f - HVP Horizontal Vertical Position* Cursor moves to<x>; <y> coordinate within the viewport, where <x> is the column of the<y> line
  156. //ESC [ s - ANSISYSSC Save Cursor – Ansi.sys emulation **With no parameters, performs a save cursor operation like DECSC
  157. //ESC [ u - ANSISYSRC Restore Cursor – Ansi.sys emulation **With no parameters, performs a restore cursor operation like DECRC
  158. //ESC [ ? 12 h - ATT160 Text Cursor Enable Blinking Start the cursor blinking
  159. //ESC [ ? 12 l - ATT160 Text Cursor Disable Blinking Stop blinking the cursor
  160. /// <summary>
  161. /// ESC [ ? 25 h - DECTCEM Text Cursor Enable Mode Show Show the cursor
  162. /// </summary>
  163. public static readonly string CSI_ShowCursor = CSI + "?25h";
  164. /// <summary>
  165. /// ESC [ ? 25 l - DECTCEM Text Cursor Enable Mode Hide Hide the cursor
  166. /// </summary>
  167. public static readonly string CSI_HideCursor = CSI + "?25l";
  168. //ESC [ ? 12 h - ATT160 Text Cursor Enable Blinking Start the cursor blinking
  169. //ESC [ ? 12 l - ATT160 Text Cursor Disable Blinking Stop blinking the cursor
  170. //ESC [ ? 25 h - DECTCEM Text Cursor Enable Mode Show Show the cursor
  171. //ESC [ ? 25 l - DECTCEM Text Cursor Enable Mode Hide Hide the cursor
  172. /// <summary>
  173. /// Styles for ANSI ESC "[x q" - Set Cursor Style
  174. /// </summary>
  175. public enum DECSCUSR_Style {
  176. /// <summary>
  177. /// DECSCUSR - User Shape - Default cursor shape configured by the user
  178. /// </summary>
  179. UserShape = 0,
  180. /// <summary>
  181. /// DECSCUSR - Blinking Block - Blinking block cursor shape
  182. /// </summary>
  183. BlinkingBlock = 1,
  184. /// <summary>
  185. /// DECSCUSR - Steady Block - Steady block cursor shape
  186. /// </summary>
  187. SteadyBlock = 2,
  188. /// <summary>
  189. /// DECSCUSR - Blinking Underline - Blinking underline cursor shape
  190. /// </summary>
  191. BlinkingUnderline = 3,
  192. /// <summary>
  193. /// DECSCUSR - Steady Underline - Steady underline cursor shape
  194. /// </summary>
  195. SteadyUnderline = 4,
  196. /// <summary>
  197. /// DECSCUSR - Blinking Bar - Blinking bar cursor shape
  198. /// </summary>
  199. BlinkingBar = 5,
  200. /// <summary>
  201. /// DECSCUSR - Steady Bar - Steady bar cursor shape
  202. /// </summary>
  203. SteadyBar = 6
  204. }
  205. /// <summary>
  206. /// ESC [ n SP q - Select Cursor Style (DECSCUSR)
  207. /// https://terminalguide.namepad.de/seq/csi_sq_t_space/
  208. /// </summary>
  209. /// <param name="style"></param>
  210. /// <returns></returns>
  211. public static string CSI_SetCursorStyle (DECSCUSR_Style style) => $"{CSI}{(int)style} q";
  212. #endregion
  213. #region Colors
  214. /// <summary>
  215. /// ESC [ (n) m - SGR - Set Graphics Rendition - Set the format of the screen and text as specified by (n)
  216. /// This command is special in that the (n) position can accept between 0 and 16 parameters separated by semicolons.
  217. /// When no parameters are specified, it is treated the same as a single 0 parameter.
  218. /// https://terminalguide.namepad.de/seq/csi_sm/
  219. /// </summary>
  220. public static string CSI_SetGraphicsRendition (params int [] parameters) => $"{CSI}{string.Join (";", parameters)}m";
  221. /// <summary>
  222. /// ESC[38;5;{id}m - Set foreground color (256 colors)
  223. /// </summary>
  224. public static string CSI_SetForegroundColor (int id) => $"{CSI}38;5;{id}m";
  225. /// <summary>
  226. /// ESC[48;5;{id}m - Set background color (256 colors)
  227. /// </summary>
  228. public static string CSI_SetBackgroundColor (int id) => $"{CSI}48;5;{id}m";
  229. /// <summary>
  230. /// ESC[38;2;{r};{g};{b}m Set foreground color as RGB.
  231. /// </summary>
  232. public static string CSI_SetForegroundColorRGB (int r, int g, int b) => $"{CSI}38;2;{r};{g};{b}m";
  233. /// <summary>
  234. /// ESC[48;2;{r};{g};{b}m Set background color as RGB.
  235. /// </summary>
  236. public static string CSI_SetBackgroundColorRGB (int r, int g, int b) => $"{CSI}48;2;{r};{g};{b}m";
  237. #endregion
  238. #region Requests
  239. /// <summary>
  240. /// ESC [ ? 6 n - Request Cursor Position Report (?) (DECXCPR)
  241. /// https://terminalguide.namepad.de/seq/csi_sn__p-6/
  242. /// </summary>
  243. public static readonly string CSI_RequestCursorPositionReport = CSI + "?6n";
  244. /// <summary>
  245. /// The terminal reply to <see cref="CSI_RequestCursorPositionReport"/>. ESC [ ? (y) ; (x) R
  246. /// </summary>
  247. public const string CSI_RequestCursorPositionReport_Terminator = "R";
  248. /// <summary>
  249. /// ESC [ 0 c - Send Device Attributes (Primary DA)
  250. ///
  251. /// https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Application-Program-Command-functions
  252. /// https://www.xfree86.org/current/ctlseqs.html
  253. /// Windows Terminal v1.17 and below emits “\x1b[?1;0c”, indicating "VT101 with No Options".
  254. /// Windows Terminal v1.18+ emits: \x1b[?61;6;7;22;23;24;28;32;42c"
  255. /// See https://github.com/microsoft/terminal/pull/14906
  256. ///
  257. /// 61 - The device conforms to level 1 of the character cell display architecture
  258. /// (See https://github.com/microsoft/terminal/issues/15693#issuecomment-1633304497)
  259. /// 6 = Selective erase
  260. /// 7 = Soft fonts
  261. /// 22 = Color text
  262. /// 23 = Greek character sets
  263. /// 24 = Turkish character sets
  264. /// 28 = Rectangular area operations
  265. /// 32 = Text macros
  266. /// 42 = ISO Latin-2 character set
  267. ///
  268. /// </summary>
  269. public static readonly string CSI_SendDeviceAttributes = CSI + "0c";
  270. /// <summary>
  271. /// ESC [ > 0 c - Send Device Attributes (Secondary DA)
  272. /// Windows Terminal v1.18+ emits: "\x1b[>0;10;1c" (vt100, firmware version 1.0, vt220)
  273. /// </summary>
  274. public static readonly string CSI_SendDeviceAttributes2 = CSI + ">0c";
  275. /// <summary>
  276. /// The terminator indicating a reply to <see cref="CSI_SendDeviceAttributes"/> or <see cref="CSI_SendDeviceAttributes2"/>
  277. ///
  278. /// </summary>
  279. public const string CSI_ReportDeviceAttributes_Terminator = "c";
  280. /// <summary>
  281. /// CSI 1 8 t | yes | yes | yes | report window size in chars
  282. /// https://terminalguide.namepad.de/seq/csi_st-18/
  283. /// </summary>
  284. public static readonly string CSI_ReportTerminalSizeInChars = CSI + "18t";
  285. /// <summary>
  286. /// The terminator indicating a reply to <see cref="CSI_ReportTerminalSizeInChars"/> : ESC [ 8 ; height ; width t
  287. /// </summary>
  288. public const string CSI_ReportTerminalSizeInChars_Terminator = "t";
  289. /// <summary>
  290. /// The value of the response to <see cref="CSI_ReportTerminalSizeInChars"/> indicating value 1 and 2 are the terminal size in chars.
  291. /// </summary>
  292. public const string CSI_ReportTerminalSizeInChars_ResponseValue = "8";
  293. #endregion
  294. /// <summary>
  295. /// Ensures a console key is mapped to one that works correctly with ANSI escape sequences.
  296. /// </summary>
  297. /// <param name="consoleKeyInfo">The <see cref="ConsoleKeyInfo"/>.</param>
  298. /// <returns>The <see cref="ConsoleKeyInfo"/> modified.</returns>
  299. public static ConsoleKeyInfo MapConsoleKeyInfo (ConsoleKeyInfo consoleKeyInfo)
  300. {
  301. ConsoleKeyInfo newConsoleKeyInfo = consoleKeyInfo;
  302. ConsoleKey key;
  303. var keyChar = consoleKeyInfo.KeyChar;
  304. switch ((uint)keyChar) {
  305. case 0:
  306. if (consoleKeyInfo.Key == (ConsoleKey)64) { // Ctrl+Space in Windows.
  307. newConsoleKeyInfo = new ConsoleKeyInfo (' ', ConsoleKey.Spacebar,
  308. (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0,
  309. (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
  310. (consoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0);
  311. }
  312. break;
  313. case uint n when n > 0 && n <= KeyEsc:
  314. if (consoleKeyInfo.Key == 0 && consoleKeyInfo.KeyChar == '\r') {
  315. key = ConsoleKey.Enter;
  316. newConsoleKeyInfo = new ConsoleKeyInfo (consoleKeyInfo.KeyChar,
  317. key,
  318. (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0,
  319. (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
  320. (consoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0);
  321. } else if (consoleKeyInfo.Key == 0) {
  322. key = (ConsoleKey)(char)(consoleKeyInfo.KeyChar + (uint)ConsoleKey.A - 1);
  323. newConsoleKeyInfo = new ConsoleKeyInfo ((char)key,
  324. key,
  325. (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0,
  326. (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
  327. true);
  328. }
  329. break;
  330. case 127: // DEL
  331. newConsoleKeyInfo = new ConsoleKeyInfo (consoleKeyInfo.KeyChar, ConsoleKey.Backspace,
  332. (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0,
  333. (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
  334. (consoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0);
  335. break;
  336. default:
  337. newConsoleKeyInfo = consoleKeyInfo;
  338. break;
  339. }
  340. return newConsoleKeyInfo;
  341. }
  342. /// <summary>
  343. /// A helper to resize the <see cref="ConsoleKeyInfo"/> as needed.
  344. /// </summary>
  345. /// <param name="consoleKeyInfo">The <see cref="ConsoleKeyInfo"/>.</param>
  346. /// <param name="cki">The <see cref="ConsoleKeyInfo"/> array to resize.</param>
  347. /// <returns>The <see cref="ConsoleKeyInfo"/> resized.</returns>
  348. public static ConsoleKeyInfo [] ResizeArray (ConsoleKeyInfo consoleKeyInfo, ConsoleKeyInfo [] cki)
  349. {
  350. Array.Resize (ref cki, cki == null ? 1 : cki.Length + 1);
  351. cki [cki.Length - 1] = consoleKeyInfo;
  352. return cki;
  353. }
  354. /// <summary>
  355. /// Decodes an ANSI escape sequence.
  356. /// </summary>
  357. /// <param name="escSeqRequests">The <see cref="EscSeqRequests"/> which may contain a request.</param>
  358. /// <param name="newConsoleKeyInfo">The <see cref="ConsoleKeyInfo"/> which may changes.</param>
  359. /// <param name="key">The <see cref="ConsoleKey"/> which may changes.</param>
  360. /// <param name="cki">The <see cref="ConsoleKeyInfo"/> array.</param>
  361. /// <param name="mod">The <see cref="ConsoleModifiers"/> which may changes.</param>
  362. /// <param name="c1Control">The control returned by the <see cref="GetC1ControlChar(char)"/> method.</param>
  363. /// <param name="code">The code returned by the <see cref="GetEscapeResult(char[])"/> method.</param>
  364. /// <param name="values">The values returned by the <see cref="GetEscapeResult(char[])"/> method.</param>
  365. /// <param name="terminator">The terminator returned by the <see cref="GetEscapeResult(char[])"/> method.</param>
  366. /// <param name="isMouse">Indicates if the escape sequence is a mouse event.</param>
  367. /// <param name="buttonState">The <see cref="MouseFlags"/> button state.</param>
  368. /// <param name="pos">The <see cref="MouseFlags"/> position.</param>
  369. /// <param name="isResponse">Indicates if the escape sequence is a response to a request.</param>
  370. /// <param name="continuousButtonPressedHandler">The handler that will process the event.</param>
  371. public static void DecodeEscSeq (EscSeqRequests escSeqRequests, ref ConsoleKeyInfo newConsoleKeyInfo, ref ConsoleKey key, ConsoleKeyInfo [] cki, ref ConsoleModifiers mod, out string c1Control, out string code, out string [] values, out string terminator, out bool isMouse, out List<MouseFlags> buttonState, out Point pos, out bool isResponse, Action<MouseFlags, Point> continuousButtonPressedHandler)
  372. {
  373. char [] kChars = GetKeyCharArray (cki);
  374. (c1Control, code, values, terminator) = GetEscapeResult (kChars);
  375. isMouse = false;
  376. buttonState = new List<MouseFlags> () { 0 };
  377. pos = default;
  378. isResponse = false;
  379. switch (c1Control) {
  380. case "ESC":
  381. if (values == null && string.IsNullOrEmpty (terminator)) {
  382. key = ConsoleKey.Escape;
  383. newConsoleKeyInfo = new ConsoleKeyInfo (cki [0].KeyChar, key,
  384. (mod & ConsoleModifiers.Shift) != 0,
  385. (mod & ConsoleModifiers.Alt) != 0,
  386. (mod & ConsoleModifiers.Control) != 0);
  387. } else if ((uint)cki [1].KeyChar >= 1 && (uint)cki [1].KeyChar <= 26) {
  388. key = (ConsoleKey)(char)(cki [1].KeyChar + (uint)ConsoleKey.A - 1);
  389. newConsoleKeyInfo = new ConsoleKeyInfo (cki [1].KeyChar,
  390. key,
  391. false,
  392. true,
  393. true);
  394. } else {
  395. if (cki [1].KeyChar >= 97 && cki [1].KeyChar <= 122) {
  396. key = (ConsoleKey)cki [1].KeyChar.ToString ().ToUpper () [0];
  397. } else {
  398. key = (ConsoleKey)cki [1].KeyChar;
  399. }
  400. newConsoleKeyInfo = new ConsoleKeyInfo ((char)key,
  401. (ConsoleKey)Math.Min ((uint)key, 255),
  402. false,
  403. true,
  404. false);
  405. }
  406. break;
  407. case "SS3":
  408. key = GetConsoleKey (terminator [0], values [0], ref mod);
  409. newConsoleKeyInfo = new ConsoleKeyInfo ('\0',
  410. key,
  411. (mod & ConsoleModifiers.Shift) != 0,
  412. (mod & ConsoleModifiers.Alt) != 0,
  413. (mod & ConsoleModifiers.Control) != 0);
  414. break;
  415. case "CSI":
  416. if (!string.IsNullOrEmpty (code) && code == "<") {
  417. GetMouse (cki, out buttonState, out pos, continuousButtonPressedHandler);
  418. isMouse = true;
  419. return;
  420. } else if (escSeqRequests != null && escSeqRequests.HasResponse (terminator)) {
  421. isResponse = true;
  422. escSeqRequests.Remove (terminator);
  423. return;
  424. }
  425. if (!string.IsNullOrEmpty (terminator)) {
  426. key = GetConsoleKey (terminator [0], values [0], ref mod);
  427. if (key != 0 && values.Length > 1) {
  428. mod |= GetConsoleModifiers (values [1]);
  429. }
  430. newConsoleKeyInfo = new ConsoleKeyInfo ('\0',
  431. key,
  432. (mod & ConsoleModifiers.Shift) != 0,
  433. (mod & ConsoleModifiers.Alt) != 0,
  434. (mod & ConsoleModifiers.Control) != 0);
  435. } else {
  436. // BUGBUG: See https://github.com/gui-cs/Terminal.Gui/issues/2803
  437. // This is caused by NetDriver depending on Console.KeyAvailable?
  438. throw new InvalidOperationException ($"CSI response, but there's no terminator");
  439. //newConsoleKeyInfo = new ConsoleKeyInfo ('\0',
  440. // key,
  441. // (mod & ConsoleModifiers.Shift) != 0,
  442. // (mod & ConsoleModifiers.Alt) != 0,
  443. // (mod & ConsoleModifiers.Control) != 0);
  444. }
  445. break;
  446. }
  447. }
  448. /// <summary>
  449. /// Gets all the needed information about a escape sequence.
  450. /// </summary>
  451. /// <param name="kChar">The array with all chars.</param>
  452. /// <returns>
  453. /// The c1Control returned by <see cref="GetC1ControlChar(char)"/>, code, values and terminating.
  454. /// </returns>
  455. public static (string c1Control, string code, string [] values, string terminating) GetEscapeResult (char [] kChar)
  456. {
  457. if (kChar == null || kChar.Length == 0) {
  458. return (null, null, null, null);
  459. }
  460. if (kChar [0] != KeyEsc) {
  461. throw new InvalidOperationException ("Invalid escape character!");
  462. }
  463. if (kChar.Length == 1) {
  464. return ("ESC", null, null, null);
  465. }
  466. if (kChar.Length == 2) {
  467. return ("ESC", null, null, kChar [1].ToString ());
  468. }
  469. string c1Control = GetC1ControlChar (kChar [1]);
  470. string code = null;
  471. int nSep = kChar.Count (x => x == ';') + 1;
  472. string [] values = new string [nSep];
  473. int valueIdx = 0;
  474. string terminating = "";
  475. for (int i = 2; i < kChar.Length; i++) {
  476. var c = kChar [i];
  477. if (char.IsDigit (c)) {
  478. values [valueIdx] += c.ToString ();
  479. } else if (c == ';') {
  480. valueIdx++;
  481. } else if (valueIdx == nSep - 1 || i == kChar.Length - 1) {
  482. terminating += c.ToString ();
  483. } else {
  484. code += c.ToString ();
  485. }
  486. }
  487. return (c1Control, code, values, terminating);
  488. }
  489. /// <summary>
  490. /// Gets the c1Control used in the called escape sequence.
  491. /// </summary>
  492. /// <param name="c">The char used.</param>
  493. /// <returns>The c1Control.</returns>
  494. public static string GetC1ControlChar (char c)
  495. {
  496. // These control characters are used in the vtXXX emulation.
  497. switch (c) {
  498. case 'D':
  499. return "IND"; // Index
  500. case 'E':
  501. return "NEL"; // Next Line
  502. case 'H':
  503. return "HTS"; // Tab Set
  504. case 'M':
  505. return "RI"; // Reverse Index
  506. case 'N':
  507. return "SS2"; // Single Shift Select of G2 Character Set: affects next character only
  508. case 'O':
  509. return "SS3"; // Single Shift Select of G3 Character Set: affects next character only
  510. case 'P':
  511. return "DCS"; // Device Control String
  512. case 'V':
  513. return "SPA"; // Start of Guarded Area
  514. case 'W':
  515. return "EPA"; // End of Guarded Area
  516. case 'X':
  517. return "SOS"; // Start of String
  518. case 'Z':
  519. return "DECID"; // Return Terminal ID Obsolete form of CSI c (DA)
  520. case '[':
  521. return "CSI"; // Control Sequence Introducer
  522. case '\\':
  523. return "ST"; // String Terminator
  524. case ']':
  525. return "OSC"; // Operating System Command
  526. case '^':
  527. return "PM"; // Privacy Message
  528. case '_':
  529. return "APC"; // Application Program Command
  530. default:
  531. return ""; // Not supported
  532. }
  533. }
  534. /// <summary>
  535. /// Gets the <see cref="ConsoleModifiers"/> from the value.
  536. /// </summary>
  537. /// <param name="value">The value.</param>
  538. /// <returns>The <see cref="ConsoleModifiers"/> or zero.</returns>
  539. public static ConsoleModifiers GetConsoleModifiers (string value)
  540. {
  541. switch (value) {
  542. case "2":
  543. return ConsoleModifiers.Shift;
  544. case "3":
  545. return ConsoleModifiers.Alt;
  546. case "4":
  547. return ConsoleModifiers.Shift | ConsoleModifiers.Alt;
  548. case "5":
  549. return ConsoleModifiers.Control;
  550. case "6":
  551. return ConsoleModifiers.Shift | ConsoleModifiers.Control;
  552. case "7":
  553. return ConsoleModifiers.Alt | ConsoleModifiers.Control;
  554. case "8":
  555. return ConsoleModifiers.Shift | ConsoleModifiers.Alt | ConsoleModifiers.Control;
  556. default:
  557. return 0;
  558. }
  559. }
  560. /// <summary>
  561. /// Gets the <see cref="ConsoleKey"/> depending on terminating and value.
  562. /// </summary>
  563. /// <param name="terminator">The terminator indicating a reply to <see cref="CSI_SendDeviceAttributes"/> or <see cref="CSI_SendDeviceAttributes2"/>.</param>
  564. /// <param name="value">The value.</param>
  565. /// <param name="mod">The <see cref="ConsoleModifiers"/> which may changes.</param>
  566. /// <returns>The <see cref="ConsoleKey"/> and probably the <see cref="ConsoleModifiers"/>.</returns>
  567. public static ConsoleKey GetConsoleKey (char terminator, string value, ref ConsoleModifiers mod)
  568. {
  569. ConsoleKey key;
  570. switch (terminator) {
  571. case 'A':
  572. key = ConsoleKey.UpArrow;
  573. break;
  574. case 'B':
  575. key = ConsoleKey.DownArrow;
  576. break;
  577. case 'C':
  578. key = ConsoleKey.RightArrow;
  579. break;
  580. case 'D':
  581. key = ConsoleKey.LeftArrow;
  582. break;
  583. case 'F':
  584. key = ConsoleKey.End;
  585. break;
  586. case 'H':
  587. key = ConsoleKey.Home;
  588. break;
  589. case 'P':
  590. key = ConsoleKey.F1;
  591. break;
  592. case 'Q':
  593. key = ConsoleKey.F2;
  594. break;
  595. case 'R':
  596. key = ConsoleKey.F3;
  597. break;
  598. case 'S':
  599. key = ConsoleKey.F4;
  600. break;
  601. case 'Z':
  602. key = ConsoleKey.Tab;
  603. mod |= ConsoleModifiers.Shift;
  604. break;
  605. case '~':
  606. switch (value) {
  607. case "2":
  608. key = ConsoleKey.Insert;
  609. break;
  610. case "3":
  611. key = ConsoleKey.Delete;
  612. break;
  613. case "5":
  614. key = ConsoleKey.PageUp;
  615. break;
  616. case "6":
  617. key = ConsoleKey.PageDown;
  618. break;
  619. case "15":
  620. key = ConsoleKey.F5;
  621. break;
  622. case "17":
  623. key = ConsoleKey.F6;
  624. break;
  625. case "18":
  626. key = ConsoleKey.F7;
  627. break;
  628. case "19":
  629. key = ConsoleKey.F8;
  630. break;
  631. case "20":
  632. key = ConsoleKey.F9;
  633. break;
  634. case "21":
  635. key = ConsoleKey.F10;
  636. break;
  637. case "23":
  638. key = ConsoleKey.F11;
  639. break;
  640. case "24":
  641. key = ConsoleKey.F12;
  642. break;
  643. default:
  644. key = 0;
  645. break;
  646. }
  647. break;
  648. default:
  649. key = 0;
  650. break;
  651. }
  652. return key;
  653. }
  654. /// <summary>
  655. /// A helper to get only the <see cref="ConsoleKeyInfo.KeyChar"/> from the <see cref="ConsoleKeyInfo"/> array.
  656. /// </summary>
  657. /// <param name="cki"></param>
  658. /// <returns>The char array of the escape sequence.</returns>
  659. public static char [] GetKeyCharArray (ConsoleKeyInfo [] cki)
  660. {
  661. char [] kChar = new char [] { };
  662. var length = 0;
  663. foreach (var kc in cki) {
  664. length++;
  665. Array.Resize (ref kChar, length);
  666. kChar [length - 1] = kc.KeyChar;
  667. }
  668. return kChar;
  669. }
  670. private static MouseFlags? lastMouseButtonPressed;
  671. //private static MouseFlags? lastMouseButtonReleased;
  672. private static bool isButtonPressed;
  673. //private static bool isButtonReleased;
  674. private static bool isButtonClicked;
  675. private static bool isButtonDoubleClicked;
  676. private static bool isButtonTripleClicked;
  677. private static Point point;
  678. /// <summary>
  679. /// Gets the <see cref="MouseFlags"/> mouse button flags and the position.
  680. /// </summary>
  681. /// <param name="cki">The <see cref="ConsoleKeyInfo"/> array.</param>
  682. /// <param name="mouseFlags">The mouse button flags.</param>
  683. /// <param name="pos">The mouse position.</param>
  684. /// <param name="continuousButtonPressedHandler">The handler that will process the event.</param>
  685. public static void GetMouse (ConsoleKeyInfo [] cki, out List<MouseFlags> mouseFlags, out Point pos, Action<MouseFlags, Point> continuousButtonPressedHandler)
  686. {
  687. MouseFlags buttonState = 0;
  688. pos = new Point ();
  689. int buttonCode = 0;
  690. bool foundButtonCode = false;
  691. int foundPoint = 0;
  692. string value = "";
  693. var kChar = GetKeyCharArray (cki);
  694. //System.Diagnostics.Debug.WriteLine ($"kChar: {new string (kChar)}");
  695. for (int i = 0; i < kChar.Length; i++) {
  696. var c = kChar [i];
  697. if (c == '<') {
  698. foundButtonCode = true;
  699. } else if (foundButtonCode && c != ';') {
  700. value += c.ToString ();
  701. } else if (c == ';') {
  702. if (foundButtonCode) {
  703. foundButtonCode = false;
  704. buttonCode = int.Parse (value);
  705. }
  706. if (foundPoint == 1) {
  707. pos.X = int.Parse (value) - 1;
  708. }
  709. value = "";
  710. foundPoint++;
  711. } else if (foundPoint > 0 && c != 'm' && c != 'M') {
  712. value += c.ToString ();
  713. } else if (c == 'm' || c == 'M') {
  714. //pos.Y = int.Parse (value) + Console.WindowTop - 1;
  715. pos.Y = int.Parse (value) - 1;
  716. switch (buttonCode) {
  717. case 0:
  718. case 8:
  719. case 16:
  720. case 24:
  721. case 32:
  722. case 36:
  723. case 40:
  724. case 48:
  725. case 56:
  726. buttonState = c == 'M' ? MouseFlags.Button1Pressed
  727. : MouseFlags.Button1Released;
  728. break;
  729. case 1:
  730. case 9:
  731. case 17:
  732. case 25:
  733. case 33:
  734. case 37:
  735. case 41:
  736. case 45:
  737. case 49:
  738. case 53:
  739. case 57:
  740. case 61:
  741. buttonState = c == 'M' ? MouseFlags.Button2Pressed
  742. : MouseFlags.Button2Released;
  743. break;
  744. case 2:
  745. case 10:
  746. case 14:
  747. case 18:
  748. case 22:
  749. case 26:
  750. case 30:
  751. case 34:
  752. case 42:
  753. case 46:
  754. case 50:
  755. case 54:
  756. case 58:
  757. case 62:
  758. buttonState = c == 'M' ? MouseFlags.Button3Pressed
  759. : MouseFlags.Button3Released;
  760. break;
  761. case 35:
  762. //// Needed for Windows OS
  763. //if (isButtonPressed && c == 'm'
  764. // && (lastMouseEvent.ButtonState == MouseFlags.Button1Pressed
  765. // || lastMouseEvent.ButtonState == MouseFlags.Button2Pressed
  766. // || lastMouseEvent.ButtonState == MouseFlags.Button3Pressed)) {
  767. // switch (lastMouseEvent.ButtonState) {
  768. // case MouseFlags.Button1Pressed:
  769. // buttonState = MouseFlags.Button1Released;
  770. // break;
  771. // case MouseFlags.Button2Pressed:
  772. // buttonState = MouseFlags.Button2Released;
  773. // break;
  774. // case MouseFlags.Button3Pressed:
  775. // buttonState = MouseFlags.Button3Released;
  776. // break;
  777. // }
  778. //} else {
  779. // buttonState = MouseFlags.ReportMousePosition;
  780. //}
  781. //break;
  782. case 39:
  783. case 43:
  784. case 47:
  785. case 51:
  786. case 55:
  787. case 59:
  788. case 63:
  789. buttonState = MouseFlags.ReportMousePosition;
  790. break;
  791. case 64:
  792. buttonState = MouseFlags.WheeledUp;
  793. break;
  794. case 65:
  795. buttonState = MouseFlags.WheeledDown;
  796. break;
  797. case 68:
  798. case 72:
  799. case 80:
  800. buttonState = MouseFlags.WheeledLeft; // Shift/Ctrl+WheeledUp
  801. break;
  802. case 69:
  803. case 73:
  804. case 81:
  805. buttonState = MouseFlags.WheeledRight; // Shift/Ctrl+WheeledDown
  806. break;
  807. }
  808. // Modifiers.
  809. switch (buttonCode) {
  810. case 8:
  811. case 9:
  812. case 10:
  813. case 43:
  814. buttonState |= MouseFlags.ButtonAlt;
  815. break;
  816. case 14:
  817. case 47:
  818. buttonState |= MouseFlags.ButtonAlt | MouseFlags.ButtonShift;
  819. break;
  820. case 16:
  821. case 17:
  822. case 18:
  823. case 51:
  824. buttonState |= MouseFlags.ButtonCtrl;
  825. break;
  826. case 22:
  827. case 55:
  828. buttonState |= MouseFlags.ButtonCtrl | MouseFlags.ButtonShift;
  829. break;
  830. case 24:
  831. case 25:
  832. case 26:
  833. case 59:
  834. buttonState |= MouseFlags.ButtonCtrl | MouseFlags.ButtonAlt;
  835. break;
  836. case 30:
  837. case 63:
  838. buttonState |= MouseFlags.ButtonCtrl | MouseFlags.ButtonShift | MouseFlags.ButtonAlt;
  839. break;
  840. case 32:
  841. case 33:
  842. case 34:
  843. buttonState |= MouseFlags.ReportMousePosition;
  844. break;
  845. case 36:
  846. case 37:
  847. buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonShift;
  848. break;
  849. case 39:
  850. case 68:
  851. case 69:
  852. buttonState |= MouseFlags.ButtonShift;
  853. break;
  854. case 40:
  855. case 41:
  856. case 42:
  857. buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonAlt;
  858. break;
  859. case 45:
  860. case 46:
  861. buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonAlt | MouseFlags.ButtonShift;
  862. break;
  863. case 48:
  864. case 49:
  865. case 50:
  866. buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonCtrl;
  867. break;
  868. case 53:
  869. case 54:
  870. buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonCtrl | MouseFlags.ButtonShift;
  871. break;
  872. case 56:
  873. case 57:
  874. case 58:
  875. buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonCtrl | MouseFlags.ButtonAlt;
  876. break;
  877. case 61:
  878. case 62:
  879. buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonCtrl | MouseFlags.ButtonShift | MouseFlags.ButtonAlt;
  880. break;
  881. }
  882. }
  883. }
  884. mouseFlags = new List<MouseFlags> () { MouseFlags.AllEvents };
  885. if (lastMouseButtonPressed != null && !isButtonPressed && !buttonState.HasFlag (MouseFlags.ReportMousePosition)
  886. && !buttonState.HasFlag (MouseFlags.Button1Released)
  887. && !buttonState.HasFlag (MouseFlags.Button2Released)
  888. && !buttonState.HasFlag (MouseFlags.Button3Released)
  889. && !buttonState.HasFlag (MouseFlags.Button4Released)) {
  890. lastMouseButtonPressed = null;
  891. isButtonPressed = false;
  892. }
  893. if (!isButtonClicked && !isButtonDoubleClicked && ((buttonState == MouseFlags.Button1Pressed || buttonState == MouseFlags.Button2Pressed ||
  894. buttonState == MouseFlags.Button3Pressed || buttonState == MouseFlags.Button4Pressed) && lastMouseButtonPressed == null) ||
  895. isButtonPressed && lastMouseButtonPressed != null && buttonState.HasFlag (MouseFlags.ReportMousePosition)) {
  896. mouseFlags [0] = buttonState;
  897. lastMouseButtonPressed = buttonState;
  898. isButtonPressed = true;
  899. if ((mouseFlags [0] & MouseFlags.ReportMousePosition) == 0) {
  900. point = new Point () {
  901. X = pos.X,
  902. Y = pos.Y
  903. };
  904. Application.MainLoop.AddIdle (() => {
  905. Task.Run (async () => await ProcessContinuousButtonPressedAsync (buttonState, continuousButtonPressedHandler));
  906. return false;
  907. });
  908. } else if (mouseFlags [0] == MouseFlags.ReportMousePosition) {
  909. isButtonPressed = false;
  910. }
  911. } else if (isButtonDoubleClicked && (buttonState == MouseFlags.Button1Pressed || buttonState == MouseFlags.Button2Pressed ||
  912. buttonState == MouseFlags.Button3Pressed || buttonState == MouseFlags.Button4Pressed)) {
  913. mouseFlags [0] = GetButtonTripleClicked (buttonState);
  914. isButtonDoubleClicked = false;
  915. isButtonTripleClicked = true;
  916. } else if (isButtonClicked && (buttonState == MouseFlags.Button1Pressed || buttonState == MouseFlags.Button2Pressed ||
  917. buttonState == MouseFlags.Button3Pressed || buttonState == MouseFlags.Button4Pressed)) {
  918. mouseFlags [0] = GetButtonDoubleClicked (buttonState);
  919. isButtonClicked = false;
  920. isButtonDoubleClicked = true;
  921. Application.MainLoop.AddIdle (() => {
  922. Task.Run (async () => await ProcessButtonDoubleClickedAsync ());
  923. return false;
  924. });
  925. }
  926. //else if (isButtonReleased && !isButtonClicked && buttonState == MouseFlags.ReportMousePosition) {
  927. // mouseFlag [0] = GetButtonClicked ((MouseFlags)lastMouseButtonReleased);
  928. // lastMouseButtonReleased = null;
  929. // isButtonReleased = false;
  930. // isButtonClicked = true;
  931. // Application.MainLoop.AddIdle (() => {
  932. // Task.Run (async () => await ProcessButtonClickedAsync ());
  933. // return false;
  934. // });
  935. //}
  936. else if (!isButtonClicked && !isButtonDoubleClicked && (buttonState == MouseFlags.Button1Released || buttonState == MouseFlags.Button2Released ||
  937. buttonState == MouseFlags.Button3Released || buttonState == MouseFlags.Button4Released)) {
  938. mouseFlags [0] = buttonState;
  939. isButtonPressed = false;
  940. if (isButtonTripleClicked) {
  941. isButtonTripleClicked = false;
  942. } else if (pos.X == point.X && pos.Y == point.Y) {
  943. mouseFlags.Add (GetButtonClicked (buttonState));
  944. isButtonClicked = true;
  945. Application.MainLoop.AddIdle (() => {
  946. Task.Run (async () => await ProcessButtonClickedAsync ());
  947. return false;
  948. });
  949. }
  950. point = pos;
  951. //if ((lastMouseButtonPressed & MouseFlags.ReportMousePosition) == 0) {
  952. // lastMouseButtonReleased = buttonState;
  953. // isButtonPressed = false;
  954. // isButtonReleased = true;
  955. //} else {
  956. // lastMouseButtonPressed = null;
  957. // isButtonPressed = false;
  958. //}
  959. } else if (buttonState == MouseFlags.WheeledUp) {
  960. mouseFlags [0] = MouseFlags.WheeledUp;
  961. } else if (buttonState == MouseFlags.WheeledDown) {
  962. mouseFlags [0] = MouseFlags.WheeledDown;
  963. } else if (buttonState == MouseFlags.WheeledLeft) {
  964. mouseFlags [0] = MouseFlags.WheeledLeft;
  965. } else if (buttonState == MouseFlags.WheeledRight) {
  966. mouseFlags [0] = MouseFlags.WheeledRight;
  967. } else if (buttonState == MouseFlags.ReportMousePosition) {
  968. mouseFlags [0] = MouseFlags.ReportMousePosition;
  969. } else {
  970. mouseFlags [0] = buttonState;
  971. //foreach (var flag in buttonState.GetUniqueFlags()) {
  972. // mouseFlag [0] |= flag;
  973. //}
  974. }
  975. mouseFlags [0] = SetControlKeyStates (buttonState, mouseFlags [0]);
  976. //buttonState = mouseFlags;
  977. //System.Diagnostics.Debug.WriteLine ($"buttonState: {buttonState} X: {pos.X} Y: {pos.Y}");
  978. //foreach (var mf in mouseFlags) {
  979. // System.Diagnostics.Debug.WriteLine ($"mouseFlags: {mf} X: {pos.X} Y: {pos.Y}");
  980. //}
  981. }
  982. private static async Task ProcessContinuousButtonPressedAsync (MouseFlags mouseFlag, Action<MouseFlags, Point> continuousButtonPressedHandler)
  983. {
  984. while (isButtonPressed) {
  985. await Task.Delay (100);
  986. //var me = new MouseEvent () {
  987. // X = point.X,
  988. // Y = point.Y,
  989. // Flags = mouseFlag
  990. //};
  991. var view = Application.WantContinuousButtonPressedView;
  992. if (view == null)
  993. break;
  994. if (isButtonPressed && lastMouseButtonPressed != null && (mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  995. Application.Invoke (() => continuousButtonPressedHandler (mouseFlag, point));
  996. }
  997. }
  998. }
  999. private static async Task ProcessButtonClickedAsync ()
  1000. {
  1001. await Task.Delay (300);
  1002. isButtonClicked = false;
  1003. }
  1004. private static async Task ProcessButtonDoubleClickedAsync ()
  1005. {
  1006. await Task.Delay (300);
  1007. isButtonDoubleClicked = false;
  1008. }
  1009. private static MouseFlags GetButtonClicked (MouseFlags mouseFlag)
  1010. {
  1011. MouseFlags mf = default;
  1012. switch (mouseFlag) {
  1013. case MouseFlags.Button1Released:
  1014. mf = MouseFlags.Button1Clicked;
  1015. break;
  1016. case MouseFlags.Button2Released:
  1017. mf = MouseFlags.Button2Clicked;
  1018. break;
  1019. case MouseFlags.Button3Released:
  1020. mf = MouseFlags.Button3Clicked;
  1021. break;
  1022. }
  1023. return mf;
  1024. }
  1025. private static MouseFlags GetButtonDoubleClicked (MouseFlags mouseFlag)
  1026. {
  1027. MouseFlags mf = default;
  1028. switch (mouseFlag) {
  1029. case MouseFlags.Button1Pressed:
  1030. mf = MouseFlags.Button1DoubleClicked;
  1031. break;
  1032. case MouseFlags.Button2Pressed:
  1033. mf = MouseFlags.Button2DoubleClicked;
  1034. break;
  1035. case MouseFlags.Button3Pressed:
  1036. mf = MouseFlags.Button3DoubleClicked;
  1037. break;
  1038. }
  1039. return mf;
  1040. }
  1041. private static MouseFlags GetButtonTripleClicked (MouseFlags mouseFlag)
  1042. {
  1043. MouseFlags mf = default;
  1044. switch (mouseFlag) {
  1045. case MouseFlags.Button1Pressed:
  1046. mf = MouseFlags.Button1TripleClicked;
  1047. break;
  1048. case MouseFlags.Button2Pressed:
  1049. mf = MouseFlags.Button2TripleClicked;
  1050. break;
  1051. case MouseFlags.Button3Pressed:
  1052. mf = MouseFlags.Button3TripleClicked;
  1053. break;
  1054. }
  1055. return mf;
  1056. }
  1057. private static MouseFlags SetControlKeyStates (MouseFlags buttonState, MouseFlags mouseFlag)
  1058. {
  1059. if ((buttonState & MouseFlags.ButtonCtrl) != 0 && (mouseFlag & MouseFlags.ButtonCtrl) == 0)
  1060. mouseFlag |= MouseFlags.ButtonCtrl;
  1061. if ((buttonState & MouseFlags.ButtonShift) != 0 && (mouseFlag & MouseFlags.ButtonShift) == 0)
  1062. mouseFlag |= MouseFlags.ButtonShift;
  1063. if ((buttonState & MouseFlags.ButtonAlt) != 0 && (mouseFlag & MouseFlags.ButtonAlt) == 0)
  1064. mouseFlag |= MouseFlags.ButtonAlt;
  1065. return mouseFlag;
  1066. }
  1067. // TODO: Move this out of here and into ConsoleDriver or somewhere else.
  1068. /// <summary>
  1069. /// Get the terminal that holds the console driver.
  1070. /// </summary>
  1071. /// <param name="process">The process.</param>
  1072. /// <returns>If supported the executable console process, null otherwise.</returns>
  1073. public static Process GetParentProcess (Process process)
  1074. {
  1075. if (!RuntimeInformation.IsOSPlatform (OSPlatform.Windows)) {
  1076. return null;
  1077. }
  1078. string query = "SELECT ParentProcessId FROM Win32_Process WHERE ProcessId = " + process.Id;
  1079. using (ManagementObjectSearcher mos = new ManagementObjectSearcher (query)) {
  1080. foreach (ManagementObject mo in mos.Get ()) {
  1081. if (mo ["ParentProcessId"] != null) {
  1082. try {
  1083. var id = Convert.ToInt32 (mo ["ParentProcessId"]);
  1084. return Process.GetProcessById (id);
  1085. } catch {
  1086. }
  1087. }
  1088. }
  1089. }
  1090. return null;
  1091. }
  1092. }