EscSeqUtils.cs 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211
  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)KeyCode.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="row">Origin is (1,1).</param>
  152. /// <param name="col">Origin is (1,1).</param>
  153. /// <returns></returns>
  154. public static string CSI_SetCursorPosition (int row, int col) => $"{CSI}{row};{col}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 [ (n) m - Uses <see cref="CSI_SetGraphicsRendition(int[])" /> to set the foreground color.
  223. /// </summary>
  224. /// <param name="code">One of the 16 color codes.</param>
  225. /// <returns></returns>
  226. public static string CSI_SetForegroundColor (AnsiColorCode code) => CSI_SetGraphicsRendition ((int)code);
  227. /// <summary>
  228. /// ESC [ (n) m - Uses <see cref="CSI_SetGraphicsRendition(int[])" /> to set the background color.
  229. /// </summary>
  230. /// <param name="code">One of the 16 color codes.</param>
  231. /// <returns></returns>
  232. public static string CSI_SetBackgroundColor (AnsiColorCode code) => CSI_SetGraphicsRendition ((int)code+10);
  233. /// <summary>
  234. /// ESC[38;5;{id}m - Set foreground color (256 colors)
  235. /// </summary>
  236. public static string CSI_SetForegroundColor256 (int color) => $"{CSI}38;5;{color}m";
  237. /// <summary>
  238. /// ESC[48;5;{id}m - Set background color (256 colors)
  239. /// </summary>
  240. public static string CSI_SetBackgroundColor256 (int color) => $"{CSI}48;5;{color}m";
  241. /// <summary>
  242. /// ESC[38;2;{r};{g};{b}m Set foreground color as RGB.
  243. /// </summary>
  244. public static string CSI_SetForegroundColorRGB (int r, int g, int b) => $"{CSI}38;2;{r};{g};{b}m";
  245. /// <summary>
  246. /// ESC[48;2;{r};{g};{b}m Set background color as RGB.
  247. /// </summary>
  248. public static string CSI_SetBackgroundColorRGB (int r, int g, int b) => $"{CSI}48;2;{r};{g};{b}m";
  249. #endregion
  250. #region Requests
  251. /// <summary>
  252. /// ESC [ ? 6 n - Request Cursor Position Report (?) (DECXCPR)
  253. /// https://terminalguide.namepad.de/seq/csi_sn__p-6/
  254. /// </summary>
  255. public static readonly string CSI_RequestCursorPositionReport = CSI + "?6n";
  256. /// <summary>
  257. /// The terminal reply to <see cref="CSI_RequestCursorPositionReport"/>. ESC [ ? (y) ; (x) R
  258. /// </summary>
  259. public const string CSI_RequestCursorPositionReport_Terminator = "R";
  260. /// <summary>
  261. /// ESC [ 0 c - Send Device Attributes (Primary DA)
  262. ///
  263. /// https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Application-Program-Command-functions
  264. /// https://www.xfree86.org/current/ctlseqs.html
  265. /// Windows Terminal v1.17 and below emits “\x1b[?1;0c”, indicating "VT101 with No Options".
  266. /// Windows Terminal v1.18+ emits: \x1b[?61;6;7;22;23;24;28;32;42c"
  267. /// See https://github.com/microsoft/terminal/pull/14906
  268. ///
  269. /// 61 - The device conforms to level 1 of the character cell display architecture
  270. /// (See https://github.com/microsoft/terminal/issues/15693#issuecomment-1633304497)
  271. /// 6 = Selective erase
  272. /// 7 = Soft fonts
  273. /// 22 = Color text
  274. /// 23 = Greek character sets
  275. /// 24 = Turkish character sets
  276. /// 28 = Rectangular area operations
  277. /// 32 = Text macros
  278. /// 42 = ISO Latin-2 character set
  279. ///
  280. /// </summary>
  281. public static readonly string CSI_SendDeviceAttributes = CSI + "0c";
  282. /// <summary>
  283. /// ESC [ > 0 c - Send Device Attributes (Secondary DA)
  284. /// Windows Terminal v1.18+ emits: "\x1b[>0;10;1c" (vt100, firmware version 1.0, vt220)
  285. /// </summary>
  286. public static readonly string CSI_SendDeviceAttributes2 = CSI + ">0c";
  287. /// <summary>
  288. /// The terminator indicating a reply to <see cref="CSI_SendDeviceAttributes"/> or <see cref="CSI_SendDeviceAttributes2"/>
  289. ///
  290. /// </summary>
  291. public const string CSI_ReportDeviceAttributes_Terminator = "c";
  292. /// <summary>
  293. /// CSI 1 8 t | yes | yes | yes | report window size in chars
  294. /// https://terminalguide.namepad.de/seq/csi_st-18/
  295. /// </summary>
  296. public static readonly string CSI_ReportTerminalSizeInChars = CSI + "18t";
  297. /// <summary>
  298. /// The terminator indicating a reply to <see cref="CSI_ReportTerminalSizeInChars"/> : ESC [ 8 ; height ; width t
  299. /// </summary>
  300. public const string CSI_ReportTerminalSizeInChars_Terminator = "t";
  301. /// <summary>
  302. /// The value of the response to <see cref="CSI_ReportTerminalSizeInChars"/> indicating value 1 and 2 are the terminal size in chars.
  303. /// </summary>
  304. public const string CSI_ReportTerminalSizeInChars_ResponseValue = "8";
  305. #endregion
  306. /// <summary>
  307. /// Ensures a console key is mapped to one that works correctly with ANSI escape sequences.
  308. /// </summary>
  309. /// <param name="consoleKeyInfo">The <see cref="ConsoleKeyInfo"/>.</param>
  310. /// <returns>The <see cref="ConsoleKeyInfo"/> modified.</returns>
  311. public static ConsoleKeyInfo MapConsoleKeyInfo (ConsoleKeyInfo consoleKeyInfo)
  312. {
  313. ConsoleKeyInfo newConsoleKeyInfo = consoleKeyInfo;
  314. ConsoleKey key;
  315. var keyChar = consoleKeyInfo.KeyChar;
  316. switch ((uint)keyChar) {
  317. case 0:
  318. if (consoleKeyInfo.Key == (ConsoleKey)64) { // Ctrl+Space in Windows.
  319. newConsoleKeyInfo = new ConsoleKeyInfo (' ', ConsoleKey.Spacebar,
  320. (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0,
  321. (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
  322. (consoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0);
  323. }
  324. break;
  325. case uint n when n > 0 && n <= KeyEsc:
  326. if (consoleKeyInfo.Key == 0 && consoleKeyInfo.KeyChar == '\r') {
  327. key = ConsoleKey.Enter;
  328. newConsoleKeyInfo = new ConsoleKeyInfo (consoleKeyInfo.KeyChar,
  329. key,
  330. (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0,
  331. (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
  332. (consoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0);
  333. } else if (consoleKeyInfo.Key == 0) {
  334. key = (ConsoleKey)(char)(consoleKeyInfo.KeyChar + (uint)ConsoleKey.A - 1);
  335. newConsoleKeyInfo = new ConsoleKeyInfo ((char)key,
  336. key,
  337. (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0,
  338. (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
  339. true);
  340. }
  341. break;
  342. case 127: // DEL
  343. newConsoleKeyInfo = new ConsoleKeyInfo (consoleKeyInfo.KeyChar, ConsoleKey.Backspace,
  344. (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0,
  345. (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
  346. (consoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0);
  347. break;
  348. default:
  349. newConsoleKeyInfo = consoleKeyInfo;
  350. break;
  351. }
  352. return newConsoleKeyInfo;
  353. }
  354. /// <summary>
  355. /// A helper to resize the <see cref="ConsoleKeyInfo"/> as needed.
  356. /// </summary>
  357. /// <param name="consoleKeyInfo">The <see cref="ConsoleKeyInfo"/>.</param>
  358. /// <param name="cki">The <see cref="ConsoleKeyInfo"/> array to resize.</param>
  359. /// <returns>The <see cref="ConsoleKeyInfo"/> resized.</returns>
  360. public static ConsoleKeyInfo [] ResizeArray (ConsoleKeyInfo consoleKeyInfo, ConsoleKeyInfo [] cki)
  361. {
  362. Array.Resize (ref cki, cki == null ? 1 : cki.Length + 1);
  363. cki [cki.Length - 1] = consoleKeyInfo;
  364. return cki;
  365. }
  366. /// <summary>
  367. /// Decodes an ANSI escape sequence.
  368. /// </summary>
  369. /// <param name="escSeqRequests">The <see cref="EscSeqRequests"/> which may contain a request.</param>
  370. /// <param name="newConsoleKeyInfo">The <see cref="ConsoleKeyInfo"/> which may changes.</param>
  371. /// <param name="key">The <see cref="ConsoleKey"/> which may changes.</param>
  372. /// <param name="cki">The <see cref="ConsoleKeyInfo"/> array.</param>
  373. /// <param name="mod">The <see cref="ConsoleModifiers"/> which may changes.</param>
  374. /// <param name="c1Control">The control returned by the <see cref="GetC1ControlChar(char)"/> method.</param>
  375. /// <param name="code">The code returned by the <see cref="GetEscapeResult(char[])"/> method.</param>
  376. /// <param name="values">The values returned by the <see cref="GetEscapeResult(char[])"/> method.</param>
  377. /// <param name="terminator">The terminator returned by the <see cref="GetEscapeResult(char[])"/> method.</param>
  378. /// <param name="isMouse">Indicates if the escape sequence is a mouse event.</param>
  379. /// <param name="buttonState">The <see cref="MouseFlags"/> button state.</param>
  380. /// <param name="pos">The <see cref="MouseFlags"/> position.</param>
  381. /// <param name="isResponse">Indicates if the escape sequence is a response to a request.</param>
  382. /// <param name="continuousButtonPressedHandler">The handler that will process the event.</param>
  383. 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)
  384. {
  385. char [] kChars = GetKeyCharArray (cki);
  386. (c1Control, code, values, terminator) = GetEscapeResult (kChars);
  387. isMouse = false;
  388. buttonState = new List<MouseFlags> () { 0 };
  389. pos = default;
  390. isResponse = false;
  391. switch (c1Control) {
  392. case "ESC":
  393. if (values == null && string.IsNullOrEmpty (terminator)) {
  394. key = ConsoleKey.Escape;
  395. newConsoleKeyInfo = new ConsoleKeyInfo (cki [0].KeyChar, key,
  396. (mod & ConsoleModifiers.Shift) != 0,
  397. (mod & ConsoleModifiers.Alt) != 0,
  398. (mod & ConsoleModifiers.Control) != 0);
  399. } else if ((uint)cki [1].KeyChar >= 1 && (uint)cki [1].KeyChar <= 26) {
  400. key = (ConsoleKey)(char)(cki [1].KeyChar + (uint)ConsoleKey.A - 1);
  401. newConsoleKeyInfo = new ConsoleKeyInfo (cki [1].KeyChar,
  402. key,
  403. false,
  404. true,
  405. true);
  406. } else {
  407. if (cki [1].KeyChar >= 97 && cki [1].KeyChar <= 122) {
  408. key = (ConsoleKey)cki [1].KeyChar.ToString ().ToUpper () [0];
  409. } else {
  410. key = (ConsoleKey)cki [1].KeyChar;
  411. }
  412. newConsoleKeyInfo = new ConsoleKeyInfo ((char)key,
  413. (ConsoleKey)Math.Min ((uint)key, 255),
  414. false,
  415. true,
  416. false);
  417. }
  418. break;
  419. case "SS3":
  420. key = GetConsoleKey (terminator [0], values [0], ref mod);
  421. newConsoleKeyInfo = new ConsoleKeyInfo ('\0',
  422. key,
  423. (mod & ConsoleModifiers.Shift) != 0,
  424. (mod & ConsoleModifiers.Alt) != 0,
  425. (mod & ConsoleModifiers.Control) != 0);
  426. break;
  427. case "CSI":
  428. if (!string.IsNullOrEmpty (code) && code == "<") {
  429. GetMouse (cki, out buttonState, out pos, continuousButtonPressedHandler);
  430. isMouse = true;
  431. return;
  432. } else if (escSeqRequests != null && escSeqRequests.HasResponse (terminator)) {
  433. isResponse = true;
  434. escSeqRequests.Remove (terminator);
  435. return;
  436. }
  437. if (!string.IsNullOrEmpty (terminator)) {
  438. key = GetConsoleKey (terminator [0], values [0], ref mod);
  439. if (key != 0 && values.Length > 1) {
  440. mod |= GetConsoleModifiers (values [1]);
  441. }
  442. newConsoleKeyInfo = new ConsoleKeyInfo ('\0',
  443. key,
  444. (mod & ConsoleModifiers.Shift) != 0,
  445. (mod & ConsoleModifiers.Alt) != 0,
  446. (mod & ConsoleModifiers.Control) != 0);
  447. } else {
  448. // BUGBUG: See https://github.com/gui-cs/Terminal.Gui/issues/2803
  449. // This is caused by NetDriver depending on Console.KeyAvailable?
  450. throw new InvalidOperationException ($"CSI response, but there's no terminator");
  451. //newConsoleKeyInfo = new ConsoleKeyInfo ('\0',
  452. // key,
  453. // (mod & ConsoleModifiers.Shift) != 0,
  454. // (mod & ConsoleModifiers.Alt) != 0,
  455. // (mod & ConsoleModifiers.Control) != 0);
  456. }
  457. break;
  458. }
  459. }
  460. /// <summary>
  461. /// Gets all the needed information about a escape sequence.
  462. /// </summary>
  463. /// <param name="kChar">The array with all chars.</param>
  464. /// <returns>
  465. /// The c1Control returned by <see cref="GetC1ControlChar(char)"/>, code, values and terminating.
  466. /// </returns>
  467. public static (string c1Control, string code, string [] values, string terminating) GetEscapeResult (char [] kChar)
  468. {
  469. if (kChar == null || kChar.Length == 0) {
  470. return (null, null, null, null);
  471. }
  472. if (kChar [0] != KeyEsc) {
  473. throw new InvalidOperationException ("Invalid escape character!");
  474. }
  475. if (kChar.Length == 1) {
  476. return ("ESC", null, null, null);
  477. }
  478. if (kChar.Length == 2) {
  479. return ("ESC", null, null, kChar [1].ToString ());
  480. }
  481. string c1Control = GetC1ControlChar (kChar [1]);
  482. string code = null;
  483. int nSep = kChar.Count (x => x == ';') + 1;
  484. string [] values = new string [nSep];
  485. int valueIdx = 0;
  486. string terminating = "";
  487. for (int i = 2; i < kChar.Length; i++) {
  488. var c = kChar [i];
  489. if (char.IsDigit (c)) {
  490. values [valueIdx] += c.ToString ();
  491. } else if (c == ';') {
  492. valueIdx++;
  493. } else if (valueIdx == nSep - 1 || i == kChar.Length - 1) {
  494. terminating += c.ToString ();
  495. } else {
  496. code += c.ToString ();
  497. }
  498. }
  499. return (c1Control, code, values, terminating);
  500. }
  501. /// <summary>
  502. /// Gets the c1Control used in the called escape sequence.
  503. /// </summary>
  504. /// <param name="c">The char used.</param>
  505. /// <returns>The c1Control.</returns>
  506. public static string GetC1ControlChar (char c)
  507. {
  508. // These control characters are used in the vtXXX emulation.
  509. switch (c) {
  510. case 'D':
  511. return "IND"; // Index
  512. case 'E':
  513. return "NEL"; // Next Line
  514. case 'H':
  515. return "HTS"; // Tab Set
  516. case 'M':
  517. return "RI"; // Reverse Index
  518. case 'N':
  519. return "SS2"; // Single Shift Select of G2 Character Set: affects next character only
  520. case 'O':
  521. return "SS3"; // Single Shift Select of G3 Character Set: affects next character only
  522. case 'P':
  523. return "DCS"; // Device Control String
  524. case 'V':
  525. return "SPA"; // Start of Guarded Area
  526. case 'W':
  527. return "EPA"; // End of Guarded Area
  528. case 'X':
  529. return "SOS"; // Start of String
  530. case 'Z':
  531. return "DECID"; // Return Terminal ID Obsolete form of CSI c (DA)
  532. case '[':
  533. return "CSI"; // Control Sequence Introducer
  534. case '\\':
  535. return "ST"; // String Terminator
  536. case ']':
  537. return "OSC"; // Operating System Command
  538. case '^':
  539. return "PM"; // Privacy Message
  540. case '_':
  541. return "APC"; // Application Program Command
  542. default:
  543. return ""; // Not supported
  544. }
  545. }
  546. /// <summary>
  547. /// Gets the <see cref="ConsoleModifiers"/> from the value.
  548. /// </summary>
  549. /// <param name="value">The value.</param>
  550. /// <returns>The <see cref="ConsoleModifiers"/> or zero.</returns>
  551. public static ConsoleModifiers GetConsoleModifiers (string value)
  552. {
  553. switch (value) {
  554. case "2":
  555. return ConsoleModifiers.Shift;
  556. case "3":
  557. return ConsoleModifiers.Alt;
  558. case "4":
  559. return ConsoleModifiers.Shift | ConsoleModifiers.Alt;
  560. case "5":
  561. return ConsoleModifiers.Control;
  562. case "6":
  563. return ConsoleModifiers.Shift | ConsoleModifiers.Control;
  564. case "7":
  565. return ConsoleModifiers.Alt | ConsoleModifiers.Control;
  566. case "8":
  567. return ConsoleModifiers.Shift | ConsoleModifiers.Alt | ConsoleModifiers.Control;
  568. default:
  569. return 0;
  570. }
  571. }
  572. /// <summary>
  573. /// Gets the <see cref="ConsoleKey"/> depending on terminating and value.
  574. /// </summary>
  575. /// <param name="terminator">The terminator indicating a reply to <see cref="CSI_SendDeviceAttributes"/> or <see cref="CSI_SendDeviceAttributes2"/>.</param>
  576. /// <param name="value">The value.</param>
  577. /// <param name="mod">The <see cref="ConsoleModifiers"/> which may changes.</param>
  578. /// <returns>The <see cref="ConsoleKey"/> and probably the <see cref="ConsoleModifiers"/>.</returns>
  579. public static ConsoleKey GetConsoleKey (char terminator, string value, ref ConsoleModifiers mod)
  580. {
  581. ConsoleKey key;
  582. switch (terminator) {
  583. case 'A':
  584. key = ConsoleKey.UpArrow;
  585. break;
  586. case 'B':
  587. key = ConsoleKey.DownArrow;
  588. break;
  589. case 'C':
  590. key = ConsoleKey.RightArrow;
  591. break;
  592. case 'D':
  593. key = ConsoleKey.LeftArrow;
  594. break;
  595. case 'F':
  596. key = ConsoleKey.End;
  597. break;
  598. case 'H':
  599. key = ConsoleKey.Home;
  600. break;
  601. case 'P':
  602. key = ConsoleKey.F1;
  603. break;
  604. case 'Q':
  605. key = ConsoleKey.F2;
  606. break;
  607. case 'R':
  608. key = ConsoleKey.F3;
  609. break;
  610. case 'S':
  611. key = ConsoleKey.F4;
  612. break;
  613. case 'Z':
  614. key = ConsoleKey.Tab;
  615. mod |= ConsoleModifiers.Shift;
  616. break;
  617. case '~':
  618. switch (value) {
  619. case "2":
  620. key = ConsoleKey.Insert;
  621. break;
  622. case "3":
  623. key = ConsoleKey.Delete;
  624. break;
  625. case "5":
  626. key = ConsoleKey.PageUp;
  627. break;
  628. case "6":
  629. key = ConsoleKey.PageDown;
  630. break;
  631. case "15":
  632. key = ConsoleKey.F5;
  633. break;
  634. case "17":
  635. key = ConsoleKey.F6;
  636. break;
  637. case "18":
  638. key = ConsoleKey.F7;
  639. break;
  640. case "19":
  641. key = ConsoleKey.F8;
  642. break;
  643. case "20":
  644. key = ConsoleKey.F9;
  645. break;
  646. case "21":
  647. key = ConsoleKey.F10;
  648. break;
  649. case "23":
  650. key = ConsoleKey.F11;
  651. break;
  652. case "24":
  653. key = ConsoleKey.F12;
  654. break;
  655. default:
  656. key = 0;
  657. break;
  658. }
  659. break;
  660. default:
  661. key = 0;
  662. break;
  663. }
  664. return key;
  665. }
  666. /// <summary>
  667. /// A helper to get only the <see cref="ConsoleKeyInfo.KeyChar"/> from the <see cref="ConsoleKeyInfo"/> array.
  668. /// </summary>
  669. /// <param name="cki"></param>
  670. /// <returns>The char array of the escape sequence.</returns>
  671. public static char [] GetKeyCharArray (ConsoleKeyInfo [] cki)
  672. {
  673. char [] kChar = new char [] { };
  674. var length = 0;
  675. foreach (var kc in cki) {
  676. length++;
  677. Array.Resize (ref kChar, length);
  678. kChar [length - 1] = kc.KeyChar;
  679. }
  680. return kChar;
  681. }
  682. private static MouseFlags? lastMouseButtonPressed;
  683. //private static MouseFlags? lastMouseButtonReleased;
  684. private static bool isButtonPressed;
  685. //private static bool isButtonReleased;
  686. private static bool isButtonClicked;
  687. private static bool isButtonDoubleClicked;
  688. private static bool isButtonTripleClicked;
  689. private static Point point;
  690. /// <summary>
  691. /// Gets the <see cref="MouseFlags"/> mouse button flags and the position.
  692. /// </summary>
  693. /// <param name="cki">The <see cref="ConsoleKeyInfo"/> array.</param>
  694. /// <param name="mouseFlags">The mouse button flags.</param>
  695. /// <param name="pos">The mouse position.</param>
  696. /// <param name="continuousButtonPressedHandler">The handler that will process the event.</param>
  697. public static void GetMouse (ConsoleKeyInfo [] cki, out List<MouseFlags> mouseFlags, out Point pos, Action<MouseFlags, Point> continuousButtonPressedHandler)
  698. {
  699. MouseFlags buttonState = 0;
  700. pos = new Point ();
  701. int buttonCode = 0;
  702. bool foundButtonCode = false;
  703. int foundPoint = 0;
  704. string value = "";
  705. var kChar = GetKeyCharArray (cki);
  706. //System.Diagnostics.Debug.WriteLine ($"kChar: {new string (kChar)}");
  707. for (int i = 0; i < kChar.Length; i++) {
  708. var c = kChar [i];
  709. if (c == '<') {
  710. foundButtonCode = true;
  711. } else if (foundButtonCode && c != ';') {
  712. value += c.ToString ();
  713. } else if (c == ';') {
  714. if (foundButtonCode) {
  715. foundButtonCode = false;
  716. buttonCode = int.Parse (value);
  717. }
  718. if (foundPoint == 1) {
  719. pos.X = int.Parse (value) - 1;
  720. }
  721. value = "";
  722. foundPoint++;
  723. } else if (foundPoint > 0 && c != 'm' && c != 'M') {
  724. value += c.ToString ();
  725. } else if (c == 'm' || c == 'M') {
  726. //pos.Y = int.Parse (value) + Console.WindowTop - 1;
  727. pos.Y = int.Parse (value) - 1;
  728. switch (buttonCode) {
  729. case 0:
  730. case 8:
  731. case 16:
  732. case 24:
  733. case 32:
  734. case 36:
  735. case 40:
  736. case 48:
  737. case 56:
  738. buttonState = c == 'M' ? MouseFlags.Button1Pressed
  739. : MouseFlags.Button1Released;
  740. break;
  741. case 1:
  742. case 9:
  743. case 17:
  744. case 25:
  745. case 33:
  746. case 37:
  747. case 41:
  748. case 45:
  749. case 49:
  750. case 53:
  751. case 57:
  752. case 61:
  753. buttonState = c == 'M' ? MouseFlags.Button2Pressed
  754. : MouseFlags.Button2Released;
  755. break;
  756. case 2:
  757. case 10:
  758. case 14:
  759. case 18:
  760. case 22:
  761. case 26:
  762. case 30:
  763. case 34:
  764. case 42:
  765. case 46:
  766. case 50:
  767. case 54:
  768. case 58:
  769. case 62:
  770. buttonState = c == 'M' ? MouseFlags.Button3Pressed
  771. : MouseFlags.Button3Released;
  772. break;
  773. case 35:
  774. //// Needed for Windows OS
  775. //if (isButtonPressed && c == 'm'
  776. // && (lastMouseEvent.ButtonState == MouseFlags.Button1Pressed
  777. // || lastMouseEvent.ButtonState == MouseFlags.Button2Pressed
  778. // || lastMouseEvent.ButtonState == MouseFlags.Button3Pressed)) {
  779. // switch (lastMouseEvent.ButtonState) {
  780. // case MouseFlags.Button1Pressed:
  781. // buttonState = MouseFlags.Button1Released;
  782. // break;
  783. // case MouseFlags.Button2Pressed:
  784. // buttonState = MouseFlags.Button2Released;
  785. // break;
  786. // case MouseFlags.Button3Pressed:
  787. // buttonState = MouseFlags.Button3Released;
  788. // break;
  789. // }
  790. //} else {
  791. // buttonState = MouseFlags.ReportMousePosition;
  792. //}
  793. //break;
  794. case 39:
  795. case 43:
  796. case 47:
  797. case 51:
  798. case 55:
  799. case 59:
  800. case 63:
  801. buttonState = MouseFlags.ReportMousePosition;
  802. break;
  803. case 64:
  804. buttonState = MouseFlags.WheeledUp;
  805. break;
  806. case 65:
  807. buttonState = MouseFlags.WheeledDown;
  808. break;
  809. case 68:
  810. case 72:
  811. case 80:
  812. buttonState = MouseFlags.WheeledLeft; // Shift/Ctrl+WheeledUp
  813. break;
  814. case 69:
  815. case 73:
  816. case 81:
  817. buttonState = MouseFlags.WheeledRight; // Shift/Ctrl+WheeledDown
  818. break;
  819. }
  820. // Modifiers.
  821. switch (buttonCode) {
  822. case 8:
  823. case 9:
  824. case 10:
  825. case 43:
  826. buttonState |= MouseFlags.ButtonAlt;
  827. break;
  828. case 14:
  829. case 47:
  830. buttonState |= MouseFlags.ButtonAlt | MouseFlags.ButtonShift;
  831. break;
  832. case 16:
  833. case 17:
  834. case 18:
  835. case 51:
  836. buttonState |= MouseFlags.ButtonCtrl;
  837. break;
  838. case 22:
  839. case 55:
  840. buttonState |= MouseFlags.ButtonCtrl | MouseFlags.ButtonShift;
  841. break;
  842. case 24:
  843. case 25:
  844. case 26:
  845. case 59:
  846. buttonState |= MouseFlags.ButtonCtrl | MouseFlags.ButtonAlt;
  847. break;
  848. case 30:
  849. case 63:
  850. buttonState |= MouseFlags.ButtonCtrl | MouseFlags.ButtonShift | MouseFlags.ButtonAlt;
  851. break;
  852. case 32:
  853. case 33:
  854. case 34:
  855. buttonState |= MouseFlags.ReportMousePosition;
  856. break;
  857. case 36:
  858. case 37:
  859. buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonShift;
  860. break;
  861. case 39:
  862. case 68:
  863. case 69:
  864. buttonState |= MouseFlags.ButtonShift;
  865. break;
  866. case 40:
  867. case 41:
  868. case 42:
  869. buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonAlt;
  870. break;
  871. case 45:
  872. case 46:
  873. buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonAlt | MouseFlags.ButtonShift;
  874. break;
  875. case 48:
  876. case 49:
  877. case 50:
  878. buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonCtrl;
  879. break;
  880. case 53:
  881. case 54:
  882. buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonCtrl | MouseFlags.ButtonShift;
  883. break;
  884. case 56:
  885. case 57:
  886. case 58:
  887. buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonCtrl | MouseFlags.ButtonAlt;
  888. break;
  889. case 61:
  890. case 62:
  891. buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonCtrl | MouseFlags.ButtonShift | MouseFlags.ButtonAlt;
  892. break;
  893. }
  894. }
  895. }
  896. mouseFlags = new List<MouseFlags> () { MouseFlags.AllEvents };
  897. if (lastMouseButtonPressed != null && !isButtonPressed && !buttonState.HasFlag (MouseFlags.ReportMousePosition)
  898. && !buttonState.HasFlag (MouseFlags.Button1Released)
  899. && !buttonState.HasFlag (MouseFlags.Button2Released)
  900. && !buttonState.HasFlag (MouseFlags.Button3Released)
  901. && !buttonState.HasFlag (MouseFlags.Button4Released)) {
  902. lastMouseButtonPressed = null;
  903. isButtonPressed = false;
  904. }
  905. if (!isButtonClicked && !isButtonDoubleClicked && ((buttonState == MouseFlags.Button1Pressed || buttonState == MouseFlags.Button2Pressed ||
  906. buttonState == MouseFlags.Button3Pressed || buttonState == MouseFlags.Button4Pressed) && lastMouseButtonPressed == null) ||
  907. isButtonPressed && lastMouseButtonPressed != null && buttonState.HasFlag (MouseFlags.ReportMousePosition)) {
  908. mouseFlags [0] = buttonState;
  909. lastMouseButtonPressed = buttonState;
  910. isButtonPressed = true;
  911. if ((mouseFlags [0] & MouseFlags.ReportMousePosition) == 0) {
  912. point = new Point () {
  913. X = pos.X,
  914. Y = pos.Y
  915. };
  916. Application.MainLoop.AddIdle (() => {
  917. Task.Run (async () => await ProcessContinuousButtonPressedAsync (buttonState, continuousButtonPressedHandler));
  918. return false;
  919. });
  920. } else if (mouseFlags [0] == MouseFlags.ReportMousePosition) {
  921. isButtonPressed = false;
  922. }
  923. } else if (isButtonDoubleClicked && (buttonState == MouseFlags.Button1Pressed || buttonState == MouseFlags.Button2Pressed ||
  924. buttonState == MouseFlags.Button3Pressed || buttonState == MouseFlags.Button4Pressed)) {
  925. mouseFlags [0] = GetButtonTripleClicked (buttonState);
  926. isButtonDoubleClicked = false;
  927. isButtonTripleClicked = true;
  928. } else if (isButtonClicked && (buttonState == MouseFlags.Button1Pressed || buttonState == MouseFlags.Button2Pressed ||
  929. buttonState == MouseFlags.Button3Pressed || buttonState == MouseFlags.Button4Pressed)) {
  930. mouseFlags [0] = GetButtonDoubleClicked (buttonState);
  931. isButtonClicked = false;
  932. isButtonDoubleClicked = true;
  933. Application.MainLoop.AddIdle (() => {
  934. Task.Run (async () => await ProcessButtonDoubleClickedAsync ());
  935. return false;
  936. });
  937. }
  938. //else if (isButtonReleased && !isButtonClicked && buttonState == MouseFlags.ReportMousePosition) {
  939. // mouseFlag [0] = GetButtonClicked ((MouseFlags)lastMouseButtonReleased);
  940. // lastMouseButtonReleased = null;
  941. // isButtonReleased = false;
  942. // isButtonClicked = true;
  943. // Application.MainLoop.AddIdle (() => {
  944. // Task.Run (async () => await ProcessButtonClickedAsync ());
  945. // return false;
  946. // });
  947. //}
  948. else if (!isButtonClicked && !isButtonDoubleClicked && (buttonState == MouseFlags.Button1Released || buttonState == MouseFlags.Button2Released ||
  949. buttonState == MouseFlags.Button3Released || buttonState == MouseFlags.Button4Released)) {
  950. mouseFlags [0] = buttonState;
  951. isButtonPressed = false;
  952. if (isButtonTripleClicked) {
  953. isButtonTripleClicked = false;
  954. } else if (pos.X == point.X && pos.Y == point.Y) {
  955. mouseFlags.Add (GetButtonClicked (buttonState));
  956. isButtonClicked = true;
  957. Application.MainLoop.AddIdle (() => {
  958. Task.Run (async () => await ProcessButtonClickedAsync ());
  959. return false;
  960. });
  961. }
  962. point = pos;
  963. //if ((lastMouseButtonPressed & MouseFlags.ReportMousePosition) == 0) {
  964. // lastMouseButtonReleased = buttonState;
  965. // isButtonPressed = false;
  966. // isButtonReleased = true;
  967. //} else {
  968. // lastMouseButtonPressed = null;
  969. // isButtonPressed = false;
  970. //}
  971. } else if (buttonState == MouseFlags.WheeledUp) {
  972. mouseFlags [0] = MouseFlags.WheeledUp;
  973. } else if (buttonState == MouseFlags.WheeledDown) {
  974. mouseFlags [0] = MouseFlags.WheeledDown;
  975. } else if (buttonState == MouseFlags.WheeledLeft) {
  976. mouseFlags [0] = MouseFlags.WheeledLeft;
  977. } else if (buttonState == MouseFlags.WheeledRight) {
  978. mouseFlags [0] = MouseFlags.WheeledRight;
  979. } else if (buttonState == MouseFlags.ReportMousePosition) {
  980. mouseFlags [0] = MouseFlags.ReportMousePosition;
  981. } else {
  982. mouseFlags [0] = buttonState;
  983. //foreach (var flag in buttonState.GetUniqueFlags()) {
  984. // mouseFlag [0] |= flag;
  985. //}
  986. }
  987. mouseFlags [0] = SetControlKeyStates (buttonState, mouseFlags [0]);
  988. //buttonState = mouseFlags;
  989. //System.Diagnostics.Debug.WriteLine ($"buttonState: {buttonState} X: {pos.X} Y: {pos.Y}");
  990. //foreach (var mf in mouseFlags) {
  991. // System.Diagnostics.Debug.WriteLine ($"mouseFlags: {mf} X: {pos.X} Y: {pos.Y}");
  992. //}
  993. }
  994. private static async Task ProcessContinuousButtonPressedAsync (MouseFlags mouseFlag, Action<MouseFlags, Point> continuousButtonPressedHandler)
  995. {
  996. while (isButtonPressed) {
  997. await Task.Delay (100);
  998. //var me = new MouseEvent () {
  999. // X = point.X,
  1000. // Y = point.Y,
  1001. // Flags = mouseFlag
  1002. //};
  1003. var view = Application.WantContinuousButtonPressedView;
  1004. if (view == null)
  1005. break;
  1006. if (isButtonPressed && lastMouseButtonPressed != null && (mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  1007. Application.Invoke (() => continuousButtonPressedHandler (mouseFlag, point));
  1008. }
  1009. }
  1010. }
  1011. private static async Task ProcessButtonClickedAsync ()
  1012. {
  1013. await Task.Delay (300);
  1014. isButtonClicked = false;
  1015. }
  1016. private static async Task ProcessButtonDoubleClickedAsync ()
  1017. {
  1018. await Task.Delay (300);
  1019. isButtonDoubleClicked = false;
  1020. }
  1021. private static MouseFlags GetButtonClicked (MouseFlags mouseFlag)
  1022. {
  1023. MouseFlags mf = default;
  1024. switch (mouseFlag) {
  1025. case MouseFlags.Button1Released:
  1026. mf = MouseFlags.Button1Clicked;
  1027. break;
  1028. case MouseFlags.Button2Released:
  1029. mf = MouseFlags.Button2Clicked;
  1030. break;
  1031. case MouseFlags.Button3Released:
  1032. mf = MouseFlags.Button3Clicked;
  1033. break;
  1034. }
  1035. return mf;
  1036. }
  1037. private static MouseFlags GetButtonDoubleClicked (MouseFlags mouseFlag)
  1038. {
  1039. MouseFlags mf = default;
  1040. switch (mouseFlag) {
  1041. case MouseFlags.Button1Pressed:
  1042. mf = MouseFlags.Button1DoubleClicked;
  1043. break;
  1044. case MouseFlags.Button2Pressed:
  1045. mf = MouseFlags.Button2DoubleClicked;
  1046. break;
  1047. case MouseFlags.Button3Pressed:
  1048. mf = MouseFlags.Button3DoubleClicked;
  1049. break;
  1050. }
  1051. return mf;
  1052. }
  1053. private static MouseFlags GetButtonTripleClicked (MouseFlags mouseFlag)
  1054. {
  1055. MouseFlags mf = default;
  1056. switch (mouseFlag) {
  1057. case MouseFlags.Button1Pressed:
  1058. mf = MouseFlags.Button1TripleClicked;
  1059. break;
  1060. case MouseFlags.Button2Pressed:
  1061. mf = MouseFlags.Button2TripleClicked;
  1062. break;
  1063. case MouseFlags.Button3Pressed:
  1064. mf = MouseFlags.Button3TripleClicked;
  1065. break;
  1066. }
  1067. return mf;
  1068. }
  1069. private static MouseFlags SetControlKeyStates (MouseFlags buttonState, MouseFlags mouseFlag)
  1070. {
  1071. if ((buttonState & MouseFlags.ButtonCtrl) != 0 && (mouseFlag & MouseFlags.ButtonCtrl) == 0)
  1072. mouseFlag |= MouseFlags.ButtonCtrl;
  1073. if ((buttonState & MouseFlags.ButtonShift) != 0 && (mouseFlag & MouseFlags.ButtonShift) == 0)
  1074. mouseFlag |= MouseFlags.ButtonShift;
  1075. if ((buttonState & MouseFlags.ButtonAlt) != 0 && (mouseFlag & MouseFlags.ButtonAlt) == 0)
  1076. mouseFlag |= MouseFlags.ButtonAlt;
  1077. return mouseFlag;
  1078. }
  1079. // TODO: Move this out of here and into ConsoleDriver or somewhere else.
  1080. /// <summary>
  1081. /// Get the terminal that holds the console driver.
  1082. /// </summary>
  1083. /// <param name="process">The process.</param>
  1084. /// <returns>If supported the executable console process, null otherwise.</returns>
  1085. public static Process GetParentProcess (Process process)
  1086. {
  1087. if (!RuntimeInformation.IsOSPlatform (OSPlatform.Windows)) {
  1088. return null;
  1089. }
  1090. string query = "SELECT ParentProcessId FROM Win32_Process WHERE ProcessId = " + process.Id;
  1091. using (ManagementObjectSearcher mos = new ManagementObjectSearcher (query)) {
  1092. foreach (ManagementObject mo in mos.Get ()) {
  1093. if (mo ["ParentProcessId"] != null) {
  1094. try {
  1095. var id = Convert.ToInt32 (mo ["ParentProcessId"]);
  1096. return Process.GetProcessById (id);
  1097. } catch {
  1098. }
  1099. }
  1100. }
  1101. }
  1102. return null;
  1103. }
  1104. }