EscSeqUtils.cs 53 KB

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