Skip to main content

native_theme/
error.rs

1// Error enum with Display, std::error::Error, and From conversions
2//
3// Option F: flat 9-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 path of the property (e.g. `"button.min_width"`).
14    pub path: String,
15    /// The actual value found.
16    pub value: f64,
17    /// Lower bound (inclusive), or `None` for open-ended.
18    pub min: Option<f64>,
19    /// Upper bound (inclusive), or `None` for open-ended.
20    pub max: Option<f64>,
21}
22
23impl fmt::Display for RangeViolation {
24    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25        let lo = self
26            .min
27            .map_or_else(|| "-inf".to_owned(), |v| v.to_string());
28        let hi = self.max.map_or_else(|| "inf".to_owned(), |v| v.to_string());
29        write!(
30            f,
31            "{} must be {}..={}, got {}",
32            self.path, lo, hi, self.value
33        )
34    }
35}
36
37/// Coarse error category returned by [`Error::kind()`].
38///
39/// Follows the `std::io::ErrorKind` precedent: callers can match on the kind
40/// for broad dispatch without inspecting each variant.
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42#[non_exhaustive]
43pub enum ErrorKind {
44    /// Platform feature not available or not supported.
45    Platform,
46    /// Parsing or lookup failure (TOML, preset name).
47    Parse,
48    /// Theme resolution failure (missing fields, range violations).
49    Resolution,
50    /// File I/O error.
51    Io,
52}
53
54/// Errors that can occur when reading or processing theme data.
55///
56/// This is a flat enum with 9 variants. Use [`Error::kind()`] for coarse
57/// dispatch without matching every variant.
58#[derive(Debug)]
59#[non_exhaustive]
60pub enum Error {
61    /// A feature is compiled in but disabled at runtime or not applicable.
62    FeatureDisabled {
63        /// Feature name (e.g. `"kde"`, `"portal"`).
64        name: &'static str,
65        /// What the feature is needed for (e.g. `"KDE theme detection"`).
66        needed_for: &'static str,
67    },
68
69    /// The current platform is not supported.
70    PlatformUnsupported {
71        /// Platform identifier (e.g. `"wasm"`, `"freebsd"`).
72        platform: &'static str,
73    },
74
75    /// A preset name was not found in the bundled set.
76    UnknownPreset {
77        /// The requested preset name.
78        name: String,
79        /// Available preset names.
80        known: &'static [&'static str],
81    },
82
83    /// File-system watching is not available.
84    WatchUnavailable {
85        /// Why watching is unavailable.
86        reason: &'static str,
87    },
88
89    /// The theme has no variant for the requested color mode.
90    ///
91    /// Returned by [`Theme::pick_variant()`](crate::Theme::pick_variant) and
92    /// [`Theme::into_variant()`](crate::Theme::into_variant) when the theme
93    /// has neither a light nor a dark variant set.
94    NoVariant {
95        /// The color mode that was requested.
96        mode: crate::theme::ColorMode,
97    },
98
99    /// TOML parsing or serialization error.
100    Toml(toml::de::Error),
101
102    /// File I/O error.
103    Io(std::io::Error),
104
105    /// Theme resolution found missing fields that could not be inherited.
106    ResolutionIncomplete {
107        /// Dot-separated paths of fields still `None` after resolution.
108        missing: Vec<String>,
109    },
110
111    /// Theme resolution found numeric values outside allowed ranges.
112    ResolutionInvalid {
113        /// One entry per out-of-range property.
114        errors: Vec<RangeViolation>,
115    },
116
117    /// A platform reader failed with a platform-specific error.
118    ReaderFailed {
119        /// Reader name (e.g. `"kde"`, `"gnome-portal"`, `"windows"`).
120        reader: &'static str,
121        /// The underlying error.
122        source: Box<dyn std::error::Error + Send + Sync>,
123    },
124}
125
126impl Error {
127    /// Returns the coarse [`ErrorKind`] for this error.
128    ///
129    /// Useful for broad dispatch (e.g. "is this a platform problem or a
130    /// parse problem?") without matching every variant.
131    #[must_use]
132    pub fn kind(&self) -> ErrorKind {
133        match self {
134            Error::FeatureDisabled { .. } => ErrorKind::Platform,
135            Error::PlatformUnsupported { .. } => ErrorKind::Platform,
136            Error::WatchUnavailable { .. } => ErrorKind::Platform,
137            Error::NoVariant { .. } => ErrorKind::Resolution,
138            Error::ReaderFailed { .. } => ErrorKind::Platform,
139            Error::UnknownPreset { .. } => ErrorKind::Parse,
140            Error::Toml(_) => ErrorKind::Parse,
141            Error::Io(_) => ErrorKind::Io,
142            Error::ResolutionIncomplete { .. } => ErrorKind::Resolution,
143            Error::ResolutionInvalid { .. } => ErrorKind::Resolution,
144        }
145    }
146}
147
148impl fmt::Display for Error {
149    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150        match self {
151            Error::FeatureDisabled { name, needed_for } => {
152                write!(f, "feature \"{name}\" is required for {needed_for}")
153            }
154            Error::PlatformUnsupported { platform } => {
155                write!(f, "platform not supported: {platform}")
156            }
157            Error::UnknownPreset { name, known } => {
158                write!(
159                    f,
160                    "unknown preset \"{name}\"; available: {}",
161                    known.join(", ")
162                )
163            }
164            Error::WatchUnavailable { reason } => {
165                write!(f, "theme watching unavailable: {reason}")
166            }
167            Error::NoVariant { mode } => {
168                write!(f, "theme has no variant for {mode:?}")
169            }
170            Error::Toml(err) => write!(f, "TOML error: {err}"),
171            Error::Io(err) => write!(f, "I/O error: {err}"),
172            Error::ResolutionIncomplete { missing } => {
173                write!(
174                    f,
175                    "theme resolution failed: {} missing field(s):",
176                    missing.len()
177                )?;
178
179                // Group fields by category, preserving insertion order within each group.
180                let categories: &[&str] =
181                    &["root defaults", "text scale", "widget fields", "icon set"];
182                for &cat in categories {
183                    let fields: Vec<&str> = missing
184                        .iter()
185                        .filter(|field| field_category(field) == cat)
186                        .map(|s| s.as_str())
187                        .collect();
188                    if fields.is_empty() {
189                        continue;
190                    }
191                    write!(f, "\n  [{cat}]")?;
192                    for field in &fields {
193                        write!(f, "\n    - {field}")?;
194                    }
195                }
196
197                // Hint when root defaults are missing (the most common user mistake).
198                let has_root = missing
199                    .iter()
200                    .any(|field| field_category(field) == "root defaults");
201                if has_root {
202                    write!(
203                        f,
204                        "\n  hint: root defaults drive widget inheritance; \
205                         consider using Theme::preset(name) and then Theme::merge() to inherit from a complete preset"
206                    )?;
207                }
208
209                Ok(())
210            }
211            Error::ResolutionInvalid { errors } => {
212                write!(
213                    f,
214                    "theme resolution failed: {} range violation(s):",
215                    errors.len()
216                )?;
217                for violation in errors {
218                    write!(f, "\n  - {violation}")?;
219                }
220                Ok(())
221            }
222            Error::ReaderFailed { reader, source } => {
223                write!(f, "{reader} reader failed: {source}")
224            }
225        }
226    }
227}
228
229/// Categorize a field path into a human-readable group name.
230fn field_category(field: &str) -> &'static str {
231    match field.split('.').next() {
232        Some("defaults") => "root defaults",
233        Some("text_scale") => "text scale",
234        _ => "widget fields",
235    }
236}
237
238impl std::error::Error for Error {
239    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
240        match self {
241            Error::Toml(err) => Some(err),
242            Error::Io(err) => Some(err),
243            Error::ReaderFailed { source, .. } => Some(source.as_ref()),
244            Error::FeatureDisabled { .. }
245            | Error::PlatformUnsupported { .. }
246            | Error::UnknownPreset { .. }
247            | Error::WatchUnavailable { .. }
248            | Error::NoVariant { .. }
249            | Error::ResolutionIncomplete { .. }
250            | Error::ResolutionInvalid { .. } => None,
251        }
252    }
253}
254
255impl From<toml::de::Error> for Error {
256    fn from(err: toml::de::Error) -> Self {
257        Error::Toml(err)
258    }
259}
260
261impl From<toml::ser::Error> for Error {
262    fn from(err: toml::ser::Error) -> Self {
263        // Serialization errors are stringified because Error::Toml wraps only
264        // toml::de::Error. This preserves the existing From<toml::ser::Error>
265        // conversion used by presets::to_toml().
266        Error::ReaderFailed {
267            reader: "toml-serializer",
268            source: Box::new(err),
269        }
270    }
271}
272
273impl From<std::io::Error> for Error {
274    fn from(err: std::io::Error) -> Self {
275        Error::Io(err)
276    }
277}
278
279#[cfg(test)]
280#[allow(clippy::unwrap_used, clippy::expect_used)]
281mod tests {
282    use super::*;
283
284    // === ErrorKind dispatch tests ===
285
286    #[test]
287    fn kind_platform_for_feature_disabled() {
288        let err = Error::FeatureDisabled {
289            name: "kde",
290            needed_for: "KDE theme detection",
291        };
292        assert_eq!(err.kind(), ErrorKind::Platform);
293    }
294
295    #[test]
296    fn kind_platform_for_platform_unsupported() {
297        let err = Error::PlatformUnsupported { platform: "wasm" };
298        assert_eq!(err.kind(), ErrorKind::Platform);
299    }
300
301    #[test]
302    fn kind_platform_for_watch_unavailable() {
303        let err = Error::WatchUnavailable {
304            reason: "notify crate not compiled",
305        };
306        assert_eq!(err.kind(), ErrorKind::Platform);
307    }
308
309    #[test]
310    fn kind_platform_for_reader_failed() {
311        let err = Error::ReaderFailed {
312            reader: "kde",
313            source: Box::new(std::io::Error::other("dbus down")),
314        };
315        assert_eq!(err.kind(), ErrorKind::Platform);
316    }
317
318    #[test]
319    fn kind_parse_for_unknown_preset() {
320        let err = Error::UnknownPreset {
321            name: "foobar".into(),
322            known: &["adwaita", "kde-breeze"],
323        };
324        assert_eq!(err.kind(), ErrorKind::Parse);
325    }
326
327    #[test]
328    fn kind_parse_for_toml() {
329        let toml_err: Result<toml::Value, toml::de::Error> = toml::from_str("=invalid");
330        let err = Error::Toml(toml_err.unwrap_err());
331        assert_eq!(err.kind(), ErrorKind::Parse);
332    }
333
334    #[test]
335    fn kind_resolution_for_incomplete() {
336        let err = Error::ResolutionIncomplete {
337            missing: vec!["defaults.accent_color".into()],
338        };
339        assert_eq!(err.kind(), ErrorKind::Resolution);
340    }
341
342    #[test]
343    fn kind_resolution_for_invalid() {
344        let err = Error::ResolutionInvalid {
345            errors: vec![RangeViolation {
346                path: "button.min_width".into(),
347                value: -5.0,
348                min: Some(0.0),
349                max: None,
350            }],
351        };
352        assert_eq!(err.kind(), ErrorKind::Resolution);
353    }
354
355    #[test]
356    fn kind_io_for_io() {
357        let err = Error::Io(std::io::Error::other("disk failure"));
358        assert_eq!(err.kind(), ErrorKind::Io);
359    }
360
361    // === Send + Sync ===
362
363    #[test]
364    fn error_is_send_sync() {
365        fn assert_send_sync<T: Send + Sync>() {}
366        assert_send_sync::<Error>();
367    }
368
369    // === Display tests ===
370
371    #[test]
372    fn display_feature_disabled_includes_name_and_needed_for() {
373        let err = Error::FeatureDisabled {
374            name: "kde",
375            needed_for: "KDE theme detection",
376        };
377        let msg = err.to_string();
378        assert!(msg.contains("kde"), "got: {msg}");
379        assert!(msg.contains("KDE theme detection"), "got: {msg}");
380    }
381
382    #[test]
383    fn display_resolution_incomplete_categorizes_fields() {
384        let err = Error::ResolutionIncomplete {
385            missing: vec![
386                "defaults.accent_color".into(),
387                "button.font.color".into(),
388                "window.border.corner_radius".into(),
389            ],
390        };
391        let msg = err.to_string();
392        assert!(msg.contains("3 missing field(s)"), "got: {msg}");
393        assert!(msg.contains("[root defaults]"), "got: {msg}");
394        assert!(msg.contains("defaults.accent_color"), "got: {msg}");
395        assert!(msg.contains("[widget fields]"), "got: {msg}");
396        assert!(msg.contains("button.font.color"), "got: {msg}");
397        assert!(msg.contains("window.border.corner_radius"), "got: {msg}");
398        assert!(msg.contains("hint:"), "got: {msg}");
399        assert!(msg.contains("preset"), "got: {msg}");
400    }
401
402    #[test]
403    fn display_resolution_incomplete_no_hint_without_root_defaults() {
404        let err = Error::ResolutionIncomplete {
405            missing: vec!["button.font.color".into()],
406        };
407        let msg = err.to_string();
408        assert!(msg.contains("[widget fields]"), "got: {msg}");
409        assert!(!msg.contains("hint:"), "got: {msg}");
410    }
411
412    #[test]
413    fn display_resolution_incomplete_groups_text_scale() {
414        let err = Error::ResolutionIncomplete {
415            missing: vec!["text_scale.caption".into(), "defaults.font.family".into()],
416        };
417        let msg = err.to_string();
418        assert!(msg.contains("[text scale]"), "got: {msg}");
419        assert!(msg.contains("[root defaults]"), "got: {msg}");
420    }
421
422    #[test]
423    fn display_resolution_incomplete_widget_category() {
424        // icon_set is no longer validated per-variant; test a widget field instead
425        let err = Error::ResolutionIncomplete {
426            missing: vec!["button.font.color".into()],
427        };
428        let msg = err.to_string();
429        assert!(msg.contains("[widget fields]"), "got: {msg}");
430        assert!(!msg.contains("hint:"), "got: {msg}");
431    }
432
433    #[test]
434    fn display_resolution_invalid_lists_violations() {
435        let err = Error::ResolutionInvalid {
436            errors: vec![
437                RangeViolation {
438                    path: "button.min_width".into(),
439                    value: -5.0,
440                    min: Some(0.0),
441                    max: None,
442                },
443                RangeViolation {
444                    path: "slider.track_height".into(),
445                    value: 200.0,
446                    min: Some(1.0),
447                    max: Some(100.0),
448                },
449            ],
450        };
451        let msg = err.to_string();
452        assert!(msg.contains("2 range violation(s)"), "got: {msg}");
453        assert!(msg.contains("button.min_width"), "got: {msg}");
454        assert!(msg.contains("-5"), "got: {msg}");
455        assert!(msg.contains("slider.track_height"), "got: {msg}");
456        assert!(msg.contains("200"), "got: {msg}");
457    }
458
459    #[test]
460    fn display_unknown_preset_shows_name_and_available() {
461        let err = Error::UnknownPreset {
462            name: "foobar".into(),
463            known: &["adwaita", "kde-breeze"],
464        };
465        let msg = err.to_string();
466        assert!(msg.contains("foobar"), "got: {msg}");
467        assert!(msg.contains("adwaita"), "got: {msg}");
468        assert!(msg.contains("kde-breeze"), "got: {msg}");
469    }
470
471    // === source() tests ===
472
473    #[test]
474    fn source_some_for_io() {
475        let err = Error::Io(std::io::Error::other("disk failure"));
476        assert!(
477            std::error::Error::source(&err).is_some(),
478            "Io should return Some from source()"
479        );
480    }
481
482    #[test]
483    fn source_some_for_reader_failed() {
484        let err = Error::ReaderFailed {
485            reader: "kde",
486            source: Box::new(std::io::Error::other("dbus down")),
487        };
488        let source = std::error::Error::source(&err);
489        assert!(
490            source.is_some(),
491            "ReaderFailed should return Some from source()"
492        );
493        assert!(source.unwrap().to_string().contains("dbus down"));
494    }
495
496    #[test]
497    fn source_some_for_toml() {
498        let toml_err: Result<toml::Value, toml::de::Error> = toml::from_str("=invalid");
499        let err = Error::Toml(toml_err.unwrap_err());
500        assert!(
501            std::error::Error::source(&err).is_some(),
502            "Toml should return Some from source()"
503        );
504    }
505
506    #[test]
507    fn source_none_for_feature_disabled() {
508        let err = Error::FeatureDisabled {
509            name: "kde",
510            needed_for: "detection",
511        };
512        assert!(std::error::Error::source(&err).is_none());
513    }
514
515    #[test]
516    fn source_none_for_platform_unsupported() {
517        let err = Error::PlatformUnsupported { platform: "wasm" };
518        assert!(std::error::Error::source(&err).is_none());
519    }
520
521    #[test]
522    fn source_none_for_watch_unavailable() {
523        let err = Error::WatchUnavailable {
524            reason: "not compiled",
525        };
526        assert!(std::error::Error::source(&err).is_none());
527    }
528
529    #[test]
530    fn source_none_for_unknown_preset() {
531        let err = Error::UnknownPreset {
532            name: "x".into(),
533            known: &[],
534        };
535        assert!(std::error::Error::source(&err).is_none());
536    }
537
538    #[test]
539    fn source_none_for_resolution_incomplete() {
540        let err = Error::ResolutionIncomplete {
541            missing: vec!["a".into()],
542        };
543        assert!(std::error::Error::source(&err).is_none());
544    }
545
546    #[test]
547    fn source_none_for_resolution_invalid() {
548        let err = Error::ResolutionInvalid {
549            errors: vec![RangeViolation {
550                path: "x".into(),
551                value: 0.0,
552                min: None,
553                max: None,
554            }],
555        };
556        assert!(std::error::Error::source(&err).is_none());
557    }
558
559    // === From impls ===
560
561    #[test]
562    fn from_toml_de_error_produces_toml_variant() {
563        let toml_err: Result<toml::Value, toml::de::Error> = toml::from_str("=invalid");
564        let err: Error = toml_err.unwrap_err().into();
565        match &err {
566            Error::Toml(_) => {} // correct
567            other => panic!("expected Toml variant, got: {other:?}"),
568        }
569    }
570
571    #[test]
572    fn from_io_error_produces_io_variant_no_arc() {
573        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "missing file");
574        let err: Error = io_err.into();
575        match &err {
576            Error::Io(e) => {
577                assert_eq!(e.kind(), std::io::ErrorKind::NotFound);
578                assert!(e.to_string().contains("missing file"));
579            }
580            other => panic!("expected Io variant, got: {other:?}"),
581        }
582    }
583
584    // === Derive checks ===
585
586    #[test]
587    fn error_kind_derives() {
588        // Debug
589        let k = ErrorKind::Platform;
590        let dbg = format!("{k:?}");
591        assert!(dbg.contains("Platform"));
592
593        // Clone + Copy
594        let k2 = k;
595        let k3 = k2;
596        assert_eq!(k, k3);
597
598        // PartialEq + Eq
599        assert_eq!(ErrorKind::Parse, ErrorKind::Parse);
600        assert_ne!(ErrorKind::Io, ErrorKind::Resolution);
601    }
602
603    #[test]
604    fn range_violation_derives_debug_clone() {
605        let v = RangeViolation {
606            path: "x".into(),
607            value: 1.0,
608            min: Some(0.0),
609            max: Some(10.0),
610        };
611        // Debug
612        let dbg = format!("{v:?}");
613        assert!(dbg.contains("RangeViolation"));
614
615        // Clone
616        let v2 = v.clone();
617        assert_eq!(v2.path, "x");
618        assert!((v2.value - 1.0).abs() < f64::EPSILON);
619    }
620
621    // === RangeViolation Display ===
622
623    #[test]
624    fn range_violation_display_both_bounds() {
625        let v = RangeViolation {
626            path: "button.min_width".into(),
627            value: -5.0,
628            min: Some(0.0),
629            max: Some(1000.0),
630        };
631        let msg = v.to_string();
632        assert!(msg.contains("button.min_width"), "got: {msg}");
633        assert!(msg.contains("0..=1000"), "got: {msg}");
634        assert!(msg.contains("-5"), "got: {msg}");
635    }
636
637    #[test]
638    fn range_violation_display_open_max() {
639        let v = RangeViolation {
640            path: "x".into(),
641            value: -1.0,
642            min: Some(0.0),
643            max: None,
644        };
645        let msg = v.to_string();
646        assert!(msg.contains("0..=inf"), "got: {msg}");
647    }
648
649    #[test]
650    fn range_violation_display_open_min() {
651        let v = RangeViolation {
652            path: "x".into(),
653            value: 999.0,
654            min: None,
655            max: Some(100.0),
656        };
657        let msg = v.to_string();
658        assert!(msg.contains("-inf..=100"), "got: {msg}");
659    }
660}