KeyBindings.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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 is null || !key.IsValid)
  125. {
  126. //throw new ArgumentException ("Invalid Key", nameof (commands));
  127. return;
  128. }
  129. if (commands.Length == 0)
  130. {
  131. throw new ArgumentException (@"At least one command must be specified", nameof (commands));
  132. }
  133. if (TryGet (key, out KeyBinding binding))
  134. {
  135. throw new InvalidOperationException (@$"A key binding for {key} exists ({binding}).");
  136. //Bindings [key] = new (commands, scope, BoundView);
  137. }
  138. else
  139. {
  140. Add (key, new KeyBinding (commands, scope, BoundView), null);
  141. }
  142. }
  143. /// <summary>
  144. /// <para>
  145. /// Adds a new key combination that will trigger the commands in <paramref name="commands"/> (if supported by the
  146. /// View - see <see cref="View.GetSupportedCommands"/>).
  147. /// </para>
  148. /// <para>
  149. /// 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"/>.
  150. /// Otherwise, it will be set to <see cref="KeyBindingScope.Application"/>.
  151. /// </para>
  152. /// <para>
  153. /// If the key is already bound to a different array of <see cref="Command"/>s it will be rebound
  154. /// <paramref name="commands"/>.
  155. /// </para>
  156. /// </summary>
  157. /// <remarks>
  158. /// Commands are only ever applied to the current <see cref="View"/> (i.e. this feature cannot be used to switch
  159. /// focus to another view and perform multiple commands there).
  160. /// </remarks>
  161. /// <param name="key">The key to check.</param>
  162. /// <param name="boundViewForAppScope">Optional View for <see cref="KeyBindingScope.Application"/> bindings.</param>
  163. /// <param name="commands">
  164. /// The command to invoked on the <see cref="View"/> when <paramref name="key"/> is pressed. When
  165. /// multiple commands are provided,they will be applied in sequence. The bound <paramref name="key"/> strike will be
  166. /// consumed if any took effect.
  167. /// </param>
  168. public void Add (Key key, View? boundViewForAppScope = null, params Command [] commands)
  169. {
  170. if (BoundView is null && boundViewForAppScope is null)
  171. {
  172. throw new ArgumentException (@"Application scoped KeyBindings must provide a bound view to Add.", nameof(boundViewForAppScope));
  173. }
  174. Add (key, BoundView is { } ? KeyBindingScope.Focused : KeyBindingScope.Application, boundViewForAppScope, commands);
  175. }
  176. /// <summary>
  177. /// <para>
  178. /// Adds a new key combination that will trigger the commands in <paramref name="commands"/> (if supported by the
  179. /// View - see <see cref="View.GetSupportedCommands"/>).
  180. /// </para>
  181. /// <para>
  182. /// 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"/>.
  183. /// Otherwise, it will be set to <see cref="KeyBindingScope.Application"/>.
  184. /// </para>
  185. /// <para>
  186. /// If the key is already bound to a different array of <see cref="Command"/>s it will be rebound
  187. /// <paramref name="commands"/>.
  188. /// </para>
  189. /// </summary>
  190. /// <remarks>
  191. /// Commands are only ever applied to the current <see cref="View"/> (i.e. this feature cannot be used to switch
  192. /// focus to another view and perform multiple commands there).
  193. /// </remarks>
  194. /// <param name="key">The key to check.</param>
  195. /// <param name="commands">
  196. /// The command to invoked on the <see cref="View"/> when <paramref name="key"/> is pressed. When
  197. /// multiple commands are provided,they will be applied in sequence. The bound <paramref name="key"/> strike will be
  198. /// consumed if any took effect.
  199. /// </param>
  200. public void Add (Key key, params Command [] commands)
  201. {
  202. if (BoundView is null)
  203. {
  204. throw new ArgumentException (@"Application scoped KeyBindings must provide a boundViewForAppScope to Add.");
  205. }
  206. Add (key, BoundView is { } ? KeyBindingScope.Focused : KeyBindingScope.Application, null, commands);
  207. }
  208. /// <summary>Removes all <see cref="KeyBinding"/> objects from the collection.</summary>
  209. public void Clear ()
  210. {
  211. Bindings.Clear ();
  212. }
  213. /// <summary>
  214. /// Removes all key bindings that trigger the given command set. Views can have multiple different keys bound to
  215. /// the same command sets and this method will clear all of them.
  216. /// </summary>
  217. /// <param name="command"></param>
  218. public void Clear (params Command [] command)
  219. {
  220. KeyValuePair<Key, KeyBinding> [] kvps = Bindings
  221. .Where (kvp => kvp.Value.Commands.SequenceEqual (command))
  222. .ToArray ();
  223. foreach (KeyValuePair<Key, KeyBinding> kvp in kvps)
  224. {
  225. Remove (kvp.Key);
  226. }
  227. }
  228. /// <summary>Gets the <see cref="KeyBinding"/> for the specified <see cref="Key"/>.</summary>
  229. /// <param name="key"></param>
  230. /// <returns></returns>
  231. public KeyBinding Get (Key key)
  232. {
  233. if (TryGet (key, out KeyBinding binding))
  234. {
  235. return binding;
  236. }
  237. throw new InvalidOperationException ($"Key {key} is not bound.");
  238. }
  239. /// <summary>Gets the <see cref="KeyBinding"/> for the specified <see cref="Key"/>.</summary>
  240. /// <param name="key"></param>
  241. /// <param name="scope"></param>
  242. /// <returns></returns>
  243. public KeyBinding Get (Key key, KeyBindingScope scope)
  244. {
  245. if (TryGet (key, scope, out KeyBinding binding))
  246. {
  247. return binding;
  248. }
  249. throw new InvalidOperationException ($"Key {key}/{scope} is not bound.");
  250. }
  251. /// <summary>Gets the array of <see cref="Command"/>s bound to <paramref name="key"/> if it exists.</summary>
  252. /// <param name="key">The key to check.</param>
  253. /// <returns>
  254. /// The array of <see cref="Command"/>s if <paramref name="key"/> is bound. An empty <see cref="Command"/> array
  255. /// if not.
  256. /// </returns>
  257. public Command [] GetCommands (Key key)
  258. {
  259. if (TryGet (key, out KeyBinding bindings))
  260. {
  261. return bindings.Commands;
  262. }
  263. return Array.Empty<Command> ();
  264. }
  265. /// <summary>Gets the Key used by a set of commands.</summary>
  266. /// <remarks></remarks>
  267. /// <param name="commands">The set of commands to search.</param>
  268. /// <returns>The <see cref="Key"/> used by a <see cref="Command"/></returns>
  269. /// <exception cref="InvalidOperationException">If no matching set of commands was found.</exception>
  270. public Key GetKeyFromCommands (params Command [] commands) { return Bindings.First (a => a.Value.Commands.SequenceEqual (commands)).Key; }
  271. /// <summary>Removes a <see cref="KeyBinding"/> from the collection.</summary>
  272. /// <param name="key"></param>
  273. /// <param name="boundViewForAppScope">Optional View for <see cref="KeyBindingScope.Application"/> bindings.</param>
  274. public void Remove (Key key, View? boundViewForAppScope = null)
  275. {
  276. if (!TryGet (key, out KeyBinding binding))
  277. {
  278. return;
  279. }
  280. Bindings.Remove (key);
  281. }
  282. /// <summary>Replaces a key combination already bound to a set of <see cref="Command"/>s.</summary>
  283. /// <remarks></remarks>
  284. /// <param name="oldKey">The key to be replaced.</param>
  285. /// <param name="newKey">The new key to be used.</param>
  286. public void ReplaceKey (Key oldKey, Key newKey)
  287. {
  288. if (!TryGet (oldKey, out KeyBinding _))
  289. {
  290. return;
  291. }
  292. KeyBinding value = Bindings [oldKey];
  293. Remove (oldKey);
  294. Add (newKey, value);
  295. }
  296. /// <summary>Replaces the commands already bound to a key.</summary>
  297. /// <remarks>
  298. /// <para>
  299. /// If the key is not already bound, it will be added.
  300. /// </para>
  301. /// </remarks>
  302. /// <param name="key">The key bound to the command to be replaced.</param>
  303. /// <param name="commands">The set of commands to replace the old ones with.</param>
  304. public void ReplaceCommands (Key key, params Command [] commands)
  305. {
  306. if (TryGet (key, out KeyBinding binding))
  307. {
  308. binding.Commands = commands;
  309. }
  310. else
  311. {
  312. Add (key, commands);
  313. }
  314. }
  315. /// <summary>Gets the commands bound with the specified Key.</summary>
  316. /// <remarks></remarks>
  317. /// <param name="key">The key to check.</param>
  318. /// <param name="binding">
  319. /// When this method returns, contains the commands bound with the specified Key, if the Key is
  320. /// found; otherwise, null. This parameter is passed uninitialized.
  321. /// </param>
  322. /// <returns><see langword="true"/> if the Key is bound; otherwise <see langword="false"/>.</returns>
  323. public bool TryGet (Key key, out KeyBinding binding)
  324. {
  325. binding = new (Array.Empty<Command> (), KeyBindingScope.Disabled, null);
  326. if (key.IsValid)
  327. {
  328. return Bindings.TryGetValue (key, out binding);
  329. }
  330. return false;
  331. }
  332. /// <summary>Gets the commands bound with the specified Key that are scoped to a particular scope.</summary>
  333. /// <remarks></remarks>
  334. /// <param name="key">The key to check.</param>
  335. /// <param name="scope">the scope to filter on</param>
  336. /// <param name="binding">
  337. /// When this method returns, contains the commands bound with the specified Key, if the Key is
  338. /// found; otherwise, null. This parameter is passed uninitialized.
  339. /// </param>
  340. /// <returns><see langword="true"/> if the Key is bound; otherwise <see langword="false"/>.</returns>
  341. public bool TryGet (Key key, KeyBindingScope scope, out KeyBinding binding)
  342. {
  343. binding = new (Array.Empty<Command> (), KeyBindingScope.Disabled, null);
  344. if (key.IsValid && Bindings.TryGetValue (key, out binding))
  345. {
  346. if (scope.HasFlag (binding.Scope))
  347. {
  348. return true;
  349. }
  350. }
  351. return false;
  352. }
  353. }