Skip to main content

native_theme/model/
mod.rs

1// Theme model: ThemeMode and Theme, plus sub-module re-exports
2
3/// Light or dark color mode preference.
4///
5/// Used by [`SystemTheme`](crate::SystemTheme) to indicate the OS color
6/// mode and by [`SystemTheme::pick()`](crate::SystemTheme::pick) to select
7/// a resolved variant.
8///
9/// # Examples
10///
11/// ```
12/// use native_theme::theme::ColorMode;
13///
14/// let mode = ColorMode::Dark;
15/// assert!(mode.is_dark());
16/// ```
17#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
18#[non_exhaustive]
19pub enum ColorMode {
20    /// Light appearance.
21    Light,
22    /// Dark appearance.
23    Dark,
24}
25
26impl ColorMode {
27    /// Returns `true` if this is dark mode.
28    #[must_use]
29    pub fn is_dark(self) -> bool {
30        matches!(self, Self::Dark)
31    }
32}
33
34/// Animated icon types (frame sequences and transforms).
35pub(crate) mod animated;
36/// Disclosure arrow placement convention.
37pub(crate) mod arrow_side;
38/// Border specification sub-struct for widget border properties.
39pub(crate) mod border;
40/// Bundled SVG icon lookup tables.
41pub(crate) mod bundled;
42/// Global theme defaults shared across widgets.
43pub(crate) mod defaults;
44/// Dialog entrance motion convention.
45pub(crate) mod dialog_entrance_style;
46/// Dialog button ordering convention.
47pub(crate) mod dialog_order;
48/// Per-widget font specification and text scale.
49pub(crate) mod font;
50/// Per-context icon sizes.
51pub(crate) mod icon_sizes;
52/// Icon roles, sets, and provider trait.
53pub(crate) mod icons;
54/// Resolved (non-optional) theme types produced after resolution.
55pub(crate) mod resolved;
56/// Active-tab indicator placement convention.
57pub(crate) mod tab_indicator_side;
58/// Per-widget struct pairs and macros.
59pub(crate) mod widgets;
60
61pub use animated::{
62    AnimatedIcon, EmptyFrameListError, FrameList, FramesData, TransformAnimation, TransformData,
63};
64pub use arrow_side::ArrowSide;
65pub use border::{
66    DefaultsBorderSpec, ResolvedDefaultsBorder, ResolvedPadding, ResolvedWidgetBorder,
67    WidgetBorderSpec,
68};
69// Crate-internal; external code uses the per-set loaders in `crate::icons`.
70pub(crate) use bundled::{bundled_icon_by_name, bundled_icon_svg};
71pub use defaults::ThemeDefaults;
72pub use dialog_entrance_style::DialogEntranceStyle;
73pub use dialog_order::DialogButtonOrder;
74pub use font::{
75    FontSize, FontSpec, FontStyle, ResolvedFontSpec, TextScale, TextScaleEntry, intern_font_family,
76};
77pub use icon_sizes::IconSizes;
78pub use icons::{IconData, IconProvider, IconRole, IconSet, RgbaData, icon_name};
79pub use resolved::{
80    Resolved, ResolvedDefaults, ResolvedIconSizes, ResolvedTextScale, ResolvedTextScaleEntry,
81    ResolvedTheme,
82};
83pub use tab_indicator_side::TabIndicatorSide;
84pub use widgets::*; // 27 XxxTheme + ResolvedXxxTheme pairs: 26 per-variant widgets + LayoutTheme
85
86use std::borrow::Cow;
87
88use serde::{Deserialize, Serialize};
89
90/// A single light or dark theme variant containing all visual properties.
91///
92/// Composes defaults, per-widget structs, and optional text scale into one coherent set.
93/// Empty sub-structs are omitted from serialization to keep TOML files clean.
94///
95/// # Examples
96///
97/// ```
98/// use native_theme::theme::ThemeMode;
99/// use native_theme::color::Rgba;
100///
101/// let mut variant = ThemeMode::default();
102/// variant.defaults.accent_color = Some(Rgba::rgb(0, 120, 215));
103/// variant.defaults.font.family = Some("Inter".into());
104/// assert!(!variant.is_empty());
105/// ```
106#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
107#[serde(default)]
108pub struct ThemeMode {
109    /// Global defaults inherited by all widgets.
110    #[serde(default, skip_serializing_if = "ThemeDefaults::is_empty")]
111    pub defaults: ThemeDefaults,
112
113    /// Per-role text scale overrides.
114    #[serde(default, skip_serializing_if = "TextScale::is_empty")]
115    pub text_scale: TextScale,
116
117    /// Window chrome: background, title bar, radius, shadow.
118    #[serde(default, skip_serializing_if = "WindowTheme::is_empty")]
119    pub window: WindowTheme,
120
121    /// Push button: colors, sizing, spacing, geometry.
122    #[serde(default, skip_serializing_if = "ButtonTheme::is_empty")]
123    pub button: ButtonTheme,
124
125    /// Single-line and multi-line text input fields.
126    #[serde(default, skip_serializing_if = "InputTheme::is_empty")]
127    pub input: InputTheme,
128
129    /// Multi-line text field: its own padding; the rest is `input`'s.
130    #[serde(default, skip_serializing_if = "TextAreaTheme::is_empty")]
131    pub text_area: TextAreaTheme,
132
133    /// Checkbox and radio button indicator geometry.
134    #[serde(default, skip_serializing_if = "CheckboxTheme::is_empty")]
135    pub checkbox: CheckboxTheme,
136
137    /// Popup and context menu appearance.
138    #[serde(default, skip_serializing_if = "MenuTheme::is_empty")]
139    pub menu: MenuTheme,
140
141    /// Tooltip popup appearance.
142    #[serde(default, skip_serializing_if = "TooltipTheme::is_empty")]
143    pub tooltip: TooltipTheme,
144
145    /// Scrollbar colors and geometry.
146    #[serde(default, skip_serializing_if = "ScrollbarTheme::is_empty")]
147    pub scrollbar: ScrollbarTheme,
148
149    /// Slider control colors and geometry.
150    #[serde(default, skip_serializing_if = "SliderTheme::is_empty")]
151    pub slider: SliderTheme,
152
153    /// Progress bar colors and geometry.
154    #[serde(default, skip_serializing_if = "ProgressBarTheme::is_empty")]
155    pub progress_bar: ProgressBarTheme,
156
157    /// Tab bar colors and sizing.
158    #[serde(default, skip_serializing_if = "TabTheme::is_empty")]
159    pub tab: TabTheme,
160
161    /// Sidebar panel background and foreground colors.
162    #[serde(default, skip_serializing_if = "SidebarTheme::is_empty")]
163    pub sidebar: SidebarTheme,
164
165    /// Toolbar sizing, spacing, and font.
166    #[serde(default, skip_serializing_if = "ToolbarTheme::is_empty")]
167    pub toolbar: ToolbarTheme,
168
169    /// Status bar font.
170    #[serde(default, skip_serializing_if = "StatusBarTheme::is_empty")]
171    pub status_bar: StatusBarTheme,
172
173    /// List and table colors and row geometry.
174    #[serde(default, skip_serializing_if = "ListTheme::is_empty")]
175    pub list: ListTheme,
176
177    /// Popover / dropdown panel appearance.
178    #[serde(default, skip_serializing_if = "PopoverTheme::is_empty")]
179    pub popover: PopoverTheme,
180
181    /// Splitter handle width.
182    #[serde(default, skip_serializing_if = "SplitterTheme::is_empty")]
183    pub splitter: SplitterTheme,
184
185    /// Separator line color.
186    #[serde(default, skip_serializing_if = "SeparatorTheme::is_empty")]
187    pub separator: SeparatorTheme,
188
189    /// Toggle switch track, thumb, and geometry.
190    #[serde(default, skip_serializing_if = "SwitchTheme::is_empty")]
191    pub switch: SwitchTheme,
192
193    /// Dialog sizing, spacing, button order, and title font.
194    #[serde(default, skip_serializing_if = "DialogTheme::is_empty")]
195    pub dialog: DialogTheme,
196
197    /// Spinner / indeterminate progress indicator.
198    #[serde(default, skip_serializing_if = "SpinnerTheme::is_empty")]
199    pub spinner: SpinnerTheme,
200
201    /// ComboBox / dropdown trigger sizing.
202    #[serde(default, skip_serializing_if = "ComboBoxTheme::is_empty")]
203    pub combo_box: ComboBoxTheme,
204
205    /// Segmented control sizing.
206    #[serde(default, skip_serializing_if = "SegmentedControlTheme::is_empty")]
207    pub segmented_control: SegmentedControlTheme,
208
209    /// Card / container colors and geometry.
210    #[serde(default, skip_serializing_if = "CardTheme::is_empty")]
211    pub card: CardTheme,
212
213    /// Expander / disclosure row geometry.
214    #[serde(default, skip_serializing_if = "ExpanderTheme::is_empty")]
215    pub expander: ExpanderTheme,
216
217    /// Hyperlink colors and underline setting.
218    #[serde(default, skip_serializing_if = "LinkTheme::is_empty")]
219    pub link: LinkTheme,
220}
221
222impl_merge!(ThemeMode {
223    nested {
224        defaults, text_scale, window, button, input, text_area, checkbox, menu,
225        tooltip, scrollbar, slider, progress_bar, tab, sidebar,
226        toolbar, status_bar, list, popover, splitter, separator,
227        switch, dialog, spinner, combo_box, segmented_control,
228        card, expander, link
229    }
230});
231
232/// A complete native theme with a name and optional light/dark variants.
233///
234/// This is the top-level type that theme files deserialize into and that
235/// platform readers produce.
236///
237/// # Examples
238///
239/// ```
240/// use native_theme::theme::Theme;
241///
242/// // Load a bundled preset
243/// let theme = Theme::preset("dracula").unwrap();
244/// assert_eq!(theme.name, "Dracula");
245///
246/// // Parse from a TOML string
247/// let toml = r##"
248/// name = "Custom"
249/// [light.defaults]
250/// accent_color = "#ff6600"
251/// "##;
252/// let custom = Theme::from_toml(toml).unwrap();
253/// assert_eq!(custom.name, "Custom");
254///
255/// // Merge themes (overlay wins for populated fields)
256/// let mut base = Theme::preset("catppuccin-mocha").unwrap();
257/// base.merge(&custom);
258/// assert_eq!(base.name, "Catppuccin Mocha"); // base name is preserved
259/// ```
260#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
261pub struct Theme {
262    /// Theme name (e.g., "KDE Breeze", "Adwaita", "Windows 11").
263    ///
264    /// Uses `Cow<'static, str>` so bundled presets can store borrowed
265    /// `&'static str` values without per-load `String` allocations.
266    /// User-provided names (from TOML files or runtime detection)
267    /// are `Cow::Owned`. A TOML file may omit it (an overlay needs no
268    /// name: [`merge`](Self::merge) keeps the base's); it is then empty.
269    #[serde(default)]
270    pub name: Cow<'static, str>,
271
272    /// Light variant of the theme.
273    #[serde(default, skip_serializing_if = "Option::is_none")]
274    pub light: Option<ThemeMode>,
275
276    /// Dark variant of the theme.
277    #[serde(default, skip_serializing_if = "Option::is_none")]
278    pub dark: Option<ThemeMode>,
279
280    /// Layout spacing constants (shared between light and dark variants).
281    #[serde(default, skip_serializing_if = "LayoutTheme::is_empty")]
282    pub layout: LayoutTheme,
283
284    /// Which icon loading mechanism to use (`Freedesktop`, `Material`, `Lucide`,
285    /// `SfSymbols`, `SegoeFluent`). Shared across light and dark variants.
286    /// When `None`, filled during resolution from
287    /// [`system_icon_set()`](crate::detect::system_icon_set).
288    ///
289    /// # Examples
290    ///
291    /// ```
292    /// use native_theme::theme::{Theme, IconSet};
293    ///
294    /// let theme = Theme::preset("material-3")?;
295    /// assert_eq!(theme.icon_set, Some(IconSet::Material));
296    /// # Ok::<(), native_theme::error::Error>(())
297    /// ```
298    #[serde(default, skip_serializing_if = "Option::is_none")]
299    pub icon_set: Option<IconSet>,
300
301    /// Visual icon theme name (shared across light and dark variants).
302    ///
303    /// Acts as the default when a variant's
304    /// [`ThemeDefaults::icon_theme`](crate::model::ThemeDefaults::icon_theme)
305    /// is `None`. Variants that need a different icon theme per color mode
306    /// (e.g. KDE Plasma: `"breeze"` light / `"breeze-dark"` dark) set the
307    /// override on [`ThemeDefaults::icon_theme`].
308    ///
309    /// Precedence at resolve time:
310    /// 1. [`ThemeMode::defaults.icon_theme`](crate::model::ThemeDefaults::icon_theme) — per-variant override (if set)
311    /// 2. `Theme::icon_theme` — this field (if set)
312    /// 3. [`system_icon_theme()`](crate::detect::system_icon_theme) — runtime
313    ///    detection; none where it fails
314    ///
315    /// See `docs/archive/v0.5.7_gaps.md` §G4 for the design rationale.
316    #[serde(default, skip_serializing_if = "Option::is_none")]
317    pub icon_theme: Option<Cow<'static, str>>,
318}
319
320impl Default for Theme {
321    fn default() -> Self {
322        Self {
323            name: Cow::Borrowed(""),
324            light: None,
325            dark: None,
326            layout: LayoutTheme::default(),
327            icon_set: None,
328            icon_theme: None,
329        }
330    }
331}
332
333impl Theme {
334    /// Merge an overlay theme into this theme.
335    ///
336    /// The base name is kept. For each variant (light/dark):
337    /// - If both base and overlay have a variant, they are merged recursively.
338    /// - If only the overlay has a variant, it is cloned into the base.
339    /// - If only the base has a variant (or neither), no change.
340    pub fn merge(&mut self, overlay: &Self) {
341        // Keep base name (do not overwrite)
342
343        match (&mut self.light, &overlay.light) {
344            (Some(base), Some(over)) => base.merge(over),
345            (None, Some(over)) => self.light = Some(over.clone()),
346            _ => {}
347        }
348
349        match (&mut self.dark, &overlay.dark) {
350            (Some(base), Some(over)) => base.merge(over),
351            (None, Some(over)) => self.dark = Some(over.clone()),
352            _ => {}
353        }
354
355        self.layout.merge(&overlay.layout);
356
357        if overlay.icon_set.is_some() {
358            self.icon_set = overlay.icon_set;
359        }
360
361        if overlay.icon_theme.is_some() {
362            self.icon_theme.clone_from(&overlay.icon_theme);
363        }
364    }
365
366    /// Pick the appropriate variant for the given mode, with cross-fallback.
367    ///
368    /// When `mode` is [`ColorMode::Dark`], prefers `dark` and falls back to `light`.
369    /// When `mode` is [`ColorMode::Light`], prefers `light` and falls back to `dark`.
370    /// [`resolve`](Self::resolve) records the variant it took in
371    /// [`Resolved::mode`], so a fallback is visible after resolution.
372    ///
373    /// # Errors
374    ///
375    /// Returns [`Error::NoVariant`](crate::Error::NoVariant) if the theme has
376    /// no variants at all.
377    pub fn pick_variant(&self, mode: ColorMode) -> crate::Result<&ThemeMode> {
378        self.pick_variant_with_mode(mode)
379            .map(|(_, variant)| variant)
380    }
381
382    /// [`pick_variant`](Self::pick_variant), also returning the mode of the
383    /// variant it took (`Dark` iff `self.dark` was used).
384    pub(crate) fn pick_variant_with_mode(
385        &self,
386        mode: ColorMode,
387    ) -> crate::Result<(ColorMode, &ThemeMode)> {
388        let dark = self.dark.as_ref().map(|v| (ColorMode::Dark, v));
389        let light = self.light.as_ref().map(|v| (ColorMode::Light, v));
390        match mode {
391            ColorMode::Dark => dark.or(light),
392            ColorMode::Light => light.or(dark),
393        }
394        .ok_or(crate::Error::NoVariant { mode })
395    }
396
397    /// Extract a variant by consuming the theme, avoiding a clone.
398    ///
399    /// When `mode` is [`ColorMode::Dark`], returns the `dark` variant (falling back to
400    /// `light`). When [`ColorMode::Light`], returns `light` (falling back to `dark`).
401    ///
402    /// Use this when you own the `Theme` and don't need it afterward.
403    /// For read-only inspection, use [`pick_variant()`](Self::pick_variant).
404    ///
405    /// # Errors
406    ///
407    /// Returns [`Error::NoVariant`](crate::Error::NoVariant) if the theme has
408    /// no variants at all.
409    ///
410    /// # Examples
411    ///
412    /// ```
413    /// use native_theme::theme::ColorMode;
414    ///
415    /// let theme = native_theme::theme::Theme::preset("dracula")?;
416    /// let variant = theme.into_variant(ColorMode::Dark)?;
417    /// let resolved = variant.resolve_system()?;
418    /// # Ok::<(), Box<dyn std::error::Error>>(())
419    /// ```
420    pub fn into_variant(self, mode: ColorMode) -> crate::Result<ThemeMode> {
421        match mode {
422            ColorMode::Dark => self.dark.or(self.light),
423            ColorMode::Light => self.light.or(self.dark),
424        }
425        .ok_or(crate::Error::NoVariant { mode })
426    }
427
428    /// Resolve this theme for a color mode into a ready-to-render bundle.
429    ///
430    /// Picks the variant (with cross-fallback), applies inheritance and
431    /// validation to produce a [`ResolvedTheme`], and resolves the shared
432    /// `icon_set` / `icon_theme` fields. This is the one-call path from a
433    /// parsed [`Theme`] to the values a UI framework needs.
434    ///
435    /// `icon_set` falls back to
436    /// [`system_icon_set()`](crate::detect::system_icon_set) when the TOML
437    /// omits it. `icon_theme` uses three-tier precedence:
438    ///
439    /// 1. The picked variant's `defaults.icon_theme` (per-mode override).
440    /// 2. [`Theme::icon_theme`] (shared across variants).
441    /// 3. [`system_icon_theme()`](crate::detect::system_icon_theme) (runtime
442    ///    detect).
443    ///
444    /// Where no tier gives a name — the TOML states none and detection
445    /// fails — [`Resolved::icon_theme`] is `None`; the resolution itself
446    /// does not fail over it, and
447    /// [`system_icon_theme()`](crate::detect::system_icon_theme) gives the
448    /// reason.
449    /// [`Resolved::icon_theme_explicit`] reports whether tiers 1 or 2
450    /// fired (value came from TOML) versus tier 3 (runtime detection).
451    ///
452    /// Builds its inputs with
453    /// [`ResolutionContext::from_system`](crate::resolve::ResolutionContext::from_system)
454    /// on every call, which reads the environment and configuration files.
455    /// Its font DPI is the platform's constant (72 on macOS, 96 elsewhere);
456    /// the icon theme it detects is cached after the first call until
457    /// [`invalidate_caches()`](crate::detect::invalidate_caches). To
458    /// resolve several variants or themes with one detection, or with
459    /// inputs of your own, build the context once and call
460    /// [`resolve_with`](Self::resolve_with).
461    ///
462    /// # Errors
463    ///
464    /// Returns [`crate::Error::NoVariant`] when the theme has no variants,
465    /// or [`crate::Error::ResolutionIncomplete`] /
466    /// [`crate::Error::ResolutionInvalid`] when the picked variant cannot
467    /// be fully resolved. A value of [`Theme::layout`] out of range is also
468    /// [`crate::Error::ResolutionInvalid`].
469    ///
470    /// # Examples
471    ///
472    /// ```
473    /// use native_theme::theme::{ColorMode, Theme};
474    ///
475    /// // Theme-level `icon_theme` (tier 2) — applies to both modes.
476    /// let material = Theme::preset("material-3")?;
477    /// let r = material.resolve(ColorMode::Dark)?;
478    /// assert_eq!(r.icon_theme.as_deref(), Some("material"));
479    /// assert!(r.icon_theme_explicit);
480    ///
481    /// // Per-variant `icon_theme` (tier 1) — differs by mode.
482    /// let breeze = Theme::preset("kde-breeze")?;
483    /// assert_eq!(breeze.resolve(ColorMode::Light)?.icon_theme.as_deref(), Some("breeze"));
484    /// assert_eq!(breeze.resolve(ColorMode::Dark)?.icon_theme.as_deref(), Some("breeze-dark"));
485    /// # Ok::<(), native_theme::error::Error>(())
486    /// ```
487    pub fn resolve(&self, mode: ColorMode) -> crate::Result<Resolved> {
488        self.resolve_with(mode, &crate::resolve::ResolutionContext::from_system())
489    }
490
491    /// [`resolve`](Self::resolve) with the resolution-time inputs of `ctx`,
492    /// whose `icon_theme` is tier 3. It reads nothing from the system: the
493    /// font DPI, button order and detected icon theme are `ctx`'s.
494    ///
495    /// # Errors
496    ///
497    /// As [`resolve`](Self::resolve).
498    ///
499    /// # Examples
500    ///
501    /// ```
502    /// use native_theme::resolve::ResolutionContext;
503    /// use native_theme::theme::{ColorMode, Theme};
504    ///
505    /// // One context for both variants; 72 DPI makes a point a pixel.
506    /// let ctx = ResolutionContext { font_dpi: 72.0, ..ResolutionContext::for_tests() };
507    /// let breeze = Theme::preset("kde-breeze")?;
508    /// let light = breeze.resolve_with(ColorMode::Light, &ctx)?;
509    /// let dark = breeze.resolve_with(ColorMode::Dark, &ctx)?;
510    /// assert_eq!(light.variant.defaults.font.size, 10.0); // `size_pt = 10.0`
511    /// assert_eq!(light.icon_theme.as_deref(), Some("breeze"));
512    /// assert_eq!(dark.icon_theme.as_deref(), Some("breeze-dark"));
513    /// # Ok::<(), native_theme::error::Error>(())
514    /// ```
515    pub fn resolve_with(
516        &self,
517        mode: ColorMode,
518        ctx: &crate::resolve::ResolutionContext,
519    ) -> crate::Result<Resolved> {
520        let (picked_mode, variant_ref) = self.pick_variant_with_mode(mode)?;
521        crate::resolve::validate_helpers::check_font_dpi(ctx.font_dpi)?;
522        crate::resolve::validate_helpers::check_layout(&self.layout)?;
523
524        let tier1 = variant_ref.defaults.icon_theme.clone();
525        let tier2 = self.icon_theme.clone();
526        let icon_theme_explicit = tier1.is_some() || tier2.is_some();
527        let icon_theme = tier1.or(tier2).or_else(|| ctx.icon_theme.clone());
528
529        let icon_set = self.icon_set.unwrap_or_else(crate::detect::system_icon_set);
530
531        let variant = variant_ref
532            .clone()
533            .into_resolved(ctx)
534            .map_err(|e| e.in_variant(picked_mode))?;
535
536        Ok(Resolved {
537            mode: picked_mode,
538            variant,
539            icon_set,
540            icon_theme,
541            icon_theme_explicit,
542        })
543    }
544
545    /// Returns true when the theme states nothing: no variant, no layout
546    /// value, no icon set and no icon theme. The name is not checked.
547    pub fn is_empty(&self) -> bool {
548        self.light.is_none()
549            && self.dark.is_none()
550            && self.layout.is_empty()
551            && self.icon_set.is_none()
552            && self.icon_theme.is_none()
553    }
554
555    /// Load a bundled theme preset by name.
556    ///
557    /// Returns the preset as a fully populated [`Theme`] with both
558    /// light and dark variants.
559    ///
560    /// # Errors
561    /// Returns [`crate::Error::UnknownPreset`] if the preset name is not recognized.
562    ///
563    /// # Examples
564    /// ```
565    /// let theme = native_theme::theme::Theme::preset("catppuccin-mocha")?;
566    /// assert!(theme.light.is_some());
567    /// # Ok::<(), native_theme::error::Error>(())
568    /// ```
569    ///
570    /// Bundled preset names are `Cow::Borrowed` (no allocation):
571    /// ```
572    /// use native_theme::theme::Theme;
573    ///
574    /// let theme = Theme::preset("dracula")?;
575    /// assert!(matches!(theme.name, std::borrow::Cow::Borrowed(_)));
576    /// # Ok::<(), native_theme::error::Error>(())
577    /// ```
578    pub fn preset(name: &str) -> crate::Result<Self> {
579        crate::presets::preset(name)
580    }
581
582    /// Parse a TOML string into a [`Theme`].
583    ///
584    /// # TOML Format
585    ///
586    /// Theme files use the following structure. Every field is optional,
587    /// `name` included --
588    /// omit any field you don't need. Unknown fields are silently ignored;
589    /// [`lint_toml`](Self::lint_toml) reports them. Hex colors accept
590    /// `#RGB`, `#RGBA`, `#RRGGBB` or `#RRGGBBAA` (the `#` is optional). A size carries its unit in its key:
591    /// `_px` for logical pixels, and `size_pt` or `size_px` for a font.
592    /// A widget border's padding takes one key per side (`padding_top_px`,
593    /// `padding_right_px`, `padding_bottom_px`, `padding_left_px`) or one per
594    /// axis (`padding_horizontal_px`, `padding_vertical_px`), not both for
595    /// the same axis.
596    ///
597    /// ```
598    /// use native_theme::theme::Theme;
599    ///
600    /// let toml = r##"
601    /// name = "My Theme"
602    ///
603    /// [light.defaults]
604    /// accent_color = "#4a90d9"
605    /// background_color = "#fafafa"
606    /// text_color = "#2e3436"
607    /// surface_color = "#ffffff"
608    /// muted_color = "#929292"
609    /// shadow_color = "#00000018"
610    /// danger_color = "#dc3545"
611    /// warning_color = "#f0ad4e"
612    /// success_color = "#28a745"
613    /// info_color = "#4a90d9"
614    /// selection_background = "#4a90d9"
615    /// selection_text_color = "#ffffff"
616    /// link_color = "#2a6cb6"
617    /// focus_ring_color = "#4a90d9"
618    /// disabled_text_color = "#c0c0c0"
619    /// disabled_opacity = 0.5
620    ///
621    /// [light.defaults.font]
622    /// family = "sans-serif"
623    /// size_pt = 10.0
624    ///
625    /// [light.defaults.mono_font]
626    /// family = "monospace"
627    /// size_pt = 10.0
628    ///
629    /// [light.defaults.border]
630    /// color = "#c0c0c0"
631    /// corner_radius_px = 6.0
632    /// corner_radius_lg_px = 12.0
633    /// line_width_px = 1.0
634    /// opacity = 0.15
635    /// shadow_enabled = true
636    ///
637    /// [light.button]
638    /// background_color = "#e8e8e8"
639    /// min_height_px = 32.0
640    ///
641    /// [light.button.font]
642    /// color = "#2e3436"
643    ///
644    /// [light.button.border]
645    /// padding_horizontal_px = 12.0
646    /// padding_vertical_px = 6.0
647    ///
648    /// [light.tooltip]
649    /// background_color = "#2e3436"
650    /// max_width_px = 300.0
651    ///
652    /// [light.tooltip.font]
653    /// color = "#f0f0f0"
654    ///
655    /// ## [dark.*] mirrors the same structure as [light.*]
656    /// "##;
657    ///
658    /// assert!(Theme::lint_toml(toml)?.is_empty());
659    /// let theme = Theme::from_toml(toml)?;
660    /// let light = theme.light.as_ref();
661    /// assert_eq!(light.and_then(|v| v.button.min_height), Some(32.0));
662    /// assert_eq!(light.and_then(|v| v.tooltip.max_width), Some(300.0));
663    /// assert_eq!(
664    ///     light.and_then(|v| v.defaults.border.corner_radius),
665    ///     Some(6.0)
666    /// );
667    /// let button_border = light.and_then(|v| v.button.border.as_ref());
668    /// assert_eq!(button_border.and_then(|b| b.padding_left), Some(12.0));
669    /// assert_eq!(button_border.and_then(|b| b.padding_bottom), Some(6.0));
670    /// # Ok::<(), native_theme::error::Error>(())
671    /// ```
672    ///
673    /// # Errors
674    /// Returns [`crate::Error::Toml`] if the TOML is invalid.
675    ///
676    /// # Examples
677    /// ```
678    /// let toml = r##"
679    /// name = "My Theme"
680    /// [light.defaults]
681    /// accent_color = "#ff0000"
682    /// "##;
683    /// let theme = native_theme::theme::Theme::from_toml(toml).unwrap();
684    /// assert_eq!(theme.name, "My Theme");
685    /// ```
686    pub fn from_toml(toml_str: &str) -> crate::Result<Self> {
687        crate::presets::from_toml(toml_str)
688    }
689
690    /// Load a [`Theme`] from a TOML file.
691    ///
692    /// # Errors
693    /// Returns [`crate::Error::Io`] if the file cannot be read, or
694    /// [`crate::Error::Toml`] if the TOML content is invalid.
695    ///
696    /// # Examples
697    /// ```no_run
698    /// let theme = native_theme::theme::Theme::from_file("my-theme.toml").unwrap();
699    /// ```
700    pub fn from_file(path: impl AsRef<std::path::Path>) -> crate::Result<Self> {
701        crate::presets::from_file(path)
702    }
703
704    /// List all available bundled presets with structured metadata.
705    ///
706    /// Returns a static slice of [`PresetInfo`](crate::presets::PresetInfo) entries,
707    /// one per bundled preset. Each entry carries the machine-readable key,
708    /// human-readable display name, and target platform tags.
709    ///
710    /// # Examples
711    /// ```
712    /// let presets = native_theme::theme::Theme::list_presets();
713    /// assert_eq!(presets.len(), 17);
714    /// assert_eq!(presets[0].key, "kde-breeze");
715    /// assert_eq!(presets[0].display_name, "KDE Breeze");
716    /// ```
717    #[must_use]
718    pub fn list_presets() -> &'static [crate::presets::PresetInfo] {
719        crate::presets::list_presets()
720    }
721
722    /// List presets appropriate for the current platform, with structured metadata.
723    ///
724    /// Platform presets are included where their platform tag matches:
725    /// kde-breeze on KDE, adwaita on Linux, windows-11 on Windows,
726    /// macos-monterey and macos-tahoe on macOS, ios-13 on macOS and iOS. `material-3` and the
727    /// community themes are always included.
728    ///
729    /// Note: Unlike [`list_presets()`](Self::list_presets) which returns a static slice,
730    /// this method returns `Vec` because it filters the preset list at runtime based
731    /// on the detected platform.
732    ///
733    /// # Examples
734    /// ```
735    /// let presets = native_theme::theme::Theme::list_presets_for_platform();
736    /// // On Linux KDE: kde-breeze, adwaita, material-3 and all community themes
737    /// // On Windows: windows-11, material-3 and all community themes
738    /// assert!(!presets.is_empty());
739    /// ```
740    #[must_use]
741    pub fn list_presets_for_platform() -> Vec<crate::presets::PresetInfo> {
742        crate::presets::list_presets_for_platform()
743    }
744
745    /// Serialize this theme to a TOML string.
746    ///
747    /// # Errors
748    /// Returns [`crate::Error::ReaderFailed`] if serialization fails.
749    ///
750    /// # Examples
751    /// ```
752    /// let theme = native_theme::theme::Theme::preset("catppuccin-mocha").unwrap();
753    /// let toml_str = theme.to_toml().unwrap();
754    /// assert!(toml_str.contains("name = \"Catppuccin Mocha\""));
755    /// ```
756    pub fn to_toml(&self) -> crate::Result<String> {
757        crate::presets::to_toml(self)
758    }
759
760    /// Check a TOML string for unrecognized field names.
761    ///
762    /// Parses the TOML as a generic table and walks all keys, comparing
763    /// against the known fields for each section. Returns a `Vec<String>`
764    /// of warnings for any keys that don't match a known field. An empty
765    /// vec means all keys are recognized.
766    ///
767    /// This is an opt-in linting tool for theme authors. It does NOT affect
768    /// `from_toml()` behavior (which silently ignores unknown fields via serde).
769    ///
770    /// # Errors
771    ///
772    /// Returns `Err` if the TOML string cannot be parsed at all.
773    ///
774    /// # Examples
775    ///
776    /// ```
777    /// let warnings = native_theme::theme::Theme::lint_toml(r##"
778    /// name = "Test"
779    /// [light.defaults]
780    /// backround = "#ffffff"
781    /// "##).unwrap();
782    /// assert_eq!(warnings.len(), 1);
783    /// assert!(warnings[0].contains("backround"));
784    /// ```
785    pub fn lint_toml(toml_str: &str) -> crate::Result<Vec<String>> {
786        let value: toml::Value =
787            toml::from_str(toml_str).map_err(|e: toml::de::Error| crate::Error::Toml(e))?;
788
789        let mut warnings = Vec::new();
790
791        let top_table = match &value {
792            toml::Value::Table(t) => t,
793            _ => return Ok(warnings),
794        };
795
796        // Known top-level keys
797        const TOP_KEYS: &[&str] = &["name", "light", "dark", "layout", "icon_set", "icon_theme"];
798
799        for key in top_table.keys() {
800            if !TOP_KEYS.contains(&key.as_str()) {
801                warnings.push(format!("unknown field: {key}"));
802            }
803        }
804
805        // Structural variant-level keys that are NOT widgets
806        const STRUCTURAL_KEYS: &[&str] = &["defaults", "text_scale"];
807
808        // Phase 93-05 G5: build BOTH field registries from inventory.
809        // - widget_registry: one entry per per-variant widget (ButtonTheme ->
810        //   "button", etc.) populated by #[derive(ThemeWidget)].
811        // - struct_registry: one entry per plain struct (FontSpec, IconSizes,
812        //   ThemeDefaults, LayoutTheme, ...) populated by #[derive(ThemeFields)].
813        let widget_registry: std::collections::HashMap<&str, &[&str]> =
814            inventory::iter::<crate::resolve::WidgetFieldInfo>()
815                .map(|info| (info.widget_name, info.field_names))
816                .collect();
817        let struct_registry: std::collections::HashMap<&str, &[&str]> =
818            inventory::iter::<crate::resolve::FieldInfo>()
819                .map(|info| (info.struct_name, info.field_names))
820                .collect();
821
822        // Helper: fetch a plain-struct field list by type name. Returns None
823        // when the struct did not opt in to ThemeFields -- sub-table linting
824        // is silently skipped in that case, matching the former `continue;`
825        // behaviour when a sub-table's type wasn't recognised.
826        let get_struct_fields =
827            |name: &str| -> Option<&[&str]> { struct_registry.get(name).copied() };
828
829        // Lint a text_scale section
830        let lint_text_scale = |table: &toml::map::Map<String, toml::Value>,
831                               prefix: &str,
832                               warnings: &mut Vec<String>| {
833            let Some(scale_fields) = get_struct_fields("TextScale") else {
834                return;
835            };
836            let entry_fields = get_struct_fields("TextScaleEntry");
837            for key in table.keys() {
838                if !scale_fields.contains(&key.as_str()) {
839                    warnings.push(format!("unknown field: {prefix}.{key}"));
840                } else if let Some(toml::Value::Table(entry_table)) = table.get(key)
841                    && let Some(entry_fields) = entry_fields
842                {
843                    for ekey in entry_table.keys() {
844                        if !entry_fields.contains(&ekey.as_str()) {
845                            warnings.push(format!("unknown field: {prefix}.{key}.{ekey}"));
846                        }
847                    }
848                }
849            }
850        };
851
852        // Lint a defaults section (with nested font, mono_font, border, icon_sizes)
853        let lint_defaults = |table: &toml::map::Map<String, toml::Value>,
854                             prefix: &str,
855                             warnings: &mut Vec<String>| {
856            let Some(defaults_fields) = get_struct_fields("ThemeDefaults") else {
857                return;
858            };
859            for key in table.keys() {
860                if !defaults_fields.contains(&key.as_str()) {
861                    warnings.push(format!("unknown field: {prefix}.{key}"));
862                    continue;
863                }
864                // Check sub-tables for nested struct fields
865                if let Some(toml::Value::Table(sub)) = table.get(key) {
866                    let known = match key.as_str() {
867                        "font" | "mono_font" => get_struct_fields("FontSpec"),
868                        "border" => get_struct_fields("DefaultsBorderSpec"),
869                        "icon_sizes" => get_struct_fields("IconSizes"),
870                        _ => continue,
871                    };
872                    let Some(known) = known else { continue };
873                    for skey in sub.keys() {
874                        if !known.contains(&skey.as_str()) {
875                            warnings.push(format!("unknown field: {prefix}.{key}.{skey}"));
876                        }
877                    }
878                }
879            }
880        };
881
882        // Lint a variant section (light or dark).
883        let lint_variant = |table: &toml::map::Map<String, toml::Value>,
884                            prefix: &str,
885                            warnings: &mut Vec<String>| {
886            for key in table.keys() {
887                let key_str = key.as_str();
888
889                // Check structural keys first, then widget registry
890                let is_structural = STRUCTURAL_KEYS.contains(&key_str);
891                let widget_fields = widget_registry.get(key_str);
892
893                if !is_structural && widget_fields.is_none() {
894                    warnings.push(format!("unknown field: {prefix}.{key}"));
895                    continue;
896                }
897
898                if let Some(toml::Value::Table(sub)) = table.get(key) {
899                    let sub_prefix = format!("{prefix}.{key}");
900                    match key_str {
901                        "defaults" => lint_defaults(sub, &sub_prefix, warnings),
902                        "text_scale" => lint_text_scale(sub, &sub_prefix, warnings),
903                        _ => {
904                            if let Some(fields) = widget_fields {
905                                for skey in sub.keys() {
906                                    if !fields.contains(&skey.as_str()) {
907                                        warnings
908                                            .push(format!("unknown field: {sub_prefix}.{skey}"));
909                                    }
910                                    // Validate sub-tables (font/border nested structs)
911                                    if let Some(toml::Value::Table(nested)) = sub.get(skey) {
912                                        let nested_known = match skey.as_str() {
913                                            s if s == "font" || s.ends_with("_font") => {
914                                                get_struct_fields("FontSpec")
915                                            }
916                                            "border" => get_struct_fields("WidgetBorderSpec"),
917                                            _ => None,
918                                        };
919                                        if let Some(known) = nested_known {
920                                            for nkey in nested.keys() {
921                                                if !known.contains(&nkey.as_str()) {
922                                                    warnings.push(format!(
923                                                        "unknown field: {sub_prefix}.{skey}.{nkey}"
924                                                    ));
925                                                }
926                                            }
927                                        }
928                                    }
929                                }
930                            }
931                        }
932                    }
933                }
934            }
935        };
936
937        // Lint light and dark variant sections
938        for variant_key in &["light", "dark"] {
939            if let Some(toml::Value::Table(variant_table)) = top_table.get(*variant_key) {
940                lint_variant(variant_table, variant_key, &mut warnings);
941            }
942        }
943
944        // Lint top-level [layout] section. LayoutTheme is a "widget" at the
945        // macro level (for its Resolved-pair codegen) but skips the widget
946        // inventory -- its fields are in the struct registry instead.
947        if let Some(toml::Value::Table(layout_table)) = top_table.get("layout")
948            && let Some(layout_fields) = get_struct_fields("LayoutTheme")
949        {
950            for key in layout_table.keys() {
951                if !layout_fields.contains(&key.as_str()) {
952                    warnings.push(format!("unknown field: layout.{key}"));
953                }
954            }
955        }
956
957        Ok(warnings)
958    }
959}
960
961#[cfg(test)]
962#[allow(clippy::unwrap_used, clippy::expect_used)]
963mod tests {
964    use super::*;
965    use crate::Rgba;
966
967    // === ThemeMode tests ===
968
969    #[test]
970    fn theme_variant_default_is_empty() {
971        assert!(ThemeMode::default().is_empty());
972    }
973
974    #[test]
975    fn theme_variant_not_empty_when_color_set() {
976        let mut v = ThemeMode::default();
977        v.defaults.accent_color = Some(Rgba::rgb(0, 120, 215));
978        assert!(!v.is_empty());
979    }
980
981    #[test]
982    fn theme_variant_not_empty_when_font_set() {
983        let mut v = ThemeMode::default();
984        v.defaults.font.family = Some("Inter".into());
985        assert!(!v.is_empty());
986    }
987
988    #[test]
989    fn theme_variant_merge_recursively() {
990        let mut base = ThemeMode::default();
991        base.defaults.background_color = Some(Rgba::rgb(255, 255, 255));
992        base.defaults.font.family = Some("Noto Sans".into());
993
994        let mut overlay = ThemeMode::default();
995        overlay.defaults.accent_color = Some(Rgba::rgb(0, 120, 215));
996        overlay.defaults.border.corner_radius = Some(4.0);
997
998        base.merge(&overlay);
999
1000        // base background preserved
1001        assert_eq!(
1002            base.defaults.background_color,
1003            Some(Rgba::rgb(255, 255, 255))
1004        );
1005        // overlay accent applied
1006        assert_eq!(base.defaults.accent_color, Some(Rgba::rgb(0, 120, 215)));
1007        // base font preserved
1008        assert_eq!(base.defaults.font.family.as_deref(), Some("Noto Sans"));
1009        // overlay border applied
1010        assert_eq!(base.defaults.border.corner_radius, Some(4.0));
1011    }
1012
1013    #[test]
1014    fn theme_variant_has_all_widgets() {
1015        let mut v = ThemeMode::default();
1016        // Set a field on each of the 25 widgets
1017        v.window.background_color = Some(Rgba::rgb(255, 255, 255));
1018        v.button.min_height = Some(32.0);
1019        v.input.min_height = Some(32.0);
1020        v.checkbox.indicator_width = Some(18.0);
1021        v.menu.row_height = Some(28.0);
1022        v.tooltip.max_width = Some(300.0);
1023        v.scrollbar.groove_width = Some(14.0);
1024        v.slider.track_height = Some(4.0);
1025        v.progress_bar.track_height = Some(6.0);
1026        v.tab.min_height = Some(32.0);
1027        v.sidebar.background_color = Some(Rgba::rgb(240, 240, 240));
1028        v.toolbar.bar_height = Some(40.0);
1029        v.status_bar.background_color = Some(Rgba::rgb(240, 240, 240));
1030        v.list.row_height = Some(28.0);
1031        v.popover.background_color = Some(Rgba::rgb(255, 255, 255));
1032        v.splitter.divider_width = Some(4.0);
1033        v.separator.line_color = Some(Rgba::rgb(200, 200, 200));
1034        v.switch.track_width = Some(32.0);
1035        v.dialog.min_width = Some(320.0);
1036        v.spinner.diameter = Some(24.0);
1037        v.combo_box.min_height = Some(32.0);
1038        v.segmented_control.segment_height = Some(28.0);
1039        v.card.background_color = Some(Rgba::rgb(255, 255, 255));
1040        v.expander.header_height = Some(32.0);
1041        v.link.underline_enabled = Some(true);
1042
1043        assert!(!v.is_empty());
1044        assert!(!v.window.is_empty());
1045        assert!(!v.button.is_empty());
1046        assert!(!v.input.is_empty());
1047        assert!(!v.checkbox.is_empty());
1048        assert!(!v.menu.is_empty());
1049        assert!(!v.tooltip.is_empty());
1050        assert!(!v.scrollbar.is_empty());
1051        assert!(!v.slider.is_empty());
1052        assert!(!v.progress_bar.is_empty());
1053        assert!(!v.tab.is_empty());
1054        assert!(!v.sidebar.is_empty());
1055        assert!(!v.toolbar.is_empty());
1056        assert!(!v.status_bar.is_empty());
1057        assert!(!v.list.is_empty());
1058        assert!(!v.popover.is_empty());
1059        assert!(!v.splitter.is_empty());
1060        assert!(!v.separator.is_empty());
1061        assert!(!v.switch.is_empty());
1062        assert!(!v.dialog.is_empty());
1063        assert!(!v.spinner.is_empty());
1064        assert!(!v.combo_box.is_empty());
1065        assert!(!v.segmented_control.is_empty());
1066        assert!(!v.card.is_empty());
1067        assert!(!v.expander.is_empty());
1068        assert!(!v.link.is_empty());
1069    }
1070
1071    #[test]
1072    fn theme_variant_merge_per_widget() {
1073        let mut base = ThemeMode::default();
1074        base.button.background_color = Some(Rgba::rgb(200, 200, 200));
1075        base.button.min_height = Some(28.0);
1076        base.tooltip.background_color = Some(Rgba::rgb(50, 50, 50));
1077
1078        let mut overlay = ThemeMode::default();
1079        overlay.button.background_color = Some(Rgba::rgb(255, 255, 255));
1080        overlay.button.min_width = Some(64.0);
1081
1082        base.merge(&overlay);
1083
1084        // overlay background wins
1085        assert_eq!(base.button.background_color, Some(Rgba::rgb(255, 255, 255)));
1086        // overlay min_width added
1087        assert_eq!(base.button.min_width, Some(64.0));
1088        // base min_height preserved
1089        assert_eq!(base.button.min_height, Some(28.0));
1090        // tooltip from base preserved
1091        assert_eq!(base.tooltip.background_color, Some(Rgba::rgb(50, 50, 50)));
1092    }
1093
1094    // === Theme tests ===
1095
1096    #[test]
1097    fn native_theme_default_is_empty() {
1098        let theme = Theme::default();
1099        assert!(theme.is_empty());
1100        assert_eq!(theme.name, "");
1101    }
1102
1103    #[test]
1104    fn native_theme_merge_keeps_base_name() {
1105        let mut base = Theme {
1106            name: "Base Theme".into(),
1107            ..Theme::default()
1108        };
1109        let overlay = Theme {
1110            name: "Overlay Theme".into(),
1111            ..Theme::default()
1112        };
1113        base.merge(&overlay);
1114        assert_eq!(base.name, "Base Theme");
1115    }
1116
1117    #[test]
1118    fn nameless_overlay_parses_and_merges() {
1119        let toml = "[light.defaults]\naccent_color = \"#ff6600\"";
1120        assert!(Theme::lint_toml(toml).unwrap().is_empty());
1121        let overlay = Theme::from_toml(toml).unwrap();
1122        assert_eq!(overlay.name, "");
1123
1124        let mut base = Theme::preset("catppuccin-mocha").unwrap();
1125        base.merge(&overlay);
1126        assert_eq!(base.name, "Catppuccin Mocha");
1127        assert_eq!(
1128            base.light.as_ref().unwrap().defaults.accent_color,
1129            Some(Rgba::rgb(0xff, 0x66, 0x00))
1130        );
1131    }
1132
1133    #[test]
1134    fn icon_set_segoe_fluent_toml_round_trip() {
1135        let theme = Theme::from_toml("name = \"T\"\nicon_set = \"segoe-fluent\"").unwrap();
1136        assert_eq!(theme.icon_set, Some(IconSet::SegoeFluent));
1137        let toml_text = theme.to_toml().unwrap();
1138        assert!(
1139            toml_text.contains("icon_set = \"segoe-fluent\""),
1140            "serialized name changed: {toml_text}"
1141        );
1142        assert_eq!(
1143            Theme::from_toml(&toml_text).unwrap().icon_set,
1144            Some(IconSet::SegoeFluent)
1145        );
1146    }
1147
1148    #[test]
1149    fn native_theme_merge_overlay_light_into_none() {
1150        let mut base = Theme {
1151            name: "Theme".into(),
1152            ..Theme::default()
1153        };
1154
1155        let mut overlay = Theme {
1156            name: "Overlay".into(),
1157            ..Theme::default()
1158        };
1159        let mut light = ThemeMode::default();
1160        light.defaults.accent_color = Some(Rgba::rgb(0, 120, 215));
1161        overlay.light = Some(light);
1162
1163        base.merge(&overlay);
1164
1165        assert!(base.light.is_some());
1166        assert_eq!(
1167            base.light.as_ref().unwrap().defaults.accent_color,
1168            Some(Rgba::rgb(0, 120, 215))
1169        );
1170    }
1171
1172    #[test]
1173    fn native_theme_merge_both_light_variants() {
1174        let mut base = Theme {
1175            name: "Theme".into(),
1176            ..Theme::default()
1177        };
1178        let mut base_light = ThemeMode::default();
1179        base_light.defaults.background_color = Some(Rgba::rgb(255, 255, 255));
1180        base.light = Some(base_light);
1181
1182        let mut overlay = Theme {
1183            name: "Overlay".into(),
1184            ..Theme::default()
1185        };
1186        let mut overlay_light = ThemeMode::default();
1187        overlay_light.defaults.accent_color = Some(Rgba::rgb(0, 120, 215));
1188        overlay.light = Some(overlay_light);
1189
1190        base.merge(&overlay);
1191
1192        let light = base.light.as_ref().unwrap();
1193        // base background preserved
1194        assert_eq!(
1195            light.defaults.background_color,
1196            Some(Rgba::rgb(255, 255, 255))
1197        );
1198        // overlay accent merged in
1199        assert_eq!(light.defaults.accent_color, Some(Rgba::rgb(0, 120, 215)));
1200    }
1201
1202    #[test]
1203    fn native_theme_merge_base_light_only_preserved() {
1204        let mut base = Theme {
1205            name: "Theme".into(),
1206            ..Theme::default()
1207        };
1208        let mut base_light = ThemeMode::default();
1209        base_light.defaults.font.family = Some("Inter".into());
1210        base.light = Some(base_light);
1211
1212        let overlay = Theme {
1213            name: "Overlay".into(),
1214            ..Theme::default()
1215        }; // no light
1216
1217        base.merge(&overlay);
1218
1219        assert!(base.light.is_some());
1220        assert_eq!(
1221            base.light.as_ref().unwrap().defaults.font.family.as_deref(),
1222            Some("Inter")
1223        );
1224    }
1225
1226    #[test]
1227    fn native_theme_merge_dark_variant() {
1228        let mut base = Theme {
1229            name: "Theme".into(),
1230            ..Theme::default()
1231        };
1232
1233        let mut overlay = Theme {
1234            name: "Overlay".into(),
1235            ..Theme::default()
1236        };
1237        let mut dark = ThemeMode::default();
1238        dark.defaults.background_color = Some(Rgba::rgb(30, 30, 30));
1239        overlay.dark = Some(dark);
1240
1241        base.merge(&overlay);
1242
1243        assert!(base.dark.is_some());
1244        assert_eq!(
1245            base.dark.as_ref().unwrap().defaults.background_color,
1246            Some(Rgba::rgb(30, 30, 30))
1247        );
1248    }
1249
1250    #[test]
1251    fn native_theme_not_empty_with_light() {
1252        let mut theme = Theme {
1253            name: "Theme".into(),
1254            ..Theme::default()
1255        };
1256        theme.light = Some(ThemeMode::default());
1257        assert!(!theme.is_empty());
1258    }
1259
1260    // === pick_variant tests ===
1261
1262    #[test]
1263    fn pick_variant_dark_with_both_variants_returns_dark() {
1264        let mut theme = Theme {
1265            name: "Test".into(),
1266            ..Theme::default()
1267        };
1268        let mut light = ThemeMode::default();
1269        light.defaults.background_color = Some(Rgba::rgb(255, 255, 255));
1270        theme.light = Some(light);
1271        let mut dark = ThemeMode::default();
1272        dark.defaults.background_color = Some(Rgba::rgb(30, 30, 30));
1273        theme.dark = Some(dark);
1274
1275        let picked = theme.pick_variant(ColorMode::Dark).unwrap();
1276        assert_eq!(
1277            picked.defaults.background_color,
1278            Some(Rgba::rgb(30, 30, 30))
1279        );
1280    }
1281
1282    #[test]
1283    fn pick_variant_light_with_both_variants_returns_light() {
1284        let mut theme = Theme {
1285            name: "Test".into(),
1286            ..Theme::default()
1287        };
1288        let mut light = ThemeMode::default();
1289        light.defaults.background_color = Some(Rgba::rgb(255, 255, 255));
1290        theme.light = Some(light);
1291        let mut dark = ThemeMode::default();
1292        dark.defaults.background_color = Some(Rgba::rgb(30, 30, 30));
1293        theme.dark = Some(dark);
1294
1295        let picked = theme.pick_variant(ColorMode::Light).unwrap();
1296        assert_eq!(
1297            picked.defaults.background_color,
1298            Some(Rgba::rgb(255, 255, 255))
1299        );
1300    }
1301
1302    #[test]
1303    fn pick_variant_dark_with_only_light_falls_back() {
1304        let mut theme = Theme {
1305            name: "Test".into(),
1306            ..Theme::default()
1307        };
1308        let mut light = ThemeMode::default();
1309        light.defaults.background_color = Some(Rgba::rgb(255, 255, 255));
1310        theme.light = Some(light);
1311
1312        let picked = theme.pick_variant(ColorMode::Dark).unwrap();
1313        assert_eq!(
1314            picked.defaults.background_color,
1315            Some(Rgba::rgb(255, 255, 255))
1316        );
1317    }
1318
1319    #[test]
1320    fn pick_variant_light_with_only_dark_falls_back() {
1321        let mut theme = Theme {
1322            name: "Test".into(),
1323            ..Theme::default()
1324        };
1325        let mut dark = ThemeMode::default();
1326        dark.defaults.background_color = Some(Rgba::rgb(30, 30, 30));
1327        theme.dark = Some(dark);
1328
1329        let picked = theme.pick_variant(ColorMode::Light).unwrap();
1330        assert_eq!(
1331            picked.defaults.background_color,
1332            Some(Rgba::rgb(30, 30, 30))
1333        );
1334    }
1335
1336    #[test]
1337    fn pick_variant_with_no_variants_returns_err() {
1338        let theme = Theme {
1339            name: "Empty".into(),
1340            ..Theme::default()
1341        };
1342        assert!(theme.pick_variant(ColorMode::Dark).is_err());
1343        assert!(theme.pick_variant(ColorMode::Light).is_err());
1344    }
1345
1346    // === icon_set tests (on Theme, shared across variants) ===
1347
1348    #[test]
1349    fn icon_set_default_is_none() {
1350        assert!(Theme::default().icon_set.is_none());
1351    }
1352
1353    #[test]
1354    fn icon_set_merge_overlay() {
1355        let mut base = Theme {
1356            name: "Base".into(),
1357            ..Theme::default()
1358        };
1359        let mut overlay = Theme {
1360            name: "Overlay".into(),
1361            ..Theme::default()
1362        };
1363        overlay.icon_set = Some(IconSet::Material);
1364        base.merge(&overlay);
1365        assert_eq!(base.icon_set, Some(IconSet::Material));
1366    }
1367
1368    #[test]
1369    fn icon_set_merge_none_preserves() {
1370        let mut base = Theme {
1371            name: "Base".into(),
1372            ..Theme::default()
1373        };
1374        base.icon_set = Some(IconSet::SfSymbols);
1375        let overlay = Theme {
1376            name: "Overlay".into(),
1377            ..Theme::default()
1378        };
1379        base.merge(&overlay);
1380        assert_eq!(base.icon_set, Some(IconSet::SfSymbols));
1381    }
1382
1383    #[test]
1384    fn icon_set_is_empty_when_set() {
1385        assert!(Theme::default().is_empty());
1386        let mut t = Theme {
1387            name: "Test".into(),
1388            ..Theme::default()
1389        };
1390        t.icon_set = Some(IconSet::Material);
1391        assert!(!t.is_empty());
1392    }
1393
1394    #[test]
1395    fn icon_set_toml_round_trip() {
1396        let mut theme = Theme {
1397            name: "Test".into(),
1398            ..Theme::default()
1399        };
1400        theme.icon_set = Some(IconSet::Material);
1401        let mut light = ThemeMode::default();
1402        light.defaults.icon_theme = Some("material".into());
1403        theme.light = Some(light);
1404        let toml_str = theme.to_toml().unwrap();
1405        assert!(toml_str.contains("icon_set"));
1406        let deserialized = Theme::from_toml(&toml_str).unwrap();
1407        assert_eq!(deserialized.icon_set, Some(IconSet::Material));
1408        assert_eq!(
1409            deserialized
1410                .light
1411                .as_ref()
1412                .unwrap()
1413                .defaults
1414                .icon_theme
1415                .as_deref(),
1416            Some("material")
1417        );
1418    }
1419
1420    #[test]
1421    fn icon_set_toml_absent_deserializes_to_none() {
1422        let toml_str = r##"
1423name = "Bare"
1424[light.defaults]
1425accent_color = "#ff0000"
1426"##;
1427        let theme = Theme::from_toml(toml_str).unwrap();
1428        assert!(theme.icon_set.is_none());
1429        assert!(theme.light.as_ref().unwrap().defaults.icon_theme.is_none());
1430    }
1431
1432    #[test]
1433    fn native_theme_serde_toml_round_trip() {
1434        // Load a preset, serialize to TOML, deserialize back, and verify equality
1435        let theme = Theme::preset("material-3").expect("material-3 preset should load");
1436        let toml_str = theme.to_toml().expect("should serialize");
1437        let theme2 = Theme::from_toml(&toml_str).expect("should deserialize");
1438        assert_eq!(theme, theme2, "round-trip should preserve Theme");
1439    }
1440
1441    // === Theme::resolve() tests ===
1442
1443    #[test]
1444    fn resolve_material_uses_theme_level_icon_theme() {
1445        // material-3.toml has `icon_theme = "material"` at the root (tier 2).
1446        // The resolver must fill `icon_theme = "material"` for both modes.
1447        let theme = Theme::preset("material-3").unwrap();
1448        for mode in [ColorMode::Light, ColorMode::Dark] {
1449            let r = theme.resolve(mode).unwrap();
1450            assert_eq!(
1451                r.icon_theme.as_deref(),
1452                Some("material"),
1453                "material (tier 2) for {mode:?}"
1454            );
1455            assert!(
1456                r.icon_theme_explicit,
1457                "explicit flag must be true for {mode:?}"
1458            );
1459            assert_eq!(r.icon_set, IconSet::Material);
1460        }
1461    }
1462
1463    #[test]
1464    fn resolve_kde_breeze_uses_per_variant_icon_theme() {
1465        // kde-breeze.toml has `icon_theme` under each [light.defaults] /
1466        // [dark.defaults] (tier 1). Light → "breeze", Dark → "breeze-dark".
1467        let theme = Theme::preset("kde-breeze").unwrap();
1468
1469        let light = theme.resolve(ColorMode::Light).unwrap();
1470        assert_eq!(light.icon_theme.as_deref(), Some("breeze"));
1471        assert!(light.icon_theme_explicit);
1472
1473        let dark = theme.resolve(ColorMode::Dark).unwrap();
1474        assert_eq!(dark.icon_theme.as_deref(), Some("breeze-dark"));
1475        assert!(dark.icon_theme_explicit);
1476
1477        assert_eq!(light.icon_set, IconSet::Freedesktop);
1478        assert_eq!(dark.icon_set, IconSet::Freedesktop);
1479    }
1480
1481    /// adwaita with no icon theme stated anywhere, so tier 3 decides.
1482    fn adwaita_without_icon_theme() -> Theme {
1483        let mut theme = Theme::preset("adwaita").unwrap();
1484        theme.icon_theme = None;
1485        if let Some(v) = theme.light.as_mut() {
1486            v.defaults.icon_theme = None;
1487        }
1488        if let Some(v) = theme.dark.as_mut() {
1489            v.defaults.icon_theme = None;
1490        }
1491        theme
1492    }
1493
1494    #[test]
1495    fn resolve_minimal_theme_takes_the_detected_icon_theme() {
1496        // No icon_theme anywhere → tier 3, the context's detected theme.
1497        let ctx = crate::resolve::ResolutionContext::with_detected_icon_theme(Ok(
1498            "detected-theme".to_string()
1499        ));
1500        let r = adwaita_without_icon_theme()
1501            .resolve_with(ColorMode::Light, &ctx)
1502            .unwrap();
1503        assert_eq!(r.icon_theme.as_deref(), Some("detected-theme"));
1504        assert!(
1505            !r.icon_theme_explicit,
1506            "tier 3 fallback must report explicit = false"
1507        );
1508    }
1509
1510    #[test]
1511    fn resolve_minimal_theme_without_detection_has_no_icon_theme() {
1512        // No icon_theme anywhere and detection failed → None, and the
1513        // resolution itself still succeeds.
1514        let ctx = crate::resolve::ResolutionContext::with_detected_icon_theme(Err(
1515            crate::Error::PlatformUnsupported {
1516                platform: "the test's failing detection",
1517            },
1518        ));
1519        let r = adwaita_without_icon_theme()
1520            .resolve_with(ColorMode::Light, &ctx)
1521            .expect("a failed icon-theme detection must not fail resolution");
1522        assert_eq!(r.icon_theme, None);
1523        assert!(!r.icon_theme_explicit);
1524    }
1525
1526    #[test]
1527    fn resolve_minimal_theme_resolves_whatever_detection_gives() {
1528        // Through `resolve` itself: detection's outcome is host-dependent,
1529        // but the resolution succeeds and reports tier 3 either way.
1530        let r = adwaita_without_icon_theme()
1531            .resolve(ColorMode::Light)
1532            .unwrap();
1533        assert!(!r.icon_theme_explicit);
1534        assert_eq!(
1535            r.icon_theme.as_deref(),
1536            crate::detect::system_icon_theme().ok().as_deref()
1537        );
1538    }
1539
1540    #[test]
1541    fn resolve_tier1_wins_over_tier2() {
1542        // When BOTH Theme::icon_theme (tier 2) and variant.defaults.icon_theme
1543        // (tier 1) are set, tier 1 wins.
1544        let mut theme = Theme::preset("adwaita").unwrap();
1545        theme.icon_theme = Some(Cow::Borrowed("theme-level"));
1546        theme.light.as_mut().unwrap().defaults.icon_theme = Some(Cow::Borrowed("per-variant"));
1547        let r = theme.resolve(ColorMode::Light).unwrap();
1548        assert_eq!(r.icon_theme.as_deref(), Some("per-variant"));
1549        assert!(r.icon_theme_explicit);
1550    }
1551
1552    #[test]
1553    fn resolve_cross_mode_fallback_picks_available_variant() {
1554        // Theme with only a light variant, asked for dark → pick_variant
1555        // cross-falls-back to light and reports light's icon_theme.
1556        let mut theme = Theme::preset("adwaita").unwrap();
1557        theme.dark = None;
1558        theme.icon_theme = None;
1559        theme.light.as_mut().unwrap().defaults.icon_theme = Some(Cow::Borrowed("only-one"));
1560        let r = theme.resolve(ColorMode::Dark).unwrap();
1561        assert_eq!(r.icon_theme.as_deref(), Some("only-one"));
1562        assert!(r.icon_theme_explicit);
1563    }
1564
1565    #[test]
1566    fn resolve_light_only_asked_dark_reports_light_mode() {
1567        let mut theme = Theme::preset("adwaita").unwrap();
1568        theme.dark = None;
1569        let r = theme.resolve(ColorMode::Dark).unwrap();
1570        assert_eq!(r.mode, ColorMode::Light);
1571    }
1572
1573    #[test]
1574    fn resolve_reports_requested_mode_when_variant_present() {
1575        let theme = Theme::preset("adwaita").unwrap();
1576        assert_eq!(
1577            theme.resolve(ColorMode::Dark).unwrap().mode,
1578            ColorMode::Dark
1579        );
1580        assert_eq!(
1581            theme.resolve(ColorMode::Light).unwrap().mode,
1582            ColorMode::Light
1583        );
1584    }
1585
1586    #[test]
1587    fn resolve_empty_theme_returns_no_variant_error() {
1588        let theme = Theme {
1589            name: "Empty".into(),
1590            ..Theme::default()
1591        };
1592        assert!(matches!(
1593            theme.resolve(ColorMode::Light),
1594            Err(crate::Error::NoVariant {
1595                mode: ColorMode::Light
1596            })
1597        ));
1598    }
1599
1600    #[test]
1601    fn resolve_all_presets_succeed() {
1602        // Every bundled preset must resolve in both modes.
1603        for info in Theme::list_presets() {
1604            let theme = Theme::preset(info.key).unwrap();
1605            for mode in [ColorMode::Light, ColorMode::Dark] {
1606                theme.resolve(mode).unwrap_or_else(|e| {
1607                    panic!("preset '{}' failed to resolve({mode:?}): {e}", info.key)
1608                });
1609            }
1610        }
1611    }
1612
1613    // === lint_toml tests ===
1614
1615    #[test]
1616    fn lint_toml_valid_returns_empty() {
1617        let toml = r##"
1618name = "Valid Theme"
1619[light.defaults]
1620accent_color = "#ff0000"
1621background_color = "#ffffff"
1622[light.defaults.font]
1623family = "Inter"
1624size_px = 14.0
1625[light.button]
1626min_height_px = 32.0
1627"##;
1628        let warnings = Theme::lint_toml(toml).unwrap();
1629        assert!(
1630            warnings.is_empty(),
1631            "Expected no warnings, got: {warnings:?}"
1632        );
1633    }
1634
1635    #[test]
1636    fn lint_toml_detects_unknown_top_level() {
1637        let toml = r##"
1638name = "Test"
1639theme_version = 2
1640"##;
1641        let warnings = Theme::lint_toml(toml).unwrap();
1642        assert_eq!(warnings.len(), 1);
1643        assert!(warnings[0].contains("theme_version"));
1644    }
1645
1646    #[test]
1647    fn lint_toml_detects_misspelled_defaults_field() {
1648        let toml = r##"
1649name = "Test"
1650[light.defaults]
1651backround = "#ffffff"
1652"##;
1653        let warnings = Theme::lint_toml(toml).unwrap();
1654        assert_eq!(warnings.len(), 1);
1655        assert!(warnings[0].contains("backround"));
1656        assert!(warnings[0].contains("light.defaults.backround"));
1657    }
1658
1659    #[test]
1660    fn lint_toml_detects_unknown_widget_field() {
1661        let toml = r##"
1662name = "Test"
1663[dark.button]
1664primary_bg = "#0078d7"
1665"##;
1666        let warnings = Theme::lint_toml(toml).unwrap();
1667        assert_eq!(warnings.len(), 1);
1668        assert!(warnings[0].contains("primary_bg"));
1669    }
1670
1671    #[test]
1672    fn lint_toml_detects_unknown_variant_section() {
1673        let toml = r##"
1674name = "Test"
1675[light.badges]
1676color = "#ff0000"
1677"##;
1678        let warnings = Theme::lint_toml(toml).unwrap();
1679        assert_eq!(warnings.len(), 1);
1680        assert!(warnings[0].contains("badges"));
1681    }
1682
1683    #[test]
1684    fn lint_toml_detects_unknown_font_subfield() {
1685        let toml = r##"
1686name = "Test"
1687[light.defaults.font]
1688famly = "Inter"
1689"##;
1690        let warnings = Theme::lint_toml(toml).unwrap();
1691        assert_eq!(warnings.len(), 1);
1692        assert!(warnings[0].contains("famly"));
1693    }
1694
1695    #[test]
1696    fn lint_toml_detects_unknown_border_subfield() {
1697        let toml = r##"
1698name = "Test"
1699[light.defaults.border]
1700radiusss = 4.0
1701"##;
1702        let warnings = Theme::lint_toml(toml).unwrap();
1703        assert_eq!(warnings.len(), 1);
1704        assert!(warnings[0].contains("radiusss"));
1705    }
1706
1707    #[test]
1708    fn lint_toml_detects_unknown_text_scale_entry() {
1709        let toml = r##"
1710name = "Test"
1711[light.text_scale.headline]
1712size = 24.0
1713"##;
1714        let warnings = Theme::lint_toml(toml).unwrap();
1715        assert_eq!(warnings.len(), 1);
1716        assert!(warnings[0].contains("headline"));
1717    }
1718
1719    #[test]
1720    fn lint_toml_detects_unknown_text_scale_entry_field() {
1721        let toml = r##"
1722name = "Test"
1723[light.text_scale.caption]
1724font_size = 12.0
1725"##;
1726        let warnings = Theme::lint_toml(toml).unwrap();
1727        assert_eq!(warnings.len(), 1);
1728        assert!(warnings[0].contains("font_size"));
1729    }
1730
1731    #[test]
1732    fn lint_toml_multiple_errors() {
1733        let toml = r##"
1734name = "Test"
1735author = "Me"
1736[light.defaults]
1737backround = "#ffffff"
1738[light.button]
1739primay_bg = "#0078d7"
1740"##;
1741        let warnings = Theme::lint_toml(toml).unwrap();
1742        assert_eq!(warnings.len(), 3);
1743    }
1744
1745    #[test]
1746    fn lint_toml_invalid_toml_returns_error() {
1747        let result = Theme::lint_toml("{{{{invalid");
1748        assert!(result.is_err());
1749    }
1750
1751    #[test]
1752    fn lint_toml_preset_has_no_warnings() {
1753        // Spot-check one preset for lint cleanliness via round-trip
1754        let theme = Theme::preset("material-3").expect("material-3 preset should load");
1755        let toml_str = theme.to_toml().expect("should serialize");
1756        let warnings = Theme::lint_toml(&toml_str).expect("should parse");
1757        assert!(
1758            warnings.is_empty(),
1759            "material-3 preset should have no lint warnings, got: {warnings:?}"
1760        );
1761    }
1762
1763    #[test]
1764    fn lint_toml_all_presets_clean() {
1765        for info in Theme::list_presets() {
1766            let name = info.key;
1767            // Load the raw TOML source for each preset via include_str
1768            // by loading via preset() + to_toml() round-trip
1769            let theme = Theme::preset(name).unwrap_or_else(|e| {
1770                panic!("preset {name} should load: {e}");
1771            });
1772            let toml_str = theme.to_toml().unwrap_or_else(|e| {
1773                panic!("preset {name} should serialize: {e}");
1774            });
1775            let warnings = Theme::lint_toml(&toml_str).unwrap_or_else(|e| {
1776                panic!("preset {name} should lint: {e}");
1777            });
1778            assert!(
1779                warnings.is_empty(),
1780                "preset {name} should have no lint warnings, got: {warnings:?}"
1781            );
1782        }
1783    }
1784
1785    #[test]
1786    fn lint_toml_accepts_padding_sides_and_shorthand() {
1787        let toml = r##"
1788name = "Test"
1789[light.button.border]
1790padding_top_px = 1.0
1791padding_right_px = 2.0
1792padding_bottom_px = 3.0
1793padding_left_px = 4.0
1794[light.input.border]
1795padding_horizontal_px = 6.0
1796padding_vertical_px = 0.0
1797"##;
1798        let warnings = Theme::lint_toml(toml).unwrap();
1799        assert!(warnings.is_empty(), "got: {warnings:?}");
1800        let warnings =
1801            Theme::lint_toml("name = \"T\"\n[light.input.border]\npadding_sideways_px = 1.0\n")
1802                .unwrap();
1803        assert_eq!(warnings.len(), 1, "got: {warnings:?}");
1804    }
1805
1806    #[test]
1807    fn lint_toml_rejects_unknown_field_on_registered_widget() {
1808        // Verify that lint_toml discovers widget field names from inventory.
1809        // If a field name is not in the registered FIELD_NAMES for a widget,
1810        // lint_toml should report it as unknown.
1811        let toml = r##"
1812name = "Test"
1813[light.button]
1814nonexistent_field = "#ff0000"
1815"##;
1816        let warnings = Theme::lint_toml(toml).unwrap();
1817        assert_eq!(warnings.len(), 1);
1818        assert!(warnings[0].contains("nonexistent_field"));
1819        assert!(warnings[0].contains("light.button"));
1820    }
1821
1822    #[test]
1823    fn lint_toml_recognizes_all_registered_widgets() {
1824        // Every widget registered via inventory::submit! should be accepted
1825        // as a valid variant-level section key.
1826        for entry in inventory::iter::<crate::resolve::WidgetFieldInfo> {
1827            let toml_str = format!("name = \"Test\"\n[light.{}]\n", entry.widget_name,);
1828            let warnings = Theme::lint_toml(&toml_str).unwrap();
1829            assert!(
1830                warnings.is_empty(),
1831                "widget '{}' should be recognized, got: {:?}",
1832                entry.widget_name,
1833                warnings,
1834            );
1835        }
1836    }
1837
1838    // === Theme layout integration tests ===
1839
1840    #[test]
1841    fn theme_spec_layout_merge() {
1842        let mut base = Theme {
1843            name: "Base".into(),
1844            ..Theme::default()
1845        };
1846        base.layout.widget_gap = Some(6.0);
1847
1848        let mut overlay = Theme {
1849            name: "Overlay".into(),
1850            ..Theme::default()
1851        };
1852        overlay.layout.container_margin = Some(8.0);
1853
1854        base.merge(&overlay);
1855        assert_eq!(base.layout.widget_gap, Some(6.0));
1856        assert_eq!(base.layout.container_margin, Some(8.0));
1857    }
1858
1859    #[test]
1860    fn theme_spec_layout_toml_round_trip() {
1861        let mut theme = Theme {
1862            name: "Layout Test".into(),
1863            ..Theme::default()
1864        };
1865        theme.layout.widget_gap = Some(8.0);
1866        theme.layout.container_margin = Some(12.0);
1867        theme.layout.window_margin = Some(16.0);
1868        theme.layout.section_gap = Some(24.0);
1869
1870        let toml_str = theme.to_toml().unwrap();
1871        let theme2 = Theme::from_toml(&toml_str).unwrap();
1872        assert_eq!(theme.layout, theme2.layout);
1873    }
1874
1875    #[test]
1876    fn theme_spec_is_empty_with_layout() {
1877        let mut theme = Theme {
1878            name: "Layout Only".into(),
1879            ..Theme::default()
1880        };
1881        assert!(theme.is_empty()); // name doesn't count
1882        theme.layout.widget_gap = Some(8.0);
1883        assert!(!theme.is_empty());
1884    }
1885
1886    #[test]
1887    fn theme_spec_layout_top_level_toml() {
1888        let mut theme = Theme {
1889            name: "Top Level".into(),
1890            ..Theme::default()
1891        };
1892        theme.layout.widget_gap = Some(8.0);
1893
1894        let toml_str = theme.to_toml().unwrap();
1895        // [layout] must be at top level, not under [light.layout] or [dark.layout]
1896        assert!(
1897            toml_str.contains("[layout]"),
1898            "TOML should have [layout] section"
1899        );
1900        assert!(!toml_str.contains("[light.layout]"));
1901        assert!(!toml_str.contains("[dark.layout]"));
1902    }
1903
1904    // === Phase 93-05 G5: ThemeFields inventory baseline-equality tests ===
1905    //
1906    // Each struct that is expected to register via #[derive(ThemeFields)]
1907    // must produce a FieldInfo entry whose `field_names` matches the
1908    // pre-migration hand-authored FIELD_NAMES list bit-for-bit. Failure means
1909    // either the derive emission path is wrong (serde rename drift) or
1910    // the derive was not applied to the struct.
1911
1912    fn field_info_entry(name: &'static str) -> Option<&'static [&'static str]> {
1913        inventory::iter::<crate::resolve::FieldInfo>()
1914            .find(|info| info.struct_name == name)
1915            .map(|info| info.field_names)
1916    }
1917
1918    #[test]
1919    fn font_spec_field_info_matches_baseline() {
1920        let baseline: &[&str] = &["family", "size_pt", "size_px", "weight", "style", "color"];
1921        assert_eq!(field_info_entry("FontSpec"), Some(baseline));
1922    }
1923
1924    #[test]
1925    fn text_scale_entry_field_info_matches_baseline() {
1926        let baseline: &[&str] = &[
1927            "size_pt",
1928            "size_px",
1929            "weight",
1930            "line_height_pt",
1931            "line_height_px",
1932        ];
1933        assert_eq!(field_info_entry("TextScaleEntry"), Some(baseline));
1934    }
1935
1936    #[test]
1937    fn text_scale_field_info_matches_baseline() {
1938        let baseline: &[&str] = &["caption", "section_heading", "dialog_title", "display"];
1939        assert_eq!(field_info_entry("TextScale"), Some(baseline));
1940    }
1941
1942    #[test]
1943    fn defaults_border_spec_field_info_matches_baseline() {
1944        let baseline: &[&str] = &[
1945            "color",
1946            "corner_radius_px",
1947            "corner_radius_lg_px",
1948            "line_width_px",
1949            "opacity",
1950            "shadow_enabled",
1951        ];
1952        assert_eq!(field_info_entry("DefaultsBorderSpec"), Some(baseline));
1953    }
1954
1955    #[test]
1956    fn widget_border_spec_field_info_matches_baseline() {
1957        let baseline: &[&str] = &[
1958            "color",
1959            "corner_radius_px",
1960            "line_width_px",
1961            "shadow_enabled",
1962            "padding_top_px",
1963            "padding_right_px",
1964            "padding_bottom_px",
1965            "padding_left_px",
1966            "padding_horizontal_px",
1967            "padding_vertical_px",
1968        ];
1969        assert_eq!(field_info_entry("WidgetBorderSpec"), Some(baseline));
1970    }
1971
1972    #[test]
1973    fn theme_defaults_field_info_matches_baseline() {
1974        let baseline: &[&str] = &[
1975            "font",
1976            "line_height",
1977            "mono_font",
1978            "background_color",
1979            "text_color",
1980            "accent_color",
1981            "accent_text_color",
1982            "surface_color",
1983            "muted_color",
1984            "shadow_color",
1985            "link_color",
1986            "selection_background",
1987            "selection_text_color",
1988            "selection_inactive_background",
1989            "text_selection_background",
1990            "text_selection_color",
1991            "disabled_text_color",
1992            "danger_color",
1993            "danger_text_color",
1994            "warning_color",
1995            "warning_text_color",
1996            "success_color",
1997            "success_text_color",
1998            "info_color",
1999            "info_text_color",
2000            "border",
2001            "disabled_opacity",
2002            "focus_ring_color",
2003            "focus_ring_width_px",
2004            "focus_ring_offset_px",
2005            "icon_sizes",
2006            "icon_theme",
2007        ];
2008        assert_eq!(field_info_entry("ThemeDefaults"), Some(baseline));
2009    }
2010
2011    #[test]
2012    fn icon_sizes_field_info_matches_baseline() {
2013        let baseline: &[&str] = &[
2014            "toolbar_px",
2015            "small_px",
2016            "large_px",
2017            "dialog_px",
2018            "panel_px",
2019        ];
2020        assert_eq!(field_info_entry("IconSizes"), Some(baseline));
2021    }
2022
2023    #[test]
2024    fn layout_theme_field_info_matches_baseline() {
2025        let baseline: &[&str] = &[
2026            "widget_gap_px",
2027            "container_margin_px",
2028            "window_margin_px",
2029            "section_gap_px",
2030        ];
2031        assert_eq!(field_info_entry("LayoutTheme"), Some(baseline));
2032    }
2033
2034    #[test]
2035    fn widget_registry_still_has_all_widgets() {
2036        // Regression guard: the existing WidgetFieldInfo inventory must remain
2037        // populated after ThemeFields migration. LayoutTheme is NOT a widget
2038        // (it uses `skip_inventory`), so we expect at least the 25 per-variant
2039        // widgets registered through ThemeWidget.
2040        let widget_count = inventory::iter::<crate::resolve::WidgetFieldInfo>().count();
2041        assert!(
2042            widget_count >= 25,
2043            "expected >=25 widgets in WidgetFieldInfo, got {widget_count}"
2044        );
2045    }
2046
2047    // === docs/property-registry.toml key sets against the inventory ===
2048    //
2049    // The registry lists every property per table by its serialized TOML key;
2050    // the inventory records the same keys from the structs. Types stay
2051    // hand-kept and are not compared. `[theme_variant]` is skipped: `Theme`
2052    // and `ThemeMode` do not register in the inventory.
2053
2054    #[test]
2055    fn property_registry_keys_match_derive_inventory() {
2056        use std::collections::BTreeSet;
2057
2058        let registry: toml::Table = include_str!("../../../docs/property-registry.toml")
2059            .parse()
2060            .expect("docs/property-registry.toml is valid TOML");
2061
2062        let struct_fields = |names: &[&'static str]| -> BTreeSet<String> {
2063            names
2064                .iter()
2065                .filter_map(|name| field_info_entry(name))
2066                .flat_map(|fields| fields.iter().map(|f| (*f).to_string()))
2067                .collect()
2068        };
2069        let table_keys = |value: Option<&toml::Value>| -> Option<BTreeSet<String>> {
2070            value
2071                .and_then(|v| v.as_table())
2072                .map(|t| t.keys().cloned().collect())
2073        };
2074
2075        // `Border` is one table for both border structs; its comments say
2076        // which keys belong to defaults and which to widget borders.
2077        const STRUCTURES: &[(&str, &[&str])] = &[
2078            ("Font", &["FontSpec"]),
2079            ("Border", &["DefaultsBorderSpec", "WidgetBorderSpec"]),
2080            ("IconSizes", &["IconSizes"]),
2081            ("TextScaleEntry", &["TextScaleEntry"]),
2082        ];
2083        const STRUCT_TABLES: &[(&str, &[&str])] = &[
2084            ("defaults", &["ThemeDefaults"]),
2085            ("text_scale", &["TextScale"]),
2086            ("layout", &["LayoutTheme"]),
2087        ];
2088        const SKIPPED_TABLES: &[&str] = &["theme_variant"];
2089
2090        fn compare(
2091            drift: &mut Vec<String>,
2092            table: &str,
2093            registry: Option<BTreeSet<String>>,
2094            code: &BTreeSet<String>,
2095        ) {
2096            let Some(registry) = registry else {
2097                drift.push(format!("[{table}] is missing"));
2098                return;
2099            };
2100            for key in registry.difference(code) {
2101                drift.push(format!("[{table}] {key}: in the registry, not in the code"));
2102            }
2103            for key in code.difference(&registry) {
2104                drift.push(format!("[{table}] {key}: in the code, not in the registry"));
2105            }
2106        }
2107
2108        let mut drift: Vec<String> = Vec::new();
2109
2110        let structures = registry
2111            .get("_structures")
2112            .and_then(|v| v.as_table())
2113            .expect("[_structures] exists");
2114        for name in structures.keys() {
2115            if !STRUCTURES.iter().any(|(n, _)| n == name) {
2116                drift.push(format!(
2117                    "[_structures.{name}] maps to no struct in the test"
2118                ));
2119            }
2120        }
2121        for (name, structs) in STRUCTURES {
2122            let code = struct_fields(structs);
2123            assert!(!code.is_empty(), "no FieldInfo entry for {structs:?}");
2124            compare(
2125                &mut drift,
2126                &format!("_structures.{name}"),
2127                table_keys(structures.get(*name)),
2128                &code,
2129            );
2130        }
2131
2132        for (table, structs) in STRUCT_TABLES {
2133            let code = struct_fields(structs);
2134            assert!(!code.is_empty(), "no FieldInfo entry for {structs:?}");
2135            compare(&mut drift, table, table_keys(registry.get(*table)), &code);
2136        }
2137
2138        let mut widget_count = 0usize;
2139        for info in inventory::iter::<crate::resolve::WidgetFieldInfo>() {
2140            widget_count += 1;
2141            let code: BTreeSet<String> =
2142                info.field_names.iter().map(|f| (*f).to_string()).collect();
2143            compare(
2144                &mut drift,
2145                info.widget_name,
2146                table_keys(registry.get(info.widget_name)),
2147                &code,
2148            );
2149        }
2150        assert!(
2151            widget_count >= 25,
2152            "expected >=25 widgets, got {widget_count}"
2153        );
2154
2155        for table in registry.keys() {
2156            let known = table == "_structures"
2157                || SKIPPED_TABLES.contains(&table.as_str())
2158                || STRUCT_TABLES.iter().any(|(t, _)| t == table)
2159                || inventory::iter::<crate::resolve::WidgetFieldInfo>()
2160                    .any(|info| info.widget_name == table);
2161            if !known {
2162                drift.push(format!(
2163                    "[{table}] is in the registry, but no widget or struct"
2164                ));
2165            }
2166        }
2167
2168        assert!(
2169            drift.is_empty(),
2170            "docs/property-registry.toml diverges from the derive inventory:\n{}",
2171            drift.join("\n")
2172        );
2173    }
2174}