KeyBindings.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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. public class KeyBindings
  7. {
  8. /// <summary>
  9. /// Initializes a new instance. This constructor is used when the <see cref="KeyBindings"/> are not bound to a
  10. /// <see cref="View"/>. This is used for Application.KeyBindings and unit tests.
  11. /// </summary>
  12. public KeyBindings () { }
  13. /// <summary>Initializes a new instance bound to <paramref name="boundView"/>.</summary>
  14. public KeyBindings (View boundView) { BoundView = boundView; }
  15. /// <summary>Adds a <see cref="KeyBinding"/> to the collection.</summary>
  16. /// <param name="key"></param>
  17. /// <param name="binding"></param>
  18. /// <param name="boundViewForAppScope">Optional View for <see cref="KeyBindingScope.Application"/> bindings.</param>
  19. public void Add (Key key, KeyBinding binding, View? boundViewForAppScope = null)
  20. {
  21. if (BoundView is { } && binding.Scope.FastHasFlags (KeyBindingScope.Application))
  22. {
  23. throw new ArgumentException ("Application scoped KeyBindings must be added via Application.KeyBindings.Add");
  24. }
  25. if (TryGet (key, out KeyBinding _))
  26. {
  27. throw new InvalidOperationException (@$"A key binding for {key} exists ({binding}).");
  28. //Bindings [key] = binding;
  29. }
  30. if (BoundView is { })
  31. {
  32. binding.BoundView = BoundView;
  33. }
  34. else
  35. {
  36. binding.BoundView = boundViewForAppScope;
  37. }
  38. Bindings.Add (key, binding);
  39. }
  40. /// <summary>
  41. /// <para>Adds a new key combination that will trigger the commands in <paramref name="commands"/>.</para>
  42. /// <para>
  43. /// If the key is already bound to a different array of <see cref="Command"/>s it will be rebound
  44. /// <paramref name="commands"/>.
  45. /// </para>
  46. /// </summary>
  47. /// <remarks>
  48. /// Commands are only ever applied to the current <see cref="View"/> (i.e. this feature cannot be used to switch
  49. /// focus to another view and perform multiple commands there).
  50. /// </remarks>
  51. /// <param name="key">The key to check.</param>
  52. /// <param name="scope">The scope for the command.</param>
  53. /// <param name="boundViewForAppScope">Optional View for <see cref="KeyBindingScope.Application"/> bindings.</param>
  54. /// <param name="commands">
  55. /// The command to invoked on the <see cref="View"/> when <paramref name="key"/> is pressed. When
  56. /// multiple commands are provided,they will be applied in sequence. The bound <paramref name="key"/> strike will be
  57. /// consumed if any took effect.
  58. /// </param>
  59. public void Add (Key key, KeyBindingScope scope, View? boundViewForAppScope = null, params Command [] commands)
  60. {
  61. if (BoundView is { } && scope.FastHasFlags (KeyBindingScope.Application))
  62. {
  63. throw new ArgumentException ("Application scoped KeyBindings must be added via Application.KeyBindings.Add");
  64. }
  65. if (key is null || !key.IsValid)
  66. {
  67. //throw new ArgumentException ("Invalid Key", nameof (commands));
  68. return;
  69. }
  70. if (commands.Length == 0)
  71. {
  72. throw new ArgumentException (@"At least one command must be specified", nameof (commands));
  73. }
  74. if (TryGet (key, out KeyBinding binding))
  75. {
  76. throw new InvalidOperationException (@$"A key binding for {key} exists ({binding}).");
  77. //Bindings [key] = new (commands, scope, BoundView);
  78. }
  79. Add (key, new KeyBinding (commands, scope, BoundView), boundViewForAppScope);
  80. }
  81. /// <summary>
  82. /// <para>Adds a new key combination that will trigger the commands in <paramref name="commands"/>.</para>
  83. /// <para>
  84. /// If the key is already bound to a different array of <see cref="Command"/>s it will be rebound
  85. /// <paramref name="commands"/>.
  86. /// </para>
  87. /// </summary>
  88. /// <remarks>
  89. /// Commands are only ever applied to the current <see cref="View"/> (i.e. this feature cannot be used to switch
  90. /// focus to another view and perform multiple commands there).
  91. /// </remarks>
  92. /// <param name="key">The key to check.</param>
  93. /// <param name="scope">The scope for the command.</param>
  94. /// <param name="commands">
  95. /// The command to invoked on the <see cref="View"/> when <paramref name="key"/> is pressed. When
  96. /// multiple commands are provided,they will be applied in sequence. The bound <paramref name="key"/> strike will be
  97. /// consumed if any took effect.
  98. /// </param>
  99. public void Add (Key key, KeyBindingScope scope, params Command [] commands)
  100. {
  101. if (BoundView is { } && scope.FastHasFlags (KeyBindingScope.Application))
  102. {
  103. throw new ArgumentException ("Application scoped KeyBindings must be added via Application.KeyBindings.Add");
  104. }
  105. if (key == Key.Empty || !key.IsValid)
  106. {
  107. throw new ArgumentException (@"Invalid Key", nameof (commands));
  108. }
  109. if (commands.Length == 0)
  110. {
  111. throw new ArgumentException (@"At least one command must be specified", nameof (commands));
  112. }
  113. if (TryGet (key, out KeyBinding binding))
  114. {
  115. throw new InvalidOperationException (@$"A key binding for {key} exists ({binding}).");
  116. }
  117. Add (key, new KeyBinding (commands, scope, BoundView));
  118. }
  119. /// <summary>
  120. /// <para>
  121. /// Adds a new key combination that will trigger the commands in <paramref name="commands"/> (if supported by the
  122. /// View - see <see cref="View.GetSupportedCommands"/>).
  123. /// </para>
  124. /// <para>
  125. /// This is a helper function for <see cref="Add(Key,KeyBinding,View?)"/>. If used for a View (
  126. /// <see cref="BoundView"/> is set), the scope will be set to <see cref="KeyBindingScope.Focused"/>.
  127. /// Otherwise, it will be set to <see cref="KeyBindingScope.Application"/>.
  128. /// </para>
  129. /// <para>
  130. /// If the key is already bound to a different array of <see cref="Command"/>s it will be rebound
  131. /// <paramref name="commands"/>.
  132. /// </para>
  133. /// </summary>
  134. /// <remarks>
  135. /// Commands are only ever applied to the current <see cref="View"/> (i.e. this feature cannot be used to switch
  136. /// focus to another view and perform multiple commands there).
  137. /// </remarks>
  138. /// <param name="key">The key to check.</param>
  139. /// <param name="boundViewForAppScope">Optional View for <see cref="KeyBindingScope.Application"/> bindings.</param>
  140. /// <param name="commands">
  141. /// The command to invoked on the <see cref="View"/> when <paramref name="key"/> is pressed. When
  142. /// multiple commands are provided,they will be applied in sequence. The bound <paramref name="key"/> strike will be
  143. /// consumed if any took effect.
  144. /// </param>
  145. public void Add (Key key, View? boundViewForAppScope = null, params Command [] commands)
  146. {
  147. if (BoundView is null && boundViewForAppScope is null)
  148. {
  149. throw new ArgumentException (@"Application scoped KeyBindings must provide a bound view to Add.", nameof (boundViewForAppScope));
  150. }
  151. Add (key, BoundView is { } ? KeyBindingScope.Focused : KeyBindingScope.Application, boundViewForAppScope, commands);
  152. }
  153. /// <summary>
  154. /// <para>
  155. /// Adds a new key combination that will trigger the commands in <paramref name="commands"/> (if supported by the
  156. /// View - see <see cref="View.GetSupportedCommands"/>).
  157. /// </para>
  158. /// <para>
  159. /// This is a helper function for <see cref="Add(Key,KeyBinding,View?)"/>. If used for a View (
  160. /// <see cref="BoundView"/> is set), the scope will be set to <see cref="KeyBindingScope.Focused"/>.
  161. /// Otherwise, it will be set to <see cref="KeyBindingScope.Application"/>.
  162. /// </para>
  163. /// <para>
  164. /// If the key is already bound to a different array of <see cref="Command"/>s it will be rebound
  165. /// <paramref name="commands"/>.
  166. /// </para>
  167. /// </summary>
  168. /// <remarks>
  169. /// Commands are only ever applied to the current <see cref="View"/> (i.e. this feature cannot be used to switch
  170. /// focus to another view and perform multiple commands there).
  171. /// </remarks>
  172. /// <param name="key">The key to check.</param>
  173. /// <param name="commands">
  174. /// The command to invoked on the <see cref="View"/> when <paramref name="key"/> is pressed. When
  175. /// multiple commands are provided,they will be applied in sequence. The bound <paramref name="key"/> strike will be
  176. /// consumed if any took effect.
  177. /// </param>
  178. public void Add (Key key, params Command [] commands)
  179. {
  180. if (BoundView is null)
  181. {
  182. throw new ArgumentException (@"Application scoped KeyBindings must provide a boundViewForAppScope to Add.");
  183. }
  184. Add (key, BoundView is { } ? KeyBindingScope.Focused : KeyBindingScope.Application, null, commands);
  185. }
  186. // TODO: Add a dictionary comparer that ignores Scope
  187. // TODO: This should not be public!
  188. /// <summary>The collection of <see cref="KeyBinding"/> objects.</summary>
  189. public Dictionary<Key, KeyBinding> Bindings { get; } = new ();
  190. /// <summary>
  191. /// The view that the <see cref="KeyBindings"/> are bound to.
  192. /// </summary>
  193. /// <remarks>
  194. /// If <see langword="null"/>, the <see cref="KeyBindings"/> are not bound to a <see cref="View"/>. This is used for
  195. /// Application.KeyBindings.
  196. /// </remarks>
  197. public View? BoundView { get; }
  198. /// <summary>Removes all <see cref="KeyBinding"/> objects from the collection.</summary>
  199. public void Clear () { Bindings.Clear (); }
  200. /// <summary>
  201. /// Removes all key bindings that trigger the given command set. Views can have multiple different keys bound to
  202. /// the same command sets and this method will clear all of them.
  203. /// </summary>
  204. /// <param name="command"></param>
  205. public void Clear (params Command [] command)
  206. {
  207. KeyValuePair<Key, KeyBinding> [] kvps = Bindings
  208. .Where (kvp => kvp.Value.Commands.SequenceEqual (command))
  209. .ToArray ();
  210. foreach (KeyValuePair<Key, KeyBinding> kvp in kvps)
  211. {
  212. Remove (kvp.Key);
  213. }
  214. }
  215. /// <summary>Gets the <see cref="KeyBinding"/> for the specified <see cref="Key"/>.</summary>
  216. /// <param name="key"></param>
  217. /// <returns></returns>
  218. public KeyBinding Get (Key key)
  219. {
  220. if (TryGet (key, out KeyBinding binding))
  221. {
  222. return binding;
  223. }
  224. throw new InvalidOperationException ($"Key {key} is not bound.");
  225. }
  226. /// <summary>Gets the <see cref="KeyBinding"/> for the specified <see cref="Key"/>.</summary>
  227. /// <param name="key"></param>
  228. /// <param name="scope"></param>
  229. /// <returns></returns>
  230. public KeyBinding Get (Key key, KeyBindingScope scope)
  231. {
  232. if (TryGet (key, scope, out KeyBinding binding))
  233. {
  234. return binding;
  235. }
  236. throw new InvalidOperationException ($"Key {key}/{scope} is not bound.");
  237. }
  238. /// <summary>Gets the array of <see cref="Command"/>s bound to <paramref name="key"/> if it exists.</summary>
  239. /// <param name="key">The key to check.</param>
  240. /// <returns>
  241. /// The array of <see cref="Command"/>s if <paramref name="key"/> is bound. An empty <see cref="Command"/> array
  242. /// if not.
  243. /// </returns>
  244. public Command [] GetCommands (Key key)
  245. {
  246. if (TryGet (key, out KeyBinding bindings))
  247. {
  248. return bindings.Commands;
  249. }
  250. return Array.Empty<Command> ();
  251. }
  252. // TODO: Consider having this return all keys bound to the commands
  253. /// <summary>Gets the first Key bound to the set of commands specified by <paramref name="commands"/>.</summary>
  254. /// <param name="commands">The set of commands to search.</param>
  255. /// <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>
  256. public Key? GetKeyFromCommands (params Command [] commands)
  257. {
  258. return Bindings.FirstOrDefault (a => a.Value.Commands.SequenceEqual (commands)).Key;
  259. }
  260. /// <summary>Removes a <see cref="KeyBinding"/> from the collection.</summary>
  261. /// <param name="key"></param>
  262. /// <param name="boundViewForAppScope">Optional View for <see cref="KeyBindingScope.Application"/> bindings.</param>
  263. public void Remove (Key key, View? boundViewForAppScope = null)
  264. {
  265. if (!TryGet (key, out KeyBinding binding))
  266. {
  267. return;
  268. }
  269. Bindings.Remove (key);
  270. }
  271. /// <summary>Replaces the commands already bound to a key.</summary>
  272. /// <remarks>
  273. /// <para>
  274. /// If the key is not already bound, it will be added.
  275. /// </para>
  276. /// </remarks>
  277. /// <param name="key">The key bound to the command to be replaced.</param>
  278. /// <param name="commands">The set of commands to replace the old ones with.</param>
  279. public void ReplaceCommands (Key key, params Command [] commands)
  280. {
  281. if (TryGet (key, out KeyBinding binding))
  282. {
  283. binding.Commands = commands;
  284. }
  285. else
  286. {
  287. Add (key, commands);
  288. }
  289. }
  290. /// <summary>Replaces a key combination already bound to a set of <see cref="Command"/>s.</summary>
  291. /// <remarks></remarks>
  292. /// <param name="oldKey">The key to be replaced.</param>
  293. /// <param name="newKey">The new key to be used. If <see cref="Key.Empty"/> no action will be taken.</param>
  294. public void ReplaceKey (Key oldKey, Key newKey)
  295. {
  296. if (!TryGet (oldKey, out KeyBinding _))
  297. {
  298. throw new InvalidOperationException ($"Key {oldKey} is not bound.");
  299. }
  300. if (!newKey.IsValid)
  301. {
  302. throw new InvalidOperationException ($"Key {newKey} is is not valid.");
  303. }
  304. KeyBinding value = Bindings [oldKey];
  305. Remove (oldKey);
  306. Add (newKey, value);
  307. }
  308. /// <summary>Gets the commands bound with the specified Key.</summary>
  309. /// <remarks></remarks>
  310. /// <param name="key">The key to check.</param>
  311. /// <param name="binding">
  312. /// When this method returns, contains the commands bound with the specified Key, if the Key is
  313. /// found; otherwise, null. This parameter is passed uninitialized.
  314. /// </param>
  315. /// <returns><see langword="true"/> if the Key is bound; otherwise <see langword="false"/>.</returns>
  316. public bool TryGet (Key key, out KeyBinding binding)
  317. {
  318. binding = new (Array.Empty<Command> (), KeyBindingScope.Disabled, null);
  319. if (key.IsValid)
  320. {
  321. return Bindings.TryGetValue (key, out binding);
  322. }
  323. return false;
  324. }
  325. /// <summary>Gets the commands bound with the specified Key that are scoped to a particular scope.</summary>
  326. /// <remarks></remarks>
  327. /// <param name="key">The key to check.</param>
  328. /// <param name="scope">the scope to filter on</param>
  329. /// <param name="binding">
  330. /// When this method returns, contains the commands bound with the specified Key, if the Key is
  331. /// found; otherwise, null. This parameter is passed uninitialized.
  332. /// </param>
  333. /// <returns><see langword="true"/> if the Key is bound; otherwise <see langword="false"/>.</returns>
  334. public bool TryGet (Key key, KeyBindingScope scope, out KeyBinding binding)
  335. {
  336. binding = new (Array.Empty<Command> (), KeyBindingScope.Disabled, null);
  337. if (key.IsValid && Bindings.TryGetValue (key, out binding))
  338. {
  339. if (scope.HasFlag (binding.Scope))
  340. {
  341. return true;
  342. }
  343. }
  344. return false;
  345. }
  346. }