KeyBindings.cs 13 KB

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