native-theme 0.6.1

Cross-platform native theme detection and loading for Rust GUI applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
//! macOS theme reader: reads semantic NSColor values with P3-to-sRGB conversion,
//! resolves both light and dark appearance variants via NSAppearance, reads
//! system/monospace/per-widget fonts via NSFont, scrollbar overlay mode, and
//! accessibility flags.

// Objective-C FFI via objc2 -- no safe alternative
#![allow(unsafe_code)]

#[cfg(all(target_os = "macos", feature = "macos"))]
use block2::RcBlock;
#[cfg(all(target_os = "macos", feature = "macos"))]
use objc2_app_kit::{
    NSAppearance, NSColor, NSColorSpace, NSFont, NSFontTraitsAttribute, NSFontWeightRegular,
    NSFontWeightTrait, NSScroller, NSScrollerStyle, NSWorkspace,
};
#[cfg(all(target_os = "macos", feature = "macos"))]
use objc2_foundation::{NSDictionary, NSNumber, NSString};

/// Convert an NSColor to sRGB and extract RGBA components.
///
/// Converts the color to the sRGB color space via `colorUsingColorSpace`,
/// handling P3-to-sRGB conversion automatically. Returns `None` if the
/// color cannot be converted (e.g., pattern colors).
#[cfg(all(target_os = "macos", feature = "macos"))]
fn nscolor_to_rgba(color: &NSColor, srgb: &NSColorSpace) -> Option<crate::Rgba> {
    let srgb_color = color.colorUsingColorSpace(srgb)?;
    let r = srgb_color.redComponent() as f32;
    let g = srgb_color.greenComponent() as f32;
    let b = srgb_color.blueComponent() as f32;
    let a = srgb_color.alphaComponent() as f32;
    Some(crate::Rgba::from_f32(r, g, b, a))
}

/// Per-widget colors read from appearance-dependent NSColor APIs.
#[cfg(all(target_os = "macos", feature = "macos"))]
#[derive(Default)]
struct PerWidgetColors {
    placeholder: Option<crate::Rgba>,
    selection_inactive: Option<crate::Rgba>,
    alternate_row: Option<crate::Rgba>,
    header_foreground: Option<crate::Rgba>,
    grid_color: Option<crate::Rgba>,
    title_bar_foreground: Option<crate::Rgba>,
}

/// Read all semantic NSColor values for the current appearance context.
///
/// Returns both the ThemeDefaults and per-widget color data. Must be called
/// within an `NSAppearance::performAsCurrentDrawingAppearance` block so that
/// dynamic colors resolve to the correct appearance.
#[cfg(all(target_os = "macos", feature = "macos"))]
fn read_appearance_colors() -> (crate::ThemeDefaults, PerWidgetColors) {
    let srgb = NSColorSpace::sRGBColorSpace();

    // Bind all NSColor temporaries before borrowing them.
    let label_c = NSColor::labelColor();
    let control_accent = NSColor::controlAccentColor();
    let window_bg = NSColor::windowBackgroundColor();
    let control_bg = NSColor::controlBackgroundColor();
    let separator_c = NSColor::separatorColor();
    let secondary_label = NSColor::secondaryLabelColor();
    let shadow_c = NSColor::shadowColor();
    let alt_sel_text = NSColor::alternateSelectedControlTextColor();
    let system_red = NSColor::systemRedColor();
    let system_orange = NSColor::systemOrangeColor();
    let system_green = NSColor::systemGreenColor();
    let system_blue = NSColor::systemBlueColor();
    let sel_content_bg = NSColor::selectedContentBackgroundColor();
    let sel_text = NSColor::selectedTextColor();
    let link_c = NSColor::linkColor();
    let focus_c = NSColor::keyboardFocusIndicatorColor();
    let disabled_text = NSColor::disabledControlTextColor();

    // Additional per-widget color bindings (MACOS-03).
    let placeholder_c = NSColor::placeholderTextColor();
    let unemph_sel_bg = NSColor::unemphasizedSelectedContentBackgroundColor();
    let alt_bg_colors = NSColor::alternatingContentBackgroundColors();
    let header_text_c = NSColor::headerTextColor();
    let grid_c = NSColor::gridColor();
    let frame_text_c = NSColor::windowFrameTextColor();

    let label = nscolor_to_rgba(&label_c, &srgb);

    let defaults = crate::ThemeDefaults {
        accent_color: nscolor_to_rgba(&control_accent, &srgb),
        accent_text_color: nscolor_to_rgba(&alt_sel_text, &srgb),
        background_color: nscolor_to_rgba(&window_bg, &srgb),
        text_color: label,
        surface_color: nscolor_to_rgba(&control_bg, &srgb),
        // platform-facts.md:1051: border.color is separatorColor on macOS.
        border: crate::model::border::DefaultsBorderSpec {
            color: nscolor_to_rgba(&separator_c, &srgb),
            ..Default::default()
        },
        muted_color: nscolor_to_rgba(&secondary_label, &srgb),
        shadow_color: nscolor_to_rgba(&shadow_c, &srgb),
        danger_color: nscolor_to_rgba(&system_red, &srgb),
        danger_text_color: label,
        warning_color: nscolor_to_rgba(&system_orange, &srgb),
        warning_text_color: label,
        success_color: nscolor_to_rgba(&system_green, &srgb),
        success_text_color: label,
        info_color: nscolor_to_rgba(&system_blue, &srgb),
        info_text_color: label,
        selection_background: nscolor_to_rgba(&sel_content_bg, &srgb),
        selection_text_color: nscolor_to_rgba(&sel_text, &srgb),
        selection_inactive_background: nscolor_to_rgba(&unemph_sel_bg, &srgb),
        link_color: nscolor_to_rgba(&link_c, &srgb),
        focus_ring_color: nscolor_to_rgba(&focus_c, &srgb),
        disabled_text_color: nscolor_to_rgba(&disabled_text, &srgb),
        ..Default::default()
    };

    // Alternate row: index 1 of alternatingContentBackgroundColors (index 0 is normal).
    let alternate_row = if alt_bg_colors.count() >= 2 {
        nscolor_to_rgba(&alt_bg_colors.objectAtIndex(1), &srgb)
    } else {
        None
    };

    let per_widget = PerWidgetColors {
        placeholder: nscolor_to_rgba(&placeholder_c, &srgb),
        selection_inactive: nscolor_to_rgba(&unemph_sel_bg, &srgb),
        alternate_row,
        header_foreground: nscolor_to_rgba(&header_text_c, &srgb),
        grid_color: nscolor_to_rgba(&grid_c, &srgb),
        title_bar_foreground: nscolor_to_rgba(&frame_text_c, &srgb),
    };

    (defaults, per_widget)
}

/// Read scrollbar overlay mode from NSScroller.preferredScrollerStyle.
///
/// Returns `true` if the preferred scroller style is overlay, `false` for legacy.
/// Requires main thread (MainThreadMarker).
#[cfg(all(target_os = "macos", feature = "macos"))]
fn read_scrollbar_style(mtm: objc2::MainThreadMarker) -> Option<bool> {
    Some(NSScroller::preferredScrollerStyle(mtm) == NSScrollerStyle::Overlay)
}

/// Read accessibility flags from NSWorkspace.
///
/// Returns (reduce_motion, high_contrast, reduce_transparency). No text-scaling
/// factor: macOS's accessibility text size affects only a few Apple apps, and
/// `preferredFont(forTextStyle:)` still returns fixed sizes
/// (docs/platform-facts.md:1123), so the fonts the reader reads already carry
/// whatever size the system gives them.
#[cfg(all(target_os = "macos", feature = "macos"))]
fn read_accessibility() -> (Option<bool>, Option<bool>, Option<bool>) {
    let workspace = NSWorkspace::sharedWorkspace();
    (
        Some(workspace.accessibilityDisplayShouldReduceMotion()),
        Some(workspace.accessibilityDisplayShouldIncreaseContrast()),
        Some(workspace.accessibilityDisplayShouldReduceTransparency()),
    )
}

/// Map an AppKit font weight (-1.0..1.0) to the nearest CSS weight (100..900).
///
/// Uses the standard AppKit-to-CSS mapping thresholds. Returns `None` if the
/// font descriptor's traits dictionary does not contain the weight key.
#[cfg(all(target_os = "macos", feature = "macos"))]
fn nsfont_weight_to_css(font: &NSFont) -> Option<u16> {
    let descriptor = font.fontDescriptor();
    // Get the traits dictionary from the font descriptor.
    let traits_key: &NSString = unsafe { NSFontTraitsAttribute };
    let traits_obj = descriptor.objectForKey(traits_key)?;
    // Safety: the traits attribute is an NSDictionary<NSFontDescriptorTraitKey, id>
    let traits_dict: &NSDictionary<NSString, objc2::runtime::AnyObject> =
        unsafe { &*(&*traits_obj as *const _ as *const _) };
    let weight_key: &NSString = unsafe { NSFontWeightTrait };
    let weight_obj = traits_dict.objectForKey(weight_key)?;
    // Safety: the weight trait value is an NSNumber wrapping a CGFloat.
    let weight_num: &NSNumber = unsafe { &*(&*weight_obj as *const _ as *const NSNumber) };
    let w = weight_num.doubleValue();

    // Map AppKit weight range to CSS weight buckets.
    let css = if w <= -0.75 {
        100
    } else if w <= -0.35 {
        200
    } else if w <= -0.1 {
        300
    } else if w <= 0.1 {
        400
    } else if w <= 0.27 {
        500
    } else if w <= 0.35 {
        600
    } else if w <= 0.5 {
        700
    } else if w <= 0.6 {
        800
    } else {
        900
    };
    Some(css)
}

/// Build a [`FontSpec`] from an NSFont, extracting family, size, and weight.
#[cfg(all(target_os = "macos", feature = "macos"))]
fn fontspec_from_nsfont(font: &NSFont) -> crate::FontSpec {
    crate::FontSpec {
        family: font
            .familyName()
            .map(|n| std::sync::Arc::from(n.to_string())),
        size: Some(crate::model::font::FontSize::Pt(font.pointSize() as f32)),
        weight: nsfont_weight_to_css(font),
        ..Default::default()
    }
}

/// Read system and monospace font information via NSFont.
///
/// Fonts are appearance-independent, so this only needs to be called once
/// (not per-appearance). Includes CSS weight extraction from the font descriptor.
#[cfg(all(target_os = "macos", feature = "macos"))]
fn read_fonts() -> (crate::FontSpec, crate::FontSpec) {
    let system_size = NSFont::systemFontSize();
    let system_font = NSFont::systemFontOfSize(system_size);
    let mono_font =
        unsafe { NSFont::monospacedSystemFontOfSize_weight(system_size, NSFontWeightRegular) };

    (
        fontspec_from_nsfont(&system_font),
        fontspec_from_nsfont(&mono_font),
    )
}

/// The macOS system UI font as Core Text resolves it: its family name and
/// the file it lives in (egui connector spec §8.2).
#[cfg(all(target_os = "macos", feature = "system-fonts"))]
pub(crate) struct SystemUiFont {
    /// Core Text's family name for the font (`kCTFontFamilyNameAttribute`).
    pub(crate) family: String,
    /// The font file (`kCTFontURLAttribute` as a file path).
    pub(crate) path: std::path::PathBuf,
}

/// Ask Core Text which font is the system UI font — `CTFontUIFontType::System`
/// at the type's default size, no language — and, for `italic`, its italic
/// variant (the upright font where Core Text has none). `None` where Core
/// Text returns none, an attribute is missing or is not the type the
/// attribute documents, or the URL is not a file path. `CTFont::family_name`
/// is not used: its binding `expect`s a non-null result (objc2-core-text
/// 0.3.2 `src/generated/CTFont.rs` lines 977–983).
#[cfg(all(target_os = "macos", feature = "system-fonts"))]
pub(crate) fn system_ui_font(italic: bool) -> Option<SystemUiFont> {
    use objc2_core_foundation::{CFString, CFURL};
    use objc2_core_text::{
        CTFont, CTFontSymbolicTraits, CTFontUIFontType, kCTFontFamilyNameAttribute,
        kCTFontURLAttribute,
    };
    // SAFETY: `CTFontCreateUIFontForLanguage` takes a UI font type, a size
    // (0.0 = the type's default) and an optional language; a null language
    // is documented as allowed, and the binding maps a NULL result to None.
    let upright = unsafe { CTFont::new_ui_font_for_language(CTFontUIFontType::System, 0.0, None) }?;
    let font = if italic {
        // SAFETY: a null matrix is documented as allowed by the binding's
        // safety note; the value and mask both name the italic trait.
        let slanted = unsafe {
            upright.copy_with_symbolic_traits(
                0.0,
                std::ptr::null(),
                CTFontSymbolicTraits::ItalicTrait,
                CTFontSymbolicTraits::ItalicTrait,
            )
        };
        slanted.unwrap_or(upright)
    } else {
        upright
    };
    // SAFETY: the two keys are Core Text's own statics, declared in `extern`
    // blocks; reading them is an FFI read of a constant.
    let (family_key, url_key) = unsafe { (kCTFontFamilyNameAttribute, kCTFontURLAttribute) };
    // SAFETY: `CTFontCopyAttribute` returns a retained reference or NULL,
    // which the binding maps to None; the downcasts check the type id.
    let family = unsafe { font.attribute(family_key) }?
        .downcast::<CFString>()
        .ok()?
        .to_string();
    let path = unsafe { font.attribute(url_key) }?
        .downcast::<CFURL>()
        .ok()?
        .to_file_path()?;
    Some(SystemUiFont { family, path })
}

/// Read per-widget fonts: menu, tooltip, and title bar.
///
/// Appearance-independent -- called once. Returns (menu, tooltip, title_bar).
#[cfg(all(target_os = "macos", feature = "macos"))]
fn read_per_widget_fonts() -> (crate::FontSpec, crate::FontSpec, crate::FontSpec) {
    let menu_font = NSFont::menuFontOfSize(0.0);
    let tooltip_font = NSFont::toolTipsFontOfSize(0.0);
    let title_bar_font = NSFont::titleBarFontOfSize(0.0);

    (
        fontspec_from_nsfont(&menu_font),
        fontspec_from_nsfont(&tooltip_font),
        fontspec_from_nsfont(&title_bar_font),
    )
}

/// Return per-widget defaults populated from macOS HIG sizes.
///
/// Values based on AppKit intrinsic content sizes and Apple Human Interface
/// Guidelines for standard control dimensions.
#[cfg_attr(not(all(target_os = "macos", feature = "macos")), allow(dead_code))]
pub(crate) fn macos_widget_defaults() -> crate::ThemeMode {
    use crate::model::border::WidgetBorderSpec;
    crate::ThemeMode {
        button: crate::ButtonTheme {
            min_height: Some(22.0), // NSButton regular control size
            // platform-facts.md:1171 (§2.3): ~8 (WebKit); the legacy HIG 12 is
            // inter-button spacing (platform-facts.md:195)
            border: Some(WidgetBorderSpec {
                padding_left: Some(8.0),
                padding_right: Some(8.0),
                ..Default::default()
            }),
            ..Default::default()
        },
        checkbox: crate::CheckboxTheme {
            indicator_width: Some(14.0), // NSButton switch type
            label_gap: Some(4.0),
            ..Default::default()
        },
        input: crate::InputTheme {
            min_height: Some(22.0), // NSTextField regular
            // platform-facts.md:1196 (§2.4)
            border: Some(WidgetBorderSpec {
                padding_left: Some(4.0),
                padding_right: Some(4.0),
                ..Default::default()
            }),
            ..Default::default()
        },
        scrollbar: crate::ScrollbarTheme {
            groove_width: Some(15.0), // NSScroller legacy style
            thumb_width: Some(7.0),   // Overlay style
            ..Default::default()
        },
        slider: crate::SliderTheme {
            track_height: Some(5.0), // platform-facts.md:1292 (§2.9): NSSlider
            thumb_diameter: Some(21.0),
            ..Default::default()
        },
        progress_bar: crate::ProgressBarTheme {
            track_height: Some(6.0), // NSProgressIndicator regular
            ..Default::default()
        },
        tab: crate::TabTheme {
            min_height: Some(24.0), // NSTabView
            // platform-facts.md:1318 (§2.11)
            border: Some(WidgetBorderSpec {
                padding_left: Some(12.0),
                padding_right: Some(12.0),
                ..Default::default()
            }),
            ..Default::default()
        },
        menu: crate::MenuTheme {
            row_height: Some(22.0), // Standard menu item
            // platform-facts.md:1235 (§2.6)
            border: Some(WidgetBorderSpec {
                padding_left: Some(12.0),
                padding_right: Some(12.0),
                ..Default::default()
            }),
            ..Default::default()
        },
        tooltip: crate::TooltipTheme {
            // platform-facts.md:1257-1258 (§2.7)
            border: Some(WidgetBorderSpec {
                padding_left: Some(4.0),
                padding_right: Some(4.0),
                padding_top: Some(4.0),
                padding_bottom: Some(4.0),
                ..Default::default()
            }),
            ..Default::default()
        },
        list: crate::ListTheme {
            row_height: Some(24.0), // NSTableView row
            // platform-facts.md:1390 (§2.15)
            border: Some(WidgetBorderSpec {
                padding_left: Some(4.0),
                padding_right: Some(4.0),
                ..Default::default()
            }),
            ..Default::default()
        },
        toolbar: crate::ToolbarTheme {
            bar_height: Some(38.0), // platform-facts.md:1351 (§2.13): NSToolbar
            item_gap: Some(8.0),    // platform-facts.md:1352 (§2.13): AppKit
            ..Default::default()
        },
        splitter: crate::SplitterTheme {
            divider_width: Some(9.0), // NSSplitView divider
            ..Default::default()
        },
        ..Default::default()
    }
}

/// Per-widget font and text scale data passed to [`build_theme`].
///
/// Collected once (appearance-independent) and applied to both variants.
#[cfg_attr(not(all(target_os = "macos", feature = "macos")), allow(dead_code))]
struct WidgetFontData {
    menu_font: crate::FontSpec,
    tooltip_font: crate::FontSpec,
    title_bar_font: crate::FontSpec,
}

/// Testable core: assemble a Theme from pre-read color and font data.
///
/// Takes pre-resolved ThemeDefaults for both light and dark variants, plus
/// per-widget font data. Both variants are always
/// populated (unlike KDE/GNOME/Windows which populate only the active one),
/// since macOS can resolve colors for both appearances.
#[cfg_attr(not(all(target_os = "macos", feature = "macos")), allow(dead_code))]
fn build_theme(
    light_defaults: crate::ThemeDefaults,
    dark_defaults: crate::ThemeDefaults,
    widget_fonts: &WidgetFontData,
) -> crate::Theme {
    let widget_defaults = macos_widget_defaults();

    let mut light_variant = widget_defaults.clone();
    light_variant.defaults = light_defaults;
    light_variant.menu.font = Some(widget_fonts.menu_font.clone());
    light_variant.tooltip.font = Some(widget_fonts.tooltip_font.clone());
    light_variant.window.title_bar_font = Some(widget_fonts.title_bar_font.clone());

    let mut dark_variant = widget_defaults;
    dark_variant.defaults = dark_defaults;
    dark_variant.menu.font = Some(widget_fonts.menu_font.clone());
    dark_variant.tooltip.font = Some(widget_fonts.tooltip_font.clone());
    dark_variant.window.title_bar_font = Some(widget_fonts.title_bar_font.clone());

    crate::Theme {
        name: "macOS".into(),
        light: Some(light_variant),
        dark: Some(dark_variant),
        layout: crate::LayoutTheme::default(),
        icon_set: Some(crate::IconSet::SfSymbols),
        // macOS uses the same icon theme ("sf-symbols") for both variants; the
        // Theme-level field is populated via the merged macos-sonoma preset.
        icon_theme: None,
    }
}

/// Read the current macOS theme, resolving both light and dark appearance variants.
///
/// Uses `NSAppearance::performAsCurrentDrawingAppearance` (macOS 11+) to scope
/// semantic color resolution to each appearance. Reads ~25 NSColor semantic
/// colors per variant with P3-to-sRGB conversion, per-widget fonts with weight,
/// scrollbar overlay mode, and accessibility flags.
///
/// # Errors
///
/// Returns `Error::ReaderFailed` if neither light nor dark appearance can be created
/// (extremely unlikely on any macOS version that supports these APIs).
///
/// Internal reader dispatched through the [`crate::reader::ThemeReader`] trait
/// by [`pipeline::select_reader`]; external consumers should use
/// [`SystemTheme::from_system()`](crate::SystemTheme::from_system).
///
/// The body contains no `.await` points — wrapping a sync implementation in
/// an async trait method produces a future that resolves immediately.
#[cfg(all(target_os = "macos", feature = "macos"))]
pub(crate) struct MacosReader;

#[cfg(all(target_os = "macos", feature = "macos"))]
#[async_trait::async_trait]
impl crate::reader::ThemeReader for MacosReader {
    async fn read(&self) -> crate::Result<crate::ReaderResult> {
        read_macos()
    }
}

#[cfg(all(target_os = "macos", feature = "macos"))]
fn read_macos() -> crate::Result<crate::ReaderResult> {
    let light_name = NSString::from_str("NSAppearanceNameAqua");
    let dark_name = NSString::from_str("NSAppearanceNameDarkAqua");

    let light_appearance = NSAppearance::appearanceNamed(&light_name);
    let dark_appearance = NSAppearance::appearanceNamed(&dark_name);

    if light_appearance.is_none() && dark_appearance.is_none() {
        return Err(crate::Error::ReaderFailed {
            reader: "macos",
            source: "neither light nor dark NSAppearance could be created".into(),
        });
    }

    // Read appearance-independent data once.
    let (font, mono_font) = read_fonts();
    let (menu_font, tooltip_font, title_bar_font) = read_per_widget_fonts();
    let widget_fonts = WidgetFontData {
        menu_font,
        tooltip_font,
        title_bar_font,
    };

    // Type alias for the appearance-block data.
    type AppearanceData = (crate::ThemeDefaults, PerWidgetColors);

    let (light_defaults, light_pw) = if let Some(app) = &light_appearance {
        let data = std::cell::RefCell::new(None::<AppearanceData>);
        {
            let block = RcBlock::new(|| {
                *data.borrow_mut() = Some(read_appearance_colors());
            });
            app.performAsCurrentDrawingAppearance(&block);
        }
        let (mut d, pw) = data.into_inner().unwrap_or_default();
        d.font = font.clone();
        d.mono_font = mono_font.clone();
        (d, Some(pw))
    } else {
        (crate::ThemeDefaults::default(), None)
    };

    let (dark_defaults, dark_pw) = if let Some(app) = &dark_appearance {
        let data = std::cell::RefCell::new(None::<AppearanceData>);
        {
            let block = RcBlock::new(|| {
                *data.borrow_mut() = Some(read_appearance_colors());
            });
            app.performAsCurrentDrawingAppearance(&block);
        }
        let (mut d, pw) = data.into_inner().unwrap_or_default();
        d.font = font;
        d.mono_font = mono_font;
        (d, Some(pw))
    } else {
        (crate::ThemeDefaults::default(), None)
    };

    let mut theme = build_theme(light_defaults, dark_defaults, &widget_fonts);

    // Apply per-widget colors (appearance-dependent, per variant).
    if let (Some(v), Some(pw)) = (&mut theme.light, light_pw) {
        v.input.placeholder_color = pw.placeholder;
        v.input.selection_background = pw.selection_inactive;
        v.list.alternate_row_background = pw.alternate_row;
        if let Some(color) = pw.header_foreground {
            v.list.header_font.get_or_insert_default().color = Some(color);
        }
        v.list.grid_color = pw.grid_color;
        if let Some(color) = pw.title_bar_foreground {
            v.window.title_bar_font.get_or_insert_default().color = Some(color);
        }
    }
    if let (Some(v), Some(pw)) = (&mut theme.dark, dark_pw) {
        v.input.placeholder_color = pw.placeholder;
        v.input.selection_background = pw.selection_inactive;
        v.list.alternate_row_background = pw.alternate_row;
        if let Some(color) = pw.header_foreground {
            v.list.header_font.get_or_insert_default().color = Some(color);
        }
        v.list.grid_color = pw.grid_color;
        if let Some(color) = pw.title_bar_foreground {
            v.window.title_bar_font.get_or_insert_default().color = Some(color);
        }
    }

    // Scrollbar overlay mode (appearance-independent, requires main thread).
    let overlay_mode = objc2::MainThreadMarker::new().and_then(read_scrollbar_style);
    if let Some(v) = &mut theme.light {
        v.scrollbar.overlay_mode = overlay_mode;
    }
    if let Some(v) = &mut theme.dark {
        v.scrollbar.overlay_mode = overlay_mode;
    }

    // Accessibility flags (appearance-independent).
    let (reduce_motion, high_contrast, reduce_transparency) = read_accessibility();
    let mut acc = crate::AccessibilityPreferences::default();
    if let Some(rm) = reduce_motion {
        acc.reduce_motion = rm;
    }
    if let Some(hc) = high_contrast {
        acc.high_contrast = hc;
    }
    if let Some(rt) = reduce_transparency {
        acc.reduce_transparency = rt;
    }

    // macOS coordinate system uses 72 DPI as its base.
    // NSFont.pointSize() returns Apple points where 1pt = 1 logical pixel,
    // so the formula pt * 72/72 = pt (identity) is correct.
    let font_dpi = Some(72.0_f32);

    let output = crate::ReaderOutput::Dual {
        light: Box::new(theme.light.unwrap_or_default()),
        dark: Box::new(theme.dark.unwrap_or_default()),
    };

    Ok(crate::ReaderResult {
        output,
        name: theme.name,
        icon_set: theme.icon_set,
        layout: theme.layout,
        font_dpi,
        accessibility: acc,
    })
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::model::font::FontSize;

    fn sample_widget_fonts() -> WidgetFontData {
        use crate::model::font::FontSize;
        WidgetFontData {
            menu_font: crate::FontSpec {
                family: Some("SF Pro".into()),
                size: Some(FontSize::Pt(14.0)),
                weight: Some(400),
                ..Default::default()
            },
            tooltip_font: crate::FontSpec {
                family: Some("SF Pro".into()),
                size: Some(FontSize::Pt(11.0)),
                weight: Some(400),
                ..Default::default()
            },
            title_bar_font: crate::FontSpec {
                family: Some("SF Pro".into()),
                size: Some(FontSize::Pt(13.0)),
                weight: Some(700),
                ..Default::default()
            },
        }
    }

    fn sample_light_defaults() -> crate::ThemeDefaults {
        use crate::model::font::FontSize;
        crate::ThemeDefaults {
            accent_color: Some(crate::Rgba::rgb(0, 122, 255)),
            background_color: Some(crate::Rgba::rgb(246, 246, 246)),
            text_color: Some(crate::Rgba::rgb(0, 0, 0)),
            surface_color: Some(crate::Rgba::rgb(255, 255, 255)),
            border: crate::model::border::DefaultsBorderSpec {
                color: Some(crate::Rgba::rgb(200, 200, 200)),
                ..Default::default()
            },
            font: crate::FontSpec {
                family: Some("SF Pro".into()),
                size: Some(FontSize::Pt(13.0)),
                weight: None,
                ..Default::default()
            },
            mono_font: crate::FontSpec {
                family: Some("SF Mono".into()),
                size: Some(FontSize::Pt(13.0)),
                weight: None,
                ..Default::default()
            },
            ..Default::default()
        }
    }

    fn sample_dark_defaults() -> crate::ThemeDefaults {
        use crate::model::font::FontSize;
        crate::ThemeDefaults {
            accent_color: Some(crate::Rgba::rgb(10, 132, 255)),
            background_color: Some(crate::Rgba::rgb(30, 30, 30)),
            text_color: Some(crate::Rgba::rgb(255, 255, 255)),
            surface_color: Some(crate::Rgba::rgb(44, 44, 46)),
            border: crate::model::border::DefaultsBorderSpec {
                color: Some(crate::Rgba::rgb(56, 56, 58)),
                ..Default::default()
            },
            font: crate::FontSpec {
                family: Some("SF Pro".into()),
                size: Some(FontSize::Pt(13.0)),
                weight: None,
                ..Default::default()
            },
            ..Default::default()
        }
    }

    #[test]
    fn build_theme_populates_both_variants() {
        let theme = build_theme(
            sample_light_defaults(),
            sample_dark_defaults(),
            &sample_widget_fonts(),
        );

        assert!(theme.light.is_some(), "light variant should be Some");
        assert!(theme.dark.is_some(), "dark variant should be Some");

        // Colors should differ between variants
        let light = theme.light.as_ref().unwrap();
        let dark = theme.dark.as_ref().unwrap();
        assert_ne!(light.defaults.accent_color, dark.defaults.accent_color);
        assert_ne!(
            light.defaults.background_color,
            dark.defaults.background_color
        );

        // Fonts should be identical in both
        assert_eq!(light.defaults.font, dark.defaults.font);
    }

    #[test]
    fn build_theme_name_is_macos() {
        let theme = build_theme(
            sample_light_defaults(),
            sample_dark_defaults(),
            &sample_widget_fonts(),
        );
        assert_eq!(theme.name, "macOS");
    }

    #[test]
    fn build_theme_fonts_populated() {
        use crate::model::font::FontSize;
        let defaults = crate::ThemeDefaults {
            font: crate::FontSpec {
                family: Some("SF Pro".into()),
                size: Some(FontSize::Pt(13.0)),
                weight: None,
                ..Default::default()
            },
            mono_font: crate::FontSpec {
                family: Some("SF Mono".into()),
                size: Some(FontSize::Pt(13.0)),
                weight: None,
                ..Default::default()
            },
            ..Default::default()
        };

        let theme = build_theme(defaults.clone(), defaults, &sample_widget_fonts());

        let light = theme.light.as_ref().unwrap();
        assert_eq!(light.defaults.font.family.as_deref(), Some("SF Pro"));
        assert_eq!(light.defaults.font.size, Some(FontSize::Pt(13.0)));
        assert_eq!(light.defaults.mono_font.family.as_deref(), Some("SF Mono"));
        assert_eq!(light.defaults.mono_font.size, Some(FontSize::Pt(13.0)));

        let dark = theme.dark.as_ref().unwrap();
        assert_eq!(dark.defaults.font.family.as_deref(), Some("SF Pro"));
        assert_eq!(dark.defaults.font.size, Some(FontSize::Pt(13.0)));
    }

    #[test]
    fn build_theme_defaults_empty_produces_nonempty_variant() {
        let theme = build_theme(
            crate::ThemeDefaults::default(),
            crate::ThemeDefaults::default(),
            &sample_widget_fonts(),
        );

        let light = theme.light.as_ref().unwrap();
        // Variant should not be empty because widget defaults are populated
        assert!(
            !light.is_empty(),
            "light variant should have widget defaults"
        );

        let dark = theme.dark.as_ref().unwrap();
        assert!(!dark.is_empty(), "dark variant should have widget defaults");
    }

    #[test]
    fn build_theme_colors_propagated_correctly() {
        let blue = crate::Rgba::rgb(0, 122, 255);
        let red = crate::Rgba::rgb(255, 59, 48);

        let light_defaults = crate::ThemeDefaults {
            accent_color: Some(blue),
            ..Default::default()
        };
        let dark_defaults = crate::ThemeDefaults {
            accent_color: Some(red),
            ..Default::default()
        };

        let theme = build_theme(light_defaults, dark_defaults, &sample_widget_fonts());

        let light = theme.light.as_ref().unwrap();
        let dark = theme.dark.as_ref().unwrap();

        assert_eq!(light.defaults.accent_color, Some(blue));
        assert_eq!(dark.defaults.accent_color, Some(red));
    }

    #[test]
    fn macos_widget_defaults_spot_check() {
        let wv = macos_widget_defaults();
        assert_eq!(
            wv.button.min_height,
            Some(22.0),
            "NSButton regular control size"
        );
        assert_eq!(
            wv.scrollbar.groove_width,
            Some(15.0),
            "NSScroller legacy style"
        );
        assert_eq!(
            wv.checkbox.indicator_width,
            Some(14.0),
            "NSButton switch type"
        );
        assert_eq!(
            wv.slider.thumb_diameter,
            Some(21.0),
            "NSSlider circular knob"
        );
        assert_eq!(wv.slider.track_height, Some(5.0), "NSSlider track");
    }

    #[test]
    fn build_theme_has_icon_set_sf_symbols() {
        let theme = build_theme(
            sample_light_defaults(),
            sample_dark_defaults(),
            &sample_widget_fonts(),
        );

        // icon_set is now on Theme, shared across variants
        assert_eq!(theme.icon_set, Some(crate::IconSet::SfSymbols));
    }

    #[test]
    fn build_theme_per_widget_fonts_populated() {
        let wf = sample_widget_fonts();
        let theme = build_theme(sample_light_defaults(), sample_dark_defaults(), &wf);

        let light = theme.light.as_ref().unwrap();
        assert_eq!(
            light.menu.font.as_ref().unwrap().size,
            Some(FontSize::Pt(14.0)),
            "menu font size"
        );
        assert_eq!(
            light.tooltip.font.as_ref().unwrap().size,
            Some(FontSize::Pt(11.0)),
            "tooltip font size"
        );
        assert_eq!(
            light.window.title_bar_font.as_ref().unwrap().weight,
            Some(700),
            "title bar font weight"
        );

        // Both variants should have the same per-widget fonts
        let dark = theme.dark.as_ref().unwrap();
        assert_eq!(light.menu.font, dark.menu.font);
        assert_eq!(light.tooltip.font, dark.tooltip.font);
        assert_eq!(light.window.title_bar_font, dark.window.title_bar_font);
    }

    #[test]
    fn build_theme_per_widget_colors_not_populated_by_build() {
        // build_theme does not populate per-widget colors -- that's done by
        // from_macos() after build_theme returns. Verify they start as None.
        let theme = build_theme(
            sample_light_defaults(),
            sample_dark_defaults(),
            &sample_widget_fonts(),
        );
        let light = theme.light.as_ref().unwrap();
        assert!(
            light.input.placeholder_color.is_none(),
            "placeholder_color starts None (set by from_macos)"
        );
        assert!(
            light.list.alternate_row_background.is_none(),
            "alternate_row_background starts None"
        );
        assert!(light.list.header_font.is_none(), "header_font starts None");
        assert!(light.list.grid_color.is_none(), "grid_color starts None");
    }

    #[test]
    fn build_theme_scrollbar_overlay_not_set_by_build() {
        // Scrollbar overlay mode is set after build_theme by from_macos().
        let theme = build_theme(
            sample_light_defaults(),
            sample_dark_defaults(),
            &sample_widget_fonts(),
        );
        let light = theme.light.as_ref().unwrap();
        assert!(
            light.scrollbar.overlay_mode.is_none(),
            "overlay_mode starts None (set by from_macos)"
        );
    }

    #[test]
    fn build_theme_dialog_button_order_not_set_by_build() {
        // Dialog button order is set after build_theme by from_macos().
        let theme = build_theme(
            sample_light_defaults(),
            sample_dark_defaults(),
            &sample_widget_fonts(),
        );
        let light = theme.light.as_ref().unwrap();
        assert!(
            light.dialog.button_order.is_none(),
            "button_order starts None (set by from_macos)"
        );
    }

    #[test]
    fn build_theme_accessibility_not_set_by_build() {
        // Accessibility flags are set after build_theme by from_macos().
        let theme = build_theme(
            sample_light_defaults(),
            sample_dark_defaults(),
            &sample_widget_fonts(),
        );
        // Accessibility fields are no longer on ThemeDefaults;
        // they live on AccessibilityPreferences (constructed by pipeline).
        assert!(theme.light.is_some());
    }

    #[test]
    fn test_macos_resolve_validate() {
        // Load macOS-sonoma preset as base (provides full color/geometry/spacing).
        let mut base = crate::Theme::preset("macos-sonoma").unwrap();
        // Build reader output with sample data (simulates from_macos() on real hardware).
        let reader_output = build_theme(
            sample_light_defaults(),
            sample_dark_defaults(),
            &sample_widget_fonts(),
        );
        // Merge reader output on top of preset.
        base.merge(&reader_output);

        // Test light variant.
        let mut light = base
            .light
            .clone()
            .expect("light variant should exist after merge");
        light.resolve_all();
        let resolved = light.validate().unwrap_or_else(|e| {
            panic!("macOS resolve/validate pipeline failed (light): {e}");
        });

        // Spot-check: reader-sourced fields present.
        assert_eq!(
            resolved.defaults.accent_color,
            crate::Rgba::rgb(0, 122, 255),
            "accent should be from macOS reader"
        );
        assert_eq!(
            resolved.defaults.font.family.as_ref(),
            "SF Pro",
            "font family should be from macOS reader"
        );
        // icon_set is now on Theme/SystemTheme, not on ResolvedTheme

        // Test dark variant too.
        let mut dark = base
            .dark
            .clone()
            .expect("dark variant should exist after merge");
        dark.resolve_all();
        let resolved_dark = dark.validate().unwrap_or_else(|e| {
            panic!("macOS resolve/validate pipeline failed (dark): {e}");
        });
        assert_eq!(
            resolved_dark.defaults.accent_color,
            crate::Rgba::rgb(10, 132, 255),
            "dark accent should be from macOS reader"
        );
    }

    // === Border colour (platform-facts.md:1051: separatorColor) ===

    #[cfg(all(target_os = "macos", feature = "macos"))]
    #[test]
    fn read_appearance_colors_reads_border_color_from_separator_color() {
        let (defaults, _) = super::read_appearance_colors();
        assert!(
            defaults.border.color.is_some(),
            "defaults.border.color should be read from NSColor.separatorColor"
        );
    }

    // === Plan 94-03 (G8): MacosReader ThemeReader impl ===
    //
    // Locks the G8 contract on the macOS side: a unit struct `MacosReader`
    // exists at the module root and implements `crate::reader::ThemeReader`.
    // Before Task 2 lands, this fails to compile (`no struct MacosReader` /
    // `unresolved module crate::reader`).
    //
    // The trait object coercion is the structural object-safety probe. Body
    // is gated on `cfg(all(target_os = "macos", feature = "macos"))` so that
    // the non-macOS build only compile-checks the trait path reference.
    #[test]
    fn macos_reader_exists() {
        // Reference the trait path once so name resolution fires on all
        // targets regardless of whether the MacosReader struct is compiled.
        let _: Option<&dyn crate::reader::ThemeReader> = None;

        #[cfg(all(target_os = "macos", feature = "macos"))]
        {
            let r: Box<dyn crate::reader::ThemeReader> = Box::new(super::MacosReader);
            let _ = &r;
        }
    }
}