ferrokit_core/
appearance.rs1use crate::kept::{UiCell, UiLocal};
4use std::cell::{Cell, RefCell};
5
6use block2::RcBlock;
7use objc2::Message as _;
8use objc2::rc::Retained;
9use objc2::runtime::{AnyObject, NSObject, ProtocolObject};
10use objc2::{MainThreadOnly, define_class, msg_send};
11use objc2_app_kit::{NSApplication, NSColor, NSColorSpace};
12use objc2_foundation::{
13 NSDictionary, NSKeyValueChangeKey, NSKeyValueObservingOptions, NSNotification, NSNotificationCenter,
14 NSObjectNSKeyValueObserverRegistration, NSObjectProtocol, NSString,
15};
16
17use crate::events::{Event, emit};
18use crate::host::mtm;
19
20#[derive(Debug, Clone, Copy, PartialEq)]
22pub struct Rgba {
23 pub r: f32,
25 pub g: f32,
27 pub b: f32,
29 pub a: f32,
31}
32
33#[derive(Debug, Clone, Copy, PartialEq)]
35pub struct SystemColors {
36 pub dark: bool,
38 pub window_background: Rgba,
40 pub control_background: Rgba,
42 pub text: Rgba,
44 pub secondary_text: Rgba,
46 pub separator: Rgba,
48 pub accent: Rgba,
50 pub selected_content_background: Rgba,
52 pub green: Rgba,
54 pub red: Rgba,
56 pub orange: Rgba,
58}
59
60define_class!(
61 #[unsafe(super(NSObject))]
65 #[thread_kind = MainThreadOnly]
66 #[name = "FerrokitCoreAppearanceObserver"]
67 struct AppearanceObserver;
68
69 impl AppearanceObserver {
70 #[unsafe(method(observeValueForKeyPath:ofObject:change:context:))]
71 fn observe(
72 &self,
73 _key_path: Option<&NSString>,
74 _object: Option<&AnyObject>,
75 _change: Option<&NSDictionary<NSKeyValueChangeKey, AnyObject>>,
76 _context: *mut std::ffi::c_void,
77 ) {
78 crate::boundary::guarded("an appearance change (observe)", (), || {
79 changed();
80 })
81 }
82 }
83);
84
85fn changed() {
86 GENERATION.with(|g| g.set(g.get() + 1));
87 emit(Event::AppearanceChanged);
88}
89
90thread_local! {
91 static KVO: UiCell<Option<Retained<AppearanceObserver>>> = const { UiCell::new(None) };
92 static OBSERVER: UiCell<Option<Retained<ProtocolObject<dyn NSObjectProtocol>>>> = const { UiCell::new(None) };
93 static GENERATION: Cell<u64> = const { Cell::new(0) };
94}
95
96pub fn generation() -> u64 {
99 GENERATION.with(Cell::get)
100}
101
102pub fn observe_appearance() {
106 if OBSERVER.with_borrow(Option::is_some) {
107 return;
108 }
109 let observer = AppearanceObserver::alloc(mtm()).set_ivars(());
110 let observer: Retained<AppearanceObserver> = unsafe { msg_send![super(observer), init] };
111 unsafe {
113 NSApplication::sharedApplication(mtm()).addObserver_forKeyPath_options_context(
114 &observer,
115 &NSString::from_str("effectiveAppearance"),
116 NSKeyValueObservingOptions::New,
117 std::ptr::null_mut(),
118 );
119 }
120 KVO.with_borrow_mut(|k| *k = Some(observer));
121
122 let block = RcBlock::new(|_: std::ptr::NonNull<NSNotification>| changed());
123 let center = NSNotificationCenter::defaultCenter();
124 let token = unsafe {
127 center.addObserverForName_object_queue_usingBlock(
128 Some(&NSString::from_str("NSSystemColorsDidChangeNotification")),
129 None,
130 None,
131 &block,
132 )
133 };
134 OBSERVER.with_borrow_mut(|o| *o = Some(token));
135}
136
137fn rgba(color: &NSColor) -> Rgba {
138 let c = color.colorUsingColorSpace(&NSColorSpace::sRGBColorSpace()).unwrap_or_else(|| color.retain());
139 Rgba { r: c.redComponent() as f32, g: c.greenComponent() as f32, b: c.blueComponent() as f32, a: c.alphaComponent() as f32 }
140}
141
142pub fn is_dark() -> bool {
145 let appearance = NSApplication::sharedApplication(mtm()).effectiveAppearance();
146 let names = objc2_foundation::NSArray::from_retained_slice(&[
147 unsafe { objc2_app_kit::NSAppearanceNameAqua }.retain(),
149 unsafe { objc2_app_kit::NSAppearanceNameDarkAqua }.retain(),
150 ]);
151 appearance.bestMatchFromAppearancesWithNames(&names).is_some_and(|n: Retained<NSString>| n.to_string().contains("Dark"))
152}
153
154pub fn system_colors() -> SystemColors {
156 let appearance = NSApplication::sharedApplication(mtm()).effectiveAppearance();
157 let dark = is_dark();
158 let out = RefCell::new(None);
159 let block = RcBlock::new(|| {
160 *out.borrow_mut() = Some(SystemColors {
161 dark,
162 window_background: rgba(&NSColor::windowBackgroundColor()),
163 control_background: rgba(&NSColor::controlBackgroundColor()),
164 text: rgba(&NSColor::labelColor()),
165 secondary_text: rgba(&NSColor::secondaryLabelColor()),
166 separator: rgba(&NSColor::separatorColor()),
167 accent: rgba(&NSColor::controlAccentColor()),
168 selected_content_background: rgba(&NSColor::selectedContentBackgroundColor()),
169 green: rgba(&NSColor::systemGreenColor()),
170 red: rgba(&NSColor::systemRedColor()),
171 orange: rgba(&NSColor::systemOrangeColor()),
172 });
173 });
174 appearance.performAsCurrentDrawingAppearance(&block);
175 drop(block);
176 out.into_inner().expect("performAsCurrentDrawingAppearance runs the block")
177}