KeyBindings.cs 17 KB

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