ExampleContextInjector.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. namespace Terminal.Gui.Examples;
  2. /// <summary>
  3. /// Handles automatic injection of test context into running examples.
  4. /// This class monitors for the presence of an <see cref="ExampleContext"/> in the environment
  5. /// and automatically injects keystrokes via <see cref="Application.Driver"/> after the application initializes.
  6. /// </summary>
  7. public static class ExampleContextInjector
  8. {
  9. private static bool _initialized;
  10. /// <summary>
  11. /// Sets up automatic key injection if a test context is present in the environment.
  12. /// Call this method before calling <see cref="Application.Init"/> or <see cref="IApplication.Init"/>.
  13. /// </summary>
  14. /// <remarks>
  15. /// This method is safe to call multiple times - it will only set up injection once.
  16. /// The actual key injection happens after the application is initialized, via the
  17. /// <see cref="Application.InitializedChanged"/> event.
  18. /// </remarks>
  19. public static void SetupAutomaticInjection ()
  20. {
  21. if (_initialized)
  22. {
  23. return;
  24. }
  25. _initialized = true;
  26. // Check for test context in environment variable
  27. string? contextJson = Environment.GetEnvironmentVariable (ExampleContext.ENVIRONMENT_VARIABLE_NAME);
  28. if (string.IsNullOrEmpty (contextJson))
  29. {
  30. return;
  31. }
  32. ExampleContext? context = ExampleContext.FromJson (contextJson);
  33. if (context is null || context.KeysToInject.Count == 0)
  34. {
  35. return;
  36. }
  37. // Subscribe to InitializedChanged to inject keys after initialization
  38. Application.InitializedChanged += OnInitializedChanged;
  39. return;
  40. void OnInitializedChanged (object? sender, EventArgs<bool> e)
  41. {
  42. if (!e.Value)
  43. {
  44. return;
  45. }
  46. // Application has been initialized, inject the keys
  47. if (Application.Driver is null)
  48. {
  49. return;
  50. }
  51. foreach (string keyStr in context.KeysToInject)
  52. {
  53. if (Input.Key.TryParse (keyStr, out Input.Key? key) && key is { })
  54. {
  55. Application.Driver.EnqueueKeyEvent (key);
  56. }
  57. }
  58. // Unsubscribe after injecting keys once
  59. Application.InitializedChanged -= OnInitializedChanged;
  60. }
  61. }
  62. }