InputBindings.cs 9.8 KB

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