Skip to main content

native_theme/resolve/
mod.rs

1// Resolution engine: three-stage pipeline.
2//
3// 1. resolve() -- pure data transform: fills None fields from defaults and
4//    related widgets via ~91 inheritance rules. No OS detection, no I/O.
5// 2. resolve_platform_defaults() -- fills fields that require OS detection:
6//    button_order (from detected desktop environment).
7// 3. validate() -- extracts Option<T> -> T, producing ResolvedTheme.
8//
9// Convenience: resolve_all() = 1+2, into_resolved() = 1+2+3.
10//
11// Split into submodules:
12// - inheritance: Phase 1-5 resolution rules (fill None fields from defaults/other widgets)
13// - validate: Field extraction, range checks, ResolvedTheme construction
14
15pub(crate) mod context;
16pub(crate) mod inheritance;
17pub(crate) mod validate;
18pub(crate) mod validate_helpers;
19
20pub use context::ResolutionContext;
21
22/// Widget field metadata for TOML linting. Populated by `#[derive(ThemeWidget)]`.
23pub(crate) struct WidgetFieldInfo {
24    /// Snake_case widget name (e.g., "button", "segmented_control").
25    pub widget_name: &'static str,
26    /// All serialized TOML field names for this widget.
27    pub field_names: &'static [&'static str],
28}
29inventory::collect!(WidgetFieldInfo);
30
31/// Non-widget (plain struct) field metadata for TOML linting.
32///
33/// Populated by `#[derive(ThemeFields)]` on plain structs like `FontSpec`,
34/// `IconSizes`, `ThemeDefaults`, etc. Consumed by `lint_toml` to detect
35/// unknown keys in sub-tables. See `docs/archive/v0.5.7_gaps.md` §G5 for
36/// rationale — this sister registry to `WidgetFieldInfo` eliminates the
37/// hand-authored `FIELD_NAMES` constants that previously duplicated
38/// struct field lists.
39pub(crate) struct FieldInfo {
40    /// Pascal-case type name (e.g. "FontSpec", "IconSizes", "ThemeDefaults").
41    pub struct_name: &'static str,
42    /// All serialized TOML field names for this struct.
43    pub field_names: &'static [&'static str],
44}
45inventory::collect!(FieldInfo);
46
47/// Border inheritance registry (Phase 94-01 G6).
48///
49/// Populated by `#[derive(ThemeWidget)]` for widgets that declare
50/// `#[theme_inherit(border_kind = "full" | "full_lg" | "partial")]`. Each
51/// declaration produces one row in this registry.
52///
53/// Consumed by the inverted drift test
54/// `border_inheritance_toml_matches_macro_emit` in `inheritance.rs::tests`
55/// which asserts `docs/inheritance-rules.toml [border_inheritance]` matches
56/// the registry byte-for-byte (macro is the source of truth post-G6;
57/// TOML is a generated-documentation output).
58///
59/// Sister registry to [`WidgetFieldInfo`] / [`FieldInfo`] — same
60/// inventory-crate pattern (`inventory::submit!` from the derive output).
61///
62/// Fields carry `#[cfg_attr(not(test), allow(dead_code))]` because they are
63/// consumed only by the drift tests in `inheritance.rs::tests`
64/// (introspection via `inventory::iter`). A non-test build compiles the
65/// registry rows but never reads them — matching Phase 93-09's conditional
66/// `allow(dead_code)` pattern for self-unmasking (if a future non-test
67/// consumer lands, the allow stops firing and real dead-code regressions
68/// surface).
69pub(crate) struct BorderInheritanceInfo {
70    /// Snake_case widget name (e.g., "button", "segmented_control").
71    #[cfg_attr(not(test), allow(dead_code))]
72    pub widget_name: &'static str,
73    /// Inheritance kind: `"full"`, `"full_lg"`, or `"partial"`.
74    ///
75    /// Uses a plain `&'static str` instead of an enum to keep the
76    /// inventory schema dependency-free — `BorderInheritanceKind` lives
77    /// in `native-theme-derive` which the runtime crate cannot import.
78    #[cfg_attr(not(test), allow(dead_code))]
79    pub kind: &'static str,
80}
81inventory::collect!(BorderInheritanceInfo);
82
83/// Font inheritance registry (Phase 94-01 G6).
84///
85/// Populated by `#[derive(ThemeWidget)]` for widgets that declare one or
86/// more `#[theme_inherit(font = "<field>")]` attributes. Each attribute
87/// produces one row in this registry; widgets like `list` (item_font +
88/// header_font) and `dialog` (title_font + body_font) contribute two rows.
89///
90/// Consumed by the inverted drift test
91/// `font_inheritance_toml_matches_macro_emit` in `inheritance.rs::tests`
92/// which asserts `docs/inheritance-rules.toml [font_inheritance]` matches
93/// the registry byte-for-byte.
94///
95/// Fields carry `#[cfg_attr(not(test), allow(dead_code))]` — see
96/// [`BorderInheritanceInfo`] for rationale.
97pub(crate) struct FontInheritanceInfo {
98    /// Snake_case widget name (e.g., "button", "list", "dialog", "link").
99    #[cfg_attr(not(test), allow(dead_code))]
100    pub widget_name: &'static str,
101    /// Name of the font field on the widget Option struct
102    /// (e.g., `"font"`, `"title_bar_font"`, `"item_font"`, `"header_font"`,
103    /// `"title_font"`, `"body_font"`).
104    #[cfg_attr(not(test), allow(dead_code))]
105    pub font_field: &'static str,
106}
107inventory::collect!(FontInheritanceInfo);
108
109/// Uniform inheritance registry.
110///
111/// Populated by `#[derive(ThemeWidget)]`: one row per field that declares
112/// `#[theme(inherit_from = "...")]`. Consumed by the drift test
113/// `uniform_rules_all_accounted_for` in `inheritance.rs::tests`, which
114/// asserts each such `docs/inheritance-rules.toml [uniform]` rule names the
115/// same source as the attribute.
116///
117/// Fields carry `#[cfg_attr(not(test), allow(dead_code))]` — see
118/// [`BorderInheritanceInfo`] for rationale.
119pub(crate) struct UniformInheritanceInfo {
120    /// Snake_case widget name (e.g., "button", "segmented_control").
121    #[cfg_attr(not(test), allow(dead_code))]
122    pub widget_name: &'static str,
123    /// Name of the field on the widget Option struct (e.g., `"icon_size"`,
124    /// not the serialized `"icon_size_px"`).
125    #[cfg_attr(not(test), allow(dead_code))]
126    pub field: &'static str,
127    /// The `inherit_from` path as written (e.g., `"defaults.accent_color"`).
128    #[cfg_attr(not(test), allow(dead_code))]
129    pub inherit_from: &'static str,
130}
131inventory::collect!(UniformInheritanceInfo);
132
133use crate::model::ThemeMode;
134use crate::model::resolved::ResolvedTheme;
135
136impl ThemeMode {
137    /// Apply all ~91 inheritance rules in 4-phase order (pure data transform).
138    ///
139    /// After calling resolve(), most Option fields that were None will be filled
140    /// from defaults or related widget fields. Calling resolve() twice produces
141    /// the same result (idempotent).
142    ///
143    /// This method is a pure data transform: it does not perform any OS detection
144    /// or I/O. For full resolution including platform defaults (dialog button
145    /// order from the desktop environment), use [`resolve_all()`](Self::resolve_all).
146    ///
147    /// # Phases
148    ///
149    /// 1. **Defaults internal chains** -- accent derives selection, focus_ring_color;
150    ///    selection derives selection_inactive.
151    /// 2. **Safety nets** -- platform-divergent fields get a reasonable fallback.
152    /// 3. **Widget-from-defaults** -- colors, geometry, fonts, text scale entries
153    ///    all inherit from defaults.
154    /// 4. **Widget-to-widget** -- inactive title bar fields fall back to active.
155    #[doc(hidden)]
156    pub fn resolve(&mut self) {
157        self.resolve_defaults_internal();
158        self.resolve_safety_nets();
159        self.resolve_widgets_from_defaults();
160        self.resolve_widget_to_widget();
161    }
162
163    /// Fill platform-detected defaults that require OS interaction.
164    ///
165    /// Currently fills:
166    /// - `dialog.button_order` from the detected desktop environment if not already set
167    ///
168    /// This is separated from [`resolve()`](Self::resolve) because it performs
169    /// runtime OS detection (reading desktop environment settings), unlike the
170    /// pure inheritance rules in resolve().
171    ///
172    /// Note: `icon_set` resolution is handled at the
173    /// [`Theme`](crate::Theme) / pipeline level. `icon_theme` is per-variant
174    /// on [`ThemeDefaults`](crate::ThemeDefaults) and resolved in the pipeline.
175    #[doc(hidden)]
176    pub fn resolve_platform_defaults(&mut self) {
177        if self.dialog.button_order.is_none() {
178            self.dialog.button_order = Some(inheritance::platform_button_order());
179        }
180    }
181
182    /// Apply all inheritance rules and platform defaults.
183    ///
184    /// Convenience method that calls [`resolve()`](Self::resolve) followed by
185    /// [`resolve_platform_defaults()`](Self::resolve_platform_defaults).
186    ///
187    /// **Note:** this does *not* handle `font_dpi`. Pass the DPI value to
188    /// [`validate_with_dpi()`](Self::validate_with_dpi) or use
189    /// [`into_resolved()`](Self::into_resolved), which takes the DPI from its
190    /// [`ResolutionContext`].
191    #[doc(hidden)]
192    pub fn resolve_all(&mut self) {
193        self.resolve();
194        self.resolve_platform_defaults();
195    }
196
197    /// Apply inheritance rules using a pre-built [`ResolutionContext`].
198    ///
199    /// Replacement for [`resolve_all()`](Self::resolve_all) that reads
200    /// `ctx.button_order` instead of calling
201    /// `inheritance::platform_button_order` inline. Used by
202    /// [`into_resolved`](Self::into_resolved) so that platform detection
203    /// happens once per theme-build (in
204    /// [`ResolutionContext::from_system`](crate::resolve::ResolutionContext::from_system))
205    /// rather than inside each variant resolution.
206    ///
207    /// Note: `icon_theme` resolution lives in
208    /// [`pipeline::run_pipeline`](crate::pipeline) with three-tier
209    /// precedence. This method intentionally does not read
210    /// `ctx.icon_theme`.
211    #[doc(hidden)]
212    pub fn resolve_all_with_context(&mut self, ctx: &ResolutionContext) {
213        self.resolve();
214        if self.dialog.button_order.is_none() {
215            self.dialog.button_order = Some(ctx.button_order);
216        }
217    }
218
219    /// Resolve all inheritance rules and validate in one step.
220    ///
221    /// This is the recommended way to convert a `ThemeMode` into a
222    /// [`ResolvedTheme`]. It applies every inheritance rule (including
223    /// the `ctx.button_order` platform default) followed by
224    /// [`validate_with_dpi()`](Self::validate_with_dpi), ensuring no
225    /// fields are left unresolved.
226    ///
227    /// # Arguments
228    ///
229    /// * `ctx` -- resolution-time inputs captured once per theme-build.
230    ///   Use [`ResolutionContext::from_system`](crate::resolve::ResolutionContext::from_system)
231    ///   for OS-detected values (Linux/Windows ≈ 96 DPI, macOS = 72 DPI,
232    ///   button order per desktop environment), or
233    ///   [`ResolutionContext::for_tests`](crate::resolve::ResolutionContext::for_tests)
234    ///   for deterministic test values (96 DPI, `PrimaryRight`,
235    ///   no `icon_theme`). The [`resolve_system()`](Self::resolve_system)
236    ///   shortcut wraps the `from_system()` case.
237    ///
238    /// # Errors
239    ///
240    /// Returns [`crate::Error::ResolutionInvalid`] with the one path
241    /// `context.font_dpi` if `ctx.font_dpi` is not finite and positive.
242    /// Returns [`crate::Error::ResolutionIncomplete`] if any fields
243    /// remain `None` after resolution, or
244    /// [`crate::Error::ResolutionInvalid`] if range checks fail.
245    ///
246    /// # Examples
247    ///
248    /// ```
249    /// use native_theme::resolve::ResolutionContext;
250    /// use native_theme::theme::Theme;
251    ///
252    /// let theme = Theme::preset("dracula")?;
253    /// let variant = theme.dark.ok_or("no dark variant")?;
254    /// let resolved = variant.into_resolved(&ResolutionContext::from_system())?;
255    /// // Or use the zero-argument shortcut:
256    /// // let resolved = variant.resolve_system()?;
257    /// let _accent = resolved.defaults.accent_color;
258    /// # Ok::<(), Box<dyn std::error::Error>>(())
259    /// ```
260    pub fn into_resolved(mut self, ctx: &ResolutionContext) -> crate::Result<ResolvedTheme> {
261        self.resolve_all_with_context(ctx);
262        self.validate_with_dpi(ctx.font_dpi)
263    }
264
265    /// Resolve using the OS-detected context.
266    ///
267    /// Equivalent to
268    /// `self.into_resolved(&ResolutionContext::from_system())`.
269    ///
270    /// Placed on `ThemeMode` (not `Theme`) because `Theme` has both
271    /// light and dark variants — variant selection must be explicit via
272    /// [`Theme::into_variant`](crate::theme::Theme::into_variant), a
273    /// deliberate deviation from `docs/archive/v0.5.7_gaps.md` §G7 step 4.
274    ///
275    /// # Errors
276    ///
277    /// Returns [`crate::Error::ResolutionIncomplete`] if any fields
278    /// remain `None` after resolution, or
279    /// [`crate::Error::ResolutionInvalid`] if range checks fail.
280    ///
281    /// # Examples
282    ///
283    /// ```
284    /// use native_theme::theme::{ColorMode, Theme};
285    ///
286    /// let theme = Theme::preset("dracula")?;
287    /// let variant = theme.into_variant(ColorMode::Dark)?;
288    /// let resolved = variant.resolve_system()?;
289    /// let _accent = resolved.defaults.accent_color;
290    /// # Ok::<(), Box<dyn std::error::Error>>(())
291    /// ```
292    pub fn resolve_system(self) -> crate::Result<ResolvedTheme> {
293        self.into_resolved(&ResolutionContext::from_system())
294    }
295}
296
297#[cfg(test)]
298#[allow(clippy::unwrap_used, clippy::expect_used)]
299mod tests;