EscSeqUtils.cs 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712
  1. #nullable enable
  2. using Terminal.Gui.ConsoleDrivers;
  3. namespace Terminal.Gui;
  4. /// <summary>
  5. /// Provides a platform-independent API for managing ANSI escape sequences.
  6. /// </summary>
  7. /// <remarks>
  8. /// Useful resources:
  9. /// * https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences
  10. /// * https://invisible-island.net/xterm/ctlseqs/ctlseqs.html
  11. /// * https://vt100.net/
  12. /// </remarks>
  13. public static class EscSeqUtils
  14. {
  15. /// <summary>
  16. /// Options for ANSI ESC "[xJ" - Clears part of the screen.
  17. /// </summary>
  18. public enum ClearScreenOptions
  19. {
  20. /// <summary>
  21. /// If n is 0 (or missing), clear from cursor to end of screen.
  22. /// </summary>
  23. CursorToEndOfScreen = 0,
  24. /// <summary>
  25. /// If n is 1, clear from cursor to beginning of the screen.
  26. /// </summary>
  27. CursorToBeginningOfScreen = 1,
  28. /// <summary>
  29. /// If n is 2, clear entire screen (and moves cursor to upper left on DOS ANSI.SYS).
  30. /// </summary>
  31. EntireScreen = 2,
  32. /// <summary>
  33. /// If n is 3, clear entire screen and delete all lines saved in the scrollback buffer
  34. /// </summary>
  35. EntireScreenAndScrollbackBuffer = 3
  36. }
  37. /// <summary>
  38. /// Escape key code (ASCII 27/0x1B).
  39. /// </summary>
  40. public const char KeyEsc = (char)KeyCode.Esc;
  41. /// <summary>
  42. /// ESC [ - The CSI (Control Sequence Introducer).
  43. /// </summary>
  44. public const string CSI = "\u001B[";
  45. /// <summary>
  46. /// ESC [ ? 1047 h - Activate xterm alternative buffer (no backscroll)
  47. /// </summary>
  48. /// <remarks>
  49. /// From
  50. /// https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Functions-using-CSI-_-ordered-by-the-final-character_s_
  51. /// Use Alternate Screen Buffer, xterm.
  52. /// </remarks>
  53. public static readonly string CSI_ActivateAltBufferNoBackscroll = CSI + "?1047h";
  54. /// <summary>
  55. /// ESC [ ? 1003 l - Disable any mouse event tracking.
  56. /// </summary>
  57. public static readonly string CSI_DisableAnyEventMouse = CSI + "?1003l";
  58. /// <summary>
  59. /// ESC [ ? 1006 l - Disable SGR (Select Graphic Rendition).
  60. /// </summary>
  61. public static readonly string CSI_DisableSgrExtModeMouse = CSI + "?1006l";
  62. /// <summary>
  63. /// ESC [ ? 1015 l - Disable URXVT (Unicode Extended Virtual Terminal).
  64. /// </summary>
  65. public static readonly string CSI_DisableUrxvtExtModeMouse = CSI + "?1015l";
  66. /// <summary>
  67. /// ESC [ ? 1003 h - Enable mouse event tracking.
  68. /// </summary>
  69. public static readonly string CSI_EnableAnyEventMouse = CSI + "?1003h";
  70. /// <summary>
  71. /// ESC [ ? 1006 h - Enable SGR (Select Graphic Rendition).
  72. /// </summary>
  73. public static readonly string CSI_EnableSgrExtModeMouse = CSI + "?1006h";
  74. /// <summary>
  75. /// ESC [ ? 1015 h - Enable URXVT (Unicode Extended Virtual Terminal).
  76. /// </summary>
  77. public static readonly string CSI_EnableUrxvtExtModeMouse = CSI + "?1015h";
  78. /// <summary>
  79. /// ESC [ ? 1047 l - Restore xterm working buffer (with backscroll)
  80. /// </summary>
  81. /// <remarks>
  82. /// From
  83. /// https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Functions-using-CSI-_-ordered-by-the-final-character_s_
  84. /// Use Normal Screen Buffer, xterm. Clear the screen first if in the Alternate Screen Buffer.
  85. /// </remarks>
  86. public static readonly string CSI_RestoreAltBufferWithBackscroll = CSI + "?1047l";
  87. /// <summary>
  88. /// ESC [ ? 1049 l - Restore cursor position and restore xterm working buffer (with backscroll)
  89. /// </summary>
  90. /// <remarks>
  91. /// From
  92. /// https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Functions-using-CSI-_-ordered-by-the-final-character_s_
  93. /// Use Normal Screen Buffer and restore cursor as in DECRC, xterm.
  94. /// resource.This combines the effects of the 1047 and 1048 modes.
  95. /// </remarks>
  96. public static readonly string CSI_RestoreCursorAndRestoreAltBufferWithBackscroll = CSI + "?1049l";
  97. /// <summary>
  98. /// ESC [ ? 1049 h - Save cursor position and activate xterm alternative buffer (no backscroll)
  99. /// </summary>
  100. /// <remarks>
  101. /// From
  102. /// https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Functions-using-CSI-_-ordered-by-the-final-character_s_
  103. /// Save cursor as in DECSC, xterm. After saving the cursor, switch to the Alternate Screen Buffer,
  104. /// clearing it first.
  105. /// This control combines the effects of the 1047 and 1048 modes.
  106. /// Use this with terminfo-based applications rather than the 47 mode.
  107. /// </remarks>
  108. public static readonly string CSI_SaveCursorAndActivateAltBufferNoBackscroll = CSI + "?1049h";
  109. //private static bool isButtonReleased;
  110. private static bool _isButtonClicked;
  111. private static bool _isButtonDoubleClicked;
  112. //private static MouseFlags? lastMouseButtonReleased;
  113. // QUESTION: What's the difference between isButtonClicked and isButtonPressed?
  114. // Some clarity or comments would be handy, here.
  115. // It also seems like some enforcement of valid states might be a good idea.
  116. private static bool _isButtonPressed;
  117. private static bool _isButtonTripleClicked;
  118. private static MouseFlags? _lastMouseButtonPressed;
  119. private static Point? _point;
  120. /// <summary>
  121. /// Control sequence for disabling mouse events.
  122. /// </summary>
  123. public static string CSI_DisableMouseEvents { get; set; } =
  124. CSI_DisableAnyEventMouse + CSI_DisableUrxvtExtModeMouse + CSI_DisableSgrExtModeMouse;
  125. /// <summary>
  126. /// Control sequence for enabling mouse events.
  127. /// </summary>
  128. public static string CSI_EnableMouseEvents { get; set; } =
  129. CSI_EnableAnyEventMouse + CSI_EnableUrxvtExtModeMouse + CSI_EnableSgrExtModeMouse;
  130. /// <summary>
  131. /// ESC [ x J - Clears part of the screen. See <see cref="ClearScreenOptions"/>.
  132. /// </summary>
  133. /// <param name="option"></param>
  134. /// <returns></returns>
  135. public static string CSI_ClearScreen (ClearScreenOptions option) { return $"{CSI}{(int)option}J"; }
  136. /// <summary>
  137. /// Specify the incomplete <see cref="ConsoleKeyInfo"/> array not yet recognized as valid ANSI escape sequence.
  138. /// </summary>
  139. public static ConsoleKeyInfo []? IncompleteCkInfos { get; set; }
  140. /// <summary>
  141. /// Decodes an ANSI escape sequence.
  142. /// </summary>
  143. /// <param name="escSeqRequests">The <see cref="EscSeqRequests"/> which may contain a request.</param>
  144. /// <param name="newConsoleKeyInfo">The <see cref="ConsoleKeyInfo"/> which may change.</param>
  145. /// <param name="key">The <see cref="ConsoleKey"/> which may change.</param>
  146. /// <param name="cki">The <see cref="ConsoleKeyInfo"/> array.</param>
  147. /// <param name="mod">The <see cref="ConsoleModifiers"/> which may change.</param>
  148. /// <param name="c1Control">The control returned by the <see cref="GetC1ControlChar"/> method.</param>
  149. /// <param name="code">The code returned by the <see cref="GetEscapeResult(char[])"/> method.</param>
  150. /// <param name="values">The values returned by the <see cref="GetEscapeResult(char[])"/> method.</param>
  151. /// <param name="terminator">The terminator returned by the <see cref="GetEscapeResult(char[])"/> method.</param>
  152. /// <param name="isMouse">Indicates if the escape sequence is a mouse event.</param>
  153. /// <param name="buttonState">The <see cref="MouseFlags"/> button state.</param>
  154. /// <param name="pos">The <see cref="MouseFlags"/> position.</param>
  155. /// <param name="seqReqStatus">The <see cref="EscSeqReqStatus"/> object.</param>
  156. /// <param name="continuousButtonPressedHandler">The handler that will process the event.</param>
  157. public static void DecodeEscSeq (
  158. EscSeqRequests? escSeqRequests,
  159. ref ConsoleKeyInfo newConsoleKeyInfo,
  160. ref ConsoleKey key,
  161. ConsoleKeyInfo [] cki,
  162. ref ConsoleModifiers mod,
  163. out string c1Control,
  164. out string code,
  165. out string [] values,
  166. out string terminator,
  167. out bool isMouse,
  168. out List<MouseFlags> buttonState,
  169. out Point pos,
  170. out EscSeqReqStatus? seqReqStatus,
  171. Action<MouseFlags, Point> continuousButtonPressedHandler
  172. )
  173. {
  174. char [] kChars = GetKeyCharArray (cki);
  175. (c1Control, code, values, terminator) = GetEscapeResult (kChars);
  176. isMouse = false;
  177. buttonState = [0];
  178. pos = default (Point);
  179. seqReqStatus = null;
  180. var keyChar = '\0';
  181. switch (c1Control)
  182. {
  183. case "ESC":
  184. if (values is null && string.IsNullOrEmpty (terminator))
  185. {
  186. key = ConsoleKey.Escape;
  187. newConsoleKeyInfo = new (
  188. cki [0].KeyChar,
  189. key,
  190. (mod & ConsoleModifiers.Shift) != 0,
  191. (mod & ConsoleModifiers.Alt) != 0,
  192. (mod & ConsoleModifiers.Control) != 0);
  193. }
  194. else if ((uint)cki [1].KeyChar >= 1 && (uint)cki [1].KeyChar <= 26 && (uint)cki [1].KeyChar != '\n' && (uint)cki [1].KeyChar != '\r')
  195. {
  196. key = (ConsoleKey)(char)(cki [1].KeyChar + (uint)ConsoleKey.A - 1);
  197. mod = ConsoleModifiers.Alt | ConsoleModifiers.Control;
  198. newConsoleKeyInfo = new (
  199. cki [1].KeyChar,
  200. key,
  201. (mod & ConsoleModifiers.Shift) != 0,
  202. (mod & ConsoleModifiers.Alt) != 0,
  203. (mod & ConsoleModifiers.Control) != 0);
  204. }
  205. else if (cki [1].KeyChar >= 65 && cki [1].KeyChar <= 90)
  206. {
  207. key = (ConsoleKey)cki [1].KeyChar;
  208. mod = ConsoleModifiers.Shift | ConsoleModifiers.Alt;
  209. newConsoleKeyInfo = new (
  210. cki [1].KeyChar,
  211. (ConsoleKey)Math.Min ((uint)key, 255),
  212. (mod & ConsoleModifiers.Shift) != 0,
  213. (mod & ConsoleModifiers.Alt) != 0,
  214. (mod & ConsoleModifiers.Control) != 0);
  215. }
  216. else if (cki [1].KeyChar >= 97 && cki [1].KeyChar <= 122)
  217. {
  218. key = (ConsoleKey)cki [1].KeyChar.ToString ().ToUpper () [0];
  219. mod = ConsoleModifiers.Alt;
  220. newConsoleKeyInfo = new (
  221. cki [1].KeyChar,
  222. (ConsoleKey)Math.Min ((uint)key, 255),
  223. (mod & ConsoleModifiers.Shift) != 0,
  224. (mod & ConsoleModifiers.Alt) != 0,
  225. (mod & ConsoleModifiers.Control) != 0);
  226. }
  227. else if (cki [1].KeyChar is '\0' or ' ')
  228. {
  229. key = ConsoleKey.Spacebar;
  230. if (kChars.Length > 1 && kChars [1] == '\0')
  231. {
  232. mod = ConsoleModifiers.Alt | ConsoleModifiers.Control;
  233. }
  234. else
  235. {
  236. mod = ConsoleModifiers.Shift | ConsoleModifiers.Alt;
  237. }
  238. newConsoleKeyInfo = new (
  239. cki [1].KeyChar,
  240. (ConsoleKey)Math.Min ((uint)key, 255),
  241. (mod & ConsoleModifiers.Shift) != 0,
  242. (mod & ConsoleModifiers.Alt) != 0,
  243. (mod & ConsoleModifiers.Control) != 0);
  244. }
  245. else if (cki [1].KeyChar is '\n' or '\r')
  246. {
  247. key = ConsoleKey.Enter;
  248. if (kChars.Length > 1 && kChars [1] == '\n')
  249. {
  250. mod = ConsoleModifiers.Alt | ConsoleModifiers.Control;
  251. }
  252. else
  253. {
  254. mod = ConsoleModifiers.Shift | ConsoleModifiers.Alt;
  255. }
  256. newConsoleKeyInfo = new (
  257. cki [1].KeyChar,
  258. (ConsoleKey)Math.Min ((uint)key, 255),
  259. (mod & ConsoleModifiers.Shift) != 0,
  260. (mod & ConsoleModifiers.Alt) != 0,
  261. (mod & ConsoleModifiers.Control) != 0);
  262. }
  263. else
  264. {
  265. key = (ConsoleKey)cki [1].KeyChar;
  266. mod = ConsoleModifiers.Alt;
  267. newConsoleKeyInfo = new (
  268. cki [1].KeyChar,
  269. (ConsoleKey)Math.Min ((uint)key, 255),
  270. (mod & ConsoleModifiers.Shift) != 0,
  271. (mod & ConsoleModifiers.Alt) != 0,
  272. (mod & ConsoleModifiers.Control) != 0);
  273. }
  274. break;
  275. case "SS3":
  276. key = GetConsoleKey (terminator [0], values [0], ref mod, ref keyChar);
  277. newConsoleKeyInfo = new (
  278. keyChar,
  279. key,
  280. (mod & ConsoleModifiers.Shift) != 0,
  281. (mod & ConsoleModifiers.Alt) != 0,
  282. (mod & ConsoleModifiers.Control) != 0);
  283. break;
  284. case "CSI":
  285. if (!string.IsNullOrEmpty (code) && code == "<")
  286. {
  287. GetMouse (cki, out buttonState, out pos, continuousButtonPressedHandler);
  288. isMouse = true;
  289. return;
  290. }
  291. if (escSeqRequests is { } && escSeqRequests.HasResponse (terminator, out seqReqStatus))
  292. {
  293. escSeqRequests.Remove (seqReqStatus);
  294. return;
  295. }
  296. if (!string.IsNullOrEmpty (terminator))
  297. {
  298. System.Diagnostics.Debug.Assert (terminator.Length == 1);
  299. key = GetConsoleKey (terminator [0], values [0], ref mod, ref keyChar);
  300. if (key != 0 && values.Length > 1)
  301. {
  302. mod |= GetConsoleModifiers (values [1]);
  303. }
  304. newConsoleKeyInfo = new (
  305. keyChar,
  306. key,
  307. (mod & ConsoleModifiers.Shift) != 0,
  308. (mod & ConsoleModifiers.Alt) != 0,
  309. (mod & ConsoleModifiers.Control) != 0);
  310. }
  311. else
  312. {
  313. // BUGBUG: See https://github.com/gui-cs/Terminal.Gui/issues/2803
  314. // This is caused by NetDriver depending on Console.KeyAvailable?
  315. //throw new InvalidOperationException ("CSI response, but there's no terminator");
  316. IncompleteCkInfos = cki;
  317. }
  318. break;
  319. default:
  320. newConsoleKeyInfo = MapConsoleKeyInfo (cki [0]);
  321. key = newConsoleKeyInfo.Key;
  322. mod = newConsoleKeyInfo.Modifiers;
  323. break;
  324. }
  325. }
  326. /// <summary>
  327. /// Gets the c1Control used in the called escape sequence.
  328. /// </summary>
  329. /// <param name="c">The char used.</param>
  330. /// <returns>The c1Control.</returns>
  331. [Pure]
  332. public static string GetC1ControlChar (in char c)
  333. {
  334. // These control characters are used in the vtXXX emulation.
  335. return c switch
  336. {
  337. 'D' => "IND", // Index
  338. 'E' => "NEL", // Next Line
  339. 'H' => "HTS", // Tab Set
  340. 'M' => "RI", // Reverse Index
  341. 'N' => "SS2", // Single Shift Select of G2 Character Set: affects next character only
  342. 'O' => "SS3", // Single Shift Select of G3 Character Set: affects next character only
  343. 'P' => "DCS", // Device Control String
  344. 'V' => "SPA", // Start of Guarded Area
  345. 'W' => "EPA", // End of Guarded Area
  346. 'X' => "SOS", // Start of String
  347. 'Z' => "DECID", // Return Terminal ID Obsolete form of CSI c (DA)
  348. '[' => "CSI", // Control Sequence Introducer
  349. '\\' => "ST", // String Terminator
  350. ']' => "OSC", // Operating System Command
  351. '^' => "PM", // Privacy Message
  352. '_' => "APC", // Application Program Command
  353. _ => string.Empty
  354. };
  355. }
  356. /// <summary>
  357. /// Gets the <see cref="ConsoleKey"/> depending on terminating and value.
  358. /// </summary>
  359. /// <param name="terminator">
  360. /// The terminator indicating a reply to <see cref="CSI_SendDeviceAttributes"/> or
  361. /// <see cref="CSI_SendDeviceAttributes2"/>.
  362. /// </param>
  363. /// <param name="value">The value.</param>
  364. /// <param name="mod">The <see cref="ConsoleModifiers"/> which may change.</param>
  365. /// <param name="keyChar">Normally is '\0' but on some cases may need other value.</param>
  366. /// <returns>The <see cref="ConsoleKey"/> and probably the <see cref="ConsoleModifiers"/>.</returns>
  367. public static ConsoleKey GetConsoleKey (char terminator, string? value, ref ConsoleModifiers mod, ref char keyChar)
  368. {
  369. if (terminator == 'Z')
  370. {
  371. mod |= ConsoleModifiers.Shift;
  372. }
  373. if (terminator == 'l')
  374. {
  375. keyChar = '+';
  376. }
  377. if (terminator == 'm')
  378. {
  379. keyChar = '-';
  380. }
  381. return (terminator, value) switch
  382. {
  383. ('A', _) => ConsoleKey.UpArrow,
  384. ('B', _) => ConsoleKey.DownArrow,
  385. ('C', _) => ConsoleKey.RightArrow,
  386. ('D', _) => ConsoleKey.LeftArrow,
  387. ('E', _) => ConsoleKey.Clear,
  388. ('F', _) => ConsoleKey.End,
  389. ('H', _) => ConsoleKey.Home,
  390. ('P', _) => ConsoleKey.F1,
  391. ('Q', _) => ConsoleKey.F2,
  392. ('R', _) => ConsoleKey.F3,
  393. ('S', _) => ConsoleKey.F4,
  394. ('Z', _) => ConsoleKey.Tab,
  395. ('~', "2") => ConsoleKey.Insert,
  396. ('~', "3") => ConsoleKey.Delete,
  397. ('~', "5") => ConsoleKey.PageUp,
  398. ('~', "6") => ConsoleKey.PageDown,
  399. ('~', "15") => ConsoleKey.F5,
  400. ('~', "17") => ConsoleKey.F6,
  401. ('~', "18") => ConsoleKey.F7,
  402. ('~', "19") => ConsoleKey.F8,
  403. ('~', "20") => ConsoleKey.F9,
  404. ('~', "21") => ConsoleKey.F10,
  405. ('~', "23") => ConsoleKey.F11,
  406. ('~', "24") => ConsoleKey.F12,
  407. // These terminators are used by macOS on a numeric keypad without keys modifiers
  408. ('l', null) => ConsoleKey.Add,
  409. ('m', null) => ConsoleKey.Subtract,
  410. ('p', null) => ConsoleKey.Insert,
  411. ('q', null) => ConsoleKey.End,
  412. ('r', null) => ConsoleKey.DownArrow,
  413. ('s', null) => ConsoleKey.PageDown,
  414. ('t', null) => ConsoleKey.LeftArrow,
  415. ('u', null) => ConsoleKey.Clear,
  416. ('v', null) => ConsoleKey.RightArrow,
  417. ('w', null) => ConsoleKey.Home,
  418. ('x', null) => ConsoleKey.UpArrow,
  419. ('y', null) => ConsoleKey.PageUp,
  420. (_, _) => 0
  421. };
  422. }
  423. /// <summary>
  424. /// Gets the <see cref="ConsoleModifiers"/> from the value.
  425. /// </summary>
  426. /// <param name="value">The value.</param>
  427. /// <returns>The <see cref="ConsoleModifiers"/> or zero.</returns>
  428. public static ConsoleModifiers GetConsoleModifiers (string? value)
  429. {
  430. return value switch
  431. {
  432. "2" => ConsoleModifiers.Shift,
  433. "3" => ConsoleModifiers.Alt,
  434. "4" => ConsoleModifiers.Shift | ConsoleModifiers.Alt,
  435. "5" => ConsoleModifiers.Control,
  436. "6" => ConsoleModifiers.Shift | ConsoleModifiers.Control,
  437. "7" => ConsoleModifiers.Alt | ConsoleModifiers.Control,
  438. "8" => ConsoleModifiers.Shift | ConsoleModifiers.Alt | ConsoleModifiers.Control,
  439. _ => 0
  440. };
  441. }
  442. #nullable restore
  443. /// <summary>
  444. /// Gets all the needed information about an escape sequence.
  445. /// </summary>
  446. /// <param name="kChar">The array with all chars.</param>
  447. /// <returns>
  448. /// The c1Control returned by <see cref="GetC1ControlChar"/>, code, values and terminating.
  449. /// </returns>
  450. public static (string c1Control, string code, string [] values, string terminating) GetEscapeResult (char [] kChar)
  451. {
  452. if (kChar is null || kChar.Length == 0 || (kChar.Length == 1 && kChar [0] != KeyEsc))
  453. {
  454. return (null, null, null, null);
  455. }
  456. if (kChar [0] != KeyEsc)
  457. {
  458. throw new InvalidOperationException ("Invalid escape character!");
  459. }
  460. if (kChar.Length == 1)
  461. {
  462. return ("ESC", null, null, null);
  463. }
  464. if (kChar.Length == 2)
  465. {
  466. return ("ESC", null, null, kChar [1].ToString ());
  467. }
  468. string c1Control = GetC1ControlChar (kChar [1]);
  469. string code = null;
  470. int nSep = kChar.Count (static x => x == ';') + 1;
  471. var values = new string [nSep];
  472. var valueIdx = 0;
  473. var terminating = string.Empty;
  474. for (var i = 2; i < kChar.Length; i++)
  475. {
  476. char c = kChar [i];
  477. if (char.IsDigit (c))
  478. {
  479. // PERF: Ouch
  480. values [valueIdx] += c.ToString ();
  481. }
  482. else if (c == ';')
  483. {
  484. valueIdx++;
  485. }
  486. else if (valueIdx == nSep - 1 || i == kChar.Length - 1)
  487. {
  488. // PERF: Ouch
  489. terminating += c.ToString ();
  490. }
  491. else
  492. {
  493. // PERF: Ouch
  494. code += c.ToString ();
  495. }
  496. }
  497. return (c1Control, code, values, terminating);
  498. }
  499. /// <summary>
  500. /// A helper to get only the <see cref="ConsoleKeyInfo.KeyChar"/> from the <see cref="ConsoleKeyInfo"/> array.
  501. /// </summary>
  502. /// <param name="cki"></param>
  503. /// <returns>The char array of the escape sequence.</returns>
  504. // PERF: This is expensive
  505. public static char [] GetKeyCharArray (ConsoleKeyInfo [] cki)
  506. {
  507. char [] kChar = [];
  508. var length = 0;
  509. foreach (ConsoleKeyInfo kc in cki)
  510. {
  511. length++;
  512. Array.Resize (ref kChar, length);
  513. kChar [length - 1] = kc.KeyChar;
  514. }
  515. return kChar;
  516. }
  517. /// <summary>
  518. /// Gets the <see cref="MouseFlags"/> mouse button flags and the position.
  519. /// </summary>
  520. /// <param name="cki">The <see cref="ConsoleKeyInfo"/> array.</param>
  521. /// <param name="mouseFlags">The mouse button flags.</param>
  522. /// <param name="pos">The mouse position.</param>
  523. /// <param name="continuousButtonPressedHandler">The handler that will process the event.</param>
  524. public static void GetMouse (
  525. ConsoleKeyInfo [] cki,
  526. out List<MouseFlags> mouseFlags,
  527. out Point pos,
  528. Action<MouseFlags, Point> continuousButtonPressedHandler
  529. )
  530. {
  531. MouseFlags buttonState = 0;
  532. pos = Point.Empty;
  533. var buttonCode = 0;
  534. var foundButtonCode = false;
  535. var foundPoint = 0;
  536. string value = string.Empty;
  537. char [] kChar = GetKeyCharArray (cki);
  538. // PERF: This loop could benefit from use of Spans and other strategies to avoid copies.
  539. //System.Diagnostics.Debug.WriteLine ($"kChar: {new string (kChar)}");
  540. for (var i = 0; i < kChar.Length; i++)
  541. {
  542. // PERF: Copy
  543. char c = kChar [i];
  544. if (c == '<')
  545. {
  546. foundButtonCode = true;
  547. }
  548. else if (foundButtonCode && c != ';')
  549. {
  550. // PERF: Ouch
  551. value += c.ToString ();
  552. }
  553. else if (c == ';')
  554. {
  555. if (foundButtonCode)
  556. {
  557. foundButtonCode = false;
  558. buttonCode = int.Parse (value);
  559. }
  560. if (foundPoint == 1)
  561. {
  562. pos.X = int.Parse (value) - 1;
  563. }
  564. value = string.Empty;
  565. foundPoint++;
  566. }
  567. else if (foundPoint > 0 && c != 'm' && c != 'M')
  568. {
  569. value += c.ToString ();
  570. }
  571. else if (c == 'm' || c == 'M')
  572. {
  573. //pos.Y = int.Parse (value) + Console.WindowTop - 1;
  574. pos.Y = int.Parse (value) - 1;
  575. switch (buttonCode)
  576. {
  577. case 0:
  578. case 8:
  579. case 16:
  580. case 24:
  581. case 32:
  582. case 36:
  583. case 40:
  584. case 48:
  585. case 56:
  586. buttonState = c == 'M'
  587. ? MouseFlags.Button1Pressed
  588. : MouseFlags.Button1Released;
  589. break;
  590. case 1:
  591. case 9:
  592. case 17:
  593. case 25:
  594. case 33:
  595. case 37:
  596. case 41:
  597. case 45:
  598. case 49:
  599. case 53:
  600. case 57:
  601. case 61:
  602. buttonState = c == 'M'
  603. ? MouseFlags.Button2Pressed
  604. : MouseFlags.Button2Released;
  605. break;
  606. case 2:
  607. case 10:
  608. case 14:
  609. case 18:
  610. case 22:
  611. case 26:
  612. case 30:
  613. case 34:
  614. case 42:
  615. case 46:
  616. case 50:
  617. case 54:
  618. case 58:
  619. case 62:
  620. buttonState = c == 'M'
  621. ? MouseFlags.Button3Pressed
  622. : MouseFlags.Button3Released;
  623. break;
  624. case 35:
  625. //// Needed for Windows OS
  626. //if (isButtonPressed && c == 'm'
  627. // && (lastMouseEvent.ButtonState == MouseFlags.Button1Pressed
  628. // || lastMouseEvent.ButtonState == MouseFlags.Button2Pressed
  629. // || lastMouseEvent.ButtonState == MouseFlags.Button3Pressed)) {
  630. // switch (lastMouseEvent.ButtonState) {
  631. // case MouseFlags.Button1Pressed:
  632. // buttonState = MouseFlags.Button1Released;
  633. // break;
  634. // case MouseFlags.Button2Pressed:
  635. // buttonState = MouseFlags.Button2Released;
  636. // break;
  637. // case MouseFlags.Button3Pressed:
  638. // buttonState = MouseFlags.Button3Released;
  639. // break;
  640. // }
  641. //} else {
  642. // buttonState = MouseFlags.ReportMousePosition;
  643. //}
  644. //break;
  645. case 39:
  646. case 43:
  647. case 47:
  648. case 51:
  649. case 55:
  650. case 59:
  651. case 63:
  652. buttonState = MouseFlags.ReportMousePosition;
  653. break;
  654. case 64:
  655. buttonState = MouseFlags.WheeledUp;
  656. break;
  657. case 65:
  658. buttonState = MouseFlags.WheeledDown;
  659. break;
  660. case 68:
  661. case 72:
  662. case 80:
  663. buttonState = MouseFlags.WheeledLeft; // Shift/Ctrl+WheeledUp
  664. break;
  665. case 69:
  666. case 73:
  667. case 81:
  668. buttonState = MouseFlags.WheeledRight; // Shift/Ctrl+WheeledDown
  669. break;
  670. }
  671. // Modifiers.
  672. switch (buttonCode)
  673. {
  674. case 8:
  675. case 9:
  676. case 10:
  677. case 43:
  678. buttonState |= MouseFlags.ButtonAlt;
  679. break;
  680. case 14:
  681. case 47:
  682. buttonState |= MouseFlags.ButtonAlt | MouseFlags.ButtonShift;
  683. break;
  684. case 16:
  685. case 17:
  686. case 18:
  687. case 51:
  688. buttonState |= MouseFlags.ButtonCtrl;
  689. break;
  690. case 22:
  691. case 55:
  692. buttonState |= MouseFlags.ButtonCtrl | MouseFlags.ButtonShift;
  693. break;
  694. case 24:
  695. case 25:
  696. case 26:
  697. case 59:
  698. buttonState |= MouseFlags.ButtonCtrl | MouseFlags.ButtonAlt;
  699. break;
  700. case 30:
  701. case 63:
  702. buttonState |= MouseFlags.ButtonCtrl | MouseFlags.ButtonShift | MouseFlags.ButtonAlt;
  703. break;
  704. case 32:
  705. case 33:
  706. case 34:
  707. buttonState |= MouseFlags.ReportMousePosition;
  708. break;
  709. case 36:
  710. case 37:
  711. buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonShift;
  712. break;
  713. case 39:
  714. case 68:
  715. case 69:
  716. buttonState |= MouseFlags.ButtonShift;
  717. break;
  718. case 40:
  719. case 41:
  720. case 42:
  721. buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonAlt;
  722. break;
  723. case 45:
  724. case 46:
  725. buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonAlt | MouseFlags.ButtonShift;
  726. break;
  727. case 48:
  728. case 49:
  729. case 50:
  730. buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonCtrl;
  731. break;
  732. case 53:
  733. case 54:
  734. buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonCtrl | MouseFlags.ButtonShift;
  735. break;
  736. case 56:
  737. case 57:
  738. case 58:
  739. buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonCtrl | MouseFlags.ButtonAlt;
  740. break;
  741. case 61:
  742. case 62:
  743. buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonCtrl | MouseFlags.ButtonShift | MouseFlags.ButtonAlt;
  744. break;
  745. }
  746. }
  747. }
  748. mouseFlags = [MouseFlags.AllEvents];
  749. if (_lastMouseButtonPressed != null
  750. && !_isButtonPressed
  751. && !buttonState.HasFlag (MouseFlags.ReportMousePosition)
  752. && !buttonState.HasFlag (MouseFlags.Button1Released)
  753. && !buttonState.HasFlag (MouseFlags.Button2Released)
  754. && !buttonState.HasFlag (MouseFlags.Button3Released)
  755. && !buttonState.HasFlag (MouseFlags.Button4Released))
  756. {
  757. _lastMouseButtonPressed = null;
  758. _isButtonPressed = false;
  759. }
  760. if ((!_isButtonClicked
  761. && !_isButtonDoubleClicked
  762. && (buttonState == MouseFlags.Button1Pressed
  763. || buttonState == MouseFlags.Button2Pressed
  764. || buttonState == MouseFlags.Button3Pressed
  765. || buttonState == MouseFlags.Button4Pressed)
  766. && _lastMouseButtonPressed is null)
  767. || (_isButtonPressed && _lastMouseButtonPressed is { } && buttonState.HasFlag (MouseFlags.ReportMousePosition)))
  768. {
  769. mouseFlags [0] = buttonState;
  770. _lastMouseButtonPressed = buttonState;
  771. _isButtonPressed = true;
  772. _point = pos;
  773. if ((mouseFlags [0] & MouseFlags.ReportMousePosition) == 0)
  774. {
  775. Application.MainLoop?.AddIdle (
  776. () =>
  777. {
  778. // INTENT: What's this trying to do?
  779. // The task itself is not awaited.
  780. Task.Run (
  781. async () => await ProcessContinuousButtonPressedAsync (
  782. buttonState,
  783. continuousButtonPressedHandler));
  784. return false;
  785. });
  786. }
  787. else if (mouseFlags [0].HasFlag (MouseFlags.ReportMousePosition))
  788. {
  789. _point = pos;
  790. // The isButtonPressed must always be true, otherwise we can lose the feature
  791. // If mouse flags has ReportMousePosition this feature won't run
  792. // but is always prepared with the new location
  793. //isButtonPressed = false;
  794. }
  795. }
  796. else if (_isButtonDoubleClicked
  797. && (buttonState == MouseFlags.Button1Pressed
  798. || buttonState == MouseFlags.Button2Pressed
  799. || buttonState == MouseFlags.Button3Pressed
  800. || buttonState == MouseFlags.Button4Pressed))
  801. {
  802. mouseFlags [0] = GetButtonTripleClicked (buttonState);
  803. _isButtonDoubleClicked = false;
  804. _isButtonTripleClicked = true;
  805. }
  806. else if (_isButtonClicked
  807. && (buttonState == MouseFlags.Button1Pressed
  808. || buttonState == MouseFlags.Button2Pressed
  809. || buttonState == MouseFlags.Button3Pressed
  810. || buttonState == MouseFlags.Button4Pressed))
  811. {
  812. mouseFlags [0] = GetButtonDoubleClicked (buttonState);
  813. _isButtonClicked = false;
  814. _isButtonDoubleClicked = true;
  815. Application.MainLoop?.AddIdle (
  816. () =>
  817. {
  818. Task.Run (async () => await ProcessButtonDoubleClickedAsync ());
  819. return false;
  820. });
  821. }
  822. //else if (isButtonReleased && !isButtonClicked && buttonState == MouseFlags.ReportMousePosition) {
  823. // mouseFlag [0] = GetButtonClicked ((MouseFlags)lastMouseButtonReleased);
  824. // lastMouseButtonReleased = null;
  825. // isButtonReleased = false;
  826. // isButtonClicked = true;
  827. // Application.MainLoop.AddIdle (() => {
  828. // Task.Run (async () => await ProcessButtonClickedAsync ());
  829. // return false;
  830. // });
  831. //}
  832. else if (!_isButtonClicked
  833. && !_isButtonDoubleClicked
  834. && (buttonState == MouseFlags.Button1Released
  835. || buttonState == MouseFlags.Button2Released
  836. || buttonState == MouseFlags.Button3Released
  837. || buttonState == MouseFlags.Button4Released))
  838. {
  839. mouseFlags [0] = buttonState;
  840. _isButtonPressed = false;
  841. if (_isButtonTripleClicked)
  842. {
  843. _isButtonTripleClicked = false;
  844. }
  845. else if (pos.X == _point?.X && pos.Y == _point?.Y)
  846. {
  847. mouseFlags.Add (GetButtonClicked (buttonState));
  848. _isButtonClicked = true;
  849. Application.MainLoop?.AddIdle (
  850. () =>
  851. {
  852. Task.Run (async () => await ProcessButtonClickedAsync ());
  853. return false;
  854. });
  855. }
  856. _point = pos;
  857. //if ((lastMouseButtonPressed & MouseFlags.ReportMousePosition) == 0) {
  858. // lastMouseButtonReleased = buttonState;
  859. // isButtonPressed = false;
  860. // isButtonReleased = true;
  861. //} else {
  862. // lastMouseButtonPressed = null;
  863. // isButtonPressed = false;
  864. //}
  865. }
  866. else if (buttonState == MouseFlags.WheeledUp)
  867. {
  868. mouseFlags [0] = MouseFlags.WheeledUp;
  869. }
  870. else if (buttonState == MouseFlags.WheeledDown)
  871. {
  872. mouseFlags [0] = MouseFlags.WheeledDown;
  873. }
  874. else if (buttonState == MouseFlags.WheeledLeft)
  875. {
  876. mouseFlags [0] = MouseFlags.WheeledLeft;
  877. }
  878. else if (buttonState == MouseFlags.WheeledRight)
  879. {
  880. mouseFlags [0] = MouseFlags.WheeledRight;
  881. }
  882. else if (buttonState == MouseFlags.ReportMousePosition)
  883. {
  884. mouseFlags [0] = MouseFlags.ReportMousePosition;
  885. }
  886. else
  887. {
  888. mouseFlags [0] = buttonState;
  889. //foreach (var flag in buttonState.GetUniqueFlags()) {
  890. // mouseFlag [0] |= flag;
  891. //}
  892. }
  893. mouseFlags [0] = SetControlKeyStates (buttonState, mouseFlags [0]);
  894. //buttonState = mouseFlags;
  895. //System.Diagnostics.Debug.WriteLine ($"buttonState: {buttonState} X: {pos.X} Y: {pos.Y}");
  896. //foreach (var mf in mouseFlags) {
  897. // System.Diagnostics.Debug.WriteLine ($"mouseFlags: {mf} X: {pos.X} Y: {pos.Y}");
  898. //}
  899. }
  900. /// <summary>
  901. /// Ensures a console key is mapped to one that works correctly with ANSI escape sequences.
  902. /// </summary>
  903. /// <param name="consoleKeyInfo">The <see cref="ConsoleKeyInfo"/>.</param>
  904. /// <returns>The <see cref="ConsoleKeyInfo"/> modified.</returns>
  905. public static ConsoleKeyInfo MapConsoleKeyInfo (ConsoleKeyInfo consoleKeyInfo)
  906. {
  907. ConsoleKeyInfo newConsoleKeyInfo = consoleKeyInfo;
  908. ConsoleKey key = ConsoleKey.None;
  909. char keyChar = consoleKeyInfo.KeyChar;
  910. switch ((uint)keyChar)
  911. {
  912. case 0:
  913. if (consoleKeyInfo.Key == (ConsoleKey)64)
  914. { // Ctrl+Space in Windows.
  915. newConsoleKeyInfo = new (
  916. consoleKeyInfo.KeyChar,
  917. ConsoleKey.Spacebar,
  918. (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0,
  919. (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
  920. (consoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0);
  921. }
  922. else if (consoleKeyInfo.Key == ConsoleKey.None)
  923. {
  924. newConsoleKeyInfo = new (
  925. consoleKeyInfo.KeyChar,
  926. ConsoleKey.Spacebar,
  927. (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0,
  928. (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
  929. true);
  930. }
  931. break;
  932. case uint n when n is > 0 and <= KeyEsc:
  933. if (consoleKeyInfo is { Key: 0, KeyChar: '\t' })
  934. {
  935. key = ConsoleKey.Tab;
  936. newConsoleKeyInfo = new (
  937. consoleKeyInfo.KeyChar,
  938. key,
  939. (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0,
  940. (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
  941. (consoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0);
  942. }
  943. else if (consoleKeyInfo is { Key: 0, KeyChar: '\r' })
  944. {
  945. key = ConsoleKey.Enter;
  946. newConsoleKeyInfo = new (
  947. consoleKeyInfo.KeyChar,
  948. key,
  949. (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0,
  950. (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
  951. (consoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0);
  952. }
  953. else if (consoleKeyInfo is { Key: 0, KeyChar: '\n' })
  954. {
  955. key = ConsoleKey.Enter;
  956. newConsoleKeyInfo = new (
  957. consoleKeyInfo.KeyChar,
  958. key,
  959. (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0,
  960. (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
  961. true);
  962. }
  963. else if (consoleKeyInfo.Key == 0)
  964. {
  965. key = (ConsoleKey)(char)(consoleKeyInfo.KeyChar + (uint)ConsoleKey.A - 1);
  966. newConsoleKeyInfo = new (
  967. consoleKeyInfo.KeyChar,
  968. key,
  969. (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0,
  970. (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
  971. true);
  972. }
  973. break;
  974. case 127: // DEL
  975. key = ConsoleKey.Backspace;
  976. newConsoleKeyInfo = new (
  977. consoleKeyInfo.KeyChar,
  978. key,
  979. (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0,
  980. (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
  981. (consoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0);
  982. break;
  983. default:
  984. uint ck = ConsoleKeyMapping.MapKeyCodeToConsoleKey ((KeyCode)consoleKeyInfo.KeyChar, out bool isConsoleKey);
  985. if (isConsoleKey)
  986. {
  987. key = (ConsoleKey)ck;
  988. }
  989. newConsoleKeyInfo = new (
  990. consoleKeyInfo.KeyChar,
  991. key,
  992. GetShiftMod (consoleKeyInfo.Modifiers),
  993. (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
  994. (consoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0);
  995. break;
  996. }
  997. return newConsoleKeyInfo;
  998. bool GetShiftMod (ConsoleModifiers modifiers)
  999. {
  1000. if (consoleKeyInfo.KeyChar is >= (char)ConsoleKey.A and <= (char)ConsoleKey.Z && modifiers == ConsoleModifiers.None)
  1001. {
  1002. return true;
  1003. }
  1004. return (modifiers & ConsoleModifiers.Shift) != 0;
  1005. }
  1006. }
  1007. private static MouseFlags _lastMouseFlags;
  1008. /// <summary>
  1009. /// Provides a handler to be invoked when mouse continuous button pressed is processed.
  1010. /// </summary>
  1011. public static event EventHandler<MouseEventArgs> ContinuousButtonPressed;
  1012. /// <summary>
  1013. /// Provides a default mouse event handler that can be used by any driver.
  1014. /// </summary>
  1015. /// <param name="mouseFlag">The mouse flags event.</param>
  1016. /// <param name="pos">The mouse position.</param>
  1017. public static void ProcessMouseEvent (MouseFlags mouseFlag, Point pos)
  1018. {
  1019. bool WasButtonReleased (MouseFlags flag)
  1020. {
  1021. return flag.HasFlag (MouseFlags.Button1Released)
  1022. || flag.HasFlag (MouseFlags.Button2Released)
  1023. || flag.HasFlag (MouseFlags.Button3Released)
  1024. || flag.HasFlag (MouseFlags.Button4Released);
  1025. }
  1026. bool IsButtonNotPressed (MouseFlags flag)
  1027. {
  1028. return !flag.HasFlag (MouseFlags.Button1Pressed)
  1029. && !flag.HasFlag (MouseFlags.Button2Pressed)
  1030. && !flag.HasFlag (MouseFlags.Button3Pressed)
  1031. && !flag.HasFlag (MouseFlags.Button4Pressed);
  1032. }
  1033. bool IsButtonClickedOrDoubleClicked (MouseFlags flag)
  1034. {
  1035. return flag.HasFlag (MouseFlags.Button1Clicked)
  1036. || flag.HasFlag (MouseFlags.Button2Clicked)
  1037. || flag.HasFlag (MouseFlags.Button3Clicked)
  1038. || flag.HasFlag (MouseFlags.Button4Clicked)
  1039. || flag.HasFlag (MouseFlags.Button1DoubleClicked)
  1040. || flag.HasFlag (MouseFlags.Button2DoubleClicked)
  1041. || flag.HasFlag (MouseFlags.Button3DoubleClicked)
  1042. || flag.HasFlag (MouseFlags.Button4DoubleClicked);
  1043. }
  1044. if ((WasButtonReleased (mouseFlag) && IsButtonNotPressed (_lastMouseFlags)) || (IsButtonClickedOrDoubleClicked (mouseFlag) && _lastMouseFlags == 0))
  1045. {
  1046. return;
  1047. }
  1048. _lastMouseFlags = mouseFlag;
  1049. var me = new MouseEventArgs { Flags = mouseFlag, Position = pos };
  1050. ContinuousButtonPressed?.Invoke ((mouseFlag, pos), me);
  1051. }
  1052. /// <summary>
  1053. /// A helper to resize the <see cref="ConsoleKeyInfo"/> as needed.
  1054. /// </summary>
  1055. /// <param name="consoleKeyInfo">The <see cref="ConsoleKeyInfo"/>.</param>
  1056. /// <param name="cki">The <see cref="ConsoleKeyInfo"/> array to resize.</param>
  1057. /// <returns>The <see cref="ConsoleKeyInfo"/> resized.</returns>
  1058. public static ConsoleKeyInfo [] ResizeArray (ConsoleKeyInfo consoleKeyInfo, ConsoleKeyInfo [] cki)
  1059. {
  1060. Array.Resize (ref cki, cki is null ? 1 : cki.Length + 1);
  1061. cki [^1] = consoleKeyInfo;
  1062. return cki;
  1063. }
  1064. /// <summary>
  1065. /// Insert a <see cref="ConsoleKeyInfo"/> array into the another <see cref="ConsoleKeyInfo"/> array at the specified
  1066. /// index.
  1067. /// </summary>
  1068. /// <param name="toInsert">The array to insert.</param>
  1069. /// <param name="cki">The array where will be added the array.</param>
  1070. /// <param name="index">The start index to insert the array, default is 0.</param>
  1071. /// <returns>The <see cref="ConsoleKeyInfo"/> array with another array inserted.</returns>
  1072. public static ConsoleKeyInfo [] InsertArray ([CanBeNull] ConsoleKeyInfo [] toInsert, ConsoleKeyInfo [] cki, int index = 0)
  1073. {
  1074. if (toInsert is null)
  1075. {
  1076. return cki;
  1077. }
  1078. if (cki is null)
  1079. {
  1080. return toInsert;
  1081. }
  1082. if (index < 0)
  1083. {
  1084. index = 0;
  1085. }
  1086. ConsoleKeyInfo [] backupCki = cki.Clone () as ConsoleKeyInfo [];
  1087. Array.Resize (ref cki, cki.Length + toInsert.Length);
  1088. for (var i = 0; i < cki.Length; i++)
  1089. {
  1090. if (i == index)
  1091. {
  1092. for (var j = 0; j < toInsert.Length; j++)
  1093. {
  1094. cki [i] = toInsert [j];
  1095. i++;
  1096. }
  1097. for (int k = index; k < backupCki!.Length; k++)
  1098. {
  1099. cki [i] = backupCki [k];
  1100. i++;
  1101. }
  1102. }
  1103. else
  1104. {
  1105. cki [i] = backupCki! [i];
  1106. }
  1107. }
  1108. return cki;
  1109. }
  1110. private static MouseFlags GetButtonClicked (MouseFlags mouseFlag)
  1111. {
  1112. MouseFlags mf = default;
  1113. switch (mouseFlag)
  1114. {
  1115. case MouseFlags.Button1Released:
  1116. mf = MouseFlags.Button1Clicked;
  1117. break;
  1118. case MouseFlags.Button2Released:
  1119. mf = MouseFlags.Button2Clicked;
  1120. break;
  1121. case MouseFlags.Button3Released:
  1122. mf = MouseFlags.Button3Clicked;
  1123. break;
  1124. }
  1125. return mf;
  1126. }
  1127. private static MouseFlags GetButtonDoubleClicked (MouseFlags mouseFlag)
  1128. {
  1129. MouseFlags mf = default;
  1130. switch (mouseFlag)
  1131. {
  1132. case MouseFlags.Button1Pressed:
  1133. mf = MouseFlags.Button1DoubleClicked;
  1134. break;
  1135. case MouseFlags.Button2Pressed:
  1136. mf = MouseFlags.Button2DoubleClicked;
  1137. break;
  1138. case MouseFlags.Button3Pressed:
  1139. mf = MouseFlags.Button3DoubleClicked;
  1140. break;
  1141. }
  1142. return mf;
  1143. }
  1144. private static MouseFlags GetButtonTripleClicked (MouseFlags mouseFlag)
  1145. {
  1146. MouseFlags mf = default;
  1147. switch (mouseFlag)
  1148. {
  1149. case MouseFlags.Button1Pressed:
  1150. mf = MouseFlags.Button1TripleClicked;
  1151. break;
  1152. case MouseFlags.Button2Pressed:
  1153. mf = MouseFlags.Button2TripleClicked;
  1154. break;
  1155. case MouseFlags.Button3Pressed:
  1156. mf = MouseFlags.Button3TripleClicked;
  1157. break;
  1158. }
  1159. return mf;
  1160. }
  1161. private static async Task ProcessButtonClickedAsync ()
  1162. {
  1163. await Task.Delay (300);
  1164. _isButtonClicked = false;
  1165. }
  1166. private static async Task ProcessButtonDoubleClickedAsync ()
  1167. {
  1168. await Task.Delay (300);
  1169. _isButtonDoubleClicked = false;
  1170. }
  1171. private static async Task ProcessContinuousButtonPressedAsync (MouseFlags mouseFlag, Action<MouseFlags, Point> continuousButtonPressedHandler)
  1172. {
  1173. // PERF: Pause and poll in a hot loop.
  1174. // This should be replaced with event dispatch and a synchronization primitive such as AutoResetEvent.
  1175. // Will make a massive difference in responsiveness.
  1176. while (_isButtonPressed)
  1177. {
  1178. await Task.Delay (100);
  1179. View view = Application.WantContinuousButtonPressedView;
  1180. if (view is null)
  1181. {
  1182. break;
  1183. }
  1184. if (_isButtonPressed && _lastMouseButtonPressed is { } && (mouseFlag & MouseFlags.ReportMousePosition) == 0)
  1185. {
  1186. Application.Invoke (() => continuousButtonPressedHandler (mouseFlag, _point ?? Point.Empty));
  1187. }
  1188. }
  1189. }
  1190. private static MouseFlags SetControlKeyStates (MouseFlags buttonState, MouseFlags mouseFlag)
  1191. {
  1192. if ((buttonState & MouseFlags.ButtonCtrl) != 0 && (mouseFlag & MouseFlags.ButtonCtrl) == 0)
  1193. {
  1194. mouseFlag |= MouseFlags.ButtonCtrl;
  1195. }
  1196. if ((buttonState & MouseFlags.ButtonShift) != 0 && (mouseFlag & MouseFlags.ButtonShift) == 0)
  1197. {
  1198. mouseFlag |= MouseFlags.ButtonShift;
  1199. }
  1200. if ((buttonState & MouseFlags.ButtonAlt) != 0 && (mouseFlag & MouseFlags.ButtonAlt) == 0)
  1201. {
  1202. mouseFlag |= MouseFlags.ButtonAlt;
  1203. }
  1204. return mouseFlag;
  1205. }
  1206. /// <summary>
  1207. /// Split a raw string into a list of string with the correct ansi escape sequence.
  1208. /// </summary>
  1209. /// <param name="rawData">The raw string containing one or many ansi escape sequence.</param>
  1210. /// <returns>A list with a valid ansi escape sequence.</returns>
  1211. public static List<string> SplitEscapeRawString (string rawData)
  1212. {
  1213. List<string> splitList = [];
  1214. var isEscSeq = false;
  1215. var split = string.Empty;
  1216. char previousChar = '\0';
  1217. for (var i = 0; i < rawData.Length; i++)
  1218. {
  1219. char c = rawData [i];
  1220. if (c == '\u001B')
  1221. {
  1222. isEscSeq = true;
  1223. split = AddAndClearSplit ();
  1224. split += c.ToString ();
  1225. }
  1226. else if (!isEscSeq && c >= Key.Space)
  1227. {
  1228. split = AddAndClearSplit ();
  1229. splitList.Add (c.ToString ());
  1230. }
  1231. else if ((previousChar != '\u001B' && c <= Key.Space) || (previousChar != '\u001B' && c == 127)
  1232. || (char.IsLetter (previousChar) && char.IsLower (c) && char.IsLetter (c))
  1233. || (!string.IsNullOrEmpty (split) && split.Length > 2 && char.IsLetter (previousChar) && char.IsLetter (c)))
  1234. {
  1235. isEscSeq = false;
  1236. split = AddAndClearSplit ();
  1237. splitList.Add (c.ToString ());
  1238. }
  1239. else
  1240. {
  1241. split += c.ToString ();
  1242. }
  1243. if (!string.IsNullOrEmpty (split) && i == rawData.Length - 1)
  1244. {
  1245. splitList.Add (split);
  1246. }
  1247. previousChar = c;
  1248. }
  1249. return splitList;
  1250. string AddAndClearSplit ()
  1251. {
  1252. if (!string.IsNullOrEmpty (split))
  1253. {
  1254. splitList.Add (split);
  1255. split = string.Empty;
  1256. }
  1257. return split;
  1258. }
  1259. }
  1260. /// <summary>
  1261. /// Convert a <see cref="ConsoleKeyInfo"/> array to string.
  1262. /// </summary>
  1263. /// <param name="consoleKeyInfos"></param>
  1264. /// <returns>The string representing the array.</returns>
  1265. public static string ToString (ConsoleKeyInfo [] consoleKeyInfos)
  1266. {
  1267. StringBuilder sb = new ();
  1268. foreach (ConsoleKeyInfo keyChar in consoleKeyInfos)
  1269. {
  1270. sb.Append (keyChar.KeyChar);
  1271. }
  1272. return sb.ToString ();
  1273. }
  1274. /// <summary>
  1275. /// Convert a string to <see cref="ConsoleKeyInfo"/> array.
  1276. /// </summary>
  1277. /// <param name="ansi"></param>
  1278. /// <returns>The <see cref="ConsoleKeyInfo"/>representing the string.</returns>
  1279. public static ConsoleKeyInfo [] ToConsoleKeyInfoArray (string ansi)
  1280. {
  1281. if (ansi is null)
  1282. {
  1283. return null;
  1284. }
  1285. ConsoleKeyInfo [] cki = new ConsoleKeyInfo [ansi.Length];
  1286. for (var i = 0; i < ansi.Length; i++)
  1287. {
  1288. char c = ansi [i];
  1289. cki [i] = new (c, 0, false, false, false);
  1290. }
  1291. return cki;
  1292. }
  1293. #region Cursor
  1294. //ESC [ M - RI Reverse Index – Performs the reverse operation of \n, moves cursor up one line, maintains horizontal position, scrolls buffer if necessary*
  1295. /// <summary>
  1296. /// ESC [ 7 - Save Cursor Position in Memory**
  1297. /// </summary>
  1298. public static readonly string CSI_SaveCursorPosition = CSI + "7";
  1299. /// <summary>
  1300. /// ESC [ 8 - DECSR Restore Cursor Position from Memory**
  1301. /// </summary>
  1302. public static readonly string CSI_RestoreCursorPosition = CSI + "8";
  1303. /// <summary>
  1304. /// ESC [ 8 ; height ; width t - Set Terminal Window Size
  1305. /// https://terminalguide.namepad.de/seq/csi_st-8/
  1306. /// </summary>
  1307. public static string CSI_SetTerminalWindowSize (int height, int width) { return $"{CSI}8;{height};{width}t"; }
  1308. //ESC [ < n > A - CUU - Cursor Up Cursor up by < n >
  1309. //ESC [ < n > B - CUD - Cursor Down Cursor down by < n >
  1310. //ESC [ < n > C - CUF - Cursor Forward Cursor forward (Right) by < n >
  1311. //ESC [ < n > D - CUB - Cursor Backward Cursor backward (Left) by < n >
  1312. //ESC [ < n > E - CNL - Cursor Next Line - Cursor down < n > lines from current position
  1313. //ESC [ < n > F - CPL - Cursor Previous Line Cursor up < n > lines from current position
  1314. //ESC [ < n > G - CHA - Cursor Horizontal Absolute Cursor moves to < n > th position horizontally in the current line
  1315. //ESC [ < n > d - VPA - Vertical Line Position Absolute Cursor moves to the < n > th position vertically in the current column
  1316. /// <summary>
  1317. /// ESC [ y ; x H - CUP Cursor Position - Cursor moves to x ; y coordinate within the viewport, where x is the column
  1318. /// of the y line
  1319. /// </summary>
  1320. /// <param name="row">Origin is (1,1).</param>
  1321. /// <param name="col">Origin is (1,1).</param>
  1322. /// <returns></returns>
  1323. public static string CSI_SetCursorPosition (int row, int col) { return $"{CSI}{row};{col}H"; }
  1324. //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
  1325. //ESC [ s - ANSISYSSC Save Cursor – Ansi.sys emulation **With no parameters, performs a save cursor operation like DECSC
  1326. //ESC [ u - ANSISYSRC Restore Cursor – Ansi.sys emulation **With no parameters, performs a restore cursor operation like DECRC
  1327. //ESC [ ? 12 h - ATT160 Text Cursor Enable Blinking Start the cursor blinking
  1328. //ESC [ ? 12 l - ATT160 Text Cursor Disable Blinking Stop blinking the cursor
  1329. /// <summary>
  1330. /// ESC [ ? 25 h - DECTCEM Text Cursor Enable Mode Show Show the cursor
  1331. /// </summary>
  1332. public static readonly string CSI_ShowCursor = CSI + "?25h";
  1333. /// <summary>
  1334. /// ESC [ ? 25 l - DECTCEM Text Cursor Enable Mode Hide Hide the cursor
  1335. /// </summary>
  1336. public static readonly string CSI_HideCursor = CSI + "?25l";
  1337. //ESC [ ? 12 h - ATT160 Text Cursor Enable Blinking Start the cursor blinking
  1338. //ESC [ ? 12 l - ATT160 Text Cursor Disable Blinking Stop blinking the cursor
  1339. //ESC [ ? 25 h - DECTCEM Text Cursor Enable Mode Show Show the cursor
  1340. //ESC [ ? 25 l - DECTCEM Text Cursor Enable Mode Hide Hide the cursor
  1341. /// <summary>
  1342. /// Styles for ANSI ESC "[x q" - Set Cursor Style
  1343. /// </summary>
  1344. public enum DECSCUSR_Style
  1345. {
  1346. /// <summary>
  1347. /// DECSCUSR - User Shape - Default cursor shape configured by the user
  1348. /// </summary>
  1349. UserShape = 0,
  1350. /// <summary>
  1351. /// DECSCUSR - Blinking Block - Blinking block cursor shape
  1352. /// </summary>
  1353. BlinkingBlock = 1,
  1354. /// <summary>
  1355. /// DECSCUSR - Steady Block - Steady block cursor shape
  1356. /// </summary>
  1357. SteadyBlock = 2,
  1358. /// <summary>
  1359. /// DECSCUSR - Blinking Underline - Blinking underline cursor shape
  1360. /// </summary>
  1361. BlinkingUnderline = 3,
  1362. /// <summary>
  1363. /// DECSCUSR - Steady Underline - Steady underline cursor shape
  1364. /// </summary>
  1365. SteadyUnderline = 4,
  1366. /// <summary>
  1367. /// DECSCUSR - Blinking Bar - Blinking bar cursor shape
  1368. /// </summary>
  1369. BlinkingBar = 5,
  1370. /// <summary>
  1371. /// DECSCUSR - Steady Bar - Steady bar cursor shape
  1372. /// </summary>
  1373. SteadyBar = 6
  1374. }
  1375. /// <summary>
  1376. /// ESC [ n SP q - Select Cursor Style (DECSCUSR)
  1377. /// https://terminalguide.namepad.de/seq/csi_sq_t_space/
  1378. /// </summary>
  1379. /// <param name="style"></param>
  1380. /// <returns></returns>
  1381. public static string CSI_SetCursorStyle (DECSCUSR_Style style) { return $"{CSI}{(int)style} q"; }
  1382. #endregion
  1383. #region Colors
  1384. /// <summary>
  1385. /// ESC [ (n) m - SGR - Set Graphics Rendition - Set the format of the screen and text as specified by (n)
  1386. /// This command is special in that the (n) position can accept between 0 and 16 parameters separated by semicolons.
  1387. /// When no parameters are specified, it is treated the same as a single 0 parameter.
  1388. /// https://terminalguide.namepad.de/seq/csi_sm/
  1389. /// </summary>
  1390. public static string CSI_SetGraphicsRendition (params int [] parameters) { return $"{CSI}{string.Join (";", parameters)}m"; }
  1391. /// <summary>
  1392. /// ESC [ (n) m - Uses <see cref="CSI_SetGraphicsRendition(int[])"/> to set the foreground color.
  1393. /// </summary>
  1394. /// <param name="code">One of the 16 color codes.</param>
  1395. /// <returns></returns>
  1396. public static string CSI_SetForegroundColor (AnsiColorCode code) { return CSI_SetGraphicsRendition ((int)code); }
  1397. /// <summary>
  1398. /// ESC [ (n) m - Uses <see cref="CSI_SetGraphicsRendition(int[])"/> to set the background color.
  1399. /// </summary>
  1400. /// <param name="code">One of the 16 color codes.</param>
  1401. /// <returns></returns>
  1402. public static string CSI_SetBackgroundColor (AnsiColorCode code) { return CSI_SetGraphicsRendition ((int)code + 10); }
  1403. /// <summary>
  1404. /// ESC[38;5;{id}m - Set foreground color (256 colors)
  1405. /// </summary>
  1406. public static string CSI_SetForegroundColor256 (int color) { return $"{CSI}38;5;{color}m"; }
  1407. /// <summary>
  1408. /// ESC[48;5;{id}m - Set background color (256 colors)
  1409. /// </summary>
  1410. public static string CSI_SetBackgroundColor256 (int color) { return $"{CSI}48;5;{color}m"; }
  1411. /// <summary>
  1412. /// ESC[38;2;{r};{g};{b}m Set foreground color as RGB.
  1413. /// </summary>
  1414. public static string CSI_SetForegroundColorRGB (int r, int g, int b) { return $"{CSI}38;2;{r};{g};{b}m"; }
  1415. /// <summary>
  1416. /// ESC[48;2;{r};{g};{b}m Set background color as RGB.
  1417. /// </summary>
  1418. public static string CSI_SetBackgroundColorRGB (int r, int g, int b) { return $"{CSI}48;2;{r};{g};{b}m"; }
  1419. #endregion
  1420. #region Requests
  1421. /// <summary>
  1422. /// ESC [ ? 6 n - Request Cursor Position Report (?) (DECXCPR)
  1423. /// https://terminalguide.namepad.de/seq/csi_sn__p-6/
  1424. /// The terminal reply to <see cref="CSI_RequestCursorPositionReport"/>. ESC [ ? (y) ; (x) ; 1 R
  1425. /// </summary>
  1426. public static readonly AnsiEscapeSequenceRequest CSI_RequestCursorPositionReport = new () { Request = CSI + "?6n", Terminator = "R" };
  1427. /// <summary>
  1428. /// ESC [ 0 c - Send Device Attributes (Primary DA)
  1429. /// https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Application-Program-Command-functions
  1430. /// https://www.xfree86.org/current/ctlseqs.html
  1431. /// Windows Terminal v1.17 and below emits “\x1b[?1;0c”, indicating "VT101 with No Options".
  1432. /// Windows Terminal v1.18+ emits: \x1b[?61;6;7;22;23;24;28;32;42c"
  1433. /// See https://github.com/microsoft/terminal/pull/14906
  1434. /// 61 - The device conforms to level 1 of the character cell display architecture
  1435. /// (See https://github.com/microsoft/terminal/issues/15693#issuecomment-1633304497)
  1436. /// 6 = Selective erase
  1437. /// 7 = Soft fonts
  1438. /// 22 = Color text
  1439. /// 23 = Greek character sets
  1440. /// 24 = Turkish character sets
  1441. /// 28 = Rectangular area operations
  1442. /// 32 = Text macros
  1443. /// 42 = ISO Latin-2 character set
  1444. /// The terminator indicating a reply to <see cref="CSI_SendDeviceAttributes"/> or
  1445. /// <see cref="CSI_SendDeviceAttributes2"/>
  1446. /// </summary>
  1447. public static readonly AnsiEscapeSequenceRequest CSI_SendDeviceAttributes = new () { Request = CSI + "0c", Terminator = "c" };
  1448. /// <summary>
  1449. /// ESC [ > 0 c - Send Device Attributes (Secondary DA)
  1450. /// Windows Terminal v1.18+ emits: "\x1b[>0;10;1c" (vt100, firmware version 1.0, vt220)
  1451. /// The terminator indicating a reply to <see cref="CSI_SendDeviceAttributes"/> or
  1452. /// <see cref="CSI_SendDeviceAttributes2"/>
  1453. /// </summary>
  1454. public static readonly AnsiEscapeSequenceRequest CSI_SendDeviceAttributes2 = new () { Request = CSI + ">0c", Terminator = "c" };
  1455. /*
  1456. TODO: depends on https://github.com/gui-cs/Terminal.Gui/pull/3768
  1457. /// <summary>
  1458. /// CSI 16 t - Request sixel resolution (width and height in pixels)
  1459. /// </summary>
  1460. public static readonly AnsiEscapeSequenceRequest CSI_RequestSixelResolution = new () { Request = CSI + "16t", Terminator = "t" };
  1461. /// <summary>
  1462. /// CSI 14 t - Request window size in pixels (width x height)
  1463. /// </summary>
  1464. public static readonly AnsiEscapeSequenceRequest CSI_RequestWindowSizeInPixels = new () { Request = CSI + "14t", Terminator = "t" };
  1465. */
  1466. /// <summary>
  1467. /// CSI 1 8 t | yes | yes | yes | report window size in chars
  1468. /// https://terminalguide.namepad.de/seq/csi_st-18/
  1469. /// The terminator indicating a reply to <see cref="CSI_ReportTerminalSizeInChars"/> : ESC [ 8 ; height ; width t
  1470. /// </summary>
  1471. public static readonly AnsiEscapeSequenceRequest CSI_ReportTerminalSizeInChars = new () { Request = CSI + "18t", Terminator = "t", Value = "8" };
  1472. #endregion
  1473. }