Skip to main content

native_theme/
error.rs

1// Error enum with Display, std::error::Error, and From conversions
2//
3// Option F: flat 10-variant Error + ErrorKind + RangeViolation
4
5use std::fmt;
6
7/// A range-violation error for a single theme property.
8///
9/// Produced during validation when a resolved numeric property falls outside
10/// its allowed range.
11#[derive(Debug, Clone)]
12pub struct RangeViolation {
13    /// Dot-separated TOML path of the property (e.g.
14    /// `"light.button.min_width_px"`), as
15    /// [`Error::ResolutionIncomplete`] describes.
16    pub path: String,
17    /// The actual value found.
18    pub value: f64,
19    /// Lower bound (inclusive), or `None` for open-ended.
20    pub min: Option<f64>,
21    /// Upper bound (inclusive), or `None` for open-ended.
22    pub max: Option<f64>,
23}
24
25impl fmt::Display for RangeViolation {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        let lo = self
28            .min
29            .map_or_else(|| "-inf".to_owned(), |v| v.to_string());
30        let hi = self.max.map_or_else(|| "inf".to_owned(), |v| v.to_string());
31        write!(
32            f,
33            "{} must be {}..={}, got {}",
34            self.path, lo, hi, self.value
35        )
36    }
37}
38
39/// Coarse error category returned by [`Error::kind()`].
40///
41/// Follows the `std::io::ErrorKind` precedent: callers can match on the kind
42/// for broad dispatch without inspecting each variant.
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44#[non_exhaustive]
45pub enum ErrorKind {
46    /// Platform feature not available or not supported.
47    Platform,
48    /// Parsing or lookup failure (TOML, preset name).
49    Parse,
50    /// Theme resolution failure (missing fields, range violations).
51    Resolution,
52    /// File I/O error.
53    Io,
54}
55
56/// Errors that can occur when reading or processing theme data.
57///
58/// This is a flat enum with 10 variants. Use [`Error::kind()`] for coarse
59/// dispatch without matching every variant.
60#[derive(Debug)]
61#[non_exhaustive]
62pub enum Error {
63    /// The platform has a theme reader, but the Cargo feature that compiles it
64    /// is not enabled (`macos` on macOS, `windows` on Windows).
65    FeatureDisabled {
66        /// Feature name (`"macos"` or `"windows"`).
67        name: &'static str,
68        /// What the feature is needed for (e.g. `"macOS theme detection"`).
69        needed_for: &'static str,
70    },
71
72    /// The current platform is not supported.
73    PlatformUnsupported {
74        /// Platform identifier, `std::env::consts::OS` (e.g. `"freebsd"`).
75        platform: &'static str,
76    },
77
78    /// A preset name was not found in the bundled set.
79    UnknownPreset {
80        /// The requested preset name.
81        name: String,
82        /// Available preset names: empty where the platform has no OS
83        /// generations to choose between (`from_system_with_preset` on Linux,
84        /// BSD and other platforms without a generation table).
85        known: &'static [&'static str],
86    },
87
88    /// Theme-change watching is not available: no backend for this desktop
89    /// environment, or the platform's feature is disabled.
90    WatchUnavailable {
91        /// Why watching is unavailable.
92        reason: &'static str,
93    },
94
95    /// The theme has neither a light nor a dark variant.
96    ///
97    /// Returned by [`Theme::pick_variant()`](crate::Theme::pick_variant) and
98    /// [`Theme::into_variant()`](crate::Theme::into_variant) when the theme
99    /// has neither a light nor a dark variant set.
100    NoVariant {
101        /// The color mode that was requested.
102        mode: crate::theme::ColorMode,
103    },
104
105    /// TOML parsing error. (Serialization errors from `Theme::to_toml` are
106    /// `ReaderFailed` with reader `"toml-serializer"`.)
107    Toml(toml::de::Error),
108
109    /// A theme file could not be read.
110    Io {
111        /// The file that could not be read.
112        path: std::path::PathBuf,
113        /// The underlying I/O error.
114        source: std::io::Error,
115    },
116
117    /// Theme resolution found missing fields that could not be inherited.
118    ///
119    /// Each path, here and in [`RangeViolation::path`], names the key a
120    /// theme author writes in TOML: `button.min_height_px`,
121    /// `button.border.padding_left_px`, `defaults.icon_sizes.toolbar_px`.
122    /// A path from a whole theme ([`Theme::resolve`](crate::Theme::resolve),
123    /// [`Theme::resolve_with`](crate::Theme::resolve_with),
124    /// [`SystemTheme::from_system`](crate::SystemTheme::from_system),
125    /// [`SystemTheme::with_overlay`](crate::SystemTheme::with_overlay))
126    /// starts with the table of the variant that failed, `light.` or
127    /// `dark.`, except a `layout.*` key and [`Error::ResolutionInvalid`]'s
128    /// `context.font_dpi`, which no variant holds; a
129    /// [`ThemeMode`](crate::theme::ThemeMode) resolved alone has no variant
130    /// table, so its paths start below it.
131    ///
132    /// A font size is one field with two keys, `size_pt` and `size_px` (a
133    /// text-scale line height likewise, `line_height_pt` and
134    /// `line_height_px`): an out-of-range one is named by the key in the
135    /// unit its value carries, under the table the value lands in (a
136    /// `button.font` that inherits a `defaults.font` in points is
137    /// `button.font.size_pt`), a missing one by the field, `size`
138    /// (`line_height`).
139    ResolutionIncomplete {
140        /// Dot-separated TOML paths of fields still `None` after resolution.
141        missing: Vec<String>,
142    },
143
144    /// Theme resolution found numeric values outside allowed ranges. Each
145    /// violation's path is a TOML path, as [`Error::ResolutionIncomplete`]
146    /// describes, except `context.font_dpi`: the
147    /// [`ResolutionContext::font_dpi`](crate::ResolutionContext::font_dpi)
148    /// the resolution was given, which no theme states. A DPI that is not
149    /// finite and positive is that one violation, and no field is checked.
150    ResolutionInvalid {
151        /// One entry per out-of-range property.
152        errors: Vec<RangeViolation>,
153    },
154
155    /// A platform reader failed with a platform-specific error.
156    ReaderFailed {
157        /// Reader name (e.g. `"windows"`, `"icon-theme"`, `"kde-watcher"`).
158        reader: &'static str,
159        /// The underlying error.
160        source: Box<dyn std::error::Error + Send + Sync>,
161    },
162}
163
164impl Error {
165    /// Returns the coarse [`ErrorKind`] for this error.
166    ///
167    /// Useful for broad dispatch (e.g. "is this a platform problem or a
168    /// parse problem?") without matching every variant.
169    #[must_use]
170    pub fn kind(&self) -> ErrorKind {
171        match self {
172            Error::FeatureDisabled { .. } => ErrorKind::Platform,
173            Error::PlatformUnsupported { .. } => ErrorKind::Platform,
174            Error::WatchUnavailable { .. } => ErrorKind::Platform,
175            Error::NoVariant { .. } => ErrorKind::Resolution,
176            Error::ReaderFailed { .. } => ErrorKind::Platform,
177            Error::UnknownPreset { .. } => ErrorKind::Parse,
178            Error::Toml(_) => ErrorKind::Parse,
179            Error::Io { .. } => ErrorKind::Io,
180            Error::ResolutionIncomplete { .. } => ErrorKind::Resolution,
181            Error::ResolutionInvalid { .. } => ErrorKind::Resolution,
182        }
183    }
184}
185
186impl Error {
187    /// This error with each path it names prefixed by the table of the
188    /// variant that failed: `light.` or `dark.`. Errors that name no path
189    /// are returned unchanged, and so is `context.font_dpi`, which no
190    /// variant states. The theme-wide checks (`check_font_dpi`,
191    /// `check_layout`) belong before the variants resolve, as both callers
192    /// run them, so a `layout.*` path never reaches here.
193    pub(crate) fn in_variant(self, mode: crate::theme::ColorMode) -> Self {
194        let table = match mode {
195            crate::theme::ColorMode::Light => "light",
196            crate::theme::ColorMode::Dark => "dark",
197        };
198        match self {
199            Error::ResolutionIncomplete { missing } => Error::ResolutionIncomplete {
200                missing: missing
201                    .into_iter()
202                    .map(|path| format!("{table}.{path}"))
203                    .collect(),
204            },
205            Error::ResolutionInvalid { errors } => Error::ResolutionInvalid {
206                errors: errors
207                    .into_iter()
208                    .map(|rv| {
209                        if rv.path.starts_with("context.") {
210                            rv
211                        } else {
212                            RangeViolation {
213                                path: format!("{table}.{}", rv.path),
214                                ..rv
215                            }
216                        }
217                    })
218                    .collect(),
219            },
220            other => other,
221        }
222    }
223}
224
225impl fmt::Display for Error {
226    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
227        match self {
228            Error::FeatureDisabled { name, needed_for } => {
229                write!(f, "feature \"{name}\" is required for {needed_for}")
230            }
231            Error::PlatformUnsupported { platform } => {
232                write!(f, "platform not supported: {platform}")
233            }
234            Error::UnknownPreset { name, known: [] } => {
235                write!(
236                    f,
237                    "unknown preset \"{name}\": this platform has no OS generations to choose between"
238                )
239            }
240            Error::UnknownPreset { name, known } => {
241                write!(
242                    f,
243                    "unknown preset \"{name}\"; available: {}",
244                    known.join(", ")
245                )
246            }
247            Error::WatchUnavailable { reason } => {
248                write!(f, "theme watching unavailable: {reason}")
249            }
250            Error::NoVariant { mode } => {
251                write!(
252                    f,
253                    "theme defines neither a light nor a dark variant (requested {mode:?})"
254                )
255            }
256            Error::Toml(err) => write!(f, "TOML error: {err}"),
257            Error::Io { path, source } => {
258                write!(f, "cannot read theme file `{}`: {source}", path.display())
259            }
260            Error::ResolutionIncomplete { missing } => {
261                write!(
262                    f,
263                    "theme resolution failed: {} missing field(s):",
264                    missing.len()
265                )?;
266
267                // Group fields by category, preserving insertion order within each group.
268                let categories: &[&str] = &["root defaults", "text scale", "widget fields"];
269                for &cat in categories {
270                    let fields: Vec<&str> = missing
271                        .iter()
272                        .filter(|field| field_category(field) == cat)
273                        .map(|s| s.as_str())
274                        .collect();
275                    if fields.is_empty() {
276                        continue;
277                    }
278                    write!(f, "\n  [{cat}]")?;
279                    for field in &fields {
280                        write!(f, "\n    - {field}")?;
281                    }
282                }
283
284                // Hint when root defaults are missing (the most common user mistake).
285                let has_root = missing
286                    .iter()
287                    .any(|field| field_category(field) == "root defaults");
288                if has_root {
289                    write!(
290                        f,
291                        "\n  hint: root defaults drive widget inheritance; \
292                         consider using Theme::preset(name) and then Theme::merge() to inherit from a complete preset"
293                    )?;
294                }
295
296                Ok(())
297            }
298            Error::ResolutionInvalid { errors } => {
299                write!(
300                    f,
301                    "theme resolution failed: {} range violation(s):",
302                    errors.len()
303                )?;
304                for violation in errors {
305                    write!(f, "\n  - {violation}")?;
306                }
307                Ok(())
308            }
309            Error::ReaderFailed { reader, source } => {
310                write!(f, "{reader} reader failed: {source}")
311            }
312        }
313    }
314}
315
316/// Categorize a field path into a human-readable group name. A leading
317/// variant table (`light.`, `dark.`) does not count.
318fn field_category(field: &str) -> &'static str {
319    let field = field
320        .strip_prefix("light.")
321        .or_else(|| field.strip_prefix("dark."))
322        .unwrap_or(field);
323    match field.split('.').next() {
324        Some("defaults") => "root defaults",
325        Some("text_scale") => "text scale",
326        _ => "widget fields",
327    }
328}
329
330impl std::error::Error for Error {
331    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
332        match self {
333            Error::Toml(err) => Some(err),
334            Error::Io { source, .. } => Some(source),
335            Error::ReaderFailed { source, .. } => Some(source.as_ref()),
336            Error::FeatureDisabled { .. }
337            | Error::PlatformUnsupported { .. }
338            | Error::UnknownPreset { .. }
339            | Error::WatchUnavailable { .. }
340            | Error::NoVariant { .. }
341            | Error::ResolutionIncomplete { .. }
342            | Error::ResolutionInvalid { .. } => None,
343        }
344    }
345}
346
347impl From<toml::de::Error> for Error {
348    fn from(err: toml::de::Error) -> Self {
349        Error::Toml(err)
350    }
351}
352
353impl From<toml::ser::Error> for Error {
354    fn from(err: toml::ser::Error) -> Self {
355        // Serialization errors are stringified because Error::Toml wraps only
356        // toml::de::Error. This preserves the existing From<toml::ser::Error>
357        // conversion used by presets::to_toml().
358        Error::ReaderFailed {
359            reader: reader_names::TOML_SERIALIZER,
360            source: Box::new(err),
361        }
362    }
363}
364
365/// Declares the reader-name consts and, for the test, the list of them all.
366macro_rules! reader_names {
367    ($($(#[$meta:meta])* $name:ident = $value:literal;)*) => {
368        $($(#[$meta])* pub(crate) const $name: &str = $value;)*
369
370        /// Every name declared above, for the test that keeps them one style.
371        #[cfg(test)]
372        pub(crate) const ALL: &[&str] = &[$($value),*];
373    };
374}
375
376/// The `reader` name of every [`Error::ReaderFailed`], lowercase kebab-case.
377pub(crate) mod reader_names {
378    reader_names! {
379        #[cfg_attr(not(all(target_os = "windows", feature = "windows")), allow(dead_code))]
380        WINDOWS = "windows";
381        #[cfg_attr(not(all(target_os = "macos", feature = "macos")), allow(dead_code))]
382        MACOS = "macos";
383        ICON_THEME = "icon-theme";
384        TOML_SERIALIZER = "toml-serializer";
385        PRESET_CACHE = "preset-cache";
386        #[cfg_attr(not(feature = "svg-rasterize"), allow(dead_code))]
387        SVG_RASTERIZER = "svg-rasterizer";
388        #[cfg_attr(
389            not(all(feature = "watch", feature = "kde", target_os = "linux")),
390            allow(dead_code)
391        )]
392        KDE_WATCHER = "kde-watcher";
393        #[cfg_attr(
394            not(all(feature = "watch", feature = "portal", target_os = "linux")),
395            allow(dead_code)
396        )]
397        GNOME_WATCHER = "gnome-watcher";
398        #[cfg_attr(
399            not(all(feature = "watch", feature = "windows", target_os = "windows")),
400            allow(dead_code)
401        )]
402        WINDOWS_WATCHER = "windows-watcher";
403    }
404}
405
406#[cfg(test)]
407#[allow(clippy::unwrap_used, clippy::expect_used)]
408mod tests {
409    use super::*;
410
411    #[test]
412    fn reader_names_are_lowercase_kebab_case_and_unique() {
413        for name in reader_names::ALL {
414            assert!(
415                !name.is_empty()
416                    && !name.starts_with('-')
417                    && !name.ends_with('-')
418                    && name
419                        .chars()
420                        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-'),
421                "{name:?} is not lowercase kebab-case"
422            );
423        }
424        let mut sorted = reader_names::ALL.to_vec();
425        sorted.sort_unstable();
426        assert!(sorted.windows(2).all(|w| w[0] != w[1]), "duplicate name");
427    }
428
429    // === ErrorKind dispatch tests ===
430
431    #[test]
432    fn kind_platform_for_feature_disabled() {
433        let err = Error::FeatureDisabled {
434            name: "kde",
435            needed_for: "KDE theme detection",
436        };
437        assert_eq!(err.kind(), ErrorKind::Platform);
438    }
439
440    #[test]
441    fn kind_platform_for_platform_unsupported() {
442        let err = Error::PlatformUnsupported { platform: "wasm" };
443        assert_eq!(err.kind(), ErrorKind::Platform);
444    }
445
446    #[test]
447    fn kind_platform_for_watch_unavailable() {
448        let err = Error::WatchUnavailable {
449            reason: "notify crate not compiled",
450        };
451        assert_eq!(err.kind(), ErrorKind::Platform);
452    }
453
454    #[test]
455    fn kind_platform_for_reader_failed() {
456        let err = Error::ReaderFailed {
457            reader: reader_names::ICON_THEME,
458            source: Box::new(std::io::Error::other("dbus down")),
459        };
460        assert_eq!(err.kind(), ErrorKind::Platform);
461    }
462
463    #[test]
464    fn kind_parse_for_unknown_preset() {
465        let err = Error::UnknownPreset {
466            name: "foobar".into(),
467            known: &["adwaita", "kde-breeze"],
468        };
469        assert_eq!(err.kind(), ErrorKind::Parse);
470    }
471
472    #[test]
473    fn kind_parse_for_toml() {
474        let toml_err: Result<toml::Value, toml::de::Error> = toml::from_str("=invalid");
475        let err = Error::Toml(toml_err.unwrap_err());
476        assert_eq!(err.kind(), ErrorKind::Parse);
477    }
478
479    #[test]
480    fn kind_resolution_for_incomplete() {
481        let err = Error::ResolutionIncomplete {
482            missing: vec!["defaults.accent_color".into()],
483        };
484        assert_eq!(err.kind(), ErrorKind::Resolution);
485    }
486
487    #[test]
488    fn kind_resolution_for_invalid() {
489        let err = Error::ResolutionInvalid {
490            errors: vec![RangeViolation {
491                path: "button.min_width_px".into(),
492                value: -5.0,
493                min: Some(0.0),
494                max: None,
495            }],
496        };
497        assert_eq!(err.kind(), ErrorKind::Resolution);
498    }
499
500    #[test]
501    fn kind_io_for_io() {
502        let err = Error::Io {
503            path: "theme.toml".into(),
504            source: std::io::Error::other("disk failure"),
505        };
506        assert_eq!(err.kind(), ErrorKind::Io);
507    }
508
509    // === Send + Sync ===
510
511    #[test]
512    fn error_is_send_sync() {
513        fn assert_send_sync<T: Send + Sync>() {}
514        assert_send_sync::<Error>();
515    }
516
517    // === Display tests ===
518
519    #[test]
520    fn display_feature_disabled_includes_name_and_needed_for() {
521        let err = Error::FeatureDisabled {
522            name: "kde",
523            needed_for: "KDE theme detection",
524        };
525        let msg = err.to_string();
526        assert!(msg.contains("kde"), "got: {msg}");
527        assert!(msg.contains("KDE theme detection"), "got: {msg}");
528    }
529
530    #[test]
531    fn display_resolution_incomplete_categorizes_fields() {
532        let err = Error::ResolutionIncomplete {
533            missing: vec![
534                "defaults.accent_color".into(),
535                "button.font.color".into(),
536                "window.border.corner_radius_px".into(),
537            ],
538        };
539        let msg = err.to_string();
540        assert!(msg.contains("3 missing field(s)"), "got: {msg}");
541        assert!(msg.contains("[root defaults]"), "got: {msg}");
542        assert!(msg.contains("defaults.accent_color"), "got: {msg}");
543        assert!(msg.contains("[widget fields]"), "got: {msg}");
544        assert!(msg.contains("button.font.color"), "got: {msg}");
545        assert!(msg.contains("window.border.corner_radius_px"), "got: {msg}");
546        assert!(msg.contains("hint:"), "got: {msg}");
547        assert!(msg.contains("preset"), "got: {msg}");
548    }
549
550    #[test]
551    fn display_resolution_incomplete_no_hint_without_root_defaults() {
552        let err = Error::ResolutionIncomplete {
553            missing: vec!["button.font.color".into()],
554        };
555        let msg = err.to_string();
556        assert!(msg.contains("[widget fields]"), "got: {msg}");
557        assert!(!msg.contains("hint:"), "got: {msg}");
558    }
559
560    #[test]
561    fn display_no_variant_says_both_variants_are_missing() {
562        let err = Error::NoVariant {
563            mode: crate::theme::ColorMode::Dark,
564        };
565        assert_eq!(
566            err.to_string(),
567            "theme defines neither a light nor a dark variant (requested Dark)"
568        );
569    }
570
571    #[test]
572    fn display_resolution_incomplete_groups_text_scale() {
573        let err = Error::ResolutionIncomplete {
574            missing: vec!["text_scale.caption".into(), "defaults.font.family".into()],
575        };
576        let msg = err.to_string();
577        assert!(msg.contains("[text scale]"), "got: {msg}");
578        assert!(msg.contains("[root defaults]"), "got: {msg}");
579    }
580
581    #[test]
582    fn in_variant_prefixes_a_variant_path_and_not_the_context() {
583        let violation = |path: &str| RangeViolation {
584            path: path.into(),
585            value: 0.0,
586            min: Some(f64::MIN_POSITIVE),
587            max: None,
588        };
589        let err = Error::ResolutionInvalid {
590            errors: vec![
591                violation("context.font_dpi"),
592                violation("button.min_height_px"),
593            ],
594        }
595        .in_variant(crate::theme::ColorMode::Dark);
596        let Error::ResolutionInvalid { errors } = err else {
597            panic!("expected ResolutionInvalid, got: {err:?}");
598        };
599        let paths: Vec<&str> = errors.iter().map(|rv| rv.path.as_str()).collect();
600        assert_eq!(paths, ["context.font_dpi", "dark.button.min_height_px"]);
601    }
602
603    #[test]
604    fn display_resolution_incomplete_groups_variant_prefixed_paths() {
605        let err = Error::ResolutionIncomplete {
606            missing: vec![
607                "dark.text_scale.caption".into(),
608                "light.defaults.icon_sizes.toolbar_px".into(),
609                "light.button.min_height_px".into(),
610            ],
611        };
612        let msg = err.to_string();
613        assert!(
614            msg.contains("[text scale]\n    - dark.text_scale.caption"),
615            "got: {msg}"
616        );
617        assert!(
618            msg.contains("[root defaults]\n    - light.defaults.icon_sizes.toolbar_px"),
619            "got: {msg}"
620        );
621        assert!(
622            msg.contains("[widget fields]\n    - light.button.min_height_px"),
623            "got: {msg}"
624        );
625        assert!(msg.contains("hint:"), "got: {msg}");
626    }
627
628    #[test]
629    fn display_resolution_incomplete_widget_category() {
630        // icon_set is no longer validated per-variant; test a widget field instead
631        let err = Error::ResolutionIncomplete {
632            missing: vec!["button.font.color".into()],
633        };
634        let msg = err.to_string();
635        assert!(msg.contains("[widget fields]"), "got: {msg}");
636        assert!(!msg.contains("hint:"), "got: {msg}");
637    }
638
639    #[test]
640    fn display_resolution_invalid_lists_violations() {
641        let err = Error::ResolutionInvalid {
642            errors: vec![
643                RangeViolation {
644                    path: "button.min_width_px".into(),
645                    value: -5.0,
646                    min: Some(0.0),
647                    max: None,
648                },
649                RangeViolation {
650                    path: "slider.track_height_px".into(),
651                    value: 200.0,
652                    min: Some(1.0),
653                    max: Some(100.0),
654                },
655            ],
656        };
657        let msg = err.to_string();
658        assert!(msg.contains("2 range violation(s)"), "got: {msg}");
659        assert!(msg.contains("button.min_width_px"), "got: {msg}");
660        assert!(msg.contains("-5"), "got: {msg}");
661        assert!(msg.contains("slider.track_height_px"), "got: {msg}");
662        assert!(msg.contains("200"), "got: {msg}");
663    }
664
665    #[test]
666    fn display_unknown_preset_shows_name_and_available() {
667        let err = Error::UnknownPreset {
668            name: "foobar".into(),
669            known: &["adwaita", "kde-breeze"],
670        };
671        let msg = err.to_string();
672        assert!(msg.contains("foobar"), "got: {msg}");
673        assert!(msg.contains("adwaita"), "got: {msg}");
674        assert!(msg.contains("kde-breeze"), "got: {msg}");
675    }
676
677    #[test]
678    fn display_unknown_preset_without_presets_says_so() {
679        let err = Error::UnknownPreset {
680            name: "adwaita".into(),
681            known: &[],
682        };
683        assert_eq!(
684            err.to_string(),
685            "unknown preset \"adwaita\": this platform has no OS generations to choose between"
686        );
687    }
688
689    // === source() tests ===
690
691    #[test]
692    fn source_some_for_io() {
693        let err = Error::Io {
694            path: "theme.toml".into(),
695            source: std::io::Error::other("disk failure"),
696        };
697        assert!(
698            std::error::Error::source(&err).is_some(),
699            "Io should return Some from source()"
700        );
701    }
702
703    #[test]
704    fn source_some_for_reader_failed() {
705        let err = Error::ReaderFailed {
706            reader: reader_names::ICON_THEME,
707            source: Box::new(std::io::Error::other("dbus down")),
708        };
709        let source = std::error::Error::source(&err);
710        assert!(
711            source.is_some(),
712            "ReaderFailed should return Some from source()"
713        );
714        assert!(source.unwrap().to_string().contains("dbus down"));
715    }
716
717    #[test]
718    fn source_some_for_toml() {
719        let toml_err: Result<toml::Value, toml::de::Error> = toml::from_str("=invalid");
720        let err = Error::Toml(toml_err.unwrap_err());
721        assert!(
722            std::error::Error::source(&err).is_some(),
723            "Toml should return Some from source()"
724        );
725    }
726
727    #[test]
728    fn source_none_for_feature_disabled() {
729        let err = Error::FeatureDisabled {
730            name: "kde",
731            needed_for: "detection",
732        };
733        assert!(std::error::Error::source(&err).is_none());
734    }
735
736    #[test]
737    fn source_none_for_platform_unsupported() {
738        let err = Error::PlatformUnsupported { platform: "wasm" };
739        assert!(std::error::Error::source(&err).is_none());
740    }
741
742    #[test]
743    fn source_none_for_watch_unavailable() {
744        let err = Error::WatchUnavailable {
745            reason: "not compiled",
746        };
747        assert!(std::error::Error::source(&err).is_none());
748    }
749
750    #[test]
751    fn source_none_for_unknown_preset() {
752        let err = Error::UnknownPreset {
753            name: "x".into(),
754            known: &[],
755        };
756        assert!(std::error::Error::source(&err).is_none());
757    }
758
759    #[test]
760    fn source_none_for_resolution_incomplete() {
761        let err = Error::ResolutionIncomplete {
762            missing: vec!["a".into()],
763        };
764        assert!(std::error::Error::source(&err).is_none());
765    }
766
767    #[test]
768    fn source_none_for_resolution_invalid() {
769        let err = Error::ResolutionInvalid {
770            errors: vec![RangeViolation {
771                path: "x".into(),
772                value: 0.0,
773                min: None,
774                max: None,
775            }],
776        };
777        assert!(std::error::Error::source(&err).is_none());
778    }
779
780    // === From impls ===
781
782    #[test]
783    fn from_toml_de_error_produces_toml_variant() {
784        let toml_err: Result<toml::Value, toml::de::Error> = toml::from_str("=invalid");
785        let err: Error = toml_err.unwrap_err().into();
786        match &err {
787            Error::Toml(_) => {} // correct
788            other => panic!("expected Toml variant, got: {other:?}"),
789        }
790    }
791
792    #[test]
793    fn display_io_names_path_and_source() {
794        let err = Error::Io {
795            path: "/themes/my-theme.toml".into(),
796            source: std::io::Error::new(std::io::ErrorKind::NotFound, "missing file"),
797        };
798        assert_eq!(
799            err.to_string(),
800            "cannot read theme file `/themes/my-theme.toml`: missing file"
801        );
802    }
803
804    // === Derive checks ===
805
806    #[test]
807    fn error_kind_derives() {
808        // Debug
809        let k = ErrorKind::Platform;
810        let dbg = format!("{k:?}");
811        assert!(dbg.contains("Platform"));
812
813        // Clone + Copy
814        let k2 = k;
815        let k3 = k2;
816        assert_eq!(k, k3);
817
818        // PartialEq + Eq
819        assert_eq!(ErrorKind::Parse, ErrorKind::Parse);
820        assert_ne!(ErrorKind::Io, ErrorKind::Resolution);
821    }
822
823    #[test]
824    fn range_violation_derives_debug_clone() {
825        let v = RangeViolation {
826            path: "x".into(),
827            value: 1.0,
828            min: Some(0.0),
829            max: Some(10.0),
830        };
831        // Debug
832        let dbg = format!("{v:?}");
833        assert!(dbg.contains("RangeViolation"));
834
835        // Clone
836        let v2 = v.clone();
837        assert_eq!(v2.path, "x");
838        assert!((v2.value - 1.0).abs() < f64::EPSILON);
839    }
840
841    // === RangeViolation Display ===
842
843    #[test]
844    fn range_violation_display_both_bounds() {
845        let v = RangeViolation {
846            path: "button.min_width_px".into(),
847            value: -5.0,
848            min: Some(0.0),
849            max: Some(1000.0),
850        };
851        let msg = v.to_string();
852        assert!(msg.contains("button.min_width_px"), "got: {msg}");
853        assert!(msg.contains("0..=1000"), "got: {msg}");
854        assert!(msg.contains("-5"), "got: {msg}");
855    }
856
857    #[test]
858    fn range_violation_display_open_max() {
859        let v = RangeViolation {
860            path: "x".into(),
861            value: -1.0,
862            min: Some(0.0),
863            max: None,
864        };
865        let msg = v.to_string();
866        assert!(msg.contains("0..=inf"), "got: {msg}");
867    }
868
869    #[test]
870    fn range_violation_display_open_min() {
871        let v = RangeViolation {
872            path: "x".into(),
873            value: 999.0,
874            min: None,
875            max: Some(100.0),
876        };
877        let msg = v.to_string();
878        assert!(msg.contains("-inf..=100"), "got: {msg}");
879    }
880}