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];
}
}
}
}
struct AnswerState<T> {
value: RefCell<Option<T>>,
answered: Cell<bool>,
waker: RefCell<Option<Waker>>,
}
#[must_use = "the dialog's answer is dropped unless it's awaited"]
pub struct Answer<T> {
state: Rc<AnswerState<T>>,
on_drop: Option<Box<dyn FnOnce()>>,
}
impl<T> fmt::Debug for Answer<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Answer").field("answered", &self.state.answered.get()).finish()
}
}
pub(crate) struct Responder<T>(Rc<AnswerState<T>>);
impl<T> Responder<T> {
pub(crate) fn send(&self, value: T) {
if self.0.answered.replace(true) {
return;
}
*self.0.value.borrow_mut() = Some(value);
let waker = self.0.waker.borrow_mut().take();
if let Some(w) = waker {
w.wake();
}
}
}
pub(crate) fn answer<T>(on_drop: impl FnOnce() + 'static) -> (Answer<T>, Responder<T>) {
let state = Rc::new(AnswerState { value: RefCell::new(None), answered: Cell::new(false), waker: RefCell::new(None) });
(Answer { state: state.clone(), on_drop: Some(Box::new(on_drop)) }, Responder(state))
}
impl<T> Future for Answer<T> {
type Output = T;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<T> {
if let Some(value) = self.state.value.borrow_mut().take() {
return Poll::Ready(value);
}
*self.state.waker.borrow_mut() = Some(cx.waker().clone());
Poll::Pending
}
}
impl<T> Drop for Answer<T> {
fn drop(&mut self) {
if !self.state.answered.get()
&& let Some(close) = self.on_drop.take()
{
close();
}
}
}
#[cfg(feature = "tokio")]
#[must_use = "the result is dropped unless it's awaited (the runtime task still runs until then)"]
pub struct OnRuntime<T> {
join: tokio::task::JoinHandle<T>,
}
#[cfg(feature = "tokio")]
impl<T> fmt::Debug for OnRuntime<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("OnRuntime").field("finished", &self.join.is_finished()).finish()
}
}
#[cfg(feature = "tokio")]
pub fn on_runtime<F>(handle: &tokio::runtime::Handle, future: F) -> OnRuntime<F::Output>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
OnRuntime { join: handle.spawn(future) }
}
#[cfg(feature = "tokio")]
impl<T> Future for OnRuntime<T> {
type Output = T;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<T> {
match Pin::new(&mut self.join).poll(cx) {
Poll::Pending => Poll::Pending,
Poll::Ready(Ok(value)) => Poll::Ready(value),
Poll::Ready(Err(e)) if e.is_panic() => std::panic::resume_unwind(e.into_panic()),
Poll::Ready(Err(_)) => panic!("its task on the tokio runtime was cancelled (did the runtime shut down?)"),
}
}
}
#[cfg(feature = "tokio")]
impl<T> Drop for OnRuntime<T> {
fn drop(&mut self) {
self.join.abort();
}
}
#[cfg(test)]
mod tests {
use super::*;
fn block_on<F: Future>(f: F) -> F::Output {
struct Unpark(std::thread::Thread);
impl Wake for Unpark {
fn wake(self: Arc<Self>) {
self.0.unpark();
}
}
let waker = Waker::from(Arc::new(Unpark(std::thread::current())));
let mut f = std::pin::pin!(f);
loop {
if let Poll::Ready(v) = f.as_mut().poll(&mut Context::from_waker(&waker)) {
return v;
}
std::thread::park_timeout(Duration::from_millis(50));
}
}
#[test]
fn an_answer_is_ready_once_sent_and_the_first_answer_counts() {
let closed = Rc::new(Cell::new(false));
let c = closed.clone();
let (answer, responder) = answer::<u32>(move || c.set(true));
responder.send(7);
responder.send(8);
assert_eq!(block_on(answer), 7);
assert!(!closed.get(), "an answered dialog isn't closed again");
}
#[test]
fn dropping_an_unanswered_answer_closes_its_dialog() {
let closed = Rc::new(Cell::new(false));
let c = closed.clone();
let (answer, responder) = answer::<u32>(move || c.set(true));
drop(answer);
assert!(closed.get());
responder.send(1); }
#[cfg(feature = "tokio")]
#[test]
fn on_runtime_gives_the_output_and_carries_a_panic() {
let rt = tokio::runtime::Runtime::new().unwrap();
assert_eq!(block_on(on_runtime(rt.handle(), async { 6 * 7 })), 42);
let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| block_on(on_runtime(rt.handle(), async { panic!("boom") }))));
let payload = caught.expect_err("the panic reaches the awaiting side");
assert_eq!(payload.downcast_ref::<&str>(), Some(&"boom"));
}
#[cfg(feature = "tokio")]
#[test]
fn dropping_on_runtime_aborts_the_runtime_task() {
let rt = tokio::runtime::Runtime::new().unwrap();
let finished = Arc::new(AtomicBool::new(false));
let f = finished.clone();
let started = Arc::new(AtomicBool::new(false));
let s = started.clone();
let fut = on_runtime(rt.handle(), async move {
s.store(true, Ordering::SeqCst);
tokio::time::sleep(Duration::from_millis(300)).await;
f.store(true, Ordering::SeqCst);
});
while !started.load(Ordering::SeqCst) {
std::thread::sleep(Duration::from_millis(5));
}
drop(fut);
std::thread::sleep(Duration::from_millis(500));
assert!(!finished.load(Ordering::SeqCst), "the runtime task was aborted");
}
}