EscSeqUtils.cs 53 KB

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