#![allow(unsafe_code)]
use core::ptr::NonNull;
use std::sync::mpsc;
use block2::RcBlock;
use objc2::runtime::{AnyObject, ProtocolObject};
use objc2_core_foundation::{CFRetained, CFRunLoop};
use objc2_foundation::{
NSDistributedNotificationCenter, NSNotification, NSNotificationName, NSObjectProtocol, NSString,
};
use super::ThemeChangeEvent;
struct SendableCFRunLoop(NonNull<CFRunLoop>);
unsafe impl Send for SendableCFRunLoop {}
impl SendableCFRunLoop {
fn from_retained(retained: &CFRetained<CFRunLoop>) -> Self {
Self(NonNull::from(&**retained))
}
unsafe fn stop(&self) {
unsafe { self.0.as_ref().stop() };
}
}
pub(crate) fn watch_macos(
callback: impl Fn(ThemeChangeEvent) + Send + 'static,
) -> crate::Result<super::ThemeSubscription> {
let (shutdown_tx, _shutdown_rx) = mpsc::channel::<()>();
let (loop_tx, loop_rx) = mpsc::channel::<SendableCFRunLoop>();
let thread = std::thread::spawn(move || {
let Some(run_loop) = CFRunLoop::current() else {
return;
};
let sendable = SendableCFRunLoop::from_retained(&run_loop);
if loop_tx.send(sendable).is_err() {
return;
}
let center = NSDistributedNotificationCenter::defaultCenter();
let name: &NSNotificationName =
&NSString::from_str("AppleInterfaceThemeChangedNotification");
let block: RcBlock<dyn Fn(NonNull<NSNotification>)> =
RcBlock::new(move |_notification: NonNull<NSNotification>| {
callback(ThemeChangeEvent::Changed);
});
let observer: objc2::rc::Retained<ProtocolObject<dyn NSObjectProtocol>> = unsafe {
center.addObserverForName_object_queue_usingBlock(
Some(name),
None, None, &block,
)
};
CFRunLoop::run();
unsafe {
let observer_any: &AnyObject = (*observer).as_ref();
center.removeObserver(observer_any);
}
});
let sendable_loop = loop_rx.recv().map_err(|_| crate::Error::ReaderFailed {
reader: "macos_watcher",
source: "macOS watcher thread failed to start".into(),
})?;
let platform_shutdown = Box::new(move || {
unsafe { sendable_loop.stop() };
});
Ok(super::ThemeSubscription::new(
shutdown_tx,
thread,
Some(platform_shutdown),
))
}