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