CWPEventHelper.cs 2.1 KB

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