EscSeqUtils.cs 80 KB

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