EscSeqUtils.cs 54 KB

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