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