KeyBindings.cs 9.0 KB

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