use std::cell::Cell;
use std::time::{Duration, Instant};
use gpui::App;
pub const TICK: Duration = Duration::from_millis(100);
pub const STALL: Duration = Duration::from_millis(250);
thread_local! {
static LAST_FRAME: Cell<Option<Instant>> = const { Cell::new(None) };
static WAVES: Cell<u64> = const { Cell::new(0) };
static ACTIVE: Cell<bool> = const { Cell::new(false) };
}
pub fn note_frame() {
LAST_FRAME.with(|c| c.set(Some(Instant::now())));
if ACTIVE.with(|a| a.replace(false)) {
let n = WAVES.with(|w| w.get());
sk_tree::log::record(
"window",
format!("[window] frames resumed — the background tick stands down ({n} background waves so far)"),
);
}
}
pub fn pumped_once() -> bool {
LAST_FRAME.with(|c| c.get().is_some())
}
pub fn due(last_frame: Option<Instant>, now: Instant) -> bool {
match last_frame {
Some(t) => now.saturating_duration_since(t) >= STALL,
None => false,
}
}
pub fn start(cx: &mut App) {
cx.spawn(async move |cx| loop {
cx.background_executor().timer(TICK).await;
if !due(LAST_FRAME.with(|c| c.get()), Instant::now()) {
continue;
}
let Some(handle) = crate::MAIN_WINDOW.with(|w| w.get()) else {
continue;
};
let _ = handle.update(cx, |_, window, cx| wave(window, cx));
})
.detach();
}
fn wave(window: &mut gpui::Window, cx: &mut App) {
if sk_runtime::with_app(|_| ()).is_some() {
return;
}
if sk_runtime::bridge::poisoned() {
crate::crash_window::on_poisoned(cx);
return;
}
if !ACTIVE.with(|a| a.replace(true)) {
sk_tree::log::record(
"window",
"[window] no frames (the window is minimised or hidden) — timers, sockets and devtools now run \
on a background tick every 100 ms; requestAnimationFrame waits for the next drawn frame",
);
}
WAVES.with(|w| w.set(w.get() + 1));
crate::drain_log_tee();
crate::js_wave(window, cx, crate::Wave::Background);
crate::after_wave(window, cx);
}