KeyBindings.cs 18 KB

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