KeyBindings.cs 16 KB

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