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            changed();
79        }
80    }
81);
82
83fn changed() {
84    GENERATION.with(|g| g.set(g.get() + 1));
85    emit(Event::AppearanceChanged);
86}
87
88thread_local! {
89    static KVO: UiCell<Option<Retained<AppearanceObserver>>> = const { UiCell::new(None) };
90    static OBSERVER: UiCell<Option<Retained<ProtocolObject<dyn NSObjectProtocol>>>> = const { UiCell::new(None) };
91    static GENERATION: Cell<u64> = const { Cell::new(0) };
92}
93
94/// Increments whenever the app's appearance (Dark Mode) or the system colours
95/// (accent) change.
96pub fn generation() -> u64 {
97    GENERATION.with(Cell::get)
98}
99
100/// Starts tracking NSApp's appearance and the system colours, emitting
101/// [`Event::AppearanceChanged`] on changes. Idempotent; [`crate::attach`]
102/// calls it, and a standalone app (no host window) calls it directly.
103pub fn observe_appearance() {
104    if OBSERVER.with_borrow(Option::is_some) {
105        return;
106    }
107    let observer = AppearanceObserver::alloc(mtm()).set_ivars(());
108    let observer: Retained<AppearanceObserver> = unsafe { msg_send![super(observer), init] };
109    // SAFETY: the observer is kept alive in KVO for the rest of the program.
110    unsafe {
111        NSApplication::sharedApplication(mtm()).addObserver_forKeyPath_options_context(
112            &observer,
113            &NSString::from_str("effectiveAppearance"),
114            NSKeyValueObservingOptions::New,
115            std::ptr::null_mut(),
116        );
117    }
118    KVO.with_borrow_mut(|k| *k = Some(observer));
119
120    let block = RcBlock::new(|_: std::ptr::NonNull<NSNotification>| changed());
121    let center = NSNotificationCenter::defaultCenter();
122    // SAFETY: observer block retained by the notification center; delivered on
123    // the posting (main) thread.
124    let token = unsafe {
125        center.addObserverForName_object_queue_usingBlock(
126            Some(&NSString::from_str("NSSystemColorsDidChangeNotification")),
127            None,
128            None,
129            &block,
130        )
131    };
132    OBSERVER.with_borrow_mut(|o| *o = Some(token));
133}
134
135fn rgba(color: &NSColor) -> Rgba {
136    let c = color.colorUsingColorSpace(&NSColorSpace::sRGBColorSpace()).unwrap_or_else(|| color.retain());
137    Rgba { r: c.redComponent() as f32, g: c.greenComponent() as f32, b: c.blueComponent() as f32, a: c.alphaComponent() as f32 }
138}
139
140/// Whether the app currently resolves to a dark appearance (system setting or
141/// app override).
142pub fn is_dark() -> bool {
143    let appearance = NSApplication::sharedApplication(mtm()).effectiveAppearance();
144    let names = objc2_foundation::NSArray::from_retained_slice(&[
145        // SAFETY: framework string constants.
146        unsafe { objc2_app_kit::NSAppearanceNameAqua }.retain(),
147        unsafe { objc2_app_kit::NSAppearanceNameDarkAqua }.retain(),
148    ]);
149    appearance.bestMatchFromAppearancesWithNames(&names).is_some_and(|n: Retained<NSString>| n.to_string().contains("Dark"))
150}
151
152/// Resolves the system colours for the app's appearance.
153pub fn system_colors() -> SystemColors {
154    let appearance = NSApplication::sharedApplication(mtm()).effectiveAppearance();
155    let dark = is_dark();
156    let out = RefCell::new(None);
157    let block = RcBlock::new(|| {
158        *out.borrow_mut() = Some(SystemColors {
159            dark,
160            window_background: rgba(&NSColor::windowBackgroundColor()),
161            control_background: rgba(&NSColor::controlBackgroundColor()),
162            text: rgba(&NSColor::labelColor()),
163            secondary_text: rgba(&NSColor::secondaryLabelColor()),
164            separator: rgba(&NSColor::separatorColor()),
165            accent: rgba(&NSColor::controlAccentColor()),
166            selected_content_background: rgba(&NSColor::selectedContentBackgroundColor()),
167            green: rgba(&NSColor::systemGreenColor()),
168            red: rgba(&NSColor::systemRedColor()),
169            orange: rgba(&NSColor::systemOrangeColor()),
170        });
171    });
172    appearance.performAsCurrentDrawingAppearance(&block);
173    drop(block);
174    out.into_inner().expect("performAsCurrentDrawingAppearance runs the block")
175}