CWPEventHelper.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #nullable enable
  2. namespace Terminal.Gui.App;
  3. using System;
  4. /// <summary>
  5. /// Provides helper methods for executing event-driven workflows in the Cancellable Work Pattern (CWP).
  6. /// </summary>
  7. /// <remarks>
  8. /// <para>
  9. /// Used for workflows where an event is raised to allow cancellation or customization of a result,
  10. /// such as in <see cref="Application.RaiseKeyDownEvent"/>. The <see cref="Execute{T}"/> method invokes an
  11. /// event handler and returns whether the operation was handled, supporting result production
  12. /// scenarios with <see cref="ResultEventArgs{T}"/>.
  13. /// </para>
  14. /// </remarks>
  15. /// <seealso cref="ResultEventArgs{T}"/>
  16. public static class CWPEventHelper
  17. {
  18. /// <summary>
  19. /// Executes an event-driven CWP workflow by raising an event.
  20. /// </summary>
  21. /// <typeparam name="T">The type of the result in the event arguments.</typeparam>
  22. /// <param name="eventHandler">The event handler to invoke, or null if no handler is subscribed.</param>
  23. /// <param name="args">The event arguments, containing a result and handled status.</param>
  24. /// <returns>True if the event was handled, false otherwise.</returns>
  25. /// <exception cref="ArgumentNullException">Thrown if <paramref name="args"/> is null.</exception>
  26. /// <example>
  27. /// <code>
  28. /// EventHandler&lt;ResultEventArgs&lt;Key&gt;&gt;? keyDownHandler = (sender, args) =>
  29. /// {
  30. /// if (args.Result?.KeyCode == KeyCode.Q | KeyCode.CtrlMask)
  31. /// {
  32. /// args.Handled = true;
  33. /// }
  34. /// };
  35. /// ResultEventArgs&lt;Key&gt; args = new(new Key(KeyCode.Q | KeyCode.CtrlMask));
  36. /// bool handled = CWPEventHelper.Execute(keyDownHandler, args);
  37. /// </code>
  38. /// </example>
  39. public static bool Execute<T> (
  40. EventHandler<ResultEventArgs<T>>? eventHandler,
  41. ResultEventArgs<T> args)
  42. {
  43. ArgumentNullException.ThrowIfNull (args);
  44. if (eventHandler == null)
  45. {
  46. return false;
  47. }
  48. eventHandler.Invoke (null, args);
  49. return args.Handled;
  50. }
  51. }