use std::{
cell::{Cell, RefCell},
collections::VecDeque,
rc::{Rc, Weak},
};
use crate::{App, AppCell, AppRefMut, ForegroundExecutor};
pub(crate) struct PowerNotifications {
executor: ForegroundExecutor,
pending: RefCell<VecDeque<fn(&mut App)>>,
retry_scheduled: Cell<bool>,
}
impl PowerNotifications {
pub(crate) fn new(executor: ForegroundExecutor) -> Rc<Self> {
Rc::new(Self {
executor,
pending: RefCell::default(),
retry_scheduled: Cell::new(false),
})
}
pub(crate) fn borrow_for_sleep<'a>(
this: &Rc<Self>,
app: &'a Rc<AppCell>,
) -> Option<AppRefMut<'a>> {
Self::borrow_for(this, app, |cx| {
cx.system_sleep_observers
.clone()
.retain(move |callback| (callback)(cx));
})
}
pub(crate) fn borrow_for_wake<'a>(
this: &Rc<Self>,
app: &'a Rc<AppCell>,
) -> Option<AppRefMut<'a>> {
Self::borrow_for(this, app, |cx| {
cx.system_wake_observers
.clone()
.retain(move |callback| (callback)(cx));
})
}
fn borrow_for<'a>(
this: &Rc<Self>,
app: &'a Rc<AppCell>,
notify: fn(&mut App),
) -> Option<AppRefMut<'a>> {
let Ok(mut cx) = app.try_borrow_mut() else {
this.pending.borrow_mut().push_back(notify);
Self::schedule_retry(this, Rc::downgrade(app));
return None;
};
if this.pending.borrow().is_empty() {
return Some(cx);
}
this.pending.borrow_mut().push_back(notify);
Self::deliver_pending(this, &mut cx);
None
}
fn deliver_pending(this: &Rc<Self>, cx: &mut App) {
loop {
let Some(notify) = this.pending.borrow_mut().pop_front() else {
break;
};
notify(cx);
}
}
fn schedule_retry(this: &Rc<Self>, app: Weak<AppCell>) {
if this.retry_scheduled.replace(true) {
return;
}
let retry = this.clone();
this.executor
.spawn(async move {
retry.retry_scheduled.set(false);
let Some(app) = app.upgrade() else {
return;
};
match app.try_borrow_mut() {
Ok(mut cx) => Self::deliver_pending(&retry, &mut cx),
Err(_) => Self::schedule_retry(&retry, Rc::downgrade(&app)),
}
})
.detach();
}
}