Skip to main content

nifty_macos/
waker.rs

1//! Waking the main thread from others, through the main dispatch queue the run loop drains.
2
3use std::fmt;
4use std::sync::Arc;
5
6use dispatch2::{DispatchQueue, MainThreadBound};
7use objc2::MainThreadMarker;
8
9use nifty_runtime::{WakeHandler, Waker};
10
11pub struct MacWaker(Arc<MainThreadBound<WakeHandler>>);
12
13impl MacWaker {
14    pub(crate) fn new(mtm: MainThreadMarker, on_wake: WakeHandler) -> Self {
15        Self(Arc::new(MainThreadBound::new(on_wake, mtm)))
16    }
17}
18
19impl Waker for MacWaker {
20    fn wake(&self) {
21        let on_wake = Arc::clone(&self.0);
22        DispatchQueue::main().exec_async(move || {
23            let mtm = MainThreadMarker::new().expect("the main queue runs on the main thread");
24            (on_wake.get(mtm))();
25        });
26    }
27}
28
29impl fmt::Debug for MacWaker {
30    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31        f.debug_struct("MacWaker").finish_non_exhaustive()
32    }
33}