use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::task::{self, Context, Wake, Waker};
use std::time::Duration;
use web_time::Instant;
use crate::widget::State;
pub(crate) type Poll = Box<dyn FnMut(&mut Context, &mut State) -> (bool, bool)>;
pub(crate) struct Task {
pub deps: u64,
pub poll: Option<Poll>,
pub polled: bool,
}
pub(crate) type Tasks = HashMap<u64, Task>;
pub(crate) fn poll(
tasks: &mut Tasks,
states: &mut HashMap<u64, State>,
waker: &Waker,
only_new: bool,
) -> bool {
let mut cx = Context::from_waker(waker);
let mut changed = false;
for (id, t) in tasks.iter_mut() {
if only_new && t.polled {
continue;
}
t.polled = true;
if let Some(p) = &mut t.poll {
let (c, done) = p(&mut cx, states.entry(*id).or_default());
changed |= c;
if done {
t.poll = None;
}
}
}
changed
}
pub(crate) struct LoopWaker {
wake: Box<dyn Fn() + Send + Sync>,
pending: AtomicBool,
}
impl LoopWaker {
pub fn new(wake: impl Fn() + Send + Sync + 'static) -> Arc<Self> {
Arc::new(LoopWaker {
wake: Box::new(wake),
pending: AtomicBool::new(false),
})
}
pub fn clear(&self) {
self.pending.store(false, Ordering::Release);
}
pub fn pending(&self) -> bool {
self.pending.load(Ordering::Acquire)
}
}
impl Wake for LoopWaker {
fn wake(self: Arc<Self>) {
self.wake_by_ref();
}
fn wake_by_ref(self: &Arc<Self>) {
if !self.pending.swap(true, Ordering::AcqRel) {
(self.wake)();
}
}
}
#[derive(Clone, Default)]
pub struct Notifier(Arc<Notify>);
#[derive(Default)]
pub(crate) struct Notify {
version: AtomicU64,
waker: Mutex<Option<Waker>>,
}
impl Notifier {
pub fn new() -> Self {
Self::default()
}
pub fn notify(&self) {
self.0.version.fetch_add(1, Ordering::AcqRel);
if let Some(w) = &*self.0.waker.lock().unwrap() {
w.wake_by_ref();
}
}
pub(crate) fn poll_version(&self, cx: &Context) -> u64 {
let mut slot = self.0.waker.lock().unwrap();
if !slot.as_ref().is_some_and(|w| w.will_wake(cx.waker())) {
*slot = Some(cx.waker().clone());
}
drop(slot);
self.0.version.load(Ordering::Acquire)
}
pub(crate) fn id(&self) -> usize {
Arc::as_ptr(&self.0) as usize
}
}
thread_local! {
static TIMERS: RefCell<Vec<(Instant, Waker)>> = const { RefCell::new(Vec::new()) };
static CLOCK: Cell<Option<Instant>> = const { Cell::new(None) };
}
pub(crate) fn now() -> Instant {
CLOCK.get().unwrap_or_else(Instant::now)
}
pub(crate) fn set_clock(t: Option<Instant>) {
CLOCK.set(t);
}
pub fn sleep(d: Duration) -> Sleep {
Sleep(now() + d)
}
pub struct Sleep(Instant);
impl Future for Sleep {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> task::Poll<()> {
if now() >= self.0 {
return task::Poll::Ready(());
}
TIMERS.with_borrow_mut(|t| {
if !t
.iter()
.any(|(d, w)| *d == self.0 && w.will_wake(cx.waker()))
{
t.push((self.0, cx.waker().clone()));
}
});
task::Poll::Pending
}
}
pub(crate) fn fire_timers(now: Instant) -> Option<Instant> {
TIMERS.with_borrow_mut(|t| {
t.retain(|(d, w)| {
if *d <= now {
w.wake_by_ref();
}
*d > now
});
t.iter().map(|(d, _)| *d).min()
})
}