dispatcher.rs

  1#![allow(non_upper_case_globals)]
  2#![allow(non_camel_case_types)]
  3#![allow(non_snake_case)]
  4
  5use crate::{PlatformDispatcher, TaskLabel};
  6use async_task::Runnable;
  7use block::{Block, ConcreteBlock, RcBlock};
  8use core_foundation::{
  9    base::CFTypeRef,
 10    runloop::{
 11        CFRunLoopRef, CFRunLoopRunInMode, CFRunLoopWakeUp, kCFRunLoopCommonModes,
 12        kCFRunLoopDefaultMode,
 13    },
 14};
 15use objc::{
 16    class, msg_send,
 17    runtime::{BOOL, YES},
 18    sel, sel_impl,
 19};
 20use parking::{Parker, Unparker};
 21use parking_lot::Mutex;
 22use smol::io::BlockOn;
 23use std::{
 24    cell::Cell,
 25    ffi::c_void,
 26    ptr::{NonNull, addr_of},
 27    sync::Arc,
 28    time::Duration,
 29};
 30
 31/// All items in the generated file are marked as pub, so we're gonna wrap it in a separate mod to prevent
 32/// these pub items from leaking into public API.
 33pub(crate) mod dispatch_sys {
 34    include!(concat!(env!("OUT_DIR"), "/dispatch_sys.rs"));
 35}
 36
 37use dispatch_sys::*;
 38pub(crate) fn dispatch_get_main_queue() -> dispatch_queue_t {
 39    addr_of!(_dispatch_main_q) as *const _ as dispatch_queue_t
 40}
 41
 42pub(crate) struct MacDispatcher {
 43    parker: Arc<Mutex<Parker>>,
 44}
 45
 46impl Default for MacDispatcher {
 47    fn default() -> Self {
 48        Self::new()
 49    }
 50}
 51
 52impl MacDispatcher {
 53    pub fn new() -> Self {
 54        MacDispatcher {
 55            parker: Arc::new(Mutex::new(Parker::new())),
 56        }
 57    }
 58}
 59
 60impl PlatformDispatcher for MacDispatcher {
 61    fn is_main_thread(&self) -> bool {
 62        let is_main_thread: BOOL = unsafe { msg_send![class!(NSThread), isMainThread] };
 63        is_main_thread == YES
 64    }
 65
 66    fn dispatch(&self, runnable: Runnable, _: Option<TaskLabel>) {
 67        unsafe {
 68            dispatch_async_f(
 69                dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH.try_into().unwrap(), 0),
 70                runnable.into_raw().as_ptr() as *mut c_void,
 71                Some(trampoline),
 72            );
 73        }
 74    }
 75
 76    fn dispatch_on_main_thread(&self, runnable: Runnable) {
 77        use core_foundation::runloop::CFRunLoopGetMain;
 78
 79        unsafe {
 80            let mut runnable = Cell::new(Some(runnable));
 81            let main_run_loop = CFRunLoopGetMain();
 82            let block = ConcreteBlock::new(move || {
 83                if let Some(runnable) = runnable.take() {
 84                    runnable.run();
 85                }
 86            })
 87            .copy();
 88            CFRunLoopPerformBlock(
 89                main_run_loop,
 90                kCFRunLoopDefaultMode as _,
 91                &*block as *const Block<_, _> as _,
 92            );
 93        }
 94    }
 95
 96    fn dispatch_after(&self, duration: Duration, runnable: Runnable) {
 97        unsafe {
 98            let queue =
 99                dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH.try_into().unwrap(), 0);
100            let when = dispatch_time(DISPATCH_TIME_NOW as u64, duration.as_nanos() as i64);
101            dispatch_after_f(
102                when,
103                queue,
104                runnable.into_raw().as_ptr() as *mut c_void,
105                Some(trampoline),
106            );
107        }
108    }
109
110    fn tick(&self, background_only: bool) -> bool {
111        unsafe {
112            CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0., 0);
113        }
114        true
115    }
116
117    fn park(&self, timeout: Option<Duration>) -> bool {
118        if let Some(timeout) = timeout {
119            self.parker.lock().park_timeout(timeout)
120        } else {
121            self.parker.lock().park();
122            true
123        }
124    }
125
126    fn unparker(&self) -> Unparker {
127        self.parker.lock().unparker()
128    }
129}
130
131extern "C" fn trampoline(runnable: *mut c_void) {
132    let task = unsafe { Runnable::<()>::from_raw(NonNull::new_unchecked(runnable as *mut ())) };
133    task.run();
134}
135
136unsafe extern "C" {
137    fn CFRunLoopPerformBlock(rl: CFRunLoopRef, mode: CFTypeRef, block: *const c_void);
138}