Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

5.1 KB
Raw Blame
//! System events that can silently kill open connections: the primary network changing (Wi-Fi
//! switch, VPN, cable) and the machine waking from sleep.

#[cfg(target_os = "macos")]
mod imp {
    use std::ffi::c_void;
    use std::ptr::null;

    type CFTypeRef = *const c_void;
    type CFStringRef = *const c_void;
    type CFArrayRef = *const c_void;
    type CFRunLoopRef = *const c_void;
    type CFRunLoopSourceRef = *const c_void;

    #[repr(C)]
    struct SCDynamicStoreContext {
        version: isize,
        info: *mut c_void,
        retain: *const c_void,
        release: *const c_void,
        copy_description: *const c_void,
    }

    #[link(name = "CoreFoundation", kind = "framework")]
    unsafe extern "C" {
        static kCFRunLoopCommonModes: CFStringRef;
        static kCFTypeArrayCallBacks: c_void;
        fn CFRunLoopGetMain() -> CFRunLoopRef;
        fn CFRunLoopAddSource(rl: CFRunLoopRef, src: CFRunLoopSourceRef, mode: CFStringRef);
        fn CFStringCreateWithCString(alloc: CFTypeRef, s: *const i8, enc: u32) -> CFStringRef;
        fn CFArrayCreate(alloc: CFTypeRef, values: *const CFTypeRef, n: isize, cb: *const c_void) -> CFArrayRef;
    }

    #[link(name = "SystemConfiguration", kind = "framework")]
    unsafe extern "C" {
        fn SCDynamicStoreCreate(
            alloc: CFTypeRef,
            name: CFStringRef,
            cb: unsafe extern "C" fn(CFTypeRef, CFArrayRef, *mut c_void),
            ctx: *mut SCDynamicStoreContext,
        ) -> CFTypeRef;
        fn SCDynamicStoreSetNotificationKeys(store: CFTypeRef, keys: CFArrayRef, patterns: CFArrayRef) -> u8;
        fn SCDynamicStoreCreateRunLoopSource(alloc: CFTypeRef, store: CFTypeRef, order: isize) -> CFRunLoopSourceRef;
    }

    #[link(name = "IOKit", kind = "framework")]
    unsafe extern "C" {
        fn IORegisterForSystemPower(
            refcon: *mut c_void,
            port: *mut *mut c_void,
            cb: unsafe extern "C" fn(*mut c_void, u32, u32, *mut c_void),
            notifier: *mut u32,
        ) -> u32;
        fn IONotificationPortSetDispatchQueue(port: *mut c_void, queue: *mut c_void);
        fn IOAllowPowerChange(kernel_port: u32, notification_id: isize) -> i32;
    }

    unsafe extern "C" {
        fn dispatch_get_global_queue(identifier: isize, flags: usize) -> *mut c_void;
    }

    const IO_CAN_SYSTEM_SLEEP: u32 = 0xE000_0270;
    const IO_SYSTEM_WILL_SLEEP: u32 = 0xE000_0280;
    const IO_SYSTEM_HAS_POWERED_ON: u32 = 0xE000_0300;

    static mut ROOT_PORT: u32 = 0;

    thread_local! {
        static INSTALLED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
    }

    fn on_change(why: &str) {
        crate::proxy::invalidate();
        crate::http_clear_pool();
        crate::probe_sockets(why);
    }

    unsafe extern "C" fn store_changed(_store: CFTypeRef, _keys: CFArrayRef, _info: *mut c_void) {
        on_change("network change");
    }

    unsafe extern "C" fn power_changed(_refcon: *mut c_void, _service: u32, msg: u32, arg: *mut c_void) {
        match msg {
            IO_CAN_SYSTEM_SLEEP | IO_SYSTEM_WILL_SLEEP => unsafe {
                IOAllowPowerChange(ROOT_PORT, arg as isize);
            },
            IO_SYSTEM_HAS_POWERED_ON => rt::post(|| on_change("wake")),
            _ => {}
        }
    }

    pub fn install() {
        if INSTALLED.with(|i| i.replace(true)) {
            return;
        }
        unsafe {
            let main = CFRunLoopGetMain();
            let cfstr = |s: &std::ffi::CStr| CFStringCreateWithCString(null(), s.as_ptr(), 0x0800_0100);
            let keys = [
                cfstr(c"State:/Network/Global/IPv4"),
                cfstr(c"State:/Network/Global/IPv6"),
                cfstr(c"State:/Network/Global/Proxies"),
            ];
            let mut ctx = SCDynamicStoreContext { version: 0, info: std::ptr::null_mut(), retain: null(), release: null(), copy_description: null() };
            let store = SCDynamicStoreCreate(null(), cfstr(c"threert.net"), store_changed, &mut ctx);
            if !store.is_null() {
                let arr = CFArrayCreate(null(), keys.as_ptr(), keys.len() as isize, &kCFTypeArrayCallBacks);
                SCDynamicStoreSetNotificationKeys(store, arr, null());
                let src = SCDynamicStoreCreateRunLoopSource(null(), store, 0);
                if !src.is_null() {
                    CFRunLoopAddSource(main, src, kCFRunLoopCommonModes);
                }
            } else {
                eprintln!("[net] could not watch network changes");
            }
            let mut port: *mut c_void = std::ptr::null_mut();
            let mut notifier: u32 = 0;
            let root = IORegisterForSystemPower(std::ptr::null_mut(), &mut port, power_changed, &mut notifier);
            if root != 0 && !port.is_null() {
                ROOT_PORT = root;
                IONotificationPortSetDispatchQueue(port, dispatch_get_global_queue(0, 0));
            } else {
                eprintln!("[net] could not register for wake notifications");
            }
        }
    }
}

#[cfg(not(target_os = "macos"))]
mod imp {
    pub fn install() {}
}

/// Main thread, once per process.
pub fn install() {
    imp::install();
}