Skip to main content

ferrokit_core/
appearance.rs

1//! System appearance and colours (risk 8).
2
3use 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/// An sRGB colour, components in 0..=1.
21#[derive(Debug, Clone, Copy, PartialEq)]
22pub struct Rgba {
23    /// Red, 0..=1.
24    pub r: f32,
25    /// Green, 0..=1.
26    pub g: f32,
27    /// Blue, 0..=1.
28    pub b: f32,
29    /// Alpha, 0..=1.
30    pub a: f32,
31}
32
33/// The system's semantic colours, resolved for the window's current appearance.
34#[derive(Debug, Clone, Copy, PartialEq)]
35pub struct SystemColors {
36    /// Whether the app resolves to a dark appearance.
37    pub dark: bool,
38    /// `windowBackgroundColor`.
39    pub window_background: Rgba,
40    /// `controlBackgroundColor` (e.g. behind table rows).
41    pub control_background: Rgba,
42    /// `labelColor`.
43    pub text: Rgba,
44    /// `secondaryLabelColor`.
45    pub secondary_text: Rgba,
46    /// `separatorColor`.
47    pub separator: Rgba,
48    /// `controlAccentColor` (the user's accent colour).
49    pub accent: Rgba,
50    /// `selectedContentBackgroundColor`.
51    pub selected_content_background: Rgba,
52    /// `systemGreenColor`.
53    pub green: Rgba,
54    /// `systemRedColor`.
55    pub red: Rgba,
56    /// `systemOrangeColor`.
57    pub orange: Rgba,
58}
59
60define_class!(
61    // Observes NSApp.effectiveAppearance (system Dark Mode switches and app
62    // overrides). The window's own appearance can't be used: Iced pins it to
63    // its theme's mode whenever the app sets a theme.
64    #[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
96/// Increments whenever the app's appearance (Dark Mode) or the system colours
97/// (accent) change.
98pub fn generation() -> u64 {
99    GENERATION.with(Cell::get)
100}
101
102/// Starts tracking NSApp's appearance and the system colours, emitting
103/// [`Event::AppearanceChanged`] on changes. Idempotent; [`crate::attach`]
104/// calls it, and a standalone app (no host window) calls it directly.
105pub 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    // SAFETY: the observer is kept alive in KVO for the rest of the program.
112    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    // SAFETY: observer block retained by the notification center; delivered on
125    // the posting (main) thread.
126    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
142/// Whether the app currently resolves to a dark appearance (system setting or
143/// app override).
144pub fn is_dark() -> bool {
145    let appearance = NSApplication::sharedApplication(mtm()).effectiveAppearance();
146    let names = objc2_foundation::NSArray::from_retained_slice(&[
147        // SAFETY: framework string constants.
148        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
154/// Resolves the system colours for the app's appearance.
155pub 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}