dispatcher.rs

 1#![allow(non_upper_case_globals)]
 2#![allow(non_camel_case_types)]
 3#![allow(non_snake_case)]
 4
 5use async_task::Runnable;
 6use objc::{
 7    class, msg_send,
 8    runtime::{BOOL, YES},
 9    sel, sel_impl,
10};
11use std::ffi::c_void;
12
13use crate::platform;
14
15include!(concat!(env!("OUT_DIR"), "/dispatch_sys.rs"));
16
17pub fn dispatch_get_main_queue() -> dispatch_queue_t {
18    unsafe { &_dispatch_main_q as *const _ as dispatch_queue_t }
19}
20
21pub struct Dispatcher;
22
23impl platform::Dispatcher for Dispatcher {
24    fn is_main_thread(&self) -> bool {
25        let is_main_thread: BOOL = unsafe { msg_send![class!(NSThread), isMainThread] };
26        is_main_thread == YES
27    }
28
29    fn run_on_main_thread(&self, runnable: Runnable) {
30        unsafe {
31            dispatch_async_f(
32                dispatch_get_main_queue(),
33                runnable.into_raw() as *mut c_void,
34                Some(trampoline),
35            );
36        }
37
38        extern "C" fn trampoline(runnable: *mut c_void) {
39            let task = unsafe { Runnable::from_raw(runnable as *mut ()) };
40            task.run();
41        }
42    }
43}