Skip to main content

native_theme/model/
defaults.rs

1// ThemeDefaults: global properties shared across widgets
2
3use std::borrow::Cow;
4
5use crate::Rgba;
6use crate::model::border::DefaultsBorderSpec;
7use crate::model::{FontSpec, IconSizes};
8use native_theme_derive::ThemeFields;
9use serde::{Deserialize, Serialize};
10
11/// Global theme defaults shared across all widgets.
12///
13/// # Field structure
14///
15/// This struct uses two patterns for its fields:
16///
17/// - **`Option<T>` leaf fields** (`accent_color`, `disabled_opacity`, `line_height`, etc.) —
18///   `None` means "not set." During merge, an overlay's `Some` value replaces
19///   the base wholesale.
20///
21/// - **Non-Option nested struct fields** (`font`, `mono_font`, `border`,
22///   `icon_sizes`) — these support partial field-by-field override during
23///   merge. For example, an overlay that sets only `font.size` will inherit
24///   the base's `font.family` and `font.weight`. This makes theme merging
25///   more flexible: you can fine-tune individual properties without replacing
26///   the entire sub-struct.
27///
28/// This asymmetry is intentional. Checking "is accent_color set?" is
29/// `defaults.accent_color.is_some()`, while checking "is font set?" requires
30/// inspecting individual fields like `defaults.font.family.is_some()`.
31///
32/// When resolving a widget's properties, `None` on the widget struct
33/// means "inherit from `ThemeDefaults`".
34#[serde_with::skip_serializing_none]
35#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, ThemeFields)]
36#[serde(default)]
37pub struct ThemeDefaults {
38    // ---- Base font ----
39    /// Primary UI font (family, size, weight).
40    #[serde(default, skip_serializing_if = "FontSpec::is_empty")]
41    pub font: FontSpec,
42
43    /// Line height multiplier (e.g. 1.4 = 140% of font size).
44    pub line_height: Option<f32>,
45
46    /// Monospace font for code/terminal content.
47    #[serde(default, skip_serializing_if = "FontSpec::is_empty")]
48    pub mono_font: FontSpec,
49
50    // ---- Base colors ----
51    /// Main window/surface background color.
52    pub background_color: Option<Rgba>,
53    /// Default text color.
54    pub text_color: Option<Rgba>,
55    /// Accent/brand color for interactive elements.
56    pub accent_color: Option<Rgba>,
57    /// Text color used on accent-colored backgrounds.
58    pub accent_text_color: Option<Rgba>,
59    /// Elevated surface color (cards, dialogs, popovers).
60    pub surface_color: Option<Rgba>,
61    /// Secondary/subdued text color.
62    pub muted_color: Option<Rgba>,
63    /// Drop shadow color (with alpha).
64    pub shadow_color: Option<Rgba>,
65    /// Hyperlink text color.
66    pub link_color: Option<Rgba>,
67    /// Selection highlight background.
68    pub selection_background: Option<Rgba>,
69    /// Text color over selection highlight.
70    pub selection_text_color: Option<Rgba>,
71    /// Selection background when window is unfocused.
72    pub selection_inactive_background: Option<Rgba>,
73    /// Text selection background (inline text highlight).
74    pub text_selection_background: Option<Rgba>,
75    /// Text selection color (inline text highlight).
76    pub text_selection_color: Option<Rgba>,
77    /// Text color for disabled controls.
78    pub disabled_text_color: Option<Rgba>,
79
80    // ---- Status colors ----
81    /// Danger/error color.
82    pub danger_color: Option<Rgba>,
83    /// Text color on danger-colored backgrounds.
84    pub danger_text_color: Option<Rgba>,
85    /// Warning color.
86    pub warning_color: Option<Rgba>,
87    /// Text color on warning-colored backgrounds.
88    pub warning_text_color: Option<Rgba>,
89    /// Success/confirmation color.
90    pub success_color: Option<Rgba>,
91    /// Text color on success-colored backgrounds.
92    pub success_text_color: Option<Rgba>,
93    /// Informational color.
94    pub info_color: Option<Rgba>,
95    /// Text color on info-colored backgrounds.
96    pub info_text_color: Option<Rgba>,
97
98    // ---- Global geometry ----
99    /// Border sub-struct (color, corner_radius, line_width, etc.).
100    #[serde(default, skip_serializing_if = "DefaultsBorderSpec::is_empty")]
101    pub border: DefaultsBorderSpec,
102    /// Opacity for disabled controls (0.0–1.0).
103    pub disabled_opacity: Option<f32>,
104
105    // ---- Focus ring ----
106    /// Focus indicator outline color.
107    pub focus_ring_color: Option<Rgba>,
108    /// Focus indicator outline width.
109    #[serde(rename = "focus_ring_width_px")]
110    pub focus_ring_width: Option<f32>,
111    /// Gap between element edge and focus indicator.
112    #[serde(rename = "focus_ring_offset_px")]
113    pub focus_ring_offset: Option<f32>,
114
115    // ---- Icon sizes ----
116    /// Per-context icon sizes.
117    #[serde(default, skip_serializing_if = "IconSizes::is_empty")]
118    pub icon_sizes: IconSizes,
119
120    /// Visual icon theme name for this variant — OVERRIDE of
121    /// [`crate::Theme::icon_theme`].
122    ///
123    /// When a theme uses the same icon theme for both light and dark variants,
124    /// prefer declaring it at [`crate::Theme::icon_theme`] (shared across
125    /// variants). Set this per-variant override only when the value differs
126    /// by color mode — for example KDE Plasma's `"breeze"` (light) vs
127    /// `"breeze-dark"` (dark).
128    ///
129    /// Precedence at resolve time:
130    /// 1. `ThemeDefaults::icon_theme` (this field, per-variant override) — if set
131    /// 2. [`crate::Theme::icon_theme`] (shared across variants) — if set
132    /// 3. [`crate::model::icons::system_icon_theme()`] (runtime fallback)
133    ///
134    /// See doc 1 §20, `docs/todo_v0.5.7_gaps.md` §G4, and the Phase 80-fix
135    /// decision for the full rationale.
136    pub icon_theme: Option<Cow<'static, str>>,
137}
138
139// Phase 93-05 G5: ThemeDefaults::FIELD_NAMES was a hand-authored 32-entry
140// mirror of the serde field names. Removed -- #[derive(ThemeFields)] above
141// registers the same list automatically into `crate::resolve::FieldInfo`,
142// consumed by `lint_toml`. See docs/todo_v0.5.7_gaps.md §G5.
143
144impl_merge!(ThemeDefaults {
145    option {
146        line_height,
147        background_color, text_color, accent_color, accent_text_color,
148        surface_color, muted_color, shadow_color, link_color,
149        selection_background, selection_text_color,
150        selection_inactive_background,
151        text_selection_background, text_selection_color,
152        disabled_text_color,
153        danger_color, danger_text_color, warning_color, warning_text_color,
154        success_color, success_text_color, info_color, info_text_color,
155        disabled_opacity, focus_ring_color, focus_ring_width, focus_ring_offset,
156        icon_theme
157    }
158    nested { font, mono_font, border, icon_sizes }
159});
160
161#[cfg(test)]
162#[allow(clippy::unwrap_used, clippy::expect_used)]
163mod tests {
164    use super::*;
165    use crate::Rgba;
166    use crate::model::border::DefaultsBorderSpec;
167    use crate::model::font::FontSize;
168    use crate::model::{FontSpec, IconSizes};
169
170    // === default / is_empty ===
171
172    #[test]
173    fn default_has_all_none_options() {
174        let d = ThemeDefaults::default();
175        assert!(d.background_color.is_none());
176        assert!(d.text_color.is_none());
177        assert!(d.accent_color.is_none());
178        assert!(d.accent_text_color.is_none());
179        assert!(d.surface_color.is_none());
180        assert!(d.muted_color.is_none());
181        assert!(d.shadow_color.is_none());
182        assert!(d.link_color.is_none());
183        assert!(d.selection_background.is_none());
184        assert!(d.selection_text_color.is_none());
185        assert!(d.selection_inactive_background.is_none());
186        assert!(d.text_selection_background.is_none());
187        assert!(d.text_selection_color.is_none());
188        assert!(d.disabled_text_color.is_none());
189        assert!(d.danger_color.is_none());
190        assert!(d.danger_text_color.is_none());
191        assert!(d.warning_color.is_none());
192        assert!(d.warning_text_color.is_none());
193        assert!(d.success_color.is_none());
194        assert!(d.success_text_color.is_none());
195        assert!(d.info_color.is_none());
196        assert!(d.info_text_color.is_none());
197        assert!(d.disabled_opacity.is_none());
198        assert!(d.focus_ring_color.is_none());
199        assert!(d.focus_ring_width.is_none());
200        assert!(d.focus_ring_offset.is_none());
201        assert!(d.line_height.is_none());
202        assert!(d.icon_theme.is_none());
203    }
204
205    #[test]
206    fn default_nested_structs_are_all_empty() {
207        let d = ThemeDefaults::default();
208        assert!(d.font.is_empty());
209        assert!(d.mono_font.is_empty());
210        assert!(d.border.is_empty());
211        assert!(d.icon_sizes.is_empty());
212    }
213
214    #[test]
215    fn default_is_empty() {
216        assert!(ThemeDefaults::default().is_empty());
217    }
218
219    #[test]
220    fn not_empty_when_accent_color_set() {
221        let d = ThemeDefaults {
222            accent_color: Some(Rgba::rgb(0, 120, 215)),
223            ..Default::default()
224        };
225        assert!(!d.is_empty());
226    }
227
228    #[test]
229    fn not_empty_when_font_family_set() {
230        let d = ThemeDefaults {
231            font: FontSpec {
232                family: Some("Inter".into()),
233                ..Default::default()
234            },
235            ..Default::default()
236        };
237        assert!(!d.is_empty());
238    }
239
240    #[test]
241    fn not_empty_when_border_set() {
242        let d = ThemeDefaults {
243            border: DefaultsBorderSpec {
244                corner_radius: Some(4.0),
245                ..Default::default()
246            },
247            ..Default::default()
248        };
249        assert!(!d.is_empty());
250    }
251
252    // === font and mono_font are plain FontSpec (not Option) ===
253
254    #[test]
255    fn font_is_plain_fontspec_not_option() {
256        let d = ThemeDefaults::default();
257        // If this compiles, font is FontSpec (not Option<FontSpec>)
258        let _ = d.font.family;
259        let _ = d.font.size;
260        let _ = d.font.weight;
261    }
262
263    #[test]
264    fn mono_font_is_plain_fontspec_not_option() {
265        let d = ThemeDefaults::default();
266        let _ = d.mono_font.family;
267    }
268
269    // === merge ===
270
271    #[test]
272    fn merge_option_overlay_wins() {
273        let mut base = ThemeDefaults {
274            accent_color: Some(Rgba::rgb(100, 100, 100)),
275            ..Default::default()
276        };
277        let overlay = ThemeDefaults {
278            accent_color: Some(Rgba::rgb(0, 120, 215)),
279            ..Default::default()
280        };
281        base.merge(&overlay);
282        assert_eq!(base.accent_color, Some(Rgba::rgb(0, 120, 215)));
283    }
284
285    #[test]
286    fn merge_none_preserves_base() {
287        let mut base = ThemeDefaults {
288            accent_color: Some(Rgba::rgb(0, 120, 215)),
289            ..Default::default()
290        };
291        let overlay = ThemeDefaults::default();
292        base.merge(&overlay);
293        assert_eq!(base.accent_color, Some(Rgba::rgb(0, 120, 215)));
294    }
295
296    #[test]
297    fn merge_font_family_preserved_when_overlay_family_none() {
298        let mut base = ThemeDefaults {
299            font: FontSpec {
300                family: Some("Noto Sans".into()),
301                size: Some(FontSize::Px(11.0)),
302                weight: None,
303                ..Default::default()
304            },
305            ..Default::default()
306        };
307        let overlay = ThemeDefaults {
308            font: FontSpec {
309                family: None,
310                size: None,
311                weight: Some(700),
312                ..Default::default()
313            },
314            ..Default::default()
315        };
316        base.merge(&overlay);
317        assert_eq!(base.font.family.as_deref(), Some("Noto Sans")); // preserved
318        assert_eq!(base.font.size, Some(FontSize::Px(11.0))); // preserved
319        assert_eq!(base.font.weight, Some(700)); // overlay wins
320    }
321
322    #[test]
323    fn merge_border_nested_merges_recursively() {
324        let mut base = ThemeDefaults {
325            border: DefaultsBorderSpec {
326                corner_radius: Some(4.0),
327                ..Default::default()
328            },
329            ..Default::default()
330        };
331        let overlay = ThemeDefaults {
332            border: DefaultsBorderSpec {
333                line_width: Some(1.0),
334                ..Default::default()
335            },
336            ..Default::default()
337        };
338        base.merge(&overlay);
339        assert_eq!(base.border.corner_radius, Some(4.0)); // preserved
340        assert_eq!(base.border.line_width, Some(1.0)); // overlay wins
341    }
342
343    #[test]
344    fn merge_icon_sizes_nested_merges_recursively() {
345        let mut base = ThemeDefaults {
346            icon_sizes: IconSizes {
347                toolbar: Some(22.0),
348                ..Default::default()
349            },
350            ..Default::default()
351        };
352        let overlay = ThemeDefaults {
353            icon_sizes: IconSizes {
354                small: Some(16.0),
355                ..Default::default()
356            },
357            ..Default::default()
358        };
359        base.merge(&overlay);
360        assert_eq!(base.icon_sizes.toolbar, Some(22.0)); // preserved
361        assert_eq!(base.icon_sizes.small, Some(16.0)); // overlay wins
362    }
363
364    // === TOML round-trip ===
365
366    #[test]
367    fn toml_round_trip_accent_color_and_font_family() {
368        let d = ThemeDefaults {
369            accent_color: Some(Rgba::rgb(0, 120, 215)),
370            font: FontSpec {
371                family: Some("Inter".into()),
372                ..Default::default()
373            },
374            ..Default::default()
375        };
376        let toml_str = toml::to_string(&d).unwrap();
377        // Font section should appear
378        assert!(
379            toml_str.contains("[font]"),
380            "Expected [font] section, got: {toml_str}"
381        );
382        // accent_color should appear as hex
383        assert!(
384            toml_str.contains("accent_color"),
385            "Expected accent_color field, got: {toml_str}"
386        );
387        // Round-trip
388        let d2: ThemeDefaults = toml::from_str(&toml_str).unwrap();
389        assert_eq!(d, d2);
390    }
391
392    #[test]
393    fn toml_empty_sections_suppressed() {
394        // An all-default ThemeDefaults should produce minimal or empty TOML
395        let d = ThemeDefaults::default();
396        let toml_str = toml::to_string(&d).unwrap();
397        // No sub-tables should appear for empty nested structs
398        assert!(
399            !toml_str.contains("[font]"),
400            "Empty font should be suppressed: {toml_str}"
401        );
402        assert!(
403            !toml_str.contains("[mono_font]"),
404            "Empty mono_font should be suppressed: {toml_str}"
405        );
406        assert!(
407            !toml_str.contains("[border]"),
408            "Empty border should be suppressed: {toml_str}"
409        );
410        assert!(
411            !toml_str.contains("[icon_sizes]"),
412            "Empty icon_sizes should be suppressed: {toml_str}"
413        );
414    }
415
416    #[test]
417    fn toml_mono_font_sub_table() {
418        let d = ThemeDefaults {
419            mono_font: FontSpec {
420                family: Some("JetBrains Mono".into()),
421                size: Some(FontSize::Px(12.0)),
422                ..Default::default()
423            },
424            ..Default::default()
425        };
426        let toml_str = toml::to_string(&d).unwrap();
427        assert!(
428            toml_str.contains("[mono_font]"),
429            "Expected [mono_font] section, got: {toml_str}"
430        );
431        let d2: ThemeDefaults = toml::from_str(&toml_str).unwrap();
432        assert_eq!(d, d2);
433    }
434
435    #[test]
436    fn toml_border_sub_table() {
437        let d = ThemeDefaults {
438            border: DefaultsBorderSpec {
439                corner_radius: Some(4.0),
440                line_width: Some(1.0),
441                ..Default::default()
442            },
443            ..Default::default()
444        };
445        let toml_str = toml::to_string(&d).unwrap();
446        assert!(
447            toml_str.contains("[border]"),
448            "Expected [border] section, got: {toml_str}"
449        );
450        let d2: ThemeDefaults = toml::from_str(&toml_str).unwrap();
451        assert_eq!(d, d2);
452    }
453}