KeyBindings.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. #nullable enable
  2. using System.Diagnostics;
  3. namespace Terminal.Gui;
  4. /// <summary>
  5. /// Provides a collection of <see cref="KeyBinding"/> objects bound to a <see cref="Key"/>.
  6. /// </summary>
  7. public class KeyBindings
  8. {
  9. /// <summary>
  10. /// Initializes a new instance. This constructor is used when the <see cref="KeyBindings"/> are not bound to a
  11. /// <see cref="View"/>. This is used for Application.KeyBindings and unit tests.
  12. /// </summary>
  13. public KeyBindings () { }
  14. /// <summary>Initializes a new instance bound to <paramref name="boundView"/>.</summary>
  15. public KeyBindings (View boundView) { BoundView = boundView; }
  16. /// <summary>
  17. /// The view that the <see cref="KeyBindings"/> are bound to.
  18. /// </summary>
  19. /// <remarks>
  20. /// If <see langword="null"/>, the <see cref="KeyBindings"/> are not bound to a <see cref="View"/>. This is used for Application.KeyBindings.
  21. /// </remarks>
  22. public View? BoundView { get; }
  23. // TODO: Add a dictionary comparer that ignores Scope
  24. // TODO: This should not be public!
  25. /// <summary>The collection of <see cref="KeyBinding"/> objects.</summary>
  26. public Dictionary<Key, KeyBinding> Bindings { get; } = new ();
  27. /// <summary>Adds a <see cref="KeyBinding"/> to the collection.</summary>
  28. /// <param name="key"></param>
  29. /// <param name="binding"></param>
  30. public void Add (Key key, KeyBinding binding)
  31. {
  32. if (BoundView is { } && binding.Scope.FastHasFlags (KeyBindingScope.Application))
  33. {
  34. throw new ArgumentException ("Application scoped KeyBindings must be added via Application.KeyBindings.Add");
  35. }
  36. if (TryGet (key, out KeyBinding _))
  37. {
  38. Bindings [key] = binding;
  39. }
  40. else
  41. {
  42. Bindings.Add (key, binding);
  43. }
  44. }
  45. /// <summary>
  46. /// <para>Adds a new key combination that will trigger the commands in <paramref name="commands"/>.</para>
  47. /// <para>
  48. /// If the key is already bound to a different array of <see cref="Command"/>s it will be rebound
  49. /// <paramref name="commands"/>.
  50. /// </para>
  51. /// </summary>
  52. /// <remarks>
  53. /// Commands are only ever applied to the current <see cref="View"/> (i.e. this feature cannot be used to switch
  54. /// focus to another view and perform multiple commands there).
  55. /// </remarks>
  56. /// <param name="key">The key to check.</param>
  57. /// <param name="scope">The scope for the command.</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. public void Add (Key key, KeyBindingScope scope, params Command [] commands)
  64. {
  65. if (BoundView is { } && scope.FastHasFlags (KeyBindingScope.Application))
  66. {
  67. throw new ArgumentException ("Application scoped KeyBindings must be added via Application.KeyBindings.Add");
  68. }
  69. if (key is null || !key.IsValid)
  70. {
  71. //throw new ArgumentException ("Invalid Key", nameof (commands));
  72. return;
  73. }
  74. if (commands.Length == 0)
  75. {
  76. throw new ArgumentException (@"At least one command must be specified", nameof (commands));
  77. }
  78. if (TryGet (key, out KeyBinding _))
  79. {
  80. Bindings [key] = new (commands, scope);
  81. }
  82. else
  83. {
  84. Add (key, new KeyBinding (commands, scope));
  85. }
  86. }
  87. /// <summary>
  88. /// <para>
  89. /// Adds a new key combination that will trigger the commands in <paramref name="commands"/> (if supported by the
  90. /// View - see <see cref="View.GetSupportedCommands"/>).
  91. /// </para>
  92. /// <para>
  93. /// This is a helper function for <see cref="Add(Key,KeyBindingScope,Terminal.Gui.Command[])"/> for
  94. /// <see cref="KeyBindingScope.Focused"/> scoped commands.
  95. /// </para>
  96. /// <para>
  97. /// If the key is already bound to a different array of <see cref="Command"/>s it will be rebound
  98. /// <paramref name="commands"/>.
  99. /// </para>
  100. /// </summary>
  101. /// <remarks>
  102. /// Commands are only ever applied to the current <see cref="View"/> (i.e. this feature cannot be used to switch
  103. /// focus to another view and perform multiple commands there).
  104. /// </remarks>
  105. /// <param name="key">The key to check.</param>
  106. /// <param name="commands">
  107. /// The command to invoked on the <see cref="View"/> when <paramref name="key"/> is pressed. When
  108. /// multiple commands are provided,they will be applied in sequence. The bound <paramref name="key"/> strike will be
  109. /// consumed if any took effect.
  110. /// </param>
  111. public void Add (Key key, params Command [] commands)
  112. {
  113. Add (key, KeyBindingScope.Focused, commands);
  114. }
  115. /// <summary>Removes all <see cref="KeyBinding"/> objects from the collection.</summary>
  116. public void Clear ()
  117. {
  118. Application.ClearKeyBindings (BoundView);
  119. Bindings.Clear ();
  120. }
  121. /// <summary>
  122. /// Removes all key bindings that trigger the given command set. Views can have multiple different keys bound to
  123. /// the same command sets and this method will clear all of them.
  124. /// </summary>
  125. /// <param name="command"></param>
  126. public void Clear (params Command [] command)
  127. {
  128. KeyValuePair<Key, KeyBinding> [] kvps = Bindings
  129. .Where (kvp => kvp.Value.Commands.SequenceEqual (command))
  130. .ToArray ();
  131. foreach (KeyValuePair<Key, KeyBinding> kvp in kvps)
  132. {
  133. Remove (kvp.Key);
  134. }
  135. }
  136. /// <summary>Gets the <see cref="KeyBinding"/> for the specified <see cref="Key"/>.</summary>
  137. /// <param name="key"></param>
  138. /// <returns></returns>
  139. public KeyBinding Get (Key key)
  140. {
  141. if (TryGet (key, out KeyBinding binding))
  142. {
  143. return binding;
  144. }
  145. throw new InvalidOperationException ($"Key {key} is not bound.");
  146. }
  147. /// <summary>Gets the <see cref="KeyBinding"/> for the specified <see cref="Key"/>.</summary>
  148. /// <param name="key"></param>
  149. /// <param name="scope"></param>
  150. /// <returns></returns>
  151. public KeyBinding Get (Key key, KeyBindingScope scope)
  152. {
  153. if (TryGet (key, scope, out KeyBinding binding))
  154. {
  155. return binding;
  156. }
  157. throw new InvalidOperationException ($"Key {key}/{scope} is not bound.");
  158. }
  159. /// <summary>Gets the array of <see cref="Command"/>s bound to <paramref name="key"/> if it exists.</summary>
  160. /// <param name="key">The key to check.</param>
  161. /// <returns>
  162. /// The array of <see cref="Command"/>s if <paramref name="key"/> is bound. An empty <see cref="Command"/> array
  163. /// if not.
  164. /// </returns>
  165. public Command [] GetCommands (Key key)
  166. {
  167. if (TryGet (key, out KeyBinding bindings))
  168. {
  169. return bindings.Commands;
  170. }
  171. return Array.Empty<Command> ();
  172. }
  173. /// <summary>Gets the Key used by a set of commands.</summary>
  174. /// <remarks></remarks>
  175. /// <param name="commands">The set of commands to search.</param>
  176. /// <returns>The <see cref="Key"/> used by a <see cref="Command"/></returns>
  177. /// <exception cref="InvalidOperationException">If no matching set of commands was found.</exception>
  178. public Key GetKeyFromCommands (params Command [] commands) { return Bindings.First (a => a.Value.Commands.SequenceEqual (commands)).Key; }
  179. /// <summary>Removes a <see cref="KeyBinding"/> from the collection.</summary>
  180. /// <param name="key"></param>
  181. public void Remove (Key key)
  182. {
  183. Bindings.Remove (key);
  184. Application.RemoveKeyBinding (key, BoundView);
  185. }
  186. /// <summary>Replaces a key combination already bound to a set of <see cref="Command"/>s.</summary>
  187. /// <remarks></remarks>
  188. /// <param name="oldKey">The key to be replaced.</param>
  189. /// <param name="newKey">The new key to be used.</param>
  190. public void Replace (Key oldKey, Key newKey)
  191. {
  192. if (!TryGet (oldKey, out KeyBinding _))
  193. {
  194. return;
  195. }
  196. KeyBinding value = Bindings [oldKey];
  197. Remove (oldKey);
  198. Add (newKey, value);
  199. }
  200. /// <summary>Gets the commands bound with the specified Key.</summary>
  201. /// <remarks></remarks>
  202. /// <param name="key">The key to check.</param>
  203. /// <param name="binding">
  204. /// When this method returns, contains the commands bound with the specified Key, if the Key is
  205. /// found; otherwise, null. This parameter is passed uninitialized.
  206. /// </param>
  207. /// <returns><see langword="true"/> if the Key is bound; otherwise <see langword="false"/>.</returns>
  208. public bool TryGet (Key key, out KeyBinding binding)
  209. {
  210. if (key.IsValid)
  211. {
  212. return Bindings.TryGetValue (key, out binding);
  213. }
  214. binding = new (Array.Empty<Command> (), KeyBindingScope.Focused);
  215. return false;
  216. }
  217. /// <summary>Gets the commands bound with the specified Key that are scoped to a particular scope.</summary>
  218. /// <remarks></remarks>
  219. /// <param name="key">The key to check.</param>
  220. /// <param name="scope">the scope to filter on</param>
  221. /// <param name="binding">
  222. /// When this method returns, contains the commands bound with the specified Key, if the Key is
  223. /// found; otherwise, null. This parameter is passed uninitialized.
  224. /// </param>
  225. /// <returns><see langword="true"/> if the Key is bound; otherwise <see langword="false"/>.</returns>
  226. public bool TryGet (Key key, KeyBindingScope scope, out KeyBinding binding)
  227. {
  228. if (key.IsValid && Bindings.TryGetValue (key, out binding))
  229. {
  230. if (scope.HasFlag (binding.Scope))
  231. {
  232. return true;
  233. }
  234. }
  235. binding = new (Array.Empty<Command> (), KeyBindingScope.Focused);
  236. return false;
  237. }
  238. }