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