CWPEventHelper.cs 2.2 KB

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