native-theme 0.6.1

Cross-platform native theme detection and loading for Rust GUI applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
// ThemeDefaults: global properties shared across widgets

use std::borrow::Cow;

use crate::Rgba;
use crate::model::border::DefaultsBorderSpec;
use crate::model::{FontSpec, IconSizes};
use native_theme_derive::ThemeFields;
use serde::{Deserialize, Serialize};

/// Global theme defaults shared across all widgets.
///
/// # Field structure
///
/// This struct uses two patterns for its fields:
///
/// - **`Option<T>` leaf fields** (`accent_color`, `disabled_opacity`, `line_height`, etc.) —
///   `None` means "not set." During merge, an overlay's `Some` value replaces
///   the base wholesale.
///
/// - **Non-Option nested struct fields** (`font`, `mono_font`, `border`,
///   `icon_sizes`) — these support partial field-by-field override during
///   merge. For example, an overlay that sets only `font.size` will inherit
///   the base's `font.family` and `font.weight`. This makes theme merging
///   more flexible: you can fine-tune individual properties without replacing
///   the entire sub-struct.
///
/// This asymmetry is intentional. Checking "is accent_color set?" is
/// `defaults.accent_color.is_some()`, while checking "is font set?" requires
/// inspecting individual fields like `defaults.font.family.is_some()`.
///
/// When resolving a widget's properties, `None` on the widget struct
/// means "inherit from `ThemeDefaults`".
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, ThemeFields)]
#[serde(default)]
pub struct ThemeDefaults {
    // ---- Base font ----
    /// Primary UI font (family, size, weight).
    #[serde(default, skip_serializing_if = "FontSpec::is_empty")]
    pub font: FontSpec,

    /// Line height multiplier (e.g. 1.4 = 140% of font size).
    pub line_height: Option<f32>,

    /// Monospace font for code/terminal content.
    #[serde(default, skip_serializing_if = "FontSpec::is_empty")]
    pub mono_font: FontSpec,

    // ---- Base colors ----
    /// Main window/surface background color.
    pub background_color: Option<Rgba>,
    /// Default text color.
    pub text_color: Option<Rgba>,
    /// Accent/brand color for interactive elements.
    pub accent_color: Option<Rgba>,
    /// Text color used on accent-colored backgrounds.
    pub accent_text_color: Option<Rgba>,
    /// Elevated surface color (cards, dialogs, popovers).
    pub surface_color: Option<Rgba>,
    /// Secondary/subdued text color.
    pub muted_color: Option<Rgba>,
    /// Drop shadow color (with alpha).
    pub shadow_color: Option<Rgba>,
    /// Hyperlink text color.
    pub link_color: Option<Rgba>,
    /// Selection highlight background.
    pub selection_background: Option<Rgba>,
    /// Text color over selection highlight.
    pub selection_text_color: Option<Rgba>,
    /// Selection background when window is unfocused.
    pub selection_inactive_background: Option<Rgba>,
    /// Text selection background (inline text highlight).
    pub text_selection_background: Option<Rgba>,
    /// Text selection color (inline text highlight).
    pub text_selection_color: Option<Rgba>,
    /// Text color for disabled controls, before `disabled_opacity` fades the
    /// widget: the enabled text colour where the platform dims by opacity.
    pub disabled_text_color: Option<Rgba>,

    // ---- Status colors ----
    /// Danger/error color.
    pub danger_color: Option<Rgba>,
    /// Text color on danger-colored backgrounds.
    pub danger_text_color: Option<Rgba>,
    /// Warning color.
    pub warning_color: Option<Rgba>,
    /// Text color on warning-colored backgrounds.
    pub warning_text_color: Option<Rgba>,
    /// Success/confirmation color.
    pub success_color: Option<Rgba>,
    /// Text color on success-colored backgrounds.
    pub success_text_color: Option<Rgba>,
    /// Informational color.
    pub info_color: Option<Rgba>,
    /// Text color on info-colored backgrounds.
    pub info_text_color: Option<Rgba>,

    // ---- Global geometry ----
    /// Border sub-struct (color, corner_radius, line_width, etc.).
    #[serde(default, skip_serializing_if = "DefaultsBorderSpec::is_empty")]
    pub border: DefaultsBorderSpec,
    /// Opacity for disabled controls (0.0–1.0), applied to the whole widget.
    ///
    /// A consumer applies both this and the disabled colours
    /// (`disabled_text_color`, each widget's `disabled_*`). A platform dims by
    /// one mechanism, and the data makes the other an identity: 1.0 where the
    /// platform dims by colour (KDE, Windows), and disabled colours equal to
    /// the enabled ones where it dims by opacity (GNOME;
    /// docs/platform-facts.md §2.1.6). A widget with no `disabled_opacity`
    /// of its own (menu, list, link) fades by this one.
    pub disabled_opacity: Option<f32>,

    // ---- Focus ring ----
    /// Focus indicator outline color.
    pub focus_ring_color: Option<Rgba>,
    /// Focus indicator outline width.
    #[serde(rename = "focus_ring_width_px")]
    pub focus_ring_width: Option<f32>,
    /// Gap between element edge and focus indicator.
    #[serde(rename = "focus_ring_offset_px")]
    pub focus_ring_offset: Option<f32>,

    // ---- Icon sizes ----
    /// Per-context icon sizes.
    #[serde(default, skip_serializing_if = "IconSizes::is_empty")]
    pub icon_sizes: IconSizes,

    /// Visual icon theme name for this variant — OVERRIDE of
    /// [`crate::Theme::icon_theme`].
    ///
    /// When a theme uses the same icon theme for both light and dark variants,
    /// prefer declaring it at [`crate::Theme::icon_theme`] (shared across
    /// variants). Set this per-variant override only when the value differs
    /// by color mode — for example KDE Plasma's `"breeze"` (light) vs
    /// `"breeze-dark"` (dark).
    ///
    /// Precedence at resolve time:
    /// 1. `ThemeDefaults::icon_theme` (this field, per-variant override) — if set
    /// 2. [`crate::Theme::icon_theme`] (shared across variants) — if set
    /// 3. [`crate::model::icons::system_icon_theme()`] (runtime detection;
    ///    none where it fails)
    ///
    /// See `docs/archive/v0.5.7_gaps.md` §G4 for the rationale.
    pub icon_theme: Option<Cow<'static, str>>,
}

// Phase 93-05 G5: ThemeDefaults::FIELD_NAMES was a hand-authored 32-entry
// mirror of the serde field names. Removed -- #[derive(ThemeFields)] above
// registers the same list automatically into `crate::resolve::FieldInfo`,
// consumed by `lint_toml`. See docs/archive/v0.5.7_gaps.md §G5.

impl_merge!(ThemeDefaults {
    option {
        line_height,
        background_color, text_color, accent_color, accent_text_color,
        surface_color, muted_color, shadow_color, link_color,
        selection_background, selection_text_color,
        selection_inactive_background,
        text_selection_background, text_selection_color,
        disabled_text_color,
        danger_color, danger_text_color, warning_color, warning_text_color,
        success_color, success_text_color, info_color, info_text_color,
        disabled_opacity, focus_ring_color, focus_ring_width, focus_ring_offset,
        icon_theme
    }
    nested { font, mono_font, border, icon_sizes }
});

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::Rgba;
    use crate::model::border::DefaultsBorderSpec;
    use crate::model::font::FontSize;
    use crate::model::{FontSpec, IconSizes};

    // === default / is_empty ===

    #[test]
    fn default_has_all_none_options() {
        let d = ThemeDefaults::default();
        assert!(d.background_color.is_none());
        assert!(d.text_color.is_none());
        assert!(d.accent_color.is_none());
        assert!(d.accent_text_color.is_none());
        assert!(d.surface_color.is_none());
        assert!(d.muted_color.is_none());
        assert!(d.shadow_color.is_none());
        assert!(d.link_color.is_none());
        assert!(d.selection_background.is_none());
        assert!(d.selection_text_color.is_none());
        assert!(d.selection_inactive_background.is_none());
        assert!(d.text_selection_background.is_none());
        assert!(d.text_selection_color.is_none());
        assert!(d.disabled_text_color.is_none());
        assert!(d.danger_color.is_none());
        assert!(d.danger_text_color.is_none());
        assert!(d.warning_color.is_none());
        assert!(d.warning_text_color.is_none());
        assert!(d.success_color.is_none());
        assert!(d.success_text_color.is_none());
        assert!(d.info_color.is_none());
        assert!(d.info_text_color.is_none());
        assert!(d.disabled_opacity.is_none());
        assert!(d.focus_ring_color.is_none());
        assert!(d.focus_ring_width.is_none());
        assert!(d.focus_ring_offset.is_none());
        assert!(d.line_height.is_none());
        assert!(d.icon_theme.is_none());
    }

    #[test]
    fn default_nested_structs_are_all_empty() {
        let d = ThemeDefaults::default();
        assert!(d.font.is_empty());
        assert!(d.mono_font.is_empty());
        assert!(d.border.is_empty());
        assert!(d.icon_sizes.is_empty());
    }

    #[test]
    fn default_is_empty() {
        assert!(ThemeDefaults::default().is_empty());
    }

    #[test]
    fn not_empty_when_accent_color_set() {
        let d = ThemeDefaults {
            accent_color: Some(Rgba::rgb(0, 120, 215)),
            ..Default::default()
        };
        assert!(!d.is_empty());
    }

    #[test]
    fn not_empty_when_font_family_set() {
        let d = ThemeDefaults {
            font: FontSpec {
                family: Some("Inter".into()),
                ..Default::default()
            },
            ..Default::default()
        };
        assert!(!d.is_empty());
    }

    #[test]
    fn not_empty_when_border_set() {
        let d = ThemeDefaults {
            border: DefaultsBorderSpec {
                corner_radius: Some(4.0),
                ..Default::default()
            },
            ..Default::default()
        };
        assert!(!d.is_empty());
    }

    // === font and mono_font are plain FontSpec (not Option) ===

    #[test]
    fn font_is_plain_fontspec_not_option() {
        let d = ThemeDefaults::default();
        // If this compiles, font is FontSpec (not Option<FontSpec>)
        let _ = d.font.family;
        let _ = d.font.size;
        let _ = d.font.weight;
    }

    #[test]
    fn mono_font_is_plain_fontspec_not_option() {
        let d = ThemeDefaults::default();
        let _ = d.mono_font.family;
    }

    // === merge ===

    #[test]
    fn merge_option_overlay_wins() {
        let mut base = ThemeDefaults {
            accent_color: Some(Rgba::rgb(100, 100, 100)),
            ..Default::default()
        };
        let overlay = ThemeDefaults {
            accent_color: Some(Rgba::rgb(0, 120, 215)),
            ..Default::default()
        };
        base.merge(&overlay);
        assert_eq!(base.accent_color, Some(Rgba::rgb(0, 120, 215)));
    }

    #[test]
    fn merge_none_preserves_base() {
        let mut base = ThemeDefaults {
            accent_color: Some(Rgba::rgb(0, 120, 215)),
            ..Default::default()
        };
        let overlay = ThemeDefaults::default();
        base.merge(&overlay);
        assert_eq!(base.accent_color, Some(Rgba::rgb(0, 120, 215)));
    }

    #[test]
    fn merge_font_family_preserved_when_overlay_family_none() {
        let mut base = ThemeDefaults {
            font: FontSpec {
                family: Some("Noto Sans".into()),
                size: Some(FontSize::Px(11.0)),
                weight: None,
                ..Default::default()
            },
            ..Default::default()
        };
        let overlay = ThemeDefaults {
            font: FontSpec {
                family: None,
                size: None,
                weight: Some(700),
                ..Default::default()
            },
            ..Default::default()
        };
        base.merge(&overlay);
        assert_eq!(base.font.family.as_deref(), Some("Noto Sans")); // preserved
        assert_eq!(base.font.size, Some(FontSize::Px(11.0))); // preserved
        assert_eq!(base.font.weight, Some(700)); // overlay wins
    }

    #[test]
    fn merge_border_nested_merges_recursively() {
        let mut base = ThemeDefaults {
            border: DefaultsBorderSpec {
                corner_radius: Some(4.0),
                ..Default::default()
            },
            ..Default::default()
        };
        let overlay = ThemeDefaults {
            border: DefaultsBorderSpec {
                line_width: Some(1.0),
                ..Default::default()
            },
            ..Default::default()
        };
        base.merge(&overlay);
        assert_eq!(base.border.corner_radius, Some(4.0)); // preserved
        assert_eq!(base.border.line_width, Some(1.0)); // overlay wins
    }

    #[test]
    fn merge_icon_sizes_nested_merges_recursively() {
        let mut base = ThemeDefaults {
            icon_sizes: IconSizes {
                toolbar: Some(22.0),
                ..Default::default()
            },
            ..Default::default()
        };
        let overlay = ThemeDefaults {
            icon_sizes: IconSizes {
                small: Some(16.0),
                ..Default::default()
            },
            ..Default::default()
        };
        base.merge(&overlay);
        assert_eq!(base.icon_sizes.toolbar, Some(22.0)); // preserved
        assert_eq!(base.icon_sizes.small, Some(16.0)); // overlay wins
    }

    // === TOML round-trip ===

    #[test]
    fn toml_round_trip_accent_color_and_font_family() {
        let d = ThemeDefaults {
            accent_color: Some(Rgba::rgb(0, 120, 215)),
            font: FontSpec {
                family: Some("Inter".into()),
                ..Default::default()
            },
            ..Default::default()
        };
        let toml_str = toml::to_string(&d).unwrap();
        // Font section should appear
        assert!(
            toml_str.contains("[font]"),
            "Expected [font] section, got: {toml_str}"
        );
        // accent_color should appear as hex
        assert!(
            toml_str.contains("accent_color"),
            "Expected accent_color field, got: {toml_str}"
        );
        // Round-trip
        let d2: ThemeDefaults = toml::from_str(&toml_str).unwrap();
        assert_eq!(d, d2);
    }

    #[test]
    fn toml_empty_sections_suppressed() {
        // An all-default ThemeDefaults should produce minimal or empty TOML
        let d = ThemeDefaults::default();
        let toml_str = toml::to_string(&d).unwrap();
        // No sub-tables should appear for empty nested structs
        assert!(
            !toml_str.contains("[font]"),
            "Empty font should be suppressed: {toml_str}"
        );
        assert!(
            !toml_str.contains("[mono_font]"),
            "Empty mono_font should be suppressed: {toml_str}"
        );
        assert!(
            !toml_str.contains("[border]"),
            "Empty border should be suppressed: {toml_str}"
        );
        assert!(
            !toml_str.contains("[icon_sizes]"),
            "Empty icon_sizes should be suppressed: {toml_str}"
        );
    }

    #[test]
    fn toml_mono_font_sub_table() {
        let d = ThemeDefaults {
            mono_font: FontSpec {
                family: Some("JetBrains Mono".into()),
                size: Some(FontSize::Px(12.0)),
                ..Default::default()
            },
            ..Default::default()
        };
        let toml_str = toml::to_string(&d).unwrap();
        assert!(
            toml_str.contains("[mono_font]"),
            "Expected [mono_font] section, got: {toml_str}"
        );
        let d2: ThemeDefaults = toml::from_str(&toml_str).unwrap();
        assert_eq!(d, d2);
    }

    #[test]
    fn toml_border_sub_table() {
        let d = ThemeDefaults {
            border: DefaultsBorderSpec {
                corner_radius: Some(4.0),
                line_width: Some(1.0),
                ..Default::default()
            },
            ..Default::default()
        };
        let toml_str = toml::to_string(&d).unwrap();
        assert!(
            toml_str.contains("[border]"),
            "Expected [border] section, got: {toml_str}"
        );
        let d2: ThemeDefaults = toml::from_str(&toml_str).unwrap();
        assert_eq!(d, d2);
    }
}