EscSeqUtils.cs 79 KB

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