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    /// Whether every font size is rounded to whole logical pixels after its
47    /// conversion (`true`), as Qt rounds a font's pixel size: to hundredths,
48    /// then to a whole number, halves up, before any scale. `None` or
49    /// `false`: sizes keep their fraction. Text-scale line heights are not
50    /// rounded, and a size that rounds to 0 is rejected as out of range
51    /// (docs/platform-facts.md §2.1.1).
52    pub font_whole_pixels: Option<bool>,
53
54    /// Monospace font for code/terminal content.
55    #[serde(default, skip_serializing_if = "FontSpec::is_empty")]
56    pub mono_font: FontSpec,
57
58    // ---- Base colors ----
59    /// Main window/surface background color.
60    pub background_color: Option<Rgba>,
61    /// Default text color.
62    pub text_color: Option<Rgba>,
63    /// Accent/brand color for interactive elements.
64    pub accent_color: Option<Rgba>,
65    /// Text color used on accent-colored backgrounds.
66    pub accent_text_color: Option<Rgba>,
67    /// Elevated surface color (cards, dialogs, popovers).
68    pub surface_color: Option<Rgba>,
69    /// Secondary/subdued text color.
70    pub muted_color: Option<Rgba>,
71    /// Drop shadow color (with alpha).
72    pub shadow_color: Option<Rgba>,
73    /// Hyperlink text color.
74    pub link_color: Option<Rgba>,
75    /// Selection highlight background.
76    pub selection_background: Option<Rgba>,
77    /// Text color over selection highlight.
78    pub selection_text_color: Option<Rgba>,
79    /// Selection background when window is unfocused.
80    pub selection_inactive_background: Option<Rgba>,
81    /// Text color over `selection_inactive_background`, the selection of a
82    /// view without the focus; unstated, `selection_text_color`.
83    pub selection_inactive_text_color: Option<Rgba>,
84    /// Text selection background (inline text highlight).
85    pub text_selection_background: Option<Rgba>,
86    /// Text selection color (inline text highlight).
87    pub text_selection_color: Option<Rgba>,
88    /// Text color for disabled controls, before `disabled_opacity` fades the
89    /// widget: the enabled text colour where the platform dims by opacity.
90    pub disabled_text_color: Option<Rgba>,
91
92    // ---- Status colors ----
93    /// Danger/error color.
94    pub danger_color: Option<Rgba>,
95    /// Text color on danger-colored backgrounds.
96    pub danger_text_color: Option<Rgba>,
97    /// Warning color.
98    pub warning_color: Option<Rgba>,
99    /// Text color on warning-colored backgrounds.
100    pub warning_text_color: Option<Rgba>,
101    /// Success/confirmation color.
102    pub success_color: Option<Rgba>,
103    /// Text color on success-colored backgrounds.
104    pub success_text_color: Option<Rgba>,
105    /// Informational color.
106    pub info_color: Option<Rgba>,
107    /// Text color on info-colored backgrounds.
108    pub info_text_color: Option<Rgba>,
109
110    // ---- Global geometry ----
111    /// Border sub-struct (color, corner_radius, line_width, etc.).
112    #[serde(default, skip_serializing_if = "DefaultsBorderSpec::is_empty")]
113    pub border: DefaultsBorderSpec,
114    /// Opacity for disabled controls (0.0–1.0), applied to the whole widget.
115    ///
116    /// A consumer applies both this and the disabled colours
117    /// (`disabled_text_color`, each widget's `disabled_*`). A platform dims by
118    /// one mechanism, and the data makes the other an identity: 1.0 where the
119    /// platform dims by colour (KDE, Windows), and disabled colours equal to
120    /// the enabled ones where it dims by opacity (GNOME;
121    /// docs/platform-facts.md §2.1.6). A widget with no `disabled_opacity`
122    /// of its own (menu, list, link) fades by this one.
123    pub disabled_opacity: Option<f32>,
124
125    // ---- Focus ring ----
126    /// Focus indicator outline color.
127    pub focus_ring_color: Option<Rgba>,
128    /// Focus indicator outline width.
129    #[serde(rename = "focus_ring_width_px")]
130    pub focus_ring_width: Option<f32>,
131    /// Gap between element edge and focus indicator.
132    #[serde(rename = "focus_ring_offset_px")]
133    pub focus_ring_offset: Option<f32>,
134    /// Whether the platform shows its focus ring only for a focus that came
135    /// from the keyboard (`true`), or for any focus (`false`). `None` where the
136    /// theme does not say: a connector then draws the ring on any focus.
137    /// docs/platform-facts.md §2.1.5.
138    pub focus_ring_keyboard_only: Option<bool>,
139
140    // ---- Icon sizes ----
141    /// Per-context icon sizes.
142    #[serde(default, skip_serializing_if = "IconSizes::is_empty")]
143    pub icon_sizes: IconSizes,
144
145    /// Visual icon theme name for this variant — OVERRIDE of
146    /// [`crate::Theme::icon_theme`].
147    ///
148    /// When a theme uses the same icon theme for both light and dark variants,
149    /// prefer declaring it at [`crate::Theme::icon_theme`] (shared across
150    /// variants). Set this per-variant override only when the value differs
151    /// by color mode — for example KDE Plasma's `"breeze"` (light) vs
152    /// `"breeze-dark"` (dark).
153    ///
154    /// Precedence at resolve time:
155    /// 1. `ThemeDefaults::icon_theme` (this field, per-variant override) — if set
156    /// 2. [`crate::Theme::icon_theme`] (shared across variants) — if set
157    /// 3. [`crate::detect::system_icon_theme()`] (runtime detection;
158    ///    none where it fails)
159    ///
160    /// See `docs/archive/v0.5.7_gaps.md` §G4 for the rationale.
161    pub icon_theme: Option<Cow<'static, str>>,
162}
163
164// #[derive(ThemeFields)] above registers the serde field names into
165// `crate::resolve::FieldInfo`, consumed by `lint_toml` (docs/archive/v0.5.7_gaps.md §G5).
166
167impl_merge!(ThemeDefaults {
168    option {
169        line_height,
170        background_color, text_color, accent_color, accent_text_color,
171        surface_color, muted_color, shadow_color, link_color,
172        selection_background, selection_text_color,
173        selection_inactive_background, selection_inactive_text_color,
174        text_selection_background, text_selection_color,
175        disabled_text_color,
176        danger_color, danger_text_color, warning_color, warning_text_color,
177        success_color, success_text_color, info_color, info_text_color,
178        disabled_opacity, focus_ring_color, focus_ring_width, focus_ring_offset,
179        focus_ring_keyboard_only,
180        font_whole_pixels,
181        icon_theme
182    }
183    nested { font, mono_font, border, icon_sizes }
184});
185
186#[cfg(test)]
187#[allow(clippy::unwrap_used, clippy::expect_used)]
188mod tests {
189    use super::*;
190    use crate::Rgba;
191    use crate::model::border::DefaultsBorderSpec;
192    use crate::model::font::FontSize;
193    use crate::model::{FontSpec, IconSizes};
194
195    // === default / is_empty ===
196
197    #[test]
198    fn default_has_all_none_options() {
199        let d = ThemeDefaults::default();
200        assert!(d.background_color.is_none());
201        assert!(d.text_color.is_none());
202        assert!(d.accent_color.is_none());
203        assert!(d.accent_text_color.is_none());
204        assert!(d.surface_color.is_none());
205        assert!(d.muted_color.is_none());
206        assert!(d.shadow_color.is_none());
207        assert!(d.link_color.is_none());
208        assert!(d.selection_background.is_none());
209        assert!(d.selection_text_color.is_none());
210        assert!(d.selection_inactive_background.is_none());
211        assert!(d.selection_inactive_text_color.is_none());
212        assert!(d.text_selection_background.is_none());
213        assert!(d.text_selection_color.is_none());
214        assert!(d.disabled_text_color.is_none());
215        assert!(d.danger_color.is_none());
216        assert!(d.danger_text_color.is_none());
217        assert!(d.warning_color.is_none());
218        assert!(d.warning_text_color.is_none());
219        assert!(d.success_color.is_none());
220        assert!(d.success_text_color.is_none());
221        assert!(d.info_color.is_none());
222        assert!(d.info_text_color.is_none());
223        assert!(d.disabled_opacity.is_none());
224        assert!(d.focus_ring_color.is_none());
225        assert!(d.focus_ring_width.is_none());
226        assert!(d.focus_ring_offset.is_none());
227        assert!(d.focus_ring_keyboard_only.is_none());
228        assert!(d.font_whole_pixels.is_none());
229        assert!(d.line_height.is_none());
230        assert!(d.icon_theme.is_none());
231    }
232
233    #[test]
234    fn default_nested_structs_are_all_empty() {
235        let d = ThemeDefaults::default();
236        assert!(d.font.is_empty());
237        assert!(d.mono_font.is_empty());
238        assert!(d.border.is_empty());
239        assert!(d.icon_sizes.is_empty());
240    }
241
242    #[test]
243    fn default_is_empty() {
244        assert!(ThemeDefaults::default().is_empty());
245    }
246
247    #[test]
248    fn not_empty_when_accent_color_set() {
249        let d = ThemeDefaults {
250            accent_color: Some(Rgba::rgb(0, 120, 215)),
251            ..Default::default()
252        };
253        assert!(!d.is_empty());
254    }
255
256    #[test]
257    fn not_empty_when_font_family_set() {
258        let d = ThemeDefaults {
259            font: FontSpec {
260                family: Some("Inter".into()),
261                ..Default::default()
262            },
263            ..Default::default()
264        };
265        assert!(!d.is_empty());
266    }
267
268    #[test]
269    fn not_empty_when_border_set() {
270        let d = ThemeDefaults {
271            border: DefaultsBorderSpec {
272                corner_radius: Some(4.0),
273                ..Default::default()
274            },
275            ..Default::default()
276        };
277        assert!(!d.is_empty());
278    }
279
280    // === font and mono_font are plain FontSpec (not Option) ===
281
282    #[test]
283    fn font_is_plain_fontspec_not_option() {
284        let d = ThemeDefaults::default();
285        // If this compiles, font is FontSpec (not Option<FontSpec>)
286        let _ = d.font.family;
287        let _ = d.font.size;
288        let _ = d.font.weight;
289    }
290
291    #[test]
292    fn mono_font_is_plain_fontspec_not_option() {
293        let d = ThemeDefaults::default();
294        let _ = d.mono_font.family;
295    }
296
297    // === merge ===
298
299    #[test]
300    fn merge_option_overlay_wins() {
301        let mut base = ThemeDefaults {
302            accent_color: Some(Rgba::rgb(100, 100, 100)),
303            ..Default::default()
304        };
305        let overlay = ThemeDefaults {
306            accent_color: Some(Rgba::rgb(0, 120, 215)),
307            ..Default::default()
308        };
309        base.merge(&overlay);
310        assert_eq!(base.accent_color, Some(Rgba::rgb(0, 120, 215)));
311    }
312
313    #[test]
314    fn merge_none_preserves_base() {
315        let mut base = ThemeDefaults {
316            accent_color: Some(Rgba::rgb(0, 120, 215)),
317            ..Default::default()
318        };
319        let overlay = ThemeDefaults::default();
320        base.merge(&overlay);
321        assert_eq!(base.accent_color, Some(Rgba::rgb(0, 120, 215)));
322    }
323
324    #[test]
325    fn merge_keeps_and_overrides_focus_ring_keyboard_only() {
326        let mut base = ThemeDefaults {
327            focus_ring_keyboard_only: Some(true),
328            ..Default::default()
329        };
330        base.merge(&ThemeDefaults::default());
331        assert_eq!(base.focus_ring_keyboard_only, Some(true));
332        let overlay = ThemeDefaults {
333            focus_ring_keyboard_only: Some(false),
334            ..Default::default()
335        };
336        base.merge(&overlay);
337        assert_eq!(base.focus_ring_keyboard_only, Some(false));
338    }
339
340    #[test]
341    fn merge_keeps_and_overrides_font_whole_pixels() {
342        let mut base = ThemeDefaults {
343            font_whole_pixels: Some(true),
344            ..Default::default()
345        };
346        base.merge(&ThemeDefaults::default());
347        assert_eq!(base.font_whole_pixels, Some(true));
348        let overlay = ThemeDefaults {
349            font_whole_pixels: Some(false),
350            ..Default::default()
351        };
352        base.merge(&overlay);
353        assert_eq!(base.font_whole_pixels, Some(false));
354    }
355
356    #[test]
357    fn merge_font_family_preserved_when_overlay_family_none() {
358        let mut base = ThemeDefaults {
359            font: FontSpec {
360                family: Some("Noto Sans".into()),
361                size: Some(FontSize::Px(11.0)),
362                weight: None,
363                ..Default::default()
364            },
365            ..Default::default()
366        };
367        let overlay = ThemeDefaults {
368            font: FontSpec {
369                family: None,
370                size: None,
371                weight: Some(700),
372                ..Default::default()
373            },
374            ..Default::default()
375        };
376        base.merge(&overlay);
377        assert_eq!(base.font.family.as_deref(), Some("Noto Sans")); // preserved
378        assert_eq!(base.font.size, Some(FontSize::Px(11.0))); // preserved
379        assert_eq!(base.font.weight, Some(700)); // overlay wins
380    }
381
382    #[test]
383    fn merge_border_nested_merges_recursively() {
384        let mut base = ThemeDefaults {
385            border: DefaultsBorderSpec {
386                corner_radius: Some(4.0),
387                ..Default::default()
388            },
389            ..Default::default()
390        };
391        let overlay = ThemeDefaults {
392            border: DefaultsBorderSpec {
393                line_width: Some(1.0),
394                ..Default::default()
395            },
396            ..Default::default()
397        };
398        base.merge(&overlay);
399        assert_eq!(base.border.corner_radius, Some(4.0)); // preserved
400        assert_eq!(base.border.line_width, Some(1.0)); // overlay wins
401    }
402
403    #[test]
404    fn merge_icon_sizes_nested_merges_recursively() {
405        let mut base = ThemeDefaults {
406            icon_sizes: IconSizes {
407                toolbar: Some(22.0),
408                ..Default::default()
409            },
410            ..Default::default()
411        };
412        let overlay = ThemeDefaults {
413            icon_sizes: IconSizes {
414                small: Some(16.0),
415                ..Default::default()
416            },
417            ..Default::default()
418        };
419        base.merge(&overlay);
420        assert_eq!(base.icon_sizes.toolbar, Some(22.0)); // preserved
421        assert_eq!(base.icon_sizes.small, Some(16.0)); // overlay wins
422    }
423
424    // === TOML round-trip ===
425
426    #[test]
427    fn toml_round_trip_accent_color_and_font_family() {
428        let d = ThemeDefaults {
429            accent_color: Some(Rgba::rgb(0, 120, 215)),
430            font: FontSpec {
431                family: Some("Inter".into()),
432                ..Default::default()
433            },
434            ..Default::default()
435        };
436        let toml_str = toml::to_string(&d).unwrap();
437        // Font section should appear
438        assert!(
439            toml_str.contains("[font]"),
440            "Expected [font] section, got: {toml_str}"
441        );
442        // accent_color should appear as hex
443        assert!(
444            toml_str.contains("accent_color"),
445            "Expected accent_color field, got: {toml_str}"
446        );
447        // Round-trip
448        let d2: ThemeDefaults = toml::from_str(&toml_str).unwrap();
449        assert_eq!(d, d2);
450    }
451
452    #[test]
453    fn toml_empty_sections_suppressed() {
454        // An all-default ThemeDefaults should produce minimal or empty TOML
455        let d = ThemeDefaults::default();
456        let toml_str = toml::to_string(&d).unwrap();
457        // No sub-tables should appear for empty nested structs
458        assert!(
459            !toml_str.contains("[font]"),
460            "Empty font should be suppressed: {toml_str}"
461        );
462        assert!(
463            !toml_str.contains("[mono_font]"),
464            "Empty mono_font should be suppressed: {toml_str}"
465        );
466        assert!(
467            !toml_str.contains("[border]"),
468            "Empty border should be suppressed: {toml_str}"
469        );
470        assert!(
471            !toml_str.contains("[icon_sizes]"),
472            "Empty icon_sizes should be suppressed: {toml_str}"
473        );
474    }
475
476    #[test]
477    fn toml_mono_font_sub_table() {
478        let d = ThemeDefaults {
479            mono_font: FontSpec {
480                family: Some("JetBrains Mono".into()),
481                size: Some(FontSize::Px(12.0)),
482                ..Default::default()
483            },
484            ..Default::default()
485        };
486        let toml_str = toml::to_string(&d).unwrap();
487        assert!(
488            toml_str.contains("[mono_font]"),
489            "Expected [mono_font] section, got: {toml_str}"
490        );
491        let d2: ThemeDefaults = toml::from_str(&toml_str).unwrap();
492        assert_eq!(d, d2);
493    }
494
495    #[test]
496    fn toml_border_sub_table() {
497        let d = ThemeDefaults {
498            border: DefaultsBorderSpec {
499                corner_radius: Some(4.0),
500                line_width: Some(1.0),
501                ..Default::default()
502            },
503            ..Default::default()
504        };
505        let toml_str = toml::to_string(&d).unwrap();
506        assert!(
507            toml_str.contains("[border]"),
508            "Expected [border] section, got: {toml_str}"
509        );
510        let d2: ThemeDefaults = toml::from_str(&toml_str).unwrap();
511        assert_eq!(d, d2);
512    }
513}