EscSeqUtils.cs 52 KB

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