Skip to main content

xrack_runtime/
event_loop.rs

1use std::{
2    any::Any,
3    cell::{OnceCell, RefCell},
4    collections::HashMap,
5    marker::PhantomData,
6    rc::Rc,
7    sync::{Arc, Mutex},
8    thread::{self, ThreadId},
9};
10
11type UiCallback = Box<dyn FnOnce() + Send>;
12type Post = dyn Fn(UiCallback) -> Result<(), EventLoopError> + Send + Sync;
13static EVENT_LOOP: Mutex<Option<Arc<Post>>> = Mutex::new(None);
14
15#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
16pub enum EventLoopError {
17    #[error("the XRack UI event loop is not running")]
18    NotRunning,
19    #[error("the XRack UI event loop queue is full")]
20    QueueFull,
21    #[error("an XRack UI event loop is already running")]
22    AlreadyRunning,
23}
24
25/// Schedule a closure on the UI event loop from any thread.
26/// A successful return means the closure was queued.
27/// The queue holds at most 256 callbacks on the desktop host. Pending callbacks
28/// are discarded when the loop exits.
29pub fn invoke_from_event_loop(
30    callback: impl FnOnce() + Send + 'static,
31) -> Result<(), EventLoopError> {
32    let post = EVENT_LOOP.lock().unwrap().clone();
33    post.ok_or(EventLoopError::NotRunning)?(Box::new(callback))
34}
35
36/// Keeps the platform's event loop registered until it exits.
37#[doc(hidden)]
38pub struct EventLoopRegistration(());
39
40impl EventLoopRegistration {
41    pub fn new(
42        post: impl Fn(UiCallback) -> Result<(), EventLoopError> + Send + Sync + 'static,
43    ) -> Result<Self, EventLoopError> {
44        let mut active = EVENT_LOOP.lock().unwrap();
45        if active.is_some() {
46            return Err(EventLoopError::AlreadyRunning);
47        }
48        *active = Some(Arc::new(post));
49        Ok(Self(()))
50    }
51}
52
53impl Drop for EventLoopRegistration {
54    fn drop(&mut self) {
55        let previous = EVENT_LOOP.lock().unwrap().take();
56        drop(previous);
57    }
58}
59
60type ComponentLookup<C> = Rc<dyn Fn() -> Option<C>>;
61thread_local! {
62    static COMPONENTS: RefCell<HashMap<usize, Box<dyn Any>>> = RefCell::default();
63}
64
65#[derive(Default)]
66pub(crate) struct WeakRegistration(OnceCell<Arc<()>>);
67
68impl Drop for WeakRegistration {
69    fn drop(&mut self) {
70        if let Some(identity) = self.0.get() {
71            // The state and its registered Rc weak reference stay on this thread.
72            let _ = COMPONENTS.try_with(|components| {
73                components
74                    .borrow_mut()
75                    .remove(&(Arc::as_ptr(identity) as usize))
76            });
77        }
78    }
79}
80
81/// A handle that can be sent to a worker without keeping the component alive.
82pub struct WeakComponent<C> {
83    // Keep this allocation alive until the last handle is dropped so a stale
84    // handle cannot identify a later component at the same address.
85    identity: Arc<()>,
86    owner: ThreadId,
87    component: PhantomData<fn() -> C>,
88}
89
90impl<C> Clone for WeakComponent<C> {
91    fn clone(&self) -> Self {
92        Self {
93            identity: self.identity.clone(),
94            owner: self.owner,
95            component: PhantomData,
96        }
97    }
98}
99
100impl<C: 'static> WeakComponent<C> {
101    #[doc(hidden)]
102    pub fn new<S: 'static>(
103        state: &Rc<S>,
104        lifetime: &crate::ComponentLifetime,
105        wrap: fn(Rc<S>) -> C,
106    ) -> Self {
107        let identity = lifetime.weak.0.get_or_init(|| {
108            let identity = Arc::new(());
109            let state = Rc::downgrade(state);
110            let lookup: ComponentLookup<C> = Rc::new(move || state.upgrade().map(wrap));
111            COMPONENTS.with(|components| {
112                components
113                    .borrow_mut()
114                    .insert(Arc::as_ptr(&identity) as usize, Box::new(lookup));
115            });
116            identity
117        });
118        Self {
119            identity: identity.clone(),
120            owner: thread::current().id(),
121            component: PhantomData,
122        }
123    }
124
125    /// Obtain the component on its owning thread while it is still alive.
126    pub fn upgrade(&self) -> Option<C> {
127        if self.owner != thread::current().id() {
128            return None;
129        }
130        let lookup = COMPONENTS
131            .try_with(|components| {
132                components
133                    .borrow()
134                    .get(&(Arc::as_ptr(&self.identity) as usize))?
135                    .downcast_ref::<ComponentLookup<C>>()
136                    .cloned()
137            })
138            .ok()
139            .flatten()?;
140        lookup()
141    }
142
143    /// Queue an update and run it on the UI thread if the component still exists.
144    pub fn upgrade_in_event_loop(
145        &self,
146        callback: impl FnOnce(C) + Send + 'static,
147    ) -> Result<(), EventLoopError> {
148        let weak = self.clone();
149        invoke_from_event_loop(move || {
150            if let Some(component) = weak.upgrade() {
151                callback(component);
152            }
153        })
154    }
155}
156
157#[cfg(test)]
158mod tests {
159    use super::*;
160    use crate::ComponentLifetime;
161    use std::{cell::Cell, sync::mpsc};
162
163    #[derive(Default)]
164    struct ComponentState {
165        lifetime: ComponentLifetime,
166        value: Cell<u32>,
167    }
168
169    #[test]
170    fn worker_posts_to_the_owner_and_a_destroyed_component_is_skipped() {
171        assert_eq!(
172            invoke_from_event_loop(|| {}),
173            Err(EventLoopError::NotRunning)
174        );
175        let (send, receive) = mpsc::channel::<UiCallback>();
176        let registration = EventLoopRegistration::new(move |callback| {
177            send.send(callback).map_err(|_| EventLoopError::NotRunning)
178        })
179        .unwrap();
180        let ui_thread = thread::current().id();
181        let state = Rc::new(ComponentState::default());
182        let weak = WeakComponent::new(&state, &state.lifetime, |state| state);
183        let gone = Rc::new(ComponentState::default());
184        let gone_weak = WeakComponent::new(&gone, &gone.lifetime, |state| state);
185        let gone_identity = Arc::as_ptr(&gone_weak.identity) as usize;
186        let (done, observed) = mpsc::channel();
187
188        thread::spawn(move || {
189            assert!(weak.upgrade().is_none());
190            invoke_from_event_loop(move || done.send(thread::current().id()).unwrap()).unwrap();
191            weak.upgrade_in_event_loop(move |state| {
192                assert_eq!(thread::current().id(), ui_thread);
193                state.value.set(42);
194            })
195            .unwrap();
196            gone_weak
197                .upgrade_in_event_loop(|_| panic!("component was destroyed"))
198                .unwrap();
199        })
200        .join()
201        .unwrap();
202
203        drop(gone);
204        COMPONENTS.with(|components| assert!(!components.borrow().contains_key(&gone_identity)));
205        assert_eq!(state.value.get(), 0);
206        for _ in 0..3 {
207            receive.try_recv().unwrap()();
208        }
209        assert_eq!(observed.try_recv().unwrap(), ui_thread);
210        assert_eq!(state.value.get(), 42);
211        drop(registration);
212        assert_eq!(
213            invoke_from_event_loop(|| {}),
214            Err(EventLoopError::NotRunning)
215        );
216    }
217}