EscSeqUtils.cs 38 KB

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