Skip to main content

uzor_framework/host/
headless.rs

1//! The headless host (design §9.1): deterministic, clock-injected, no OS.
2//!
3//! Time never moves on its own — [`HeadlessHost::advance`] adds `dt` to
4//! the host clock and runs exactly one tick (plus the settling tick the
5//! host's own echo answers cause), painting every due frame request into
6//! a recording context. Host-bound commands that need an OS answer are
7//! answered automatically: `Spawn` gets a `Created` echo, `Close` gets
8//! `Destroyed`. Every §9.2 script runs against this host.
9
10use std::sync::Arc;
11
12use uzor::testing::RecordingRenderContext;
13
14use crate::runtime::{Runtime, RuntimeConfig, TickOutput};
15use crate::types::bus::{HostCaps, InputEnvelope, InputEvent, WindowInput};
16use crate::types::command::{AppCommand, WindowCmd};
17use crate::types::ids::{Seconds, WindowId};
18use crate::types::snapshot::VisualSnapshot;
19use crate::types::spec::Spec;
20use crate::types::window::{SizePx, WindowCommand, WindowSpec};
21use crate::{App, Handle, Waker};
22
23/// A runtime driven by hand: no event loop, no wall clock, no GPU.
24pub struct HeadlessHost<S: Spec, A: App<Spec = S>> {
25    rt: Runtime<S, A>,
26    handle: Handle<S>,
27    now: Seconds,
28    /// Capabilities reported in every `Created` echo.
29    pub caps: HostCaps,
30    /// Device pixel ratio reported for auto-answered spawned windows.
31    pub dpr: f64,
32    /// The paint recorder of the last `advance` (draw ops are inspectable
33    /// through it; it is reused, so it accumulates — call
34    /// [`RecordingRenderContext`] accessors per test section).
35    pub ctx: RecordingRenderContext,
36    last: TickOutput,
37    command_log: Vec<(WindowId, WindowCommand)>,
38    #[cfg(feature = "automation")]
39    auto: HeadlessAuto,
40    /// Paint target of `advance` instead of `ctx` (the live loop: real text
41    /// metrics, see [`run_headless`]).
42    #[cfg(feature = "automation")]
43    live_ctx: Option<Box<dyn uzor::render::RenderContext>>,
44}
45
46/// Automation bookkeeping of the headless host.
47#[cfg(feature = "automation")]
48#[derive(Default)]
49struct HeadlessAuto {
50    /// The port last served (its input tap sees pushed input).
51    port: Option<crate::automation::AutomationPort>,
52    waits: crate::automation::FrameWaits,
53    /// Last clear colour per window.
54    background: std::collections::HashMap<WindowId, u32>,
55}
56
57impl<S: Spec, A: App<Spec = S>> HeadlessHost<S, A> {
58    /// A host and the app's handle, with a no-op waker (design §9.1).
59    pub fn new(app: A, cfg: RuntimeConfig) -> (Self, Handle<S>) {
60        Self::with_waker(app, cfg, Waker::noop())
61    }
62
63    /// A host whose app handle wakes `waker` on every dispatch (a live
64    /// loop sleeps until then; see [`run_headless`]).
65    pub fn with_waker(app: A, cfg: RuntimeConfig, waker: Waker) -> (Self, Handle<S>) {
66        let (rt, handle) = Runtime::new(app, cfg, waker);
67        let host = Self {
68            rt,
69            handle: handle.clone(),
70            now: Seconds::ZERO,
71            caps: HostCaps {
72                multi_window: true,
73                os_resize_bezel: false,
74                clipboard_async: false,
75            },
76            dpr: 1.0,
77            ctx: RecordingRenderContext::new(),
78            last: TickOutput::default(),
79            command_log: Vec::new(),
80            #[cfg(feature = "automation")]
81            auto: HeadlessAuto::default(),
82            #[cfg(feature = "automation")]
83            live_ctx: None,
84        };
85        (host, handle)
86    }
87
88    /// Open a window and run the ticks that settle its creation (the
89    /// `Spawn` command is auto-answered with a `Created` echo carrying
90    /// `size` and `dpr`). Returns the engine-assigned id.
91    pub fn open_window(&mut self, size: SizePx, dpr: f64) -> WindowId {
92        let n = self.snapshot().windows.len();
93        let key = format!("win-{n}");
94        let mut spec = WindowSpec::new(key, "headless", size);
95        let _ = &mut spec; // spec travels whole; dpr rides the echo.
96        self.handle
97            .dispatch(AppCommand::Window(WindowCmd::Open(spec)))
98            .unwrap_or_else(|e| panic!("headless inbox: {e}"));
99        self.dpr = dpr;
100        self.advance(0.0);
101        self.snapshot()
102            .windows
103            .last()
104            .unwrap_or_else(|| panic!("window did not open"))
105            .id
106    }
107
108    /// Queue one input event for the next tick (hop 1 of §4.4).
109    pub fn input(&mut self, win: WindowId, event: InputEvent) {
110        #[cfg(feature = "automation")]
111        if let Some(port) = &self.auto.port {
112            crate::automation::tap_input(port, &self.rt, win, &event);
113        }
114        self.rt.push_input(InputEnvelope {
115            window: win,
116            t: self.now,
117            event,
118        });
119    }
120
121    /// Move the host clock by `dt` seconds, run one tick (plus one
122    /// settling tick when the tick's host-bound commands needed an echo
123    /// answer), and paint every due frame request. The output of the whole
124    /// advance is kept for [`HeadlessHost::window_commands`].
125    pub fn advance(&mut self, dt: f64) -> &TickOutput {
126        self.now = self.now.after(Seconds(dt));
127        let mut out = self.rt.tick(self.now);
128
129        // Answer the commands only an OS could: spawns get created with
130        // the host's caps, closes get destroyed.
131        let mut echoes = Vec::new();
132        for (win, cmd) in &out.window_commands {
133            match cmd {
134                WindowCommand::Spawn(spec) => echoes.push((
135                    *win,
136                    WindowInput::Created {
137                        size: spec.inner_size,
138                        dpr: self.dpr,
139                        // A known position: expand gutters and drag-out
140                        // need a known outer rect.
141                        position: Some((100, 100)),
142                        caps: self.caps,
143                    },
144                )),
145                WindowCommand::Close => echoes.push((*win, WindowInput::Destroyed)),
146                _ => {}
147            }
148        }
149        if !echoes.is_empty() {
150            for (win, event) in echoes {
151                self.rt.push_input(InputEnvelope {
152                    window: win,
153                    t: self.now,
154                    event: InputEvent::Window(event),
155                });
156            }
157            let more = self.rt.tick(self.now);
158            out.window_commands.extend(more.window_commands);
159            out.frames.extend(more.frames);
160            out.wake = earliest(out.wake, more.wake);
161        }
162
163        let frames = std::mem::take(&mut out.frames);
164        for req in &frames {
165            #[cfg(feature = "automation")]
166            match self.live_ctx.as_deref_mut() {
167                Some(ctx) => self.rt.paint(req, ctx),
168                None => self.rt.paint(req, &mut self.ctx),
169            }
170            #[cfg(not(feature = "automation"))]
171            self.rt.paint(req, &mut self.ctx);
172            #[cfg(feature = "automation")]
173            {
174                self.auto.background.insert(req.window, req.background);
175                self.auto.waits.painted();
176            }
177        }
178        out.frames = frames;
179        self.command_log.extend(out.window_commands.iter().cloned());
180        self.last = out;
181        &self.last
182    }
183
184    /// Paint window `win` once into `ctx` at its viewport size and `dpr`, outside the
185    /// tick (frame dumps, screenshots, goldens). The caller sizes `ctx`
186    /// (viewport × `dpr`) and clears it. Returns the viewport size in logical pixels,
187    /// or `None` for an unknown window.
188    pub fn paint_window(&mut self, win: WindowId, dpr: f64, ctx: &mut dyn uzor::render::RenderContext) -> Option<(f64, f64)> {
189        let snap = self.snapshot();
190        let vp = snap.window(win)?.geometry.viewport;
191        drop(snap);
192        let size = SizePx::new(vp.width.round().max(1.0) as u32, vp.height.round().max(1.0) as u32);
193        let req = crate::FrameRequest {
194            window: win,
195            size,
196            dpr,
197            background: 0,
198            regions: Default::default(),
199            invalidations: Default::default(),
200        };
201        self.rt.paint(&req, ctx);
202        Some((vp.width, vp.height))
203    }
204
205    /// Answer every job queued on `port` (feature `automation`): input is
206    /// fed and followed by one `advance(dt)` before its reply; screenshots
207    /// are offscreen (there is no window to read back). While someone waits
208    /// for a painted frame ([`crate::automation::AutoCmd::Frame`]) the
209    /// clock moves by `dt` per call.
210    #[cfg(feature = "automation")]
211    pub fn serve_automation(&mut self, port: &crate::automation::AutomationPort, dt: f64) {
212        let jobs = self.serve_jobs(port, &mut |_| dt);
213        if jobs == 0 && self.auto.waits.anyone_waiting() {
214            self.advance(dt);
215        }
216    }
217
218    /// Answer queued jobs; `dt_of` gives the clock step for each input's
219    /// advance. Returns the number of jobs.
220    #[cfg(feature = "automation")]
221    fn serve_jobs(&mut self, port: &crate::automation::AutomationPort, dt_of: &mut dyn FnMut(&Self) -> f64) -> usize {
222        use crate::automation::{answer_plain, resolve_window, AutoCmd, AutoError, AutoReply, ShotSource};
223        if self.auto.port.is_none() {
224            self.auto.port = Some(port.clone());
225        }
226        let jobs = port.drain();
227        let n = jobs.len();
228        for (cmd, reply) in jobs {
229            let Some((cmd, reply)) = self.auto.waits.take(cmd, reply) else { continue };
230            let dpr = self.dpr;
231            let bgs = self.auto.background.clone();
232            let bg_of = move |w: WindowId| bgs.get(&w).copied().unwrap_or(0xffffffff);
233            let answer = match &cmd {
234                AutoCmd::Input { win, events } => match resolve_window(&self.rt, *win) {
235                    Some(w) => {
236                        for ev in events.clone() {
237                            self.input(w, ev);
238                        }
239                        let dt = dt_of(self);
240                        self.advance(dt);
241                        AutoReply::InputDone { window: w, frame: self.auto.waits.frames }
242                    }
243                    None => AutoReply::Error(AutoError::NoWindow),
244                },
245                AutoCmd::Screenshot { win, .. } => {
246                    let c = AutoCmd::Screenshot { win: *win, source: ShotSource::Offscreen };
247                    answer_plain(&mut self.rt, &c, &|_| dpr, &bg_of).unwrap_or(AutoReply::Error(AutoError::Unsupported("screenshot")))
248                }
249                other => answer_plain(&mut self.rt, other, &|_| dpr, &bg_of).unwrap_or(AutoReply::Error(AutoError::Unsupported("command"))),
250            };
251            let _ = reply.send(answer);
252        }
253        n
254    }
255
256    /// The wake hint of the last `advance`.
257    pub fn last_wake(&self) -> crate::types::frame::Wake {
258        self.last.wake
259    }
260
261    /// The last published snapshot.
262    pub fn snapshot(&self) -> Arc<VisualSnapshot<S>> {
263        self.rt.snapshot()
264    }
265
266    /// The host-bound window commands of the last `advance`.
267    pub fn window_commands(&self) -> &[(WindowId, WindowCommand)] {
268        &self.last.window_commands
269    }
270
271    /// Every host-bound window command since construction, in order (the
272    /// executor's own log — assertions over a whole script read this, not
273    /// the last tick's slice).
274    pub fn command_log(&self) -> &[(WindowId, WindowCommand)] {
275        &self.command_log
276    }
277
278    /// The runtime (tests drive app-level tools through it).
279    pub fn runtime(&self) -> &Runtime<S, A> {
280        &self.rt
281    }
282
283    /// The runtime, mutably.
284    pub fn runtime_mut(&mut self) -> &mut Runtime<S, A> {
285        &mut self.rt
286    }
287}
288
289/// The sooner of two wake hints (`Immediate` < `At(t)` < `Idle`).
290fn earliest(
291    a: crate::types::frame::Wake,
292    b: crate::types::frame::Wake,
293) -> crate::types::frame::Wake {
294    use crate::types::frame::Wake;
295    match (a, b) {
296        (Wake::Immediate, _) | (_, Wake::Immediate) => Wake::Immediate,
297        (Wake::At(x), Wake::At(y)) => Wake::At(if x.get() <= y.get() { x } else { y }),
298        (Wake::At(x), Wake::Idle) | (Wake::Idle, Wake::At(x)) => Wake::At(x),
299        (Wake::Idle, Wake::Idle) => Wake::Idle,
300    }
301}
302
303/// Run `app` live with no window and no display: a real-time loop on a
304/// [`HeadlessHost`] that serves `port` (feature `automation`, native
305/// only). Windows the app opens are auto-created at their spec size and
306/// `dpr`; frames paint into a recorder that is cleared each turn;
307/// screenshots are offscreen (tiny-skia). Returns when the app exits or
308/// its last window closes.
309#[cfg(all(feature = "automation", not(target_arch = "wasm32")))]
310pub fn run_headless<S: Spec, A: App<Spec = S>>(
311    app: A,
312    cfg: RuntimeConfig,
313    dpr: f64,
314    port: crate::automation::AutomationPort,
315) {
316    use crate::types::frame::Wake;
317    use std::sync::{Condvar, Mutex};
318    use std::time::{Duration, Instant};
319
320    #[derive(Default)]
321    struct Signal {
322        woken: Mutex<bool>,
323        cv: Condvar,
324    }
325    impl Signal {
326        fn wake(&self) {
327            *self.woken.lock().unwrap_or_else(|p| p.into_inner()) = true;
328            self.cv.notify_all();
329        }
330        /// Sleep up to `max` unless woken; true when woken.
331        fn wait(&self, max: Option<Duration>) -> bool {
332            let mut w = self.woken.lock().unwrap_or_else(|p| p.into_inner());
333            if !*w {
334                w = match max {
335                    Some(d) => self.cv.wait_timeout(w, d).unwrap_or_else(|p| p.into_inner()).0,
336                    None => self.cv.wait(w).unwrap_or_else(|p| p.into_inner()),
337                };
338            }
339            std::mem::replace(&mut *w, false)
340        }
341    }
342
343    // A paced frame: animations tick at most this often.
344    const FRAME: f64 = 1.0 / 60.0;
345    let sig = Arc::new(Signal::default());
346    let s1 = Arc::clone(&sig);
347    let (mut host, _handle) = HeadlessHost::with_waker(app, cfg, Waker::new(move || s1.wake()));
348    host.dpr = if dpr > 0.0 { dpr } else { 1.0 };
349    // Frames paint into a 1x1 tiny-skia context: drawing is clipped away,
350    // but text measures with the real fonts, exactly as in the offscreen
351    // screenshots (the recorder's zero-wide text would leave layouts that
352    // apps cache, such as wrapped messages, collapsed).
353    host.live_ctx = Some(Box::new(uzor_render_tiny_skia::TinySkiaCpuRenderContext::new(1, 1, host.dpr)));
354    let s2 = Arc::clone(&sig);
355    port.set_waker(move || s2.wake());
356    let start = Instant::now();
357    let clock = move || start.elapsed().as_secs_f64();
358
359    host.advance(0.0);
360    host.ctx.ops.clear();
361    let mut had_window = !host.snapshot().windows.is_empty();
362    let mut last_tick = clock();
363    let mut due_now = true;
364    let mut want_more = false;
365    loop {
366        let now = clock();
367        let jobs = host.serve_jobs(&port, &mut |h: &HeadlessHost<S, A>| (now - h.now.get()).max(0.0));
368        if jobs > 0 {
369            last_tick = now;
370        }
371        let wake = host.last_wake();
372        let paint_more = std::mem::take(&mut want_more) || host.rt.take_paint_wants_tick();
373        let due = due_now
374            || paint_more
375            || match wake {
376                Wake::Immediate => now - last_tick >= FRAME,
377                Wake::At(t) => t.get() <= now,
378                Wake::Idle => false,
379            };
380        if due {
381            let dt = (now - host.now.get()).max(0.0);
382            host.advance(dt);
383            host.ctx.ops.clear();
384            last_tick = now;
385        }
386        due_now = false;
387        let windows = host.snapshot().windows.len();
388        had_window |= windows > 0;
389        if host.rt.should_exit() || (had_window && windows == 0) {
390            return;
391        }
392        let now = clock();
393        want_more = host.rt.take_paint_wants_tick();
394        let sleep = match host.last_wake() {
395            _ if want_more => Some((last_tick + FRAME - now).max(0.0)),
396            Wake::Immediate => Some((last_tick + FRAME - now).max(0.0)),
397            Wake::At(t) => Some((t.get() - now).max(0.0)),
398            Wake::Idle => None,
399        };
400        if sleep.is_some_and(|d| d <= 0.0) {
401            continue;
402        }
403        if sig.wait(sleep.map(Duration::from_secs_f64)) {
404            due_now = true;
405        }
406    }
407}