EscSeqUtils.cs 53 KB

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