InputBindings.cs 11 KB

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