AnsiEscapeSequenceRequestUtils.cs 72 KB

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