AnsiEscapeSequenceRequestUtils.cs 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853
  1. #nullable enable
  2. using Terminal.Gui.ConsoleDrivers;
  3. using static Terminal.Gui.ConsoleDrivers.ConsoleKeyMapping;
  4. namespace Terminal.Gui;
  5. // QUESTION: Should this class be refactored into separate classes for:
  6. // QUESTION: CSI definitions
  7. // QUESTION: Primitives like DecodeEsqReq
  8. // QUESTION: Screen/Color/Cursor handling
  9. // QUESTION: Mouse handling
  10. // QUESTION: Keyboard handling
  11. /// <summary>
  12. /// Provides a platform-independent API for managing ANSI escape sequences.
  13. /// </summary>
  14. /// <remarks>
  15. /// Useful resources:
  16. /// * https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences
  17. /// * https://invisible-island.net/xterm/ctlseqs/ctlseqs.html
  18. /// * https://vt100.net/
  19. /// </remarks>
  20. public static class AnsiEscapeSequenceRequestUtils
  21. {
  22. // TODO: One type per file - Move this enum to a separate file.
  23. /// <summary>
  24. /// Options for ANSI ESC "[xJ" - Clears part of the screen.
  25. /// </summary>
  26. public enum ClearScreenOptions
  27. {
  28. /// <summary>
  29. /// If n is 0 (or missing), clear from cursor to end of screen.
  30. /// </summary>
  31. CursorToEndOfScreen = 0,
  32. /// <summary>
  33. /// If n is 1, clear from cursor to beginning of the screen.
  34. /// </summary>
  35. CursorToBeginningOfScreen = 1,
  36. /// <summary>
  37. /// If n is 2, clear entire screen (and moves cursor to upper left on DOS ANSI.SYS).
  38. /// </summary>
  39. EntireScreen = 2,
  40. /// <summary>
  41. /// If n is 3, clear entire screen and delete all lines saved in the scrollback buffer
  42. /// </summary>
  43. EntireScreenAndScrollbackBuffer = 3
  44. }
  45. // QUESTION: I wonder if EscSeqUtils.CSI_... should be more strongly typed such that this (and Terminator could be
  46. // QUESTION: public required CSIRequests Request { get; init; }
  47. // QUESTION: public required CSITerminators Terminator { get; init; }
  48. /// <summary>
  49. /// Escape key code (ASCII 27/0x1B).
  50. /// </summary>
  51. public const char KeyEsc = (char)KeyCode.Esc;
  52. /// <summary>
  53. /// ESC [ - The CSI (Control Sequence Introducer).
  54. /// </summary>
  55. public const string CSI = "\u001B[";
  56. /// <summary>
  57. /// ESC [ ? 1047 h - Activate xterm alternative buffer (no backscroll)
  58. /// </summary>
  59. /// <remarks>
  60. /// From
  61. /// https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Functions-using-CSI-_-ordered-by-the-final-character_s_
  62. /// Use Alternate Screen Buffer, xterm.
  63. /// </remarks>
  64. public static readonly string CSI_ActivateAltBufferNoBackscroll = CSI + "?1047h";
  65. /// <summary>
  66. /// ESC [ ? 1003 l - Disable any mouse event tracking.
  67. /// </summary>
  68. public static readonly string CSI_DisableAnyEventMouse = CSI + "?1003l";
  69. /// <summary>
  70. /// ESC [ ? 1006 l - Disable SGR (Select Graphic Rendition).
  71. /// </summary>
  72. public static readonly string CSI_DisableSgrExtModeMouse = CSI + "?1006l";
  73. /// <summary>
  74. /// ESC [ ? 1015 l - Disable URXVT (Unicode Extended Virtual Terminal).
  75. /// </summary>
  76. public static readonly string CSI_DisableUrxvtExtModeMouse = CSI + "?1015l";
  77. /// <summary>
  78. /// ESC [ ? 1003 h - Enable mouse event tracking.
  79. /// </summary>
  80. public static readonly string CSI_EnableAnyEventMouse = CSI + "?1003h";
  81. /// <summary>
  82. /// ESC [ ? 1006 h - Enable SGR (Select Graphic Rendition).
  83. /// </summary>
  84. public static readonly string CSI_EnableSgrExtModeMouse = CSI + "?1006h";
  85. /// <summary>
  86. /// ESC [ ? 1015 h - Enable URXVT (Unicode Extended Virtual Terminal).
  87. /// </summary>
  88. public static readonly string CSI_EnableUrxvtExtModeMouse = CSI + "?1015h";
  89. /// <summary>
  90. /// ESC [ ? 1047 l - Restore xterm working buffer (with backscroll)
  91. /// </summary>
  92. /// <remarks>
  93. /// From
  94. /// https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Functions-using-CSI-_-ordered-by-the-final-character_s_
  95. /// Use Normal Screen Buffer, xterm. Clear the screen first if in the Alternate Screen Buffer.
  96. /// </remarks>
  97. public static readonly string CSI_RestoreAltBufferWithBackscroll = CSI + "?1047l";
  98. /// <summary>
  99. /// ESC [ ? 1049 l - Restore cursor position and restore xterm working buffer (with backscroll)
  100. /// </summary>
  101. /// <remarks>
  102. /// From
  103. /// https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Functions-using-CSI-_-ordered-by-the-final-character_s_
  104. /// Use Normal Screen Buffer and restore cursor as in DECRC, xterm.
  105. /// resource.This combines the effects of the 1047 and 1048 modes.
  106. /// </remarks>
  107. public static readonly string CSI_RestoreCursorAndRestoreAltBufferWithBackscroll = CSI + "?1049l";
  108. /// <summary>
  109. /// ESC [ ? 1049 h - Save cursor position and activate xterm alternative buffer (no backscroll)
  110. /// </summary>
  111. /// <remarks>
  112. /// From
  113. /// https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Functions-using-CSI-_-ordered-by-the-final-character_s_
  114. /// Save cursor as in DECSC, xterm. After saving the cursor, switch to the Alternate Screen Buffer,
  115. /// clearing it first.
  116. /// This control combines the effects of the 1047 and 1048 modes.
  117. /// Use this with terminfo-based applications rather than the 47 mode.
  118. /// </remarks>
  119. public static readonly string CSI_SaveCursorAndActivateAltBufferNoBackscroll = CSI + "?1049h";
  120. //private static bool isButtonReleased;
  121. private static bool _isButtonClicked;
  122. private static bool _isButtonDoubleClicked;
  123. //private static MouseFlags? lastMouseButtonReleased;
  124. // QUESTION: What's the difference between isButtonClicked and isButtonPressed?
  125. // Some clarity or comments would be handy, here.
  126. // It also seems like some enforcement of valid states might be a good idea.
  127. private static bool _isButtonPressed;
  128. private static bool _isButtonTripleClicked;
  129. private static MouseFlags? _lastMouseButtonPressed;
  130. private static Point? _point;
  131. /// <summary>
  132. /// Control sequence for disabling mouse events.
  133. /// </summary>
  134. public static string CSI_DisableMouseEvents { get; set; } =
  135. CSI_DisableAnyEventMouse + CSI_DisableUrxvtExtModeMouse + CSI_DisableSgrExtModeMouse;
  136. /// <summary>
  137. /// Control sequence for enabling mouse events.
  138. /// </summary>
  139. public static string CSI_EnableMouseEvents { get; set; } =
  140. CSI_EnableAnyEventMouse + CSI_EnableUrxvtExtModeMouse + CSI_EnableSgrExtModeMouse;
  141. /// <summary>
  142. /// ESC [ x J - Clears part of the screen. See <see cref="ClearScreenOptions"/>.
  143. /// </summary>
  144. /// <param name="option"></param>
  145. /// <returns></returns>
  146. public static string CSI_ClearScreen (ClearScreenOptions option) { return $"{CSI}{(int)option}J"; }
  147. /// <summary>
  148. /// Specify the incomplete <see cref="ConsoleKeyInfo"/> array not yet recognized as valid ANSI escape sequence.
  149. /// </summary>
  150. public static ConsoleKeyInfo []? IncompleteCkInfos { get; set; }
  151. /// <summary>
  152. /// Represent a response that was requested by an invalid terminator.
  153. /// </summary>
  154. public static string? InvalidRequestTerminator { get; set; }
  155. /// <summary>
  156. /// Decodes an ANSI escape sequence.
  157. /// </summary>
  158. /// <param name="escSeqRequests">The <see cref="AnsiEscapeSequenceRequests"/> which may contain a request.</param>
  159. /// <param name="newConsoleKeyInfo">The <see cref="ConsoleKeyInfo"/> which may change.</param>
  160. /// <param name="key">The <see cref="ConsoleKey"/> which may change.</param>
  161. /// <param name="cki">The <see cref="ConsoleKeyInfo"/> array.</param>
  162. /// <param name="mod">The <see cref="ConsoleModifiers"/> which may change.</param>
  163. /// <param name="c1Control">The control returned by the <see cref="GetC1ControlChar"/> method.</param>
  164. /// <param name="code">The code returned by the <see cref="GetEscapeResult(char[])"/> method.</param>
  165. /// <param name="values">The values returned by the <see cref="GetEscapeResult(char[])"/> method.</param>
  166. /// <param name="terminator">The terminator returned by the <see cref="GetEscapeResult(char[])"/> method.</param>
  167. /// <param name="isMouse">Indicates if the escape sequence is a mouse event.</param>
  168. /// <param name="buttonState">The <see cref="MouseFlags"/> button state.</param>
  169. /// <param name="pos">The <see cref="MouseFlags"/> position.</param>
  170. /// <param name="seqReqStatus">The <see cref="AnsiEscapeSequenceRequestStatus"/> object.</param>
  171. /// <param name="continuousButtonPressedHandler">The handler that will process the event.</param>
  172. public static void DecodeEscSeq (
  173. AnsiEscapeSequenceRequests? escSeqRequests,
  174. ref ConsoleKeyInfo newConsoleKeyInfo,
  175. ref ConsoleKey key,
  176. ConsoleKeyInfo [] cki,
  177. ref ConsoleModifiers mod,
  178. out string c1Control,
  179. out string code,
  180. out string [] values,
  181. out string terminator,
  182. out bool isMouse,
  183. out List<MouseFlags> buttonState,
  184. out Point pos,
  185. out AnsiEscapeSequenceRequestStatus? seqReqStatus,
  186. Action<MouseFlags, Point> continuousButtonPressedHandler
  187. )
  188. {
  189. char [] kChars = GetKeyCharArray (cki);
  190. (c1Control, code, values, terminator) = GetEscapeResult (kChars);
  191. isMouse = false;
  192. buttonState = [0];
  193. pos = default (Point);
  194. seqReqStatus = null;
  195. var keyChar = '\0';
  196. switch (c1Control)
  197. {
  198. case "ESC":
  199. if (values is null && string.IsNullOrEmpty (terminator))
  200. {
  201. key = ConsoleKey.Escape;
  202. newConsoleKeyInfo = new (
  203. cki [0].KeyChar,
  204. key,
  205. (mod & ConsoleModifiers.Shift) != 0,
  206. (mod & ConsoleModifiers.Alt) != 0,
  207. (mod & ConsoleModifiers.Control) != 0);
  208. }
  209. else if ((uint)cki [1].KeyChar >= 1 && (uint)cki [1].KeyChar <= 26 && (uint)cki [1].KeyChar != '\n' && (uint)cki [1].KeyChar != '\r')
  210. {
  211. key = (ConsoleKey)(char)(cki [1].KeyChar + (uint)ConsoleKey.A - 1);
  212. mod = ConsoleModifiers.Alt | ConsoleModifiers.Control;
  213. newConsoleKeyInfo = new (
  214. cki [1].KeyChar,
  215. key,
  216. (mod & ConsoleModifiers.Shift) != 0,
  217. (mod & ConsoleModifiers.Alt) != 0,
  218. (mod & ConsoleModifiers.Control) != 0);
  219. }
  220. else if (cki [1].KeyChar >= 65 && cki [1].KeyChar <= 90)
  221. {
  222. key = (ConsoleKey)cki [1].KeyChar;
  223. mod = ConsoleModifiers.Shift | ConsoleModifiers.Alt;
  224. newConsoleKeyInfo = new (
  225. cki [1].KeyChar,
  226. (ConsoleKey)Math.Min ((uint)key, 255),
  227. (mod & ConsoleModifiers.Shift) != 0,
  228. (mod & ConsoleModifiers.Alt) != 0,
  229. (mod & ConsoleModifiers.Control) != 0);
  230. }
  231. else if (cki [1].KeyChar >= 97 && cki [1].KeyChar <= 122)
  232. {
  233. key = (ConsoleKey)cki [1].KeyChar.ToString ().ToUpper () [0];
  234. mod = ConsoleModifiers.Alt;
  235. newConsoleKeyInfo = new (
  236. cki [1].KeyChar,
  237. (ConsoleKey)Math.Min ((uint)key, 255),
  238. (mod & ConsoleModifiers.Shift) != 0,
  239. (mod & ConsoleModifiers.Alt) != 0,
  240. (mod & ConsoleModifiers.Control) != 0);
  241. }
  242. else if (cki [1].KeyChar is '\0' or ' ')
  243. {
  244. key = ConsoleKey.Spacebar;
  245. if (kChars.Length > 1 && kChars [1] == '\0')
  246. {
  247. mod = ConsoleModifiers.Alt | ConsoleModifiers.Control;
  248. }
  249. else
  250. {
  251. mod = ConsoleModifiers.Shift | ConsoleModifiers.Alt;
  252. }
  253. newConsoleKeyInfo = new (
  254. cki [1].KeyChar,
  255. (ConsoleKey)Math.Min ((uint)key, 255),
  256. (mod & ConsoleModifiers.Shift) != 0,
  257. (mod & ConsoleModifiers.Alt) != 0,
  258. (mod & ConsoleModifiers.Control) != 0);
  259. }
  260. else if (cki [1].KeyChar is '\n' or '\r')
  261. {
  262. key = ConsoleKey.Enter;
  263. if (kChars.Length > 1 && kChars [1] == '\n')
  264. {
  265. mod = ConsoleModifiers.Alt | ConsoleModifiers.Control;
  266. }
  267. else
  268. {
  269. mod = ConsoleModifiers.Shift | ConsoleModifiers.Alt;
  270. }
  271. newConsoleKeyInfo = new (
  272. cki [1].KeyChar,
  273. (ConsoleKey)Math.Min ((uint)key, 255),
  274. (mod & ConsoleModifiers.Shift) != 0,
  275. (mod & ConsoleModifiers.Alt) != 0,
  276. (mod & ConsoleModifiers.Control) != 0);
  277. }
  278. else
  279. {
  280. key = (ConsoleKey)cki [1].KeyChar;
  281. mod = ConsoleModifiers.Alt;
  282. newConsoleKeyInfo = new (
  283. cki [1].KeyChar,
  284. (ConsoleKey)Math.Min ((uint)key, 255),
  285. (mod & ConsoleModifiers.Shift) != 0,
  286. (mod & ConsoleModifiers.Alt) != 0,
  287. (mod & ConsoleModifiers.Control) != 0);
  288. }
  289. break;
  290. case "SS3":
  291. key = GetConsoleKey (terminator [0], values [0], ref mod, ref keyChar);
  292. newConsoleKeyInfo = new (
  293. keyChar,
  294. key,
  295. (mod & ConsoleModifiers.Shift) != 0,
  296. (mod & ConsoleModifiers.Alt) != 0,
  297. (mod & ConsoleModifiers.Control) != 0);
  298. break;
  299. case "CSI":
  300. if (!string.IsNullOrEmpty (code) && code == "<")
  301. {
  302. GetMouse (cki, out buttonState, out pos, continuousButtonPressedHandler);
  303. isMouse = true;
  304. return;
  305. }
  306. if (escSeqRequests is { } && escSeqRequests.HasResponse (terminator, out seqReqStatus))
  307. {
  308. escSeqRequests.Remove (seqReqStatus);
  309. return;
  310. }
  311. if (!string.IsNullOrEmpty (terminator))
  312. {
  313. System.Diagnostics.Debug.Assert (terminator.Length == 1);
  314. key = GetConsoleKey (terminator [0], values [0], ref mod, ref keyChar);
  315. if (key != 0 && values.Length > 1)
  316. {
  317. mod |= GetConsoleModifiers (values [1]);
  318. }
  319. if (keyChar != 0 || key != 0 || mod != 0)
  320. {
  321. newConsoleKeyInfo = new (
  322. keyChar,
  323. key,
  324. (mod & ConsoleModifiers.Shift) != 0,
  325. (mod & ConsoleModifiers.Alt) != 0,
  326. (mod & ConsoleModifiers.Control) != 0);
  327. }
  328. else
  329. {
  330. // It's request response that wasn't handled by a valid request terminator
  331. System.Diagnostics.Debug.Assert (escSeqRequests is null or { Statuses.Count: > 0 });
  332. InvalidRequestTerminator = ToString (cki);
  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.Key == 0)
  998. {
  999. key = (ConsoleKey)(char)(consoleKeyInfo.KeyChar + (uint)ConsoleKey.A - 1);
  1000. newConsoleKeyInfo = new (
  1001. consoleKeyInfo.KeyChar,
  1002. key,
  1003. (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0,
  1004. (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
  1005. true);
  1006. }
  1007. break;
  1008. case 127: // DEL
  1009. key = ConsoleKey.Backspace;
  1010. newConsoleKeyInfo = new (
  1011. consoleKeyInfo.KeyChar,
  1012. key,
  1013. (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0,
  1014. (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
  1015. (consoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0);
  1016. break;
  1017. default:
  1018. uint ck = MapKeyCodeToConsoleKey ((KeyCode)consoleKeyInfo.KeyChar, out bool isConsoleKey);
  1019. if (isConsoleKey)
  1020. {
  1021. key = (ConsoleKey)ck;
  1022. }
  1023. newConsoleKeyInfo = new (
  1024. keyChar,
  1025. key,
  1026. GetShiftMod (consoleKeyInfo.Modifiers),
  1027. (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0,
  1028. (consoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0);
  1029. break;
  1030. }
  1031. return newConsoleKeyInfo;
  1032. bool GetShiftMod (ConsoleModifiers modifiers)
  1033. {
  1034. if (consoleKeyInfo.KeyChar is >= (char)ConsoleKey.A and <= (char)ConsoleKey.Z && modifiers == ConsoleModifiers.None)
  1035. {
  1036. return true;
  1037. }
  1038. return (modifiers & ConsoleModifiers.Shift) != 0;
  1039. }
  1040. }
  1041. private static MouseFlags _lastMouseFlags;
  1042. /// <summary>
  1043. /// Provides a handler to be invoked when mouse continuous button pressed is processed.
  1044. /// </summary>
  1045. public static event EventHandler<MouseEventArgs> ContinuousButtonPressed;
  1046. /// <summary>
  1047. /// Provides a default mouse event handler that can be used by any driver.
  1048. /// </summary>
  1049. /// <param name="mouseFlag">The mouse flags event.</param>
  1050. /// <param name="pos">The mouse position.</param>
  1051. public static void ProcessMouseEvent (MouseFlags mouseFlag, Point pos)
  1052. {
  1053. bool WasButtonReleased (MouseFlags flag)
  1054. {
  1055. return flag.HasFlag (MouseFlags.Button1Released)
  1056. || flag.HasFlag (MouseFlags.Button2Released)
  1057. || flag.HasFlag (MouseFlags.Button3Released)
  1058. || flag.HasFlag (MouseFlags.Button4Released);
  1059. }
  1060. bool IsButtonNotPressed (MouseFlags flag)
  1061. {
  1062. return !flag.HasFlag (MouseFlags.Button1Pressed)
  1063. && !flag.HasFlag (MouseFlags.Button2Pressed)
  1064. && !flag.HasFlag (MouseFlags.Button3Pressed)
  1065. && !flag.HasFlag (MouseFlags.Button4Pressed);
  1066. }
  1067. bool IsButtonClickedOrDoubleClicked (MouseFlags flag)
  1068. {
  1069. return flag.HasFlag (MouseFlags.Button1Clicked)
  1070. || flag.HasFlag (MouseFlags.Button2Clicked)
  1071. || flag.HasFlag (MouseFlags.Button3Clicked)
  1072. || flag.HasFlag (MouseFlags.Button4Clicked)
  1073. || flag.HasFlag (MouseFlags.Button1DoubleClicked)
  1074. || flag.HasFlag (MouseFlags.Button2DoubleClicked)
  1075. || flag.HasFlag (MouseFlags.Button3DoubleClicked)
  1076. || flag.HasFlag (MouseFlags.Button4DoubleClicked);
  1077. }
  1078. if ((WasButtonReleased (mouseFlag) && IsButtonNotPressed (_lastMouseFlags)) || (IsButtonClickedOrDoubleClicked (mouseFlag) && _lastMouseFlags == 0))
  1079. {
  1080. return;
  1081. }
  1082. _lastMouseFlags = mouseFlag;
  1083. var me = new MouseEventArgs { Flags = mouseFlag, Position = pos };
  1084. ContinuousButtonPressed?.Invoke ((mouseFlag, pos), me);
  1085. }
  1086. /// <summary>
  1087. /// A helper to resize the <see cref="ConsoleKeyInfo"/> as needed.
  1088. /// </summary>
  1089. /// <param name="consoleKeyInfo">The <see cref="ConsoleKeyInfo"/>.</param>
  1090. /// <param name="cki">The <see cref="ConsoleKeyInfo"/> array to resize.</param>
  1091. /// <returns>The <see cref="ConsoleKeyInfo"/> resized.</returns>
  1092. public static ConsoleKeyInfo [] ResizeArray (ConsoleKeyInfo consoleKeyInfo, ConsoleKeyInfo [] cki)
  1093. {
  1094. Array.Resize (ref cki, cki is null ? 1 : cki.Length + 1);
  1095. cki [^1] = consoleKeyInfo;
  1096. return cki;
  1097. }
  1098. /// <summary>
  1099. /// Insert a <see cref="ConsoleKeyInfo"/> array into the another <see cref="ConsoleKeyInfo"/> array at the specified
  1100. /// index.
  1101. /// </summary>
  1102. /// <param name="toInsert">The array to insert.</param>
  1103. /// <param name="cki">The array where will be added the array.</param>
  1104. /// <param name="index">The start index to insert the array, default is 0.</param>
  1105. /// <returns>The <see cref="ConsoleKeyInfo"/> array with another array inserted.</returns>
  1106. public static ConsoleKeyInfo [] InsertArray ([CanBeNull] ConsoleKeyInfo [] toInsert, ConsoleKeyInfo [] cki, int index = 0)
  1107. {
  1108. if (toInsert is null)
  1109. {
  1110. return cki;
  1111. }
  1112. if (cki is null)
  1113. {
  1114. return toInsert;
  1115. }
  1116. if (index < 0)
  1117. {
  1118. index = 0;
  1119. }
  1120. ConsoleKeyInfo [] backupCki = cki.Clone () as ConsoleKeyInfo [];
  1121. Array.Resize (ref cki, cki.Length + toInsert.Length);
  1122. for (var i = 0; i < cki.Length; i++)
  1123. {
  1124. if (i == index)
  1125. {
  1126. for (var j = 0; j < toInsert.Length; j++)
  1127. {
  1128. cki [i] = toInsert [j];
  1129. i++;
  1130. }
  1131. for (int k = index; k < backupCki!.Length; k++)
  1132. {
  1133. cki [i] = backupCki [k];
  1134. i++;
  1135. }
  1136. }
  1137. else
  1138. {
  1139. cki [i] = backupCki! [i];
  1140. }
  1141. }
  1142. return cki;
  1143. }
  1144. private static MouseFlags GetButtonClicked (MouseFlags mouseFlag)
  1145. {
  1146. MouseFlags mf = default;
  1147. switch (mouseFlag)
  1148. {
  1149. case MouseFlags.Button1Released:
  1150. mf = MouseFlags.Button1Clicked;
  1151. break;
  1152. case MouseFlags.Button2Released:
  1153. mf = MouseFlags.Button2Clicked;
  1154. break;
  1155. case MouseFlags.Button3Released:
  1156. mf = MouseFlags.Button3Clicked;
  1157. break;
  1158. }
  1159. return mf;
  1160. }
  1161. private static MouseFlags GetButtonDoubleClicked (MouseFlags mouseFlag)
  1162. {
  1163. MouseFlags mf = default;
  1164. switch (mouseFlag)
  1165. {
  1166. case MouseFlags.Button1Pressed:
  1167. mf = MouseFlags.Button1DoubleClicked;
  1168. break;
  1169. case MouseFlags.Button2Pressed:
  1170. mf = MouseFlags.Button2DoubleClicked;
  1171. break;
  1172. case MouseFlags.Button3Pressed:
  1173. mf = MouseFlags.Button3DoubleClicked;
  1174. break;
  1175. }
  1176. return mf;
  1177. }
  1178. private static MouseFlags GetButtonTripleClicked (MouseFlags mouseFlag)
  1179. {
  1180. MouseFlags mf = default;
  1181. switch (mouseFlag)
  1182. {
  1183. case MouseFlags.Button1Pressed:
  1184. mf = MouseFlags.Button1TripleClicked;
  1185. break;
  1186. case MouseFlags.Button2Pressed:
  1187. mf = MouseFlags.Button2TripleClicked;
  1188. break;
  1189. case MouseFlags.Button3Pressed:
  1190. mf = MouseFlags.Button3TripleClicked;
  1191. break;
  1192. }
  1193. return mf;
  1194. }
  1195. internal static KeyCode MapKey (ConsoleKeyInfo keyInfo)
  1196. {
  1197. switch (keyInfo.Key)
  1198. {
  1199. case ConsoleKey.OemPeriod:
  1200. case ConsoleKey.OemComma:
  1201. case ConsoleKey.OemPlus:
  1202. case ConsoleKey.OemMinus:
  1203. case ConsoleKey.Packet:
  1204. case ConsoleKey.Oem1:
  1205. case ConsoleKey.Oem2:
  1206. case ConsoleKey.Oem3:
  1207. case ConsoleKey.Oem4:
  1208. case ConsoleKey.Oem5:
  1209. case ConsoleKey.Oem6:
  1210. case ConsoleKey.Oem7:
  1211. case ConsoleKey.Oem8:
  1212. case ConsoleKey.Oem102:
  1213. if (keyInfo.KeyChar == 0)
  1214. {
  1215. // If the keyChar is 0, keyInfo.Key value is not a printable character.
  1216. return KeyCode.Null; // MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode)keyInfo.Key);
  1217. }
  1218. if (keyInfo.Modifiers != ConsoleModifiers.Shift)
  1219. {
  1220. // If Shift wasn't down we don't need to do anything but return the keyInfo.KeyChar
  1221. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar);
  1222. }
  1223. // Strip off Shift - We got here because they KeyChar from Windows is the shifted char (e.g. "Ç")
  1224. // and passing on Shift would be redundant.
  1225. return MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)keyInfo.KeyChar);
  1226. }
  1227. // Handle control keys whose VK codes match the related ASCII value (those below ASCII 33) like ESC
  1228. if (keyInfo.Key != ConsoleKey.None && Enum.IsDefined (typeof (KeyCode), (uint)keyInfo.Key))
  1229. {
  1230. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control) && keyInfo.Key == ConsoleKey.I)
  1231. {
  1232. return KeyCode.Tab;
  1233. }
  1234. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)(uint)keyInfo.Key);
  1235. }
  1236. // Handle control keys (e.g. CursorUp)
  1237. if (keyInfo.Key != ConsoleKey.None
  1238. && Enum.IsDefined (typeof (KeyCode), (uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint))
  1239. {
  1240. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)((uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint));
  1241. }
  1242. if ((ConsoleKey)keyInfo.KeyChar is >= ConsoleKey.A and <= ConsoleKey.Z)
  1243. {
  1244. // Shifted
  1245. keyInfo = new (
  1246. keyInfo.KeyChar,
  1247. (ConsoleKey)keyInfo.KeyChar,
  1248. true,
  1249. keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt),
  1250. keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control));
  1251. }
  1252. if ((ConsoleKey)keyInfo.KeyChar - 32 is >= ConsoleKey.A and <= ConsoleKey.Z)
  1253. {
  1254. // Unshifted
  1255. keyInfo = new (
  1256. keyInfo.KeyChar,
  1257. (ConsoleKey)(keyInfo.KeyChar - 32),
  1258. false,
  1259. keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt),
  1260. keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control));
  1261. }
  1262. if (keyInfo.Key is >= ConsoleKey.A and <= ConsoleKey.Z)
  1263. {
  1264. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt)
  1265. || keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control))
  1266. {
  1267. // NetDriver doesn't support Shift-Ctrl/Shift-Alt combos
  1268. return MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)keyInfo.Key);
  1269. }
  1270. if (keyInfo.Modifiers == ConsoleModifiers.Shift)
  1271. {
  1272. // If ShiftMask is on add the ShiftMask
  1273. if (char.IsUpper (keyInfo.KeyChar))
  1274. {
  1275. return (KeyCode)keyInfo.Key | KeyCode.ShiftMask;
  1276. }
  1277. }
  1278. return (KeyCode)keyInfo.Key;
  1279. }
  1280. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar);
  1281. }
  1282. private static async Task ProcessButtonClickedAsync ()
  1283. {
  1284. await Task.Delay (300);
  1285. _isButtonClicked = false;
  1286. }
  1287. private static async Task ProcessButtonDoubleClickedAsync ()
  1288. {
  1289. await Task.Delay (300);
  1290. _isButtonDoubleClicked = false;
  1291. }
  1292. private static async Task ProcessContinuousButtonPressedAsync (MouseFlags mouseFlag, Action<MouseFlags, Point> continuousButtonPressedHandler)
  1293. {
  1294. // PERF: Pause and poll in a hot loop.
  1295. // This should be replaced with event dispatch and a synchronization primitive such as AutoResetEvent.
  1296. // Will make a massive difference in responsiveness.
  1297. while (_isButtonPressed)
  1298. {
  1299. await Task.Delay (100);
  1300. View view = Application.WantContinuousButtonPressedView;
  1301. if (view is null)
  1302. {
  1303. break;
  1304. }
  1305. if (_isButtonPressed && _lastMouseButtonPressed is { } && (mouseFlag & MouseFlags.ReportMousePosition) == 0)
  1306. {
  1307. Application.Invoke (() => continuousButtonPressedHandler (mouseFlag, _point ?? Point.Empty));
  1308. }
  1309. }
  1310. }
  1311. private static MouseFlags SetControlKeyStates (MouseFlags buttonState, MouseFlags mouseFlag)
  1312. {
  1313. if ((buttonState & MouseFlags.ButtonCtrl) != 0 && (mouseFlag & MouseFlags.ButtonCtrl) == 0)
  1314. {
  1315. mouseFlag |= MouseFlags.ButtonCtrl;
  1316. }
  1317. if ((buttonState & MouseFlags.ButtonShift) != 0 && (mouseFlag & MouseFlags.ButtonShift) == 0)
  1318. {
  1319. mouseFlag |= MouseFlags.ButtonShift;
  1320. }
  1321. if ((buttonState & MouseFlags.ButtonAlt) != 0 && (mouseFlag & MouseFlags.ButtonAlt) == 0)
  1322. {
  1323. mouseFlag |= MouseFlags.ButtonAlt;
  1324. }
  1325. return mouseFlag;
  1326. }
  1327. /// <summary>
  1328. /// Split a raw string into a list of string with the correct ansi escape sequence.
  1329. /// </summary>
  1330. /// <param name="rawData">The raw string containing one or many ansi escape sequence.</param>
  1331. /// <returns>A list with a valid ansi escape sequence.</returns>
  1332. public static List<string> SplitEscapeRawString (string rawData)
  1333. {
  1334. List<string> splitList = [];
  1335. var isEscSeq = false;
  1336. var split = string.Empty;
  1337. char previousChar = '\0';
  1338. for (var i = 0; i < rawData.Length; i++)
  1339. {
  1340. char c = rawData [i];
  1341. if (c == '\u001B')
  1342. {
  1343. isEscSeq = true;
  1344. split = AddAndClearSplit ();
  1345. split += c.ToString ();
  1346. }
  1347. else if (!isEscSeq && c >= Key.Space)
  1348. {
  1349. split = AddAndClearSplit ();
  1350. splitList.Add (c.ToString ());
  1351. }
  1352. else if ((previousChar != '\u001B' && c <= Key.Space) || (previousChar != '\u001B' && c == 127)
  1353. || (char.IsLetter (previousChar) && char.IsLower (c) && char.IsLetter (c))
  1354. || (!string.IsNullOrEmpty (split) && split.Length > 2 && char.IsLetter (previousChar) && char.IsLetterOrDigit (c))
  1355. || (!string.IsNullOrEmpty (split) && split.Length > 2 && char.IsLetter (previousChar) && char.IsPunctuation (c))
  1356. || (!string.IsNullOrEmpty (split) && split.Length > 2 && char.IsLetter (previousChar) && char.IsSymbol (c)))
  1357. {
  1358. isEscSeq = false;
  1359. split = AddAndClearSplit ();
  1360. splitList.Add (c.ToString ());
  1361. }
  1362. else
  1363. {
  1364. split += c.ToString ();
  1365. }
  1366. if (!string.IsNullOrEmpty (split) && i == rawData.Length - 1)
  1367. {
  1368. splitList.Add (split);
  1369. }
  1370. previousChar = c;
  1371. }
  1372. return splitList;
  1373. string AddAndClearSplit ()
  1374. {
  1375. if (!string.IsNullOrEmpty (split))
  1376. {
  1377. splitList.Add (split);
  1378. split = string.Empty;
  1379. }
  1380. return split;
  1381. }
  1382. }
  1383. /// <summary>
  1384. /// Convert a <see cref="ConsoleKeyInfo"/> array to string.
  1385. /// </summary>
  1386. /// <param name="consoleKeyInfos"></param>
  1387. /// <returns>The string representing the array.</returns>
  1388. public static string ToString (ConsoleKeyInfo [] consoleKeyInfos)
  1389. {
  1390. StringBuilder sb = new ();
  1391. foreach (ConsoleKeyInfo keyChar in consoleKeyInfos)
  1392. {
  1393. sb.Append (keyChar.KeyChar);
  1394. }
  1395. return sb.ToString ();
  1396. }
  1397. /// <summary>
  1398. /// Convert a string to <see cref="ConsoleKeyInfo"/> array.
  1399. /// </summary>
  1400. /// <param name="ansi"></param>
  1401. /// <returns>The <see cref="ConsoleKeyInfo"/>representing the string.</returns>
  1402. public static ConsoleKeyInfo [] ToConsoleKeyInfoArray (string ansi)
  1403. {
  1404. if (ansi is null)
  1405. {
  1406. return null;
  1407. }
  1408. ConsoleKeyInfo [] cki = new ConsoleKeyInfo [ansi.Length];
  1409. for (var i = 0; i < ansi.Length; i++)
  1410. {
  1411. char c = ansi [i];
  1412. cki [i] = new (c, 0, false, false, false);
  1413. }
  1414. return cki;
  1415. }
  1416. #region Cursor
  1417. //ESC [ M - RI Reverse Index – Performs the reverse operation of \n, moves cursor up one line, maintains horizontal position, scrolls buffer if necessary*
  1418. /// <summary>
  1419. /// ESC [ 7 - Save Cursor Position in Memory**
  1420. /// </summary>
  1421. public static readonly string CSI_SaveCursorPosition = CSI + "7";
  1422. /// <summary>
  1423. /// ESC [ 8 - DECSR Restore Cursor Position from Memory**
  1424. /// </summary>
  1425. public static readonly string CSI_RestoreCursorPosition = CSI + "8";
  1426. /// <summary>
  1427. /// ESC [ 8 ; height ; width t - Set Terminal Window Size
  1428. /// https://terminalguide.namepad.de/seq/csi_st-8/
  1429. /// </summary>
  1430. public static string CSI_SetTerminalWindowSize (int height, int width) { return $"{CSI}8;{height};{width}t"; }
  1431. //ESC [ < n > A - CUU - Cursor Up Cursor up by < n >
  1432. //ESC [ < n > B - CUD - Cursor Down Cursor down by < n >
  1433. //ESC [ < n > C - CUF - Cursor Forward Cursor forward (Right) by < n >
  1434. //ESC [ < n > D - CUB - Cursor Backward Cursor backward (Left) by < n >
  1435. //ESC [ < n > E - CNL - Cursor Next Line - Cursor down < n > lines from current position
  1436. //ESC [ < n > F - CPL - Cursor Previous Line Cursor up < n > lines from current position
  1437. //ESC [ < n > G - CHA - Cursor Horizontal Absolute Cursor moves to < n > th position horizontally in the current line
  1438. //ESC [ < n > d - VPA - Vertical Line Position Absolute Cursor moves to the < n > th position vertically in the current column
  1439. /// <summary>
  1440. /// ESC [ y ; x H - CUP Cursor Position - Cursor moves to x ; y coordinate within the viewport, where x is the column
  1441. /// of the y line
  1442. /// </summary>
  1443. /// <param name="row">Origin is (1,1).</param>
  1444. /// <param name="col">Origin is (1,1).</param>
  1445. /// <returns></returns>
  1446. public static string CSI_SetCursorPosition (int row, int col) { return $"{CSI}{row};{col}H"; }
  1447. //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
  1448. //ESC [ s - ANSISYSSC Save Cursor – Ansi.sys emulation **With no parameters, performs a save cursor operation like DECSC
  1449. //ESC [ u - ANSISYSRC Restore Cursor – Ansi.sys emulation **With no parameters, performs a restore cursor operation like DECRC
  1450. //ESC [ ? 12 h - ATT160 Text Cursor Enable Blinking Start the cursor blinking
  1451. //ESC [ ? 12 l - ATT160 Text Cursor Disable Blinking Stop blinking the cursor
  1452. /// <summary>
  1453. /// ESC [ ? 25 h - DECTCEM Text Cursor Enable Mode Show Show the cursor
  1454. /// </summary>
  1455. public static readonly string CSI_ShowCursor = CSI + "?25h";
  1456. /// <summary>
  1457. /// ESC [ ? 25 l - DECTCEM Text Cursor Enable Mode Hide Hide the cursor
  1458. /// </summary>
  1459. public static readonly string CSI_HideCursor = CSI + "?25l";
  1460. //ESC [ ? 12 h - ATT160 Text Cursor Enable Blinking Start the cursor blinking
  1461. //ESC [ ? 12 l - ATT160 Text Cursor Disable Blinking Stop blinking the cursor
  1462. //ESC [ ? 25 h - DECTCEM Text Cursor Enable Mode Show Show the cursor
  1463. //ESC [ ? 25 l - DECTCEM Text Cursor Enable Mode Hide Hide the cursor
  1464. /// <summary>
  1465. /// Styles for ANSI ESC "[x q" - Set Cursor Style
  1466. /// </summary>
  1467. public enum DECSCUSR_Style
  1468. {
  1469. /// <summary>
  1470. /// DECSCUSR - User Shape - Default cursor shape configured by the user
  1471. /// </summary>
  1472. UserShape = 0,
  1473. /// <summary>
  1474. /// DECSCUSR - Blinking Block - Blinking block cursor shape
  1475. /// </summary>
  1476. BlinkingBlock = 1,
  1477. /// <summary>
  1478. /// DECSCUSR - Steady Block - Steady block cursor shape
  1479. /// </summary>
  1480. SteadyBlock = 2,
  1481. /// <summary>
  1482. /// DECSCUSR - Blinking Underline - Blinking underline cursor shape
  1483. /// </summary>
  1484. BlinkingUnderline = 3,
  1485. /// <summary>
  1486. /// DECSCUSR - Steady Underline - Steady underline cursor shape
  1487. /// </summary>
  1488. SteadyUnderline = 4,
  1489. /// <summary>
  1490. /// DECSCUSR - Blinking Bar - Blinking bar cursor shape
  1491. /// </summary>
  1492. BlinkingBar = 5,
  1493. /// <summary>
  1494. /// DECSCUSR - Steady Bar - Steady bar cursor shape
  1495. /// </summary>
  1496. SteadyBar = 6
  1497. }
  1498. /// <summary>
  1499. /// ESC [ n SP q - Select Cursor Style (DECSCUSR)
  1500. /// https://terminalguide.namepad.de/seq/csi_sq_t_space/
  1501. /// </summary>
  1502. /// <param name="style"></param>
  1503. /// <returns></returns>
  1504. public static string CSI_SetCursorStyle (DECSCUSR_Style style) { return $"{CSI}{(int)style} q"; }
  1505. #endregion
  1506. #region Colors
  1507. /// <summary>
  1508. /// ESC [ (n) m - SGR - Set Graphics Rendition - Set the format of the screen and text as specified by (n)
  1509. /// This command is special in that the (n) position can accept between 0 and 16 parameters separated by semicolons.
  1510. /// When no parameters are specified, it is treated the same as a single 0 parameter.
  1511. /// https://terminalguide.namepad.de/seq/csi_sm/
  1512. /// </summary>
  1513. public static string CSI_SetGraphicsRendition (params int [] parameters) { return $"{CSI}{string.Join (";", parameters)}m"; }
  1514. /// <summary>
  1515. /// ESC [ (n) m - Uses <see cref="CSI_SetGraphicsRendition(int[])"/> to set the foreground color.
  1516. /// </summary>
  1517. /// <param name="code">One of the 16 color codes.</param>
  1518. /// <returns></returns>
  1519. public static string CSI_SetForegroundColor (AnsiColorCode code) { return CSI_SetGraphicsRendition ((int)code); }
  1520. /// <summary>
  1521. /// ESC [ (n) m - Uses <see cref="CSI_SetGraphicsRendition(int[])"/> to set the background color.
  1522. /// </summary>
  1523. /// <param name="code">One of the 16 color codes.</param>
  1524. /// <returns></returns>
  1525. public static string CSI_SetBackgroundColor (AnsiColorCode code) { return CSI_SetGraphicsRendition ((int)code + 10); }
  1526. /// <summary>
  1527. /// ESC[38;5;{id}m - Set foreground color (256 colors)
  1528. /// </summary>
  1529. public static string CSI_SetForegroundColor256 (int color) { return $"{CSI}38;5;{color}m"; }
  1530. /// <summary>
  1531. /// ESC[48;5;{id}m - Set background color (256 colors)
  1532. /// </summary>
  1533. public static string CSI_SetBackgroundColor256 (int color) { return $"{CSI}48;5;{color}m"; }
  1534. /// <summary>
  1535. /// ESC[38;2;{r};{g};{b}m Set foreground color as RGB.
  1536. /// </summary>
  1537. public static string CSI_SetForegroundColorRGB (int r, int g, int b) { return $"{CSI}38;2;{r};{g};{b}m"; }
  1538. /// <summary>
  1539. /// ESC[48;2;{r};{g};{b}m Set background color as RGB.
  1540. /// </summary>
  1541. public static string CSI_SetBackgroundColorRGB (int r, int g, int b) { return $"{CSI}48;2;{r};{g};{b}m"; }
  1542. #endregion
  1543. #region Requests
  1544. /// <summary>
  1545. /// ESC [ ? 6 n - Request Cursor Position Report (?) (DECXCPR)
  1546. /// https://terminalguide.namepad.de/seq/csi_sn__p-6/
  1547. /// The terminal reply to <see cref="CSI_RequestCursorPositionReport"/>. ESC [ ? (y) ; (x) ; 1 R
  1548. /// </summary>
  1549. public static readonly AnsiEscapeSequenceRequest CSI_RequestCursorPositionReport = new () { Request = CSI + "?6n", Terminator = "R" };
  1550. /// <summary>
  1551. /// ESC [ 0 c - Send Device Attributes (Primary DA)
  1552. /// https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Application-Program-Command-functions
  1553. /// https://www.xfree86.org/current/ctlseqs.html
  1554. /// Windows Terminal v1.17 and below emits “\x1b[?1;0c”, indicating "VT101 with No Options".
  1555. /// Windows Terminal v1.18+ emits: \x1b[?61;6;7;22;23;24;28;32;42c"
  1556. /// See https://github.com/microsoft/terminal/pull/14906
  1557. /// 61 - The device conforms to level 1 of the character cell display architecture
  1558. /// (See https://github.com/microsoft/terminal/issues/15693#issuecomment-1633304497)
  1559. /// 6 = Selective erase
  1560. /// 7 = Soft fonts
  1561. /// 22 = Color text
  1562. /// 23 = Greek character sets
  1563. /// 24 = Turkish character sets
  1564. /// 28 = Rectangular area operations
  1565. /// 32 = Text macros
  1566. /// 42 = ISO Latin-2 character set
  1567. /// The terminator indicating a reply to <see cref="CSI_SendDeviceAttributes"/> or
  1568. /// <see cref="CSI_SendDeviceAttributes2"/>
  1569. /// </summary>
  1570. public static readonly AnsiEscapeSequenceRequest CSI_SendDeviceAttributes = new () { Request = CSI + "0c", Terminator = "c" };
  1571. /// <summary>
  1572. /// ESC [ > 0 c - Send Device Attributes (Secondary DA)
  1573. /// Windows Terminal v1.18+ emits: "\x1b[>0;10;1c" (vt100, firmware version 1.0, vt220)
  1574. /// The terminator indicating a reply to <see cref="CSI_SendDeviceAttributes"/> or
  1575. /// <see cref="CSI_SendDeviceAttributes2"/>
  1576. /// </summary>
  1577. public static readonly AnsiEscapeSequenceRequest CSI_SendDeviceAttributes2 = new () { Request = CSI + ">0c", Terminator = "c" };
  1578. /*
  1579. TODO: depends on https://github.com/gui-cs/Terminal.Gui/pull/3768
  1580. /// <summary>
  1581. /// CSI 16 t - Request sixel resolution (width and height in pixels)
  1582. /// </summary>
  1583. public static readonly AnsiEscapeSequenceRequest CSI_RequestSixelResolution = new () { Request = CSI + "16t", Terminator = "t" };
  1584. /// <summary>
  1585. /// CSI 14 t - Request window size in pixels (width x height)
  1586. /// </summary>
  1587. public static readonly AnsiEscapeSequenceRequest CSI_RequestWindowSizeInPixels = new () { Request = CSI + "14t", Terminator = "t" };
  1588. */
  1589. /// <summary>
  1590. /// CSI 1 8 t | yes | yes | yes | report window size in chars
  1591. /// https://terminalguide.namepad.de/seq/csi_st-18/
  1592. /// The terminator indicating a reply to <see cref="CSI_ReportTerminalSizeInChars"/> : ESC [ 8 ; height ; width t
  1593. /// </summary>
  1594. public static readonly AnsiEscapeSequenceRequest CSI_ReportTerminalSizeInChars = new () { Request = CSI + "18t", Terminator = "t", ExpectedResponseValue = "8" };
  1595. #endregion
  1596. }