EscSeqUtils.cs 53 KB

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