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