Skip to main content

nsh_core/
main_thread.rs

1//! Functions an app runs on the platform's main thread
2//! ([`crate::element::run_on_main_thread`]): the engine hands each to its
3//! surface's `MountSink` after the commit of the turn that asked for it,
4//! and the platform runs it on its UI thread after that commit's batch.
5
6use std::{
7    fmt,
8    future::Future,
9    pin::Pin,
10    sync::{Arc, Mutex},
11    task::{Context, Poll, Waker},
12};
13
14/// A function to run once on the platform's main thread. The platform calls
15/// [`MainThreadTask::run`] there.
16pub struct MainThreadTask(Box<dyn FnOnce() + Send>);
17
18impl MainThreadTask {
19    /// `f`, to run on the main thread.
20    pub(crate) fn new(f: impl FnOnce() + Send + 'static) -> Self {
21        Self(Box::new(f))
22    }
23
24    /// Runs it, here. A panic in it is caught and logged: it never unwinds
25    /// through the platform's run loop.
26    pub fn run(self) {
27        let task = self.0;
28        if let Err(payload) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(task)) {
29            log::error!(
30                "a function run on the main thread panicked: {}",
31                crate::element::panic_message(payload)
32            );
33        }
34    }
35}
36
37impl fmt::Debug for MainThreadTask {
38    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39        f.write_str("MainThreadTask")
40    }
41}
42
43/// Why an [`OnMainThread`] has no value.
44#[derive(Debug, Clone, PartialEq, Eq)]
45#[non_exhaustive]
46pub enum MainThreadError {
47    /// The function panicked, with this message.
48    Panicked(String),
49    /// The function never ran: its surface went away first.
50    Dropped,
51}
52
53impl fmt::Display for MainThreadError {
54    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55        match self {
56            Self::Panicked(message) => write!(f, "the main thread's function panicked: {message}"),
57            Self::Dropped => f.write_str("the main thread's function never ran"),
58        }
59    }
60}
61
62impl std::error::Error for MainThreadError {}
63
64struct Shared<R> {
65    value: Option<Result<R, MainThreadError>>,
66    waker: Option<Waker>,
67}
68
69/// The result of a function run on the main thread
70/// ([`crate::element::run_on_main_thread`]): await it on the engine thread.
71/// Dropping it does not stop the function.
72pub struct OnMainThread<R> {
73    shared: Arc<Mutex<Shared<R>>>,
74}
75
76impl<R> fmt::Debug for OnMainThread<R> {
77    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78        f.write_str("OnMainThread")
79    }
80}
81
82impl<R> Future for OnMainThread<R> {
83    type Output = Result<R, MainThreadError>;
84
85    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
86        let mut shared = self.shared.lock().expect("main thread result lock");
87        match shared.value.take() {
88            Some(value) => Poll::Ready(value),
89            None => {
90                shared.waker = Some(cx.waker().clone());
91                Poll::Pending
92            }
93        }
94    }
95}
96
97/// Answers an [`OnMainThread`] once; dropped unanswered, it answers
98/// [`MainThreadError::Dropped`].
99struct Answer<R>(Option<Arc<Mutex<Shared<R>>>>);
100
101impl<R> Answer<R> {
102    fn send(&mut self, value: Result<R, MainThreadError>) {
103        let Some(shared) = self.0.take() else { return };
104        let waker = {
105            let mut shared = shared.lock().expect("main thread result lock");
106            shared.value = Some(value);
107            shared.waker.take()
108        };
109        if let Some(waker) = waker {
110            waker.wake();
111        }
112    }
113}
114
115impl<R> Drop for Answer<R> {
116    fn drop(&mut self) {
117        self.send(Err(MainThreadError::Dropped));
118    }
119}
120
121/// `f` as a task for the main thread, and the future of its result.
122pub(crate) fn task<R: Send + 'static>(
123    f: impl FnOnce() -> R + Send + 'static,
124) -> (MainThreadTask, OnMainThread<R>) {
125    let shared = Arc::new(Mutex::new(Shared {
126        value: None,
127        waker: None,
128    }));
129    let mut answer = Answer(Some(shared.clone()));
130    let task = MainThreadTask::new(move || {
131        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f))
132            .map_err(|payload| MainThreadError::Panicked(crate::element::panic_message(payload)));
133        answer.send(result);
134    });
135    (task, OnMainThread { shared })
136}
137
138#[cfg(test)]
139mod tests {
140    use super::*;
141
142    fn poll<R>(future: &mut OnMainThread<R>) -> Poll<Result<R, MainThreadError>> {
143        Pin::new(future).poll(&mut Context::from_waker(Waker::noop()))
144    }
145
146    #[test]
147    fn a_task_answers_its_value_its_panic_or_that_it_never_ran() {
148        let (run, mut value) = task(|| 6 * 7);
149        assert!(poll(&mut value).is_pending());
150        std::thread::spawn(move || run.run()).join().unwrap();
151        assert_eq!(poll(&mut value), Poll::Ready(Ok(42)));
152
153        let (run, mut panicked) = task(|| -> u8 { panic!("boom") });
154        run.run();
155        assert_eq!(
156            poll(&mut panicked),
157            Poll::Ready(Err(MainThreadError::Panicked("boom".into())))
158        );
159
160        let (run, mut dropped) = task(|| ());
161        drop(run);
162        assert_eq!(
163            poll(&mut dropped),
164            Poll::Ready(Err(MainThreadError::Dropped))
165        );
166    }
167}