#![allow(unsafe_code)]
use std::sync::{Arc, Condvar, Mutex};
use std::time::Instant;
use block2::RcBlock;
use objc2::rc::Retained;
use objc2::runtime::AnyObject;
use objc2::{AnyThread, DefinedClass, Message, define_class, msg_send, sel};
use objc2_app_kit::{
NSPreferredScrollerStyleDidChangeNotification, NSSystemColorsDidChangeNotification,
NSWorkspace, NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification,
};
use objc2_foundation::{
NSDistributedNotificationCenter, NSNotification, NSNotificationCenter, NSNotificationName,
NSNotificationSuspensionBehavior, NSObject, NSObjectProtocol, NSOperationQueue, NSString,
};
use super::ThemeChangeEvent;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Center {
Distributed,
Local,
Workspace,
}
pub(super) struct Registration {
#[cfg_attr(not(test), allow(dead_code))]
pub(super) name_id: &'static str,
center: Center,
name: Retained<NSNotificationName>,
}
pub(super) fn registrations() -> [Registration; 4] {
let (system_colors, scroller_style, accessibility_display) = unsafe {
(
NSSystemColorsDidChangeNotification.retain(),
NSPreferredScrollerStyleDidChangeNotification.retain(),
NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification.retain(),
)
};
[
Registration {
name_id: "AppleInterfaceThemeChangedNotification",
center: Center::Distributed,
name: NSString::from_str("AppleInterfaceThemeChangedNotification"),
},
Registration {
name_id: "NSSystemColorsDidChangeNotification",
center: Center::Local,
name: system_colors,
},
Registration {
name_id: "NSPreferredScrollerStyleDidChangeNotification",
center: Center::Local,
name: scroller_style,
},
Registration {
name_id: "NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification",
center: Center::Workspace,
name: accessibility_display,
},
]
}
#[derive(Default)]
struct Pending {
last: Option<Instant>,
closed: bool,
}
struct Delivery {
pending: Mutex<Pending>,
wake: Condvar,
queue: Retained<NSOperationQueue>,
callback: Mutex<Box<dyn Fn(ThemeChangeEvent) + Send>>,
}
impl Delivery {
fn notify(self: &Arc<Self>) {
let Ok(mut pending) = self.pending.lock() else {
return;
};
if pending.closed {
return;
}
if pending.last.replace(Instant::now()).is_none() {
let delivery = Arc::clone(self);
let block = RcBlock::new(move || delivery.run());
unsafe { self.queue.addOperationWithBlock(&block) };
}
}
fn run(&self) {
{
let Ok(mut pending) = self.pending.lock() else {
return;
};
loop {
if pending.closed {
return;
}
let Some(last) = pending.last else {
return;
};
let wait = super::DEBOUNCE.saturating_sub(last.elapsed());
if wait.is_zero() {
pending.last = None;
break;
}
pending = match self.wake.wait_timeout(pending, wait) {
Ok((pending, _)) => pending,
Err(_) => return,
};
}
}
if let Ok(callback) = self.callback.lock() {
super::fire(&*callback);
}
}
fn close(&self) {
if let Ok(mut pending) = self.pending.lock() {
pending.closed = true;
}
self.wake.notify_all();
}
}
define_class!(
#[unsafe(super(NSObject))]
#[ivars = Arc<Delivery>]
struct Observer;
impl Observer {
#[unsafe(method(themeSettingChanged:))]
fn theme_setting_changed(&self, _notification: &NSNotification) {
self.ivars().notify();
}
}
unsafe impl NSObjectProtocol for Observer {}
);
impl Observer {
fn new(delivery: Arc<Delivery>) -> Retained<Self> {
let this = Self::alloc().set_ivars(delivery);
unsafe { msg_send![super(this), init] }
}
}
struct ObserverGuard {
observer: Retained<Observer>,
centers: Vec<Retained<NSNotificationCenter>>,
}
impl Drop for ObserverGuard {
fn drop(&mut self) {
let observer: &AnyObject = &self.observer;
for center in &self.centers {
unsafe { center.removeObserver(observer) };
}
let delivery = self.observer.ivars();
delivery.close();
let on_own_queue = NSOperationQueue::currentQueue()
.is_some_and(|current| Retained::as_ptr(¤t) == Retained::as_ptr(&delivery.queue));
if !on_own_queue {
delivery.queue.waitUntilAllOperationsAreFinished();
}
}
}
fn observe(
registrations: &[Registration],
callback: impl Fn(ThemeChangeEvent) + Send + 'static,
) -> ObserverGuard {
let queue = NSOperationQueue::new();
queue.setMaxConcurrentOperationCount(1);
let observer = Observer::new(Arc::new(Delivery {
pending: Mutex::new(Pending::default()),
wake: Condvar::new(),
queue,
callback: Mutex::new(Box::new(callback)),
}));
let observer_any: &AnyObject = &observer;
let mut centers: Vec<Retained<NSNotificationCenter>> = Vec::new();
for registration in registrations {
let name: &NSNotificationName = ®istration.name;
let center = match registration.center {
Center::Distributed => {
let center = NSDistributedNotificationCenter::defaultCenter();
unsafe {
center.addObserver_selector_name_object_suspensionBehavior(
observer_any,
sel!(themeSettingChanged:),
Some(name),
None,
NSNotificationSuspensionBehavior::DeliverImmediately,
);
}
center.into_super()
}
Center::Local | Center::Workspace => {
let center = if registration.center == Center::Local {
NSNotificationCenter::defaultCenter()
} else {
NSWorkspace::sharedWorkspace().notificationCenter()
};
unsafe {
center.addObserver_selector_name_object(
observer_any,
sel!(themeSettingChanged:),
Some(name),
None,
);
}
center
}
};
if !centers
.iter()
.any(|known| Retained::as_ptr(known) == Retained::as_ptr(¢er))
{
centers.push(center);
}
}
ObserverGuard { observer, centers }
}
pub(crate) fn watch_macos(
callback: impl Fn(ThemeChangeEvent) + Send + 'static,
) -> crate::Result<super::ThemeSubscription> {
let guard = observe(®istrations(), callback);
Ok(super::ThemeSubscription::from_platform_shutdown(Box::new(
move || drop(guard),
)))
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use super::*;
fn local(name: &str) -> Registration {
Registration {
name_id: "test",
center: Center::Local,
name: NSString::from_str(name),
}
}
fn post(name: &NSNotificationName) {
unsafe { NSNotificationCenter::defaultCenter().postNotificationName_object(name, None) };
}
fn queue(guard: &ObserverGuard) -> Retained<NSOperationQueue> {
guard.observer.ivars().queue.clone()
}
#[test]
fn dropping_the_guard_removes_the_observer() {
let registrations = [local("native-theme.watch.macos.test")];
let count = Arc::new(AtomicUsize::new(0));
let counter = Arc::clone(&count);
let guard = observe(®istrations, move |_| {
counter.fetch_add(1, Ordering::SeqCst);
});
let queue = queue(&guard);
post(®istrations[0].name);
queue.waitUntilAllOperationsAreFinished();
assert_eq!(count.load(Ordering::SeqCst), 1);
drop(guard);
post(®istrations[0].name);
queue.waitUntilAllOperationsAreFinished();
assert_eq!(count.load(Ordering::SeqCst), 1);
}
#[test]
fn a_panicking_callback_does_not_stop_the_observer() {
let registrations = [local("native-theme.watch.macos.panic")];
let count = Arc::new(AtomicUsize::new(0));
let counter = Arc::clone(&count);
let guard = observe(®istrations, move |_| {
let call = counter.fetch_add(1, Ordering::SeqCst);
assert!(call > 0, "the first callback panics");
});
let queue = queue(&guard);
for _ in 0..2 {
post(®istrations[0].name);
queue.waitUntilAllOperationsAreFinished();
}
assert_eq!(count.load(Ordering::SeqCst), 2);
drop(guard);
}
#[test]
fn notifications_posted_together_fire_once() {
let registrations = [
local("native-theme.watch.macos.burst-a"),
local("native-theme.watch.macos.burst-b"),
];
let count = Arc::new(AtomicUsize::new(0));
let counter = Arc::clone(&count);
let guard = observe(®istrations, move |_| {
counter.fetch_add(1, Ordering::SeqCst);
});
let queue = queue(&guard);
let before = Instant::now();
post(®istrations[0].name);
post(®istrations[1].name);
let posting = before.elapsed();
queue.waitUntilAllOperationsAreFinished();
let fires = count.load(Ordering::SeqCst);
if posting < super::super::DEBOUNCE {
assert_eq!(fires, 1, "posts {posting:?} apart fired {fires} times");
} else {
assert!(
(1..=2).contains(&fires),
"posts {posting:?} apart fired {fires} times"
);
}
drop(guard);
}
#[test]
fn the_watcher_registers_and_drops() {
let guard = observe(®istrations(), |_| {});
assert_eq!(guard.centers.len(), 3);
drop(guard);
}
}