Skip to main content

native_theme/model/
resolved.rs

1// Resolved (non-optional) theme types produced after theme resolution.
2//
3// These types mirror their Option-based counterparts in defaults.rs, font.rs,
4// icon_sizes.rs, and mod.rs (ThemeMode), but with all fields
5// guaranteed populated. Produced by validate() after resolve().
6
7use super::border::ResolvedDefaultsBorder;
8use super::font::ResolvedFontSpec;
9use crate::Rgba;
10
11// --- ResolvedIconSizes ---
12
13/// Fully resolved per-context icon sizes where every context is guaranteed populated.
14#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
15#[non_exhaustive]
16pub struct ResolvedIconSizes {
17    /// Icon size for toolbar buttons.
18    pub toolbar: f32,
19    /// Small icon size for inline use.
20    pub small: f32,
21    /// Large icon size for menus/lists.
22    pub large: f32,
23    /// Icon size for dialog buttons.
24    pub dialog: f32,
25    /// Icon size for panel headers.
26    pub panel: f32,
27}
28
29// --- ResolvedTextScaleEntry ---
30
31/// A single resolved text scale entry with guaranteed size, weight, and line height.
32///
33/// No `Default` derive: Constructed from a populated
34/// `TextScaleEntry` during resolution; the missing-field sentinel is
35/// written inline in
36/// `crate::resolve::validate_helpers::require_text_scale_entry` (private).
37#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
38#[non_exhaustive]
39pub struct ResolvedTextScaleEntry {
40    /// Font size in logical pixels. A size stated in points is converted at
41    /// the resolution context's
42    /// [`font_dpi`](crate::resolve::ResolutionContext::font_dpi).
43    pub size: f32,
44    /// CSS font weight (100-900).
45    pub weight: u16,
46    /// Line height in logical pixels. Computed as `defaults.line_height * size`
47    /// when not explicitly set. An explicit value stated in points is converted
48    /// at the same `font_dpi` as the size.
49    pub line_height: f32,
50}
51
52// --- ResolvedTextScale ---
53
54/// A fully resolved text scale with all four typographic roles populated.
55#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
56#[non_exhaustive]
57pub struct ResolvedTextScale {
58    /// Caption / small label text.
59    pub caption: ResolvedTextScaleEntry,
60    /// Section heading text.
61    pub section_heading: ResolvedTextScaleEntry,
62    /// Dialog title text.
63    pub dialog_title: ResolvedTextScaleEntry,
64    /// Large display / hero text.
65    pub display: ResolvedTextScaleEntry,
66}
67
68// --- ResolvedDefaults ---
69
70/// Fully resolved global theme defaults where every field is guaranteed populated.
71///
72/// Mirrors [`crate::model::ThemeDefaults`] but with concrete (non-Option) types.
73/// Produced by the resolution/validation pipeline.
74#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
75#[non_exhaustive]
76pub struct ResolvedDefaults {
77    // ---- Base font ----
78    /// Primary UI font.
79    pub font: ResolvedFontSpec,
80    /// Line height multiplier.
81    pub line_height: f32,
82    /// Monospace font for code/terminal content.
83    pub mono_font: ResolvedFontSpec,
84
85    // ---- Base colors ----
86    /// Main window/surface background color.
87    pub background_color: Rgba,
88    /// Default text color.
89    pub text_color: Rgba,
90    /// Accent/brand color for interactive elements.
91    pub accent_color: Rgba,
92    /// Text color used on accent-colored backgrounds.
93    pub accent_text_color: Rgba,
94    /// Elevated surface color.
95    pub surface_color: Rgba,
96    /// Secondary/subdued text color.
97    pub muted_color: Rgba,
98    /// Drop shadow color.
99    pub shadow_color: Rgba,
100    /// Hyperlink text color.
101    pub link_color: Rgba,
102    /// Selection highlight background.
103    pub selection_background: Rgba,
104    /// Text color over selection highlight.
105    pub selection_text_color: Rgba,
106    /// Selection background when window is unfocused.
107    pub selection_inactive_background: Rgba,
108    /// Text selection background (inline text highlight).
109    pub text_selection_background: Rgba,
110    /// Text selection color (inline text highlight).
111    pub text_selection_color: Rgba,
112    /// Text color for disabled controls.
113    pub disabled_text_color: Rgba,
114
115    // ---- Status colors ----
116    /// Danger/error color.
117    pub danger_color: Rgba,
118    /// Text color on danger-colored backgrounds.
119    pub danger_text_color: Rgba,
120    /// Warning color.
121    pub warning_color: Rgba,
122    /// Text color on warning-colored backgrounds.
123    pub warning_text_color: Rgba,
124    /// Success/confirmation color.
125    pub success_color: Rgba,
126    /// Text color on success-colored backgrounds.
127    pub success_text_color: Rgba,
128    /// Informational color.
129    pub info_color: Rgba,
130    /// Text color on info-colored backgrounds.
131    pub info_text_color: Rgba,
132
133    // ---- Global geometry ----
134    /// Border sub-struct (color, corner_radius, line_width, etc.).
135    pub border: ResolvedDefaultsBorder,
136    /// Opacity for disabled controls, applied to the whole widget together
137    /// with the disabled colours; 1.0 where the platform dims by colour
138    /// alone. See [`ThemeDefaults::disabled_opacity`](crate::model::ThemeDefaults::disabled_opacity).
139    pub disabled_opacity: f32,
140
141    // ---- Focus ring ----
142    /// Focus indicator outline color.
143    pub focus_ring_color: Rgba,
144    /// Focus indicator outline width.
145    pub focus_ring_width: f32,
146    /// Gap between element edge and focus indicator.
147    pub focus_ring_offset: f32,
148
149    // ---- Icon sizes ----
150    /// Per-context icon sizes.
151    pub icon_sizes: ResolvedIconSizes,
152}
153
154// --- ResolvedTheme ---
155
156/// A fully resolved theme where every field is guaranteed populated.
157///
158/// Produced by `validate()` after `resolve()`. Consumed by toolkit connectors.
159/// Mirrors [`crate::model::ThemeMode`] but with concrete (non-Option) types
160/// for all 26 per-widget structs plus defaults and text scale.
161#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
162#[non_exhaustive]
163pub struct ResolvedTheme {
164    /// Global defaults.
165    pub defaults: ResolvedDefaults,
166    /// Per-role text scale.
167    pub text_scale: ResolvedTextScale,
168
169    // ---- Per-widget resolved structs ----
170    /// Window chrome.
171    pub window: super::widgets::ResolvedWindowTheme,
172    /// Push button.
173    pub button: super::widgets::ResolvedButtonTheme,
174    /// Text input.
175    pub input: super::widgets::ResolvedInputTheme,
176    /// Multi-line text field's padding; the rest is `input`'s.
177    pub text_area: super::widgets::ResolvedTextAreaTheme,
178    /// Checkbox / radio button.
179    pub checkbox: super::widgets::ResolvedCheckboxTheme,
180    /// Popup / context menu.
181    pub menu: super::widgets::ResolvedMenuTheme,
182    /// Tooltip.
183    pub tooltip: super::widgets::ResolvedTooltipTheme,
184    /// Scrollbar.
185    pub scrollbar: super::widgets::ResolvedScrollbarTheme,
186    /// Slider.
187    pub slider: super::widgets::ResolvedSliderTheme,
188    /// Progress bar.
189    pub progress_bar: super::widgets::ResolvedProgressBarTheme,
190    /// Tab bar.
191    pub tab: super::widgets::ResolvedTabTheme,
192    /// Sidebar panel.
193    pub sidebar: super::widgets::ResolvedSidebarTheme,
194    /// Toolbar.
195    pub toolbar: super::widgets::ResolvedToolbarTheme,
196    /// Status bar.
197    pub status_bar: super::widgets::ResolvedStatusBarTheme,
198    /// List / table.
199    pub list: super::widgets::ResolvedListTheme,
200    /// Popover / dropdown.
201    pub popover: super::widgets::ResolvedPopoverTheme,
202    /// Splitter handle.
203    pub splitter: super::widgets::ResolvedSplitterTheme,
204    /// Separator line.
205    pub separator: super::widgets::ResolvedSeparatorTheme,
206    /// Toggle switch.
207    pub switch: super::widgets::ResolvedSwitchTheme,
208    /// Dialog.
209    pub dialog: super::widgets::ResolvedDialogTheme,
210    /// Spinner / progress ring.
211    pub spinner: super::widgets::ResolvedSpinnerTheme,
212    /// ComboBox / dropdown trigger.
213    pub combo_box: super::widgets::ResolvedComboBoxTheme,
214    /// Segmented control.
215    pub segmented_control: super::widgets::ResolvedSegmentedControlTheme,
216    /// Card / container.
217    pub card: super::widgets::ResolvedCardTheme,
218    /// Expander / disclosure.
219    pub expander: super::widgets::ResolvedExpanderTheme,
220    /// Hyperlink.
221    pub link: super::widgets::ResolvedLinkTheme,
222}
223
224// --- Resolved ---
225
226/// A theme fully resolved for a specific color mode.
227///
228/// Returned by [`Theme::resolve`](super::Theme::resolve). Bundles everything
229/// a UI framework needs to render a window: the picked variant's resolved
230/// visual properties, the theme's icon set, and the icon theme name — each
231/// already passed through its precedence chain.
232///
233/// # Icon theme precedence
234///
235/// The [`icon_theme`](Self::icon_theme) field is filled by checking, in order:
236///
237/// 1. The picked variant's `defaults.icon_theme` (per-mode override, e.g.
238///    KDE Plasma's `"breeze"` light / `"breeze-dark"` dark).
239/// 2. The parent [`Theme::icon_theme`](super::Theme::icon_theme) (shared
240///    across light and dark).
241/// 3. [`system_icon_theme()`](crate::detect::system_icon_theme) (runtime
242///    detect).
243///
244/// The first value that is `Some` wins. Where none is — the TOML states no
245/// icon theme and detection fails — the field is `None`: no theme stands in,
246/// and [`system_icon_theme()`](crate::detect::system_icon_theme) gives the
247/// reason.
248/// [`icon_theme_explicit`](Self::icon_theme_explicit) reports whether the
249/// value came from the TOML (tiers 1 or 2) or from runtime detection
250/// (tier 3) — useful for UI code that labels the theme-author's choice as
251/// `default (X)`.
252///
253/// # Examples
254///
255/// ```
256/// use native_theme::theme::{ColorMode, Theme};
257///
258/// let theme = Theme::preset("material-3")?;
259/// let r = theme.resolve(ColorMode::Light)?;
260/// assert_eq!(r.icon_theme.as_deref(), Some("material"));
261/// assert!(r.icon_theme_explicit);
262/// # Ok::<(), native_theme::error::Error>(())
263/// ```
264#[derive(Clone, Debug)]
265#[non_exhaustive]
266pub struct Resolved {
267    /// The mode of the variant actually resolved: `Dark` iff the theme's
268    /// `dark` variant was used. It differs from the requested mode when the
269    /// theme lacks that variant and
270    /// [`pick_variant`](super::Theme::pick_variant) falls back to the other.
271    pub mode: super::ColorMode,
272    /// The picked variant's fully-resolved visual properties.
273    pub variant: ResolvedTheme,
274    /// The theme's icon set. Falls back to
275    /// [`system_icon_set()`](crate::detect::system_icon_set) when the TOML
276    /// omits it.
277    pub icon_set: super::IconSet,
278    /// The icon theme name, resolved through the three-tier precedence
279    /// documented on the struct. `None` when the TOML states none and
280    /// detection fails; the app can call
281    /// [`system_icon_theme()`](crate::detect::system_icon_theme) for the
282    /// reason.
283    pub icon_theme: Option<std::borrow::Cow<'static, str>>,
284    /// `true` if [`icon_theme`](Self::icon_theme) came from the TOML (tiers 1
285    /// or 2); `false` if it was left to runtime system detection (tier 3),
286    /// whether or not that detection named a theme.
287    pub icon_theme_explicit: bool,
288}
289
290#[cfg(test)]
291#[allow(
292    clippy::unwrap_used,
293    clippy::expect_used,
294    clippy::bool_assert_comparison
295)]
296mod tests {
297    use super::*;
298    use crate::Rgba;
299    use crate::model::ResolvedFontSpec;
300    use crate::model::border::ResolvedDefaultsBorder;
301    use crate::model::font::FontStyle;
302
303    fn sample_font() -> ResolvedFontSpec {
304        ResolvedFontSpec {
305            family: "Inter".into(),
306            size: 14.0,
307            defined_size: Some(crate::model::font::FontSize::Px(14.0)),
308            weight: 400,
309            style: FontStyle::Normal,
310            color: Rgba::rgb(128, 128, 128),
311        }
312    }
313
314    fn sample_border() -> ResolvedDefaultsBorder {
315        ResolvedDefaultsBorder {
316            color: Rgba::rgb(200, 200, 200),
317            corner_radius: 4.0,
318            corner_radius_lg: 8.0,
319            line_width: 1.0,
320            opacity: 0.15,
321            shadow_enabled: true,
322        }
323    }
324
325    fn sample_icon_sizes() -> ResolvedIconSizes {
326        ResolvedIconSizes {
327            toolbar: 24.0,
328            small: 16.0,
329            large: 32.0,
330            dialog: 22.0,
331            panel: 20.0,
332        }
333    }
334
335    fn sample_text_scale_entry() -> ResolvedTextScaleEntry {
336        ResolvedTextScaleEntry {
337            size: 12.0,
338            weight: 400,
339            line_height: 1.4,
340        }
341    }
342
343    fn sample_defaults() -> ResolvedDefaults {
344        let c = Rgba::rgb(128, 128, 128);
345        ResolvedDefaults {
346            font: sample_font(),
347            line_height: 1.4,
348            mono_font: ResolvedFontSpec {
349                family: "JetBrains Mono".into(),
350                size: 12.0,
351                defined_size: Some(crate::model::font::FontSize::Px(12.0)),
352                weight: 400,
353                style: FontStyle::Normal,
354                color: Rgba::rgb(128, 128, 128),
355            },
356            background_color: c,
357            text_color: c,
358            accent_color: c,
359            accent_text_color: c,
360            surface_color: c,
361            muted_color: c,
362            shadow_color: c,
363            link_color: c,
364            selection_background: c,
365            selection_text_color: c,
366            selection_inactive_background: c,
367            text_selection_background: c,
368            text_selection_color: c,
369            disabled_text_color: c,
370            danger_color: c,
371            danger_text_color: c,
372            warning_color: c,
373            warning_text_color: c,
374            success_color: c,
375            success_text_color: c,
376            info_color: c,
377            info_text_color: c,
378            border: sample_border(),
379            disabled_opacity: 0.5,
380            focus_ring_color: c,
381            focus_ring_width: 2.0,
382            focus_ring_offset: 1.0,
383            icon_sizes: sample_icon_sizes(),
384        }
385    }
386
387    // --- ResolvedIconSizes tests ---
388
389    #[test]
390    fn resolved_icon_sizes_has_5_concrete_fields() {
391        let i = sample_icon_sizes();
392        assert_eq!(i.toolbar, 24.0);
393        assert_eq!(i.small, 16.0);
394        assert_eq!(i.large, 32.0);
395        assert_eq!(i.dialog, 22.0);
396        assert_eq!(i.panel, 20.0);
397    }
398
399    #[test]
400    fn resolved_icon_sizes_derives_clone_debug_partialeq() {
401        let i = sample_icon_sizes();
402        let i2 = i.clone();
403        assert_eq!(i, i2);
404        let dbg = format!("{i:?}");
405        assert!(dbg.contains("ResolvedIconSizes"));
406    }
407
408    // --- ResolvedTextScaleEntry tests ---
409
410    #[test]
411    fn resolved_text_scale_entry_has_3_concrete_fields() {
412        let e = sample_text_scale_entry();
413        assert_eq!(e.size, 12.0);
414        assert_eq!(e.weight, 400);
415        assert_eq!(e.line_height, 1.4);
416    }
417
418    #[test]
419    fn resolved_text_scale_entry_derives_clone_debug_partialeq() {
420        let e = sample_text_scale_entry();
421        let e2 = e.clone();
422        assert_eq!(e, e2);
423        let dbg = format!("{e:?}");
424        assert!(dbg.contains("ResolvedTextScaleEntry"));
425    }
426
427    // --- ResolvedTextScale tests ---
428
429    #[test]
430    fn resolved_text_scale_has_4_entries() {
431        let ts = ResolvedTextScale {
432            caption: ResolvedTextScaleEntry {
433                size: 11.0,
434                weight: 400,
435                line_height: 1.3,
436            },
437            section_heading: ResolvedTextScaleEntry {
438                size: 14.0,
439                weight: 600,
440                line_height: 1.4,
441            },
442            dialog_title: ResolvedTextScaleEntry {
443                size: 16.0,
444                weight: 700,
445                line_height: 1.2,
446            },
447            display: ResolvedTextScaleEntry {
448                size: 24.0,
449                weight: 300,
450                line_height: 1.1,
451            },
452        };
453        assert_eq!(ts.caption.size, 11.0);
454        assert_eq!(ts.section_heading.weight, 600);
455        assert_eq!(ts.dialog_title.size, 16.0);
456        assert_eq!(ts.display.weight, 300);
457    }
458
459    #[test]
460    fn resolved_text_scale_derives_clone_debug_partialeq() {
461        let e = sample_text_scale_entry();
462        let ts = ResolvedTextScale {
463            caption: e.clone(),
464            section_heading: e.clone(),
465            dialog_title: e.clone(),
466            display: e,
467        };
468        let ts2 = ts.clone();
469        assert_eq!(ts, ts2);
470        let dbg = format!("{ts:?}");
471        assert!(dbg.contains("ResolvedTextScale"));
472    }
473
474    // --- ResolvedDefaults tests ---
475
476    #[test]
477    fn resolved_defaults_all_fields_concrete() {
478        let d = sample_defaults();
479        // Fonts
480        assert_eq!(d.font.family.as_ref(), "Inter");
481        assert_eq!(d.mono_font.family.as_ref(), "JetBrains Mono");
482        assert_eq!(d.line_height, 1.4);
483        // Some colors
484        assert_eq!(d.background_color, Rgba::rgb(128, 128, 128));
485        assert_eq!(d.accent_color, Rgba::rgb(128, 128, 128));
486        // Geometry (border sub-struct)
487        assert_eq!(d.border.corner_radius, 4.0);
488        assert_eq!(d.border.shadow_enabled, true);
489        // Focus ring
490        assert_eq!(d.focus_ring_width, 2.0);
491        // Icon sizes
492        assert_eq!(d.icon_sizes.toolbar, 24.0);
493    }
494
495    #[test]
496    fn resolved_defaults_derives_clone_debug_partialeq() {
497        let d = sample_defaults();
498        let d2 = d.clone();
499        assert_eq!(d, d2);
500        let dbg = format!("{d:?}");
501        assert!(dbg.contains("ResolvedDefaults"));
502    }
503
504    // --- ResolvedTheme tests ---
505    // NOTE: These tests construct ResolvedTheme with all 25 widget structs.
506    // The widget Resolved* types will have new field names after Task 2,
507    // but for now they reference the old names -- Plan 02 (resolve.rs) will
508    // update all consumers. These tests are intentionally commented out until
509    // the full atomic commit is assembled.
510    //
511    // The structural tests for ResolvedDefaults above verify the defaults
512    // rename is correct.
513
514    // --- Behavioral tests (issue 2d) ---
515    // These tests call into resolve() and presets, which will break until
516    // Plans 02-04 update all consumers. They are kept for reference but
517    // will not compile until the atomic commit is complete.
518}