KeyBindings.cs 15 KB

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