EscSeqUtils.cs 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066
  1. #nullable enable
  2. using System.Globalization;
  3. namespace Terminal.Gui;
  4. // QUESTION: Should this class be refactored into separate classes for:
  5. // QUESTION: CSI definitions
  6. // QUESTION: Primitives like DecodeEsqReq
  7. // QUESTION: Screen/Color/Cursor handling
  8. // QUESTION: Mouse handling
  9. // QUESTION: Keyboard handling
  10. /// <summary>
  11. /// Provides a platform-independent API for managing ANSI escape sequences.
  12. /// </summary>
  13. /// <remarks>
  14. /// Useful resources:
  15. /// * https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences
  16. /// * https://invisible-island.net/xterm/ctlseqs/ctlseqs.html
  17. /// * https://vt100.net/
  18. /// </remarks>
  19. public static class EscSeqUtils
  20. {
  21. // TODO: One type per file - Move this enum to a separate file.
  22. /// <summary>
  23. /// Options for ANSI ESC "[xJ" - Clears part of the screen.
  24. /// </summary>
  25. public enum ClearScreenOptions
  26. {
  27. /// <summary>
  28. /// If n is 0 (or missing), clear from cursor to end of screen.
  29. /// </summary>
  30. CursorToEndOfScreen = 0,
  31. /// <summary>
  32. /// If n is 1, clear from cursor to beginning of the screen.
  33. /// </summary>
  34. CursorToBeginningOfScreen = 1,
  35. /// <summary>
  36. /// If n is 2, clear entire screen (and moves cursor to upper left on DOS ANSI.SYS).
  37. /// </summary>
  38. EntireScreen = 2,
  39. /// <summary>
  40. /// If n is 3, clear entire screen and delete all lines saved in the scrollback buffer
  41. /// </summary>
  42. EntireScreenAndScrollbackBuffer = 3
  43. }
  44. // QUESTION: I wonder if EscSeqUtils.CSI_... should be more strongly typed such that this (and Terminator could be
  45. // QUESTION: public required CSIRequests Request { get; init; }
  46. // QUESTION: public required CSITerminators Terminator { get; init; }
  47. /// <summary>
  48. /// Escape key code (ASCII 27/0x1B).
  49. /// </summary>
  50. public const char KeyEsc = (char)KeyCode.Esc;
  51. /// <summary>
  52. /// ESC [ - The CSI (Control Sequence Introducer).
  53. /// </summary>
  54. public const string CSI = "\u001B[";
  55. /// <summary>
  56. /// ESC [ ? 1047 h - Activate xterm alternative buffer (no backscroll)
  57. /// </summary>
  58. /// <remarks>
  59. /// From
  60. /// https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Functions-using-CSI-_-ordered-by-the-final-character_s_
  61. /// Use Alternate Screen Buffer, xterm.
  62. /// </remarks>
  63. public static readonly string CSI_ActivateAltBufferNoBackscroll = CSI + "?1047h";
  64. /// <summary>
  65. /// ESC [ ? 1003 l - Disable any mouse event tracking.
  66. /// </summary>
  67. public static readonly string CSI_DisableAnyEventMouse = CSI + "?1003l";
  68. /// <summary>
  69. /// ESC [ ? 1006 l - Disable SGR (Select Graphic Rendition).
  70. /// </summary>
  71. public static readonly string CSI_DisableSgrExtModeMouse = CSI + "?1006l";
  72. /// <summary>
  73. /// ESC [ ? 1015 l - Disable URXVT (Unicode Extended Virtual Terminal).
  74. /// </summary>
  75. public static readonly string CSI_DisableUrxvtExtModeMouse = CSI + "?1015l";
  76. /// <summary>
  77. /// ESC [ ? 1003 h - Enable mouse event tracking.
  78. /// </summary>
  79. public static readonly string CSI_EnableAnyEventMouse = CSI + "?1003h";
  80. /// <summary>
  81. /// ESC [ ? 1006 h - Enable SGR (Select Graphic Rendition).
  82. /// </summary>
  83. public static readonly string CSI_EnableSgrExtModeMouse = CSI + "?1006h";
  84. /// <summary>
  85. /// ESC [ ? 1015 h - Enable URXVT (Unicode Extended Virtual Terminal).
  86. /// </summary>
  87. public static readonly string CSI_EnableUrxvtExtModeMouse = CSI + "?1015h";
  88. /// <summary>
  89. /// ESC [ ? 1047 l - 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, xterm. Clear the screen first if in the Alternate Screen Buffer.
  95. /// </remarks>
  96. public static readonly string CSI_RestoreAltBufferWithBackscroll = CSI + "?1047l";
  97. /// <summary>
  98. /// ESC [ ? 1049 l - Restore cursor position and restore xterm working buffer (with backscroll)
  99. /// </summary>
  100. /// <remarks>
  101. /// From
  102. /// https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Functions-using-CSI-_-ordered-by-the-final-character_s_
  103. /// Use Normal Screen Buffer and restore cursor as in DECRC, xterm.
  104. /// resource.This combines the effects of the 1047 and 1048 modes.
  105. /// </remarks>
  106. public static readonly string CSI_RestoreCursorAndRestoreAltBufferWithBackscroll = CSI + "?1049l";
  107. /// <summary>
  108. /// ESC [ ? 1049 h - Save cursor position and activate xterm alternative buffer (no backscroll)
  109. /// </summary>
  110. /// <remarks>
  111. /// From
  112. /// https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Functions-using-CSI-_-ordered-by-the-final-character_s_
  113. /// Save cursor as in DECSC, xterm. After saving the cursor, switch to the Alternate Screen Buffer,
  114. /// clearing it first.
  115. /// This control combines the effects of the 1047 and 1048 modes.
  116. /// Use this with terminfo-based applications rather than the 47 mode.
  117. /// </remarks>
  118. public static readonly string CSI_SaveCursorAndActivateAltBufferNoBackscroll = CSI + "?1049h";
  119. //private static bool isButtonReleased;
  120. private static bool _isButtonClicked;
  121. private static bool _isButtonDoubleClicked;
  122. //private static MouseFlags? lastMouseButtonReleased;
  123. // QUESTION: What's the difference between isButtonClicked and isButtonPressed?
  124. // Some clarity or comments would be handy, here.
  125. // It also seems like some enforcement of valid states might be a good idea.
  126. private static bool _isButtonPressed;
  127. private static bool _isButtonTripleClicked;
  128. private static MouseFlags? _lastMouseButtonPressed;
  129. private static Point? _point;
  130. /// <summary>
  131. /// Control sequence for disabling mouse events.
  132. /// </summary>
  133. public static readonly string CSI_DisableMouseEvents =
  134. CSI_DisableAnyEventMouse + CSI_DisableUrxvtExtModeMouse + CSI_DisableSgrExtModeMouse;
  135. /// <summary>
  136. /// Control sequence for enabling mouse events.
  137. /// </summary>
  138. public static readonly string CSI_EnableMouseEvents =
  139. CSI_EnableAnyEventMouse + CSI_EnableUrxvtExtModeMouse + CSI_EnableSgrExtModeMouse;
  140. /// <summary>
  141. /// ESC [ x J - Clears part of the screen. See <see cref="ClearScreenOptions"/>.
  142. /// </summary>
  143. /// <param name="option"></param>
  144. /// <returns></returns>
  145. public static string CSI_ClearScreen (ClearScreenOptions option) { return $"{CSI}{(int)option}J"; }
  146. /// <summary>
  147. /// Specify the incomplete <see cref="ConsoleKeyInfo"/> array not yet recognized as valid ANSI escape sequence.
  148. /// </summary>
  149. public static ConsoleKeyInfo []? IncompleteCkInfos { get; set; }
  150. /// <summary>
  151. /// Decodes an ANSI escape sequence.
  152. /// </summary>
  153. /// <param name="newConsoleKeyInfo">The <see cref="ConsoleKeyInfo"/> which may change.</param>
  154. /// <param name="key">The <see cref="ConsoleKey"/> which may change.</param>
  155. /// <param name="cki">The <see cref="ConsoleKeyInfo"/> array.</param>
  156. /// <param name="mod">The <see cref="ConsoleModifiers"/> which may change.</param>
  157. /// <param name="c1Control">The control returned by the <see cref="GetC1ControlChar"/> method.</param>
  158. /// <param name="code">The code returned by the <see cref="GetEscapeResult(char[])"/> method.</param>
  159. /// <param name="values">The values returned by the <see cref="GetEscapeResult(char[])"/> method.</param>
  160. /// <param name="terminator">The terminator returned by the <see cref="GetEscapeResult(char[])"/> method.</param>
  161. /// <param name="isMouse">Indicates if the escape sequence is a mouse event.</param>
  162. /// <param name="buttonState">The <see cref="MouseFlags"/> button state.</param>
  163. /// <param name="pos">The <see cref="MouseFlags"/> position.</param>
  164. /// <param name="isResponse">Indicates if the escape sequence is a response to a request.</param>
  165. /// <param name="continuousButtonPressedHandler">The handler that will process the event.</param>
  166. public static void DecodeEscSeq (
  167. ref ConsoleKeyInfo newConsoleKeyInfo,
  168. ref ConsoleKey key,
  169. ConsoleKeyInfo [] cki,
  170. ref ConsoleModifiers mod,
  171. out string c1Control,
  172. out string code,
  173. out string [] values,
  174. out string terminator,
  175. out bool isMouse,
  176. out List<MouseFlags> buttonState,
  177. out Point pos,
  178. out bool isResponse,
  179. Action<MouseFlags, Point>? continuousButtonPressedHandler
  180. )
  181. {
  182. char [] kChars = GetKeyCharArray (cki);
  183. (c1Control, code, values, terminator) = GetEscapeResult (kChars);
  184. isMouse = false;
  185. buttonState = [0];
  186. pos = default (Point);
  187. isResponse = false;
  188. var keyChar = '\0';
  189. switch (c1Control)
  190. {
  191. case "ESC":
  192. if (values is null && string.IsNullOrEmpty (terminator))
  193. {
  194. key = ConsoleKey.Escape;
  195. newConsoleKeyInfo = new (
  196. cki [0].KeyChar,
  197. key,
  198. (mod & ConsoleModifiers.Shift) != 0,
  199. (mod & ConsoleModifiers.Alt) != 0,
  200. (mod & ConsoleModifiers.Control) != 0);
  201. }
  202. else if ((uint)cki [1].KeyChar >= 1 && (uint)cki [1].KeyChar <= 26 && (uint)cki [1].KeyChar != '\n' && (uint)cki [1].KeyChar != '\r')
  203. {
  204. key = (ConsoleKey)(char)(cki [1].KeyChar + (uint)ConsoleKey.A - 1);
  205. mod = ConsoleModifiers.Alt | ConsoleModifiers.Control;
  206. newConsoleKeyInfo = new (
  207. cki [1].KeyChar,
  208. key,
  209. (mod & ConsoleModifiers.Shift) != 0,
  210. (mod & ConsoleModifiers.Alt) != 0,
  211. (mod & ConsoleModifiers.Control) != 0);
  212. }
  213. else if (cki [1].KeyChar >= 65 && cki [1].KeyChar <= 90)
  214. {
  215. key = (ConsoleKey)cki [1].KeyChar;
  216. mod = ConsoleModifiers.Shift | ConsoleModifiers.Alt;
  217. newConsoleKeyInfo = new (
  218. cki [1].KeyChar,
  219. (ConsoleKey)Math.Min ((uint)key, 255),
  220. (mod & ConsoleModifiers.Shift) != 0,
  221. (mod & ConsoleModifiers.Alt) != 0,
  222. (mod & ConsoleModifiers.Control) != 0);
  223. }
  224. else if (cki [1].KeyChar >= 97 && cki [1].KeyChar <= 122)
  225. {
  226. key = (ConsoleKey)cki [1].KeyChar.ToString ().ToUpper () [0];
  227. mod = ConsoleModifiers.Alt;
  228. newConsoleKeyInfo = new (
  229. cki [1].KeyChar,
  230. (ConsoleKey)Math.Min ((uint)key, 255),
  231. (mod & ConsoleModifiers.Shift) != 0,
  232. (mod & ConsoleModifiers.Alt) != 0,
  233. (mod & ConsoleModifiers.Control) != 0);
  234. }
  235. else if (cki [1].KeyChar is '\0' or ' ')
  236. {
  237. key = ConsoleKey.Spacebar;
  238. if (kChars.Length > 1 && kChars [1] == '\0')
  239. {
  240. mod = ConsoleModifiers.Alt | ConsoleModifiers.Control;
  241. }
  242. else
  243. {
  244. mod = ConsoleModifiers.Shift | ConsoleModifiers.Alt;
  245. }
  246. newConsoleKeyInfo = new (
  247. cki [1].KeyChar,
  248. (ConsoleKey)Math.Min ((uint)key, 255),
  249. (mod & ConsoleModifiers.Shift) != 0,
  250. (mod & ConsoleModifiers.Alt) != 0,
  251. (mod & ConsoleModifiers.Control) != 0);
  252. }
  253. else if (cki [1].KeyChar is '\n' or '\r')
  254. {
  255. key = ConsoleKey.Enter;
  256. if (kChars.Length > 1 && kChars [1] == '\n')
  257. {
  258. mod = ConsoleModifiers.Alt | ConsoleModifiers.Control;
  259. }
  260. else
  261. {
  262. mod = ConsoleModifiers.Shift | ConsoleModifiers.Alt;
  263. }
  264. newConsoleKeyInfo = new (
  265. cki [1].KeyChar,
  266. (ConsoleKey)Math.Min ((uint)key, 255),
  267. (mod & ConsoleModifiers.Shift) != 0,
  268. (mod & ConsoleModifiers.Alt) != 0,
  269. (mod & ConsoleModifiers.Control) != 0);
  270. }
  271. else
  272. {
  273. key = (ConsoleKey)cki [1].KeyChar;
  274. mod = ConsoleModifiers.Alt;
  275. newConsoleKeyInfo = new (
  276. cki [1].KeyChar,
  277. (ConsoleKey)Math.Min ((uint)key, 255),
  278. (mod & ConsoleModifiers.Shift) != 0,
  279. (mod & ConsoleModifiers.Alt) != 0,
  280. (mod & ConsoleModifiers.Control) != 0);
  281. }
  282. break;
  283. case "SS3":
  284. key = GetConsoleKey (terminator [0], values [0], ref mod, ref keyChar);
  285. newConsoleKeyInfo = new (
  286. keyChar,
  287. key,
  288. (mod & ConsoleModifiers.Shift) != 0,
  289. (mod & ConsoleModifiers.Alt) != 0,
  290. (mod & ConsoleModifiers.Control) != 0);
  291. break;
  292. case "CSI":
  293. // Reset always IncompleteCkInfos
  294. if (IncompleteCkInfos is { })
  295. {
  296. IncompleteCkInfos = null;
  297. }
  298. if (!string.IsNullOrEmpty (code) && code == "<")
  299. {
  300. GetMouse (cki, out buttonState, out pos, continuousButtonPressedHandler);
  301. isMouse = true;
  302. return;
  303. }
  304. if (EscSeqRequests.HasResponse (terminator))
  305. {
  306. isResponse = true;
  307. EscSeqRequests.Remove (terminator);
  308. return;
  309. }
  310. if (!string.IsNullOrEmpty (terminator))
  311. {
  312. System.Diagnostics.Debug.Assert (terminator.Length == 1);
  313. key = GetConsoleKey (terminator [0], values [0], ref mod, ref keyChar);
  314. if (key != 0 && values.Length > 1)
  315. {
  316. mod |= GetConsoleModifiers (values [1]);
  317. }
  318. if (keyChar != 0 || key != 0 || mod != 0)
  319. {
  320. newConsoleKeyInfo = new (
  321. keyChar,
  322. key,
  323. (mod & ConsoleModifiers.Shift) != 0,
  324. (mod & ConsoleModifiers.Alt) != 0,
  325. (mod & ConsoleModifiers.Control) != 0);
  326. }
  327. else
  328. {
  329. // It's request response that wasn't handled by a valid request terminator
  330. System.Diagnostics.Debug.Assert (EscSeqRequests.Statuses.Count > 0);
  331. isResponse = true;
  332. EscSeqRequests.Remove (terminator);
  333. }
  334. }
  335. else
  336. {
  337. // BUGBUG: See https://github.com/gui-cs/Terminal.Gui/issues/2803
  338. // This is caused by NetDriver depending on Console.KeyAvailable?
  339. //throw new InvalidOperationException ("CSI response, but there's no terminator");
  340. IncompleteCkInfos = cki;
  341. }
  342. break;
  343. default:
  344. newConsoleKeyInfo = MapConsoleKeyInfo (cki [0]);
  345. key = newConsoleKeyInfo.Key;
  346. mod = newConsoleKeyInfo.Modifiers;
  347. break;
  348. }
  349. }
  350. /// <summary>
  351. /// Gets the c1Control used in the called escape sequence.
  352. /// </summary>
  353. /// <param name="c">The char used.</param>
  354. /// <returns>The c1Control.</returns>
  355. [Pure]
  356. public static string GetC1ControlChar (in char c)
  357. {
  358. // These control characters are used in the vtXXX emulation.
  359. return c switch
  360. {
  361. 'D' => "IND", // Index
  362. 'E' => "NEL", // Next Line
  363. 'H' => "HTS", // Tab Set
  364. 'M' => "RI", // Reverse Index
  365. 'N' => "SS2", // Single Shift Select of G2 Character Set: affects next character only
  366. 'O' => "SS3", // Single Shift Select of G3 Character Set: affects next character only
  367. 'P' => "DCS", // Device Control String
  368. 'V' => "SPA", // Start of Guarded Area
  369. 'W' => "EPA", // End of Guarded Area
  370. 'X' => "SOS", // Start of String
  371. 'Z' => "DECID", // Return Terminal ID Obsolete form of CSI c (DA)
  372. '[' => "CSI", // Control Sequence Introducer
  373. '\\' => "ST", // String Terminator
  374. ']' => "OSC", // Operating System Command
  375. '^' => "PM", // Privacy Message
  376. '_' => "APC", // Application Program Command
  377. _ => string.Empty
  378. };
  379. }
  380. /// <summary>
  381. /// Gets the <see cref="ConsoleKey"/> depending on terminating and value.
  382. /// </summary>
  383. /// <param name="terminator">
  384. /// The terminator indicating a reply to <see cref="CSI_SendDeviceAttributes"/> or
  385. /// <see cref="CSI_SendDeviceAttributes2"/>.
  386. /// </param>
  387. /// <param name="value">The value.</param>
  388. /// <param name="mod">The <see cref="ConsoleModifiers"/> which may change.</param>
  389. /// <param name="keyChar">Normally is '\0' but on some cases may need other value.</param>
  390. /// <returns>The <see cref="ConsoleKey"/> and probably the <see cref="ConsoleModifiers"/>.</returns>
  391. public static ConsoleKey GetConsoleKey (char terminator, string? value, ref ConsoleModifiers mod, ref char keyChar)
  392. {
  393. if (terminator == 'Z')
  394. {
  395. mod |= ConsoleModifiers.Shift;
  396. }
  397. if (terminator == 'l')
  398. {
  399. keyChar = '+';
  400. }
  401. if (terminator == 'm')
  402. {
  403. keyChar = '-';
  404. }
  405. return (terminator, value) switch
  406. {
  407. ('A', _) => ConsoleKey.UpArrow,
  408. ('B', _) => ConsoleKey.DownArrow,
  409. ('C', _) => ConsoleKey.RightArrow,
  410. ('D', _) => ConsoleKey.LeftArrow,
  411. ('E', _) => ConsoleKey.Clear,
  412. ('F', _) => ConsoleKey.End,
  413. ('H', _) => ConsoleKey.Home,
  414. ('P', _) => ConsoleKey.F1,
  415. ('Q', _) => ConsoleKey.F2,
  416. ('R', _) => ConsoleKey.F3,
  417. ('S', _) => ConsoleKey.F4,
  418. ('Z', _) => ConsoleKey.Tab,
  419. ('~', "2") => ConsoleKey.Insert,
  420. ('~', "3") => ConsoleKey.Delete,
  421. ('~', "5") => ConsoleKey.PageUp,
  422. ('~', "6") => ConsoleKey.PageDown,
  423. ('~', "15") => ConsoleKey.F5,
  424. ('~', "17") => ConsoleKey.F6,
  425. ('~', "18") => ConsoleKey.F7,
  426. ('~', "19") => ConsoleKey.F8,
  427. ('~', "20") => ConsoleKey.F9,
  428. ('~', "21") => ConsoleKey.F10,
  429. ('~', "23") => ConsoleKey.F11,
  430. ('~', "24") => ConsoleKey.F12,
  431. // These terminators are used by macOS on a numeric keypad without keys modifiers
  432. ('l', null) => ConsoleKey.Add,
  433. ('m', null) => ConsoleKey.Subtract,
  434. ('p', null) => ConsoleKey.Insert,
  435. ('q', null) => ConsoleKey.End,
  436. ('r', null) => ConsoleKey.DownArrow,
  437. ('s', null) => ConsoleKey.PageDown,
  438. ('t', null) => ConsoleKey.LeftArrow,
  439. ('u', null) => ConsoleKey.Clear,
  440. ('v', null) => ConsoleKey.RightArrow,
  441. ('w', null) => ConsoleKey.Home,
  442. ('x', null) => ConsoleKey.UpArrow,
  443. ('y', null) => ConsoleKey.PageUp,
  444. (_, _) => 0
  445. };
  446. }
  447. /// <summary>
  448. /// Gets the <see cref="ConsoleModifiers"/> from the value.
  449. /// </summary>
  450. /// <param name="value">The value.</param>
  451. /// <returns>The <see cref="ConsoleModifiers"/> or zero.</returns>
  452. public static ConsoleModifiers GetConsoleModifiers (string? value)
  453. {
  454. return value switch
  455. {
  456. "2" => ConsoleModifiers.Shift,
  457. "3" => ConsoleModifiers.Alt,
  458. "4" => ConsoleModifiers.Shift | ConsoleModifiers.Alt,
  459. "5" => ConsoleModifiers.Control,
  460. "6" => ConsoleModifiers.Shift | ConsoleModifiers.Control,
  461. "7" => ConsoleModifiers.Alt | ConsoleModifiers.Control,
  462. "8" => ConsoleModifiers.Shift | ConsoleModifiers.Alt | ConsoleModifiers.Control,
  463. _ => 0
  464. };
  465. }
  466. #nullable restore
  467. /// <summary>
  468. /// Gets all the needed information about an escape sequence.
  469. /// </summary>
  470. /// <param name="kChar">The array with all chars.</param>
  471. /// <returns>
  472. /// The c1Control returned by <see cref="GetC1ControlChar"/>, code, values and terminating.
  473. /// </returns>
  474. public static (string c1Control, string code, string [] values, string terminating) GetEscapeResult (char [] kChar)
  475. {
  476. if (kChar is null || kChar.Length == 0 || (kChar.Length == 1 && kChar [0] != KeyEsc))
  477. {
  478. return (null, null, null, null);
  479. }
  480. if (kChar [0] != KeyEsc)
  481. {
  482. throw new InvalidOperationException ("Invalid escape character!");
  483. }
  484. if (kChar.Length == 1)
  485. {
  486. return ("ESC", null, null, null);
  487. }
  488. if (kChar.Length == 2)
  489. {
  490. return ("ESC", null, null, kChar [1].ToString ());
  491. }
  492. string c1Control = GetC1ControlChar (kChar [1]);
  493. string code = null;
  494. int nSep = kChar.Count (static x => x == ';') + 1;
  495. var values = new string [nSep];
  496. var valueIdx = 0;
  497. var terminating = string.Empty;
  498. for (var i = 2; i < kChar.Length; i++)
  499. {
  500. char c = kChar [i];
  501. if (char.IsDigit (c))
  502. {
  503. // PERF: Ouch
  504. values [valueIdx] += c.ToString ();
  505. }
  506. else if (c == ';')
  507. {
  508. valueIdx++;
  509. }
  510. else if (valueIdx == nSep - 1 || i == kChar.Length - 1)
  511. {
  512. // PERF: Ouch
  513. terminating += c.ToString ();
  514. }
  515. else
  516. {
  517. // PERF: Ouch
  518. code += c.ToString ();
  519. }
  520. }
  521. return (c1Control, code, values, terminating);
  522. }
  523. /// <summary>
  524. /// A helper to get only the <see cref="ConsoleKeyInfo.KeyChar"/> from the <see cref="ConsoleKeyInfo"/> array.
  525. /// </summary>
  526. /// <param name="cki"></param>
  527. /// <returns>The char array of the escape sequence.</returns>
  528. // PERF: This is expensive
  529. public static char [] GetKeyCharArray (ConsoleKeyInfo [] cki)
  530. {
  531. char [] kChar = [];
  532. var length = 0;
  533. foreach (ConsoleKeyInfo kc in cki)
  534. {
  535. length++;
  536. Array.Resize (ref kChar, length);
  537. kChar [length - 1] = kc.KeyChar;
  538. }
  539. return kChar;
  540. }
  541. /// <summary>
  542. /// Gets the <see cref="MouseFlags"/> mouse button flags and the position.
  543. /// </summary>
  544. /// <param name="cki">The <see cref="ConsoleKeyInfo"/> array.</param>
  545. /// <param name="mouseFlags">The mouse button flags.</param>
  546. /// <param name="pos">The mouse position.</param>
  547. /// <param name="continuousButtonPressedHandler">The handler that will process the event.</param>
  548. public static void GetMouse (
  549. ConsoleKeyInfo [] cki,
  550. out List<MouseFlags> mouseFlags,
  551. out Point pos,
  552. Action<MouseFlags, Point> continuousButtonPressedHandler
  553. )
  554. {
  555. MouseFlags buttonState = 0;
  556. pos = Point.Empty;
  557. var buttonCode = 0;
  558. var foundButtonCode = false;
  559. var foundPoint = 0;
  560. string value = string.Empty;
  561. char [] kChar = GetKeyCharArray (cki);
  562. // PERF: This loop could benefit from use of Spans and other strategies to avoid copies.
  563. //System.Diagnostics.Debug.WriteLine ($"kChar: {new string (kChar)}");
  564. for (var i = 0; i < kChar.Length; i++)
  565. {
  566. // PERF: Copy
  567. char c = kChar [i];
  568. if (c == '<')
  569. {
  570. foundButtonCode = true;
  571. }
  572. else if (foundButtonCode && c != ';')
  573. {
  574. // PERF: Ouch
  575. value += c.ToString ();
  576. }
  577. else if (c == ';')
  578. {
  579. if (foundButtonCode)
  580. {
  581. foundButtonCode = false;
  582. buttonCode = int.Parse (value);
  583. }
  584. if (foundPoint == 1)
  585. {
  586. pos.X = int.Parse (value) - 1;
  587. }
  588. value = string.Empty;
  589. foundPoint++;
  590. }
  591. else if (foundPoint > 0 && c != 'm' && c != 'M')
  592. {
  593. value += c.ToString ();
  594. }
  595. else if (c == 'm' || c == 'M')
  596. {
  597. //pos.Y = int.Parse (value) + Console.WindowTop - 1;
  598. pos.Y = int.Parse (value) - 1;
  599. switch (buttonCode)
  600. {
  601. case 0:
  602. case 8:
  603. case 16:
  604. case 24:
  605. case 32:
  606. case 36:
  607. case 40:
  608. case 48:
  609. case 56:
  610. buttonState = c == 'M'
  611. ? MouseFlags.Button1Pressed
  612. : MouseFlags.Button1Released;
  613. break;
  614. case 1:
  615. case 9:
  616. case 17:
  617. case 25:
  618. case 33:
  619. case 37:
  620. case 41:
  621. case 45:
  622. case 49:
  623. case 53:
  624. case 57:
  625. case 61:
  626. buttonState = c == 'M'
  627. ? MouseFlags.Button2Pressed
  628. : MouseFlags.Button2Released;
  629. break;
  630. case 2:
  631. case 10:
  632. case 14:
  633. case 18:
  634. case 22:
  635. case 26:
  636. case 30:
  637. case 34:
  638. case 42:
  639. case 46:
  640. case 50:
  641. case 54:
  642. case 58:
  643. case 62:
  644. buttonState = c == 'M'
  645. ? MouseFlags.Button3Pressed
  646. : MouseFlags.Button3Released;
  647. break;
  648. case 35:
  649. //// Needed for Windows OS
  650. //if (isButtonPressed && c == 'm'
  651. // && (lastMouseEvent.ButtonState == MouseFlags.Button1Pressed
  652. // || lastMouseEvent.ButtonState == MouseFlags.Button2Pressed
  653. // || lastMouseEvent.ButtonState == MouseFlags.Button3Pressed)) {
  654. // switch (lastMouseEvent.ButtonState) {
  655. // case MouseFlags.Button1Pressed:
  656. // buttonState = MouseFlags.Button1Released;
  657. // break;
  658. // case MouseFlags.Button2Pressed:
  659. // buttonState = MouseFlags.Button2Released;
  660. // break;
  661. // case MouseFlags.Button3Pressed:
  662. // buttonState = MouseFlags.Button3Released;
  663. // break;
  664. // }
  665. //} else {
  666. // buttonState = MouseFlags.ReportMousePosition;
  667. //}
  668. //break;
  669. case 39:
  670. case 43:
  671. case 47:
  672. case 51:
  673. case 55:
  674. case 59:
  675. case 63:
  676. buttonState = MouseFlags.ReportMousePosition;
  677. break;
  678. case 64:
  679. buttonState = MouseFlags.WheeledUp;
  680. break;
  681. case 65:
  682. buttonState = MouseFlags.WheeledDown;
  683. break;
  684. case 68:
  685. case 72:
  686. case 80:
  687. buttonState = MouseFlags.WheeledLeft; // Shift/Ctrl+WheeledUp
  688. break;
  689. case 69:
  690. case 73:
  691. case 81:
  692. buttonState = MouseFlags.WheeledRight; // Shift/Ctrl+WheeledDown
  693. break;
  694. }
  695. // Modifiers.
  696. switch (buttonCode)
  697. {
  698. case 8:
  699. case 9:
  700. case 10:
  701. case 43:
  702. buttonState |= MouseFlags.ButtonAlt;
  703. break;
  704. case 14:
  705. case 47:
  706. buttonState |= MouseFlags.ButtonAlt | MouseFlags.ButtonShift;
  707. break;
  708. case 16:
  709. case 17:
  710. case 18:
  711. case 51:
  712. buttonState |= MouseFlags.ButtonCtrl;
  713. break;
  714. case 22:
  715. case 55:
  716. buttonState |= MouseFlags.ButtonCtrl | MouseFlags.ButtonShift;
  717. break;
  718. case 24:
  719. case 25:
  720. case 26:
  721. case 59:
  722. buttonState |= MouseFlags.ButtonCtrl | MouseFlags.ButtonAlt;
  723. break;
  724. case 30:
  725. case 63:
  726. buttonState |= MouseFlags.ButtonCtrl | MouseFlags.ButtonShift | MouseFlags.ButtonAlt;
  727. break;
  728. case 32:
  729. case 33:
  730. case 34:
  731. buttonState |= MouseFlags.ReportMousePosition;
  732. break;
  733. case 36:
  734. case 37:
  735. buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonShift;
  736. break;
  737. case 39:
  738. case 68:
  739. case 69:
  740. buttonState |= MouseFlags.ButtonShift;
  741. break;
  742. case 40:
  743. case 41:
  744. case 42:
  745. buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonAlt;
  746. break;
  747. case 45:
  748. case 46:
  749. buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonAlt | MouseFlags.ButtonShift;
  750. break;
  751. case 48:
  752. case 49:
  753. case 50:
  754. buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonCtrl;
  755. break;
  756. case 53:
  757. case 54:
  758. buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonCtrl | MouseFlags.ButtonShift;
  759. break;
  760. case 56:
  761. case 57:
  762. case 58:
  763. buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonCtrl | MouseFlags.ButtonAlt;
  764. break;
  765. case 61:
  766. case 62:
  767. buttonState |= MouseFlags.ReportMousePosition | MouseFlags.ButtonCtrl | MouseFlags.ButtonShift | MouseFlags.ButtonAlt;
  768. break;
  769. }
  770. }
  771. }
  772. mouseFlags = [MouseFlags.AllEvents];
  773. if (_lastMouseButtonPressed != null
  774. && !_isButtonPressed
  775. && !buttonState.HasFlag (MouseFlags.ReportMousePosition)
  776. && !buttonState.HasFlag (MouseFlags.Button1Released)
  777. && !buttonState.HasFlag (MouseFlags.Button2Released)
  778. && !buttonState.HasFlag (MouseFlags.Button3Released)
  779. && !buttonState.HasFlag (MouseFlags.Button4Released))
  780. {
  781. _lastMouseButtonPressed = null;
  782. _isButtonPressed = false;
  783. }
  784. if ((!_isButtonClicked
  785. && !_isButtonDoubleClicked
  786. && (buttonState == MouseFlags.Button1Pressed
  787. || buttonState == MouseFlags.Button2Pressed
  788. || buttonState == MouseFlags.Button3Pressed
  789. || buttonState == MouseFlags.Button4Pressed)
  790. && _lastMouseButtonPressed is null)
  791. || (_isButtonPressed && _lastMouseButtonPressed is { } && buttonState.HasFlag (MouseFlags.ReportMousePosition)))
  792. {
  793. mouseFlags [0] = buttonState;
  794. _lastMouseButtonPressed = buttonState;
  795. _isButtonPressed = true;
  796. _point = pos;
  797. if ((mouseFlags [0] & MouseFlags.ReportMousePosition) == 0)
  798. {
  799. Application.MainLoop?.AddIdle (
  800. () =>
  801. {
  802. // INTENT: What's this trying to do?
  803. // The task itself is not awaited.
  804. Task.Run (
  805. async () => await ProcessContinuousButtonPressedAsync (
  806. buttonState,
  807. continuousButtonPressedHandler));
  808. return false;
  809. });
  810. }
  811. else if (mouseFlags [0].HasFlag (MouseFlags.ReportMousePosition))
  812. {
  813. _point = pos;
  814. // The isButtonPressed must always be true, otherwise we can lose the feature
  815. // If mouse flags has ReportMousePosition this feature won't run
  816. // but is always prepared with the new location
  817. //isButtonPressed = false;
  818. }
  819. }
  820. else if (_isButtonDoubleClicked
  821. && (buttonState == MouseFlags.Button1Pressed
  822. || buttonState == MouseFlags.Button2Pressed
  823. || buttonState == MouseFlags.Button3Pressed
  824. || buttonState == MouseFlags.Button4Pressed))
  825. {
  826. mouseFlags [0] = GetButtonTripleClicked (buttonState);
  827. _isButtonDoubleClicked = false;
  828. _isButtonTripleClicked = true;
  829. }
  830. else if (_isButtonClicked
  831. && (buttonState == MouseFlags.Button1Pressed
  832. || buttonState == MouseFlags.Button2Pressed
  833. || buttonState == MouseFlags.Button3Pressed
  834. || buttonState == MouseFlags.Button4Pressed))
  835. {
  836. mouseFlags [0] = GetButtonDoubleClicked (buttonState);
  837. _isButtonClicked = false;
  838. _isButtonDoubleClicked = true;
  839. Application.MainLoop?.AddIdle (
  840. () =>
  841. {
  842. Task.Run (async () => await ProcessButtonDoubleClickedAsync ());
  843. return false;
  844. });
  845. }
  846. //else if (isButtonReleased && !isButtonClicked && buttonState == MouseFlags.ReportMousePosition) {
  847. // mouseFlag [0] = GetButtonClicked ((MouseFlags)lastMouseButtonReleased);
  848. // lastMouseButtonReleased = null;
  849. // isButtonReleased = false;
  850. // isButtonClicked = true;
  851. // Application.MainLoop.AddIdle (() => {
  852. // Task.Run (async () => await ProcessButtonClickedAsync ());
  853. // return false;
  854. // });
  855. //}
  856. else if (!_isButtonClicked
  857. && !_isButtonDoubleClicked
  858. && (buttonState == MouseFlags.Button1Released
  859. || buttonState == MouseFlags.Button2Released
  860. || buttonState == MouseFlags.Button3Released
  861. || buttonState == MouseFlags.Button4Released))
  862. {
  863. mouseFlags [0] = buttonState;
  864. _isButtonPressed = false;
  865. if (_isButtonTripleClicked)
  866. {
  867. _isButtonTripleClicked = false;
  868. }
  869. else if (pos.X == _point?.X && pos.Y == _point?.Y)
  870. {
  871. mouseFlags.Add (GetButtonClicked (buttonState));
  872. _isButtonClicked = true;
  873. Application.MainLoop?.AddIdle (
  874. () =>
  875. {
  876. Task.Run (async () => await ProcessButtonClickedAsync ());
  877. return false;
  878. });
  879. }
  880. _point = pos;
  881. //if ((lastMouseButtonPressed & MouseFlags.ReportMousePosition) == 0) {
  882. // lastMouseButtonReleased = buttonState;
  883. // isButtonPressed = false;
  884. // isButtonReleased = true;
  885. //} else {
  886. // lastMouseButtonPressed = null;
  887. // isButtonPressed = false;
  888. //}
  889. }
  890. else if (buttonState == MouseFlags.WheeledUp)
  891. {
  892. mouseFlags [0] = MouseFlags.WheeledUp;
  893. }
  894. else if (buttonState == MouseFlags.WheeledDown)
  895. {
  896. mouseFlags [0] = MouseFlags.WheeledDown;
  897. }
  898. else if (buttonState == MouseFlags.WheeledLeft)
  899. {
  900. mouseFlags [0] = MouseFlags.WheeledLeft;
  901. }
  902. else if (buttonState == MouseFlags.WheeledRight)
  903. {
  904. mouseFlags [0] = MouseFlags.WheeledRight;
  905. }
  906. else if (buttonState == MouseFlags.ReportMousePosition)
  907. {
  908. mouseFlags [0] = MouseFlags.ReportMousePosition;
  909. }
  910. else
  911. {
  912. mouseFlags [0] = buttonState;
  913. //foreach (var flag in buttonState.GetUniqueFlags()) {
  914. // mouseFlag [0] |= flag;
  915. //}
  916. }
  917. mouseFlags [0] = SetControlKeyStates (buttonState, mouseFlags [0]);
  918. //buttonState = mouseFlags;
  919. //System.Diagnostics.Debug.WriteLine ($"buttonState: {buttonState} X: {pos.X} Y: {pos.Y}");
  920. //foreach (var mf in mouseFlags) {
  921. // System.Diagnostics.Debug.WriteLine ($"mouseFlags: {mf} X: {pos.X} Y: {pos.Y}");
  922. //}
  923. }
  924. /// <summary>
  925. /// Ensures a console key is mapped to one that works correctly with ANSI escape sequences.
  926. /// </summary>
  927. /// <param name="consoleKeyInfo">The <see cref="ConsoleKeyInfo"/>.</param>
  928. /// <returns>The <see cref="ConsoleKeyInfo"/> modified.</returns>
  929. public static ConsoleKeyInfo MapConsoleKeyInfo (ConsoleKeyInfo consoleKeyInfo)
  930. {
  931. ConsoleKeyInfo newConsoleKeyInfo = consoleKeyInfo;
  932. ConsoleKey key = ConsoleKey.None;
  933. char keyChar = consoleKeyInfo.KeyChar;
  934. switch ((uint)keyChar)
  935. {
  936. case 0:
  937. if (consoleKeyInfo.Key == (ConsoleKey)64)
  938. { // Ctrl+Space in Windows.
  939. newConsoleKeyInfo = new (
  940. consoleKeyInfo.KeyChar,
  941. ConsoleKey.Spacebar,
  942. (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0,
  943. (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
  944. (consoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0);
  945. }
  946. else if (consoleKeyInfo.Key == ConsoleKey.None)
  947. {
  948. newConsoleKeyInfo = new (
  949. consoleKeyInfo.KeyChar,
  950. ConsoleKey.Spacebar,
  951. (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0,
  952. (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
  953. true);
  954. }
  955. break;
  956. case uint n when n is > 0 and <= KeyEsc:
  957. if (consoleKeyInfo is { Key: 0, KeyChar: '\u001B' })
  958. {
  959. key = ConsoleKey.Escape;
  960. newConsoleKeyInfo = new (
  961. consoleKeyInfo.KeyChar,
  962. key,
  963. (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0,
  964. (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
  965. (consoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0);
  966. }
  967. else if (consoleKeyInfo is { Key: 0, KeyChar: '\t' })
  968. {
  969. key = ConsoleKey.Tab;
  970. newConsoleKeyInfo = new (
  971. consoleKeyInfo.KeyChar,
  972. key,
  973. (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0,
  974. (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
  975. (consoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0);
  976. }
  977. else if (consoleKeyInfo is { Key: 0, KeyChar: '\r' })
  978. {
  979. key = ConsoleKey.Enter;
  980. newConsoleKeyInfo = new (
  981. consoleKeyInfo.KeyChar,
  982. key,
  983. (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0,
  984. (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
  985. (consoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0);
  986. }
  987. else if (consoleKeyInfo is { Key: 0, KeyChar: '\n' })
  988. {
  989. key = ConsoleKey.Enter;
  990. newConsoleKeyInfo = new (
  991. consoleKeyInfo.KeyChar,
  992. key,
  993. (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0,
  994. (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
  995. true);
  996. }
  997. else if (consoleKeyInfo is { Key: 0, KeyChar: '\b' })
  998. {
  999. key = ConsoleKey.Backspace;
  1000. newConsoleKeyInfo = new (
  1001. consoleKeyInfo.KeyChar,
  1002. key,
  1003. (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0,
  1004. (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
  1005. true);
  1006. }
  1007. else if (consoleKeyInfo.Key == 0)
  1008. {
  1009. key = (ConsoleKey)(char)(consoleKeyInfo.KeyChar + (uint)ConsoleKey.A - 1);
  1010. newConsoleKeyInfo = new (
  1011. consoleKeyInfo.KeyChar,
  1012. key,
  1013. (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0,
  1014. (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
  1015. true);
  1016. }
  1017. break;
  1018. case 127: // DEL
  1019. key = ConsoleKey.Backspace;
  1020. newConsoleKeyInfo = new (
  1021. consoleKeyInfo.KeyChar,
  1022. key,
  1023. (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0,
  1024. (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
  1025. (consoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0);
  1026. break;
  1027. default:
  1028. uint ck = ConsoleKeyMapping.MapKeyCodeToConsoleKey ((KeyCode)consoleKeyInfo.KeyChar, out bool isConsoleKey);
  1029. if (isConsoleKey)
  1030. {
  1031. key = (ConsoleKey)ck;
  1032. }
  1033. newConsoleKeyInfo = new (
  1034. keyChar,
  1035. key,
  1036. GetShiftMod (consoleKeyInfo.Modifiers),
  1037. (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
  1038. (consoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0);
  1039. break;
  1040. }
  1041. return newConsoleKeyInfo;
  1042. bool GetShiftMod (ConsoleModifiers modifiers)
  1043. {
  1044. if (consoleKeyInfo.KeyChar is >= (char)ConsoleKey.A and <= (char)ConsoleKey.Z && modifiers == ConsoleModifiers.None)
  1045. {
  1046. return true;
  1047. }
  1048. return (modifiers & ConsoleModifiers.Shift) != 0;
  1049. }
  1050. }
  1051. private static MouseFlags _lastMouseFlags;
  1052. /// <summary>
  1053. /// Provides a handler to be invoked when mouse continuous button pressed is processed.
  1054. /// </summary>
  1055. public static event EventHandler<MouseEventArgs> ContinuousButtonPressed;
  1056. /// <summary>
  1057. /// Provides a default mouse event handler that can be used by any driver.
  1058. /// </summary>
  1059. /// <param name="mouseFlag">The mouse flags event.</param>
  1060. /// <param name="pos">The mouse position.</param>
  1061. public static void ProcessMouseEvent (MouseFlags mouseFlag, Point pos)
  1062. {
  1063. bool WasButtonReleased (MouseFlags flag)
  1064. {
  1065. return flag.HasFlag (MouseFlags.Button1Released)
  1066. || flag.HasFlag (MouseFlags.Button2Released)
  1067. || flag.HasFlag (MouseFlags.Button3Released)
  1068. || flag.HasFlag (MouseFlags.Button4Released);
  1069. }
  1070. bool IsButtonNotPressed (MouseFlags flag)
  1071. {
  1072. return !flag.HasFlag (MouseFlags.Button1Pressed)
  1073. && !flag.HasFlag (MouseFlags.Button2Pressed)
  1074. && !flag.HasFlag (MouseFlags.Button3Pressed)
  1075. && !flag.HasFlag (MouseFlags.Button4Pressed);
  1076. }
  1077. bool IsButtonClickedOrDoubleClicked (MouseFlags flag)
  1078. {
  1079. return flag.HasFlag (MouseFlags.Button1Clicked)
  1080. || flag.HasFlag (MouseFlags.Button2Clicked)
  1081. || flag.HasFlag (MouseFlags.Button3Clicked)
  1082. || flag.HasFlag (MouseFlags.Button4Clicked)
  1083. || flag.HasFlag (MouseFlags.Button1DoubleClicked)
  1084. || flag.HasFlag (MouseFlags.Button2DoubleClicked)
  1085. || flag.HasFlag (MouseFlags.Button3DoubleClicked)
  1086. || flag.HasFlag (MouseFlags.Button4DoubleClicked);
  1087. }
  1088. if ((WasButtonReleased (mouseFlag) && IsButtonNotPressed (_lastMouseFlags)) || (IsButtonClickedOrDoubleClicked (mouseFlag) && _lastMouseFlags == 0))
  1089. {
  1090. return;
  1091. }
  1092. _lastMouseFlags = mouseFlag;
  1093. var me = new MouseEventArgs { Flags = mouseFlag, Position = pos };
  1094. ContinuousButtonPressed?.Invoke ((mouseFlag, pos), me);
  1095. }
  1096. /// <summary>
  1097. /// A helper to resize the <see cref="ConsoleKeyInfo"/> as needed.
  1098. /// </summary>
  1099. /// <param name="consoleKeyInfo">The <see cref="ConsoleKeyInfo"/>.</param>
  1100. /// <param name="cki">The <see cref="ConsoleKeyInfo"/> array to resize.</param>
  1101. /// <returns>The <see cref="ConsoleKeyInfo"/> resized.</returns>
  1102. public static ConsoleKeyInfo [] ResizeArray (ConsoleKeyInfo consoleKeyInfo, ConsoleKeyInfo [] cki)
  1103. {
  1104. Array.Resize (ref cki, cki is null ? 1 : cki.Length + 1);
  1105. cki [^1] = consoleKeyInfo;
  1106. return cki;
  1107. }
  1108. /// <summary>
  1109. /// Insert a <see cref="ConsoleKeyInfo"/> array into the another <see cref="ConsoleKeyInfo"/> array at the specified
  1110. /// index.
  1111. /// </summary>
  1112. /// <param name="toInsert">The array to insert.</param>
  1113. /// <param name="cki">The array where will be added the array.</param>
  1114. /// <param name="index">The start index to insert the array, default is 0.</param>
  1115. /// <returns>The <see cref="ConsoleKeyInfo"/> array with another array inserted.</returns>
  1116. public static ConsoleKeyInfo [] InsertArray ([CanBeNull] ConsoleKeyInfo [] toInsert, ConsoleKeyInfo [] cki, int index = 0)
  1117. {
  1118. if (toInsert is null)
  1119. {
  1120. return cki;
  1121. }
  1122. if (cki is null)
  1123. {
  1124. return toInsert;
  1125. }
  1126. if (index < 0)
  1127. {
  1128. index = 0;
  1129. }
  1130. ConsoleKeyInfo [] backupCki = cki.Clone () as ConsoleKeyInfo [];
  1131. Array.Resize (ref cki, cki.Length + toInsert.Length);
  1132. for (var i = 0; i < cki.Length; i++)
  1133. {
  1134. if (i == index)
  1135. {
  1136. for (var j = 0; j < toInsert.Length; j++)
  1137. {
  1138. cki [i] = toInsert [j];
  1139. i++;
  1140. }
  1141. for (int k = index; k < backupCki!.Length; k++)
  1142. {
  1143. cki [i] = backupCki [k];
  1144. i++;
  1145. }
  1146. }
  1147. else
  1148. {
  1149. cki [i] = backupCki! [i];
  1150. }
  1151. }
  1152. return cki;
  1153. }
  1154. private static MouseFlags GetButtonClicked (MouseFlags mouseFlag)
  1155. {
  1156. MouseFlags mf = default;
  1157. switch (mouseFlag)
  1158. {
  1159. case MouseFlags.Button1Released:
  1160. mf = MouseFlags.Button1Clicked;
  1161. break;
  1162. case MouseFlags.Button2Released:
  1163. mf = MouseFlags.Button2Clicked;
  1164. break;
  1165. case MouseFlags.Button3Released:
  1166. mf = MouseFlags.Button3Clicked;
  1167. break;
  1168. }
  1169. return mf;
  1170. }
  1171. private static MouseFlags GetButtonDoubleClicked (MouseFlags mouseFlag)
  1172. {
  1173. MouseFlags mf = default;
  1174. switch (mouseFlag)
  1175. {
  1176. case MouseFlags.Button1Pressed:
  1177. mf = MouseFlags.Button1DoubleClicked;
  1178. break;
  1179. case MouseFlags.Button2Pressed:
  1180. mf = MouseFlags.Button2DoubleClicked;
  1181. break;
  1182. case MouseFlags.Button3Pressed:
  1183. mf = MouseFlags.Button3DoubleClicked;
  1184. break;
  1185. }
  1186. return mf;
  1187. }
  1188. private static MouseFlags GetButtonTripleClicked (MouseFlags mouseFlag)
  1189. {
  1190. MouseFlags mf = default;
  1191. switch (mouseFlag)
  1192. {
  1193. case MouseFlags.Button1Pressed:
  1194. mf = MouseFlags.Button1TripleClicked;
  1195. break;
  1196. case MouseFlags.Button2Pressed:
  1197. mf = MouseFlags.Button2TripleClicked;
  1198. break;
  1199. case MouseFlags.Button3Pressed:
  1200. mf = MouseFlags.Button3TripleClicked;
  1201. break;
  1202. }
  1203. return mf;
  1204. }
  1205. internal static KeyCode MapKey (ConsoleKeyInfo keyInfo)
  1206. {
  1207. switch (keyInfo.Key)
  1208. {
  1209. case ConsoleKey.OemPeriod:
  1210. case ConsoleKey.OemComma:
  1211. case ConsoleKey.OemPlus:
  1212. case ConsoleKey.OemMinus:
  1213. case ConsoleKey.Packet:
  1214. case ConsoleKey.Oem1:
  1215. case ConsoleKey.Oem2:
  1216. case ConsoleKey.Oem3:
  1217. case ConsoleKey.Oem4:
  1218. case ConsoleKey.Oem5:
  1219. case ConsoleKey.Oem6:
  1220. case ConsoleKey.Oem7:
  1221. case ConsoleKey.Oem8:
  1222. case ConsoleKey.Oem102:
  1223. if (keyInfo.KeyChar == 0)
  1224. {
  1225. // If the keyChar is 0, keyInfo.Key value is not a printable character.
  1226. System.Diagnostics.Debug.Assert (keyInfo.Key == 0);
  1227. return KeyCode.Null; // MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode)keyInfo.Key);
  1228. }
  1229. if (keyInfo.Modifiers != ConsoleModifiers.Shift)
  1230. {
  1231. // If Shift wasn't down we don't need to do anything but return the keyInfo.KeyChar
  1232. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar);
  1233. }
  1234. // Strip off Shift - We got here because they KeyChar from Windows is the shifted char (e.g. "Ç")
  1235. // and passing on Shift would be redundant.
  1236. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)keyInfo.KeyChar);
  1237. }
  1238. // Handle control keys whose VK codes match the related ASCII value (those below ASCII 33) like ESC
  1239. if (keyInfo.Key != ConsoleKey.None && Enum.IsDefined (typeof (KeyCode), (uint)keyInfo.Key))
  1240. {
  1241. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control) && keyInfo.Key == ConsoleKey.I)
  1242. {
  1243. return KeyCode.Tab;
  1244. }
  1245. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)(uint)keyInfo.Key);
  1246. }
  1247. // Handle control keys (e.g. CursorUp)
  1248. if (keyInfo.Key != ConsoleKey.None
  1249. && Enum.IsDefined (typeof (KeyCode), (uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint))
  1250. {
  1251. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)((uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint));
  1252. }
  1253. if ((ConsoleKey)keyInfo.KeyChar is >= ConsoleKey.A and <= ConsoleKey.Z)
  1254. {
  1255. // Shifted
  1256. keyInfo = new (
  1257. keyInfo.KeyChar,
  1258. (ConsoleKey)keyInfo.KeyChar,
  1259. true,
  1260. keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt),
  1261. keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control));
  1262. }
  1263. if ((ConsoleKey)keyInfo.KeyChar - 32 is >= ConsoleKey.A and <= ConsoleKey.Z)
  1264. {
  1265. // Unshifted
  1266. keyInfo = new (
  1267. keyInfo.KeyChar,
  1268. (ConsoleKey)(keyInfo.KeyChar - 32),
  1269. false,
  1270. keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt),
  1271. keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control));
  1272. }
  1273. if (keyInfo.Key is >= ConsoleKey.A and <= ConsoleKey.Z)
  1274. {
  1275. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt)
  1276. || keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control))
  1277. {
  1278. // NetDriver doesn't support Shift-Ctrl/Shift-Alt combos
  1279. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)keyInfo.Key);
  1280. }
  1281. if (keyInfo.Modifiers == ConsoleModifiers.Shift)
  1282. {
  1283. // If ShiftMask is on add the ShiftMask
  1284. if (char.IsUpper (keyInfo.KeyChar))
  1285. {
  1286. return (KeyCode)keyInfo.Key | KeyCode.ShiftMask;
  1287. }
  1288. }
  1289. return (KeyCode)keyInfo.Key;
  1290. }
  1291. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar);
  1292. }
  1293. private static async Task ProcessButtonClickedAsync ()
  1294. {
  1295. await Task.Delay (300);
  1296. _isButtonClicked = false;
  1297. }
  1298. private static async Task ProcessButtonDoubleClickedAsync ()
  1299. {
  1300. await Task.Delay (300);
  1301. _isButtonDoubleClicked = false;
  1302. }
  1303. private static async Task ProcessContinuousButtonPressedAsync (MouseFlags mouseFlag, Action<MouseFlags, Point> continuousButtonPressedHandler)
  1304. {
  1305. // PERF: Pause and poll in a hot loop.
  1306. // This should be replaced with event dispatch and a synchronization primitive such as AutoResetEvent.
  1307. // Will make a massive difference in responsiveness.
  1308. while (_isButtonPressed)
  1309. {
  1310. await Task.Delay (100);
  1311. View view = Application.WantContinuousButtonPressedView;
  1312. if (view is null)
  1313. {
  1314. break;
  1315. }
  1316. if (_isButtonPressed && _lastMouseButtonPressed is { } && (mouseFlag & MouseFlags.ReportMousePosition) == 0)
  1317. {
  1318. Application.Invoke (() => continuousButtonPressedHandler (mouseFlag, _point ?? Point.Empty));
  1319. }
  1320. }
  1321. }
  1322. private static MouseFlags SetControlKeyStates (MouseFlags buttonState, MouseFlags mouseFlag)
  1323. {
  1324. if ((buttonState & MouseFlags.ButtonCtrl) != 0 && (mouseFlag & MouseFlags.ButtonCtrl) == 0)
  1325. {
  1326. mouseFlag |= MouseFlags.ButtonCtrl;
  1327. }
  1328. if ((buttonState & MouseFlags.ButtonShift) != 0 && (mouseFlag & MouseFlags.ButtonShift) == 0)
  1329. {
  1330. mouseFlag |= MouseFlags.ButtonShift;
  1331. }
  1332. if ((buttonState & MouseFlags.ButtonAlt) != 0 && (mouseFlag & MouseFlags.ButtonAlt) == 0)
  1333. {
  1334. mouseFlag |= MouseFlags.ButtonAlt;
  1335. }
  1336. return mouseFlag;
  1337. }
  1338. /// <summary>
  1339. /// Split a raw string into a list of string with the correct ansi escape sequence.
  1340. /// </summary>
  1341. /// <param name="rawData">The raw string containing one or many ansi escape sequence.</param>
  1342. /// <returns>A list with a valid ansi escape sequence.</returns>
  1343. public static List<string> SplitEscapeRawString (string rawData)
  1344. {
  1345. List<string> splitList = [];
  1346. var isEscSeq = false;
  1347. var split = string.Empty;
  1348. char previousChar = '\0';
  1349. for (var i = 0; i < rawData.Length; i++)
  1350. {
  1351. char c = rawData [i];
  1352. if (c == '\u001B')
  1353. {
  1354. isEscSeq = true;
  1355. split = AddAndClearSplit ();
  1356. split += c.ToString ();
  1357. }
  1358. else if (!isEscSeq && c >= Key.Space)
  1359. {
  1360. split = AddAndClearSplit ();
  1361. splitList.Add (c.ToString ());
  1362. }
  1363. else if ((previousChar != '\u001B' && c <= Key.Space) || (previousChar != '\u001B' && c == 127)
  1364. || (char.IsLetter (previousChar) && char.IsLower (c) && char.IsLetter (c))
  1365. || (!string.IsNullOrEmpty (split) && split.Length > 2 && char.IsLetter (previousChar) && char.IsLetterOrDigit (c))
  1366. || (!string.IsNullOrEmpty (split) && split.Length > 2 && char.IsLetter (previousChar) && char.IsPunctuation (c))
  1367. || (!string.IsNullOrEmpty (split) && split.Length > 2 && char.IsLetter (previousChar) && char.IsSymbol (c)))
  1368. {
  1369. isEscSeq = false;
  1370. split = AddAndClearSplit ();
  1371. splitList.Add (c.ToString ());
  1372. }
  1373. else
  1374. {
  1375. split += c.ToString ();
  1376. }
  1377. if (!string.IsNullOrEmpty (split) && i == rawData.Length - 1)
  1378. {
  1379. splitList.Add (split);
  1380. }
  1381. previousChar = c;
  1382. }
  1383. return splitList;
  1384. string AddAndClearSplit ()
  1385. {
  1386. if (!string.IsNullOrEmpty (split))
  1387. {
  1388. splitList.Add (split);
  1389. split = string.Empty;
  1390. }
  1391. return split;
  1392. }
  1393. }
  1394. /// <summary>
  1395. /// Convert a <see cref="ConsoleKeyInfo"/> array to string.
  1396. /// </summary>
  1397. /// <param name="consoleKeyInfos"></param>
  1398. /// <returns>The string representing the array.</returns>
  1399. public static string ToString (ConsoleKeyInfo [] consoleKeyInfos)
  1400. {
  1401. StringBuilder sb = new ();
  1402. foreach (ConsoleKeyInfo keyChar in consoleKeyInfos)
  1403. {
  1404. sb.Append (keyChar.KeyChar);
  1405. }
  1406. return sb.ToString ();
  1407. }
  1408. /// <summary>
  1409. /// Convert a string to <see cref="ConsoleKeyInfo"/> array.
  1410. /// </summary>
  1411. /// <param name="ansi"></param>
  1412. /// <returns>The <see cref="ConsoleKeyInfo"/>representing the string.</returns>
  1413. public static ConsoleKeyInfo [] ToConsoleKeyInfoArray (string ansi)
  1414. {
  1415. if (ansi is null)
  1416. {
  1417. return null;
  1418. }
  1419. ConsoleKeyInfo [] cki = new ConsoleKeyInfo [ansi.Length];
  1420. for (var i = 0; i < ansi.Length; i++)
  1421. {
  1422. char c = ansi [i];
  1423. cki [i] = new (c, 0, false, false, false);
  1424. }
  1425. return cki;
  1426. }
  1427. #region Cursor
  1428. //ESC [ M - RI Reverse Index – Performs the reverse operation of \n, moves cursor up one line, maintains horizontal position, scrolls buffer if necessary*
  1429. /// <summary>
  1430. /// ESC [ 7 - Save Cursor Position in Memory**
  1431. /// </summary>
  1432. public static readonly string CSI_SaveCursorPosition = CSI + "7";
  1433. /// <summary>
  1434. /// ESC [ 8 - DECSR Restore Cursor Position from Memory**
  1435. /// </summary>
  1436. public static readonly string CSI_RestoreCursorPosition = CSI + "8";
  1437. /// <summary>
  1438. /// ESC [ 8 ; height ; width t - Set Terminal Window Size
  1439. /// https://terminalguide.namepad.de/seq/csi_st-8/
  1440. /// </summary>
  1441. public static string CSI_SetTerminalWindowSize (int height, int width) { return $"{CSI}8;{height};{width}t"; }
  1442. //ESC [ < n > A - CUU - Cursor Up Cursor up by < n >
  1443. //ESC [ < n > B - CUD - Cursor Down Cursor down by < n >
  1444. //ESC [ < n > C - CUF - Cursor Forward Cursor forward (Right) by < n >
  1445. //ESC [ < n > D - CUB - Cursor Backward Cursor backward (Left) by < n >
  1446. //ESC [ < n > E - CNL - Cursor Next Line - Cursor down < n > lines from current position
  1447. //ESC [ < n > F - CPL - Cursor Previous Line Cursor up < n > lines from current position
  1448. //ESC [ < n > G - CHA - Cursor Horizontal Absolute Cursor moves to < n > th position horizontally in the current line
  1449. //ESC [ < n > d - VPA - Vertical Line Position Absolute Cursor moves to the < n > th position vertically in the current column
  1450. /// <summary>
  1451. /// ESC [ y ; x H - CUP Cursor Position - Cursor moves to x ; y coordinate within the viewport, where x is the column
  1452. /// of the y line
  1453. /// </summary>
  1454. /// <param name="row">Origin is (1,1).</param>
  1455. /// <param name="col">Origin is (1,1).</param>
  1456. /// <returns></returns>
  1457. public static string CSI_SetCursorPosition (int row, int col) { return $"{CSI}{row};{col}H"; }
  1458. /// <summary>
  1459. /// ESC [ y ; x H - CUP Cursor Position - Cursor moves to x ; y coordinate within the viewport, where x is the column
  1460. /// of the y line
  1461. /// </summary>
  1462. /// <param name="builder">StringBuilder where to append the cursor position sequence.</param>
  1463. /// <param name="row">Origin is (1,1).</param>
  1464. /// <param name="col">Origin is (1,1).</param>
  1465. public static void CSI_AppendCursorPosition (StringBuilder builder, int row, int col)
  1466. {
  1467. // InterpolatedStringHandler is composed in stack, skipping the string allocation.
  1468. builder.Append ($"{CSI}{row};{col}H");
  1469. }
  1470. /// <summary>
  1471. /// ESC [ y ; x H - CUP Cursor Position - Cursor moves to x ; y coordinate within the viewport, where x is the column
  1472. /// of the y line
  1473. /// </summary>
  1474. /// <param name="writer">TextWriter where to write the cursor position sequence.</param>
  1475. /// <param name="row">Origin is (1,1).</param>
  1476. /// <param name="col">Origin is (1,1).</param>
  1477. public static void CSI_WriteCursorPosition (TextWriter writer, int row, int col)
  1478. {
  1479. const int maxInputBufferSize =
  1480. // CSI (2) + ';' + 'H'
  1481. 4 +
  1482. // row + col (2x int sign + int max value)
  1483. 2 + 20;
  1484. Span<char> buffer = stackalloc char[maxInputBufferSize];
  1485. if (!buffer.TryWrite (CultureInfo.InvariantCulture, $"{CSI}{row};{col}H", out int charsWritten))
  1486. {
  1487. string tooLongCursorPositionSequence = $"{CSI}{row};{col}H";
  1488. throw new InvalidOperationException (
  1489. $"{nameof(CSI_WriteCursorPosition)} buffer (len: {buffer.Length}) is too short for cursor position sequence '{tooLongCursorPositionSequence}' (len: {tooLongCursorPositionSequence.Length}).");
  1490. }
  1491. ReadOnlySpan<char> cursorPositionSequence = buffer[..charsWritten];
  1492. writer.Write (cursorPositionSequence);
  1493. }
  1494. //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
  1495. //ESC [ s - ANSISYSSC Save Cursor – Ansi.sys emulation **With no parameters, performs a save cursor operation like DECSC
  1496. //ESC [ u - ANSISYSRC Restore Cursor – Ansi.sys emulation **With no parameters, performs a restore cursor operation like DECRC
  1497. //ESC [ ? 12 h - ATT160 Text Cursor Enable Blinking Start the cursor blinking
  1498. //ESC [ ? 12 l - ATT160 Text Cursor Disable Blinking Stop blinking the cursor
  1499. /// <summary>
  1500. /// ESC [ ? 25 h - DECTCEM Text Cursor Enable Mode Show Show the cursor
  1501. /// </summary>
  1502. public static readonly string CSI_ShowCursor = CSI + "?25h";
  1503. /// <summary>
  1504. /// ESC [ ? 25 l - DECTCEM Text Cursor Enable Mode Hide Hide the cursor
  1505. /// </summary>
  1506. public static readonly string CSI_HideCursor = CSI + "?25l";
  1507. //ESC [ ? 12 h - ATT160 Text Cursor Enable Blinking Start the cursor blinking
  1508. //ESC [ ? 12 l - ATT160 Text Cursor Disable Blinking Stop blinking the cursor
  1509. //ESC [ ? 25 h - DECTCEM Text Cursor Enable Mode Show Show the cursor
  1510. //ESC [ ? 25 l - DECTCEM Text Cursor Enable Mode Hide Hide the cursor
  1511. /// <summary>
  1512. /// Styles for ANSI ESC "[x q" - Set Cursor Style
  1513. /// </summary>
  1514. public enum DECSCUSR_Style
  1515. {
  1516. /// <summary>
  1517. /// DECSCUSR - User Shape - Default cursor shape configured by the user
  1518. /// </summary>
  1519. UserShape = 0,
  1520. /// <summary>
  1521. /// DECSCUSR - Blinking Block - Blinking block cursor shape
  1522. /// </summary>
  1523. BlinkingBlock = 1,
  1524. /// <summary>
  1525. /// DECSCUSR - Steady Block - Steady block cursor shape
  1526. /// </summary>
  1527. SteadyBlock = 2,
  1528. /// <summary>
  1529. /// DECSCUSR - Blinking Underline - Blinking underline cursor shape
  1530. /// </summary>
  1531. BlinkingUnderline = 3,
  1532. /// <summary>
  1533. /// DECSCUSR - Steady Underline - Steady underline cursor shape
  1534. /// </summary>
  1535. SteadyUnderline = 4,
  1536. /// <summary>
  1537. /// DECSCUSR - Blinking Bar - Blinking bar cursor shape
  1538. /// </summary>
  1539. BlinkingBar = 5,
  1540. /// <summary>
  1541. /// DECSCUSR - Steady Bar - Steady bar cursor shape
  1542. /// </summary>
  1543. SteadyBar = 6
  1544. }
  1545. /// <summary>
  1546. /// ESC [ n SP q - Select Cursor Style (DECSCUSR)
  1547. /// https://terminalguide.namepad.de/seq/csi_sq_t_space/
  1548. /// </summary>
  1549. /// <param name="style"></param>
  1550. /// <returns></returns>
  1551. public static string CSI_SetCursorStyle (DECSCUSR_Style style) { return $"{CSI}{(int)style} q"; }
  1552. #endregion
  1553. #region Colors
  1554. /// <summary>
  1555. /// ESC [ (n) m - SGR - Set Graphics Rendition - Set the format of the screen and text as specified by (n)
  1556. /// This command is special in that the (n) position can accept between 0 and 16 parameters separated by semicolons.
  1557. /// When no parameters are specified, it is treated the same as a single 0 parameter.
  1558. /// https://terminalguide.namepad.de/seq/csi_sm/
  1559. /// </summary>
  1560. public static string CSI_SetGraphicsRendition (params int [] parameters) { return $"{CSI}{string.Join (";", parameters)}m"; }
  1561. /// <summary>
  1562. /// ESC [ (n) m - Uses <see cref="CSI_SetGraphicsRendition(int[])"/> to set the foreground color.
  1563. /// </summary>
  1564. /// <param name="code">One of the 16 color codes.</param>
  1565. /// <returns></returns>
  1566. public static string CSI_SetForegroundColor (AnsiColorCode code) { return CSI_SetGraphicsRendition ((int)code); }
  1567. /// <summary>
  1568. /// ESC [ (n) m - Uses <see cref="CSI_SetGraphicsRendition(int[])"/> to set the background color.
  1569. /// </summary>
  1570. /// <param name="code">One of the 16 color codes.</param>
  1571. /// <returns></returns>
  1572. public static string CSI_SetBackgroundColor (AnsiColorCode code) { return CSI_SetGraphicsRendition ((int)code + 10); }
  1573. /// <summary>
  1574. /// ESC[38;5;{id}m - Set foreground color (256 colors)
  1575. /// </summary>
  1576. public static string CSI_SetForegroundColor256 (int color) { return $"{CSI}38;5;{color}m"; }
  1577. /// <summary>
  1578. /// ESC[48;5;{id}m - Set background color (256 colors)
  1579. /// </summary>
  1580. public static string CSI_SetBackgroundColor256 (int color) { return $"{CSI}48;5;{color}m"; }
  1581. /// <summary>
  1582. /// ESC[38;2;{r};{g};{b}m Set foreground color as RGB.
  1583. /// </summary>
  1584. public static string CSI_SetForegroundColorRGB (int r, int g, int b) { return $"{CSI}38;2;{r};{g};{b}m"; }
  1585. /// <summary>
  1586. /// ESC[38;2;{r};{g};{b}m Append foreground color as RGB to StringBuilder.
  1587. /// </summary>
  1588. public static void CSI_AppendForegroundColorRGB (StringBuilder builder, int r, int g, int b)
  1589. {
  1590. // InterpolatedStringHandler is composed in stack, skipping the string allocation.
  1591. builder.Append ($"{CSI}38;2;{r};{g};{b}m");
  1592. }
  1593. /// <summary>
  1594. /// ESC[48;2;{r};{g};{b}m Set background color as RGB.
  1595. /// </summary>
  1596. public static string CSI_SetBackgroundColorRGB (int r, int g, int b) { return $"{CSI}48;2;{r};{g};{b}m"; }
  1597. /// <summary>
  1598. /// ESC[48;2;{r};{g};{b}m Append background color as RGB to StringBuilder.
  1599. /// </summary>
  1600. public static void CSI_AppendBackgroundColorRGB (StringBuilder builder, int r, int g, int b)
  1601. {
  1602. // InterpolatedStringHandler is composed in stack, skipping the string allocation.
  1603. builder.Append ($"{CSI}48;2;{r};{g};{b}m");
  1604. }
  1605. #endregion
  1606. #region Text Styles
  1607. /// <summary>
  1608. /// Appends an ANSI SGR (Select Graphic Rendition) escape sequence to switch printed text from one <see cref="TextStyle"/> to another.
  1609. /// </summary>
  1610. /// <param name="output"><see cref="StringBuilder"/> to add escape sequence to.</param>
  1611. /// <param name="prev">Previous <see cref="TextStyle"/> to change away from.</param>
  1612. /// <param name="next">Next <see cref="TextStyle"/> to change to.</param>
  1613. /// <remarks>
  1614. /// <para>
  1615. /// Unlike colors, most text styling options are not mutually exclusive with each other, and can be applied independently. This creates a problem when
  1616. /// switching from one style to another: For instance, if your previous style is just bold, and your next style is just italic, then simply adding the
  1617. /// sequence to enable italic text would cause the text to remain bold. This method automatically handles this problem, enabling and disabling styles as
  1618. /// necessary to apply exactly the next style.
  1619. /// </para>
  1620. /// </remarks>
  1621. internal static void CSI_AppendTextStyleChange (StringBuilder output, TextStyle prev, TextStyle next)
  1622. {
  1623. // Do nothing if styles are the same, as no changes are necessary.
  1624. if (prev == next)
  1625. {
  1626. return;
  1627. }
  1628. // Bitwise operations to determine flag changes. A ^ B are the flags different between two flag sets. These different flags that exist in the next flag
  1629. // set (diff & next) are the ones that were enabled in the switch, those that exist in the previous flag set (diff & prev) are the ones that were
  1630. // disabled.
  1631. var diff = prev ^ next;
  1632. var enabled = diff & next;
  1633. var disabled = diff & prev;
  1634. // List of escape codes to apply.
  1635. var sgr = new List<int> ();
  1636. if (disabled != TextStyle.None)
  1637. {
  1638. // Special case: Both bold and faint have the same disabling code. While unusual, it can be valid to have both enabled at the same time, so when
  1639. // one and only one of them is being disabled, we need to re-enable the other afterward. We can check what flags remain enabled by taking
  1640. // prev & next, as this is the set of flags both have.
  1641. if (disabled.HasFlag (TextStyle.Bold))
  1642. {
  1643. sgr.Add (22);
  1644. if ((prev & next).HasFlag (TextStyle.Faint))
  1645. {
  1646. sgr.Add (2);
  1647. }
  1648. }
  1649. if (disabled.HasFlag (TextStyle.Faint))
  1650. {
  1651. sgr.Add (22);
  1652. if ((prev & next).HasFlag (TextStyle.Bold))
  1653. {
  1654. sgr.Add (1);
  1655. }
  1656. }
  1657. if (disabled.HasFlag (TextStyle.Italic))
  1658. {
  1659. sgr.Add (23);
  1660. }
  1661. if (disabled.HasFlag (TextStyle.Underline))
  1662. {
  1663. sgr.Add (24);
  1664. }
  1665. if (disabled.HasFlag (TextStyle.Blink))
  1666. {
  1667. sgr.Add (25);
  1668. }
  1669. if (disabled.HasFlag (TextStyle.Reverse))
  1670. {
  1671. sgr.Add (27);
  1672. }
  1673. if (disabled.HasFlag (TextStyle.Strikethrough))
  1674. {
  1675. sgr.Add (29);
  1676. }
  1677. }
  1678. if (enabled != TextStyle.None)
  1679. {
  1680. if (enabled.HasFlag (TextStyle.Bold))
  1681. {
  1682. sgr.Add (1);
  1683. }
  1684. if (enabled.HasFlag (TextStyle.Faint))
  1685. {
  1686. sgr.Add (2);
  1687. }
  1688. if (enabled.HasFlag (TextStyle.Italic))
  1689. {
  1690. sgr.Add (3);
  1691. }
  1692. if (enabled.HasFlag (TextStyle.Underline))
  1693. {
  1694. sgr.Add (4);
  1695. }
  1696. if (enabled.HasFlag (TextStyle.Blink))
  1697. {
  1698. sgr.Add (5);
  1699. }
  1700. if (enabled.HasFlag (TextStyle.Reverse))
  1701. {
  1702. sgr.Add (7);
  1703. }
  1704. if (enabled.HasFlag (TextStyle.Strikethrough))
  1705. {
  1706. sgr.Add (9);
  1707. }
  1708. }
  1709. output.Append ("\x1b[");
  1710. output.Append (string.Join (';', sgr));
  1711. output.Append ('m');
  1712. }
  1713. #endregion Text Styles
  1714. #region Requests
  1715. /// <summary>
  1716. /// ESC [ ? 6 n - Request Cursor Position Report (?) (DECXCPR)
  1717. /// https://terminalguide.namepad.de/seq/csi_sn__p-6/
  1718. /// The terminal reply to <see cref="CSI_RequestCursorPositionReport"/>. ESC [ ? (y) ; (x) ; 1 R
  1719. /// </summary>
  1720. public static readonly AnsiEscapeSequence CSI_RequestCursorPositionReport = new () { Request = CSI + "?6n", Terminator = "R" };
  1721. /// <summary>
  1722. /// The terminal reply to <see cref="CSI_RequestCursorPositionReport"/>. ESC [ ? (y) ; (x) R
  1723. /// </summary>
  1724. public const string CSI_RequestCursorPositionReport_Terminator = "R";
  1725. /// <summary>
  1726. /// ESC [ 0 c - Send Device Attributes (Primary DA)
  1727. /// https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Application-Program-Command-functions
  1728. /// https://www.xfree86.org/current/ctlseqs.html
  1729. /// Windows Terminal v1.17 and below emits “\x1b[?1;0c”, indicating "VT101 with No Options".
  1730. /// Windows Terminal v1.18+ emits: \x1b[?61;6;7;22;23;24;28;32;42c"
  1731. /// See https://github.com/microsoft/terminal/pull/14906
  1732. /// 61 - The device conforms to level 1 of the character cell display architecture
  1733. /// (See https://github.com/microsoft/terminal/issues/15693#issuecomment-1633304497)
  1734. /// 6 = Selective erase
  1735. /// 7 = Soft fonts
  1736. /// 22 = Color text
  1737. /// 23 = Greek character sets
  1738. /// 24 = Turkish character sets
  1739. /// 28 = Rectangular area operations
  1740. /// 32 = Text macros
  1741. /// 42 = ISO Latin-2 character set
  1742. /// The terminator indicating a reply to <see cref="CSI_SendDeviceAttributes"/> or
  1743. /// <see cref="CSI_SendDeviceAttributes2"/>
  1744. /// </summary>
  1745. public static readonly AnsiEscapeSequence CSI_SendDeviceAttributes = new () { Request = CSI + "0c", Terminator = "c" };
  1746. /// <summary>
  1747. /// ESC [ > 0 c - Send Device Attributes (Secondary DA)
  1748. /// Windows Terminal v1.18+ emits: "\x1b[>0;10;1c" (vt100, firmware version 1.0, vt220)
  1749. /// </summary>
  1750. public static readonly AnsiEscapeSequence CSI_SendDeviceAttributes2 = new () { Request = CSI + ">0c", Terminator = "c" };
  1751. /// <summary>
  1752. /// CSI 16 t - Request sixel resolution (width and height in pixels)
  1753. /// </summary>
  1754. public static readonly AnsiEscapeSequence CSI_RequestSixelResolution = new () { Request = CSI + "16t", Terminator = "t" };
  1755. /// <summary>
  1756. /// CSI 14 t - Request window size in pixels (width x height)
  1757. /// </summary>
  1758. public static readonly AnsiEscapeSequence CSI_RequestWindowSizeInPixels = new () { Request = CSI + "14t", Terminator = "t" };
  1759. /// <summary>
  1760. /// CSI 1 8 t | yes | yes | yes | report window size in chars
  1761. /// https://terminalguide.namepad.de/seq/csi_st-18/
  1762. /// The terminator indicating a reply to <see cref="CSI_ReportTerminalSizeInChars"/> : ESC [ 8 ; height ; width t
  1763. /// </summary>
  1764. public static readonly AnsiEscapeSequence CSI_ReportTerminalSizeInChars = new () { Request = CSI + "18t", Terminator = "t", Value = "8" };
  1765. /// <summary>
  1766. /// The terminator indicating a reply to <see cref="CSI_ReportTerminalSizeInChars"/> : ESC [ 8 ; height ; width t
  1767. /// </summary>
  1768. public const string CSI_ReportTerminalSizeInChars_Terminator = "t";
  1769. /// <summary>
  1770. /// The value of the response to <see cref="CSI_ReportTerminalSizeInChars"/> indicating value 1 and 2 are the terminal
  1771. /// size in chars.
  1772. /// </summary>
  1773. public const string CSI_ReportTerminalSizeInChars_ResponseValue = "8";
  1774. #endregion
  1775. }