EscSeqUtils.cs 52 KB

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