EscSeqUtils.cs 66 KB

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