Skip to main content

wgame_app/
runtime.rs

1use std::{
2    boxed::Box,
3    cell::RefCell,
4    pin::Pin,
5    rc::Rc,
6    task::{Context, Poll},
7    time::Duration,
8};
9
10use futures::{FutureExt, future::FusedFuture};
11use winit::event_loop::ActiveEventLoop;
12
13use crate::{
14    app::{AppState, CURRENT, CallbackContainer},
15    executor::{ExecutorProxy, TaskId},
16    output::{CallOutput, Terminated},
17    time::{Instant, Timer, TimerQueue},
18};
19
20pub type CallbackObj = Box<dyn FnOnce(&ActiveEventLoop)>;
21
22#[derive(Clone, Copy, Default, PartialEq, Eq, Hash, Debug)]
23pub enum CallbackTrigger {
24    /// Simply trigger on next event loop poll
25    #[default]
26    Poll,
27    /// Triggner on next event loop poll if application is resumed
28    PollResumed,
29}
30
31/// Runtime handle
32#[derive(Clone)]
33pub struct Runtime {
34    pub(crate) state: Rc<RefCell<AppState>>,
35    pub(crate) executor: Rc<RefCell<ExecutorProxy>>,
36    pub(crate) timers: Rc<RefCell<TimerQueue>>,
37    pub(crate) callbacks: Rc<RefCell<CallbackContainer>>,
38}
39
40impl Runtime {
41    /// Panics if called not from app task.
42    pub fn current() -> Runtime {
43        CURRENT.with_borrow(|proxy| proxy.clone().expect("There's no current runtime"))
44    }
45
46    pub fn create_task<F: Future + 'static>(&self, future: F) -> Task<F::Output> {
47        let output = CallOutput::default();
48        let task_id = self.executor.borrow_mut().spawn(
49            {
50                let output = output.clone();
51                async move {
52                    let result = future.await;
53                    output.set_ready(Ok(result));
54                }
55            },
56            {
57                let output = output.clone();
58                move || output.set_ready(Err(Terminated))
59            },
60        );
61        Task {
62            task: task_id,
63            executor: self.executor.clone(),
64            output,
65        }
66    }
67
68    pub fn run_within_event_loop<T: 'static, F: FnOnce(&ActiveEventLoop) -> T + 'static>(
69        &self,
70        call: F,
71        trigger: CallbackTrigger,
72    ) -> CallOutput<T> {
73        let output = CallOutput::default();
74        let mut callbacks = self.callbacks.borrow_mut();
75        let list = match trigger {
76            CallbackTrigger::Poll => &mut callbacks.next_poll,
77            CallbackTrigger::PollResumed => &mut callbacks.on_resume,
78        };
79        list.push(Box::new({
80            let output = output.clone();
81            move |event_loop| {
82                let result = call(event_loop);
83                output.set_ready(result);
84            }
85        }));
86        output
87    }
88
89    pub fn create_timer(&self, timestamp: Instant) -> Timer {
90        self.timers.borrow_mut().insert(timestamp)
91    }
92}
93
94/// Single-consumer task result; clone [`Self::handle`] for cancellation access.
95///
96/// Dropping a plain task or its control handle detaches it. The application waits
97/// for remaining tasks to finish. Cancellation takes effect at a scheduler boundary
98/// and resolves the result to `Err(Terminated)`. Repeated cancellation, including
99/// after completion, is harmless. See [`Self::cancel_on_drop`] for scoped ownership.
100pub struct Task<T> {
101    task: TaskId,
102    executor: Rc<RefCell<ExecutorProxy>>,
103    output: CallOutput<Result<T, Terminated>>,
104}
105
106/// Clonable cancellation access without access to the task result.
107#[derive(Clone)]
108pub struct TaskHandle {
109    task: TaskId,
110    executor: Rc<RefCell<ExecutorProxy>>,
111}
112impl TaskHandle {
113    pub fn id(&self) -> TaskId {
114        self.task
115    }
116    /// Cancel at the next scheduler boundary. Repeated calls are harmless.
117    pub fn terminate(&self) {
118        self.executor.borrow_mut().terminate(self.task);
119    }
120}
121/// Task cancelled when its owner leaves scope, including window suspension.
122pub struct ScopedTask<T> {
123    task: Task<T>,
124}
125impl<T> ScopedTask<T> {
126    pub fn handle(&self) -> TaskHandle {
127        self.task.handle()
128    }
129}
130impl<T> Drop for ScopedTask<T> {
131    fn drop(&mut self) {
132        self.task.terminate();
133    }
134}
135impl<T> Future for ScopedTask<T> {
136    type Output = Result<T, Terminated>;
137    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
138        self.task.poll_unpin(cx)
139    }
140}
141impl<T> FusedFuture for ScopedTask<T> {
142    fn is_terminated(&self) -> bool {
143        self.task.is_terminated()
144    }
145}
146impl<T> Task<T> {
147    /// Cancel when this owner leaves scope, including window suspension.
148    ///
149    /// ```no_run
150    /// async fn background_work() {
151    ///     let task = wgame_app::spawn(async {
152    ///         loop { wgame_app::sleep(std::time::Duration::from_secs(1)).await; }
153    ///     }).cancel_on_drop();
154    ///     let handle = task.handle();
155    ///     handle.terminate();
156    ///     let _ = task.await;
157    /// }
158    /// ```
159    pub fn cancel_on_drop(self) -> ScopedTask<T> {
160        ScopedTask { task: self }
161    }
162
163    pub fn handle(&self) -> TaskHandle {
164        TaskHandle {
165            task: self.task,
166            executor: self.executor.clone(),
167        }
168    }
169
170    pub fn id(&self) -> TaskId {
171        self.task
172    }
173    pub fn terminate(&self) {
174        self.executor.borrow_mut().terminate(self.task);
175    }
176    pub fn output(&self) -> &CallOutput<Result<T, Terminated>> {
177        &self.output
178    }
179}
180
181impl<T> Future for Task<T> {
182    type Output = Result<T, Terminated>;
183
184    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
185        self.output.poll_unpin(cx)
186    }
187}
188
189impl<T> FusedFuture for Task<T> {
190    fn is_terminated(&self) -> bool {
191        self.output().is_terminated()
192    }
193}
194
195pub fn sleep_until(timestamp: Instant) -> Timer {
196    Runtime::current().create_timer(timestamp)
197}
198
199pub fn sleep(timeout: Duration) -> Timer {
200    let timestamp = Instant::now().checked_add(timeout).unwrap();
201    Runtime::current().create_timer(timestamp)
202}
203
204pub fn spawn<F>(future: F) -> Task<F::Output>
205where
206    F: Future<Output: 'static> + 'static,
207{
208    Runtime::current().create_task(future)
209}
210
211#[cfg(test)]
212mod tests {
213    use super::*;
214    use crate::executor::Executor;
215    #[test]
216    fn handle_cancels_result_and_drop_detaches() {
217        let mut executor = Executor::with_waker_factory(|_| std::task::Waker::noop().clone());
218        let rt = Runtime {
219            state: Default::default(),
220            executor: executor.proxy(),
221            timers: Default::default(),
222            callbacks: Default::default(),
223        };
224        let task = rt.create_task(std::future::pending::<u32>());
225        task.handle().clone().terminate();
226        assert!(executor.poll().is_ready());
227        assert!(matches!(task.output().try_take(), Some(Err(Terminated))));
228        let ran = Rc::new(std::cell::Cell::new(false));
229        let marker = ran.clone();
230        drop(rt.create_task(async move {
231            marker.set(true);
232        }));
233        assert!(executor.poll().is_ready());
234        assert!(ran.get());
235    }
236}