use crate::kept::{UiCell, UiLocal};
use std::cell::{Cell, RefCell};
use block2::RcBlock;
use objc2::Message as _;
use objc2::rc::Retained;
use objc2::runtime::{AnyObject, NSObject, ProtocolObject};
use objc2::{MainThreadOnly, define_class, msg_send};
use objc2_app_kit::{NSApplication, NSColor, NSColorSpace};
use objc2_foundation::{
NSDictionary, NSKeyValueChangeKey, NSKeyValueObservingOptions, NSNotification, NSNotificationCenter,
NSObjectNSKeyValueObserverRegistration, NSObjectProtocol, NSString,
};
use crate::events::{Event, emit};
use crate::host::mtm;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Rgba {
pub r: f32,
pub g: f32,
pub b: f32,
pub a: f32,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SystemColors {
pub dark: bool,
pub window_background: Rgba,
pub control_background: Rgba,
pub text: Rgba,
pub secondary_text: Rgba,
pub separator: Rgba,
pub accent: Rgba,
pub selected_content_background: Rgba,
pub green: Rgba,
pub red: Rgba,
pub orange: Rgba,
}
define_class!(
#[unsafe(super(NSObject))]
#[thread_kind = MainThreadOnly]
#[name = "FerrokitCoreAppearanceObserver"]
struct AppearanceObserver;
impl AppearanceObserver {
#[unsafe(method(observeValueForKeyPath:ofObject:change:context:))]
fn observe(
&self,
_key_path: Option<&NSString>,
_object: Option<&AnyObject>,
_change: Option<&NSDictionary<NSKeyValueChangeKey, AnyObject>>,
_context: *mut std::ffi::c_void,
) {
crate::boundary::guarded("an appearance change (observe)", (), || {
changed();
})
}
}
);
fn changed() {
GENERATION.with(|g| g.set(g.get() + 1));
emit(Event::AppearanceChanged);
}
thread_local! {
static KVO: UiCell<Option<Retained<AppearanceObserver>>> = const { UiCell::new(None) };
static OBSERVER: UiCell<Option<Retained<ProtocolObject<dyn NSObjectProtocol>>>> = const { UiCell::new(None) };
static GENERATION: Cell<u64> = const { Cell::new(0) };
}
pub fn generation() -> u64 {
GENERATION.with(Cell::get)
}
pub fn observe_appearance() {
if OBSERVER.with_borrow(Option::is_some) {
return;
}
let observer = AppearanceObserver::alloc(mtm()).set_ivars(());
let observer: Retained<AppearanceObserver> = unsafe { msg_send![super(observer), init] };
unsafe {
NSApplication::sharedApplication(mtm()).addObserver_forKeyPath_options_context(
&observer,
&NSString::from_str("effectiveAppearance"),
NSKeyValueObservingOptions::New,
std::ptr::null_mut(),
);
}
KVO.with_borrow_mut(|k| *k = Some(observer));
let block = RcBlock::new(|_: std::ptr::NonNull<NSNotification>| changed());
let center = NSNotificationCenter::defaultCenter();
let token = unsafe {
center.addObserverForName_object_queue_usingBlock(
Some(&NSString::from_str("NSSystemColorsDidChangeNotification")),
None,
None,
&block,
)
};
OBSERVER.with_borrow_mut(|o| *o = Some(token));
}
fn rgba(color: &NSColor) -> Rgba {
let c = color.colorUsingColorSpace(&NSColorSpace::sRGBColorSpace()).unwrap_or_else(|| color.retain());
Rgba { r: c.redComponent() as f32, g: c.greenComponent() as f32, b: c.blueComponent() as f32, a: c.alphaComponent() as f32 }
}
pub fn is_dark() -> bool {
let appearance = NSApplication::sharedApplication(mtm()).effectiveAppearance();
let names = objc2_foundation::NSArray::from_retained_slice(&[
unsafe { objc2_app_kit::NSAppearanceNameAqua }.retain(),
unsafe { objc2_app_kit::NSAppearanceNameDarkAqua }.retain(),
]);
appearance.bestMatchFromAppearancesWithNames(&names).is_some_and(|n: Retained<NSString>| n.to_string().contains("Dark"))
}
pub fn system_colors() -> SystemColors {
let appearance = NSApplication::sharedApplication(mtm()).effectiveAppearance();
let dark = is_dark();
let out = RefCell::new(None);
let block = RcBlock::new(|| {
*out.borrow_mut() = Some(SystemColors {
dark,
window_background: rgba(&NSColor::windowBackgroundColor()),
control_background: rgba(&NSColor::controlBackgroundColor()),
text: rgba(&NSColor::labelColor()),
secondary_text: rgba(&NSColor::secondaryLabelColor()),
separator: rgba(&NSColor::separatorColor()),
accent: rgba(&NSColor::controlAccentColor()),
selected_content_background: rgba(&NSColor::selectedContentBackgroundColor()),
green: rgba(&NSColor::systemGreenColor()),
red: rgba(&NSColor::systemRedColor()),
orange: rgba(&NSColor::systemOrangeColor()),
});
});
appearance.performAsCurrentDrawingAppearance(&block);
drop(block);
out.into_inner().expect("performAsCurrentDrawingAppearance runs the block")
}