KeyBindings.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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="boundView"/>.</summary>
  12. public KeyBindings (View? boundView) { BoundView = boundView; }
  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.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 (BoundView is { })
  33. {
  34. binding.BoundView = BoundView;
  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. /// <summary>
  43. /// <para>
  44. /// Adds a new key combination that will trigger the commands in <paramref name="commands"/> (if supported by the
  45. /// View - see <see cref="View.GetSupportedCommands"/>).
  46. /// </para>
  47. /// <para>
  48. /// This is a helper function for <see cref="Add(Key,KeyBinding,View?)"/>. If used for a View (
  49. /// <see cref="BoundView"/> is set), the scope will be set to <see cref="KeyBindingScope.Focused"/>.
  50. /// Otherwise, it will be set to <see cref="KeyBindingScope.Application"/>.
  51. /// </para>
  52. /// <para>
  53. /// If the key is already bound to a different array of <see cref="Command"/>s it will be rebound
  54. /// <paramref name="commands"/>.
  55. /// </para>
  56. /// </summary>
  57. /// <remarks>
  58. /// Commands are only ever applied to the current <see cref="View"/> (i.e. this feature cannot be used to switch
  59. /// focus to another view and perform multiple commands there).
  60. /// </remarks>
  61. /// <param name="key">The key to check.</param>
  62. /// <param name="commands">
  63. /// The command to invoked on the <see cref="View"/> when <paramref name="key"/> is pressed. When
  64. /// multiple commands are provided,they will be applied in sequence. The bound <paramref name="key"/> strike will be
  65. /// consumed if any took effect.
  66. /// </param>
  67. /// <exception cref="ArgumentException">If <paramref name="commands"/> is empty.</exception>
  68. public void Add (Key key, params Command [] commands)
  69. {
  70. Add (key, new KeyBinding (commands));
  71. }
  72. // TODO: Add a dictionary comparer that ignores Scope
  73. // TODO: This should not be public!
  74. /// <summary>The collection of <see cref="KeyBinding"/> objects.</summary>
  75. public Dictionary<Key, KeyBinding> Bindings { get; } = new (new KeyEqualityComparer ());
  76. /// <summary>
  77. /// Gets the keys that are bound.
  78. /// </summary>
  79. /// <returns></returns>
  80. public IEnumerable<Key> GetBoundKeys () { return Bindings.Keys; }
  81. /// <summary>
  82. /// The view that the <see cref="KeyBindings"/> are bound to.
  83. /// </summary>
  84. /// <remarks>
  85. /// If <see langword="null"/> the KeyBindings object is being used for Application.KeyBindings.
  86. /// </remarks>
  87. public View? BoundView { get; init; }
  88. /// <summary>Removes all <see cref="KeyBinding"/> objects from the collection.</summary>
  89. public void Clear () { Bindings.Clear (); }
  90. /// <summary>
  91. /// Removes all key bindings that trigger the given command set. Views can have multiple different keys bound to
  92. /// the same command sets and this method will clear all of them.
  93. /// </summary>
  94. /// <param name="command"></param>
  95. public void Clear (params Command [] command)
  96. {
  97. KeyValuePair<Key, KeyBinding> [] kvps = Bindings
  98. .Where (kvp => kvp.Value.Commands.SequenceEqual (command))
  99. .ToArray ();
  100. foreach (KeyValuePair<Key, KeyBinding> kvp in kvps)
  101. {
  102. Remove (kvp.Key);
  103. }
  104. }
  105. /// <summary>Gets the <see cref="KeyBinding"/> for the specified <see cref="Key"/>.</summary>
  106. /// <param name="key"></param>
  107. /// <returns></returns>
  108. public KeyBinding Get (Key key)
  109. {
  110. if (TryGet (key, out KeyBinding binding))
  111. {
  112. return binding;
  113. }
  114. throw new InvalidOperationException ($"Key {key} is not bound.");
  115. }
  116. /// <summary>Gets the array of <see cref="Command"/>s bound to <paramref name="key"/> if it exists.</summary>
  117. /// <param name="key">The key to check.</param>
  118. /// <returns>
  119. /// The array of <see cref="Command"/>s if <paramref name="key"/> is bound. An empty <see cref="Command"/> array
  120. /// if not.
  121. /// </returns>
  122. public Command [] GetCommands (Key key)
  123. {
  124. if (TryGet (key, out KeyBinding bindings))
  125. {
  126. return bindings.Commands;
  127. }
  128. return [];
  129. }
  130. /// <summary>Gets the first Key bound to the set of commands specified by <paramref name="commands"/>.</summary>
  131. /// <param name="commands">The set of commands to search.</param>
  132. /// <returns>
  133. /// The first <see cref="Key"/> bound to the set of commands specified by <paramref name="commands"/>.
  134. /// <see langword="null"/> if the set of caommands was not found.
  135. /// </returns>
  136. public Key? GetKeyFromCommands (params Command [] commands) { return Bindings.FirstOrDefault (a => a.Value.Commands.SequenceEqual (commands)).Key; }
  137. /// <summary>Gets Keys bound to the set of commands specified by <paramref name="commands"/>.</summary>
  138. /// <param name="commands">The set of commands to search.</param>
  139. /// <returns>
  140. /// The <see cref="Key"/>s bound to the set of commands specified by <paramref name="commands"/>. An empty list if the
  141. /// set of caommands was not found.
  142. /// </returns>
  143. public IEnumerable<Key> GetKeysFromCommands (params Command [] commands)
  144. {
  145. return Bindings.Where (a => a.Value.Commands.SequenceEqual (commands)).Select (a => a.Key);
  146. }
  147. /// <summary>Removes a <see cref="KeyBinding"/> from the collection.</summary>
  148. /// <param name="key"></param>
  149. /// <param name="boundViewForAppScope">Optional View for <see cref="KeyBindingScope.Application"/> bindings.</param>
  150. public void Remove (Key key, View? boundViewForAppScope = null)
  151. {
  152. if (!TryGet (key, out KeyBinding _))
  153. {
  154. return;
  155. }
  156. Bindings.Remove (key);
  157. }
  158. /// <summary>Replaces the commands already bound to a key.</summary>
  159. /// <remarks>
  160. /// <para>
  161. /// If the key is not already bound, it will be added.
  162. /// </para>
  163. /// </remarks>
  164. /// <param name="key">The key bound to the command to be replaced.</param>
  165. /// <param name="newCommands">The set of commands to replace the old ones with.</param>
  166. public void ReplaceCommands (Key key, params Command [] newCommands)
  167. {
  168. if (TryGet (key, out KeyBinding binding))
  169. {
  170. Remove (key);
  171. Add (key, newCommands);
  172. }
  173. else
  174. {
  175. Add (key, newCommands);
  176. }
  177. }
  178. /// <summary>Replaces a key combination already bound to a set of <see cref="Command"/>s.</summary>
  179. /// <remarks></remarks>
  180. /// <param name="oldKey">The key to be replaced.</param>
  181. /// <param name="newKey">The new key to be used. If <see cref="Key.Empty"/> no action will be taken.</param>
  182. public void ReplaceKey (Key oldKey, Key newKey)
  183. {
  184. if (!TryGet (oldKey, out KeyBinding _))
  185. {
  186. throw new InvalidOperationException ($"Key {oldKey} is not bound.");
  187. }
  188. if (!newKey.IsValid)
  189. {
  190. throw new InvalidOperationException ($"Key {newKey} is is not valid.");
  191. }
  192. KeyBinding value = Bindings [oldKey];
  193. Remove (oldKey);
  194. Add (newKey, value);
  195. }
  196. /// <summary>Gets the commands bound with the specified Key.</summary>
  197. /// <remarks></remarks>
  198. /// <param name="key">The key to check.</param>
  199. /// <param name="binding">
  200. /// When this method returns, contains the commands bound with the specified Key, if the Key is
  201. /// found; otherwise, null. This parameter is passed uninitialized.
  202. /// </param>
  203. /// <returns><see langword="true"/> if the Key is bound; otherwise <see langword="false"/>.</returns>
  204. public bool TryGet (Key key, out KeyBinding binding)
  205. {
  206. binding = new ([], null);
  207. if (key.IsValid)
  208. {
  209. return Bindings.TryGetValue (key, out binding);
  210. }
  211. return false;
  212. }
  213. }