namespace Terminal.Gui.Examples; /// /// Handles automatic injection of test context into running examples. /// This class monitors for the presence of an in the environment /// and automatically injects keystrokes via after the application initializes. /// public static class ExampleContextInjector { private static bool _initialized; /// /// Sets up automatic key injection if a test context is present in the environment. /// Call this method before calling or . /// /// /// /// This method is safe to call multiple times - it will only set up injection once. /// The actual key injection happens after the application is initialized, via the /// event. /// public static void SetupAutomaticInjection (IApplication? app) { if (_initialized) { return; } _initialized = true; // Check for test context in environment variable string? contextJson = Environment.GetEnvironmentVariable (ExampleContext.ENVIRONMENT_VARIABLE_NAME); if (string.IsNullOrEmpty (contextJson)) { return; } ExampleContext? context = ExampleContext.FromJson (contextJson); if (context is null || context.KeysToInject.Count == 0) { return; } // Subscribe to InitializedChanged to inject keys after initialization app.SessionBegun += AppOnSessionBegun; return; void AppOnSessionBegun (object? sender, SessionTokenEventArgs e) { // Application has been initialized, inject the keys if (app.Driver is null) { return; } foreach (string keyStr in context.KeysToInject) { if (Input.Key.TryParse (keyStr, out Input.Key? key) && key is { }) { app.Keyboard.RaiseKeyDownEvent (key); } } // Unsubscribe after injecting keys once app.SessionBegun -= AppOnSessionBegun; } } }