Key.cs 41 KB

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