1use 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
23pub struct HeadlessHost<S: Spec, A: App<Spec = S>> {
25 rt: Runtime<S, A>,
26 handle: Handle<S>,
27 now: Seconds,
28 pub caps: HostCaps,
30 pub dpr: f64,
32 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 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 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; 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 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 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 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 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 pub fn paint_window(&mut self, win: WindowId, dpr: f64, ctx: &mut dyn uzor::render::RenderContext) -> Option<(f64, f64)> {
147 let snap = self.snapshot();
148 let vp = snap.window(win)?.geometry.viewport;
149 drop(snap);
150 let size = SizePx::new(vp.width.round().max(1.0) as u32, vp.height.round().max(1.0) as u32);
151 let req = crate::FrameRequest {
152 window: win,
153 size,
154 dpr,
155 background: 0,
156 regions: Default::default(),
157 invalidations: Default::default(),
158 };
159 self.rt.paint(&req, ctx);
160 Some((vp.width, vp.height))
161 }
162
163 #[cfg(feature = "automation")]
167 pub fn serve_automation(&mut self, port: &crate::automation::AutomationPort, dt: f64) {
168 use crate::automation::{answer_plain, resolve_window, AutoCmd, AutoReply, ShotSource};
169 for (cmd, reply) in port.drain() {
170 let dpr = self.dpr;
171 let answer = match &cmd {
172 AutoCmd::Input { win, events } => match resolve_window(&self.rt, *win) {
173 Some(w) => {
174 for ev in events.clone() {
175 self.input(w, ev);
176 }
177 self.advance(dt);
178 AutoReply::InputDone { window: w, frame: (self.now.get() * 1000.0).round() as u64 }
179 }
180 None => AutoReply::Error(crate::automation::AutoError::NoWindow),
181 },
182 AutoCmd::Screenshot { win, .. } => {
183 let c = AutoCmd::Screenshot { win: *win, source: ShotSource::Offscreen };
184 answer_plain(&mut self.rt, &c, &|_| dpr, &|_| 0xffffffff).unwrap_or(AutoReply::Error(
185 crate::automation::AutoError::Unsupported("screenshot"),
186 ))
187 }
188 other => answer_plain(&mut self.rt, other, &|_| dpr, &|_| 0xffffffff)
189 .unwrap_or(AutoReply::Error(crate::automation::AutoError::Unsupported("command"))),
190 };
191 let _ = reply.send(answer);
192 }
193 }
194
195 pub fn snapshot(&self) -> Arc<VisualSnapshot<S>> {
197 self.rt.snapshot()
198 }
199
200 pub fn window_commands(&self) -> &[(WindowId, WindowCommand)] {
202 &self.last.window_commands
203 }
204
205 pub fn command_log(&self) -> &[(WindowId, WindowCommand)] {
209 &self.command_log
210 }
211
212 pub fn runtime(&self) -> &Runtime<S, A> {
214 &self.rt
215 }
216
217 pub fn runtime_mut(&mut self) -> &mut Runtime<S, A> {
219 &mut self.rt
220 }
221}
222
223fn earliest(
225 a: crate::types::frame::Wake,
226 b: crate::types::frame::Wake,
227) -> crate::types::frame::Wake {
228 use crate::types::frame::Wake;
229 match (a, b) {
230 (Wake::Immediate, _) | (_, Wake::Immediate) => Wake::Immediate,
231 (Wake::At(x), Wake::At(y)) => Wake::At(if x.get() <= y.get() { x } else { y }),
232 (Wake::At(x), Wake::Idle) | (Wake::Idle, Wake::At(x)) => Wake::At(x),
233 (Wake::Idle, Wake::Idle) => Wake::Idle,
234 }
235}