Skip to main content

native_theme/
presets.rs

1//! Bundled theme presets: [`PresetInfo`], the description of one.
2//!
3//! 17 presets are embedded at compile time: 7 platform (kde-breeze, adwaita,
4//! windows-11, macos-monterey, macos-tahoe, material-3, ios-13) and 10
5//! community (Catppuccin's 4 flavours, Nord, Dracula, Gruvbox, Solarized, Tokyo
6//! Night, One Dark). [`Theme::preset`] loads one, [`Theme::list_presets`] lists
7//! them, and [`Theme::from_toml`] and [`Theme::from_file`] load your own theme.
8
9use std::borrow::Cow;
10use std::path::Path;
11use std::sync::OnceLock;
12
13use crate::{Error, Result, Theme};
14
15/// Structured information about a bundled preset.
16///
17/// Returned by [`Theme::list_presets()`] and [`Theme::list_presets_for_platform()`]
18/// to provide richer metadata than bare preset names.
19#[derive(Clone, Debug, PartialEq, Eq)]
20#[non_exhaustive]
21pub struct PresetInfo {
22    /// Machine-readable preset key (e.g. `"catppuccin-mocha"`, `"kde-breeze"`).
23    /// Pass this to [`Theme::preset()`] to load the preset.
24    pub key: &'static str,
25    /// Human-readable display name (e.g. `"Catppuccin Mocha"`, `"KDE Breeze"`).
26    pub display_name: &'static str,
27    /// Target platform tags (e.g. `&["linux-kde"]`). Empty for presets offered
28    /// on every platform (`material-3` and the community themes).
29    pub platforms: &'static [&'static str],
30}
31
32/// Builds [`PRESET_INFOS`], [`PRESET_NAMES`] and [`PRESET_ENTRIES`] from one
33/// table, in the same order, so the three cannot disagree.
34macro_rules! bundled_presets {
35    ($($key:literal => $display_name:literal, $platforms:expr;)*) => {
36        /// Structured metadata for every bundled preset.
37        const PRESET_INFOS: &[PresetInfo] = &[$(PresetInfo {
38            key: $key,
39            display_name: $display_name,
40            platforms: $platforms,
41        }),*];
42
43        /// Every bundled preset's key.
44        const PRESET_NAMES: &[&str] = &[$($key),*];
45
46        /// Every bundled preset's key and embedded TOML source,
47        /// `presets/<key>.toml`.
48        const PRESET_ENTRIES: &[(&str, &str)] =
49            &[$(($key, include_str!(concat!("presets/", $key, ".toml")))),*];
50    };
51}
52
53// The bundled presets: key => display name, platform tags. To add a preset,
54// add its line here and its `presets/<key>.toml`, whose `name` is the display
55// name (a test checks it).
56bundled_presets! {
57    // Platform presets
58    "kde-breeze" => "KDE Breeze", &["linux-kde"];
59    "adwaita" => "Adwaita", &["linux"];
60    "windows-11" => "Windows 11", &["windows"];
61    "macos-monterey" => "macOS Monterey", &["macos"];
62    "macos-tahoe" => "macOS Tahoe", &["macos"];
63    "material-3" => "Material", &[];
64    "ios-13" => "iOS", &["macos", "ios"];
65    // Community presets
66    "catppuccin-latte" => "Catppuccin Latte", &[];
67    "catppuccin-frappe" => "Catppuccin Frappe", &[];
68    "catppuccin-macchiato" => "Catppuccin Macchiato", &[];
69    "catppuccin-mocha" => "Catppuccin Mocha", &[];
70    "nord" => "Nord", &[];
71    "dracula" => "Dracula", &[];
72    "gruvbox" => "Gruvbox", &[];
73    "solarized" => "Solarized", &[];
74    "tokyo-night" => "Tokyo Night", &[];
75    "one-dark" => "One Dark", &[];
76}
77
78/// Cached parse result. Uses `String` for the error type (not `Error`) because:
79/// - `Error` does not implement `Clone`, which is needed for cache retrieval
80/// - Preset parse errors are rare (bundled TOML is validated at dev time)
81/// - The string-erased error message is sufficient for user diagnostics
82type Parsed = std::result::Result<Theme, String>;
83
84fn parse(toml_str: &str) -> Parsed {
85    from_toml(toml_str).map_err(|e| e.to_string())
86}
87
88/// One cell per [`PRESET_ENTRIES`] entry, at the same position, so a preset's
89/// TOML is parsed on its first use only.
90static CACHE: [OnceLock<Parsed>; PRESET_ENTRIES.len()] =
91    [const { OnceLock::new() }; PRESET_ENTRIES.len()];
92
93pub(crate) fn preset(name: &str) -> Result<Theme> {
94    let Some(((_, toml_str), (info, cell))) = PRESET_ENTRIES
95        .iter()
96        .zip(PRESET_INFOS.iter().zip(&CACHE))
97        .find(|((key, _), _)| *key == name)
98    else {
99        return Err(Error::UnknownPreset {
100            name: name.to_string(),
101            known: PRESET_NAMES,
102        });
103    };
104    let parsed = cell.get_or_init(|| {
105        let mut result = parse(toml_str);
106        // The TOML name equals the display name (tested); borrowing the
107        // static one saves an owned `String` per load
108        if let Ok(ref mut theme) = result {
109            theme.name = Cow::Borrowed(info.display_name);
110        }
111        result
112    });
113    match parsed {
114        Ok(theme) => Ok(theme.clone()),
115        Err(msg) => Err(Error::ReaderFailed {
116            reader: crate::error::reader_names::PRESET_CACHE,
117            source: format!("bundled preset '{name}': {msg}").into(),
118        }),
119    }
120}
121
122pub(crate) fn list_presets() -> &'static [PresetInfo] {
123    PRESET_INFOS
124}
125
126/// Detect the current platform tag for preset filtering.
127///
128/// Returns a string like "linux-kde", "linux", "windows", or "macos".
129fn detect_platform() -> &'static str {
130    #[cfg(target_os = "macos")]
131    {
132        "macos"
133    }
134    #[cfg(target_os = "windows")]
135    {
136        "windows"
137    }
138    #[cfg(target_os = "linux")]
139    {
140        if crate::detect::detect_linux_desktop() == crate::detect::LinuxDesktop::Kde {
141            return "linux-kde";
142        }
143        "linux"
144    }
145    #[cfg(target_os = "ios")]
146    {
147        return "ios";
148    }
149    #[cfg(not(any(
150        target_os = "linux",
151        target_os = "windows",
152        target_os = "macos",
153        target_os = "ios"
154    )))]
155    {
156        "linux"
157    }
158}
159
160/// Returns preset info appropriate for the current platform.
161///
162/// Platform-specific presets (kde-breeze, adwaita, windows-11, macos-monterey, macos-tahoe, ios-13)
163/// are only included on their native platform. Community themes are always included.
164pub(crate) fn list_presets_for_platform() -> Vec<PresetInfo> {
165    let platform = detect_platform();
166
167    PRESET_INFOS
168        .iter()
169        .filter(|info| {
170            info.platforms.is_empty() || info.platforms.iter().any(|p| platform.starts_with(p))
171        })
172        .cloned()
173        .collect()
174}
175
176pub(crate) fn from_toml(toml_str: &str) -> Result<Theme> {
177    let theme: Theme = toml::from_str(toml_str)?;
178    Ok(theme)
179}
180
181pub(crate) fn from_file(path: impl AsRef<Path>) -> Result<Theme> {
182    let path = path.as_ref();
183    let contents = std::fs::read_to_string(path).map_err(|source| Error::Io {
184        path: path.to_path_buf(),
185        source,
186    })?;
187    from_toml(&contents)
188}
189
190pub(crate) fn to_toml(theme: &Theme) -> Result<String> {
191    let s = toml::to_string_pretty(theme)?;
192    Ok(s)
193}
194
195#[cfg(test)]
196mod documented_sizes;
197
198#[cfg(test)]
199#[allow(clippy::unwrap_used, clippy::expect_used)]
200mod tests {
201    use super::*;
202
203    // NOTE: all_presets_loadable_via_preset_fn and all_presets_have_nonempty_core_colors
204    // are covered by tests/preset_loading.rs (all_presets_parse_without_error,
205    // all_presets_have_both_variants, all_presets_have_core_colors).
206
207    /// Every bundled preset's own source lints clean, shorthand keys and
208    /// all. `lint_toml_all_presets_clean` lints `to_toml()` output, which
209    /// writes padding sides only, so it cannot see a shorthand key.
210    #[test]
211    fn every_bundled_preset_source_lints_clean() {
212        for (name, source) in PRESET_ENTRIES {
213            let warnings = crate::Theme::lint_toml(source)
214                .unwrap_or_else(|e| panic!("preset {name} should lint: {e}"));
215            assert!(
216                warnings.is_empty(),
217                "preset {name}'s source has lint warnings: {warnings:?}"
218            );
219        }
220        assert!(
221            PRESET_ENTRIES
222                .iter()
223                .any(|(_, s)| s.contains("padding_horizontal_px")),
224            "no bundled preset uses the shorthand any more, so this test no \
225             longer proves the linter accepts it"
226        );
227    }
228
229    /// The cache swaps each preset's TOML `name` for its display name, so
230    /// the two must be equal, or the swap would hide the TOML's.
231    #[test]
232    fn every_bundled_preset_toml_name_is_its_display_name() {
233        assert_eq!(PRESET_ENTRIES.len(), PRESET_INFOS.len());
234        for ((key, source), info) in PRESET_ENTRIES.iter().zip(PRESET_INFOS) {
235            let theme = from_toml(source).unwrap();
236            assert_eq!(
237                theme.name, info.display_name,
238                "preset {key}'s TOML name differs from its display name"
239            );
240        }
241    }
242
243    #[test]
244    fn preset_unknown_name_returns_unknown_preset() {
245        let err = preset("nonexistent").unwrap_err();
246        assert!(
247            matches!(err, Error::UnknownPreset { ref name, .. } if name == "nonexistent"),
248            "expected UnknownPreset, got: {err:?}"
249        );
250    }
251
252    // NOTE: list_presets_returns_all_seventeen is covered by
253    // tests/preset_loading.rs::list_presets_returns_seventeen_entries.
254
255    #[test]
256    fn from_toml_minimal_valid() {
257        let toml_str = r##"
258name = "Minimal"
259
260[light.defaults]
261accent_color = "#ff0000"
262"##;
263        let theme = from_toml(toml_str).unwrap();
264        assert_eq!(theme.name, "Minimal");
265        assert!(theme.light.is_some());
266        let light = theme.light.unwrap();
267        assert_eq!(
268            light.defaults.accent_color,
269            Some(crate::Rgba::rgb(255, 0, 0))
270        );
271    }
272
273    #[test]
274    fn from_toml_invalid_returns_toml_error() {
275        let err = from_toml("{{{{invalid toml").unwrap_err();
276        assert!(
277            matches!(err, Error::Toml(_)),
278            "expected Toml variant, got: {err:?}"
279        );
280    }
281
282    #[test]
283    fn to_toml_produces_valid_round_trip() {
284        let theme = preset("catppuccin-mocha").unwrap();
285        let toml_str = to_toml(&theme).unwrap();
286
287        // Must be parseable back into a Theme
288        let reparsed = from_toml(&toml_str).unwrap();
289        assert_eq!(reparsed.name, theme.name);
290        assert!(reparsed.light.is_some());
291        assert!(reparsed.dark.is_some());
292
293        // Core colors should survive the round-trip
294        let orig_light = theme.light.as_ref().unwrap();
295        let new_light = reparsed.light.as_ref().unwrap();
296        assert_eq!(
297            orig_light.defaults.accent_color,
298            new_light.defaults.accent_color
299        );
300    }
301
302    #[test]
303    fn from_file_with_tempfile() {
304        let dir = std::env::temp_dir();
305        let path = dir.join("native_theme_test_preset.toml");
306        let toml_str = r##"
307name = "File Test"
308
309[light.defaults]
310accent_color = "#00ff00"
311"##;
312        std::fs::write(&path, toml_str).unwrap();
313
314        let theme = from_file(&path).unwrap();
315        assert_eq!(theme.name, "File Test");
316        assert!(theme.light.is_some());
317
318        // Clean up
319        let _ = std::fs::remove_file(&path);
320    }
321
322    // === icon_set preset tests ===
323
324    #[test]
325    fn icon_set_native_presets_have_correct_values() {
326        use crate::IconSet;
327        let cases: &[(&str, IconSet)] = &[
328            ("windows-11", IconSet::SegoeFluent),
329            ("macos-monterey", IconSet::SfSymbols),
330            ("macos-tahoe", IconSet::SfSymbols),
331            ("ios-13", IconSet::SfSymbols),
332            ("adwaita", IconSet::Freedesktop),
333            ("kde-breeze", IconSet::Freedesktop),
334            ("material-3", IconSet::Material),
335        ];
336        for (name, expected) in cases {
337            let theme = preset(name).unwrap();
338            assert_eq!(
339                theme.icon_set,
340                Some(*expected),
341                "preset '{name}' icon_set should be Some({expected:?})"
342            );
343        }
344    }
345
346    #[test]
347    fn icon_set_community_presets_have_lucide() {
348        let community = &[
349            "catppuccin-latte",
350            "catppuccin-frappe",
351            "catppuccin-macchiato",
352            "catppuccin-mocha",
353            "nord",
354            "dracula",
355            "gruvbox",
356            "solarized",
357            "tokyo-night",
358            "one-dark",
359        ];
360        for name in community {
361            let theme = preset(name).unwrap();
362            assert_eq!(
363                theme.icon_set,
364                Some(crate::IconSet::Lucide),
365                "preset '{name}' icon_set should be Lucide"
366            );
367        }
368    }
369
370    #[test]
371    fn from_file_nonexistent_returns_error() {
372        let err = from_file("/tmp/nonexistent_theme_file_12345.toml").unwrap_err();
373        match err {
374            Error::Io { source, .. } => assert_eq!(source.kind(), std::io::ErrorKind::NotFound),
375            other => panic!("expected Io, got: {other:?}"),
376        }
377    }
378
379    #[test]
380    fn from_file_error_names_the_path() {
381        let path = "/nonexistent/native_theme_missing_12345.toml";
382        let err = Theme::from_file(path).unwrap_err();
383        let msg = err.to_string();
384        assert!(
385            msg.contains(path),
386            "error message should name the file: {msg}"
387        );
388    }
389
390    #[test]
391    fn preset_names_match_list() {
392        // Every name in list_presets() must be loadable via preset()
393        for info in list_presets() {
394            assert!(
395                preset(info.key).is_ok(),
396                "preset '{}' not loadable",
397                info.key
398            );
399        }
400    }
401
402    // NOTE: presets_have_correct_names is tested via tests/preset_loading.rs.
403    // NOTE: all_presets_with_fonts_have_valid_sizes is covered by
404    // tests/preset_loading.rs::all_presets_have_valid_fonts.
405
406    #[test]
407    fn platform_presets_no_derived_fields() {
408        // Platform presets must not contain fields that are derived by resolve()
409        let platform_presets = &[
410            "kde-breeze",
411            "adwaita",
412            "windows-11",
413            "macos-monterey",
414            "macos-tahoe",
415        ];
416        for name in platform_presets {
417            let theme = preset(name).unwrap();
418            for (label, variant_opt) in [
419                ("light", theme.light.as_ref()),
420                ("dark", theme.dark.as_ref()),
421            ] {
422                let variant = variant_opt.unwrap();
423                // button.primary_background is derived from accent, except on Windows
424                // (AccentFillColorDefault); KDE's default button has fields of its own,
425                // `default_button_*` (docs/platform-facts.md §2.3)
426                assert_eq!(
427                    variant.button.primary_background.is_some(),
428                    *name == "windows-11",
429                    "preset '{name}' {label}.button.primary_background: stated only where \
430                     platform-facts does not derive it from the accent"
431                );
432                assert_eq!(
433                    variant.button.default_button_background.is_some(),
434                    *name == "kde-breeze",
435                    "preset '{name}' {label}.button.default_button_background: stated only where \
436                     the default button is not the primary one (KDE)"
437                );
438                // checkbox.checked_background is derived from accent, except on
439                // KDE, where Breeze tints the button colour instead, and on
440                // Windows, where WinUI fills it with AccentFillColorDefault
441                // (docs/platform-facts.md:1239, §2.5)
442                assert_eq!(
443                    variant.checkbox.checked_background.is_some(),
444                    matches!(*name, "kde-breeze" | "windows-11"),
445                    "preset '{name}' {label}.checkbox.checked_background: stated only where \
446                     platform-facts does not derive it from the accent"
447                );
448                // slider.fill is derived from accent, except on Windows
449                // (AccentFillColorDefault, docs/platform-facts.md:1317, §2.9)
450                assert_eq!(
451                    variant.slider.fill_color.is_some(),
452                    *name == "windows-11",
453                    "preset '{name}' {label}.slider.fill_color: stated only where \
454                     platform-facts does not derive it from the accent"
455                );
456                // progress_bar.fill is derived from accent, except on KDE,
457                // where Breeze lays the accent at 0.7 over the window, and on
458                // Windows (AccentFillColorDefault; docs/platform-facts.md:1333, §2.10)
459                assert_eq!(
460                    variant.progress_bar.fill_color.is_some(),
461                    matches!(*name, "kde-breeze" | "windows-11"),
462                    "preset '{name}' {label}.progress_bar.fill_color: stated only where \
463                     platform-facts does not derive it from the accent"
464                );
465                // switch.checked_background is derived from accent, except on
466                // KDE, where qqc2-desktop-style lays the highlight at 0.5 over
467                // the off track, and on Windows, AccentFillColorDefault
468                // (docs/platform-facts.md §2.21 checked_background)
469                assert_eq!(
470                    variant.switch.checked_background.is_some(),
471                    matches!(*name, "kde-breeze" | "windows-11"),
472                    "preset '{name}' {label}.switch.checked_background: stated only where \
473                     platform-facts does not derive it from the accent"
474                );
475                // menu.hover_background is the selection on macOS, which it
476                // inherits; KDE (DecorationFocus at 0.3, a layer), Windows and
477                // GNOME paint a hover fill of their own (docs/platform-facts.md:1269,
478                // §2.6)
479                assert_eq!(
480                    variant.menu.hover_background.is_some(),
481                    matches!(*name, "adwaita" | "kde-breeze" | "windows-11"),
482                    "preset '{name}' {label}.menu.hover_background: stated only where \
483                     platform-facts does not give it the selection"
484                );
485            }
486        }
487    }
488
489    /// The hover outlines of the check box and the combo box: stated where
490    /// docs/platform-facts.md gives the platform's value as one colour for
491    /// every state the field covers (§2.5, §2.24).
492    #[test]
493    fn hover_outlines_are_stated_where_the_facts_give_them() {
494        let platform_presets = &[
495            "kde-breeze",
496            "adwaita",
497            "windows-11",
498            "macos-monterey",
499            "macos-tahoe",
500            "material-3",
501            "ios-13",
502        ];
503        for name in platform_presets {
504            let theme = preset(name).unwrap();
505            for (label, variant_opt) in [
506                ("light", theme.light.as_ref()),
507                ("dark", theme.dark.as_ref()),
508            ] {
509                let variant = variant_opt.unwrap();
510                assert_eq!(
511                    variant.checkbox.hover_border_color.is_some(),
512                    matches!(*name, "kde-breeze"),
513                    "preset '{name}' {label}.checkbox.hover_border_color: stated only where \
514                     platform-facts gives it"
515                );
516                assert_eq!(
517                    variant.combo_box.hover_border_color.is_some(),
518                    matches!(*name, "kde-breeze" | "material-3"),
519                    "preset '{name}' {label}.combo_box.hover_border_color: stated only where \
520                     platform-facts gives it"
521                );
522            }
523        }
524    }
525
526    /// A toolbar button's states: stated where the facts give them as one
527    /// colour for everything they cover (docs/platform-facts.md §2.13).
528    #[test]
529    fn toolbar_button_states_are_stated_where_the_facts_give_them() {
530        let platform_presets = &[
531            "kde-breeze",
532            "adwaita",
533            "windows-11",
534            "macos-monterey",
535            "macos-tahoe",
536            "material-3",
537            "ios-13",
538        ];
539        for name in platform_presets {
540            let theme = preset(name).unwrap();
541            for (label, variant_opt) in [
542                ("light", theme.light.as_ref()),
543                ("dark", theme.dark.as_ref()),
544            ] {
545                let variant = variant_opt.unwrap();
546                let fills = matches!(*name, "adwaita" | "kde-breeze" | "windows-11");
547                for (key, value) in [
548                    (
549                        "button_hover_background",
550                        variant.toolbar.button_hover_background,
551                    ),
552                    (
553                        "button_active_background",
554                        variant.toolbar.button_active_background,
555                    ),
556                    (
557                        "button_checked_background",
558                        variant.toolbar.button_checked_background,
559                    ),
560                ] {
561                    assert_eq!(
562                        value.is_some(),
563                        fills,
564                        "preset '{name}' {label}.toolbar.{key}: stated only where \
565                         platform-facts gives it"
566                    );
567                }
568                assert_eq!(
569                    variant.toolbar.button_hover_border_color.is_some(),
570                    matches!(*name, "kde-breeze"),
571                    "preset '{name}' {label}.toolbar.button_hover_border_color: stated only \
572                     where platform-facts gives it"
573                );
574            }
575        }
576    }
577
578    #[test]
579    fn issue_4_leftovers_are_stated_by_kde_breeze_alone() {
580        for info in list_presets() {
581            let name = info.key;
582            let theme = preset(name).unwrap();
583            for (label, variant_opt) in [
584                ("light", theme.light.as_ref()),
585                ("dark", theme.dark.as_ref()),
586            ] {
587                let variant = variant_opt.unwrap();
588                for (path, stated) in [
589                    (
590                        "menu.hover_border_color",
591                        variant.menu.hover_border_color.is_some(),
592                    ),
593                    (
594                        "menu.bar_hover_background",
595                        variant.menu.bar_hover_background.is_some(),
596                    ),
597                    (
598                        "menu.bar_open_background",
599                        variant.menu.bar_open_background.is_some(),
600                    ),
601                    (
602                        "menu.bar_hover_text_color",
603                        variant.menu.bar_hover_text_color.is_some(),
604                    ),
605                    (
606                        "menu.bar_padding_horizontal",
607                        variant.menu.bar_padding_horizontal.is_some(),
608                    ),
609                    (
610                        "menu.bar_padding_vertical",
611                        variant.menu.bar_padding_vertical.is_some(),
612                    ),
613                    (
614                        "list.hover_border_color",
615                        variant.list.hover_border_color.is_some(),
616                    ),
617                    ("menu.min_row_height", variant.menu.min_row_height.is_some()),
618                    (
619                        "menu.active_background",
620                        variant.menu.active_background.is_some(),
621                    ),
622                    (
623                        "menu.active_text_color",
624                        variant.menu.active_text_color.is_some(),
625                    ),
626                    (
627                        "menu.panel_padding_horizontal",
628                        variant.menu.panel_padding_horizontal.is_some(),
629                    ),
630                    (
631                        "menu.panel_padding_vertical",
632                        variant.menu.panel_padding_vertical.is_some(),
633                    ),
634                    (
635                        "list.header_separator_color",
636                        variant.list.header_separator_color.is_some(),
637                    ),
638                    (
639                        "slider.thumb_border_color",
640                        variant.slider.thumb_border_color.is_some(),
641                    ),
642                    (
643                        "slider.thumb_border_line_width",
644                        variant.slider.thumb_border_line_width.is_some(),
645                    ),
646                    (
647                        "slider.thumb_hover_border_color",
648                        variant.slider.thumb_hover_border_color.is_some(),
649                    ),
650                    (
651                        "slider.thumb_focus_border_color",
652                        variant.slider.thumb_focus_border_color.is_some(),
653                    ),
654                    (
655                        "toolbar.button_checked_border_color",
656                        variant.toolbar.button_checked_border_color.is_some(),
657                    ),
658                    (
659                        "combo_box.open_background",
660                        variant.combo_box.open_background.is_some(),
661                    ),
662                    (
663                        "combo_box.open_border_color",
664                        variant.combo_box.open_border_color.is_some(),
665                    ),
666                    (
667                        "defaults.font_whole_pixels",
668                        variant.defaults.font_whole_pixels.is_some(),
669                    ),
670                ] {
671                    assert_eq!(
672                        stated,
673                        name == "kde-breeze",
674                        "preset '{name}' {label}.{path}: stated only by kde-breeze (rationale §2)"
675                    );
676                }
677                if name == "kde-breeze" {
678                    assert!(
679                        variant.slider.thumb_hover_color.is_none(),
680                        "preset '{name}' {label}.slider.thumb_hover_color: the handle keeps its fill under the pointer (rationale E8)"
681                    );
682                }
683            }
684        }
685    }
686
687    // === resolve()/validate() integration tests (PRESET-03) ===
688
689    #[test]
690    fn all_presets_resolve_validate() {
691        for info in list_presets() {
692            let name = info.key;
693            let theme = preset(name).unwrap();
694            if let Some(mut light) = theme.light.clone() {
695                light.resolve_all();
696                light.validate().unwrap_or_else(|e| {
697                    panic!("preset {name} light variant failed validation: {e}");
698                });
699            }
700            if let Some(mut dark) = theme.dark.clone() {
701                dark.resolve_all();
702                dark.validate().unwrap_or_else(|e| {
703                    panic!("preset {name} dark variant failed validation: {e}");
704                });
705            }
706        }
707    }
708
709    #[test]
710    fn all_presets_indicator_color_inherits_accent_text_color() {
711        // platform-facts.md §2.5 records the check mark / radio dot as the
712        // on-accent colour on all four platforms, and it is painted on
713        // checkbox.checked_background <- defaults.accent_color.
714        for info in list_presets() {
715            let name = info.key;
716            let theme = preset(name).unwrap();
717            for (label, variant_opt) in
718                [("light", theme.light.clone()), ("dark", theme.dark.clone())]
719            {
720                let Some(mut variant) = variant_opt else {
721                    continue;
722                };
723                if variant.checkbox.indicator_color.is_some() {
724                    continue;
725                }
726                variant.resolve_all();
727                assert_eq!(
728                    variant.checkbox.indicator_color, variant.defaults.accent_text_color,
729                    "preset '{name}' {label}.checkbox.indicator_color should inherit \
730                     defaults.accent_text_color"
731                );
732            }
733        }
734    }
735
736    #[test]
737    fn resolve_fills_accent_derived_fields() {
738        // Load a preset that only has accent set (not explicit widget accent-derived fields).
739        // After resolve(), the accent-derived fields should be populated.
740        let theme = preset("catppuccin-mocha").unwrap();
741        let mut light = theme.light.clone().unwrap();
742
743        // Before resolve: accent-derived fields should be None (not in preset TOML)
744        assert!(
745            light.button.primary_background.is_none(),
746            "primary_background should be None pre-resolve"
747        );
748        assert!(
749            light.checkbox.checked_background.is_none(),
750            "checkbox.checked_background should be None pre-resolve"
751        );
752        assert!(
753            light.slider.fill_color.is_none(),
754            "slider.fill should be None pre-resolve"
755        );
756        assert!(
757            light.progress_bar.fill_color.is_none(),
758            "progress_bar.fill should be None pre-resolve"
759        );
760        assert!(
761            light.switch.checked_background.is_none(),
762            "switch.checked_background should be None pre-resolve"
763        );
764
765        light.resolve();
766
767        // After resolve: all accent-derived fields should equal accent
768        let accent = light.defaults.accent_color.unwrap();
769        assert_eq!(
770            light.button.primary_background,
771            Some(accent),
772            "button.primary_background should match accent"
773        );
774        assert_eq!(
775            light.checkbox.checked_background,
776            Some(accent),
777            "checkbox.checked_background should match accent"
778        );
779        assert_eq!(
780            light.slider.fill_color,
781            Some(accent),
782            "slider.fill should match accent"
783        );
784        assert_eq!(
785            light.progress_bar.fill_color,
786            Some(accent),
787            "progress_bar.fill should match accent"
788        );
789        assert_eq!(
790            light.switch.checked_background,
791            Some(accent),
792            "switch.checked_background should match accent"
793        );
794    }
795
796    #[test]
797    fn resolve_then_validate_produces_complete_theme() {
798        let theme = preset("catppuccin-mocha").unwrap();
799        let mut light = theme.light.clone().unwrap();
800        light.resolve_all();
801        let resolved = light.validate().unwrap();
802
803        assert_eq!(resolved.defaults.font.family.as_ref(), "Inter");
804        assert_eq!(resolved.defaults.font.size, 14.0);
805        assert_eq!(resolved.defaults.font.weight, 400);
806        assert_eq!(resolved.defaults.line_height, 1.2);
807        assert_eq!(resolved.defaults.border.corner_radius, 8.0);
808        assert_eq!(resolved.defaults.focus_ring_width, 2.0);
809        assert_eq!(resolved.defaults.icon_sizes.toolbar, 24.0);
810        assert_eq!(resolved.defaults.icon_sizes.toolbar, 24.0);
811        // Window inherits from defaults
812        assert_eq!(
813            resolved.window.background_color,
814            resolved.defaults.background_color
815        );
816        // icon_set is now on Theme, not on ResolvedTheme
817        assert_eq!(theme.icon_set, Some(crate::IconSet::Lucide));
818    }
819
820    #[test]
821    fn font_subfield_inheritance_integration() {
822        // Load a preset, set menu.font to only have size=12.0 (clear family/weight),
823        // resolve, and verify family/weight are inherited from defaults.
824        let theme = preset("catppuccin-mocha").unwrap();
825        let mut light = theme.light.clone().unwrap();
826
827        // Set partial font on menu
828        use crate::model::FontSpec;
829        use crate::model::font::FontSize;
830        light.menu.font = Some(FontSpec {
831            family: None,
832            size: Some(FontSize::Px(12.0)),
833            weight: None,
834            ..Default::default()
835        });
836
837        light.resolve_all();
838        let resolved = light.validate().unwrap();
839
840        // menu font should have inherited family/weight from defaults
841        assert_eq!(
842            resolved.menu.font.family.as_ref(),
843            "Inter",
844            "menu font family should inherit from defaults"
845        );
846        assert_eq!(
847            resolved.menu.font.size, 12.0,
848            "menu font size should be the explicit value"
849        );
850        assert_eq!(
851            resolved.menu.font.weight, 400,
852            "menu font weight should inherit from defaults"
853        );
854    }
855
856    #[test]
857    fn text_scale_inheritance_integration() {
858        // Load a preset, ensure text_scale.caption gets populated from defaults.
859        let theme = preset("catppuccin-mocha").unwrap();
860        let mut light = theme.light.clone().unwrap();
861
862        // Clear caption to test inheritance
863        light.text_scale.caption = None;
864
865        light.resolve_all();
866        let resolved = light.validate().unwrap();
867
868        // caption should have been populated from defaults.font (no ratio)
869        // defaults.font.size = 14.0, so caption.size = 14.0
870        let expected_size = 14.0;
871        assert!(
872            (resolved.text_scale.caption.size - expected_size).abs() < 0.01,
873            "caption size = defaults.font.size, got {}",
874            resolved.text_scale.caption.size
875        );
876        assert_eq!(
877            resolved.text_scale.caption.weight, 400,
878            "caption weight from defaults.font.weight"
879        );
880        // line_height = defaults.line_height * caption_size = 1.2 * 14.0 = 16.8
881        let expected_lh = 1.2 * expected_size;
882        assert!(
883            (resolved.text_scale.caption.line_height - expected_lh).abs() < 0.01,
884            "caption line_height should be line_height_multiplier * caption_size = {expected_lh}, got {}",
885            resolved.text_scale.caption.line_height
886        );
887    }
888
889    // NOTE: all_presets_round_trip_exact is covered by
890    // tests/preset_loading.rs::all_presets_round_trip_toml.
891
892    #[test]
893    fn list_presets_for_platform_returns_subset() {
894        let all = list_presets();
895        let filtered = list_presets_for_platform();
896        // Filtered list should be a subset of all presets
897        for info in &filtered {
898            assert!(
899                all.iter().any(|a| a.key == info.key),
900                "filtered preset '{}' not in full list",
901                info.key
902            );
903        }
904        // Community themes should always be present
905        let community = &[
906            "catppuccin-latte",
907            "catppuccin-frappe",
908            "catppuccin-macchiato",
909            "catppuccin-mocha",
910            "nord",
911            "dracula",
912            "gruvbox",
913            "solarized",
914            "tokyo-night",
915            "one-dark",
916        ];
917        for name in community {
918            assert!(
919                filtered.iter().any(|info| info.key == *name),
920                "community preset '{name}' should always be in filtered list"
921            );
922        }
923        // material-3 is cross-platform, always present
924        assert!(
925            filtered.iter().any(|info| info.key == "material-3"),
926            "material-3 should always be in filtered list"
927        );
928    }
929}