use std::sync::Arc;
use uzor::testing::RecordingRenderContext;
use crate::runtime::{Runtime, RuntimeConfig, TickOutput};
use crate::types::bus::{HostCaps, InputEnvelope, InputEvent, WindowInput};
use crate::types::command::{AppCommand, WindowCmd};
use crate::types::ids::{Seconds, WindowId};
use crate::types::snapshot::VisualSnapshot;
use crate::types::spec::Spec;
use crate::types::window::{SizePx, WindowCommand, WindowSpec};
use crate::{App, Handle, Waker};
pub struct HeadlessHost<S: Spec, A: App<Spec = S>> {
rt: Runtime<S, A>,
handle: Handle<S>,
now: Seconds,
pub caps: HostCaps,
pub dpr: f64,
pub ctx: RecordingRenderContext,
last: TickOutput,
command_log: Vec<(WindowId, WindowCommand)>,
}
impl<S: Spec, A: App<Spec = S>> HeadlessHost<S, A> {
pub fn new(app: A, cfg: RuntimeConfig) -> (Self, Handle<S>) {
let (rt, handle) = Runtime::new(app, cfg, Waker::noop());
let host = Self {
rt,
handle: handle.clone(),
now: Seconds::ZERO,
caps: HostCaps {
multi_window: true,
os_resize_bezel: false,
clipboard_async: false,
},
dpr: 1.0,
ctx: RecordingRenderContext::new(),
last: TickOutput::default(),
command_log: Vec::new(),
};
(host, handle)
}
pub fn open_window(&mut self, size: SizePx, dpr: f64) -> WindowId {
let n = self.snapshot().windows.len();
let key = format!("win-{n}");
let mut spec = WindowSpec::new(key, "headless", size);
let _ = &mut spec; self.handle
.dispatch(AppCommand::Window(WindowCmd::Open(spec)))
.unwrap_or_else(|e| panic!("headless inbox: {e}"));
self.dpr = dpr;
self.advance(0.0);
self.snapshot()
.windows
.last()
.unwrap_or_else(|| panic!("window did not open"))
.id
}
pub fn input(&mut self, win: WindowId, event: InputEvent) {
self.rt.push_input(InputEnvelope {
window: win,
t: self.now,
event,
});
}
pub fn advance(&mut self, dt: f64) -> &TickOutput {
self.now = self.now.after(Seconds(dt));
let mut out = self.rt.tick(self.now);
let mut echoes = Vec::new();
for (win, cmd) in &out.window_commands {
match cmd {
WindowCommand::Spawn(spec) => echoes.push((
*win,
WindowInput::Created {
size: spec.inner_size,
dpr: self.dpr,
position: Some((100, 100)),
caps: self.caps,
},
)),
WindowCommand::Close => echoes.push((*win, WindowInput::Destroyed)),
_ => {}
}
}
if !echoes.is_empty() {
for (win, event) in echoes {
self.rt.push_input(InputEnvelope {
window: win,
t: self.now,
event: InputEvent::Window(event),
});
}
let more = self.rt.tick(self.now);
out.window_commands.extend(more.window_commands);
out.frames.extend(more.frames);
out.wake = earliest(out.wake, more.wake);
}
let frames = std::mem::take(&mut out.frames);
for req in &frames {
self.rt.paint(req, &mut self.ctx);
}
out.frames = frames;
self.command_log.extend(out.window_commands.iter().cloned());
self.last = out;
&self.last
}
pub fn paint_window(&mut self, win: WindowId, dpr: f64, ctx: &mut dyn uzor::render::RenderContext) -> Option<(f64, f64)> {
let snap = self.snapshot();
let vp = snap.window(win)?.geometry.viewport;
drop(snap);
let size = SizePx::new(vp.width.round().max(1.0) as u32, vp.height.round().max(1.0) as u32);
let req = crate::FrameRequest {
window: win,
size,
dpr,
background: 0,
regions: Default::default(),
invalidations: Default::default(),
};
self.rt.paint(&req, ctx);
Some((vp.width, vp.height))
}
#[cfg(feature = "automation")]
pub fn serve_automation(&mut self, port: &crate::automation::AutomationPort, dt: f64) {
use crate::automation::{answer_plain, resolve_window, AutoCmd, AutoReply, ShotSource};
for (cmd, reply) in port.drain() {
let dpr = self.dpr;
let answer = match &cmd {
AutoCmd::Input { win, events } => match resolve_window(&self.rt, *win) {
Some(w) => {
for ev in events.clone() {
self.input(w, ev);
}
self.advance(dt);
AutoReply::InputDone { window: w, frame: (self.now.get() * 1000.0).round() as u64 }
}
None => AutoReply::Error(crate::automation::AutoError::NoWindow),
},
AutoCmd::Screenshot { win, .. } => {
let c = AutoCmd::Screenshot { win: *win, source: ShotSource::Offscreen };
answer_plain(&mut self.rt, &c, &|_| dpr, &|_| 0xffffffff).unwrap_or(AutoReply::Error(
crate::automation::AutoError::Unsupported("screenshot"),
))
}
other => answer_plain(&mut self.rt, other, &|_| dpr, &|_| 0xffffffff)
.unwrap_or(AutoReply::Error(crate::automation::AutoError::Unsupported("command"))),
};
let _ = reply.send(answer);
}
}
pub fn snapshot(&self) -> Arc<VisualSnapshot<S>> {
self.rt.snapshot()
}
pub fn window_commands(&self) -> &[(WindowId, WindowCommand)] {
&self.last.window_commands
}
pub fn command_log(&self) -> &[(WindowId, WindowCommand)] {
&self.command_log
}
pub fn runtime(&self) -> &Runtime<S, A> {
&self.rt
}
pub fn runtime_mut(&mut self) -> &mut Runtime<S, A> {
&mut self.rt
}
}
fn earliest(
a: crate::types::frame::Wake,
b: crate::types::frame::Wake,
) -> crate::types::frame::Wake {
use crate::types::frame::Wake;
match (a, b) {
(Wake::Immediate, _) | (_, Wake::Immediate) => Wake::Immediate,
(Wake::At(x), Wake::At(y)) => Wake::At(if x.get() <= y.get() { x } else { y }),
(Wake::At(x), Wake::Idle) | (Wake::Idle, Wake::At(x)) => Wake::At(x),
(Wake::Idle, Wake::Idle) => Wake::Idle,
}
}