EscSeqUtils.cs 74 KB

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