Skip to main content

fenestra_shell/
synthetic.rs

1//! Synthetic event injection for headless testing: agents drive an [`App`]
2//! with scripted input and look at the resulting pixels.
3
4use std::sync::{Arc, Mutex, PoisonError};
5
6use fenestra_core::{App, FrameState, InputEvent, KeyInput, Proxy, Theme, build_frame, dispatch};
7use image::RgbaImage;
8
9use crate::element_render::with_fonts;
10use crate::with_headless;
11
12/// A scripted input event for [`render_app`].
13#[derive(Debug, Clone, PartialEq)]
14pub enum SyntheticEvent {
15    /// Move the pointer to logical coordinates.
16    MouseMove {
17        /// Logical x.
18        x: f32,
19        /// Logical y.
20        y: f32,
21    },
22    /// Press the primary button.
23    MouseDown,
24    /// Release the primary button.
25    MouseUp,
26    /// Press a key.
27    Key(KeyInput),
28    /// Commit text (M5).
29    Text(String),
30    /// Scroll (winit convention: positive `dy` moves content down).
31    Wheel {
32        /// Vertical delta in logical px.
33        dy: f32,
34    },
35    /// Focus next.
36    Tab,
37    /// Focus previous.
38    ShiftTab,
39}
40
41impl From<&SyntheticEvent> for InputEvent {
42    fn from(ev: &SyntheticEvent) -> Self {
43        match ev {
44            SyntheticEvent::MouseMove { x, y } => Self::PointerMove { x: *x, y: *y },
45            SyntheticEvent::MouseDown => Self::PointerDown,
46            SyntheticEvent::MouseUp => Self::PointerUp,
47            SyntheticEvent::Key(k) => Self::Key(*k),
48            SyntheticEvent::Text(s) => Self::Text(s.clone()),
49            SyntheticEvent::Wheel { dy } => Self::Wheel { dy: *dy },
50            SyntheticEvent::Tab => Self::Tab,
51            SyntheticEvent::ShiftTab => Self::ShiftTab,
52        }
53    }
54}
55
56/// Drives an app headlessly: dispatches each event against the current
57/// view, applies the emitted messages, then renders one settle frame.
58/// Deterministic: scale 1.0, reduced motion, embedded fonts only. The
59/// requested size is clamped to the device-supported range (at least 1x1,
60/// at most the maximum texture dimension).
61///
62/// [`App::init`] runs first with a collecting [`Proxy`]; proxied messages
63/// are applied at deterministic points (before each event and before the
64/// settle frame). Messages sent from spawned threads race those drain
65/// points — keep proxy use synchronous in tests.
66///
67/// # Panics
68/// If no compute-capable GPU adapter exists or rendering fails.
69pub fn render_app<A: App>(
70    app: &mut A,
71    events: &[SyntheticEvent],
72    size: (u32, u32),
73    theme: &Theme,
74) -> RgbaImage
75where
76    A::Msg: Send,
77{
78    // Clamp before layout so the frames and the texture agree on the size.
79    let size =
80        with_headless(|h| h.clamp_size(size.0, size.1)).expect("headless renderer unavailable");
81    let pending: Arc<Mutex<Vec<A::Msg>>> = Arc::new(Mutex::new(Vec::new()));
82    let sink = Arc::clone(&pending);
83    app.init(Proxy::new(move |msg| {
84        sink.lock()
85            .unwrap_or_else(PoisonError::into_inner)
86            .push(msg);
87    }));
88    fn drain<A: App>(app: &mut A, pending: &Mutex<Vec<A::Msg>>) {
89        let msgs = std::mem::take(&mut *pending.lock().unwrap_or_else(PoisonError::into_inner));
90        for msg in msgs {
91            app.update(msg);
92        }
93    }
94    let mut state = FrameState::new();
95    state.reduced_motion = true;
96    #[expect(clippy::cast_precision_loss, reason = "window sizes fit in f32")]
97    let logical = (size.0 as f32, size.1 as f32);
98
99    let scene = with_fonts(|fonts| {
100        for ev in events {
101            drain(app, &pending);
102            let view = app.view();
103            let frame = build_frame(&view, theme, fonts, &mut state, logical, 1.0);
104            let result = dispatch(&view, &frame, &mut state, fonts, ev.into());
105            for msg in result.msgs {
106                app.update(msg);
107            }
108        }
109        // Apply late proxied messages, then one settle frame.
110        drain(app, &pending);
111        let view = app.view();
112        let frame = build_frame(&view, theme, fonts, &mut state, logical, 1.0);
113        frame.paint(fonts, &mut state)
114    });
115    with_headless(|headless| headless.render(&scene, size.0, size.1, theme.bg))
116        .expect("headless renderer unavailable")
117        .expect("headless render failed")
118}