native-theme 0.7.0

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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
// Resolved (non-optional) theme types produced after theme resolution.
//
// These types mirror their Option-based counterparts in defaults.rs, font.rs,
// icon_sizes.rs, and mod.rs (ThemeMode), but with all fields
// guaranteed populated. Produced by validate() after resolve().

use super::border::ResolvedDefaultsBorder;
use super::font::ResolvedFontSpec;
use crate::Rgba;

// --- ResolvedIconSizes ---

/// Fully resolved per-context icon sizes where every context is guaranteed populated.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub struct ResolvedIconSizes {
    /// Icon size for toolbar buttons.
    pub toolbar: f32,
    /// Small icon size for inline use.
    pub small: f32,
    /// Large icon size for menus/lists.
    pub large: f32,
    /// Icon size for dialog buttons.
    pub dialog: f32,
    /// Icon size for panel headers.
    pub panel: f32,
}

// --- ResolvedTextScaleEntry ---

/// A single resolved text scale entry with guaranteed size, weight, and line height.
///
/// No `Default` derive: Constructed from a populated
/// `TextScaleEntry` during resolution; the missing-field sentinel is
/// written inline in
/// `crate::resolve::validate_helpers::require_text_scale_entry` (private).
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub struct ResolvedTextScaleEntry {
    /// Font size in logical pixels. A size stated in points is converted at
    /// the resolution context's
    /// [`font_dpi`](crate::resolve::ResolutionContext::font_dpi).
    pub size: f32,
    /// CSS font weight (100-900).
    pub weight: u16,
    /// Line height in logical pixels. Computed as `defaults.line_height * size`
    /// when not explicitly set. An explicit value stated in points is converted
    /// at the same `font_dpi` as the size.
    pub line_height: f32,
}

// --- ResolvedTextScale ---

/// A fully resolved text scale with all four typographic roles populated.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub struct ResolvedTextScale {
    /// Caption / small label text.
    pub caption: ResolvedTextScaleEntry,
    /// Section heading text.
    pub section_heading: ResolvedTextScaleEntry,
    /// Dialog title text.
    pub dialog_title: ResolvedTextScaleEntry,
    /// Large display / hero text.
    pub display: ResolvedTextScaleEntry,
}

// --- ResolvedDefaults ---

/// Fully resolved global theme defaults where every field is guaranteed populated.
///
/// Mirrors [`crate::model::ThemeDefaults`] but with concrete (non-Option) types.
/// Produced by the resolution/validation pipeline.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub struct ResolvedDefaults {
    // ---- Base font ----
    /// Primary UI font.
    pub font: ResolvedFontSpec,
    /// Line height multiplier.
    pub line_height: f32,
    /// Monospace font for code/terminal content.
    pub mono_font: ResolvedFontSpec,

    // ---- Base colors ----
    /// Main window/surface background color.
    pub background_color: Rgba,
    /// Default text color.
    pub text_color: Rgba,
    /// Accent/brand color for interactive elements.
    pub accent_color: Rgba,
    /// Text color used on accent-colored backgrounds.
    pub accent_text_color: Rgba,
    /// Elevated surface color.
    pub surface_color: Rgba,
    /// Secondary/subdued text color.
    pub muted_color: Rgba,
    /// Drop shadow color.
    pub shadow_color: Rgba,
    /// Hyperlink text color.
    pub link_color: Rgba,
    /// Selection highlight background.
    pub selection_background: Rgba,
    /// Text color over selection highlight.
    pub selection_text_color: Rgba,
    /// Selection background when window is unfocused.
    pub selection_inactive_background: Rgba,
    /// Text selection background (inline text highlight).
    pub text_selection_background: Rgba,
    /// Text selection color (inline text highlight).
    pub text_selection_color: Rgba,
    /// Text color for disabled controls.
    pub disabled_text_color: Rgba,

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

    // ---- Global geometry ----
    /// Border sub-struct (color, corner_radius, line_width, etc.).
    pub border: ResolvedDefaultsBorder,
    /// Opacity for disabled controls, applied to the whole widget together
    /// with the disabled colours; 1.0 where the platform dims by colour
    /// alone. See [`ThemeDefaults::disabled_opacity`](crate::model::ThemeDefaults::disabled_opacity).
    pub disabled_opacity: f32,

    // ---- Focus ring ----
    /// Focus indicator outline color.
    pub focus_ring_color: Rgba,
    /// Focus indicator outline width.
    pub focus_ring_width: f32,
    /// Gap between element edge and focus indicator.
    pub focus_ring_offset: f32,

    // ---- Icon sizes ----
    /// Per-context icon sizes.
    pub icon_sizes: ResolvedIconSizes,
}

// --- ResolvedTheme ---

/// A fully resolved theme where every field is guaranteed populated.
///
/// Produced by `validate()` after `resolve()`. Consumed by toolkit connectors.
/// Mirrors [`crate::model::ThemeMode`] but with concrete (non-Option) types
/// for all 26 per-widget structs plus defaults and text scale.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub struct ResolvedTheme {
    /// Global defaults.
    pub defaults: ResolvedDefaults,
    /// Per-role text scale.
    pub text_scale: ResolvedTextScale,

    // ---- Per-widget resolved structs ----
    /// Window chrome.
    pub window: super::widgets::ResolvedWindowTheme,
    /// Push button.
    pub button: super::widgets::ResolvedButtonTheme,
    /// Text input.
    pub input: super::widgets::ResolvedInputTheme,
    /// Multi-line text field's padding; the rest is `input`'s.
    pub text_area: super::widgets::ResolvedTextAreaTheme,
    /// Checkbox / radio button.
    pub checkbox: super::widgets::ResolvedCheckboxTheme,
    /// Popup / context menu.
    pub menu: super::widgets::ResolvedMenuTheme,
    /// Tooltip.
    pub tooltip: super::widgets::ResolvedTooltipTheme,
    /// Scrollbar.
    pub scrollbar: super::widgets::ResolvedScrollbarTheme,
    /// Slider.
    pub slider: super::widgets::ResolvedSliderTheme,
    /// Progress bar.
    pub progress_bar: super::widgets::ResolvedProgressBarTheme,
    /// Tab bar.
    pub tab: super::widgets::ResolvedTabTheme,
    /// Sidebar panel.
    pub sidebar: super::widgets::ResolvedSidebarTheme,
    /// Toolbar.
    pub toolbar: super::widgets::ResolvedToolbarTheme,
    /// Status bar.
    pub status_bar: super::widgets::ResolvedStatusBarTheme,
    /// List / table.
    pub list: super::widgets::ResolvedListTheme,
    /// Popover / dropdown.
    pub popover: super::widgets::ResolvedPopoverTheme,
    /// Splitter handle.
    pub splitter: super::widgets::ResolvedSplitterTheme,
    /// Separator line.
    pub separator: super::widgets::ResolvedSeparatorTheme,
    /// Toggle switch.
    pub switch: super::widgets::ResolvedSwitchTheme,
    /// Dialog.
    pub dialog: super::widgets::ResolvedDialogTheme,
    /// Spinner / progress ring.
    pub spinner: super::widgets::ResolvedSpinnerTheme,
    /// ComboBox / dropdown trigger.
    pub combo_box: super::widgets::ResolvedComboBoxTheme,
    /// Segmented control.
    pub segmented_control: super::widgets::ResolvedSegmentedControlTheme,
    /// Card / container.
    pub card: super::widgets::ResolvedCardTheme,
    /// Expander / disclosure.
    pub expander: super::widgets::ResolvedExpanderTheme,
    /// Hyperlink.
    pub link: super::widgets::ResolvedLinkTheme,
}

// --- Resolved ---

/// A theme fully resolved for a specific color mode.
///
/// Returned by [`Theme::resolve`](super::Theme::resolve). Bundles everything
/// a UI framework needs to render a window: the picked variant's resolved
/// visual properties, the theme's icon set, and the icon theme name — each
/// already passed through its precedence chain.
///
/// # Icon theme precedence
///
/// The [`icon_theme`](Self::icon_theme) field is filled by checking, in order:
///
/// 1. The picked variant's `defaults.icon_theme` (per-mode override, e.g.
///    KDE Plasma's `"breeze"` light / `"breeze-dark"` dark).
/// 2. The parent [`Theme::icon_theme`](super::Theme::icon_theme) (shared
///    across light and dark).
/// 3. [`system_icon_theme()`](crate::detect::system_icon_theme) (runtime
///    detect).
///
/// The first value that is `Some` wins. Where none is — the TOML states no
/// icon theme and detection fails — the field is `None`: no theme stands in,
/// and [`system_icon_theme()`](crate::detect::system_icon_theme) gives the
/// reason.
/// [`icon_theme_explicit`](Self::icon_theme_explicit) reports whether the
/// value came from the TOML (tiers 1 or 2) or from runtime detection
/// (tier 3) — useful for UI code that labels the theme-author's choice as
/// `default (X)`.
///
/// # Examples
///
/// ```
/// use native_theme::theme::{ColorMode, Theme};
///
/// let theme = Theme::preset("material-3")?;
/// let r = theme.resolve(ColorMode::Light)?;
/// assert_eq!(r.icon_theme.as_deref(), Some("material"));
/// assert!(r.icon_theme_explicit);
/// # Ok::<(), native_theme::error::Error>(())
/// ```
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Resolved {
    /// The mode of the variant actually resolved: `Dark` iff the theme's
    /// `dark` variant was used. It differs from the requested mode when the
    /// theme lacks that variant and
    /// [`pick_variant`](super::Theme::pick_variant) falls back to the other.
    pub mode: super::ColorMode,
    /// The picked variant's fully-resolved visual properties.
    pub variant: ResolvedTheme,
    /// The theme's icon set. Falls back to
    /// [`system_icon_set()`](crate::detect::system_icon_set) when the TOML
    /// omits it.
    pub icon_set: super::IconSet,
    /// The icon theme name, resolved through the three-tier precedence
    /// documented on the struct. `None` when the TOML states none and
    /// detection fails; the app can call
    /// [`system_icon_theme()`](crate::detect::system_icon_theme) for the
    /// reason.
    pub icon_theme: Option<std::borrow::Cow<'static, str>>,
    /// `true` if [`icon_theme`](Self::icon_theme) came from the TOML (tiers 1
    /// or 2); `false` if it was left to runtime system detection (tier 3),
    /// whether or not that detection named a theme.
    pub icon_theme_explicit: bool,
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::bool_assert_comparison
)]
mod tests {
    use super::*;
    use crate::Rgba;
    use crate::model::ResolvedFontSpec;
    use crate::model::border::ResolvedDefaultsBorder;
    use crate::model::font::FontStyle;

    fn sample_font() -> ResolvedFontSpec {
        ResolvedFontSpec {
            family: "Inter".into(),
            size: 14.0,
            defined_size: Some(crate::model::font::FontSize::Px(14.0)),
            weight: 400,
            style: FontStyle::Normal,
            color: Rgba::rgb(128, 128, 128),
        }
    }

    fn sample_border() -> ResolvedDefaultsBorder {
        ResolvedDefaultsBorder {
            color: Rgba::rgb(200, 200, 200),
            corner_radius: 4.0,
            corner_radius_lg: 8.0,
            line_width: 1.0,
            opacity: 0.15,
            shadow_enabled: true,
        }
    }

    fn sample_icon_sizes() -> ResolvedIconSizes {
        ResolvedIconSizes {
            toolbar: 24.0,
            small: 16.0,
            large: 32.0,
            dialog: 22.0,
            panel: 20.0,
        }
    }

    fn sample_text_scale_entry() -> ResolvedTextScaleEntry {
        ResolvedTextScaleEntry {
            size: 12.0,
            weight: 400,
            line_height: 1.4,
        }
    }

    fn sample_defaults() -> ResolvedDefaults {
        let c = Rgba::rgb(128, 128, 128);
        ResolvedDefaults {
            font: sample_font(),
            line_height: 1.4,
            mono_font: ResolvedFontSpec {
                family: "JetBrains Mono".into(),
                size: 12.0,
                defined_size: Some(crate::model::font::FontSize::Px(12.0)),
                weight: 400,
                style: FontStyle::Normal,
                color: Rgba::rgb(128, 128, 128),
            },
            background_color: c,
            text_color: c,
            accent_color: c,
            accent_text_color: c,
            surface_color: c,
            muted_color: c,
            shadow_color: c,
            link_color: c,
            selection_background: c,
            selection_text_color: c,
            selection_inactive_background: c,
            text_selection_background: c,
            text_selection_color: c,
            disabled_text_color: c,
            danger_color: c,
            danger_text_color: c,
            warning_color: c,
            warning_text_color: c,
            success_color: c,
            success_text_color: c,
            info_color: c,
            info_text_color: c,
            border: sample_border(),
            disabled_opacity: 0.5,
            focus_ring_color: c,
            focus_ring_width: 2.0,
            focus_ring_offset: 1.0,
            icon_sizes: sample_icon_sizes(),
        }
    }

    // --- ResolvedIconSizes tests ---

    #[test]
    fn resolved_icon_sizes_has_5_concrete_fields() {
        let i = sample_icon_sizes();
        assert_eq!(i.toolbar, 24.0);
        assert_eq!(i.small, 16.0);
        assert_eq!(i.large, 32.0);
        assert_eq!(i.dialog, 22.0);
        assert_eq!(i.panel, 20.0);
    }

    #[test]
    fn resolved_icon_sizes_derives_clone_debug_partialeq() {
        let i = sample_icon_sizes();
        let i2 = i.clone();
        assert_eq!(i, i2);
        let dbg = format!("{i:?}");
        assert!(dbg.contains("ResolvedIconSizes"));
    }

    // --- ResolvedTextScaleEntry tests ---

    #[test]
    fn resolved_text_scale_entry_has_3_concrete_fields() {
        let e = sample_text_scale_entry();
        assert_eq!(e.size, 12.0);
        assert_eq!(e.weight, 400);
        assert_eq!(e.line_height, 1.4);
    }

    #[test]
    fn resolved_text_scale_entry_derives_clone_debug_partialeq() {
        let e = sample_text_scale_entry();
        let e2 = e.clone();
        assert_eq!(e, e2);
        let dbg = format!("{e:?}");
        assert!(dbg.contains("ResolvedTextScaleEntry"));
    }

    // --- ResolvedTextScale tests ---

    #[test]
    fn resolved_text_scale_has_4_entries() {
        let ts = ResolvedTextScale {
            caption: ResolvedTextScaleEntry {
                size: 11.0,
                weight: 400,
                line_height: 1.3,
            },
            section_heading: ResolvedTextScaleEntry {
                size: 14.0,
                weight: 600,
                line_height: 1.4,
            },
            dialog_title: ResolvedTextScaleEntry {
                size: 16.0,
                weight: 700,
                line_height: 1.2,
            },
            display: ResolvedTextScaleEntry {
                size: 24.0,
                weight: 300,
                line_height: 1.1,
            },
        };
        assert_eq!(ts.caption.size, 11.0);
        assert_eq!(ts.section_heading.weight, 600);
        assert_eq!(ts.dialog_title.size, 16.0);
        assert_eq!(ts.display.weight, 300);
    }

    #[test]
    fn resolved_text_scale_derives_clone_debug_partialeq() {
        let e = sample_text_scale_entry();
        let ts = ResolvedTextScale {
            caption: e.clone(),
            section_heading: e.clone(),
            dialog_title: e.clone(),
            display: e,
        };
        let ts2 = ts.clone();
        assert_eq!(ts, ts2);
        let dbg = format!("{ts:?}");
        assert!(dbg.contains("ResolvedTextScale"));
    }

    // --- ResolvedDefaults tests ---

    #[test]
    fn resolved_defaults_all_fields_concrete() {
        let d = sample_defaults();
        // Fonts
        assert_eq!(d.font.family.as_ref(), "Inter");
        assert_eq!(d.mono_font.family.as_ref(), "JetBrains Mono");
        assert_eq!(d.line_height, 1.4);
        // Some colors
        assert_eq!(d.background_color, Rgba::rgb(128, 128, 128));
        assert_eq!(d.accent_color, Rgba::rgb(128, 128, 128));
        // Geometry (border sub-struct)
        assert_eq!(d.border.corner_radius, 4.0);
        assert_eq!(d.border.shadow_enabled, true);
        // Focus ring
        assert_eq!(d.focus_ring_width, 2.0);
        // Icon sizes
        assert_eq!(d.icon_sizes.toolbar, 24.0);
    }

    #[test]
    fn resolved_defaults_derives_clone_debug_partialeq() {
        let d = sample_defaults();
        let d2 = d.clone();
        assert_eq!(d, d2);
        let dbg = format!("{d:?}");
        assert!(dbg.contains("ResolvedDefaults"));
    }

    // --- ResolvedTheme tests ---
    // NOTE: These tests construct ResolvedTheme with all 25 widget structs.
    // The widget Resolved* types will have new field names after Task 2,
    // but for now they reference the old names -- Plan 02 (resolve.rs) will
    // update all consumers. These tests are intentionally commented out until
    // the full atomic commit is assembled.
    //
    // The structural tests for ResolvedDefaults above verify the defaults
    // rename is correct.

    // --- Behavioral tests (issue 2d) ---
    // These tests call into resolve() and presets, which will break until
    // Plans 02-04 update all consumers. They are kept for reference but
    // will not compile until the atomic commit is complete.
}