use std::cell::Cell;
use std::sync::atomic::{AtomicBool, Ordering};
use std::task::Poll;
use std::time::{Duration, Instant};
use futures::task::AtomicWaker;
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) };
static REPORTED: Cell<bool> = const { Cell::new(false) };
static NEXT_WORK: Cell<Option<Duration>> = const { Cell::new(None) };
}
pub fn note_frame() {
LAST_FRAME.with(|c| c.set(Some(Instant::now())));
let was_active = ACTIVE.with(|a| a.replace(false));
if was_active && REPORTED.with(|r| r.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,
}
}
static POKED: AtomicBool = AtomicBool::new(false);
static POKE: AtomicWaker = AtomicWaker::new();
pub fn poke() {
POKED.store(true, Ordering::Release);
POKE.wake();
}
async fn poked() {
flagged(&POKED, &POKE).await
}
static PROMPTED: AtomicBool = AtomicBool::new(false);
static PROMPT: AtomicWaker = AtomicWaker::new();
pub fn prompt() {
PROMPTED.store(true, Ordering::Release);
PROMPT.wake();
}
async fn flagged(flag: &AtomicBool, waker: &AtomicWaker) {
std::future::poll_fn(|task| {
if flag.swap(false, Ordering::AcqRel) {
return Poll::Ready(());
}
waker.register(task.waker());
if flag.swap(false, Ordering::AcqRel) {
Poll::Ready(())
} else {
Poll::Pending
}
})
.await
}
pub fn start(cx: &mut App) {
cx.spawn(async move |cx| loop {
flagged(&PROMPTED, &PROMPT).await;
let Some(handle) = crate::MAIN_WINDOW.with(|w| w.get()) else {
continue;
};
let _ = handle.update(cx, |_, window, cx| prompt_wave(window, cx));
})
.detach();
cx.spawn(async move |cx| loop {
if !cfg!(target_os = "windows") {
cx.background_executor().timer(TICK).await;
if !due(LAST_FRAME.with(|c| c.get()), Instant::now()) {
continue;
}
} else {
let wait = if ACTIVE.with(Cell::get) {
NEXT_WORK.with(Cell::get).map(|d| d.max(TICK))
} else if crate::window::page_hidden() {
Some(TICK)
} else {
None
};
let poke = std::pin::pin!(poked());
match wait {
Some(wait) => {
let timer = std::pin::pin!(cx.background_executor().timer(wait));
futures::future::select(poke, timer).await;
}
None => poke.await,
}
if crate::window::page_hidden() {
if !due(LAST_FRAME.with(|c| c.get()), Instant::now()) {
continue;
}
} else {
let asked = Instant::now();
cx.background_executor().timer(STALL).await;
if LAST_FRAME.with(Cell::get).is_some_and(|t| t >= asked) {
continue;
}
}
}
let Some(handle) = crate::MAIN_WINDOW.with(|w| w.get()) else {
continue;
};
let _ = handle.update(cx, |_, window, cx| wave(window, cx));
})
.detach();
}
fn prompt_wave(window: &mut gpui::Window, cx: &mut App) {
if !pumped_once()
|| sk_runtime::with_app(|_| ()).is_some()
|| sk_runtime::bridge::poisoned()
|| !crate::embed::queued()
{
return;
}
crate::js_wave(window, cx, crate::Wave::Background);
crate::after_wave(window, cx);
}
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;
}
ACTIVE.with(|a| a.set(true));
if crate::window::page_hidden() && !REPORTED.with(|r| r.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);
let now = Instant::now();
let js = sk_runtime::JsRuntime::try_with(|rt| {
#[cfg(feature = "audio")]
if sk_runtime::redjs::webapi::audio::busy(rt.raw()) {
return Some(now);
}
let at = sk_runtime::redjs::web::next_work_ms(rt.raw())?;
let ms = at - sk_runtime::redjs::web::now_ms();
Some(now + Duration::from_secs_f64(ms.max(0.0) / 1000.0))
})
.flatten();
let host = sk_runtime::frames::take_wake_at();
let next = js.into_iter().chain(host).min();
NEXT_WORK.with(|n| n.set(next.map(|at| at.saturating_duration_since(now))));
}