AnsiEscapeSequenceRequestUtils.cs 71 KB

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