Key.cs 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974
  1. using System.Diagnostics.CodeAnalysis;
  2. using System.Globalization;
  3. namespace Terminal.Gui;
  4. /// <summary>
  5. /// Provides an abstraction for common keyboard operations and state. Used for processing keyboard input and
  6. /// raising keyboard events.
  7. /// </summary>
  8. /// <remarks>
  9. /// <para>
  10. /// This class provides a high-level abstraction with helper methods and properties for common keyboard
  11. /// operations. Use this class instead of the <see cref="Terminal.Gui.KeyCode"/> enumeration for keyboard input
  12. /// whenever possible.
  13. /// </para>
  14. /// <para></para>
  15. /// <para>
  16. /// The default value for <see cref="Key"/> is <see cref="KeyCode.Null"/> and can be tested using
  17. /// <see cref="Key.Empty"/>.
  18. /// </para>
  19. /// <para>
  20. /// <list type="table">
  21. /// <listheader>
  22. /// <term>Concept</term><description>Definition</description>
  23. /// </listheader>
  24. /// <item>
  25. /// <term>Testing Shift State</term>
  26. /// <description>
  27. /// The <c>Is</c> properties (<see cref="IsShift"/>,<see cref="IsCtrl"/>, <see cref="IsAlt"/>)
  28. /// test for shift state; whether the key press was modified by a shift key.
  29. /// </description>
  30. /// </item>
  31. /// <item>
  32. /// <term>Adding Shift State</term>
  33. /// <description>
  34. /// The <c>With</c> properties (<see cref="WithShift"/>,<see cref="WithCtrl"/>,
  35. /// <see cref="WithAlt"/>) return a copy of the Key with the shift modifier applied. This is useful for
  36. /// specifying a key that requires a shift modifier (e.g.
  37. /// <c>var ControlAltDelete = new Key(Key.Delete).WithAlt.WithDel;</c>.
  38. /// </description>
  39. /// </item>
  40. /// <item>
  41. /// <term>Removing Shift State</term>
  42. /// <description>
  43. /// The <c>No</c> properties (<see cref="NoShift"/>,<see cref="NoCtrl"/>, <see cref="NoAlt"/>)
  44. /// return a copy of the Key with the shift modifier removed. This is useful for specifying a key that
  45. /// does not require a shift modifier (e.g. <c>var ControlDelete = ControlAltDelete.NoCtrl;</c>.
  46. /// </description>
  47. /// </item>
  48. /// <item>
  49. /// <term>Encoding of A..Z</term>
  50. /// <description>
  51. /// Lowercase alpha keys are encoded (in <see cref="Key.KeyCode"/>) as values between 65 and
  52. /// 90 corresponding to the un-shifted A to Z keys on a keyboard. Properties are provided for these
  53. /// (e.g. <see cref="Key.A"/>, <see cref="Key.B"/>, etc.). Even though the encoded values are the same
  54. /// as the ASCII values for uppercase characters, these enum values represent *lowercase*, un-shifted
  55. /// characters.
  56. /// </description>
  57. /// </item>
  58. /// <item>
  59. /// <term>Persistence as strings</term>
  60. /// <description>
  61. /// Keys are persisted as <c>"[Modifiers]+[Key]</c>. For example
  62. /// <c>new Key(Key.Delete).WithAlt.WithDel</c> is persisted as <c>"Ctrl+Alt+Delete"</c>. See
  63. /// <see cref="ToString()"/> and <see cref="TryParse(string, out Terminal.Gui.Key)"/> for more
  64. /// information.
  65. /// </description>
  66. /// </item>
  67. /// </list>
  68. /// </para>
  69. /// </remarks>
  70. public class Key : EventArgs, IEquatable<Key>
  71. {
  72. /// <summary>Constructs a new <see cref="Key"/></summary>
  73. public Key () : this (KeyCode.Null) { }
  74. /// <summary>Constructs a new <see cref="Key"/> from the provided Key value</summary>
  75. /// <param name="k">The key</param>
  76. public Key (KeyCode k) { KeyCode = k; }
  77. /// <summary>
  78. /// Copy constructor.
  79. /// </summary>
  80. /// <param name="key">The Key to copy</param>
  81. public Key (Key key)
  82. {
  83. KeyCode = key.KeyCode;
  84. Handled = key.Handled;
  85. }
  86. /// <summary>Constructs a new <see cref="Key"/> from a char.</summary>
  87. /// <remarks>
  88. /// <para>
  89. /// The key codes for the A..Z keys are encoded as values between 65 and 90 (<see cref="KeyCode.A"/> through
  90. /// <see cref="KeyCode.Z"/>). While these are the same as the ASCII values for uppercase characters, they represent
  91. /// *keys*, not characters. Therefore, this constructor will store 'A'..'Z' as <see cref="KeyCode.A"/>..
  92. /// <see cref="KeyCode.Z"/> with the <see cref="KeyCode.ShiftMask"/> set and will store `a`..`z` as
  93. /// <see cref="KeyCode.A"/>..<see cref="KeyCode.Z"/>.
  94. /// </para>
  95. /// </remarks>
  96. /// <param name="ch"></param>
  97. public Key (char ch)
  98. {
  99. switch (ch)
  100. {
  101. case >= 'A' and <= 'Z':
  102. // Upper case A..Z mean "Shift-char" so we need to add Shift
  103. KeyCode = (KeyCode)ch | KeyCode.ShiftMask;
  104. break;
  105. case >= 'a' and <= 'z':
  106. // Lower case a..z mean no shift, so we need to store as Key.A...Key.Z
  107. KeyCode = (KeyCode)(ch - 32);
  108. return;
  109. default:
  110. KeyCode = (KeyCode)ch;
  111. break;
  112. }
  113. }
  114. /// <summary>
  115. /// Constructs a new Key from a string describing the key. See
  116. /// <see cref="TryParse(string, out Terminal.Gui.Key)"/> for information on the format of the string.
  117. /// </summary>
  118. /// <param name="str">The string describing the key.</param>
  119. public Key (string str)
  120. {
  121. bool result = TryParse (str, out Key key);
  122. if (!result)
  123. {
  124. throw new ArgumentException (@$"Invalid key string: {str}", nameof (str));
  125. }
  126. KeyCode = key.KeyCode;
  127. }
  128. /// <summary>
  129. /// The key value as a Rune. This is the actual value of the key pressed, and is independent of the modifiers.
  130. /// Useful for determining if a key represents is a printable character.
  131. /// </summary>
  132. /// <remarks>
  133. /// <para>Keys with Ctrl or Alt modifiers will return <see langword="default"/>.</para>
  134. /// <para>
  135. /// If the key is a letter key (A-Z), the Rune will be the upper or lower case letter depending on whether
  136. /// <see cref="KeyCode.ShiftMask"/> is set.
  137. /// </para>
  138. /// <para>
  139. /// If the key is outside of the <see cref="KeyCode.CharMask"/> range, the returned Rune will be
  140. /// <see langword="default"/>.
  141. /// </para>
  142. /// </remarks>
  143. public Rune AsRune => ToRune (KeyCode);
  144. private bool _handled = false;
  145. /// <summary>
  146. /// Indicates if the current Key event has already been processed and the driver should stop notifying any other
  147. /// event subscriber. It's important to set this value to true specially when updating any View's layout from inside the
  148. /// subscriber method.
  149. /// </summary>
  150. public bool Handled
  151. {
  152. get => _handled;
  153. set => _handled = value;
  154. }
  155. /// <summary>Gets a value indicating whether the Alt key was pressed (real or synthesized)</summary>
  156. /// <value><see langword="true"/> if is alternate; otherwise, <see langword="false"/>.</value>
  157. public bool IsAlt => (KeyCode & KeyCode.AltMask) != 0;
  158. /// <summary>Gets a value indicating whether the Ctrl key was pressed.</summary>
  159. /// <value><see langword="true"/> if is ctrl; otherwise, <see langword="false"/>.</value>
  160. public bool IsCtrl => (KeyCode & KeyCode.CtrlMask) != 0;
  161. /// <summary>
  162. /// Gets a value indicating whether the key represents a key in the range of <see cref="KeyCode.A"/> to
  163. /// <see cref="KeyCode.Z"/>, regardless of the <see cref="KeyCode.ShiftMask"/>. This is useful for testing if a key is
  164. /// based on these keys which are special cased.
  165. /// </summary>
  166. /// <remarks>
  167. /// IMPORTANT: Lowercase alpha keys are encoded in <see cref="Key.KeyCode"/> as values between 65 and 90
  168. /// corresponding to the un-shifted A to Z keys on a keyboard. Helper properties are provided these (e.g.
  169. /// <see cref="Key.A"/>, <see cref="Key.B"/>, etc.). Even though the values are the same as the ASCII values for
  170. /// uppercase characters, these enum values represent *lowercase*, un-shifted characters.
  171. /// </remarks>
  172. public bool IsKeyCodeAtoZ => GetIsKeyCodeAtoZ (KeyCode);
  173. /// <summary>Gets a value indicating whether the Shift key was pressed.</summary>
  174. /// <value><see langword="true"/> if is shift; otherwise, <see langword="false"/>.</value>
  175. public bool IsShift => (KeyCode & KeyCode.ShiftMask) != 0;
  176. /// <summary>
  177. /// Indicates whether the <see cref="Key"/> is valid or not. Invalid keys are <see cref="Key.Empty"/>, and keys
  178. /// with only shift modifiers.
  179. /// </summary>
  180. public bool IsValid => this != Empty && NoAlt.NoShift.NoCtrl != Empty;
  181. private readonly KeyCode _keyCode;
  182. /// <summary>The encoded key value.</summary>
  183. /// <para>
  184. /// IMPORTANT: Lowercase alpha keys are encoded (in <see cref="Gui.KeyCode"/>) as values between 65 and 90
  185. /// corresponding to the un-shifted A to Z keys on a keyboard. Enum values are provided for these (e.g.
  186. /// <see cref="KeyCode.A"/>, <see cref="KeyCode.B"/>, etc.). Even though the values are the same as the ASCII values
  187. /// for uppercase characters, these enum values represent *lowercase*, un-shifted characters.
  188. /// </para>
  189. /// <remarks>This property is the backing data for the <see cref="Key"/>. It is a <see cref="KeyCode"/> enum value.</remarks>
  190. public KeyCode KeyCode
  191. {
  192. get => _keyCode;
  193. init
  194. {
  195. #if DEBUG
  196. if (GetIsKeyCodeAtoZ (value) && (value & KeyCode.Space) != 0)
  197. {
  198. throw new ArgumentException ($"Invalid KeyCode: {value} is invalid.", nameof (value));
  199. }
  200. #endif
  201. _keyCode = value;
  202. }
  203. }
  204. /// <summary>
  205. /// Helper for removing a shift modifier from a <see cref="Key"/>.
  206. /// <code>
  207. /// var ControlAltDelete = new Key(Key.Delete).WithAlt.WithDel;
  208. /// var AltDelete = ControlAltDelete.NoCtrl;
  209. /// </code>
  210. /// </summary>
  211. public Key NoAlt => new (this) { KeyCode = KeyCode & ~KeyCode.AltMask };
  212. /// <summary>
  213. /// Helper for removing a shift modifier from a <see cref="Key"/>.
  214. /// <code>
  215. /// var ControlAltDelete = new Key(Key.Delete).WithAlt.WithDel;
  216. /// var AltDelete = ControlAltDelete.NoCtrl;
  217. /// </code>
  218. /// </summary>
  219. public Key NoCtrl => new (this) { KeyCode = KeyCode & ~KeyCode.CtrlMask };
  220. /// <summary>
  221. /// Helper for removing a shift modifier from a <see cref="Key"/>.
  222. /// <code>
  223. /// var ControlAltDelete = new Key(Key.Delete).WithAlt.WithDel;
  224. /// var AltDelete = ControlAltDelete.NoCtrl;
  225. /// </code>
  226. /// </summary>
  227. public Key NoShift => new (this) { KeyCode = KeyCode & ~KeyCode.ShiftMask };
  228. /// <summary>
  229. /// Helper for specifying a shifted <see cref="Key"/>.
  230. /// <code>
  231. /// var ControlAltDelete = new Key(Key.Delete).WithAlt.WithDel;
  232. /// </code>
  233. /// </summary>
  234. public Key WithAlt => new (this) { KeyCode = KeyCode | KeyCode.AltMask };
  235. /// <summary>
  236. /// Helper for specifying a shifted <see cref="Key"/>.
  237. /// <code>
  238. /// var ControlAltDelete = new Key(Key.Delete).WithAlt.WithDel;
  239. /// </code>
  240. /// </summary>
  241. public Key WithCtrl => new (this) { KeyCode = KeyCode | KeyCode.CtrlMask };
  242. /// <summary>
  243. /// Helper for specifying a shifted <see cref="Key"/>.
  244. /// <code>
  245. /// var ControlAltDelete = new Key(Key.Delete).WithAlt.WithDel;
  246. /// </code>
  247. /// </summary>
  248. public Key WithShift => new (this) { KeyCode = KeyCode | KeyCode.ShiftMask };
  249. /// <summary>
  250. /// Tests if a KeyCode represents a key in the range of <see cref="KeyCode.A"/> to <see cref="KeyCode.Z"/>,
  251. /// regardless of the <see cref="KeyCode.ShiftMask"/>. This is useful for testing if a key is based on these keys which
  252. /// are special cased.
  253. /// </summary>
  254. /// <remarks>
  255. /// IMPORTANT: Lowercase alpha keys are encoded in <see cref="Key.KeyCode"/> as values between 65 and 90
  256. /// corresponding to the un-shifted A to Z keys on a keyboard. Helper properties are provided these (e.g.
  257. /// <see cref="Key.A"/>, <see cref="Key.B"/>, etc.). Even though the values are the same as the ASCII values for
  258. /// uppercase characters, these enum values represent *lowercase*, un-shifted characters.
  259. /// </remarks>
  260. public static bool GetIsKeyCodeAtoZ (KeyCode keyCode)
  261. {
  262. if ((keyCode & KeyCode.AltMask) != 0 || (keyCode & KeyCode.CtrlMask) != 0)
  263. {
  264. return false;
  265. }
  266. if ((keyCode & ~KeyCode.Space & ~KeyCode.ShiftMask) is >= KeyCode.A and <= KeyCode.Z)
  267. {
  268. return true;
  269. }
  270. return (keyCode & KeyCode.CharMask) is >= KeyCode.A and <= KeyCode.Z;
  271. }
  272. /// <summary>
  273. /// Converts a <see cref="KeyCode"/> to a <see cref="Rune"/>. Useful for determining if a key represents is a
  274. /// printable character.
  275. /// </summary>
  276. /// <remarks>
  277. /// <para>Keys with Ctrl or Alt modifiers will return <see langword="default"/>.</para>
  278. /// <para>
  279. /// If the key is a letter key (A-Z), the Rune will be the upper or lower case letter depending on whether
  280. /// <see cref="KeyCode.ShiftMask"/> is set.
  281. /// </para>
  282. /// <para>
  283. /// If the key is outside of the <see cref="KeyCode.CharMask"/> range, the returned Rune will be
  284. /// <see langword="default"/>.
  285. /// </para>
  286. /// </remarks>
  287. /// <param name="key"></param>
  288. /// <returns>The key converted to a Rune. <see langword="default"/> if conversion is not possible.</returns>
  289. public static Rune ToRune (KeyCode key)
  290. {
  291. if (key is KeyCode.Null or KeyCode.SpecialMask
  292. || key.HasFlag (KeyCode.CtrlMask)
  293. || key.HasFlag (KeyCode.AltMask))
  294. {
  295. return default (Rune);
  296. }
  297. // Extract the base key code
  298. KeyCode baseKey = key;
  299. if (baseKey.HasFlag (KeyCode.ShiftMask))
  300. {
  301. baseKey &= ~KeyCode.ShiftMask;
  302. }
  303. switch (baseKey)
  304. {
  305. case >= KeyCode.A and <= KeyCode.Z when !key.HasFlag (KeyCode.ShiftMask):
  306. return new Rune ((uint)(baseKey + 32));
  307. case >= KeyCode.A and <= KeyCode.Z when key.HasFlag (KeyCode.ShiftMask):
  308. return new Rune ((uint)baseKey);
  309. case > KeyCode.Null and < KeyCode.A:
  310. return new Rune ((uint)baseKey);
  311. }
  312. if (Enum.IsDefined (typeof (KeyCode), baseKey))
  313. {
  314. return default (Rune);
  315. }
  316. return new Rune ((uint)baseKey);
  317. }
  318. #region Operators
  319. /// <summary>
  320. /// Explicitly cast a <see cref="Key"/> to a <see cref="Rune"/>. The conversion is lossy because properties such
  321. /// as <see cref="Handled"/> are not encoded in <see cref="KeyCode"/>.
  322. /// </summary>
  323. /// <remarks>Uses <see cref="AsRune"/>.</remarks>
  324. /// <param name="kea"></param>
  325. public static explicit operator Rune (Key kea) { return kea.AsRune; }
  326. // BUGBUG: (Tig) I do not think this cast operator is really needed.
  327. /// <summary>
  328. /// Explicitly cast <see cref="Key"/> to a <see langword="uint"/>. The conversion is lossy because properties such
  329. /// as <see cref="Handled"/> are not encoded in <see cref="KeyCode"/>.
  330. /// </summary>
  331. /// <param name="kea"></param>
  332. public static explicit operator uint (Key kea) { return (uint)kea.KeyCode; }
  333. /// <summary>
  334. /// Explicitly cast <see cref="Key"/> to a <see cref="KeyCode"/>. The conversion is lossy because properties such
  335. /// as <see cref="Handled"/> are not encoded in <see cref="KeyCode"/>.
  336. /// </summary>
  337. /// <param name="key"></param>
  338. public static explicit operator KeyCode (Key key) { return key.KeyCode; }
  339. /// <summary>Cast <see cref="KeyCode"/> to a <see cref="Key"/>.</summary>
  340. /// <param name="keyCode"></param>
  341. public static implicit operator Key (KeyCode keyCode) { return new Key (keyCode); }
  342. /// <summary>Cast <see langword="char"/> to a <see cref="Key"/>.</summary>
  343. /// <remarks>See <see cref="Key(char)"/> for more information.</remarks>
  344. /// <param name="ch"></param>
  345. public static implicit operator Key (char ch) { return new Key (ch); }
  346. /// <summary>Cast <see langword="string"/> to a <see cref="Key"/>.</summary>
  347. /// <remarks>See <see cref="Key(string)"/> for more information.</remarks>
  348. /// <param name="str"></param>
  349. public static implicit operator Key (string str) { return new Key (str); }
  350. /// <summary>Cast a <see cref="Key"/> to a <see langword="string"/>.</summary>
  351. /// <remarks>See <see cref="Key(string)"/> for more information.</remarks>
  352. /// <param name="key"></param>
  353. public static implicit operator string (Key key) { return key.ToString (); }
  354. /// <inheritdoc/>
  355. public override bool Equals (object obj)
  356. {
  357. return obj is Key k && k.KeyCode == KeyCode && k.Handled == Handled;
  358. }
  359. bool IEquatable<Key>.Equals (Key other) { return Equals (other); }
  360. /// <inheritdoc/>
  361. public override int GetHashCode () { return (int)KeyCode; }
  362. /// <summary>Compares two <see cref="Key"/>s for equality.</summary>
  363. /// <param name="a"></param>
  364. /// <param name="b"></param>
  365. /// <returns></returns>
  366. public static bool operator == (Key a, Key b) { return a?.KeyCode == b?.KeyCode; }
  367. /// <summary>Compares two <see cref="Key"/>s for not equality.</summary>
  368. /// <param name="a"></param>
  369. /// <param name="b"></param>
  370. /// <returns></returns>
  371. public static bool operator != (Key a, Key b) { return a?.KeyCode != b?.KeyCode; }
  372. /// <summary>Compares two <see cref="Key"/>s for less-than.</summary>
  373. /// <param name="a"></param>
  374. /// <param name="b"></param>
  375. /// <returns></returns>
  376. public static bool operator < (Key a, Key b) { return a?.KeyCode < b?.KeyCode; }
  377. /// <summary>Compares two <see cref="Key"/>s for greater-than.</summary>
  378. /// <param name="a"></param>
  379. /// <param name="b"></param>
  380. /// <returns></returns>
  381. public static bool operator > (Key a, Key b) { return a?.KeyCode > b?.KeyCode; }
  382. /// <summary>Compares two <see cref="Key"/>s for greater-than-or-equal-to.</summary>
  383. /// <param name="a"></param>
  384. /// <param name="b"></param>
  385. /// <returns></returns>
  386. public static bool operator <= (Key a, Key b) { return a?.KeyCode <= b?.KeyCode; }
  387. /// <summary>Compares two <see cref="Key"/>s for greater-than-or-equal-to.</summary>
  388. /// <param name="a"></param>
  389. /// <param name="b"></param>
  390. /// <returns></returns>
  391. public static bool operator >= (Key a, Key b) { return a?.KeyCode >= b?.KeyCode; }
  392. #endregion Operators
  393. #region String conversion
  394. /// <summary>Pretty prints the KeyEvent</summary>
  395. /// <returns></returns>
  396. public override string ToString () { return ToString (KeyCode, (Rune)'+'); }
  397. private static string GetKeyString (KeyCode key)
  398. {
  399. if (key is KeyCode.Null or KeyCode.SpecialMask)
  400. {
  401. return string.Empty;
  402. }
  403. // Extract the base key (removing modifier flags)
  404. KeyCode baseKey = key & ~KeyCode.CtrlMask & ~KeyCode.AltMask & ~KeyCode.ShiftMask;
  405. if (!key.HasFlag (KeyCode.ShiftMask) && baseKey is >= KeyCode.A and <= KeyCode.Z)
  406. {
  407. return ((Rune)(uint)(key + 32)).ToString ();
  408. }
  409. if (key is > KeyCode.Space and < KeyCode.A)
  410. {
  411. return ((Rune)(uint)key).ToString ();
  412. }
  413. string keyName = Enum.GetName (typeof (KeyCode), key);
  414. return !string.IsNullOrEmpty (keyName) ? keyName : ((Rune)(uint)key).ToString ();
  415. }
  416. /// <summary>Formats a <see cref="KeyCode"/> as a string using the default separator of '+'</summary>
  417. /// <param name="key">The key to format.</param>
  418. /// <returns>
  419. /// The formatted string. If the key is a printable character, it will be returned as a string. Otherwise, the key
  420. /// name will be returned.
  421. /// </returns>
  422. public static string ToString (KeyCode key) { return ToString (key, (Rune)'+'); }
  423. /// <summary>Formats a <see cref="KeyCode"/> as a string.</summary>
  424. /// <param name="key">The key to format.</param>
  425. /// <param name="separator">The character to use as a separator between modifier keys and and the key itself.</param>
  426. /// <returns>
  427. /// The formatted string. If the key is a printable character, it will be returned as a string. Otherwise, the key
  428. /// name will be returned.
  429. /// </returns>
  430. public static string ToString (KeyCode key, Rune separator)
  431. {
  432. if (key is KeyCode.Null)
  433. {
  434. // Same as Key.IsValid
  435. return @"Null";
  436. }
  437. var sb = new StringBuilder ();
  438. // Extract the base key (removing modifier flags)
  439. KeyCode baseKey = key & ~KeyCode.CtrlMask & ~KeyCode.AltMask & ~KeyCode.ShiftMask;
  440. // Extract and handle modifiers
  441. var hasModifiers = false;
  442. if ((key & KeyCode.CtrlMask) != 0)
  443. {
  444. sb.Append ($"Ctrl{separator}");
  445. hasModifiers = true;
  446. }
  447. if ((key & KeyCode.AltMask) != 0)
  448. {
  449. sb.Append ($"Alt{separator}");
  450. hasModifiers = true;
  451. }
  452. if ((key & KeyCode.ShiftMask) != 0 && !GetIsKeyCodeAtoZ (key))
  453. {
  454. sb.Append ($"Shift{separator}");
  455. hasModifiers = true;
  456. }
  457. // Handle special cases and modifiers on their own
  458. if (key != KeyCode.SpecialMask && (baseKey != KeyCode.Null || hasModifiers))
  459. {
  460. if ((key & KeyCode.SpecialMask) != 0 && (baseKey & ~KeyCode.Space) is >= KeyCode.A and <= KeyCode.Z)
  461. {
  462. sb.Append (baseKey & ~KeyCode.Space);
  463. }
  464. else
  465. {
  466. // Append the actual key name
  467. sb.Append (GetKeyString (baseKey));
  468. }
  469. }
  470. return TrimEndSeparator (sb.ToString (), separator);
  471. }
  472. private static string TrimEndSeparator (string input, Rune separator)
  473. {
  474. // Trim the trailing separator (+). Unless there are two separators at the end.
  475. // "+" (don't trim)
  476. // "Ctrl+" (trim)
  477. // "Ctrl++" (trim)
  478. if (input.Length > 1 && new Rune (input [^1]) == separator && new Rune (input [^2]) != separator)
  479. {
  480. return input [..^1];
  481. }
  482. return input;
  483. }
  484. private static readonly Dictionary<string, KeyCode> _modifierDict =
  485. new (StringComparer.InvariantCultureIgnoreCase)
  486. {
  487. { "Shift", KeyCode.ShiftMask }, { "Ctrl", KeyCode.CtrlMask }, { "Alt", KeyCode.AltMask }
  488. };
  489. /// <summary>Converts the provided string to a new <see cref="Key"/> instance.</summary>
  490. /// <param name="text">
  491. /// The text to analyze. Formats supported are "Ctrl+X", "Alt+X", "Shift+X", "Ctrl+Alt+X",
  492. /// "Ctrl+Shift+X", "Alt+Shift+X", "Ctrl+Alt+Shift+X", and "X".
  493. /// </param>
  494. /// <param name="key">The parsed value.</param>
  495. /// <returns>A boolean value indicating whether parsing was successful.</returns>
  496. /// <remarks></remarks>
  497. public static bool TryParse (string text, [NotNullWhen (true)] out Key key)
  498. {
  499. if (string.IsNullOrEmpty (text))
  500. {
  501. key = Key.Empty;
  502. return true;
  503. }
  504. key = null;
  505. // Split the string into parts
  506. string [] parts = text.Split ('+', '-');
  507. if (parts.Length is 0 or > 4 || parts.Any (string.IsNullOrEmpty))
  508. {
  509. return false;
  510. }
  511. // if it's just a shift key
  512. if (parts.Length == 1)
  513. {
  514. switch (parts [0])
  515. {
  516. case "Ctrl":
  517. key = KeyCode.CtrlMask;
  518. return true;
  519. case "Alt":
  520. key = KeyCode.AltMask;
  521. return true;
  522. case "Shift":
  523. key = KeyCode.ShiftMask;
  524. return true;
  525. }
  526. }
  527. var modifiers = KeyCode.Null;
  528. for (var index = 0; index < parts.Length; index++)
  529. {
  530. if (_modifierDict.TryGetValue (parts [index].ToLowerInvariant (), out KeyCode modifier))
  531. {
  532. modifiers |= modifier;
  533. parts [index] = string.Empty; // eat it
  534. }
  535. }
  536. // we now have the modifiers
  537. string partNotFound = parts.FirstOrDefault (p => !string.IsNullOrEmpty (p), string.Empty);
  538. var parsedKeyCode = KeyCode.Null;
  539. var parsedInt = 0;
  540. if (partNotFound.Length == 1)
  541. {
  542. var keyCode = (KeyCode)partNotFound [0];
  543. // if it's a single digit int, treat it as such
  544. if (int.TryParse (
  545. partNotFound,
  546. NumberStyles.Integer,
  547. CultureInfo.InvariantCulture,
  548. out parsedInt
  549. ))
  550. {
  551. keyCode = (KeyCode)((int)KeyCode.D0 + parsedInt);
  552. }
  553. else if (Enum.TryParse (partNotFound, false, out parsedKeyCode))
  554. {
  555. if (parsedKeyCode != KeyCode.Null)
  556. {
  557. if (parsedKeyCode is >= KeyCode.A and <= KeyCode.Z && modifiers == 0)
  558. {
  559. key = new Key (parsedKeyCode | KeyCode.ShiftMask);
  560. return true;
  561. }
  562. key = new Key (parsedKeyCode | modifiers);
  563. return true;
  564. }
  565. }
  566. if (GetIsKeyCodeAtoZ (keyCode) && (keyCode & KeyCode.Space) != 0)
  567. {
  568. keyCode = keyCode & ~KeyCode.Space;
  569. }
  570. key = new Key (keyCode | modifiers);
  571. return true;
  572. }
  573. if (Enum.TryParse (partNotFound, true, out parsedKeyCode))
  574. {
  575. if (parsedKeyCode != KeyCode.Null)
  576. {
  577. if (parsedKeyCode is >= KeyCode.A and <= KeyCode.Z && modifiers == 0)
  578. {
  579. key = new Key (parsedKeyCode | KeyCode.ShiftMask);
  580. return true;
  581. }
  582. if (GetIsKeyCodeAtoZ (parsedKeyCode) && (parsedKeyCode & KeyCode.Space) != 0)
  583. {
  584. parsedKeyCode = parsedKeyCode & ~KeyCode.Space;
  585. }
  586. key = new Key (parsedKeyCode | modifiers);
  587. return true;
  588. }
  589. }
  590. // if it's a number int, treat it as a unicode value
  591. if (int.TryParse (
  592. partNotFound,
  593. NumberStyles.Number,
  594. CultureInfo.InvariantCulture,
  595. out parsedInt
  596. ))
  597. {
  598. if (!Rune.IsValid (parsedInt))
  599. {
  600. return false;
  601. }
  602. if ((KeyCode)parsedInt is >= KeyCode.A and <= KeyCode.Z && modifiers == 0)
  603. {
  604. key = new Key ((KeyCode)parsedInt | KeyCode.ShiftMask);
  605. return true;
  606. }
  607. key = new Key ((KeyCode)parsedInt);
  608. return true;
  609. }
  610. if (!Enum.TryParse (partNotFound, true, out parsedKeyCode))
  611. {
  612. return false;
  613. }
  614. if (GetIsKeyCodeAtoZ (parsedKeyCode))
  615. {
  616. key = new Key (parsedKeyCode | (modifiers & ~KeyCode.Space));
  617. return true;
  618. }
  619. return false;
  620. }
  621. #endregion
  622. #region Standard Key Definitions
  623. /// <summary>An uninitialized The <see cref="Key"/> object.</summary>
  624. public new static Key Empty => new ();
  625. /// <summary>The <see cref="Key"/> object for the Backspace key.</summary>
  626. public static Key Backspace => new (KeyCode.Backspace);
  627. /// <summary>The <see cref="Key"/> object for the tab key (forwards tab key).</summary>
  628. public static Key Tab => new (KeyCode.Tab);
  629. /// <summary>The <see cref="Key"/> object for the return key.</summary>
  630. public static Key Enter => new (KeyCode.Enter);
  631. /// <summary>The <see cref="Key"/> object for the clear key.</summary>
  632. public static Key Clear => new (KeyCode.Clear);
  633. /// <summary>The <see cref="Key"/> object for the Escape key.</summary>
  634. public static Key Esc => new (KeyCode.Esc);
  635. /// <summary>The <see cref="Key"/> object for the Space bar key.</summary>
  636. public static Key Space => new (KeyCode.Space);
  637. /// <summary>The <see cref="Key"/> object for 0 key.</summary>
  638. public static Key D0 => new (KeyCode.D0);
  639. /// <summary>The <see cref="Key"/> object for 1 key.</summary>
  640. public static Key D1 => new (KeyCode.D1);
  641. /// <summary>The <see cref="Key"/> object for 2 key.</summary>
  642. public static Key D2 => new (KeyCode.D2);
  643. /// <summary>The <see cref="Key"/> object for 3 key.</summary>
  644. public static Key D3 => new (KeyCode.D3);
  645. /// <summary>The <see cref="Key"/> object for 4 key.</summary>
  646. public static Key D4 => new (KeyCode.D4);
  647. /// <summary>The <see cref="Key"/> object for 5 key.</summary>
  648. public static Key D5 => new (KeyCode.D5);
  649. /// <summary>The <see cref="Key"/> object for 6 key.</summary>
  650. public static Key D6 => new (KeyCode.D6);
  651. /// <summary>The <see cref="Key"/> object for 7 key.</summary>
  652. public static Key D7 => new (KeyCode.D7);
  653. /// <summary>The <see cref="Key"/> object for 8 key.</summary>
  654. public static Key D8 => new (KeyCode.D8);
  655. /// <summary>The <see cref="Key"/> object for 9 key.</summary>
  656. public static Key D9 => new (KeyCode.D9);
  657. /// <summary>The <see cref="Key"/> object for the A key (un-shifted). Use <c>Key.A.WithShift</c> for uppercase 'A'.</summary>
  658. public static Key A => new (KeyCode.A);
  659. /// <summary>The <see cref="Key"/> object for the B key (un-shifted). Use <c>Key.B.WithShift</c> for uppercase 'B'.</summary>
  660. public static Key B => new (KeyCode.B);
  661. /// <summary>The <see cref="Key"/> object for the C key (un-shifted). Use <c>Key.C.WithShift</c> for uppercase 'C'.</summary>
  662. public static Key C => new (KeyCode.C);
  663. /// <summary>The <see cref="Key"/> object for the D key (un-shifted). Use <c>Key.D.WithShift</c> for uppercase 'D'.</summary>
  664. public static Key D => new (KeyCode.D);
  665. /// <summary>The <see cref="Key"/> object for the E key (un-shifted). Use <c>Key.E.WithShift</c> for uppercase 'E'.</summary>
  666. public static Key E => new (KeyCode.E);
  667. /// <summary>The <see cref="Key"/> object for the F key (un-shifted). Use <c>Key.F.WithShift</c> for uppercase 'F'.</summary>
  668. public static Key F => new (KeyCode.F);
  669. /// <summary>The <see cref="Key"/> object for the G key (un-shifted). Use <c>Key.G.WithShift</c> for uppercase 'G'.</summary>
  670. public static Key G => new (KeyCode.G);
  671. /// <summary>The <see cref="Key"/> object for the H key (un-shifted). Use <c>Key.H.WithShift</c> for uppercase 'H'.</summary>
  672. public static Key H => new (KeyCode.H);
  673. /// <summary>The <see cref="Key"/> object for the I key (un-shifted). Use <c>Key.I.WithShift</c> for uppercase 'I'.</summary>
  674. public static Key I => new (KeyCode.I);
  675. /// <summary>The <see cref="Key"/> object for the J key (un-shifted). Use <c>Key.J.WithShift</c> for uppercase 'J'.</summary>
  676. public static Key J => new (KeyCode.J);
  677. /// <summary>The <see cref="Key"/> object for the K key (un-shifted). Use <c>Key.K.WithShift</c> for uppercase 'K'.</summary>
  678. public static Key K => new (KeyCode.K);
  679. /// <summary>The <see cref="Key"/> object for the L key (un-shifted). Use <c>Key.L.WithShift</c> for uppercase 'L'.</summary>
  680. public static Key L => new (KeyCode.L);
  681. /// <summary>The <see cref="Key"/> object for the M key (un-shifted). Use <c>Key.M.WithShift</c> for uppercase 'M'.</summary>
  682. public static Key M => new (KeyCode.M);
  683. /// <summary>The <see cref="Key"/> object for the N key (un-shifted). Use <c>Key.N.WithShift</c> for uppercase 'N'.</summary>
  684. public static Key N => new (KeyCode.N);
  685. /// <summary>The <see cref="Key"/> object for the O key (un-shifted). Use <c>Key.O.WithShift</c> for uppercase 'O'.</summary>
  686. public static Key O => new (KeyCode.O);
  687. /// <summary>The <see cref="Key"/> object for the P key (un-shifted). Use <c>Key.P.WithShift</c> for uppercase 'P'.</summary>
  688. public static Key P => new (KeyCode.P);
  689. /// <summary>The <see cref="Key"/> object for the Q key (un-shifted). Use <c>Key.Q.WithShift</c> for uppercase 'Q'.</summary>
  690. public static Key Q => new (KeyCode.Q);
  691. /// <summary>The <see cref="Key"/> object for the R key (un-shifted). Use <c>Key.R.WithShift</c> for uppercase 'R'.</summary>
  692. public static Key R => new (KeyCode.R);
  693. /// <summary>The <see cref="Key"/> object for the S key (un-shifted). Use <c>Key.S.WithShift</c> for uppercase 'S'.</summary>
  694. public static Key S => new (KeyCode.S);
  695. /// <summary>The <see cref="Key"/> object for the T key (un-shifted). Use <c>Key.T.WithShift</c> for uppercase 'T'.</summary>
  696. public static Key T => new (KeyCode.T);
  697. /// <summary>The <see cref="Key"/> object for the U key (un-shifted). Use <c>Key.U.WithShift</c> for uppercase 'U'.</summary>
  698. public static Key U => new (KeyCode.U);
  699. /// <summary>The <see cref="Key"/> object for the V key (un-shifted). Use <c>Key.V.WithShift</c> for uppercase 'V'.</summary>
  700. public static Key V => new (KeyCode.V);
  701. /// <summary>The <see cref="Key"/> object for the W key (un-shifted). Use <c>Key.W.WithShift</c> for uppercase 'W'.</summary>
  702. public static Key W => new (KeyCode.W);
  703. /// <summary>The <see cref="Key"/> object for the X key (un-shifted). Use <c>Key.X.WithShift</c> for uppercase 'X'.</summary>
  704. public static Key X => new (KeyCode.X);
  705. /// <summary>The <see cref="Key"/> object for the Y key (un-shifted). Use <c>Key.Y.WithShift</c> for uppercase 'Y'.</summary>
  706. public static Key Y => new (KeyCode.Y);
  707. /// <summary>The <see cref="Key"/> object for the Z key (un-shifted). Use <c>Key.Z.WithShift</c> for uppercase 'Z'.</summary>
  708. public static Key Z => new (KeyCode.Z);
  709. /// <summary>The <see cref="Key"/> object for the Delete key.</summary>
  710. public static Key Delete => new (KeyCode.Delete);
  711. /// <summary>The <see cref="Key"/> object for the Cursor up key.</summary>
  712. public static Key CursorUp => new (KeyCode.CursorUp);
  713. /// <summary>The <see cref="Key"/> object for Cursor down key.</summary>
  714. public static Key CursorDown => new (KeyCode.CursorDown);
  715. /// <summary>The <see cref="Key"/> object for Cursor left key.</summary>
  716. public static Key CursorLeft => new (KeyCode.CursorLeft);
  717. /// <summary>The <see cref="Key"/> object for Cursor right key.</summary>
  718. public static Key CursorRight => new (KeyCode.CursorRight);
  719. /// <summary>The <see cref="Key"/> object for Page Up key.</summary>
  720. public static Key PageUp => new (KeyCode.PageUp);
  721. /// <summary>The <see cref="Key"/> object for Page Down key.</summary>
  722. public static Key PageDown => new (KeyCode.PageDown);
  723. /// <summary>The <see cref="Key"/> object for Home key.</summary>
  724. public static Key Home => new (KeyCode.Home);
  725. /// <summary>The <see cref="Key"/> object for End key.</summary>
  726. public static Key End => new (KeyCode.End);
  727. /// <summary>The <see cref="Key"/> object for Insert Character key.</summary>
  728. public static Key InsertChar => new (KeyCode.Insert);
  729. /// <summary>The <see cref="Key"/> object for Delete Character key.</summary>
  730. public static Key DeleteChar => new (KeyCode.Delete);
  731. /// <summary>The <see cref="Key"/> object for Print Screen key.</summary>
  732. public static Key PrintScreen => new (KeyCode.PrintScreen);
  733. /// <summary>The <see cref="Key"/> object for F1 key.</summary>
  734. public static Key F1 => new (KeyCode.F1);
  735. /// <summary>The <see cref="Key"/> object for F2 key.</summary>
  736. public static Key F2 => new (KeyCode.F2);
  737. /// <summary>The <see cref="Key"/> object for F3 key.</summary>
  738. public static Key F3 => new (KeyCode.F3);
  739. /// <summary>The <see cref="Key"/> object for F4 key.</summary>
  740. public static Key F4 => new (KeyCode.F4);
  741. /// <summary>The <see cref="Key"/> object for F5 key.</summary>
  742. public static Key F5 => new (KeyCode.F5);
  743. /// <summary>The <see cref="Key"/> object for F6 key.</summary>
  744. public static Key F6 => new (KeyCode.F6);
  745. /// <summary>The <see cref="Key"/> object for F7 key.</summary>
  746. public static Key F7 => new (KeyCode.F7);
  747. /// <summary>The <see cref="Key"/> object for F8 key.</summary>
  748. public static Key F8 => new (KeyCode.F8);
  749. /// <summary>The <see cref="Key"/> object for F9 key.</summary>
  750. public static Key F9 => new (KeyCode.F9);
  751. /// <summary>The <see cref="Key"/> object for F10 key.</summary>
  752. public static Key F10 => new (KeyCode.F10);
  753. /// <summary>The <see cref="Key"/> object for F11 key.</summary>
  754. public static Key F11 => new (KeyCode.F11);
  755. /// <summary>The <see cref="Key"/> object for F12 key.</summary>
  756. public static Key F12 => new (KeyCode.F12);
  757. /// <summary>The <see cref="Key"/> object for F13 key.</summary>
  758. public static Key F13 => new (KeyCode.F13);
  759. /// <summary>The <see cref="Key"/> object for F14 key.</summary>
  760. public static Key F14 => new (KeyCode.F14);
  761. /// <summary>The <see cref="Key"/> object for F15 key.</summary>
  762. public static Key F15 => new (KeyCode.F15);
  763. /// <summary>The <see cref="Key"/> object for F16 key.</summary>
  764. public static Key F16 => new (KeyCode.F16);
  765. /// <summary>The <see cref="Key"/> object for F17 key.</summary>
  766. public static Key F17 => new (KeyCode.F17);
  767. /// <summary>The <see cref="Key"/> object for F18 key.</summary>
  768. public static Key F18 => new (KeyCode.F18);
  769. /// <summary>The <see cref="Key"/> object for F19 key.</summary>
  770. public static Key F19 => new (KeyCode.F19);
  771. /// <summary>The <see cref="Key"/> object for F20 key.</summary>
  772. public static Key F20 => new (KeyCode.F20);
  773. /// <summary>The <see cref="Key"/> object for F21 key.</summary>
  774. public static Key F21 => new (KeyCode.F21);
  775. /// <summary>The <see cref="Key"/> object for F22 key.</summary>
  776. public static Key F22 => new (KeyCode.F22);
  777. /// <summary>The <see cref="Key"/> object for F23 key.</summary>
  778. public static Key F23 => new (KeyCode.F23);
  779. /// <summary>The <see cref="Key"/> object for F24 key.</summary>
  780. public static Key F24 => new (KeyCode.F24);
  781. #endregion
  782. }