use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::rc::{Rc, Weak};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::task::{Context, Poll, Wake, Waker};
use std::time::Duration;
use ferrokit_core::kept::{UiCell, UiLocal};
use objc2::rc::Retained;
use objc2::runtime::AnyObject;
use objc2::msg_send;
use crate::platform::{Native, Platform};
use crate::signal::{OwnerInner, batch, disown_task, own_task, untrack, with_weak_owner};
type LocalFuture = Pin<Box<dyn Future<Output = ()>>>;
struct Slot {
future: Option<LocalFuture>,
repoll: bool,
owner: Option<Weak<OwnerInner>>,
waker: Arc<TaskWaker>,
}
thread_local! {
static TASKS: UiCell<HashMap<u64, Slot>> = UiCell::new(HashMap::new());
static NEXT: Cell<u64> = const { Cell::new(0) };
static CURRENT: Cell<Option<u64>> = const { Cell::new(None) };
}
struct TaskWaker {
id: u64,
scheduled: AtomicBool,
}
impl Wake for TaskWaker {
fn wake(self: Arc<Self>) {
self.wake_by_ref();
}
fn wake_by_ref(self: &Arc<Self>) {
if !self.scheduled.swap(true, Ordering::AcqRel) {
let id = self.id;
Native::on_main(Box::new(move || poll(id)));
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Task(u64);
impl fmt::Debug for Task {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Task").field("id", &self.0).field("finished", &self.is_finished()).finish()
}
}
impl Task {
pub fn cancel(self) {
cancel_all([self.0]);
}
pub fn detach(self) {
let owner = TASKS.with_borrow_mut(|t| t.get_mut(&self.0).and_then(|s| s.owner.take()));
if let Some(owner) = owner {
disown_task(&owner, self.0);
}
}
pub fn is_finished(self) -> bool {
!TASKS.with_borrow(|t| t.contains_key(&self.0))
}
}
pub fn spawn_local(future: impl Future<Output = ()> + 'static) -> Task {
let _ = crate::mtm();
let id = NEXT.with(|n| n.replace(n.get() + 1));
let owner = own_task(id);
let waker = Arc::new(TaskWaker { id, scheduled: AtomicBool::new(false) });
TASKS.with_borrow_mut(|t| t.insert(id, Slot { future: Some(Box::pin(future)), repoll: false, owner, waker: waker.clone() }));
waker.wake_by_ref();
Task(id)
}
pub(crate) fn cancel_all(ids: impl IntoIterator<Item = u64>) {
let mut gone = Vec::new();
for id in ids {
let slot = TASKS.try_with(|t| t.borrow_mut().remove(&id)).ok().flatten();
if let Some(slot) = slot {
if let Some(owner) = &slot.owner {
disown_task(owner, id);
}
gone.push(slot);
}
}
drop(gone);
}
fn poll(id: u64) {
let taken = TASKS.with_borrow_mut(|t| {
let slot = t.get_mut(&id)?;
match slot.future.take() {
Some(f) => Some((f, slot.waker.clone(), slot.owner.clone())),
None => {
slot.repoll = true;
slot.waker.scheduled.store(false, Ordering::Release);
None
}
}
});
let Some((mut future, waker, owner)) = taken else { return };
waker.scheduled.store(false, Ordering::Release);
let task_waker = Waker::from(waker.clone());
let prev = CURRENT.replace(Some(id));
let polled = crate::failure::guard("an async task", None, || {
Some(untrack(|| with_weak_owner(owner.as_ref(), || batch(|| future.as_mut().poll(&mut Context::from_waker(&task_waker))))))
});
CURRENT.set(prev);
match polled {
Some(Poll::Pending) => {
let mut future = Some(future);
let again = TASKS.with_borrow_mut(|t| match t.get_mut(&id) {
Some(slot) => {
slot.future = future.take();
std::mem::take(&mut slot.repoll)
}
None => false,
});
drop(future);
if again {
waker.wake_by_ref();
}
}
Some(Poll::Ready(())) | None => {
drop(future);
cancel_all([id]);
}
}
}
fn current() -> Option<u64> {
CURRENT.with(Cell::get)
}
struct Shared<T> {
result: RefCell<Option<T>>,
waker: RefCell<Option<Waker>>,
task: Cell<Option<u64>>,
}
#[must_use = "the result is dropped unless it's awaited"]
pub struct Background<T> {
shared: Rc<Shared<T>>,
}
impl<T> fmt::Debug for Background<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Background").field("done", &self.shared.result.borrow().is_some()).finish()
}
}
pub fn background<T: Send + 'static>(work: impl FnOnce() -> T + Send + 'static) -> Background<T> {
let shared = Rc::new(Shared { result: RefCell::new(None), waker: RefCell::new(None), task: Cell::new(None) });
let weak = Rc::downgrade(&shared);
crate::spawn_outcome(work, move |outcome| {
let Some(shared) = weak.upgrade() else { return }; match outcome {
Ok(result) => {
*shared.result.borrow_mut() = Some(result);
let waker = shared.waker.borrow_mut().take();
if let Some(w) = waker {
w.wake();
}
}
Err(_) => {
if let Some(task) = shared.task.get() {
crate::later(move || Task(task).cancel());
}
}
}
});
Background { shared }
}
impl<T> Future for Background<T> {
type Output = T;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<T> {
if let Some(result) = self.shared.result.borrow_mut().take() {
return Poll::Ready(result);
}
if self.shared.task.get().is_none() {
self.shared.task.set(current());
}
*self.shared.waker.borrow_mut() = Some(cx.waker().clone());
Poll::Pending
}
}
struct Timer {
fired: Cell<bool>,
waker: RefCell<Option<Waker>>,
}
#[must_use = "a sleep does nothing unless it's awaited"]
pub struct Sleep {
duration: Duration,
state: Rc<Timer>,
timer: Option<Retained<AnyObject>>,
}
impl fmt::Debug for Sleep {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Sleep").field("duration", &self.duration).field("fired", &self.state.fired.get()).finish()
}
}
pub fn sleep(duration: Duration) -> Sleep {
let _ = crate::mtm();
Sleep { duration, state: Rc::new(Timer { fired: Cell::new(false), waker: RefCell::new(None) }), timer: None }
}
impl Future for Sleep {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
if self.state.fired.get() {
return Poll::Ready(());
}
*self.state.waker.borrow_mut() = Some(cx.waker().clone());
if self.timer.is_none() {
let state = self.state.clone();
let block = block2::RcBlock::new(move |_timer: std::ptr::NonNull<AnyObject>| {
state.fired.set(true);
let waker = state.waker.borrow_mut().take();
if let Some(w) = waker {
w.wake();
}
});
let seconds = self.duration.as_secs_f64();
let timer: Retained<AnyObject> = unsafe {
let timer: Retained<AnyObject> = msg_send![objc2::class!(NSTimer), timerWithTimeInterval: seconds, repeats: false, block: &*block];
let run_loop: Retained<AnyObject> = msg_send![objc2::class!(NSRunLoop), mainRunLoop];
let () = msg_send![&*run_loop, addTimer: &*timer, forMode: objc2_foundation::NSRunLoopCommonModes];
timer
};
self.timer = Some(timer);
}
Poll::Pending
}
}
impl Drop for Sleep {
fn drop(&mut self) {
if let Some(timer) = self.timer.take() {
unsafe {
let () = msg_send![&*timer, invalidate];
}
}
}
}