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
//! Bundled theme presets and TOML serialization API.
//!
//! Provides 16 user-facing built-in presets embedded at compile time:
//! 6 platform (kde-breeze, adwaita, windows-11, macos-sonoma, material,
//! ios) and 10 community (Catppuccin 4 flavors, Nord, Dracula, Gruvbox,
//! Solarized, Tokyo Night, One Dark), plus 4 internal live presets
//! (no colours or font families: geometry, metrics and sizes, used by the
//! OS-first pipeline) and functions for
//! loading themes from TOML strings and files.

use std::borrow::Cow;
use std::collections::HashMap;
use std::path::Path;
use std::sync::LazyLock;

use crate::{Error, Result, Theme};

/// All preset entries (name + embedded TOML source), parsed once into a HashMap.
///
/// To add a new preset, add it here and (if user-facing) to [`PRESET_NAMES`].
const PRESET_ENTRIES: &[(&str, &str)] = &[
    // Platform presets
    ("kde-breeze", include_str!("presets/kde-breeze.toml")),
    ("adwaita", include_str!("presets/adwaita.toml")),
    ("windows-11", include_str!("presets/windows-11.toml")),
    ("macos-sonoma", include_str!("presets/macos-sonoma.toml")),
    ("material", include_str!("presets/material.toml")),
    ("ios", include_str!("presets/ios.toml")),
    // Community presets
    (
        "catppuccin-latte",
        include_str!("presets/catppuccin-latte.toml"),
    ),
    (
        "catppuccin-frappe",
        include_str!("presets/catppuccin-frappe.toml"),
    ),
    (
        "catppuccin-macchiato",
        include_str!("presets/catppuccin-macchiato.toml"),
    ),
    (
        "catppuccin-mocha",
        include_str!("presets/catppuccin-mocha.toml"),
    ),
    ("nord", include_str!("presets/nord.toml")),
    ("dracula", include_str!("presets/dracula.toml")),
    ("gruvbox", include_str!("presets/gruvbox.toml")),
    ("solarized", include_str!("presets/solarized.toml")),
    ("tokyo-night", include_str!("presets/tokyo-night.toml")),
    ("one-dark", include_str!("presets/one-dark.toml")),
    // Internal live presets (geometry-only, not user-selectable)
    (
        "kde-breeze-live",
        include_str!("presets/kde-breeze-live.toml"),
    ),
    ("adwaita-live", include_str!("presets/adwaita-live.toml")),
    (
        "macos-sonoma-live",
        include_str!("presets/macos-sonoma-live.toml"),
    ),
    (
        "windows-11-live",
        include_str!("presets/windows-11-live.toml"),
    ),
];

/// All available user-facing preset names (excludes internal live presets).
const PRESET_NAMES: &[&str] = &[
    "kde-breeze",
    "adwaita",
    "windows-11",
    "macos-sonoma",
    "material",
    "ios",
    "catppuccin-latte",
    "catppuccin-frappe",
    "catppuccin-macchiato",
    "catppuccin-mocha",
    "nord",
    "dracula",
    "gruvbox",
    "solarized",
    "tokyo-night",
    "one-dark",
];

/// Known display names for bundled presets (borrowed from static strings).
///
/// After TOML deserialization the `Theme.name` field is `Cow::Owned` because
/// TOML parsing cannot borrow into static memory. This map lets the cache
/// replace the owned name with a `Cow::Borrowed` reference, avoiding a
/// per-load `String` allocation for bundled preset names.
const PRESET_DISPLAY_NAMES: &[(&str, &str)] = &[
    ("kde-breeze", "KDE Breeze"),
    ("kde-breeze-live", "KDE Breeze"),
    ("adwaita", "Adwaita"),
    ("adwaita-live", "Adwaita"),
    ("windows-11", "Windows 11"),
    ("windows-11-live", "Windows 11"),
    ("macos-sonoma", "macOS Sonoma"),
    ("macos-sonoma-live", "macOS Sonoma"),
    ("material", "Material"),
    ("ios", "iOS"),
    ("catppuccin-latte", "Catppuccin Latte"),
    ("catppuccin-frappe", "Catppuccin Frappe"),
    ("catppuccin-macchiato", "Catppuccin Macchiato"),
    ("catppuccin-mocha", "Catppuccin Mocha"),
    ("nord", "Nord"),
    ("dracula", "Dracula"),
    ("gruvbox", "Gruvbox"),
    ("solarized", "Solarized"),
    ("tokyo-night", "Tokyo Night"),
    ("one-dark", "One Dark"),
];

/// Structured information about a bundled preset.
///
/// Returned by [`Theme::list_presets()`] and [`Theme::list_presets_for_platform()`]
/// to provide richer metadata than bare preset names.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PresetInfo {
    /// Machine-readable preset key (e.g. `"catppuccin-mocha"`, `"kde-breeze"`).
    /// Pass this to [`Theme::preset()`] to load the preset.
    pub key: &'static str,
    /// Human-readable display name (e.g. `"Catppuccin Mocha"`, `"KDE Breeze"`).
    pub display_name: &'static str,
    /// Target platform tags (e.g. `&["linux-kde"]`). Empty for presets offered
    /// on every platform (`material` and the community themes).
    pub platforms: &'static [&'static str],
    /// Whether the preset provides only a light variant (no dark variant).
    pub light_only: bool,
}

/// Structured metadata for all 16 user-facing presets.
///
/// Combines data from [`PRESET_NAMES`], [`PRESET_DISPLAY_NAMES`], and
/// [`PLATFORM_SPECIFIC`] into a single array for richer preset enumeration.
const PRESET_INFOS: &[PresetInfo] = &[
    // Platform presets
    PresetInfo {
        key: "kde-breeze",
        display_name: "KDE Breeze",
        platforms: &["linux-kde"],
        light_only: false,
    },
    PresetInfo {
        key: "adwaita",
        display_name: "Adwaita",
        platforms: &["linux"],
        light_only: false,
    },
    PresetInfo {
        key: "windows-11",
        display_name: "Windows 11",
        platforms: &["windows"],
        light_only: false,
    },
    PresetInfo {
        key: "macos-sonoma",
        display_name: "macOS Sonoma",
        platforms: &["macos"],
        light_only: false,
    },
    PresetInfo {
        key: "material",
        display_name: "Material",
        platforms: &[],
        light_only: false,
    },
    PresetInfo {
        key: "ios",
        display_name: "iOS",
        platforms: &["macos", "ios"],
        light_only: false,
    },
    // Community presets
    PresetInfo {
        key: "catppuccin-latte",
        display_name: "Catppuccin Latte",
        platforms: &[],
        light_only: false,
    },
    PresetInfo {
        key: "catppuccin-frappe",
        display_name: "Catppuccin Frappe",
        platforms: &[],
        light_only: false,
    },
    PresetInfo {
        key: "catppuccin-macchiato",
        display_name: "Catppuccin Macchiato",
        platforms: &[],
        light_only: false,
    },
    PresetInfo {
        key: "catppuccin-mocha",
        display_name: "Catppuccin Mocha",
        platforms: &[],
        light_only: false,
    },
    PresetInfo {
        key: "nord",
        display_name: "Nord",
        platforms: &[],
        light_only: false,
    },
    PresetInfo {
        key: "dracula",
        display_name: "Dracula",
        platforms: &[],
        light_only: false,
    },
    PresetInfo {
        key: "gruvbox",
        display_name: "Gruvbox",
        platforms: &[],
        light_only: false,
    },
    PresetInfo {
        key: "solarized",
        display_name: "Solarized",
        platforms: &[],
        light_only: false,
    },
    PresetInfo {
        key: "tokyo-night",
        display_name: "Tokyo Night",
        platforms: &[],
        light_only: false,
    },
    PresetInfo {
        key: "one-dark",
        display_name: "One Dark",
        platforms: &[],
        light_only: false,
    },
];

/// Cached parse result. Uses `String` for the error type (not `Error`) because:
/// - `Error` does not implement `Clone`, which is needed for cache retrieval
/// - Preset parse errors are rare (bundled TOML is validated at dev time)
/// - The string-erased error message is sufficient for user diagnostics
type Parsed = std::result::Result<Theme, String>;

fn parse(toml_str: &str) -> Parsed {
    from_toml(toml_str).map_err(|e| e.to_string())
}

static CACHE: LazyLock<HashMap<&str, Parsed>> = LazyLock::new(|| {
    PRESET_ENTRIES
        .iter()
        .map(|(key, toml_str)| {
            let mut result = parse(toml_str);
            // Replace the TOML-deserialized owned name with a borrowed static string
            if let Ok(ref mut theme) = result
                && let Some((_, display_name)) = PRESET_DISPLAY_NAMES.iter().find(|(k, _)| k == key)
            {
                theme.name = Cow::Borrowed(display_name);
            }
            (*key, result)
        })
        .collect()
});

pub(crate) fn preset(name: &str) -> Result<Theme> {
    match CACHE.get(name) {
        None => Err(Error::UnknownPreset {
            name: name.to_string(),
            known: PRESET_NAMES,
        }),
        Some(Ok(theme)) => Ok(theme.clone()),
        Some(Err(msg)) => Err(Error::ReaderFailed {
            reader: "preset_cache",
            source: format!("bundled preset '{name}': {msg}").into(),
        }),
    }
}

pub(crate) fn list_presets() -> &'static [PresetInfo] {
    PRESET_INFOS
}

/// Detect the current platform tag for preset filtering.
///
/// Returns a string like "linux-kde", "linux", "windows", or "macos".
#[allow(unreachable_code)]
fn detect_platform() -> &'static str {
    #[cfg(target_os = "macos")]
    {
        return "macos";
    }
    #[cfg(target_os = "windows")]
    {
        return "windows";
    }
    #[cfg(target_os = "linux")]
    {
        if crate::detect::detect_linux_desktop() == crate::detect::LinuxDesktop::Kde {
            return "linux-kde";
        }
        "linux"
    }
    #[cfg(target_os = "ios")]
    {
        return "ios";
    }
    #[cfg(not(any(
        target_os = "linux",
        target_os = "windows",
        target_os = "macos",
        target_os = "ios"
    )))]
    {
        "linux"
    }
}

/// Returns preset info appropriate for the current platform.
///
/// Platform-specific presets (kde-breeze, adwaita, windows-11, macos-sonoma, ios)
/// are only included on their native platform. Community themes are always included.
pub(crate) fn list_presets_for_platform() -> Vec<PresetInfo> {
    let platform = detect_platform();

    PRESET_INFOS
        .iter()
        .filter(|info| {
            info.platforms.is_empty() || info.platforms.iter().any(|p| platform.starts_with(p))
        })
        .cloned()
        .collect()
}

pub(crate) fn from_toml(toml_str: &str) -> Result<Theme> {
    let theme: Theme = toml::from_str(toml_str)?;
    Ok(theme)
}

pub(crate) fn from_file(path: impl AsRef<Path>) -> Result<Theme> {
    let contents = std::fs::read_to_string(path)?;
    from_toml(&contents)
}

pub(crate) fn to_toml(theme: &Theme) -> Result<String> {
    let s = toml::to_string_pretty(theme)?;
    Ok(s)
}

#[cfg(test)]
mod documented_sizes;

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

    // NOTE: all_presets_loadable_via_preset_fn and all_presets_have_nonempty_core_colors
    // are covered by tests/preset_loading.rs (all_presets_parse_without_error,
    // all_presets_have_both_variants, all_presets_have_core_colors).

    /// Every bundled preset's own source lints clean, shorthand keys and
    /// all. `lint_toml_all_presets_clean` lints `to_toml()` output, which
    /// writes padding sides only, so it cannot see a shorthand key.
    #[test]
    fn every_bundled_preset_source_lints_clean() {
        for (name, source) in PRESET_ENTRIES {
            let warnings = crate::Theme::lint_toml(source)
                .unwrap_or_else(|e| panic!("preset {name} should lint: {e}"));
            assert!(
                warnings.is_empty(),
                "preset {name}'s source has lint warnings: {warnings:?}"
            );
        }
        assert!(
            PRESET_ENTRIES
                .iter()
                .any(|(_, s)| s.contains("padding_horizontal_px")),
            "no bundled preset uses the shorthand any more, so this test no \
             longer proves the linter accepts it"
        );
    }

    #[test]
    fn preset_unknown_name_returns_unknown_preset() {
        let err = preset("nonexistent").unwrap_err();
        let Error::UnknownPreset { name, .. } = err else {
            return;
        };
        assert!(name.contains("nonexistent"));
    }

    // NOTE: list_presets_returns_all_sixteen is covered by
    // tests/preset_loading.rs::list_presets_returns_sixteen_entries.

    #[test]
    fn from_toml_minimal_valid() {
        let toml_str = r##"
name = "Minimal"

[light.defaults]
accent_color = "#ff0000"
"##;
        let theme = from_toml(toml_str).unwrap();
        assert_eq!(theme.name, "Minimal");
        assert!(theme.light.is_some());
        let light = theme.light.unwrap();
        assert_eq!(
            light.defaults.accent_color,
            Some(crate::Rgba::rgb(255, 0, 0))
        );
    }

    #[test]
    fn from_toml_invalid_returns_toml_error() {
        let err = from_toml("{{{{invalid toml").unwrap_err();
        assert!(
            matches!(err, Error::Toml(_)),
            "expected Toml variant, got: {err:?}"
        );
    }

    #[test]
    fn to_toml_produces_valid_round_trip() {
        let theme = preset("catppuccin-mocha").unwrap();
        let toml_str = to_toml(&theme).unwrap();

        // Must be parseable back into a Theme
        let reparsed = from_toml(&toml_str).unwrap();
        assert_eq!(reparsed.name, theme.name);
        assert!(reparsed.light.is_some());
        assert!(reparsed.dark.is_some());

        // Core colors should survive the round-trip
        let orig_light = theme.light.as_ref().unwrap();
        let new_light = reparsed.light.as_ref().unwrap();
        assert_eq!(
            orig_light.defaults.accent_color,
            new_light.defaults.accent_color
        );
    }

    #[test]
    fn from_file_with_tempfile() {
        let dir = std::env::temp_dir();
        let path = dir.join("native_theme_test_preset.toml");
        let toml_str = r##"
name = "File Test"

[light.defaults]
accent_color = "#00ff00"
"##;
        std::fs::write(&path, toml_str).unwrap();

        let theme = from_file(&path).unwrap();
        assert_eq!(theme.name, "File Test");
        assert!(theme.light.is_some());

        // Clean up
        let _ = std::fs::remove_file(&path);
    }

    // === icon_set preset tests ===

    #[test]
    fn icon_set_native_presets_have_correct_values() {
        use crate::IconSet;
        let cases: &[(&str, IconSet)] = &[
            ("windows-11", IconSet::SegoeIcons),
            ("macos-sonoma", IconSet::SfSymbols),
            ("ios", IconSet::SfSymbols),
            ("adwaita", IconSet::Freedesktop),
            ("kde-breeze", IconSet::Freedesktop),
            ("material", IconSet::Material),
        ];
        for (name, expected) in cases {
            let theme = preset(name).unwrap();
            assert_eq!(
                theme.icon_set,
                Some(*expected),
                "preset '{name}' icon_set should be Some({expected:?})"
            );
        }
    }

    #[test]
    fn icon_set_community_presets_have_lucide() {
        let community = &[
            "catppuccin-latte",
            "catppuccin-frappe",
            "catppuccin-macchiato",
            "catppuccin-mocha",
            "nord",
            "dracula",
            "gruvbox",
            "solarized",
            "tokyo-night",
            "one-dark",
        ];
        for name in community {
            let theme = preset(name).unwrap();
            assert_eq!(
                theme.icon_set,
                Some(crate::IconSet::Lucide),
                "preset '{name}' icon_set should be Lucide"
            );
        }
    }

    #[test]
    fn from_file_nonexistent_returns_error() {
        let err = from_file("/tmp/nonexistent_theme_file_12345.toml").unwrap_err();
        match err {
            Error::Io(e) => assert_eq!(e.kind(), std::io::ErrorKind::NotFound),
            other => panic!("expected Io, got: {other:?}"),
        }
    }

    #[test]
    fn preset_names_match_list() {
        // Every name in list_presets() must be loadable via preset()
        for info in list_presets() {
            assert!(
                preset(info.key).is_ok(),
                "preset '{}' not loadable",
                info.key
            );
        }
    }

    // NOTE: presets_have_correct_names is tested via tests/preset_loading.rs.
    // NOTE: all_presets_with_fonts_have_valid_sizes is covered by
    // tests/preset_loading.rs::all_presets_have_valid_fonts.

    #[test]
    fn platform_presets_no_derived_fields() {
        // Platform presets must not contain fields that are derived by resolve()
        let platform_presets = &["kde-breeze", "adwaita", "windows-11", "macos-sonoma"];
        for name in platform_presets {
            let theme = preset(name).unwrap();
            for (label, variant_opt) in [
                ("light", theme.light.as_ref()),
                ("dark", theme.dark.as_ref()),
            ] {
                let variant = variant_opt.unwrap();
                // button.primary_background is derived from accent - should not be in presets
                assert!(
                    variant.button.primary_background.is_none(),
                    "preset '{name}' {label}.button.primary_background should be None (derived)"
                );
                // checkbox.checked_background is derived from accent, except on
                // KDE, where Breeze tints the button colour instead
                // (docs/platform-facts.md:1218, §2.5)
                assert_eq!(
                    variant.checkbox.checked_background.is_some(),
                    *name == "kde-breeze",
                    "preset '{name}' {label}.checkbox.checked_background: stated only where \
                     platform-facts does not derive it from the accent"
                );
                // slider.fill is derived from accent
                assert!(
                    variant.slider.fill_color.is_none(),
                    "preset '{name}' {label}.slider.fill_color should be None (derived)"
                );
                // progress_bar.fill is derived from accent, except on KDE,
                // where Breeze lays the accent at 0.7 over the window
                // (docs/platform-facts.md:1301, §2.10)
                assert_eq!(
                    variant.progress_bar.fill_color.is_some(),
                    *name == "kde-breeze",
                    "preset '{name}' {label}.progress_bar.fill_color: stated only where \
                     platform-facts does not derive it from the accent"
                );
                // switch.checked_background is derived from accent
                assert!(
                    variant.switch.checked_background.is_none(),
                    "preset '{name}' {label}.switch.checked_background should be None (derived)"
                );
            }
        }
    }

    // === resolve()/validate() integration tests (PRESET-03) ===

    #[test]
    fn all_presets_resolve_validate() {
        for info in list_presets() {
            let name = info.key;
            let theme = preset(name).unwrap();
            if let Some(mut light) = theme.light.clone() {
                light.resolve_all();
                light.validate().unwrap_or_else(|e| {
                    panic!("preset {name} light variant failed validation: {e}");
                });
            }
            if let Some(mut dark) = theme.dark.clone() {
                dark.resolve_all();
                dark.validate().unwrap_or_else(|e| {
                    panic!("preset {name} dark variant failed validation: {e}");
                });
            }
        }
    }

    #[test]
    fn all_presets_indicator_color_inherits_accent_text_color() {
        // platform-facts.md §2.5 records the check mark / radio dot as the
        // on-accent colour on all four platforms, and it is painted on
        // checkbox.checked_background <- defaults.accent_color.
        for info in list_presets() {
            let name = info.key;
            let theme = preset(name).unwrap();
            for (label, variant_opt) in
                [("light", theme.light.clone()), ("dark", theme.dark.clone())]
            {
                let Some(mut variant) = variant_opt else {
                    continue;
                };
                if variant.checkbox.indicator_color.is_some() {
                    continue;
                }
                variant.resolve_all();
                assert_eq!(
                    variant.checkbox.indicator_color, variant.defaults.accent_text_color,
                    "preset '{name}' {label}.checkbox.indicator_color should inherit \
                     defaults.accent_text_color"
                );
            }
        }
    }

    #[test]
    fn resolve_fills_accent_derived_fields() {
        // Load a preset that only has accent set (not explicit widget accent-derived fields).
        // After resolve(), the accent-derived fields should be populated.
        let theme = preset("catppuccin-mocha").unwrap();
        let mut light = theme.light.clone().unwrap();

        // Before resolve: accent-derived fields should be None (not in preset TOML)
        assert!(
            light.button.primary_background.is_none(),
            "primary_background should be None pre-resolve"
        );
        assert!(
            light.checkbox.checked_background.is_none(),
            "checkbox.checked_background should be None pre-resolve"
        );
        assert!(
            light.slider.fill_color.is_none(),
            "slider.fill should be None pre-resolve"
        );
        assert!(
            light.progress_bar.fill_color.is_none(),
            "progress_bar.fill should be None pre-resolve"
        );
        assert!(
            light.switch.checked_background.is_none(),
            "switch.checked_background should be None pre-resolve"
        );

        light.resolve();

        // After resolve: all accent-derived fields should equal accent
        let accent = light.defaults.accent_color.unwrap();
        assert_eq!(
            light.button.primary_background,
            Some(accent),
            "button.primary_background should match accent"
        );
        assert_eq!(
            light.checkbox.checked_background,
            Some(accent),
            "checkbox.checked_background should match accent"
        );
        assert_eq!(
            light.slider.fill_color,
            Some(accent),
            "slider.fill should match accent"
        );
        assert_eq!(
            light.progress_bar.fill_color,
            Some(accent),
            "progress_bar.fill should match accent"
        );
        assert_eq!(
            light.switch.checked_background,
            Some(accent),
            "switch.checked_background should match accent"
        );
    }

    #[test]
    fn resolve_then_validate_produces_complete_theme() {
        let theme = preset("catppuccin-mocha").unwrap();
        let mut light = theme.light.clone().unwrap();
        light.resolve_all();
        let resolved = light.validate().unwrap();

        assert_eq!(resolved.defaults.font.family.as_ref(), "Inter");
        assert_eq!(resolved.defaults.font.size, 14.0);
        assert_eq!(resolved.defaults.font.weight, 400);
        assert_eq!(resolved.defaults.line_height, 1.2);
        assert_eq!(resolved.defaults.border.corner_radius, 8.0);
        assert_eq!(resolved.defaults.focus_ring_width, 2.0);
        assert_eq!(resolved.defaults.icon_sizes.toolbar, 24.0);
        assert_eq!(resolved.defaults.icon_sizes.toolbar, 24.0);
        // Window inherits from defaults
        assert_eq!(
            resolved.window.background_color,
            resolved.defaults.background_color
        );
        // icon_set is now on Theme, not on ResolvedTheme
        assert_eq!(theme.icon_set, Some(crate::IconSet::Lucide));
    }

    #[test]
    fn font_subfield_inheritance_integration() {
        // Load a preset, set menu.font to only have size=12.0 (clear family/weight),
        // resolve, and verify family/weight are inherited from defaults.
        let theme = preset("catppuccin-mocha").unwrap();
        let mut light = theme.light.clone().unwrap();

        // Set partial font on menu
        use crate::model::FontSpec;
        use crate::model::font::FontSize;
        light.menu.font = Some(FontSpec {
            family: None,
            size: Some(FontSize::Px(12.0)),
            weight: None,
            ..Default::default()
        });

        light.resolve_all();
        let resolved = light.validate().unwrap();

        // menu font should have inherited family/weight from defaults
        assert_eq!(
            resolved.menu.font.family.as_ref(),
            "Inter",
            "menu font family should inherit from defaults"
        );
        assert_eq!(
            resolved.menu.font.size, 12.0,
            "menu font size should be the explicit value"
        );
        assert_eq!(
            resolved.menu.font.weight, 400,
            "menu font weight should inherit from defaults"
        );
    }

    #[test]
    fn text_scale_inheritance_integration() {
        // Load a preset, ensure text_scale.caption gets populated from defaults.
        let theme = preset("catppuccin-mocha").unwrap();
        let mut light = theme.light.clone().unwrap();

        // Clear caption to test inheritance
        light.text_scale.caption = None;

        light.resolve_all();
        let resolved = light.validate().unwrap();

        // caption should have been populated from defaults.font (no ratio)
        // defaults.font.size = 14.0, so caption.size = 14.0
        let expected_size = 14.0;
        assert!(
            (resolved.text_scale.caption.size - expected_size).abs() < 0.01,
            "caption size = defaults.font.size, got {}",
            resolved.text_scale.caption.size
        );
        assert_eq!(
            resolved.text_scale.caption.weight, 400,
            "caption weight from defaults.font.weight"
        );
        // line_height = defaults.line_height * caption_size = 1.2 * 14.0 = 16.8
        let expected_lh = 1.2 * expected_size;
        assert!(
            (resolved.text_scale.caption.line_height - expected_lh).abs() < 0.01,
            "caption line_height should be line_height_multiplier * caption_size = {expected_lh}, got {}",
            resolved.text_scale.caption.line_height
        );
    }

    // NOTE: all_presets_round_trip_exact is covered by
    // tests/preset_loading.rs::all_presets_round_trip_toml.

    // === Live preset tests ===

    #[test]
    fn live_presets_loadable() {
        let live_names = &[
            "kde-breeze-live",
            "adwaita-live",
            "macos-sonoma-live",
            "windows-11-live",
        ];
        for name in live_names {
            let theme = preset(name)
                .unwrap_or_else(|e| panic!("live preset '{name}' failed to parse: {e}"));

            // Both variants must exist
            assert!(
                theme.light.is_some(),
                "live preset '{name}' missing light variant"
            );
            assert!(
                theme.dark.is_some(),
                "live preset '{name}' missing dark variant"
            );

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

            // No colors
            assert!(
                light.defaults.accent_color.is_none(),
                "live preset '{name}' light should have no accent"
            );
            assert!(
                light.defaults.background_color.is_none(),
                "live preset '{name}' light should have no background"
            );
            assert!(
                light.defaults.text_color.is_none(),
                "live preset '{name}' light should have no foreground"
            );
            assert!(
                dark.defaults.accent_color.is_none(),
                "live preset '{name}' dark should have no accent"
            );
            assert!(
                dark.defaults.background_color.is_none(),
                "live preset '{name}' dark should have no background"
            );
            assert!(
                dark.defaults.text_color.is_none(),
                "live preset '{name}' dark should have no foreground"
            );

            // No fonts
            assert!(
                light.defaults.font.family.is_none(),
                "live preset '{name}' light should have no font family"
            );
            assert!(
                light.defaults.font.size.is_none(),
                "live preset '{name}' light should have no font size"
            );
            assert!(
                light.defaults.font.weight.is_none(),
                "live preset '{name}' light should have no font weight"
            );
            assert!(
                dark.defaults.font.family.is_none(),
                "live preset '{name}' dark should have no font family"
            );
            assert!(
                dark.defaults.font.size.is_none(),
                "live preset '{name}' dark should have no font size"
            );
            assert!(
                dark.defaults.font.weight.is_none(),
                "live preset '{name}' dark should have no font weight"
            );
        }
    }

    #[test]
    fn list_presets_for_platform_returns_subset() {
        let all = list_presets();
        let filtered = list_presets_for_platform();
        // Filtered list should be a subset of all presets
        for info in &filtered {
            assert!(
                all.iter().any(|a| a.key == info.key),
                "filtered preset '{}' not in full list",
                info.key
            );
        }
        // Community themes should always be present
        let community = &[
            "catppuccin-latte",
            "catppuccin-frappe",
            "catppuccin-macchiato",
            "catppuccin-mocha",
            "nord",
            "dracula",
            "gruvbox",
            "solarized",
            "tokyo-night",
            "one-dark",
        ];
        for name in community {
            assert!(
                filtered.iter().any(|info| info.key == *name),
                "community preset '{name}' should always be in filtered list"
            );
        }
        // material is cross-platform, always present
        assert!(
            filtered.iter().any(|info| info.key == "material"),
            "material should always be in filtered list"
        );
    }

    #[test]
    fn live_presets_fail_validate_standalone() {
        let live_names = &[
            "kde-breeze-live",
            "adwaita-live",
            "macos-sonoma-live",
            "windows-11-live",
        ];
        for name in live_names {
            let theme = preset(name).unwrap();
            let mut light = theme.light.clone().unwrap();
            light.resolve();
            let result = light.validate();
            assert!(
                result.is_err(),
                "live preset '{name}' light should fail validation standalone (missing colors/fonts)"
            );

            let mut dark = theme.dark.clone().unwrap();
            dark.resolve();
            let result = dark.validate();
            assert!(
                result.is_err(),
                "live preset '{name}' dark should fail validation standalone (missing colors/fonts)"
            );
        }
    }
}