native-theme 0.7.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
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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
// Error enum with Display, std::error::Error, and From conversions
//
// Option F: flat 10-variant Error + ErrorKind + RangeViolation

use std::fmt;

/// A range-violation error for a single theme property.
///
/// Produced during validation when a resolved numeric property falls outside
/// its allowed range.
#[derive(Debug, Clone)]
pub struct RangeViolation {
    /// Dot-separated TOML path of the property (e.g.
    /// `"light.button.min_width_px"`), as
    /// [`Error::ResolutionIncomplete`] describes.
    pub path: String,
    /// The actual value found.
    pub value: f64,
    /// Lower bound (inclusive), or `None` for open-ended.
    pub min: Option<f64>,
    /// Upper bound (inclusive), or `None` for open-ended.
    pub max: Option<f64>,
}

impl fmt::Display for RangeViolation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let lo = self
            .min
            .map_or_else(|| "-inf".to_owned(), |v| v.to_string());
        let hi = self.max.map_or_else(|| "inf".to_owned(), |v| v.to_string());
        write!(
            f,
            "{} must be {}..={}, got {}",
            self.path, lo, hi, self.value
        )
    }
}

/// Coarse error category returned by [`Error::kind()`].
///
/// Follows the `std::io::ErrorKind` precedent: callers can match on the kind
/// for broad dispatch without inspecting each variant.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ErrorKind {
    /// Platform feature not available or not supported.
    Platform,
    /// Parsing or lookup failure (TOML, preset name).
    Parse,
    /// Theme resolution failure (missing fields, range violations).
    Resolution,
    /// File I/O error.
    Io,
}

/// Errors that can occur when reading or processing theme data.
///
/// This is a flat enum with 10 variants. Use [`Error::kind()`] for coarse
/// dispatch without matching every variant.
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
    /// The platform has a theme reader, but the Cargo feature that compiles it
    /// is not enabled (`macos` on macOS, `windows` on Windows).
    FeatureDisabled {
        /// Feature name (`"macos"` or `"windows"`).
        name: &'static str,
        /// What the feature is needed for (e.g. `"macOS theme detection"`).
        needed_for: &'static str,
    },

    /// The current platform is not supported.
    PlatformUnsupported {
        /// Platform identifier, `std::env::consts::OS` (e.g. `"freebsd"`).
        platform: &'static str,
    },

    /// A preset name was not found in the bundled set.
    UnknownPreset {
        /// The requested preset name.
        name: String,
        /// Available preset names: empty where the platform has no OS
        /// generations to choose between (`from_system_with_preset` on Linux,
        /// BSD and other platforms without a generation table).
        known: &'static [&'static str],
    },

    /// Theme-change watching is not available: no backend for this desktop
    /// environment, or the platform's feature is disabled.
    WatchUnavailable {
        /// Why watching is unavailable.
        reason: &'static str,
    },

    /// The theme has neither a light nor a dark variant.
    ///
    /// Returned by [`Theme::pick_variant()`](crate::Theme::pick_variant) and
    /// [`Theme::into_variant()`](crate::Theme::into_variant) when the theme
    /// has neither a light nor a dark variant set.
    NoVariant {
        /// The color mode that was requested.
        mode: crate::theme::ColorMode,
    },

    /// TOML parsing error. (Serialization errors from `Theme::to_toml` are
    /// `ReaderFailed` with reader `"toml-serializer"`.)
    Toml(toml::de::Error),

    /// A theme file could not be read.
    Io {
        /// The file that could not be read.
        path: std::path::PathBuf,
        /// The underlying I/O error.
        source: std::io::Error,
    },

    /// Theme resolution found missing fields that could not be inherited.
    ///
    /// Each path, here and in [`RangeViolation::path`], names the key a
    /// theme author writes in TOML: `button.min_height_px`,
    /// `button.border.padding_left_px`, `defaults.icon_sizes.toolbar_px`.
    /// A path from a whole theme ([`Theme::resolve`](crate::Theme::resolve),
    /// [`Theme::resolve_with`](crate::Theme::resolve_with),
    /// [`SystemTheme::from_system`](crate::SystemTheme::from_system),
    /// [`SystemTheme::with_overlay`](crate::SystemTheme::with_overlay))
    /// starts with the table of the variant that failed, `light.` or
    /// `dark.`, except a `layout.*` key and [`Error::ResolutionInvalid`]'s
    /// `context.font_dpi`, which no variant holds; a
    /// [`ThemeMode`](crate::theme::ThemeMode) resolved alone has no variant
    /// table, so its paths start below it.
    ///
    /// A font size is one field with two keys, `size_pt` and `size_px` (a
    /// text-scale line height likewise, `line_height_pt` and
    /// `line_height_px`): an out-of-range one is named by the key in the
    /// unit its value carries, under the table the value lands in (a
    /// `button.font` that inherits a `defaults.font` in points is
    /// `button.font.size_pt`), a missing one by the field, `size`
    /// (`line_height`).
    ResolutionIncomplete {
        /// Dot-separated TOML paths of fields still `None` after resolution.
        missing: Vec<String>,
    },

    /// Theme resolution found numeric values outside allowed ranges. Each
    /// violation's path is a TOML path, as [`Error::ResolutionIncomplete`]
    /// describes, except `context.font_dpi`: the
    /// [`ResolutionContext::font_dpi`](crate::ResolutionContext::font_dpi)
    /// the resolution was given, which no theme states. A DPI that is not
    /// finite and positive is that one violation, and no field is checked.
    ResolutionInvalid {
        /// One entry per out-of-range property.
        errors: Vec<RangeViolation>,
    },

    /// A platform reader failed with a platform-specific error.
    ReaderFailed {
        /// Reader name (e.g. `"windows"`, `"icon-theme"`, `"kde-watcher"`).
        reader: &'static str,
        /// The underlying error.
        source: Box<dyn std::error::Error + Send + Sync>,
    },
}

impl Error {
    /// Returns the coarse [`ErrorKind`] for this error.
    ///
    /// Useful for broad dispatch (e.g. "is this a platform problem or a
    /// parse problem?") without matching every variant.
    #[must_use]
    pub fn kind(&self) -> ErrorKind {
        match self {
            Error::FeatureDisabled { .. } => ErrorKind::Platform,
            Error::PlatformUnsupported { .. } => ErrorKind::Platform,
            Error::WatchUnavailable { .. } => ErrorKind::Platform,
            Error::NoVariant { .. } => ErrorKind::Resolution,
            Error::ReaderFailed { .. } => ErrorKind::Platform,
            Error::UnknownPreset { .. } => ErrorKind::Parse,
            Error::Toml(_) => ErrorKind::Parse,
            Error::Io { .. } => ErrorKind::Io,
            Error::ResolutionIncomplete { .. } => ErrorKind::Resolution,
            Error::ResolutionInvalid { .. } => ErrorKind::Resolution,
        }
    }
}

impl Error {
    /// This error with each path it names prefixed by the table of the
    /// variant that failed: `light.` or `dark.`. Errors that name no path
    /// are returned unchanged, and so is `context.font_dpi`, which no
    /// variant states. The theme-wide checks (`check_font_dpi`,
    /// `check_layout`) belong before the variants resolve, as both callers
    /// run them, so a `layout.*` path never reaches here.
    pub(crate) fn in_variant(self, mode: crate::theme::ColorMode) -> Self {
        let table = match mode {
            crate::theme::ColorMode::Light => "light",
            crate::theme::ColorMode::Dark => "dark",
        };
        match self {
            Error::ResolutionIncomplete { missing } => Error::ResolutionIncomplete {
                missing: missing
                    .into_iter()
                    .map(|path| format!("{table}.{path}"))
                    .collect(),
            },
            Error::ResolutionInvalid { errors } => Error::ResolutionInvalid {
                errors: errors
                    .into_iter()
                    .map(|rv| {
                        if rv.path.starts_with("context.") {
                            rv
                        } else {
                            RangeViolation {
                                path: format!("{table}.{}", rv.path),
                                ..rv
                            }
                        }
                    })
                    .collect(),
            },
            other => other,
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::FeatureDisabled { name, needed_for } => {
                write!(f, "feature \"{name}\" is required for {needed_for}")
            }
            Error::PlatformUnsupported { platform } => {
                write!(f, "platform not supported: {platform}")
            }
            Error::UnknownPreset { name, known: [] } => {
                write!(
                    f,
                    "unknown preset \"{name}\": this platform has no OS generations to choose between"
                )
            }
            Error::UnknownPreset { name, known } => {
                write!(
                    f,
                    "unknown preset \"{name}\"; available: {}",
                    known.join(", ")
                )
            }
            Error::WatchUnavailable { reason } => {
                write!(f, "theme watching unavailable: {reason}")
            }
            Error::NoVariant { mode } => {
                write!(
                    f,
                    "theme defines neither a light nor a dark variant (requested {mode:?})"
                )
            }
            Error::Toml(err) => write!(f, "TOML error: {err}"),
            Error::Io { path, source } => {
                write!(f, "cannot read theme file `{}`: {source}", path.display())
            }
            Error::ResolutionIncomplete { missing } => {
                write!(
                    f,
                    "theme resolution failed: {} missing field(s):",
                    missing.len()
                )?;

                // Group fields by category, preserving insertion order within each group.
                let categories: &[&str] = &["root defaults", "text scale", "widget fields"];
                for &cat in categories {
                    let fields: Vec<&str> = missing
                        .iter()
                        .filter(|field| field_category(field) == cat)
                        .map(|s| s.as_str())
                        .collect();
                    if fields.is_empty() {
                        continue;
                    }
                    write!(f, "\n  [{cat}]")?;
                    for field in &fields {
                        write!(f, "\n    - {field}")?;
                    }
                }

                // Hint when root defaults are missing (the most common user mistake).
                let has_root = missing
                    .iter()
                    .any(|field| field_category(field) == "root defaults");
                if has_root {
                    write!(
                        f,
                        "\n  hint: root defaults drive widget inheritance; \
                         consider using Theme::preset(name) and then Theme::merge() to inherit from a complete preset"
                    )?;
                }

                Ok(())
            }
            Error::ResolutionInvalid { errors } => {
                write!(
                    f,
                    "theme resolution failed: {} range violation(s):",
                    errors.len()
                )?;
                for violation in errors {
                    write!(f, "\n  - {violation}")?;
                }
                Ok(())
            }
            Error::ReaderFailed { reader, source } => {
                write!(f, "{reader} reader failed: {source}")
            }
        }
    }
}

/// Categorize a field path into a human-readable group name. A leading
/// variant table (`light.`, `dark.`) does not count.
fn field_category(field: &str) -> &'static str {
    let field = field
        .strip_prefix("light.")
        .or_else(|| field.strip_prefix("dark."))
        .unwrap_or(field);
    match field.split('.').next() {
        Some("defaults") => "root defaults",
        Some("text_scale") => "text scale",
        _ => "widget fields",
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Error::Toml(err) => Some(err),
            Error::Io { source, .. } => Some(source),
            Error::ReaderFailed { source, .. } => Some(source.as_ref()),
            Error::FeatureDisabled { .. }
            | Error::PlatformUnsupported { .. }
            | Error::UnknownPreset { .. }
            | Error::WatchUnavailable { .. }
            | Error::NoVariant { .. }
            | Error::ResolutionIncomplete { .. }
            | Error::ResolutionInvalid { .. } => None,
        }
    }
}

impl From<toml::de::Error> for Error {
    fn from(err: toml::de::Error) -> Self {
        Error::Toml(err)
    }
}

impl From<toml::ser::Error> for Error {
    fn from(err: toml::ser::Error) -> Self {
        // Serialization errors are stringified because Error::Toml wraps only
        // toml::de::Error. This preserves the existing From<toml::ser::Error>
        // conversion used by presets::to_toml().
        Error::ReaderFailed {
            reader: reader_names::TOML_SERIALIZER,
            source: Box::new(err),
        }
    }
}

/// Declares the reader-name consts and, for the test, the list of them all.
macro_rules! reader_names {
    ($($(#[$meta:meta])* $name:ident = $value:literal;)*) => {
        $($(#[$meta])* pub(crate) const $name: &str = $value;)*

        /// Every name declared above, for the test that keeps them one style.
        #[cfg(test)]
        pub(crate) const ALL: &[&str] = &[$($value),*];
    };
}

/// The `reader` name of every [`Error::ReaderFailed`], lowercase kebab-case.
pub(crate) mod reader_names {
    reader_names! {
        #[cfg_attr(not(all(target_os = "windows", feature = "windows")), allow(dead_code))]
        WINDOWS = "windows";
        #[cfg_attr(not(all(target_os = "macos", feature = "macos")), allow(dead_code))]
        MACOS = "macos";
        ICON_THEME = "icon-theme";
        TOML_SERIALIZER = "toml-serializer";
        PRESET_CACHE = "preset-cache";
        #[cfg_attr(not(feature = "svg-rasterize"), allow(dead_code))]
        SVG_RASTERIZER = "svg-rasterizer";
        #[cfg_attr(
            not(all(feature = "watch", feature = "kde", target_os = "linux")),
            allow(dead_code)
        )]
        KDE_WATCHER = "kde-watcher";
        #[cfg_attr(
            not(all(feature = "watch", feature = "portal", target_os = "linux")),
            allow(dead_code)
        )]
        GNOME_WATCHER = "gnome-watcher";
        #[cfg_attr(
            not(all(feature = "watch", feature = "windows", target_os = "windows")),
            allow(dead_code)
        )]
        WINDOWS_WATCHER = "windows-watcher";
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;

    #[test]
    fn reader_names_are_lowercase_kebab_case_and_unique() {
        for name in reader_names::ALL {
            assert!(
                !name.is_empty()
                    && !name.starts_with('-')
                    && !name.ends_with('-')
                    && name
                        .chars()
                        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-'),
                "{name:?} is not lowercase kebab-case"
            );
        }
        let mut sorted = reader_names::ALL.to_vec();
        sorted.sort_unstable();
        assert!(sorted.windows(2).all(|w| w[0] != w[1]), "duplicate name");
    }

    // === ErrorKind dispatch tests ===

    #[test]
    fn kind_platform_for_feature_disabled() {
        let err = Error::FeatureDisabled {
            name: "kde",
            needed_for: "KDE theme detection",
        };
        assert_eq!(err.kind(), ErrorKind::Platform);
    }

    #[test]
    fn kind_platform_for_platform_unsupported() {
        let err = Error::PlatformUnsupported { platform: "wasm" };
        assert_eq!(err.kind(), ErrorKind::Platform);
    }

    #[test]
    fn kind_platform_for_watch_unavailable() {
        let err = Error::WatchUnavailable {
            reason: "notify crate not compiled",
        };
        assert_eq!(err.kind(), ErrorKind::Platform);
    }

    #[test]
    fn kind_platform_for_reader_failed() {
        let err = Error::ReaderFailed {
            reader: reader_names::ICON_THEME,
            source: Box::new(std::io::Error::other("dbus down")),
        };
        assert_eq!(err.kind(), ErrorKind::Platform);
    }

    #[test]
    fn kind_parse_for_unknown_preset() {
        let err = Error::UnknownPreset {
            name: "foobar".into(),
            known: &["adwaita", "kde-breeze"],
        };
        assert_eq!(err.kind(), ErrorKind::Parse);
    }

    #[test]
    fn kind_parse_for_toml() {
        let toml_err: Result<toml::Value, toml::de::Error> = toml::from_str("=invalid");
        let err = Error::Toml(toml_err.unwrap_err());
        assert_eq!(err.kind(), ErrorKind::Parse);
    }

    #[test]
    fn kind_resolution_for_incomplete() {
        let err = Error::ResolutionIncomplete {
            missing: vec!["defaults.accent_color".into()],
        };
        assert_eq!(err.kind(), ErrorKind::Resolution);
    }

    #[test]
    fn kind_resolution_for_invalid() {
        let err = Error::ResolutionInvalid {
            errors: vec![RangeViolation {
                path: "button.min_width_px".into(),
                value: -5.0,
                min: Some(0.0),
                max: None,
            }],
        };
        assert_eq!(err.kind(), ErrorKind::Resolution);
    }

    #[test]
    fn kind_io_for_io() {
        let err = Error::Io {
            path: "theme.toml".into(),
            source: std::io::Error::other("disk failure"),
        };
        assert_eq!(err.kind(), ErrorKind::Io);
    }

    // === Send + Sync ===

    #[test]
    fn error_is_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<Error>();
    }

    // === Display tests ===

    #[test]
    fn display_feature_disabled_includes_name_and_needed_for() {
        let err = Error::FeatureDisabled {
            name: "kde",
            needed_for: "KDE theme detection",
        };
        let msg = err.to_string();
        assert!(msg.contains("kde"), "got: {msg}");
        assert!(msg.contains("KDE theme detection"), "got: {msg}");
    }

    #[test]
    fn display_resolution_incomplete_categorizes_fields() {
        let err = Error::ResolutionIncomplete {
            missing: vec![
                "defaults.accent_color".into(),
                "button.font.color".into(),
                "window.border.corner_radius_px".into(),
            ],
        };
        let msg = err.to_string();
        assert!(msg.contains("3 missing field(s)"), "got: {msg}");
        assert!(msg.contains("[root defaults]"), "got: {msg}");
        assert!(msg.contains("defaults.accent_color"), "got: {msg}");
        assert!(msg.contains("[widget fields]"), "got: {msg}");
        assert!(msg.contains("button.font.color"), "got: {msg}");
        assert!(msg.contains("window.border.corner_radius_px"), "got: {msg}");
        assert!(msg.contains("hint:"), "got: {msg}");
        assert!(msg.contains("preset"), "got: {msg}");
    }

    #[test]
    fn display_resolution_incomplete_no_hint_without_root_defaults() {
        let err = Error::ResolutionIncomplete {
            missing: vec!["button.font.color".into()],
        };
        let msg = err.to_string();
        assert!(msg.contains("[widget fields]"), "got: {msg}");
        assert!(!msg.contains("hint:"), "got: {msg}");
    }

    #[test]
    fn display_no_variant_says_both_variants_are_missing() {
        let err = Error::NoVariant {
            mode: crate::theme::ColorMode::Dark,
        };
        assert_eq!(
            err.to_string(),
            "theme defines neither a light nor a dark variant (requested Dark)"
        );
    }

    #[test]
    fn display_resolution_incomplete_groups_text_scale() {
        let err = Error::ResolutionIncomplete {
            missing: vec!["text_scale.caption".into(), "defaults.font.family".into()],
        };
        let msg = err.to_string();
        assert!(msg.contains("[text scale]"), "got: {msg}");
        assert!(msg.contains("[root defaults]"), "got: {msg}");
    }

    #[test]
    fn in_variant_prefixes_a_variant_path_and_not_the_context() {
        let violation = |path: &str| RangeViolation {
            path: path.into(),
            value: 0.0,
            min: Some(f64::MIN_POSITIVE),
            max: None,
        };
        let err = Error::ResolutionInvalid {
            errors: vec![
                violation("context.font_dpi"),
                violation("button.min_height_px"),
            ],
        }
        .in_variant(crate::theme::ColorMode::Dark);
        let Error::ResolutionInvalid { errors } = err else {
            panic!("expected ResolutionInvalid, got: {err:?}");
        };
        let paths: Vec<&str> = errors.iter().map(|rv| rv.path.as_str()).collect();
        assert_eq!(paths, ["context.font_dpi", "dark.button.min_height_px"]);
    }

    #[test]
    fn display_resolution_incomplete_groups_variant_prefixed_paths() {
        let err = Error::ResolutionIncomplete {
            missing: vec![
                "dark.text_scale.caption".into(),
                "light.defaults.icon_sizes.toolbar_px".into(),
                "light.button.min_height_px".into(),
            ],
        };
        let msg = err.to_string();
        assert!(
            msg.contains("[text scale]\n    - dark.text_scale.caption"),
            "got: {msg}"
        );
        assert!(
            msg.contains("[root defaults]\n    - light.defaults.icon_sizes.toolbar_px"),
            "got: {msg}"
        );
        assert!(
            msg.contains("[widget fields]\n    - light.button.min_height_px"),
            "got: {msg}"
        );
        assert!(msg.contains("hint:"), "got: {msg}");
    }

    #[test]
    fn display_resolution_incomplete_widget_category() {
        // icon_set is no longer validated per-variant; test a widget field instead
        let err = Error::ResolutionIncomplete {
            missing: vec!["button.font.color".into()],
        };
        let msg = err.to_string();
        assert!(msg.contains("[widget fields]"), "got: {msg}");
        assert!(!msg.contains("hint:"), "got: {msg}");
    }

    #[test]
    fn display_resolution_invalid_lists_violations() {
        let err = Error::ResolutionInvalid {
            errors: vec![
                RangeViolation {
                    path: "button.min_width_px".into(),
                    value: -5.0,
                    min: Some(0.0),
                    max: None,
                },
                RangeViolation {
                    path: "slider.track_height_px".into(),
                    value: 200.0,
                    min: Some(1.0),
                    max: Some(100.0),
                },
            ],
        };
        let msg = err.to_string();
        assert!(msg.contains("2 range violation(s)"), "got: {msg}");
        assert!(msg.contains("button.min_width_px"), "got: {msg}");
        assert!(msg.contains("-5"), "got: {msg}");
        assert!(msg.contains("slider.track_height_px"), "got: {msg}");
        assert!(msg.contains("200"), "got: {msg}");
    }

    #[test]
    fn display_unknown_preset_shows_name_and_available() {
        let err = Error::UnknownPreset {
            name: "foobar".into(),
            known: &["adwaita", "kde-breeze"],
        };
        let msg = err.to_string();
        assert!(msg.contains("foobar"), "got: {msg}");
        assert!(msg.contains("adwaita"), "got: {msg}");
        assert!(msg.contains("kde-breeze"), "got: {msg}");
    }

    #[test]
    fn display_unknown_preset_without_presets_says_so() {
        let err = Error::UnknownPreset {
            name: "adwaita".into(),
            known: &[],
        };
        assert_eq!(
            err.to_string(),
            "unknown preset \"adwaita\": this platform has no OS generations to choose between"
        );
    }

    // === source() tests ===

    #[test]
    fn source_some_for_io() {
        let err = Error::Io {
            path: "theme.toml".into(),
            source: std::io::Error::other("disk failure"),
        };
        assert!(
            std::error::Error::source(&err).is_some(),
            "Io should return Some from source()"
        );
    }

    #[test]
    fn source_some_for_reader_failed() {
        let err = Error::ReaderFailed {
            reader: reader_names::ICON_THEME,
            source: Box::new(std::io::Error::other("dbus down")),
        };
        let source = std::error::Error::source(&err);
        assert!(
            source.is_some(),
            "ReaderFailed should return Some from source()"
        );
        assert!(source.unwrap().to_string().contains("dbus down"));
    }

    #[test]
    fn source_some_for_toml() {
        let toml_err: Result<toml::Value, toml::de::Error> = toml::from_str("=invalid");
        let err = Error::Toml(toml_err.unwrap_err());
        assert!(
            std::error::Error::source(&err).is_some(),
            "Toml should return Some from source()"
        );
    }

    #[test]
    fn source_none_for_feature_disabled() {
        let err = Error::FeatureDisabled {
            name: "kde",
            needed_for: "detection",
        };
        assert!(std::error::Error::source(&err).is_none());
    }

    #[test]
    fn source_none_for_platform_unsupported() {
        let err = Error::PlatformUnsupported { platform: "wasm" };
        assert!(std::error::Error::source(&err).is_none());
    }

    #[test]
    fn source_none_for_watch_unavailable() {
        let err = Error::WatchUnavailable {
            reason: "not compiled",
        };
        assert!(std::error::Error::source(&err).is_none());
    }

    #[test]
    fn source_none_for_unknown_preset() {
        let err = Error::UnknownPreset {
            name: "x".into(),
            known: &[],
        };
        assert!(std::error::Error::source(&err).is_none());
    }

    #[test]
    fn source_none_for_resolution_incomplete() {
        let err = Error::ResolutionIncomplete {
            missing: vec!["a".into()],
        };
        assert!(std::error::Error::source(&err).is_none());
    }

    #[test]
    fn source_none_for_resolution_invalid() {
        let err = Error::ResolutionInvalid {
            errors: vec![RangeViolation {
                path: "x".into(),
                value: 0.0,
                min: None,
                max: None,
            }],
        };
        assert!(std::error::Error::source(&err).is_none());
    }

    // === From impls ===

    #[test]
    fn from_toml_de_error_produces_toml_variant() {
        let toml_err: Result<toml::Value, toml::de::Error> = toml::from_str("=invalid");
        let err: Error = toml_err.unwrap_err().into();
        match &err {
            Error::Toml(_) => {} // correct
            other => panic!("expected Toml variant, got: {other:?}"),
        }
    }

    #[test]
    fn display_io_names_path_and_source() {
        let err = Error::Io {
            path: "/themes/my-theme.toml".into(),
            source: std::io::Error::new(std::io::ErrorKind::NotFound, "missing file"),
        };
        assert_eq!(
            err.to_string(),
            "cannot read theme file `/themes/my-theme.toml`: missing file"
        );
    }

    // === Derive checks ===

    #[test]
    fn error_kind_derives() {
        // Debug
        let k = ErrorKind::Platform;
        let dbg = format!("{k:?}");
        assert!(dbg.contains("Platform"));

        // Clone + Copy
        let k2 = k;
        let k3 = k2;
        assert_eq!(k, k3);

        // PartialEq + Eq
        assert_eq!(ErrorKind::Parse, ErrorKind::Parse);
        assert_ne!(ErrorKind::Io, ErrorKind::Resolution);
    }

    #[test]
    fn range_violation_derives_debug_clone() {
        let v = RangeViolation {
            path: "x".into(),
            value: 1.0,
            min: Some(0.0),
            max: Some(10.0),
        };
        // Debug
        let dbg = format!("{v:?}");
        assert!(dbg.contains("RangeViolation"));

        // Clone
        let v2 = v.clone();
        assert_eq!(v2.path, "x");
        assert!((v2.value - 1.0).abs() < f64::EPSILON);
    }

    // === RangeViolation Display ===

    #[test]
    fn range_violation_display_both_bounds() {
        let v = RangeViolation {
            path: "button.min_width_px".into(),
            value: -5.0,
            min: Some(0.0),
            max: Some(1000.0),
        };
        let msg = v.to_string();
        assert!(msg.contains("button.min_width_px"), "got: {msg}");
        assert!(msg.contains("0..=1000"), "got: {msg}");
        assert!(msg.contains("-5"), "got: {msg}");
    }

    #[test]
    fn range_violation_display_open_max() {
        let v = RangeViolation {
            path: "x".into(),
            value: -1.0,
            min: Some(0.0),
            max: None,
        };
        let msg = v.to_string();
        assert!(msg.contains("0..=inf"), "got: {msg}");
    }

    #[test]
    fn range_violation_display_open_min() {
        let v = RangeViolation {
            path: "x".into(),
            value: 999.0,
            min: None,
            max: Some(100.0),
        };
        let msg = v.to_string();
        assert!(msg.contains("-inf..=100"), "got: {msg}");
    }
}