KeyBindings.cs 17 KB

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