use std::{
cell::{Cell, RefCell},
rc::{Rc, Weak},
time::Duration,
};
use cranpose_app_shell::{AppShell, FrameSchedule};
use cranpose_render_common::Renderer;
use cranpose_render_wgpu::WgpuRenderer;
use wasm_bindgen::{JsCast, closure::Closure};
use web_time::Instant;
const TIMEOUT_IDLE_BUDGET: Duration = Duration::from_millis(12);
const TIMEOUT_BUILD_POLL_MS: i32 = 50;
pub(crate) struct IdleWork {
app: Weak<RefCell<AppShell<WgpuRenderer>>>,
frame_pending: Rc<Cell<bool>>,
stands_still: Cell<bool>,
queued: Cell<bool>,
}
impl IdleWork {
pub(crate) fn new(
app: &Rc<RefCell<AppShell<WgpuRenderer>>>,
frame_pending: &Rc<Cell<bool>>,
) -> Rc<Self> {
Rc::new(Self {
app: Rc::downgrade(app),
frame_pending: Rc::clone(frame_pending),
stands_still: Cell::new(false),
queued: Cell::new(false),
})
}
pub(crate) fn queue_after_frame(
self: &Rc<Self>,
frame_started: Instant,
schedule: FrameSchedule,
) {
self.stands_still.set(schedule.is_idle());
if self.queued.get() || !(self.stands_still.get() || self.has_prefetch_work()) {
return;
}
let Some(window) = super::frame_host::window() else {
return;
};
self.queued.set(true);
if !self.ask_idle_period(&window) {
self.ask_timeout(&window, 0, Some(frame_started));
}
}
fn ask_idle_period(self: &Rc<Self>, window: &web_sys::Window) -> bool {
let this = Rc::clone(self);
let idle = Closure::once_into_js(move |deadline: web_sys::IdleDeadline| {
let remaining = Duration::from_secs_f64(deadline.time_remaining().max(0.0) / 1000.0);
let builds_wait = this.run(Instant::now() + remaining);
if (builds_wait || this.has_prefetch_work())
&& !this.queued.replace(true)
&& let Some(window) = super::frame_host::window()
&& !this.ask_idle_period(&window)
{
this.queued.set(false);
}
});
window.request_idle_callback(idle.unchecked_ref()).is_ok()
}
fn ask_timeout(
self: &Rc<Self>,
window: &web_sys::Window,
delay_ms: i32,
frame_started: Option<Instant>,
) {
let this = Rc::clone(self);
let timeout = Closure::once_into_js(move || {
let started = frame_started.unwrap_or_else(Instant::now);
if this.run(started + TIMEOUT_IDLE_BUDGET)
&& !this.queued.replace(true)
&& let Some(window) = super::frame_host::window()
{
this.ask_timeout(&window, TIMEOUT_BUILD_POLL_MS, None);
}
});
if window
.set_timeout_with_callback_and_timeout_and_arguments_0(
timeout.unchecked_ref(),
delay_ms,
)
.is_err()
{
self.queued.set(false);
}
}
fn run(&self, deadline: Instant) -> bool {
self.queued.set(false);
let Some(app) = self.app.upgrade() else {
return false;
};
let Ok(mut app) = app.try_borrow_mut() else {
return false;
};
app.run_idle_prefetch(Some(deadline), |_| false);
let builds_wait = self.stands_still.get()
&& !self.frame_pending.get()
&& app.renderer().build_while_idle();
self.stands_still.set(builds_wait);
builds_wait
}
fn has_prefetch_work(&self) -> bool {
self.app.upgrade().is_some_and(|app| {
app.try_borrow()
.is_ok_and(|app| app.has_idle_prefetch_work())
})
}
}