InputBindings.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. namespace Terminal.Gui.Input;
  2. /// <summary>
  3. /// Abstract class for <see cref="KeyBindings"/> and <see cref="MouseBindings"/>.
  4. /// </summary>
  5. /// <typeparam name="TEvent">The type of the event (e.g. <see cref="Key"/> or <see cref="MouseFlags"/>).</typeparam>
  6. /// <typeparam name="TBinding">The binding type (e.g. <see cref="KeyBinding"/>).</typeparam>
  7. public abstract class InputBindings<TEvent, TBinding> where TBinding : IInputBinding, new () where TEvent : notnull
  8. {
  9. /// <summary>
  10. /// The bindings.
  11. /// </summary>
  12. private readonly Dictionary<TEvent, TBinding> _bindings;
  13. private readonly Func<Command [], TEvent, TBinding> _constructBinding;
  14. /// <summary>
  15. /// Initializes a new instance.
  16. /// </summary>
  17. /// <param name="constructBinding"></param>
  18. /// <param name="equalityComparer"></param>
  19. protected InputBindings (Func<Command [], TEvent, TBinding> constructBinding, IEqualityComparer<TEvent> equalityComparer)
  20. {
  21. _constructBinding = constructBinding;
  22. _bindings = new (equalityComparer);
  23. }
  24. /// <summary>
  25. /// Tests whether <paramref name="eventArgs"/> is valid or not.
  26. /// </summary>
  27. /// <param name="eventArgs"></param>
  28. /// <returns></returns>
  29. public abstract bool IsValid (TEvent eventArgs);
  30. /// <summary>Adds a <typeparamref name="TEvent"/> bound to <typeparamref name="TBinding"/> to the collection.</summary>
  31. /// <param name="eventArgs"></param>
  32. /// <param name="binding"></param>
  33. public void Add (TEvent eventArgs, TBinding binding)
  34. {
  35. if (!IsValid (eventArgs))
  36. {
  37. throw new ArgumentException (@"Invalid newEventArgs", nameof (eventArgs));
  38. }
  39. #pragma warning disable CS8601 // Possible null reference assignment.
  40. if (TryGet (eventArgs, out TBinding _))
  41. {
  42. throw new InvalidOperationException (@$"A binding for {eventArgs} exists ({binding}).");
  43. }
  44. #pragma warning restore CS8601 // Possible null reference assignment.
  45. // IMPORTANT: Add a COPY of the eventArgs. This is needed because ConfigurationManager.Apply uses DeepMemberWiseCopy
  46. // IMPORTANT: update the memory referenced by the key, and Dictionary uses caching for performance, and thus
  47. // IMPORTANT: Apply will update the Dictionary with the new eventArgs, but the old eventArgs will still be in the dictionary.
  48. // IMPORTANT: See the ConfigurationManager.Illustrate_DeepMemberWiseCopy_Breaks_Dictionary test for details.
  49. _bindings.Add (eventArgs, binding);
  50. }
  51. /// <summary>
  52. /// <para>Adds a new <typeparamref name="TEvent"/> that will trigger the commands in <paramref name="commands"/>.</para>
  53. /// <para>
  54. /// If the <typeparamref name="TEvent"/> is already bound to a different set of <see cref="Command"/>s it will be rebound
  55. /// <paramref name="commands"/>.
  56. /// </para>
  57. /// </summary>
  58. /// <param name="eventArgs">The event to check.</param>
  59. /// <param name="commands">
  60. /// The command to invoked on the <see cref="View"/> when <paramref name="eventArgs"/> is received. When
  61. /// multiple commands are provided,they will be applied in sequence. The bound <paramref name="eventArgs"/> event
  62. /// will be
  63. /// consumed if any took effect.
  64. /// </param>
  65. public void Add (TEvent eventArgs, params Command [] commands)
  66. {
  67. if (commands.Length == 0)
  68. {
  69. throw new ArgumentException (@"At least one command must be specified", nameof (commands));
  70. }
  71. if (TryGet (eventArgs, out TBinding? binding))
  72. {
  73. throw new InvalidOperationException (@$"A binding for {eventArgs} exists ({binding}).");
  74. }
  75. Add (eventArgs, _constructBinding (commands, eventArgs));
  76. }
  77. /// <summary>
  78. /// Gets the bindings.
  79. /// </summary>
  80. /// <returns></returns>
  81. public IEnumerable<KeyValuePair<TEvent, TBinding>> GetBindings () { return _bindings; }
  82. /// <summary>Removes all <typeparamref name="TEvent"/> objects from the collection.</summary>
  83. public void Clear () { _bindings.Clear (); }
  84. /// <summary>
  85. /// Removes all bindings that trigger the given command set. Views can have multiple different <typeparamref name="TEvent"/>
  86. /// bound to
  87. /// the same command sets and this method will clear all of them.
  88. /// </summary>
  89. /// <param name="command"></param>
  90. public void Clear (params Command [] command)
  91. {
  92. KeyValuePair<TEvent, TBinding> [] kvps = _bindings
  93. .Where (kvp => kvp.Value.Commands.SequenceEqual (command))
  94. .ToArray ();
  95. foreach (KeyValuePair<TEvent, TBinding> kvp in kvps)
  96. {
  97. Remove (kvp.Key);
  98. }
  99. }
  100. /// <summary>Gets the <typeparamref name="TBinding"/> for the specified <typeparamref name="TEvent"/>.</summary>
  101. /// <param name="eventArgs"></param>
  102. /// <returns></returns>
  103. public TBinding? Get (TEvent eventArgs)
  104. {
  105. if (TryGet (eventArgs, out TBinding? binding))
  106. {
  107. return binding;
  108. }
  109. throw new InvalidOperationException ($"{eventArgs} is not bound.");
  110. }
  111. /// <summary>Gets the commands bound with the specified <typeparamref name="TEvent"/>.</summary>
  112. /// <remarks></remarks>
  113. /// <param name="eventArgs">The <typeparamref name="TEvent"/> to check.</param>
  114. /// <param name="binding">
  115. /// When this method returns, contains the commands bound with the <typeparamref name="TEvent"/>, if the <typeparamref name="TEvent"/> is
  116. /// not
  117. /// found; otherwise, null. This parameter is passed uninitialized.
  118. /// </param>
  119. /// <returns><see langword="true"/> if the <typeparamref name="TEvent"/> is bound; otherwise <see langword="false"/>.</returns>
  120. public bool TryGet (TEvent eventArgs, out TBinding? binding) { return _bindings.TryGetValue (eventArgs, out binding); }
  121. /// <summary>Gets the array of <see cref="Command"/>s bound to <paramref name="eventArgs"/> if it exists.</summary>
  122. /// <param name="eventArgs">The <typeparamref name="TEvent"/> to check.</param>
  123. /// <returns>
  124. /// The array of <see cref="Command"/>s if <paramref name="eventArgs"/> is bound. An empty <see cref="Command"/> array
  125. /// if not.
  126. /// </returns>
  127. public Command [] GetCommands (TEvent eventArgs)
  128. {
  129. if (TryGet (eventArgs, out TBinding? bindings))
  130. {
  131. return bindings!.Commands;
  132. }
  133. return [];
  134. }
  135. /// <summary>
  136. /// Gets the first matching <typeparamref name="TEvent"/> bound to the set of commands specified by
  137. /// <paramref name="commands"/>.
  138. /// </summary>
  139. /// <param name="commands">The set of commands to search.</param>
  140. /// <returns>
  141. /// The first matching <typeparamref name="TEvent"/> bound to the set of commands specified by
  142. /// <paramref name="commands"/>. <see langword="null"/> if the set of commands was not found.
  143. /// </returns>
  144. public TEvent? GetFirstFromCommands (params Command [] commands) { return _bindings.FirstOrDefault (a => a.Value.Commands.SequenceEqual (commands)).Key; }
  145. /// <summary>Gets all <typeparamref name="TEvent"/> bound to the set of commands specified by <paramref name="commands"/>.</summary>
  146. /// <param name="commands">The set of commands to search.</param>
  147. /// <returns>
  148. /// The <typeparamref name="TEvent"/>s bound to the set of commands specified by <paramref name="commands"/>. An empty list if
  149. /// the
  150. /// set of commands was not found.
  151. /// </returns>
  152. public IEnumerable<TEvent> GetAllFromCommands (params Command [] commands)
  153. {
  154. return _bindings.Where (a => a.Value.Commands.SequenceEqual (commands)).Select (a => a.Key);
  155. }
  156. /// <summary>Replaces a <typeparamref name="TEvent"/> combination already bound to a set of <see cref="Command"/>s.</summary>
  157. /// <remarks></remarks>
  158. /// <param name="oldEventArgs">The <typeparamref name="TEvent"/> to be replaced.</param>
  159. /// <param name="newEventArgs">
  160. /// The new <typeparamref name="TEvent"/> to be used.
  161. /// </param>
  162. public void Replace (TEvent oldEventArgs, TEvent newEventArgs)
  163. {
  164. if (!IsValid (newEventArgs))
  165. {
  166. throw new ArgumentException (@"Invalid newEventArgs", nameof (newEventArgs));
  167. }
  168. if (TryGet (oldEventArgs, out TBinding? binding))
  169. {
  170. Remove (oldEventArgs);
  171. Add (newEventArgs, binding!);
  172. }
  173. else
  174. {
  175. Add (newEventArgs, binding!);
  176. }
  177. }
  178. /// <summary>Replaces the commands already bound to a combination of <typeparamref name="TEvent"/>.</summary>
  179. /// <remarks>
  180. /// <para>
  181. /// If the of <typeparamref name="TEvent"/> is not already bound, it will be added.
  182. /// </para>
  183. /// </remarks>
  184. /// <param name="eventArgs">The combination of <typeparamref name="TEvent"/> bound to the command to be replaced.</param>
  185. /// <param name="newCommands">The set of commands to replace the old ones with.</param>
  186. public void ReplaceCommands (TEvent eventArgs, params Command [] newCommands)
  187. {
  188. #pragma warning disable CS8601 // Possible null reference assignment.
  189. if (TryGet (eventArgs, out TBinding _))
  190. {
  191. Remove (eventArgs);
  192. Add (eventArgs, newCommands);
  193. }
  194. else
  195. {
  196. Add (eventArgs, newCommands);
  197. }
  198. #pragma warning restore CS8601 // Possible null reference assignment.
  199. }
  200. /// <summary>Removes a <typeparamref name="TEvent"/> from the collection.</summary>
  201. /// <param name="eventArgs"></param>
  202. public void Remove (TEvent eventArgs)
  203. {
  204. if (!TryGet (eventArgs, out _))
  205. {
  206. return;
  207. }
  208. _bindings.Remove (eventArgs);
  209. }
  210. }