EscSeqUtils.cs 77 KB

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