KeyBindings.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. #nullable enable
  2. namespace Terminal.Gui;
  3. /// <summary>
  4. /// Provides a collection of <see cref="KeyBinding"/> objects bound to a <see cref="Key"/>.
  5. /// </summary>
  6. /// <seealso cref="Application.KeyBindings"/>
  7. /// <seealso cref="View.KeyBindings"/>
  8. /// <seealso cref="Command"/>
  9. public class KeyBindings
  10. {
  11. /// <summary>Initializes a new instance bound to <paramref name="target"/>.</summary>
  12. public KeyBindings (View? target) { Target = target; }
  13. /// <summary>Adds a <see cref="KeyBinding"/> to the collection.</summary>
  14. /// <param name="key"></param>
  15. /// <param name="binding"></param>
  16. /// <exception cref="ArgumentException">If <paramref name="binding"/> has no Commands or <paramref name="key"/> is invalid.</exception>
  17. public void Add (Key key, KeyBinding binding)
  18. {
  19. if (!key.IsValid)
  20. {
  21. throw new ArgumentException (nameof (key));
  22. }
  23. if (binding.Commands is { Length: 0 })
  24. {
  25. throw new ArgumentException (nameof (binding));
  26. }
  27. if (TryGet (key, out KeyBinding _))
  28. {
  29. throw new InvalidOperationException (@$"A key binding for {key} exists ({binding}).");
  30. //Bindings [key] = binding;
  31. }
  32. if (Target is { })
  33. {
  34. binding.Target = Target;
  35. }
  36. // IMPORTANT: Add a COPY of the key. This is needed because ConfigurationManager.Apply uses DeepMemberWiseCopy
  37. // IMPORTANT: update the memory referenced by the key, and Dictionary uses caching for performance, and thus
  38. // IMPORTANT: Apply will update the Dictionary with the new key, but the old key will still be in the dictionary.
  39. // IMPORTANT: See the ConfigurationManager.Illustrate_DeepMemberWiseCopy_Breaks_Dictionary test for details.
  40. Bindings.Add (new (key), binding);
  41. }
  42. #pragma warning disable CS1574 // XML comment has cref attribute that could not be resolved
  43. /// <summary>
  44. /// <para>
  45. /// Adds a new key combination that will trigger the commands in <paramref name="commands"/> (if supported by the
  46. /// View - see <see cref="View.GetSupportedCommands"/>).
  47. /// </para>
  48. /// <para>
  49. /// If the key is already bound to a different array of <see cref="Command"/>s it will be rebound
  50. /// <paramref name="commands"/>.
  51. /// </para>
  52. /// </summary>
  53. /// <remarks>
  54. /// Commands are only ever applied to the current <see cref="View"/> (i.e. this feature cannot be used to switch
  55. /// focus to another view and perform multiple commands there).
  56. /// </remarks>
  57. /// <param name="key">The key to check.</param>
  58. /// <param name="commands">
  59. /// The command to invoked on the <see cref="View"/> when <paramref name="key"/> is pressed. When
  60. /// multiple commands are provided,they will be applied in sequence. The bound <paramref name="key"/> strike will be
  61. /// consumed if any took effect.
  62. /// </param>
  63. /// <exception cref="ArgumentException">If <paramref name="commands"/> is empty.</exception>
  64. #pragma warning restore CS1574 // XML comment has cref attribute that could not be resolved
  65. public void Add (Key key, params Command [] commands)
  66. {
  67. Add (key, new KeyBinding (commands));
  68. }
  69. /// <summary>
  70. /// <para>
  71. /// Adds a new key combination that will trigger the commands in <paramref name="commands"/> on the View
  72. /// specified by <paramref name="target"/>.
  73. /// </para>
  74. /// <para>
  75. /// If the key is already bound to a different array of <see cref="Command"/>s it will be rebound
  76. /// <paramref name="commands"/>.
  77. /// </para>
  78. /// </summary>
  79. /// <remarks>
  80. /// </remarks>
  81. /// <param name="key">The key to check.</param>
  82. /// <param name="target">The View the commands will be invoked on. If <see langword="null"/>, the key will be bound to <see cref="Application"/>.</param>
  83. /// <param name="commands">
  84. /// The command to invoked on the <see paramref="target"/> when <paramref name="key"/> is pressed. When
  85. /// multiple commands are provided,they will be applied in sequence. The bound <paramref name="key"/> strike will be
  86. /// consumed if any took effect.
  87. /// </param>
  88. public void Add (Key key, View? target, params Command [] commands)
  89. {
  90. KeyBinding binding = new (commands, target);
  91. Add (key, binding);
  92. }
  93. // TODO: Add a dictionary comparer that ignores Scope
  94. // TODO: This should not be public!
  95. /// <summary>The collection of <see cref="KeyBinding"/> objects.</summary>
  96. public Dictionary<Key, KeyBinding> Bindings { get; } = new (new KeyEqualityComparer ());
  97. /// <summary>
  98. /// Gets the bindings bound to <paramref name="key"/>.
  99. /// </summary>
  100. /// <param name="key"></param>
  101. /// <returns></returns>
  102. public IEnumerable<KeyValuePair<Key, KeyBinding>> GetBindings (Key key)
  103. {
  104. return Bindings.Where (b => b.Key == key.KeyCode);
  105. }
  106. /// <summary>
  107. /// Gets the keys that are bound.
  108. /// </summary>
  109. /// <returns></returns>
  110. public IEnumerable<Key> GetBoundKeys () { return Bindings.Keys; }
  111. /// <summary>
  112. /// The view that the <see cref="KeyBindings"/> are bound to.
  113. /// </summary>
  114. /// <remarks>
  115. /// If <see langword="null"/> the KeyBindings object is being used for Application.KeyBindings.
  116. /// </remarks>
  117. public View? Target { get; init; }
  118. /// <summary>Removes all <see cref="KeyBinding"/> objects from the collection.</summary>
  119. public void Clear () { Bindings.Clear (); }
  120. /// <summary>
  121. /// Removes all key bindings that trigger the given command set. Views can have multiple different keys bound to
  122. /// the same command sets and this method will clear all of them.
  123. /// </summary>
  124. /// <param name="command"></param>
  125. public void Clear (params Command [] command)
  126. {
  127. KeyValuePair<Key, KeyBinding> [] kvps = Bindings
  128. .Where (kvp => kvp.Value.Commands.SequenceEqual (command))
  129. .ToArray ();
  130. foreach (KeyValuePair<Key, KeyBinding> kvp in kvps)
  131. {
  132. Remove (kvp.Key);
  133. }
  134. }
  135. /// <summary>Gets the <see cref="KeyBinding"/> for the specified <see cref="Key"/>.</summary>
  136. /// <param name="key"></param>
  137. /// <returns></returns>
  138. public KeyBinding Get (Key key)
  139. {
  140. if (TryGet (key, out KeyBinding binding))
  141. {
  142. return binding;
  143. }
  144. throw new InvalidOperationException ($"Key {key} is not bound.");
  145. }
  146. /// <summary>Gets the array of <see cref="Command"/>s bound to <paramref name="key"/> if it exists.</summary>
  147. /// <param name="key">The key to check.</param>
  148. /// <returns>
  149. /// The array of <see cref="Command"/>s if <paramref name="key"/> is bound. An empty <see cref="Command"/> array
  150. /// if not.
  151. /// </returns>
  152. public Command [] GetCommands (Key key)
  153. {
  154. if (TryGet (key, out KeyBinding bindings))
  155. {
  156. return bindings.Commands;
  157. }
  158. return [];
  159. }
  160. /// <summary>Gets the first Key bound to the set of commands specified by <paramref name="commands"/>.</summary>
  161. /// <param name="commands">The set of commands to search.</param>
  162. /// <returns>
  163. /// The first <see cref="Key"/> bound to the set of commands specified by <paramref name="commands"/>.
  164. /// <see langword="null"/> if the set of caommands was not found.
  165. /// </returns>
  166. public Key? GetKeyFromCommands (params Command [] commands) { return Bindings.FirstOrDefault (a => a.Value.Commands.SequenceEqual (commands)).Key; }
  167. /// <summary>Gets Keys bound to the set of commands specified by <paramref name="commands"/>.</summary>
  168. /// <param name="commands">The set of commands to search.</param>
  169. /// <returns>
  170. /// The <see cref="Key"/>s bound to the set of commands specified by <paramref name="commands"/>. An empty list if the
  171. /// set of caommands was not found.
  172. /// </returns>
  173. public IEnumerable<Key> GetKeysFromCommands (params Command [] commands)
  174. {
  175. return Bindings.Where (a => a.Value.Commands.SequenceEqual (commands)).Select (a => a.Key);
  176. }
  177. /// <summary>Removes a <see cref="KeyBinding"/> from the collection.</summary>
  178. /// <param name="key"></param>
  179. public void Remove (Key key)
  180. {
  181. if (!TryGet (key, out KeyBinding _))
  182. {
  183. return;
  184. }
  185. Bindings.Remove (key);
  186. }
  187. /// <summary>Replaces the commands already bound to a key.</summary>
  188. /// <remarks>
  189. /// <para>
  190. /// If the key is not already bound, it will be added.
  191. /// </para>
  192. /// </remarks>
  193. /// <param name="key">The key bound to the command to be replaced.</param>
  194. /// <param name="newCommands">The set of commands to replace the old ones with.</param>
  195. public void ReplaceCommands (Key key, params Command [] newCommands)
  196. {
  197. if (TryGet (key, out KeyBinding binding))
  198. {
  199. Remove (key);
  200. Add (key, newCommands);
  201. }
  202. else
  203. {
  204. Add (key, newCommands);
  205. }
  206. }
  207. /// <summary>Replaces a key combination already bound to a set of <see cref="Command"/>s.</summary>
  208. /// <remarks></remarks>
  209. /// <param name="oldKey">The key to be replaced.</param>
  210. /// <param name="newKey">The new key to be used. If <see cref="Key.Empty"/> no action will be taken.</param>
  211. public void ReplaceKey (Key oldKey, Key newKey)
  212. {
  213. if (!newKey.IsValid)
  214. {
  215. throw new InvalidOperationException ($"Key {newKey} is is not valid.");
  216. }
  217. if (newKey == Key.Empty)
  218. {
  219. Remove (oldKey);
  220. return;
  221. }
  222. if (TryGet (oldKey, out KeyBinding binding))
  223. {
  224. Remove (oldKey);
  225. Add (newKey, binding);
  226. }
  227. else
  228. {
  229. Add (newKey, binding);
  230. }
  231. }
  232. /// <summary>Gets the commands bound with the specified Key.</summary>
  233. /// <remarks></remarks>
  234. /// <param name="key">The key to check.</param>
  235. /// <param name="binding">
  236. /// When this method returns, contains the commands bound with the specified Key, if the Key is
  237. /// found; otherwise, null. This parameter is passed uninitialized.
  238. /// </param>
  239. /// <returns><see langword="true"/> if the Key is bound; otherwise <see langword="false"/>.</returns>
  240. public bool TryGet (Key key, out KeyBinding binding)
  241. {
  242. binding = new ([], null);
  243. if (key.IsValid)
  244. {
  245. return Bindings.TryGetValue (key, out binding);
  246. }
  247. return false;
  248. }
  249. }