EscSeqUtils.cs 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377
  1. namespace Terminal.Gui;
  2. /// <summary>
  3. /// Provides a platform-independent API for managing ANSI escape sequences.
  4. /// </summary>
  5. /// <remarks>
  6. /// Useful resources:
  7. /// * https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences
  8. /// * https://invisible-island.net/xterm/ctlseqs/ctlseqs.html
  9. /// * https://vt100.net/
  10. /// </remarks>
  11. public static class EscSeqUtils
  12. {
  13. /// <summary>
  14. /// Options for ANSI ESC "[xJ" - Clears part of the screen.
  15. /// </summary>
  16. public enum ClearScreenOptions
  17. {
  18. /// <summary>
  19. /// If n is 0 (or missing), clear from cursor to end of screen.
  20. /// </summary>
  21. CursorToEndOfScreen = 0,
  22. /// <summary>
  23. /// If n is 1, clear from cursor to beginning of the screen.
  24. /// </summary>
  25. CursorToBeginningOfScreen = 1,
  26. /// <summary>
  27. /// If n is 2, clear entire screen (and moves cursor to upper left on DOS ANSI.SYS).
  28. /// </summary>
  29. EntireScreen = 2,
  30. /// <summary>
  31. /// If n is 3, clear entire screen and delete all lines saved in the scrollback buffer
  32. /// </summary>
  33. EntireScreenAndScrollbackBuffer = 3
  34. }
  35. /// <summary>
  36. /// Escape key code (ASCII 27/0x1B).
  37. /// </summary>
  38. public const char KeyEsc = (char)KeyCode.Esc;
  39. /// <summary>
  40. /// ESC [ - The CSI (Control Sequence Introducer).
  41. /// </summary>
  42. public const string CSI = "\u001B[";
  43. /// <summary>
  44. /// ESC [ ? 1047 h - Activate xterm alternative buffer (no backscroll)
  45. /// </summary>
  46. /// <remarks>
  47. /// From
  48. /// https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Functions-using-CSI-_-ordered-by-the-final-character_s_
  49. /// Use Alternate Screen Buffer, xterm.
  50. /// </remarks>
  51. public static readonly string CSI_ActivateAltBufferNoBackscroll = CSI + "?1047h";
  52. /// <summary>
  53. /// ESC [ ? 1003 l - Disable any mouse event tracking.
  54. /// </summary>
  55. public static readonly string CSI_DisableAnyEventMouse = CSI + "?1003l";
  56. /// <summary>
  57. /// ESC [ ? 1006 l - Disable SGR (Select Graphic Rendition).
  58. /// </summary>
  59. public static readonly string CSI_DisableSgrExtModeMouse = CSI + "?1006l";
  60. /// <summary>
  61. /// ESC [ ? 1015 l - Disable URXVT (Unicode Extended Virtual Terminal).
  62. /// </summary>
  63. public static readonly string CSI_DisableUrxvtExtModeMouse = CSI + "?1015l";
  64. /// <summary>
  65. /// ESC [ ? 1003 h - Enable mouse event tracking.
  66. /// </summary>
  67. public static readonly string CSI_EnableAnyEventMouse = CSI + "?1003h";
  68. /// <summary>
  69. /// ESC [ ? 1006 h - Enable SGR (Select Graphic Rendition).
  70. /// </summary>
  71. public static readonly string CSI_EnableSgrExtModeMouse = CSI + "?1006h";
  72. /// <summary>
  73. /// ESC [ ? 1015 h - Enable URXVT (Unicode Extended Virtual Terminal).
  74. /// </summary>
  75. public static readonly string CSI_EnableUrxvtExtModeMouse = CSI + "?1015h";
  76. /// <summary>
  77. /// ESC [ ? 1047 l - Restore xterm working buffer (with backscroll)
  78. /// </summary>
  79. /// <remarks>
  80. /// From
  81. /// https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Functions-using-CSI-_-ordered-by-the-final-character_s_
  82. /// Use Normal Screen Buffer, xterm. Clear the screen first if in the Alternate Screen Buffer.
  83. /// </remarks>
  84. public static readonly string CSI_RestoreAltBufferWithBackscroll = CSI + "?1047l";
  85. /// <summary>
  86. /// ESC [ ? 1049 l - Restore cursor position and restore xterm working buffer (with backscroll)
  87. /// </summary>
  88. /// <remarks>
  89. /// From
  90. /// https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Functions-using-CSI-_-ordered-by-the-final-character_s_
  91. /// Use Normal Screen Buffer and restore cursor as in DECRC, xterm.
  92. /// resource.This combines the effects of the 1047 and 1048 modes.
  93. /// </remarks>
  94. public static readonly string CSI_RestoreCursorAndRestoreAltBufferWithBackscroll = CSI + "?1049l";
  95. /// <summary>
  96. /// ESC [ ? 1049 h - Save cursor position and activate xterm alternative buffer (no backscroll)
  97. /// </summary>
  98. /// <remarks>
  99. /// From
  100. /// https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Functions-using-CSI-_-ordered-by-the-final-character_s_
  101. /// Save cursor as in DECSC, xterm. After saving the cursor, switch to the Alternate Screen Buffer,
  102. /// clearing it first.
  103. /// This control combines the effects of the 1047 and 1048 modes.
  104. /// Use this with terminfo-based applications rather than the 47 mode.
  105. /// </remarks>
  106. public static readonly string CSI_SaveCursorAndActivateAltBufferNoBackscroll = CSI + "?1049h";
  107. //private static bool isButtonReleased;
  108. private static bool isButtonClicked;
  109. private static bool isButtonDoubleClicked;
  110. //private static MouseFlags? lastMouseButtonReleased;
  111. // QUESTION: What's the difference between isButtonClicked and isButtonPressed?
  112. // Some clarity or comments would be handy, here.
  113. // It also seems like some enforcement of valid states might be a good idea.
  114. private static bool isButtonPressed;
  115. private static bool isButtonTripleClicked;
  116. private static MouseFlags? lastMouseButtonPressed;
  117. private static Point? point;
  118. /// <summary>
  119. /// Control sequence for disabling mouse events.
  120. /// </summary>
  121. public static string CSI_DisableMouseEvents { get; set; } =
  122. CSI_DisableAnyEventMouse + CSI_DisableUrxvtExtModeMouse + CSI_DisableSgrExtModeMouse;
  123. /// <summary>
  124. /// Control sequence for enabling mouse events.
  125. /// </summary>
  126. public static string CSI_EnableMouseEvents { get; set; } =
  127. CSI_EnableAnyEventMouse + CSI_EnableUrxvtExtModeMouse + CSI_EnableSgrExtModeMouse;
  128. /// <summary>
  129. /// ESC [ x J - Clears part of the screen. See <see cref="ClearScreenOptions"/>.
  130. /// </summary>
  131. /// <param name="option"></param>
  132. /// <returns></returns>
  133. public static string CSI_ClearScreen (ClearScreenOptions option) { return $"{CSI}{(int)option}J"; }
  134. /// <summary>
  135. /// Decodes an ANSI escape sequence.
  136. /// </summary>
  137. /// <param name="escSeqRequests">The <see cref="EscSeqRequests"/> which may contain a request.</param>
  138. /// <param name="newConsoleKeyInfo">The <see cref="ConsoleKeyInfo"/> which may change.</param>
  139. /// <param name="key">The <see cref="ConsoleKey"/> which may change.</param>
  140. /// <param name="cki">The <see cref="ConsoleKeyInfo"/> array.</param>
  141. /// <param name="mod">The <see cref="ConsoleModifiers"/> which may change.</param>
  142. /// <param name="c1Control">The control returned by the <see cref="GetC1ControlChar"/> method.</param>
  143. /// <param name="code">The code returned by the <see cref="GetEscapeResult(char[])"/> method.</param>
  144. /// <param name="values">The values returned by the <see cref="GetEscapeResult(char[])"/> method.</param>
  145. /// <param name="terminator">The terminator returned by the <see cref="GetEscapeResult(char[])"/> method.</param>
  146. /// <param name="isMouse">Indicates if the escape sequence is a mouse event.</param>
  147. /// <param name="buttonState">The <see cref="MouseFlags"/> button state.</param>
  148. /// <param name="pos">The <see cref="MouseFlags"/> position.</param>
  149. /// <param name="isResponse">Indicates if the escape sequence is a response to a request.</param>
  150. /// <param name="continuousButtonPressedHandler">The handler that will process the event.</param>
  151. public static void DecodeEscSeq (
  152. EscSeqRequests escSeqRequests,
  153. ref ConsoleKeyInfo newConsoleKeyInfo,
  154. ref ConsoleKey key,
  155. ConsoleKeyInfo [] cki,
  156. ref ConsoleModifiers mod,
  157. out string c1Control,
  158. out string code,
  159. out string [] values,
  160. out string terminator,
  161. out bool isMouse,
  162. out List<MouseFlags> buttonState,
  163. out Point pos,
  164. out bool isResponse,
  165. Action<MouseFlags, Point> continuousButtonPressedHandler
  166. )
  167. {
  168. char [] kChars = GetKeyCharArray (cki);
  169. (c1Control, code, values, terminator) = GetEscapeResult (kChars);
  170. isMouse = false;
  171. buttonState = new List<MouseFlags> { 0 };
  172. pos = default (Point);
  173. isResponse = false;
  174. char keyChar = '\0';
  175. switch (c1Control)
  176. {
  177. case "ESC":
  178. if (values is null && string.IsNullOrEmpty (terminator))
  179. {
  180. key = ConsoleKey.Escape;
  181. newConsoleKeyInfo = new ConsoleKeyInfo (
  182. cki [0].KeyChar,
  183. key,
  184. (mod & ConsoleModifiers.Shift) != 0,
  185. (mod & ConsoleModifiers.Alt) != 0,
  186. (mod & ConsoleModifiers.Control) != 0);
  187. }
  188. else if ((uint)cki [1].KeyChar >= 1 && (uint)cki [1].KeyChar <= 26)
  189. {
  190. key = (ConsoleKey)(char)(cki [1].KeyChar + (uint)ConsoleKey.A - 1);
  191. newConsoleKeyInfo = new ConsoleKeyInfo (
  192. cki [1].KeyChar,
  193. key,
  194. false,
  195. true,
  196. true);
  197. }
  198. else
  199. {
  200. if (cki [1].KeyChar >= 97 && cki [1].KeyChar <= 122)
  201. {
  202. key = (ConsoleKey)cki [1].KeyChar.ToString ().ToUpper () [0];
  203. }
  204. else
  205. {
  206. key = (ConsoleKey)cki [1].KeyChar;
  207. }
  208. newConsoleKeyInfo = new ConsoleKeyInfo (
  209. (char)key,
  210. (ConsoleKey)Math.Min ((uint)key, 255),
  211. false,
  212. true,
  213. false);
  214. }
  215. break;
  216. case "SS3":
  217. key = GetConsoleKey (terminator [0], values [0], ref mod, ref keyChar);
  218. newConsoleKeyInfo = new ConsoleKeyInfo (
  219. keyChar,
  220. key,
  221. (mod & ConsoleModifiers.Shift) != 0,
  222. (mod & ConsoleModifiers.Alt) != 0,
  223. (mod & ConsoleModifiers.Control) != 0);
  224. break;
  225. case "CSI":
  226. if (!string.IsNullOrEmpty (code) && code == "<")
  227. {
  228. GetMouse (cki, out buttonState, out pos, continuousButtonPressedHandler);
  229. isMouse = true;
  230. return;
  231. }
  232. if (escSeqRequests is { } && escSeqRequests.HasResponse (terminator))
  233. {
  234. isResponse = true;
  235. escSeqRequests.Remove (terminator);
  236. return;
  237. }
  238. if (!string.IsNullOrEmpty (terminator))
  239. {
  240. key = GetConsoleKey (terminator [0], values [0], ref mod, ref keyChar);
  241. if (key != 0 && values.Length > 1)
  242. {
  243. mod |= GetConsoleModifiers (values [1]);
  244. }
  245. newConsoleKeyInfo = new ConsoleKeyInfo (
  246. keyChar,
  247. key,
  248. (mod & ConsoleModifiers.Shift) != 0,
  249. (mod & ConsoleModifiers.Alt) != 0,
  250. (mod & ConsoleModifiers.Control) != 0);
  251. }
  252. else
  253. {
  254. // BUGBUG: See https://github.com/gui-cs/Terminal.Gui/issues/2803
  255. // This is caused by NetDriver depending on Console.KeyAvailable?
  256. throw new InvalidOperationException ("CSI response, but there's no terminator");
  257. //newConsoleKeyInfo = new ConsoleKeyInfo ('\0',
  258. // key,
  259. // (mod & ConsoleModifiers.Shift) != 0,
  260. // (mod & ConsoleModifiers.Alt) != 0,
  261. // (mod & ConsoleModifiers.Control) != 0);
  262. }
  263. break;
  264. }
  265. }
  266. #nullable enable
  267. /// <summary>
  268. /// Gets the c1Control used in the called escape sequence.
  269. /// </summary>
  270. /// <param name="c">The char used.</param>
  271. /// <returns>The c1Control.</returns>
  272. [Pure]
  273. public static string GetC1ControlChar (in char c)
  274. {
  275. // These control characters are used in the vtXXX emulation.
  276. return c switch
  277. {
  278. 'D' => "IND", // Index
  279. 'E' => "NEL", // Next Line
  280. 'H' => "HTS", // Tab Set
  281. 'M' => "RI", // Reverse Index
  282. 'N' => "SS2", // Single Shift Select of G2 Character Set: affects next character only
  283. 'O' => "SS3", // Single Shift Select of G3 Character Set: affects next character only
  284. 'P' => "DCS", // Device Control String
  285. 'V' => "SPA", // Start of Guarded Area
  286. 'W' => "EPA", // End of Guarded Area
  287. 'X' => "SOS", // Start of String
  288. 'Z' => "DECID", // Return Terminal ID Obsolete form of CSI c (DA)
  289. '[' => "CSI", // Control Sequence Introducer
  290. '\\' => "ST", // String Terminator
  291. ']' => "OSC", // Operating System Command
  292. '^' => "PM", // Privacy Message
  293. '_' => "APC", // Application Program Command
  294. _ => string.Empty
  295. };
  296. }
  297. /// <summary>
  298. /// Gets the <see cref="ConsoleKey"/> depending on terminating and value.
  299. /// </summary>
  300. /// <param name="terminator">
  301. /// The terminator indicating a reply to <see cref="CSI_SendDeviceAttributes"/> or
  302. /// <see cref="CSI_SendDeviceAttributes2"/>.
  303. /// </param>
  304. /// <param name="value">The value.</param>
  305. /// <param name="mod">The <see cref="ConsoleModifiers"/> which may change.</param>
  306. /// <param name="keyChar">Normally is '\0' but on some cases may need other value.</param>
  307. /// <returns>The <see cref="ConsoleKey"/> and probably the <see cref="ConsoleModifiers"/>.</returns>
  308. public static ConsoleKey GetConsoleKey (char terminator, string? value, ref ConsoleModifiers mod, ref char keyChar)
  309. {
  310. if (terminator == 'Z')
  311. {
  312. mod |= ConsoleModifiers.Shift;
  313. }
  314. if (terminator == 'l')
  315. {
  316. keyChar = '+';
  317. }
  318. if (terminator == 'm')
  319. {
  320. keyChar = '-';
  321. }
  322. return (terminator, value) switch
  323. {
  324. ('A', _) => ConsoleKey.UpArrow,
  325. ('B', _) => ConsoleKey.DownArrow,
  326. ('C', _) => ConsoleKey.RightArrow,
  327. ('D', _) => ConsoleKey.LeftArrow,
  328. ('F', _) => ConsoleKey.End,
  329. ('H', _) => ConsoleKey.Home,
  330. ('P', _) => ConsoleKey.F1,
  331. ('Q', _) => ConsoleKey.F2,
  332. ('R', _) => ConsoleKey.F3,
  333. ('S', _) => ConsoleKey.F4,
  334. ('Z', _) => ConsoleKey.Tab,
  335. ('~', "2") => ConsoleKey.Insert,
  336. ('~', "3") => ConsoleKey.Delete,
  337. ('~', "5") => ConsoleKey.PageUp,
  338. ('~', "6") => ConsoleKey.PageDown,
  339. ('~', "15") => ConsoleKey.F5,
  340. ('~', "17") => ConsoleKey.F6,
  341. ('~', "18") => ConsoleKey.F7,
  342. ('~', "19") => ConsoleKey.F8,
  343. ('~', "20") => ConsoleKey.F9,
  344. ('~', "21") => ConsoleKey.F10,
  345. ('~', "23") => ConsoleKey.F11,
  346. ('~', "24") => ConsoleKey.F12,
  347. ('l', _) => ConsoleKey.Add,
  348. ('m', _) => ConsoleKey.Subtract,
  349. ('p', _) => ConsoleKey.Insert,
  350. ('q', _) => ConsoleKey.End,
  351. ('r', _) => ConsoleKey.DownArrow,
  352. ('s', _) => ConsoleKey.PageDown,
  353. ('t', _) => ConsoleKey.LeftArrow,
  354. ('u', _) => ConsoleKey.Clear,
  355. ('v', _) => ConsoleKey.RightArrow,
  356. ('w', _) => ConsoleKey.Home,
  357. ('x', _) => ConsoleKey.UpArrow,
  358. ('y', _) => ConsoleKey.PageUp,
  359. (_, _) => 0
  360. };
  361. }
  362. /// <summary>
  363. /// Gets the <see cref="ConsoleModifiers"/> from the value.
  364. /// </summary>
  365. /// <param name="value">The value.</param>
  366. /// <returns>The <see cref="ConsoleModifiers"/> or zero.</returns>
  367. public static ConsoleModifiers GetConsoleModifiers (string? value)
  368. {
  369. return value switch
  370. {
  371. "2" => ConsoleModifiers.Shift,
  372. "3" => ConsoleModifiers.Alt,
  373. "4" => ConsoleModifiers.Shift | ConsoleModifiers.Alt,
  374. "5" => ConsoleModifiers.Control,
  375. "6" => ConsoleModifiers.Shift | ConsoleModifiers.Control,
  376. "7" => ConsoleModifiers.Alt | ConsoleModifiers.Control,
  377. "8" => ConsoleModifiers.Shift | ConsoleModifiers.Alt | ConsoleModifiers.Control,
  378. _ => 0
  379. };
  380. }
  381. #nullable restore
  382. /// <summary>
  383. /// Gets all the needed information about an escape sequence.
  384. /// </summary>
  385. /// <param name="kChar">The array with all chars.</param>
  386. /// <returns>
  387. /// The c1Control returned by <see cref="GetC1ControlChar"/>, code, values and terminating.
  388. /// </returns>
  389. public static (string c1Control, string code, string [] values, string terminating) GetEscapeResult (char [] kChar)
  390. {
  391. if (kChar is null || kChar.Length == 0)
  392. {
  393. return (null, null, null, null);
  394. }
  395. if (kChar [0] != KeyEsc)
  396. {
  397. throw new InvalidOperationException ("Invalid escape character!");
  398. }
  399. if (kChar.Length == 1)
  400. {
  401. return ("ESC", null, null, null);
  402. }
  403. if (kChar.Length == 2)
  404. {
  405. return ("ESC", null, null, kChar [1].ToString ());
  406. }
  407. string c1Control = GetC1ControlChar (kChar [1]);
  408. string code = null;
  409. int nSep = kChar.Count (static x => x == ';') + 1;
  410. var values = new string [nSep];
  411. var valueIdx = 0;
  412. var terminating = string.Empty;
  413. for (var i = 2; i < kChar.Length; i++)
  414. {
  415. char c = kChar [i];
  416. if (char.IsDigit (c))
  417. {
  418. // PERF: Ouch
  419. values [valueIdx] += c.ToString ();
  420. }
  421. else if (c == ';')
  422. {
  423. valueIdx++;
  424. }
  425. else if (valueIdx == nSep - 1 || i == kChar.Length - 1)
  426. {
  427. // PERF: Ouch
  428. terminating += c.ToString ();
  429. }
  430. else
  431. {
  432. // PERF: Ouch
  433. code += c.ToString ();
  434. }
  435. }
  436. return (c1Control, code, values, terminating);
  437. }
  438. /// <summary>
  439. /// A helper to get only the <see cref="ConsoleKeyInfo.KeyChar"/> from the <see cref="ConsoleKeyInfo"/> array.
  440. /// </summary>
  441. /// <param name="cki"></param>
  442. /// <returns>The char array of the escape sequence.</returns>
  443. // PERF: This is expensive
  444. public static char [] GetKeyCharArray (ConsoleKeyInfo [] cki)
  445. {
  446. char [] kChar = { };
  447. var length = 0;
  448. foreach (ConsoleKeyInfo kc in cki)
  449. {
  450. length++;
  451. Array.Resize (ref kChar, length);
  452. kChar [length - 1] = kc.KeyChar;
  453. }
  454. return kChar;
  455. }
  456. /// <summary>
  457. /// Gets the <see cref="MouseFlags"/> mouse button flags and the position.
  458. /// </summary>
  459. /// <param name="cki">The <see cref="ConsoleKeyInfo"/> array.</param>
  460. /// <param name="mouseFlags">The mouse button flags.</param>
  461. /// <param name="pos">The mouse position.</param>
  462. /// <param name="continuousButtonPressedHandler">The handler that will process the event.</param>
  463. public static void GetMouse (
  464. ConsoleKeyInfo [] cki,
  465. out List<MouseFlags> mouseFlags,
  466. out Point pos,
  467. Action<MouseFlags, Point> continuousButtonPressedHandler
  468. )
  469. {
  470. MouseFlags buttonState = 0;
  471. pos = Point.Empty;
  472. var buttonCode = 0;
  473. var foundButtonCode = false;
  474. var foundPoint = 0;
  475. string value = string.Empty;
  476. char [] kChar = GetKeyCharArray (cki);
  477. // PERF: This loop could benefit from use of Spans and other strategies to avoid copies.
  478. //System.Diagnostics.Debug.WriteLine ($"kChar: {new string (kChar)}");
  479. for (var i = 0; i < kChar.Length; i++)
  480. {
  481. // PERF: Copy
  482. char c = kChar [i];
  483. if (c == '<')
  484. {
  485. foundButtonCode = true;
  486. }
  487. else if (foundButtonCode && c != ';')
  488. {
  489. // PERF: Ouch
  490. value += c.ToString ();
  491. }
  492. else if (c == ';')
  493. {
  494. if (foundButtonCode)
  495. {
  496. foundButtonCode = false;
  497. buttonCode = int.Parse (value);
  498. }
  499. if (foundPoint == 1)
  500. {
  501. pos.X = int.Parse (value) - 1;
  502. }
  503. value = string.Empty;
  504. foundPoint++;
  505. }
  506. else if (foundPoint > 0 && c != 'm' && c != 'M')
  507. {
  508. value += c.ToString ();
  509. }
  510. else if (c == 'm' || c == 'M')
  511. {
  512. //pos.Y = int.Parse (value) + Console.WindowTop - 1;
  513. pos.Y = int.Parse (value) - 1;
  514. switch (buttonCode)
  515. {
  516. case 0:
  517. case 8:
  518. case 16:
  519. case 24:
  520. case 32:
  521. case 36:
  522. case 40:
  523. case 48:
  524. case 56:
  525. buttonState = c == 'M'
  526. ? MouseFlags.Button1Pressed
  527. : MouseFlags.Button1Released;
  528. break;
  529. case 1:
  530. case 9:
  531. case 17:
  532. case 25:
  533. case 33:
  534. case 37:
  535. case 41:
  536. case 45:
  537. case 49:
  538. case 53:
  539. case 57:
  540. case 61:
  541. buttonState = c == 'M'
  542. ? MouseFlags.Button2Pressed
  543. : MouseFlags.Button2Released;
  544. break;
  545. case 2:
  546. case 10:
  547. case 14:
  548. case 18:
  549. case 22:
  550. case 26:
  551. case 30:
  552. case 34:
  553. case 42:
  554. case 46:
  555. case 50:
  556. case 54:
  557. case 58:
  558. case 62:
  559. buttonState = c == 'M'
  560. ? MouseFlags.Button3Pressed
  561. : MouseFlags.Button3Released;
  562. break;
  563. case 35:
  564. //// Needed for Windows OS
  565. //if (isButtonPressed && c == 'm'
  566. // && (lastMouseEvent.ButtonState == MouseFlags.Button1Pressed
  567. // || lastMouseEvent.ButtonState == MouseFlags.Button2Pressed
  568. // || lastMouseEvent.ButtonState == MouseFlags.Button3Pressed)) {
  569. // switch (lastMouseEvent.ButtonState) {
  570. // case MouseFlags.Button1Pressed:
  571. // buttonState = MouseFlags.Button1Released;
  572. // break;
  573. // case MouseFlags.Button2Pressed:
  574. // buttonState = MouseFlags.Button2Released;
  575. // break;
  576. // case MouseFlags.Button3Pressed:
  577. // buttonState = MouseFlags.Button3Released;
  578. // break;
  579. // }
  580. //} else {
  581. // buttonState = MouseFlags.ReportMousePosition;
  582. //}
  583. //break;
  584. case 39:
  585. case 43:
  586. case 47:
  587. case 51:
  588. case 55:
  589. case 59:
  590. case 63:
  591. buttonState = MouseFlags.ReportMousePosition;
  592. break;
  593. case 64:
  594. buttonState = MouseFlags.WheeledUp;
  595. break;
  596. case 65:
  597. buttonState = MouseFlags.WheeledDown;
  598. break;
  599. case 68:
  600. case 72:
  601. case 80:
  602. buttonState = MouseFlags.WheeledLeft; // Shift/Ctrl+WheeledUp
  603. break;
  604. case 69:
  605. case 73:
  606. case 81:
  607. buttonState = MouseFlags.WheeledRight; // Shift/Ctrl+WheeledDown
  608. break;
  609. }
  610. // Modifiers.
  611. switch (buttonCode)
  612. {
  613. case 8:
  614. case 9:
  615. case 10:
  616. case 43:
  617. buttonState |= MouseFlags.ButtonAlt;
  618. break;
  619. case 14:
  620. case 47:
  621. buttonState |= MouseFlags.ButtonAlt | MouseFlags.ButtonShift;
  622. break;
  623. case 16:
  624. case 17:
  625. case 18:
  626. case 51:
  627. buttonState |= MouseFlags.ButtonCtrl;
  628. break;
  629. case 22:
  630. case 55:
  631. buttonState |= MouseFlags.ButtonCtrl | MouseFlags.ButtonShift;
  632. break;
  633. case 24:
  634. case 25:
  635. case 26:
  636. case 59:
  637. buttonState |= MouseFlags.ButtonCtrl | MouseFlags.ButtonAlt;
  638. break;
  639. case 30:
  640. case 63:
  641. buttonState |= MouseFlags.ButtonCtrl | MouseFlags.ButtonShift | MouseFlags.ButtonAlt;
  642. break;
  643. case 32:
  644. case 33:
  645. case 34:
  646. buttonState |= MouseFlags.ReportMousePosition;
  647. break;
  648. case 36:
  649. case 37:
  650. buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonShift;
  651. break;
  652. case 39:
  653. case 68:
  654. case 69:
  655. buttonState |= MouseFlags.ButtonShift;
  656. break;
  657. case 40:
  658. case 41:
  659. case 42:
  660. buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonAlt;
  661. break;
  662. case 45:
  663. case 46:
  664. buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonAlt | MouseFlags.ButtonShift;
  665. break;
  666. case 48:
  667. case 49:
  668. case 50:
  669. buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonCtrl;
  670. break;
  671. case 53:
  672. case 54:
  673. buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonCtrl | MouseFlags.ButtonShift;
  674. break;
  675. case 56:
  676. case 57:
  677. case 58:
  678. buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonCtrl | MouseFlags.ButtonAlt;
  679. break;
  680. case 61:
  681. case 62:
  682. buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonCtrl | MouseFlags.ButtonShift | MouseFlags.ButtonAlt;
  683. break;
  684. }
  685. }
  686. }
  687. mouseFlags = [MouseFlags.AllEvents];
  688. if (lastMouseButtonPressed != null
  689. && !isButtonPressed
  690. && !buttonState.HasFlag (MouseFlags.ReportMousePosition)
  691. && !buttonState.HasFlag (MouseFlags.Button1Released)
  692. && !buttonState.HasFlag (MouseFlags.Button2Released)
  693. && !buttonState.HasFlag (MouseFlags.Button3Released)
  694. && !buttonState.HasFlag (MouseFlags.Button4Released))
  695. {
  696. lastMouseButtonPressed = null;
  697. isButtonPressed = false;
  698. }
  699. if ((!isButtonClicked
  700. && !isButtonDoubleClicked
  701. && (buttonState == MouseFlags.Button1Pressed
  702. || buttonState == MouseFlags.Button2Pressed
  703. || buttonState == MouseFlags.Button3Pressed
  704. || buttonState == MouseFlags.Button4Pressed)
  705. && lastMouseButtonPressed is null)
  706. || (isButtonPressed && lastMouseButtonPressed is { } && buttonState.HasFlag (MouseFlags.ReportMousePosition)))
  707. {
  708. mouseFlags [0] = buttonState;
  709. lastMouseButtonPressed = buttonState;
  710. isButtonPressed = true;
  711. point = pos;
  712. if ((mouseFlags [0] & MouseFlags.ReportMousePosition) == 0)
  713. {
  714. Application.MainLoop.AddIdle (
  715. () =>
  716. {
  717. // INTENT: What's this trying to do?
  718. // The task itself is not awaited.
  719. Task.Run (
  720. async () => await ProcessContinuousButtonPressedAsync (
  721. buttonState,
  722. continuousButtonPressedHandler));
  723. return false;
  724. });
  725. }
  726. else if (mouseFlags [0].HasFlag (MouseFlags.ReportMousePosition))
  727. {
  728. point = pos;
  729. // The isButtonPressed must always be true, otherwise we can lose the feature
  730. // If mouse flags has ReportMousePosition this feature won't run
  731. // but is always prepared with the new location
  732. //isButtonPressed = false;
  733. }
  734. }
  735. else if (isButtonDoubleClicked
  736. && (buttonState == MouseFlags.Button1Pressed
  737. || buttonState == MouseFlags.Button2Pressed
  738. || buttonState == MouseFlags.Button3Pressed
  739. || buttonState == MouseFlags.Button4Pressed))
  740. {
  741. mouseFlags [0] = GetButtonTripleClicked (buttonState);
  742. isButtonDoubleClicked = false;
  743. isButtonTripleClicked = true;
  744. }
  745. else if (isButtonClicked
  746. && (buttonState == MouseFlags.Button1Pressed
  747. || buttonState == MouseFlags.Button2Pressed
  748. || buttonState == MouseFlags.Button3Pressed
  749. || buttonState == MouseFlags.Button4Pressed))
  750. {
  751. mouseFlags [0] = GetButtonDoubleClicked (buttonState);
  752. isButtonClicked = false;
  753. isButtonDoubleClicked = true;
  754. Application.MainLoop.AddIdle (
  755. () =>
  756. {
  757. Task.Run (async () => await ProcessButtonDoubleClickedAsync ());
  758. return false;
  759. });
  760. }
  761. //else if (isButtonReleased && !isButtonClicked && buttonState == MouseFlags.ReportMousePosition) {
  762. // mouseFlag [0] = GetButtonClicked ((MouseFlags)lastMouseButtonReleased);
  763. // lastMouseButtonReleased = null;
  764. // isButtonReleased = false;
  765. // isButtonClicked = true;
  766. // Application.MainLoop.AddIdle (() => {
  767. // Task.Run (async () => await ProcessButtonClickedAsync ());
  768. // return false;
  769. // });
  770. //}
  771. else if (!isButtonClicked
  772. && !isButtonDoubleClicked
  773. && (buttonState == MouseFlags.Button1Released
  774. || buttonState == MouseFlags.Button2Released
  775. || buttonState == MouseFlags.Button3Released
  776. || buttonState == MouseFlags.Button4Released))
  777. {
  778. mouseFlags [0] = buttonState;
  779. isButtonPressed = false;
  780. if (isButtonTripleClicked)
  781. {
  782. isButtonTripleClicked = false;
  783. }
  784. else if (pos.X == point?.X && pos.Y == point?.Y)
  785. {
  786. mouseFlags.Add (GetButtonClicked (buttonState));
  787. isButtonClicked = true;
  788. Application.MainLoop.AddIdle (
  789. () =>
  790. {
  791. Task.Run (async () => await ProcessButtonClickedAsync ());
  792. return false;
  793. });
  794. }
  795. point = pos;
  796. //if ((lastMouseButtonPressed & MouseFlags.ReportMousePosition) == 0) {
  797. // lastMouseButtonReleased = buttonState;
  798. // isButtonPressed = false;
  799. // isButtonReleased = true;
  800. //} else {
  801. // lastMouseButtonPressed = null;
  802. // isButtonPressed = false;
  803. //}
  804. }
  805. else if (buttonState == MouseFlags.WheeledUp)
  806. {
  807. mouseFlags [0] = MouseFlags.WheeledUp;
  808. }
  809. else if (buttonState == MouseFlags.WheeledDown)
  810. {
  811. mouseFlags [0] = MouseFlags.WheeledDown;
  812. }
  813. else if (buttonState == MouseFlags.WheeledLeft)
  814. {
  815. mouseFlags [0] = MouseFlags.WheeledLeft;
  816. }
  817. else if (buttonState == MouseFlags.WheeledRight)
  818. {
  819. mouseFlags [0] = MouseFlags.WheeledRight;
  820. }
  821. else if (buttonState == MouseFlags.ReportMousePosition)
  822. {
  823. mouseFlags [0] = MouseFlags.ReportMousePosition;
  824. }
  825. else
  826. {
  827. mouseFlags [0] = buttonState;
  828. //foreach (var flag in buttonState.GetUniqueFlags()) {
  829. // mouseFlag [0] |= flag;
  830. //}
  831. }
  832. mouseFlags [0] = SetControlKeyStates (buttonState, mouseFlags [0]);
  833. //buttonState = mouseFlags;
  834. //System.Diagnostics.Debug.WriteLine ($"buttonState: {buttonState} X: {pos.X} Y: {pos.Y}");
  835. //foreach (var mf in mouseFlags) {
  836. // System.Diagnostics.Debug.WriteLine ($"mouseFlags: {mf} X: {pos.X} Y: {pos.Y}");
  837. //}
  838. }
  839. /// <summary>
  840. /// Ensures a console key is mapped to one that works correctly with ANSI escape sequences.
  841. /// </summary>
  842. /// <param name="consoleKeyInfo">The <see cref="ConsoleKeyInfo"/>.</param>
  843. /// <returns>The <see cref="ConsoleKeyInfo"/> modified.</returns>
  844. public static ConsoleKeyInfo MapConsoleKeyInfo (ConsoleKeyInfo consoleKeyInfo)
  845. {
  846. ConsoleKeyInfo newConsoleKeyInfo = consoleKeyInfo;
  847. ConsoleKey key;
  848. char keyChar = consoleKeyInfo.KeyChar;
  849. switch ((uint)keyChar)
  850. {
  851. case 0:
  852. if (consoleKeyInfo.Key == (ConsoleKey)64)
  853. { // Ctrl+Space in Windows.
  854. newConsoleKeyInfo = new ConsoleKeyInfo (
  855. ' ',
  856. ConsoleKey.Spacebar,
  857. (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0,
  858. (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
  859. (consoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0);
  860. }
  861. break;
  862. case uint n when n > 0 && n <= KeyEsc:
  863. if (consoleKeyInfo.Key == 0 && consoleKeyInfo.KeyChar == '\r')
  864. {
  865. key = ConsoleKey.Enter;
  866. newConsoleKeyInfo = new ConsoleKeyInfo (
  867. consoleKeyInfo.KeyChar,
  868. key,
  869. (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0,
  870. (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
  871. (consoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0);
  872. }
  873. else if (consoleKeyInfo.Key == 0)
  874. {
  875. key = (ConsoleKey)(char)(consoleKeyInfo.KeyChar + (uint)ConsoleKey.A - 1);
  876. newConsoleKeyInfo = new ConsoleKeyInfo (
  877. (char)key,
  878. key,
  879. (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0,
  880. (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
  881. true);
  882. }
  883. break;
  884. case 127: // DEL
  885. newConsoleKeyInfo = new ConsoleKeyInfo (
  886. consoleKeyInfo.KeyChar,
  887. ConsoleKey.Backspace,
  888. (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0,
  889. (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
  890. (consoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0);
  891. break;
  892. default:
  893. newConsoleKeyInfo = consoleKeyInfo;
  894. break;
  895. }
  896. return newConsoleKeyInfo;
  897. }
  898. /// <summary>
  899. /// A helper to resize the <see cref="ConsoleKeyInfo"/> as needed.
  900. /// </summary>
  901. /// <param name="consoleKeyInfo">The <see cref="ConsoleKeyInfo"/>.</param>
  902. /// <param name="cki">The <see cref="ConsoleKeyInfo"/> array to resize.</param>
  903. /// <returns>The <see cref="ConsoleKeyInfo"/> resized.</returns>
  904. public static ConsoleKeyInfo [] ResizeArray (ConsoleKeyInfo consoleKeyInfo, ConsoleKeyInfo [] cki)
  905. {
  906. Array.Resize (ref cki, cki is null ? 1 : cki.Length + 1);
  907. cki [cki.Length - 1] = consoleKeyInfo;
  908. return cki;
  909. }
  910. private static MouseFlags GetButtonClicked (MouseFlags mouseFlag)
  911. {
  912. MouseFlags mf = default;
  913. switch (mouseFlag)
  914. {
  915. case MouseFlags.Button1Released:
  916. mf = MouseFlags.Button1Clicked;
  917. break;
  918. case MouseFlags.Button2Released:
  919. mf = MouseFlags.Button2Clicked;
  920. break;
  921. case MouseFlags.Button3Released:
  922. mf = MouseFlags.Button3Clicked;
  923. break;
  924. }
  925. return mf;
  926. }
  927. private static MouseFlags GetButtonDoubleClicked (MouseFlags mouseFlag)
  928. {
  929. MouseFlags mf = default;
  930. switch (mouseFlag)
  931. {
  932. case MouseFlags.Button1Pressed:
  933. mf = MouseFlags.Button1DoubleClicked;
  934. break;
  935. case MouseFlags.Button2Pressed:
  936. mf = MouseFlags.Button2DoubleClicked;
  937. break;
  938. case MouseFlags.Button3Pressed:
  939. mf = MouseFlags.Button3DoubleClicked;
  940. break;
  941. }
  942. return mf;
  943. }
  944. private static MouseFlags GetButtonTripleClicked (MouseFlags mouseFlag)
  945. {
  946. MouseFlags mf = default;
  947. switch (mouseFlag)
  948. {
  949. case MouseFlags.Button1Pressed:
  950. mf = MouseFlags.Button1TripleClicked;
  951. break;
  952. case MouseFlags.Button2Pressed:
  953. mf = MouseFlags.Button2TripleClicked;
  954. break;
  955. case MouseFlags.Button3Pressed:
  956. mf = MouseFlags.Button3TripleClicked;
  957. break;
  958. }
  959. return mf;
  960. }
  961. private static async Task ProcessButtonClickedAsync ()
  962. {
  963. await Task.Delay (300);
  964. isButtonClicked = false;
  965. }
  966. private static async Task ProcessButtonDoubleClickedAsync ()
  967. {
  968. await Task.Delay (300);
  969. isButtonDoubleClicked = false;
  970. }
  971. private static async Task ProcessContinuousButtonPressedAsync (MouseFlags mouseFlag, Action<MouseFlags, Point> continuousButtonPressedHandler)
  972. {
  973. // PERF: Pause and poll in a hot loop.
  974. // This should be replaced with event dispatch and a synchronization primitive such as AutoResetEvent.
  975. // Will make a massive difference in responsiveness.
  976. while (isButtonPressed)
  977. {
  978. await Task.Delay (100);
  979. View view = Application.WantContinuousButtonPressedView;
  980. if (view is null)
  981. {
  982. break;
  983. }
  984. if (isButtonPressed && lastMouseButtonPressed is { } && (mouseFlag & MouseFlags.ReportMousePosition) == 0)
  985. {
  986. Application.Invoke (() => continuousButtonPressedHandler (mouseFlag, point ?? Point.Empty));
  987. }
  988. }
  989. }
  990. private static MouseFlags SetControlKeyStates (MouseFlags buttonState, MouseFlags mouseFlag)
  991. {
  992. if ((buttonState & MouseFlags.ButtonCtrl) != 0 && (mouseFlag & MouseFlags.ButtonCtrl) == 0)
  993. {
  994. mouseFlag |= MouseFlags.ButtonCtrl;
  995. }
  996. if ((buttonState & MouseFlags.ButtonShift) != 0 && (mouseFlag & MouseFlags.ButtonShift) == 0)
  997. {
  998. mouseFlag |= MouseFlags.ButtonShift;
  999. }
  1000. if ((buttonState & MouseFlags.ButtonAlt) != 0 && (mouseFlag & MouseFlags.ButtonAlt) == 0)
  1001. {
  1002. mouseFlag |= MouseFlags.ButtonAlt;
  1003. }
  1004. return mouseFlag;
  1005. }
  1006. #region Cursor
  1007. //ESC [ M - RI Reverse Index – Performs the reverse operation of \n, moves cursor up one line, maintains horizontal position, scrolls buffer if necessary*
  1008. /// <summary>
  1009. /// ESC [ 7 - Save Cursor Position in Memory**
  1010. /// </summary>
  1011. public static readonly string CSI_SaveCursorPosition = CSI + "7";
  1012. /// <summary>
  1013. /// ESC [ 8 - DECSR Restore Cursor Position from Memory**
  1014. /// </summary>
  1015. public static readonly string CSI_RestoreCursorPosition = CSI + "8";
  1016. /// <summary>
  1017. /// ESC [ 8 ; height ; width t - Set Terminal Window Size
  1018. /// https://terminalguide.namepad.de/seq/csi_st-8/
  1019. /// </summary>
  1020. public static string CSI_SetTerminalWindowSize (int height, int width) { return $"{CSI}8;{height};{width}t"; }
  1021. //ESC [ < n > A - CUU - Cursor Up Cursor up by < n >
  1022. //ESC [ < n > B - CUD - Cursor Down Cursor down by < n >
  1023. //ESC [ < n > C - CUF - Cursor Forward Cursor forward (Right) by < n >
  1024. //ESC [ < n > D - CUB - Cursor Backward Cursor backward (Left) by < n >
  1025. //ESC [ < n > E - CNL - Cursor Next Line - Cursor down < n > lines from current position
  1026. //ESC [ < n > F - CPL - Cursor Previous Line Cursor up < n > lines from current position
  1027. //ESC [ < n > G - CHA - Cursor Horizontal Absolute Cursor moves to < n > th position horizontally in the current line
  1028. //ESC [ < n > d - VPA - Vertical Line Position Absolute Cursor moves to the < n > th position vertically in the current column
  1029. /// <summary>
  1030. /// ESC [ y ; x H - CUP Cursor Position - Cursor moves to x ; y coordinate within the viewport, where x is the column
  1031. /// of the y line
  1032. /// </summary>
  1033. /// <param name="row">Origin is (1,1).</param>
  1034. /// <param name="col">Origin is (1,1).</param>
  1035. /// <returns></returns>
  1036. public static string CSI_SetCursorPosition (int row, int col) { return $"{CSI}{row};{col}H"; }
  1037. //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
  1038. //ESC [ s - ANSISYSSC Save Cursor – Ansi.sys emulation **With no parameters, performs a save cursor operation like DECSC
  1039. //ESC [ u - ANSISYSRC Restore Cursor – Ansi.sys emulation **With no parameters, performs a restore cursor operation like DECRC
  1040. //ESC [ ? 12 h - ATT160 Text Cursor Enable Blinking Start the cursor blinking
  1041. //ESC [ ? 12 l - ATT160 Text Cursor Disable Blinking Stop blinking the cursor
  1042. /// <summary>
  1043. /// ESC [ ? 25 h - DECTCEM Text Cursor Enable Mode Show Show the cursor
  1044. /// </summary>
  1045. public static readonly string CSI_ShowCursor = CSI + "?25h";
  1046. /// <summary>
  1047. /// ESC [ ? 25 l - DECTCEM Text Cursor Enable Mode Hide Hide the cursor
  1048. /// </summary>
  1049. public static readonly string CSI_HideCursor = CSI + "?25l";
  1050. //ESC [ ? 12 h - ATT160 Text Cursor Enable Blinking Start the cursor blinking
  1051. //ESC [ ? 12 l - ATT160 Text Cursor Disable Blinking Stop blinking the cursor
  1052. //ESC [ ? 25 h - DECTCEM Text Cursor Enable Mode Show Show the cursor
  1053. //ESC [ ? 25 l - DECTCEM Text Cursor Enable Mode Hide Hide the cursor
  1054. /// <summary>
  1055. /// Styles for ANSI ESC "[x q" - Set Cursor Style
  1056. /// </summary>
  1057. public enum DECSCUSR_Style
  1058. {
  1059. /// <summary>
  1060. /// DECSCUSR - User Shape - Default cursor shape configured by the user
  1061. /// </summary>
  1062. UserShape = 0,
  1063. /// <summary>
  1064. /// DECSCUSR - Blinking Block - Blinking block cursor shape
  1065. /// </summary>
  1066. BlinkingBlock = 1,
  1067. /// <summary>
  1068. /// DECSCUSR - Steady Block - Steady block cursor shape
  1069. /// </summary>
  1070. SteadyBlock = 2,
  1071. /// <summary>
  1072. /// DECSCUSR - Blinking Underline - Blinking underline cursor shape
  1073. /// </summary>
  1074. BlinkingUnderline = 3,
  1075. /// <summary>
  1076. /// DECSCUSR - Steady Underline - Steady underline cursor shape
  1077. /// </summary>
  1078. SteadyUnderline = 4,
  1079. /// <summary>
  1080. /// DECSCUSR - Blinking Bar - Blinking bar cursor shape
  1081. /// </summary>
  1082. BlinkingBar = 5,
  1083. /// <summary>
  1084. /// DECSCUSR - Steady Bar - Steady bar cursor shape
  1085. /// </summary>
  1086. SteadyBar = 6
  1087. }
  1088. /// <summary>
  1089. /// ESC [ n SP q - Select Cursor Style (DECSCUSR)
  1090. /// https://terminalguide.namepad.de/seq/csi_sq_t_space/
  1091. /// </summary>
  1092. /// <param name="style"></param>
  1093. /// <returns></returns>
  1094. public static string CSI_SetCursorStyle (DECSCUSR_Style style) { return $"{CSI}{(int)style} q"; }
  1095. #endregion
  1096. #region Colors
  1097. /// <summary>
  1098. /// ESC [ (n) m - SGR - Set Graphics Rendition - Set the format of the screen and text as specified by (n)
  1099. /// This command is special in that the (n) position can accept between 0 and 16 parameters separated by semicolons.
  1100. /// When no parameters are specified, it is treated the same as a single 0 parameter.
  1101. /// https://terminalguide.namepad.de/seq/csi_sm/
  1102. /// </summary>
  1103. public static string CSI_SetGraphicsRendition (params int [] parameters) { return $"{CSI}{string.Join (";", parameters)}m"; }
  1104. /// <summary>
  1105. /// ESC [ (n) m - Uses <see cref="CSI_SetGraphicsRendition(int[])"/> to set the foreground color.
  1106. /// </summary>
  1107. /// <param name="code">One of the 16 color codes.</param>
  1108. /// <returns></returns>
  1109. public static string CSI_SetForegroundColor (AnsiColorCode code) { return CSI_SetGraphicsRendition ((int)code); }
  1110. /// <summary>
  1111. /// ESC [ (n) m - Uses <see cref="CSI_SetGraphicsRendition(int[])"/> to set the background color.
  1112. /// </summary>
  1113. /// <param name="code">One of the 16 color codes.</param>
  1114. /// <returns></returns>
  1115. public static string CSI_SetBackgroundColor (AnsiColorCode code) { return CSI_SetGraphicsRendition ((int)code + 10); }
  1116. /// <summary>
  1117. /// ESC[38;5;{id}m - Set foreground color (256 colors)
  1118. /// </summary>
  1119. public static string CSI_SetForegroundColor256 (int color) { return $"{CSI}38;5;{color}m"; }
  1120. /// <summary>
  1121. /// ESC[48;5;{id}m - Set background color (256 colors)
  1122. /// </summary>
  1123. public static string CSI_SetBackgroundColor256 (int color) { return $"{CSI}48;5;{color}m"; }
  1124. /// <summary>
  1125. /// ESC[38;2;{r};{g};{b}m Set foreground color as RGB.
  1126. /// </summary>
  1127. public static string CSI_SetForegroundColorRGB (int r, int g, int b) { return $"{CSI}38;2;{r};{g};{b}m"; }
  1128. /// <summary>
  1129. /// ESC[48;2;{r};{g};{b}m Set background color as RGB.
  1130. /// </summary>
  1131. public static string CSI_SetBackgroundColorRGB (int r, int g, int b) { return $"{CSI}48;2;{r};{g};{b}m"; }
  1132. #endregion
  1133. #region Requests
  1134. /// <summary>
  1135. /// ESC [ ? 6 n - Request Cursor Position Report (?) (DECXCPR)
  1136. /// https://terminalguide.namepad.de/seq/csi_sn__p-6/
  1137. /// </summary>
  1138. public static readonly string CSI_RequestCursorPositionReport = CSI + "?6n";
  1139. /// <summary>
  1140. /// The terminal reply to <see cref="CSI_RequestCursorPositionReport"/>. ESC [ ? (y) ; (x) R
  1141. /// </summary>
  1142. public const string CSI_RequestCursorPositionReport_Terminator = "R";
  1143. /// <summary>
  1144. /// ESC [ 0 c - Send Device Attributes (Primary DA)
  1145. /// https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Application-Program-Command-functions
  1146. /// https://www.xfree86.org/current/ctlseqs.html
  1147. /// Windows Terminal v1.17 and below emits “\x1b[?1;0c”, indicating "VT101 with No Options".
  1148. /// Windows Terminal v1.18+ emits: \x1b[?61;6;7;22;23;24;28;32;42c"
  1149. /// See https://github.com/microsoft/terminal/pull/14906
  1150. /// 61 - The device conforms to level 1 of the character cell display architecture
  1151. /// (See https://github.com/microsoft/terminal/issues/15693#issuecomment-1633304497)
  1152. /// 6 = Selective erase
  1153. /// 7 = Soft fonts
  1154. /// 22 = Color text
  1155. /// 23 = Greek character sets
  1156. /// 24 = Turkish character sets
  1157. /// 28 = Rectangular area operations
  1158. /// 32 = Text macros
  1159. /// 42 = ISO Latin-2 character set
  1160. /// </summary>
  1161. public static readonly string CSI_SendDeviceAttributes = CSI + "0c";
  1162. /// <summary>
  1163. /// ESC [ > 0 c - Send Device Attributes (Secondary DA)
  1164. /// Windows Terminal v1.18+ emits: "\x1b[>0;10;1c" (vt100, firmware version 1.0, vt220)
  1165. /// </summary>
  1166. public static readonly string CSI_SendDeviceAttributes2 = CSI + ">0c";
  1167. /// <summary>
  1168. /// The terminator indicating a reply to <see cref="CSI_SendDeviceAttributes"/> or
  1169. /// <see cref="CSI_SendDeviceAttributes2"/>
  1170. /// </summary>
  1171. public const string CSI_ReportDeviceAttributes_Terminator = "c";
  1172. /// <summary>
  1173. /// CSI 1 8 t | yes | yes | yes | report window size in chars
  1174. /// https://terminalguide.namepad.de/seq/csi_st-18/
  1175. /// </summary>
  1176. public static readonly string CSI_ReportTerminalSizeInChars = CSI + "18t";
  1177. /// <summary>
  1178. /// The terminator indicating a reply to <see cref="CSI_ReportTerminalSizeInChars"/> : ESC [ 8 ; height ; width t
  1179. /// </summary>
  1180. public const string CSI_ReportTerminalSizeInChars_Terminator = "t";
  1181. /// <summary>
  1182. /// The value of the response to <see cref="CSI_ReportTerminalSizeInChars"/> indicating value 1 and 2 are the terminal
  1183. /// size in chars.
  1184. /// </summary>
  1185. public const string CSI_ReportTerminalSizeInChars_ResponseValue = "8";
  1186. #endregion
  1187. }