1use std::fmt;
6
7#[derive(Debug, Clone)]
12pub struct RangeViolation {
13 pub path: String,
17 pub value: f64,
19 pub min: Option<f64>,
21 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44#[non_exhaustive]
45pub enum ErrorKind {
46 Platform,
48 Parse,
50 Resolution,
52 Io,
54}
55
56#[derive(Debug)]
61#[non_exhaustive]
62pub enum Error {
63 FeatureDisabled {
66 name: &'static str,
68 needed_for: &'static str,
70 },
71
72 PlatformUnsupported {
74 platform: &'static str,
76 },
77
78 UnknownPreset {
80 name: String,
82 known: &'static [&'static str],
86 },
87
88 WatchUnavailable {
91 reason: &'static str,
93 },
94
95 NoVariant {
101 mode: crate::theme::ColorMode,
103 },
104
105 Toml(toml::de::Error),
108
109 Io {
111 path: std::path::PathBuf,
113 source: std::io::Error,
115 },
116
117 ResolutionIncomplete {
142 missing: Vec<String>,
144 },
145
146 ResolutionInvalid {
153 errors: Vec<RangeViolation>,
155 },
156
157 ReaderFailed {
159 reader: &'static str,
161 source: Box<dyn std::error::Error + Send + Sync>,
163 },
164}
165
166impl Error {
167 #[must_use]
172 pub fn kind(&self) -> ErrorKind {
173 match self {
174 Error::FeatureDisabled { .. } => ErrorKind::Platform,
175 Error::PlatformUnsupported { .. } => ErrorKind::Platform,
176 Error::WatchUnavailable { .. } => ErrorKind::Platform,
177 Error::NoVariant { .. } => ErrorKind::Resolution,
178 Error::ReaderFailed { .. } => ErrorKind::Platform,
179 Error::UnknownPreset { .. } => ErrorKind::Parse,
180 Error::Toml(_) => ErrorKind::Parse,
181 Error::Io { .. } => ErrorKind::Io,
182 Error::ResolutionIncomplete { .. } => ErrorKind::Resolution,
183 Error::ResolutionInvalid { .. } => ErrorKind::Resolution,
184 }
185 }
186}
187
188impl Error {
189 pub(crate) fn in_variant(self, mode: crate::theme::ColorMode) -> Self {
196 let table = match mode {
197 crate::theme::ColorMode::Light => "light",
198 crate::theme::ColorMode::Dark => "dark",
199 };
200 match self {
201 Error::ResolutionIncomplete { missing } => Error::ResolutionIncomplete {
202 missing: missing
203 .into_iter()
204 .map(|path| format!("{table}.{path}"))
205 .collect(),
206 },
207 Error::ResolutionInvalid { errors } => Error::ResolutionInvalid {
208 errors: errors
209 .into_iter()
210 .map(|rv| {
211 if rv.path.starts_with("context.") {
212 rv
213 } else {
214 RangeViolation {
215 path: format!("{table}.{}", rv.path),
216 ..rv
217 }
218 }
219 })
220 .collect(),
221 },
222 other => other,
223 }
224 }
225}
226
227impl fmt::Display for Error {
228 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229 match self {
230 Error::FeatureDisabled { name, needed_for } => {
231 write!(f, "feature \"{name}\" is required for {needed_for}")
232 }
233 Error::PlatformUnsupported { platform } => {
234 write!(f, "platform not supported: {platform}")
235 }
236 Error::UnknownPreset { name, known: [] } => {
237 write!(
238 f,
239 "unknown preset \"{name}\": this platform has no OS generations to choose between"
240 )
241 }
242 Error::UnknownPreset { name, known } => {
243 write!(
244 f,
245 "unknown preset \"{name}\"; available: {}",
246 known.join(", ")
247 )
248 }
249 Error::WatchUnavailable { reason } => {
250 write!(f, "theme watching unavailable: {reason}")
251 }
252 Error::NoVariant { mode } => {
253 write!(
254 f,
255 "theme defines neither a light nor a dark variant (requested {mode:?})"
256 )
257 }
258 Error::Toml(err) => write!(f, "TOML error: {err}"),
259 Error::Io { path, source } => {
260 write!(f, "cannot read theme file `{}`: {source}", path.display())
261 }
262 Error::ResolutionIncomplete { missing } => {
263 write!(
264 f,
265 "theme resolution failed: {} missing field(s):",
266 missing.len()
267 )?;
268
269 let categories: &[&str] = &["root defaults", "text scale", "widget fields"];
271 for &cat in categories {
272 let fields: Vec<&str> = missing
273 .iter()
274 .filter(|field| field_category(field) == cat)
275 .map(|s| s.as_str())
276 .collect();
277 if fields.is_empty() {
278 continue;
279 }
280 write!(f, "\n [{cat}]")?;
281 for field in &fields {
282 write!(f, "\n - {field}")?;
283 }
284 }
285
286 let has_root = missing
288 .iter()
289 .any(|field| field_category(field) == "root defaults");
290 if has_root {
291 write!(
292 f,
293 "\n hint: root defaults drive widget inheritance; \
294 consider using Theme::preset(name) and then Theme::merge() to inherit from a complete preset"
295 )?;
296 }
297
298 Ok(())
299 }
300 Error::ResolutionInvalid { errors } => {
301 write!(
302 f,
303 "theme resolution failed: {} range violation(s):",
304 errors.len()
305 )?;
306 for violation in errors {
307 write!(f, "\n - {violation}")?;
308 }
309 Ok(())
310 }
311 Error::ReaderFailed { reader, source } => {
312 write!(f, "{reader} reader failed: {source}")
313 }
314 }
315 }
316}
317
318fn field_category(field: &str) -> &'static str {
321 let field = field
322 .strip_prefix("light.")
323 .or_else(|| field.strip_prefix("dark."))
324 .unwrap_or(field);
325 match field.split('.').next() {
326 Some("defaults") => "root defaults",
327 Some("text_scale") => "text scale",
328 _ => "widget fields",
329 }
330}
331
332impl std::error::Error for Error {
333 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
334 match self {
335 Error::Toml(err) => Some(err),
336 Error::Io { source, .. } => Some(source),
337 Error::ReaderFailed { source, .. } => Some(source.as_ref()),
338 Error::FeatureDisabled { .. }
339 | Error::PlatformUnsupported { .. }
340 | Error::UnknownPreset { .. }
341 | Error::WatchUnavailable { .. }
342 | Error::NoVariant { .. }
343 | Error::ResolutionIncomplete { .. }
344 | Error::ResolutionInvalid { .. } => None,
345 }
346 }
347}
348
349impl From<toml::de::Error> for Error {
350 fn from(err: toml::de::Error) -> Self {
351 Error::Toml(err)
352 }
353}
354
355impl From<toml::ser::Error> for Error {
356 fn from(err: toml::ser::Error) -> Self {
357 Error::ReaderFailed {
361 reader: reader_names::TOML_SERIALIZER,
362 source: Box::new(err),
363 }
364 }
365}
366
367macro_rules! reader_names {
369 ($($(#[$meta:meta])* $name:ident = $value:literal;)*) => {
370 $($(#[$meta])* pub(crate) const $name: &str = $value;)*
371
372 #[cfg(test)]
374 pub(crate) const ALL: &[&str] = &[$($value),*];
375 };
376}
377
378pub(crate) mod reader_names {
380 reader_names! {
381 #[cfg_attr(not(all(target_os = "windows", feature = "windows")), allow(dead_code))]
382 WINDOWS = "windows";
383 #[cfg_attr(not(all(target_os = "macos", feature = "macos")), allow(dead_code))]
384 MACOS = "macos";
385 ICON_THEME = "icon-theme";
386 TOML_SERIALIZER = "toml-serializer";
387 PRESET_CACHE = "preset-cache";
388 #[cfg_attr(not(feature = "svg-rasterize"), allow(dead_code))]
389 SVG_RASTERIZER = "svg-rasterizer";
390 #[cfg_attr(
391 not(all(feature = "watch", feature = "kde", target_os = "linux")),
392 allow(dead_code)
393 )]
394 KDE_WATCHER = "kde-watcher";
395 #[cfg_attr(
396 not(all(feature = "watch", feature = "portal", target_os = "linux")),
397 allow(dead_code)
398 )]
399 GNOME_WATCHER = "gnome-watcher";
400 #[cfg_attr(
401 not(all(feature = "watch", feature = "windows", target_os = "windows")),
402 allow(dead_code)
403 )]
404 WINDOWS_WATCHER = "windows-watcher";
405 }
406}
407
408#[cfg(test)]
409#[allow(clippy::unwrap_used, clippy::expect_used)]
410mod tests {
411 use super::*;
412
413 #[test]
414 fn reader_names_are_lowercase_kebab_case_and_unique() {
415 for name in reader_names::ALL {
416 assert!(
417 !name.is_empty()
418 && !name.starts_with('-')
419 && !name.ends_with('-')
420 && name
421 .chars()
422 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-'),
423 "{name:?} is not lowercase kebab-case"
424 );
425 }
426 let mut sorted = reader_names::ALL.to_vec();
427 sorted.sort_unstable();
428 assert!(sorted.windows(2).all(|w| w[0] != w[1]), "duplicate name");
429 }
430
431 #[test]
434 fn kind_platform_for_feature_disabled() {
435 let err = Error::FeatureDisabled {
436 name: "kde",
437 needed_for: "KDE theme detection",
438 };
439 assert_eq!(err.kind(), ErrorKind::Platform);
440 }
441
442 #[test]
443 fn kind_platform_for_platform_unsupported() {
444 let err = Error::PlatformUnsupported { platform: "wasm" };
445 assert_eq!(err.kind(), ErrorKind::Platform);
446 }
447
448 #[test]
449 fn kind_platform_for_watch_unavailable() {
450 let err = Error::WatchUnavailable {
451 reason: "notify crate not compiled",
452 };
453 assert_eq!(err.kind(), ErrorKind::Platform);
454 }
455
456 #[test]
457 fn kind_platform_for_reader_failed() {
458 let err = Error::ReaderFailed {
459 reader: reader_names::ICON_THEME,
460 source: Box::new(std::io::Error::other("dbus down")),
461 };
462 assert_eq!(err.kind(), ErrorKind::Platform);
463 }
464
465 #[test]
466 fn kind_parse_for_unknown_preset() {
467 let err = Error::UnknownPreset {
468 name: "foobar".into(),
469 known: &["adwaita", "kde-breeze"],
470 };
471 assert_eq!(err.kind(), ErrorKind::Parse);
472 }
473
474 #[test]
475 fn kind_parse_for_toml() {
476 let toml_err: Result<toml::Value, toml::de::Error> = toml::from_str("=invalid");
477 let err = Error::Toml(toml_err.unwrap_err());
478 assert_eq!(err.kind(), ErrorKind::Parse);
479 }
480
481 #[test]
482 fn kind_resolution_for_incomplete() {
483 let err = Error::ResolutionIncomplete {
484 missing: vec!["defaults.accent_color".into()],
485 };
486 assert_eq!(err.kind(), ErrorKind::Resolution);
487 }
488
489 #[test]
490 fn kind_resolution_for_invalid() {
491 let err = Error::ResolutionInvalid {
492 errors: vec![RangeViolation {
493 path: "button.min_width_px".into(),
494 value: -5.0,
495 min: Some(0.0),
496 max: None,
497 }],
498 };
499 assert_eq!(err.kind(), ErrorKind::Resolution);
500 }
501
502 #[test]
503 fn kind_io_for_io() {
504 let err = Error::Io {
505 path: "theme.toml".into(),
506 source: std::io::Error::other("disk failure"),
507 };
508 assert_eq!(err.kind(), ErrorKind::Io);
509 }
510
511 #[test]
514 fn error_is_send_sync() {
515 fn assert_send_sync<T: Send + Sync>() {}
516 assert_send_sync::<Error>();
517 }
518
519 #[test]
522 fn display_feature_disabled_includes_name_and_needed_for() {
523 let err = Error::FeatureDisabled {
524 name: "kde",
525 needed_for: "KDE theme detection",
526 };
527 let msg = err.to_string();
528 assert!(msg.contains("kde"), "got: {msg}");
529 assert!(msg.contains("KDE theme detection"), "got: {msg}");
530 }
531
532 #[test]
533 fn display_resolution_incomplete_categorizes_fields() {
534 let err = Error::ResolutionIncomplete {
535 missing: vec![
536 "defaults.accent_color".into(),
537 "button.font.color".into(),
538 "window.border.corner_radius_px".into(),
539 ],
540 };
541 let msg = err.to_string();
542 assert!(msg.contains("3 missing field(s)"), "got: {msg}");
543 assert!(msg.contains("[root defaults]"), "got: {msg}");
544 assert!(msg.contains("defaults.accent_color"), "got: {msg}");
545 assert!(msg.contains("[widget fields]"), "got: {msg}");
546 assert!(msg.contains("button.font.color"), "got: {msg}");
547 assert!(msg.contains("window.border.corner_radius_px"), "got: {msg}");
548 assert!(msg.contains("hint:"), "got: {msg}");
549 assert!(msg.contains("preset"), "got: {msg}");
550 }
551
552 #[test]
553 fn display_resolution_incomplete_no_hint_without_root_defaults() {
554 let err = Error::ResolutionIncomplete {
555 missing: vec!["button.font.color".into()],
556 };
557 let msg = err.to_string();
558 assert!(msg.contains("[widget fields]"), "got: {msg}");
559 assert!(!msg.contains("hint:"), "got: {msg}");
560 }
561
562 #[test]
563 fn display_no_variant_says_both_variants_are_missing() {
564 let err = Error::NoVariant {
565 mode: crate::theme::ColorMode::Dark,
566 };
567 assert_eq!(
568 err.to_string(),
569 "theme defines neither a light nor a dark variant (requested Dark)"
570 );
571 }
572
573 #[test]
574 fn display_resolution_incomplete_groups_text_scale() {
575 let err = Error::ResolutionIncomplete {
576 missing: vec!["text_scale.caption".into(), "defaults.font.family".into()],
577 };
578 let msg = err.to_string();
579 assert!(msg.contains("[text scale]"), "got: {msg}");
580 assert!(msg.contains("[root defaults]"), "got: {msg}");
581 }
582
583 #[test]
584 fn in_variant_prefixes_a_variant_path_and_not_the_context() {
585 let violation = |path: &str| RangeViolation {
586 path: path.into(),
587 value: 0.0,
588 min: Some(f64::MIN_POSITIVE),
589 max: None,
590 };
591 let err = Error::ResolutionInvalid {
592 errors: vec![
593 violation("context.font_dpi"),
594 violation("button.min_height_px"),
595 ],
596 }
597 .in_variant(crate::theme::ColorMode::Dark);
598 let Error::ResolutionInvalid { errors } = err else {
599 panic!("expected ResolutionInvalid, got: {err:?}");
600 };
601 let paths: Vec<&str> = errors.iter().map(|rv| rv.path.as_str()).collect();
602 assert_eq!(paths, ["context.font_dpi", "dark.button.min_height_px"]);
603 }
604
605 #[test]
606 fn display_resolution_incomplete_groups_variant_prefixed_paths() {
607 let err = Error::ResolutionIncomplete {
608 missing: vec![
609 "dark.text_scale.caption".into(),
610 "light.defaults.icon_sizes.toolbar_px".into(),
611 "light.button.min_height_px".into(),
612 ],
613 };
614 let msg = err.to_string();
615 assert!(
616 msg.contains("[text scale]\n - dark.text_scale.caption"),
617 "got: {msg}"
618 );
619 assert!(
620 msg.contains("[root defaults]\n - light.defaults.icon_sizes.toolbar_px"),
621 "got: {msg}"
622 );
623 assert!(
624 msg.contains("[widget fields]\n - light.button.min_height_px"),
625 "got: {msg}"
626 );
627 assert!(msg.contains("hint:"), "got: {msg}");
628 }
629
630 #[test]
631 fn display_resolution_incomplete_widget_category() {
632 let err = Error::ResolutionIncomplete {
634 missing: vec!["button.font.color".into()],
635 };
636 let msg = err.to_string();
637 assert!(msg.contains("[widget fields]"), "got: {msg}");
638 assert!(!msg.contains("hint:"), "got: {msg}");
639 }
640
641 #[test]
642 fn display_resolution_invalid_lists_violations() {
643 let err = Error::ResolutionInvalid {
644 errors: vec![
645 RangeViolation {
646 path: "button.min_width_px".into(),
647 value: -5.0,
648 min: Some(0.0),
649 max: None,
650 },
651 RangeViolation {
652 path: "slider.track_height_px".into(),
653 value: 200.0,
654 min: Some(1.0),
655 max: Some(100.0),
656 },
657 ],
658 };
659 let msg = err.to_string();
660 assert!(msg.contains("2 range violation(s)"), "got: {msg}");
661 assert!(msg.contains("button.min_width_px"), "got: {msg}");
662 assert!(msg.contains("-5"), "got: {msg}");
663 assert!(msg.contains("slider.track_height_px"), "got: {msg}");
664 assert!(msg.contains("200"), "got: {msg}");
665 }
666
667 #[test]
668 fn display_unknown_preset_shows_name_and_available() {
669 let err = Error::UnknownPreset {
670 name: "foobar".into(),
671 known: &["adwaita", "kde-breeze"],
672 };
673 let msg = err.to_string();
674 assert!(msg.contains("foobar"), "got: {msg}");
675 assert!(msg.contains("adwaita"), "got: {msg}");
676 assert!(msg.contains("kde-breeze"), "got: {msg}");
677 }
678
679 #[test]
680 fn display_unknown_preset_without_presets_says_so() {
681 let err = Error::UnknownPreset {
682 name: "adwaita".into(),
683 known: &[],
684 };
685 assert_eq!(
686 err.to_string(),
687 "unknown preset \"adwaita\": this platform has no OS generations to choose between"
688 );
689 }
690
691 #[test]
694 fn source_some_for_io() {
695 let err = Error::Io {
696 path: "theme.toml".into(),
697 source: std::io::Error::other("disk failure"),
698 };
699 assert!(
700 std::error::Error::source(&err).is_some(),
701 "Io should return Some from source()"
702 );
703 }
704
705 #[test]
706 fn source_some_for_reader_failed() {
707 let err = Error::ReaderFailed {
708 reader: reader_names::ICON_THEME,
709 source: Box::new(std::io::Error::other("dbus down")),
710 };
711 let source = std::error::Error::source(&err);
712 assert!(
713 source.is_some(),
714 "ReaderFailed should return Some from source()"
715 );
716 assert!(source.unwrap().to_string().contains("dbus down"));
717 }
718
719 #[test]
720 fn source_some_for_toml() {
721 let toml_err: Result<toml::Value, toml::de::Error> = toml::from_str("=invalid");
722 let err = Error::Toml(toml_err.unwrap_err());
723 assert!(
724 std::error::Error::source(&err).is_some(),
725 "Toml should return Some from source()"
726 );
727 }
728
729 #[test]
730 fn source_none_for_feature_disabled() {
731 let err = Error::FeatureDisabled {
732 name: "kde",
733 needed_for: "detection",
734 };
735 assert!(std::error::Error::source(&err).is_none());
736 }
737
738 #[test]
739 fn source_none_for_platform_unsupported() {
740 let err = Error::PlatformUnsupported { platform: "wasm" };
741 assert!(std::error::Error::source(&err).is_none());
742 }
743
744 #[test]
745 fn source_none_for_watch_unavailable() {
746 let err = Error::WatchUnavailable {
747 reason: "not compiled",
748 };
749 assert!(std::error::Error::source(&err).is_none());
750 }
751
752 #[test]
753 fn source_none_for_unknown_preset() {
754 let err = Error::UnknownPreset {
755 name: "x".into(),
756 known: &[],
757 };
758 assert!(std::error::Error::source(&err).is_none());
759 }
760
761 #[test]
762 fn source_none_for_resolution_incomplete() {
763 let err = Error::ResolutionIncomplete {
764 missing: vec!["a".into()],
765 };
766 assert!(std::error::Error::source(&err).is_none());
767 }
768
769 #[test]
770 fn source_none_for_resolution_invalid() {
771 let err = Error::ResolutionInvalid {
772 errors: vec![RangeViolation {
773 path: "x".into(),
774 value: 0.0,
775 min: None,
776 max: None,
777 }],
778 };
779 assert!(std::error::Error::source(&err).is_none());
780 }
781
782 #[test]
785 fn from_toml_de_error_produces_toml_variant() {
786 let toml_err: Result<toml::Value, toml::de::Error> = toml::from_str("=invalid");
787 let err: Error = toml_err.unwrap_err().into();
788 match &err {
789 Error::Toml(_) => {} other => panic!("expected Toml variant, got: {other:?}"),
791 }
792 }
793
794 #[test]
795 fn display_io_names_path_and_source() {
796 let err = Error::Io {
797 path: "/themes/my-theme.toml".into(),
798 source: std::io::Error::new(std::io::ErrorKind::NotFound, "missing file"),
799 };
800 assert_eq!(
801 err.to_string(),
802 "cannot read theme file `/themes/my-theme.toml`: missing file"
803 );
804 }
805
806 #[test]
809 fn error_kind_derives() {
810 let k = ErrorKind::Platform;
812 let dbg = format!("{k:?}");
813 assert!(dbg.contains("Platform"));
814
815 let k2 = k;
817 let k3 = k2;
818 assert_eq!(k, k3);
819
820 assert_eq!(ErrorKind::Parse, ErrorKind::Parse);
822 assert_ne!(ErrorKind::Io, ErrorKind::Resolution);
823 }
824
825 #[test]
826 fn range_violation_derives_debug_clone() {
827 let v = RangeViolation {
828 path: "x".into(),
829 value: 1.0,
830 min: Some(0.0),
831 max: Some(10.0),
832 };
833 let dbg = format!("{v:?}");
835 assert!(dbg.contains("RangeViolation"));
836
837 let v2 = v.clone();
839 assert_eq!(v2.path, "x");
840 assert!((v2.value - 1.0).abs() < f64::EPSILON);
841 }
842
843 #[test]
846 fn range_violation_display_both_bounds() {
847 let v = RangeViolation {
848 path: "button.min_width_px".into(),
849 value: -5.0,
850 min: Some(0.0),
851 max: Some(1000.0),
852 };
853 let msg = v.to_string();
854 assert!(msg.contains("button.min_width_px"), "got: {msg}");
855 assert!(msg.contains("0..=1000"), "got: {msg}");
856 assert!(msg.contains("-5"), "got: {msg}");
857 }
858
859 #[test]
860 fn range_violation_display_open_max() {
861 let v = RangeViolation {
862 path: "x".into(),
863 value: -1.0,
864 min: Some(0.0),
865 max: None,
866 };
867 let msg = v.to_string();
868 assert!(msg.contains("0..=inf"), "got: {msg}");
869 }
870
871 #[test]
872 fn range_violation_display_open_min() {
873 let v = RangeViolation {
874 path: "x".into(),
875 value: 999.0,
876 min: None,
877 max: Some(100.0),
878 };
879 let msg = v.to_string();
880 assert!(msg.contains("-inf..=100"), "got: {msg}");
881 }
882}