AnsiEscapeSequenceRequestUtils.cs 72 KB

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