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}
39
40impl<S: Spec, A: App<Spec = S>> HeadlessHost<S, A> {
41    /// A host and the app's handle, with a no-op waker (design §9.1).
42    pub fn new(app: A, cfg: RuntimeConfig) -> (Self, Handle<S>) {
43        let (rt, handle) = Runtime::new(app, cfg, Waker::noop());
44        let host = Self {
45            rt,
46            handle: handle.clone(),
47            now: Seconds::ZERO,
48            caps: HostCaps {
49                multi_window: true,
50                os_resize_bezel: false,
51                clipboard_async: false,
52            },
53            dpr: 1.0,
54            ctx: RecordingRenderContext::new(),
55            last: TickOutput::default(),
56            command_log: Vec::new(),
57        };
58        (host, handle)
59    }
60
61    /// Open a window and run the ticks that settle its creation (the
62    /// `Spawn` command is auto-answered with a `Created` echo carrying
63    /// `size` and `dpr`). Returns the engine-assigned id.
64    pub fn open_window(&mut self, size: SizePx, dpr: f64) -> WindowId {
65        let n = self.snapshot().windows.len();
66        let key = format!("win-{n}");
67        let mut spec = WindowSpec::new(key, "headless", size);
68        let _ = &mut spec; // spec travels whole; dpr rides the echo.
69        self.handle
70            .dispatch(AppCommand::Window(WindowCmd::Open(spec)))
71            .unwrap_or_else(|e| panic!("headless inbox: {e}"));
72        self.dpr = dpr;
73        self.advance(0.0);
74        self.snapshot()
75            .windows
76            .last()
77            .unwrap_or_else(|| panic!("window did not open"))
78            .id
79    }
80
81    /// Queue one input event for the next tick (hop 1 of §4.4).
82    pub fn input(&mut self, win: WindowId, event: InputEvent) {
83        self.rt.push_input(InputEnvelope {
84            window: win,
85            t: self.now,
86            event,
87        });
88    }
89
90    /// Move the host clock by `dt` seconds, run one tick (plus one
91    /// settling tick when the tick's host-bound commands needed an echo
92    /// answer), and paint every due frame request. The output of the whole
93    /// advance is kept for [`HeadlessHost::window_commands`].
94    pub fn advance(&mut self, dt: f64) -> &TickOutput {
95        self.now = self.now.after(Seconds(dt));
96        let mut out = self.rt.tick(self.now);
97
98        // Answer the commands only an OS could: spawns get created with
99        // the host's caps, closes get destroyed.
100        let mut echoes = Vec::new();
101        for (win, cmd) in &out.window_commands {
102            match cmd {
103                WindowCommand::Spawn(spec) => echoes.push((
104                    *win,
105                    WindowInput::Created {
106                        size: spec.inner_size,
107                        dpr: self.dpr,
108                        // A known position: expand gutters and drag-out
109                        // need a known outer rect.
110                        position: Some((100, 100)),
111                        caps: self.caps,
112                    },
113                )),
114                WindowCommand::Close => echoes.push((*win, WindowInput::Destroyed)),
115                _ => {}
116            }
117        }
118        if !echoes.is_empty() {
119            for (win, event) in echoes {
120                self.rt.push_input(InputEnvelope {
121                    window: win,
122                    t: self.now,
123                    event: InputEvent::Window(event),
124                });
125            }
126            let more = self.rt.tick(self.now);
127            out.window_commands.extend(more.window_commands);
128            out.frames.extend(more.frames);
129            out.wake = earliest(out.wake, more.wake);
130        }
131
132        let frames = std::mem::take(&mut out.frames);
133        for req in &frames {
134            self.rt.paint(req, &mut self.ctx);
135        }
136        out.frames = frames;
137        self.command_log.extend(out.window_commands.iter().cloned());
138        self.last = out;
139        &self.last
140    }
141
142    /// The last published snapshot.
143    pub fn snapshot(&self) -> Arc<VisualSnapshot<S>> {
144        self.rt.snapshot()
145    }
146
147    /// The host-bound window commands of the last `advance`.
148    pub fn window_commands(&self) -> &[(WindowId, WindowCommand)] {
149        &self.last.window_commands
150    }
151
152    /// Every host-bound window command since construction, in order (the
153    /// executor's own log — assertions over a whole script read this, not
154    /// the last tick's slice).
155    pub fn command_log(&self) -> &[(WindowId, WindowCommand)] {
156        &self.command_log
157    }
158
159    /// The runtime (tests drive app-level tools through it).
160    pub fn runtime(&self) -> &Runtime<S, A> {
161        &self.rt
162    }
163
164    /// The runtime, mutably.
165    pub fn runtime_mut(&mut self) -> &mut Runtime<S, A> {
166        &mut self.rt
167    }
168}
169
170/// The sooner of two wake hints (`Immediate` < `At(t)` < `Idle`).
171fn earliest(
172    a: crate::types::frame::Wake,
173    b: crate::types::frame::Wake,
174) -> crate::types::frame::Wake {
175    use crate::types::frame::Wake;
176    match (a, b) {
177        (Wake::Immediate, _) | (_, Wake::Immediate) => Wake::Immediate,
178        (Wake::At(x), Wake::At(y)) => Wake::At(if x.get() <= y.get() { x } else { y }),
179        (Wake::At(x), Wake::Idle) | (Wake::Idle, Wake::At(x)) => Wake::At(x),
180        (Wake::Idle, Wake::Idle) => Wake::Idle,
181    }
182}