EscSeqUtils.cs 65 KB

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