1#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
18#[non_exhaustive]
19pub enum ColorMode {
20 Light,
22 Dark,
24}
25
26impl ColorMode {
27 #[must_use]
29 pub fn is_dark(self) -> bool {
30 matches!(self, Self::Dark)
31 }
32}
33
34pub(crate) mod animated;
36pub(crate) mod arrow_side;
38pub(crate) mod border;
40pub(crate) mod bundled;
42pub(crate) mod defaults;
44pub(crate) mod dialog_entrance_style;
46pub(crate) mod dialog_order;
48pub(crate) mod font;
50pub(crate) mod icon_sizes;
52pub(crate) mod icons;
54pub(crate) mod resolved;
56pub(crate) mod tab_indicator_side;
58pub(crate) mod widgets;
60
61pub use animated::{
62 AnimatedIcon, EmptyFrameListError, FrameList, FramesData, TransformAnimation, TransformData,
63};
64pub use arrow_side::ArrowSide;
65pub use border::{
66 DefaultsBorderSpec, ResolvedDefaultsBorder, ResolvedPadding, ResolvedWidgetBorder,
67 WidgetBorderSpec,
68};
69pub(crate) use bundled::{bundled_icon_by_name, bundled_icon_svg};
71pub use defaults::ThemeDefaults;
72pub use dialog_entrance_style::DialogEntranceStyle;
73pub use dialog_order::DialogButtonOrder;
74pub use font::{
75 FontSize, FontSpec, FontStyle, ResolvedFontSpec, TextScale, TextScaleEntry, intern_font_family,
76};
77pub use icon_sizes::IconSizes;
78pub use icons::{IconData, IconProvider, IconRole, IconSet, RgbaData, icon_name};
79pub use resolved::{
80 Resolved, ResolvedDefaults, ResolvedIconSizes, ResolvedTextScale, ResolvedTextScaleEntry,
81 ResolvedTheme,
82};
83pub use tab_indicator_side::TabIndicatorSide;
84pub use widgets::*; use std::borrow::Cow;
87
88use serde::{Deserialize, Serialize};
89
90#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
107#[serde(default)]
108pub struct ThemeMode {
109 #[serde(default, skip_serializing_if = "ThemeDefaults::is_empty")]
111 pub defaults: ThemeDefaults,
112
113 #[serde(default, skip_serializing_if = "TextScale::is_empty")]
115 pub text_scale: TextScale,
116
117 #[serde(default, skip_serializing_if = "WindowTheme::is_empty")]
119 pub window: WindowTheme,
120
121 #[serde(default, skip_serializing_if = "ButtonTheme::is_empty")]
123 pub button: ButtonTheme,
124
125 #[serde(default, skip_serializing_if = "InputTheme::is_empty")]
127 pub input: InputTheme,
128
129 #[serde(default, skip_serializing_if = "TextAreaTheme::is_empty")]
131 pub text_area: TextAreaTheme,
132
133 #[serde(default, skip_serializing_if = "CheckboxTheme::is_empty")]
135 pub checkbox: CheckboxTheme,
136
137 #[serde(default, skip_serializing_if = "MenuTheme::is_empty")]
139 pub menu: MenuTheme,
140
141 #[serde(default, skip_serializing_if = "TooltipTheme::is_empty")]
143 pub tooltip: TooltipTheme,
144
145 #[serde(default, skip_serializing_if = "ScrollbarTheme::is_empty")]
147 pub scrollbar: ScrollbarTheme,
148
149 #[serde(default, skip_serializing_if = "SliderTheme::is_empty")]
151 pub slider: SliderTheme,
152
153 #[serde(default, skip_serializing_if = "ProgressBarTheme::is_empty")]
155 pub progress_bar: ProgressBarTheme,
156
157 #[serde(default, skip_serializing_if = "TabTheme::is_empty")]
159 pub tab: TabTheme,
160
161 #[serde(default, skip_serializing_if = "SidebarTheme::is_empty")]
163 pub sidebar: SidebarTheme,
164
165 #[serde(default, skip_serializing_if = "ToolbarTheme::is_empty")]
167 pub toolbar: ToolbarTheme,
168
169 #[serde(default, skip_serializing_if = "StatusBarTheme::is_empty")]
171 pub status_bar: StatusBarTheme,
172
173 #[serde(default, skip_serializing_if = "ListTheme::is_empty")]
175 pub list: ListTheme,
176
177 #[serde(default, skip_serializing_if = "PopoverTheme::is_empty")]
179 pub popover: PopoverTheme,
180
181 #[serde(default, skip_serializing_if = "SplitterTheme::is_empty")]
183 pub splitter: SplitterTheme,
184
185 #[serde(default, skip_serializing_if = "SeparatorTheme::is_empty")]
187 pub separator: SeparatorTheme,
188
189 #[serde(default, skip_serializing_if = "SwitchTheme::is_empty")]
191 pub switch: SwitchTheme,
192
193 #[serde(default, skip_serializing_if = "DialogTheme::is_empty")]
195 pub dialog: DialogTheme,
196
197 #[serde(default, skip_serializing_if = "SpinnerTheme::is_empty")]
199 pub spinner: SpinnerTheme,
200
201 #[serde(default, skip_serializing_if = "ComboBoxTheme::is_empty")]
203 pub combo_box: ComboBoxTheme,
204
205 #[serde(default, skip_serializing_if = "SegmentedControlTheme::is_empty")]
207 pub segmented_control: SegmentedControlTheme,
208
209 #[serde(default, skip_serializing_if = "CardTheme::is_empty")]
211 pub card: CardTheme,
212
213 #[serde(default, skip_serializing_if = "ExpanderTheme::is_empty")]
215 pub expander: ExpanderTheme,
216
217 #[serde(default, skip_serializing_if = "LinkTheme::is_empty")]
219 pub link: LinkTheme,
220}
221
222impl_merge!(ThemeMode {
223 nested {
224 defaults, text_scale, window, button, input, text_area, checkbox, menu,
225 tooltip, scrollbar, slider, progress_bar, tab, sidebar,
226 toolbar, status_bar, list, popover, splitter, separator,
227 switch, dialog, spinner, combo_box, segmented_control,
228 card, expander, link
229 }
230});
231
232#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
261pub struct Theme {
262 #[serde(default)]
270 pub name: Cow<'static, str>,
271
272 #[serde(default, skip_serializing_if = "Option::is_none")]
274 pub light: Option<ThemeMode>,
275
276 #[serde(default, skip_serializing_if = "Option::is_none")]
278 pub dark: Option<ThemeMode>,
279
280 #[serde(default, skip_serializing_if = "LayoutTheme::is_empty")]
282 pub layout: LayoutTheme,
283
284 #[serde(default, skip_serializing_if = "Option::is_none")]
299 pub icon_set: Option<IconSet>,
300
301 #[serde(default, skip_serializing_if = "Option::is_none")]
317 pub icon_theme: Option<Cow<'static, str>>,
318}
319
320impl Default for Theme {
321 fn default() -> Self {
322 Self {
323 name: Cow::Borrowed(""),
324 light: None,
325 dark: None,
326 layout: LayoutTheme::default(),
327 icon_set: None,
328 icon_theme: None,
329 }
330 }
331}
332
333impl Theme {
334 pub fn merge(&mut self, overlay: &Self) {
341 match (&mut self.light, &overlay.light) {
344 (Some(base), Some(over)) => base.merge(over),
345 (None, Some(over)) => self.light = Some(over.clone()),
346 _ => {}
347 }
348
349 match (&mut self.dark, &overlay.dark) {
350 (Some(base), Some(over)) => base.merge(over),
351 (None, Some(over)) => self.dark = Some(over.clone()),
352 _ => {}
353 }
354
355 self.layout.merge(&overlay.layout);
356
357 if overlay.icon_set.is_some() {
358 self.icon_set = overlay.icon_set;
359 }
360
361 if overlay.icon_theme.is_some() {
362 self.icon_theme.clone_from(&overlay.icon_theme);
363 }
364 }
365
366 pub fn pick_variant(&self, mode: ColorMode) -> crate::Result<&ThemeMode> {
378 self.pick_variant_with_mode(mode)
379 .map(|(_, variant)| variant)
380 }
381
382 pub(crate) fn pick_variant_with_mode(
385 &self,
386 mode: ColorMode,
387 ) -> crate::Result<(ColorMode, &ThemeMode)> {
388 let dark = self.dark.as_ref().map(|v| (ColorMode::Dark, v));
389 let light = self.light.as_ref().map(|v| (ColorMode::Light, v));
390 match mode {
391 ColorMode::Dark => dark.or(light),
392 ColorMode::Light => light.or(dark),
393 }
394 .ok_or(crate::Error::NoVariant { mode })
395 }
396
397 pub fn into_variant(self, mode: ColorMode) -> crate::Result<ThemeMode> {
421 match mode {
422 ColorMode::Dark => self.dark.or(self.light),
423 ColorMode::Light => self.light.or(self.dark),
424 }
425 .ok_or(crate::Error::NoVariant { mode })
426 }
427
428 pub fn resolve(&self, mode: ColorMode) -> crate::Result<Resolved> {
488 self.resolve_with(mode, &crate::resolve::ResolutionContext::from_system())
489 }
490
491 pub fn resolve_with(
516 &self,
517 mode: ColorMode,
518 ctx: &crate::resolve::ResolutionContext,
519 ) -> crate::Result<Resolved> {
520 let (picked_mode, variant_ref) = self.pick_variant_with_mode(mode)?;
521 crate::resolve::validate_helpers::check_font_dpi(ctx.font_dpi)?;
522 crate::resolve::validate_helpers::check_layout(&self.layout)?;
523
524 let tier1 = variant_ref.defaults.icon_theme.clone();
525 let tier2 = self.icon_theme.clone();
526 let icon_theme_explicit = tier1.is_some() || tier2.is_some();
527 let icon_theme = tier1.or(tier2).or_else(|| ctx.icon_theme.clone());
528
529 let icon_set = self.icon_set.unwrap_or_else(crate::detect::system_icon_set);
530
531 let variant = variant_ref
532 .clone()
533 .into_resolved(ctx)
534 .map_err(|e| e.in_variant(picked_mode))?;
535
536 Ok(Resolved {
537 mode: picked_mode,
538 variant,
539 icon_set,
540 icon_theme,
541 icon_theme_explicit,
542 })
543 }
544
545 pub fn is_empty(&self) -> bool {
548 self.light.is_none()
549 && self.dark.is_none()
550 && self.layout.is_empty()
551 && self.icon_set.is_none()
552 && self.icon_theme.is_none()
553 }
554
555 pub fn preset(name: &str) -> crate::Result<Self> {
579 crate::presets::preset(name)
580 }
581
582 pub fn from_toml(toml_str: &str) -> crate::Result<Self> {
687 crate::presets::from_toml(toml_str)
688 }
689
690 pub fn from_file(path: impl AsRef<std::path::Path>) -> crate::Result<Self> {
701 crate::presets::from_file(path)
702 }
703
704 #[must_use]
718 pub fn list_presets() -> &'static [crate::presets::PresetInfo] {
719 crate::presets::list_presets()
720 }
721
722 #[must_use]
741 pub fn list_presets_for_platform() -> Vec<crate::presets::PresetInfo> {
742 crate::presets::list_presets_for_platform()
743 }
744
745 pub fn to_toml(&self) -> crate::Result<String> {
757 crate::presets::to_toml(self)
758 }
759
760 pub fn lint_toml(toml_str: &str) -> crate::Result<Vec<String>> {
786 let value: toml::Value =
787 toml::from_str(toml_str).map_err(|e: toml::de::Error| crate::Error::Toml(e))?;
788
789 let mut warnings = Vec::new();
790
791 let top_table = match &value {
792 toml::Value::Table(t) => t,
793 _ => return Ok(warnings),
794 };
795
796 const TOP_KEYS: &[&str] = &["name", "light", "dark", "layout", "icon_set", "icon_theme"];
798
799 for key in top_table.keys() {
800 if !TOP_KEYS.contains(&key.as_str()) {
801 warnings.push(format!("unknown field: {key}"));
802 }
803 }
804
805 const STRUCTURAL_KEYS: &[&str] = &["defaults", "text_scale"];
807
808 let widget_registry: std::collections::HashMap<&str, &[&str]> =
814 inventory::iter::<crate::resolve::WidgetFieldInfo>()
815 .map(|info| (info.widget_name, info.field_names))
816 .collect();
817 let struct_registry: std::collections::HashMap<&str, &[&str]> =
818 inventory::iter::<crate::resolve::FieldInfo>()
819 .map(|info| (info.struct_name, info.field_names))
820 .collect();
821
822 let get_struct_fields =
827 |name: &str| -> Option<&[&str]> { struct_registry.get(name).copied() };
828
829 let lint_text_scale = |table: &toml::map::Map<String, toml::Value>,
831 prefix: &str,
832 warnings: &mut Vec<String>| {
833 let Some(scale_fields) = get_struct_fields("TextScale") else {
834 return;
835 };
836 let entry_fields = get_struct_fields("TextScaleEntry");
837 for key in table.keys() {
838 if !scale_fields.contains(&key.as_str()) {
839 warnings.push(format!("unknown field: {prefix}.{key}"));
840 } else if let Some(toml::Value::Table(entry_table)) = table.get(key)
841 && let Some(entry_fields) = entry_fields
842 {
843 for ekey in entry_table.keys() {
844 if !entry_fields.contains(&ekey.as_str()) {
845 warnings.push(format!("unknown field: {prefix}.{key}.{ekey}"));
846 }
847 }
848 }
849 }
850 };
851
852 let lint_defaults = |table: &toml::map::Map<String, toml::Value>,
854 prefix: &str,
855 warnings: &mut Vec<String>| {
856 let Some(defaults_fields) = get_struct_fields("ThemeDefaults") else {
857 return;
858 };
859 for key in table.keys() {
860 if !defaults_fields.contains(&key.as_str()) {
861 warnings.push(format!("unknown field: {prefix}.{key}"));
862 continue;
863 }
864 if let Some(toml::Value::Table(sub)) = table.get(key) {
866 let known = match key.as_str() {
867 "font" | "mono_font" => get_struct_fields("FontSpec"),
868 "border" => get_struct_fields("DefaultsBorderSpec"),
869 "icon_sizes" => get_struct_fields("IconSizes"),
870 _ => continue,
871 };
872 let Some(known) = known else { continue };
873 for skey in sub.keys() {
874 if !known.contains(&skey.as_str()) {
875 warnings.push(format!("unknown field: {prefix}.{key}.{skey}"));
876 }
877 }
878 }
879 }
880 };
881
882 let lint_variant = |table: &toml::map::Map<String, toml::Value>,
884 prefix: &str,
885 warnings: &mut Vec<String>| {
886 for key in table.keys() {
887 let key_str = key.as_str();
888
889 let is_structural = STRUCTURAL_KEYS.contains(&key_str);
891 let widget_fields = widget_registry.get(key_str);
892
893 if !is_structural && widget_fields.is_none() {
894 warnings.push(format!("unknown field: {prefix}.{key}"));
895 continue;
896 }
897
898 if let Some(toml::Value::Table(sub)) = table.get(key) {
899 let sub_prefix = format!("{prefix}.{key}");
900 match key_str {
901 "defaults" => lint_defaults(sub, &sub_prefix, warnings),
902 "text_scale" => lint_text_scale(sub, &sub_prefix, warnings),
903 _ => {
904 if let Some(fields) = widget_fields {
905 for skey in sub.keys() {
906 if !fields.contains(&skey.as_str()) {
907 warnings
908 .push(format!("unknown field: {sub_prefix}.{skey}"));
909 }
910 if let Some(toml::Value::Table(nested)) = sub.get(skey) {
912 let nested_known = match skey.as_str() {
913 s if s == "font" || s.ends_with("_font") => {
914 get_struct_fields("FontSpec")
915 }
916 "border" => get_struct_fields("WidgetBorderSpec"),
917 _ => None,
918 };
919 if let Some(known) = nested_known {
920 for nkey in nested.keys() {
921 if !known.contains(&nkey.as_str()) {
922 warnings.push(format!(
923 "unknown field: {sub_prefix}.{skey}.{nkey}"
924 ));
925 }
926 }
927 }
928 }
929 }
930 }
931 }
932 }
933 }
934 }
935 };
936
937 for variant_key in &["light", "dark"] {
939 if let Some(toml::Value::Table(variant_table)) = top_table.get(*variant_key) {
940 lint_variant(variant_table, variant_key, &mut warnings);
941 }
942 }
943
944 if let Some(toml::Value::Table(layout_table)) = top_table.get("layout")
948 && let Some(layout_fields) = get_struct_fields("LayoutTheme")
949 {
950 for key in layout_table.keys() {
951 if !layout_fields.contains(&key.as_str()) {
952 warnings.push(format!("unknown field: layout.{key}"));
953 }
954 }
955 }
956
957 Ok(warnings)
958 }
959}
960
961#[cfg(test)]
962#[allow(clippy::unwrap_used, clippy::expect_used)]
963mod tests {
964 use super::*;
965 use crate::Rgba;
966
967 #[test]
970 fn theme_variant_default_is_empty() {
971 assert!(ThemeMode::default().is_empty());
972 }
973
974 #[test]
975 fn theme_variant_not_empty_when_color_set() {
976 let mut v = ThemeMode::default();
977 v.defaults.accent_color = Some(Rgba::rgb(0, 120, 215));
978 assert!(!v.is_empty());
979 }
980
981 #[test]
982 fn theme_variant_not_empty_when_font_set() {
983 let mut v = ThemeMode::default();
984 v.defaults.font.family = Some("Inter".into());
985 assert!(!v.is_empty());
986 }
987
988 #[test]
989 fn theme_variant_merge_recursively() {
990 let mut base = ThemeMode::default();
991 base.defaults.background_color = Some(Rgba::rgb(255, 255, 255));
992 base.defaults.font.family = Some("Noto Sans".into());
993
994 let mut overlay = ThemeMode::default();
995 overlay.defaults.accent_color = Some(Rgba::rgb(0, 120, 215));
996 overlay.defaults.border.corner_radius = Some(4.0);
997
998 base.merge(&overlay);
999
1000 assert_eq!(
1002 base.defaults.background_color,
1003 Some(Rgba::rgb(255, 255, 255))
1004 );
1005 assert_eq!(base.defaults.accent_color, Some(Rgba::rgb(0, 120, 215)));
1007 assert_eq!(base.defaults.font.family.as_deref(), Some("Noto Sans"));
1009 assert_eq!(base.defaults.border.corner_radius, Some(4.0));
1011 }
1012
1013 #[test]
1014 fn theme_variant_has_all_widgets() {
1015 let mut v = ThemeMode::default();
1016 v.window.background_color = Some(Rgba::rgb(255, 255, 255));
1018 v.button.min_height = Some(32.0);
1019 v.input.min_height = Some(32.0);
1020 v.checkbox.indicator_width = Some(18.0);
1021 v.menu.row_height = Some(28.0);
1022 v.tooltip.max_width = Some(300.0);
1023 v.scrollbar.groove_width = Some(14.0);
1024 v.slider.track_height = Some(4.0);
1025 v.progress_bar.track_height = Some(6.0);
1026 v.tab.min_height = Some(32.0);
1027 v.sidebar.background_color = Some(Rgba::rgb(240, 240, 240));
1028 v.toolbar.bar_height = Some(40.0);
1029 v.status_bar.background_color = Some(Rgba::rgb(240, 240, 240));
1030 v.list.row_height = Some(28.0);
1031 v.popover.background_color = Some(Rgba::rgb(255, 255, 255));
1032 v.splitter.divider_width = Some(4.0);
1033 v.separator.line_color = Some(Rgba::rgb(200, 200, 200));
1034 v.switch.track_width = Some(32.0);
1035 v.dialog.min_width = Some(320.0);
1036 v.spinner.diameter = Some(24.0);
1037 v.combo_box.min_height = Some(32.0);
1038 v.segmented_control.segment_height = Some(28.0);
1039 v.card.background_color = Some(Rgba::rgb(255, 255, 255));
1040 v.expander.header_height = Some(32.0);
1041 v.link.underline_enabled = Some(true);
1042
1043 assert!(!v.is_empty());
1044 assert!(!v.window.is_empty());
1045 assert!(!v.button.is_empty());
1046 assert!(!v.input.is_empty());
1047 assert!(!v.checkbox.is_empty());
1048 assert!(!v.menu.is_empty());
1049 assert!(!v.tooltip.is_empty());
1050 assert!(!v.scrollbar.is_empty());
1051 assert!(!v.slider.is_empty());
1052 assert!(!v.progress_bar.is_empty());
1053 assert!(!v.tab.is_empty());
1054 assert!(!v.sidebar.is_empty());
1055 assert!(!v.toolbar.is_empty());
1056 assert!(!v.status_bar.is_empty());
1057 assert!(!v.list.is_empty());
1058 assert!(!v.popover.is_empty());
1059 assert!(!v.splitter.is_empty());
1060 assert!(!v.separator.is_empty());
1061 assert!(!v.switch.is_empty());
1062 assert!(!v.dialog.is_empty());
1063 assert!(!v.spinner.is_empty());
1064 assert!(!v.combo_box.is_empty());
1065 assert!(!v.segmented_control.is_empty());
1066 assert!(!v.card.is_empty());
1067 assert!(!v.expander.is_empty());
1068 assert!(!v.link.is_empty());
1069 }
1070
1071 #[test]
1072 fn theme_variant_merge_per_widget() {
1073 let mut base = ThemeMode::default();
1074 base.button.background_color = Some(Rgba::rgb(200, 200, 200));
1075 base.button.min_height = Some(28.0);
1076 base.tooltip.background_color = Some(Rgba::rgb(50, 50, 50));
1077
1078 let mut overlay = ThemeMode::default();
1079 overlay.button.background_color = Some(Rgba::rgb(255, 255, 255));
1080 overlay.button.min_width = Some(64.0);
1081
1082 base.merge(&overlay);
1083
1084 assert_eq!(base.button.background_color, Some(Rgba::rgb(255, 255, 255)));
1086 assert_eq!(base.button.min_width, Some(64.0));
1088 assert_eq!(base.button.min_height, Some(28.0));
1090 assert_eq!(base.tooltip.background_color, Some(Rgba::rgb(50, 50, 50)));
1092 }
1093
1094 #[test]
1097 fn native_theme_default_is_empty() {
1098 let theme = Theme::default();
1099 assert!(theme.is_empty());
1100 assert_eq!(theme.name, "");
1101 }
1102
1103 #[test]
1104 fn native_theme_merge_keeps_base_name() {
1105 let mut base = Theme {
1106 name: "Base Theme".into(),
1107 ..Theme::default()
1108 };
1109 let overlay = Theme {
1110 name: "Overlay Theme".into(),
1111 ..Theme::default()
1112 };
1113 base.merge(&overlay);
1114 assert_eq!(base.name, "Base Theme");
1115 }
1116
1117 #[test]
1118 fn nameless_overlay_parses_and_merges() {
1119 let toml = "[light.defaults]\naccent_color = \"#ff6600\"";
1120 assert!(Theme::lint_toml(toml).unwrap().is_empty());
1121 let overlay = Theme::from_toml(toml).unwrap();
1122 assert_eq!(overlay.name, "");
1123
1124 let mut base = Theme::preset("catppuccin-mocha").unwrap();
1125 base.merge(&overlay);
1126 assert_eq!(base.name, "Catppuccin Mocha");
1127 assert_eq!(
1128 base.light.as_ref().unwrap().defaults.accent_color,
1129 Some(Rgba::rgb(0xff, 0x66, 0x00))
1130 );
1131 }
1132
1133 #[test]
1134 fn icon_set_segoe_fluent_toml_round_trip() {
1135 let theme = Theme::from_toml("name = \"T\"\nicon_set = \"segoe-fluent\"").unwrap();
1136 assert_eq!(theme.icon_set, Some(IconSet::SegoeFluent));
1137 let toml_text = theme.to_toml().unwrap();
1138 assert!(
1139 toml_text.contains("icon_set = \"segoe-fluent\""),
1140 "serialized name changed: {toml_text}"
1141 );
1142 assert_eq!(
1143 Theme::from_toml(&toml_text).unwrap().icon_set,
1144 Some(IconSet::SegoeFluent)
1145 );
1146 }
1147
1148 #[test]
1149 fn native_theme_merge_overlay_light_into_none() {
1150 let mut base = Theme {
1151 name: "Theme".into(),
1152 ..Theme::default()
1153 };
1154
1155 let mut overlay = Theme {
1156 name: "Overlay".into(),
1157 ..Theme::default()
1158 };
1159 let mut light = ThemeMode::default();
1160 light.defaults.accent_color = Some(Rgba::rgb(0, 120, 215));
1161 overlay.light = Some(light);
1162
1163 base.merge(&overlay);
1164
1165 assert!(base.light.is_some());
1166 assert_eq!(
1167 base.light.as_ref().unwrap().defaults.accent_color,
1168 Some(Rgba::rgb(0, 120, 215))
1169 );
1170 }
1171
1172 #[test]
1173 fn native_theme_merge_both_light_variants() {
1174 let mut base = Theme {
1175 name: "Theme".into(),
1176 ..Theme::default()
1177 };
1178 let mut base_light = ThemeMode::default();
1179 base_light.defaults.background_color = Some(Rgba::rgb(255, 255, 255));
1180 base.light = Some(base_light);
1181
1182 let mut overlay = Theme {
1183 name: "Overlay".into(),
1184 ..Theme::default()
1185 };
1186 let mut overlay_light = ThemeMode::default();
1187 overlay_light.defaults.accent_color = Some(Rgba::rgb(0, 120, 215));
1188 overlay.light = Some(overlay_light);
1189
1190 base.merge(&overlay);
1191
1192 let light = base.light.as_ref().unwrap();
1193 assert_eq!(
1195 light.defaults.background_color,
1196 Some(Rgba::rgb(255, 255, 255))
1197 );
1198 assert_eq!(light.defaults.accent_color, Some(Rgba::rgb(0, 120, 215)));
1200 }
1201
1202 #[test]
1203 fn native_theme_merge_base_light_only_preserved() {
1204 let mut base = Theme {
1205 name: "Theme".into(),
1206 ..Theme::default()
1207 };
1208 let mut base_light = ThemeMode::default();
1209 base_light.defaults.font.family = Some("Inter".into());
1210 base.light = Some(base_light);
1211
1212 let overlay = Theme {
1213 name: "Overlay".into(),
1214 ..Theme::default()
1215 }; base.merge(&overlay);
1218
1219 assert!(base.light.is_some());
1220 assert_eq!(
1221 base.light.as_ref().unwrap().defaults.font.family.as_deref(),
1222 Some("Inter")
1223 );
1224 }
1225
1226 #[test]
1227 fn native_theme_merge_dark_variant() {
1228 let mut base = Theme {
1229 name: "Theme".into(),
1230 ..Theme::default()
1231 };
1232
1233 let mut overlay = Theme {
1234 name: "Overlay".into(),
1235 ..Theme::default()
1236 };
1237 let mut dark = ThemeMode::default();
1238 dark.defaults.background_color = Some(Rgba::rgb(30, 30, 30));
1239 overlay.dark = Some(dark);
1240
1241 base.merge(&overlay);
1242
1243 assert!(base.dark.is_some());
1244 assert_eq!(
1245 base.dark.as_ref().unwrap().defaults.background_color,
1246 Some(Rgba::rgb(30, 30, 30))
1247 );
1248 }
1249
1250 #[test]
1251 fn native_theme_not_empty_with_light() {
1252 let mut theme = Theme {
1253 name: "Theme".into(),
1254 ..Theme::default()
1255 };
1256 theme.light = Some(ThemeMode::default());
1257 assert!(!theme.is_empty());
1258 }
1259
1260 #[test]
1263 fn pick_variant_dark_with_both_variants_returns_dark() {
1264 let mut theme = Theme {
1265 name: "Test".into(),
1266 ..Theme::default()
1267 };
1268 let mut light = ThemeMode::default();
1269 light.defaults.background_color = Some(Rgba::rgb(255, 255, 255));
1270 theme.light = Some(light);
1271 let mut dark = ThemeMode::default();
1272 dark.defaults.background_color = Some(Rgba::rgb(30, 30, 30));
1273 theme.dark = Some(dark);
1274
1275 let picked = theme.pick_variant(ColorMode::Dark).unwrap();
1276 assert_eq!(
1277 picked.defaults.background_color,
1278 Some(Rgba::rgb(30, 30, 30))
1279 );
1280 }
1281
1282 #[test]
1283 fn pick_variant_light_with_both_variants_returns_light() {
1284 let mut theme = Theme {
1285 name: "Test".into(),
1286 ..Theme::default()
1287 };
1288 let mut light = ThemeMode::default();
1289 light.defaults.background_color = Some(Rgba::rgb(255, 255, 255));
1290 theme.light = Some(light);
1291 let mut dark = ThemeMode::default();
1292 dark.defaults.background_color = Some(Rgba::rgb(30, 30, 30));
1293 theme.dark = Some(dark);
1294
1295 let picked = theme.pick_variant(ColorMode::Light).unwrap();
1296 assert_eq!(
1297 picked.defaults.background_color,
1298 Some(Rgba::rgb(255, 255, 255))
1299 );
1300 }
1301
1302 #[test]
1303 fn pick_variant_dark_with_only_light_falls_back() {
1304 let mut theme = Theme {
1305 name: "Test".into(),
1306 ..Theme::default()
1307 };
1308 let mut light = ThemeMode::default();
1309 light.defaults.background_color = Some(Rgba::rgb(255, 255, 255));
1310 theme.light = Some(light);
1311
1312 let picked = theme.pick_variant(ColorMode::Dark).unwrap();
1313 assert_eq!(
1314 picked.defaults.background_color,
1315 Some(Rgba::rgb(255, 255, 255))
1316 );
1317 }
1318
1319 #[test]
1320 fn pick_variant_light_with_only_dark_falls_back() {
1321 let mut theme = Theme {
1322 name: "Test".into(),
1323 ..Theme::default()
1324 };
1325 let mut dark = ThemeMode::default();
1326 dark.defaults.background_color = Some(Rgba::rgb(30, 30, 30));
1327 theme.dark = Some(dark);
1328
1329 let picked = theme.pick_variant(ColorMode::Light).unwrap();
1330 assert_eq!(
1331 picked.defaults.background_color,
1332 Some(Rgba::rgb(30, 30, 30))
1333 );
1334 }
1335
1336 #[test]
1337 fn pick_variant_with_no_variants_returns_err() {
1338 let theme = Theme {
1339 name: "Empty".into(),
1340 ..Theme::default()
1341 };
1342 assert!(theme.pick_variant(ColorMode::Dark).is_err());
1343 assert!(theme.pick_variant(ColorMode::Light).is_err());
1344 }
1345
1346 #[test]
1349 fn icon_set_default_is_none() {
1350 assert!(Theme::default().icon_set.is_none());
1351 }
1352
1353 #[test]
1354 fn icon_set_merge_overlay() {
1355 let mut base = Theme {
1356 name: "Base".into(),
1357 ..Theme::default()
1358 };
1359 let mut overlay = Theme {
1360 name: "Overlay".into(),
1361 ..Theme::default()
1362 };
1363 overlay.icon_set = Some(IconSet::Material);
1364 base.merge(&overlay);
1365 assert_eq!(base.icon_set, Some(IconSet::Material));
1366 }
1367
1368 #[test]
1369 fn icon_set_merge_none_preserves() {
1370 let mut base = Theme {
1371 name: "Base".into(),
1372 ..Theme::default()
1373 };
1374 base.icon_set = Some(IconSet::SfSymbols);
1375 let overlay = Theme {
1376 name: "Overlay".into(),
1377 ..Theme::default()
1378 };
1379 base.merge(&overlay);
1380 assert_eq!(base.icon_set, Some(IconSet::SfSymbols));
1381 }
1382
1383 #[test]
1384 fn icon_set_is_empty_when_set() {
1385 assert!(Theme::default().is_empty());
1386 let mut t = Theme {
1387 name: "Test".into(),
1388 ..Theme::default()
1389 };
1390 t.icon_set = Some(IconSet::Material);
1391 assert!(!t.is_empty());
1392 }
1393
1394 #[test]
1395 fn icon_set_toml_round_trip() {
1396 let mut theme = Theme {
1397 name: "Test".into(),
1398 ..Theme::default()
1399 };
1400 theme.icon_set = Some(IconSet::Material);
1401 let mut light = ThemeMode::default();
1402 light.defaults.icon_theme = Some("material".into());
1403 theme.light = Some(light);
1404 let toml_str = theme.to_toml().unwrap();
1405 assert!(toml_str.contains("icon_set"));
1406 let deserialized = Theme::from_toml(&toml_str).unwrap();
1407 assert_eq!(deserialized.icon_set, Some(IconSet::Material));
1408 assert_eq!(
1409 deserialized
1410 .light
1411 .as_ref()
1412 .unwrap()
1413 .defaults
1414 .icon_theme
1415 .as_deref(),
1416 Some("material")
1417 );
1418 }
1419
1420 #[test]
1421 fn icon_set_toml_absent_deserializes_to_none() {
1422 let toml_str = r##"
1423name = "Bare"
1424[light.defaults]
1425accent_color = "#ff0000"
1426"##;
1427 let theme = Theme::from_toml(toml_str).unwrap();
1428 assert!(theme.icon_set.is_none());
1429 assert!(theme.light.as_ref().unwrap().defaults.icon_theme.is_none());
1430 }
1431
1432 #[test]
1433 fn native_theme_serde_toml_round_trip() {
1434 let theme = Theme::preset("material-3").expect("material-3 preset should load");
1436 let toml_str = theme.to_toml().expect("should serialize");
1437 let theme2 = Theme::from_toml(&toml_str).expect("should deserialize");
1438 assert_eq!(theme, theme2, "round-trip should preserve Theme");
1439 }
1440
1441 #[test]
1444 fn resolve_material_uses_theme_level_icon_theme() {
1445 let theme = Theme::preset("material-3").unwrap();
1448 for mode in [ColorMode::Light, ColorMode::Dark] {
1449 let r = theme.resolve(mode).unwrap();
1450 assert_eq!(
1451 r.icon_theme.as_deref(),
1452 Some("material"),
1453 "material (tier 2) for {mode:?}"
1454 );
1455 assert!(
1456 r.icon_theme_explicit,
1457 "explicit flag must be true for {mode:?}"
1458 );
1459 assert_eq!(r.icon_set, IconSet::Material);
1460 }
1461 }
1462
1463 #[test]
1464 fn resolve_kde_breeze_uses_per_variant_icon_theme() {
1465 let theme = Theme::preset("kde-breeze").unwrap();
1468
1469 let light = theme.resolve(ColorMode::Light).unwrap();
1470 assert_eq!(light.icon_theme.as_deref(), Some("breeze"));
1471 assert!(light.icon_theme_explicit);
1472
1473 let dark = theme.resolve(ColorMode::Dark).unwrap();
1474 assert_eq!(dark.icon_theme.as_deref(), Some("breeze-dark"));
1475 assert!(dark.icon_theme_explicit);
1476
1477 assert_eq!(light.icon_set, IconSet::Freedesktop);
1478 assert_eq!(dark.icon_set, IconSet::Freedesktop);
1479 }
1480
1481 fn adwaita_without_icon_theme() -> Theme {
1483 let mut theme = Theme::preset("adwaita").unwrap();
1484 theme.icon_theme = None;
1485 if let Some(v) = theme.light.as_mut() {
1486 v.defaults.icon_theme = None;
1487 }
1488 if let Some(v) = theme.dark.as_mut() {
1489 v.defaults.icon_theme = None;
1490 }
1491 theme
1492 }
1493
1494 #[test]
1495 fn resolve_minimal_theme_takes_the_detected_icon_theme() {
1496 let ctx = crate::resolve::ResolutionContext::with_detected_icon_theme(Ok(
1498 "detected-theme".to_string()
1499 ));
1500 let r = adwaita_without_icon_theme()
1501 .resolve_with(ColorMode::Light, &ctx)
1502 .unwrap();
1503 assert_eq!(r.icon_theme.as_deref(), Some("detected-theme"));
1504 assert!(
1505 !r.icon_theme_explicit,
1506 "tier 3 fallback must report explicit = false"
1507 );
1508 }
1509
1510 #[test]
1511 fn resolve_minimal_theme_without_detection_has_no_icon_theme() {
1512 let ctx = crate::resolve::ResolutionContext::with_detected_icon_theme(Err(
1515 crate::Error::PlatformUnsupported {
1516 platform: "the test's failing detection",
1517 },
1518 ));
1519 let r = adwaita_without_icon_theme()
1520 .resolve_with(ColorMode::Light, &ctx)
1521 .expect("a failed icon-theme detection must not fail resolution");
1522 assert_eq!(r.icon_theme, None);
1523 assert!(!r.icon_theme_explicit);
1524 }
1525
1526 #[test]
1527 fn resolve_minimal_theme_resolves_whatever_detection_gives() {
1528 let r = adwaita_without_icon_theme()
1531 .resolve(ColorMode::Light)
1532 .unwrap();
1533 assert!(!r.icon_theme_explicit);
1534 assert_eq!(
1535 r.icon_theme.as_deref(),
1536 crate::detect::system_icon_theme().ok().as_deref()
1537 );
1538 }
1539
1540 #[test]
1541 fn resolve_tier1_wins_over_tier2() {
1542 let mut theme = Theme::preset("adwaita").unwrap();
1545 theme.icon_theme = Some(Cow::Borrowed("theme-level"));
1546 theme.light.as_mut().unwrap().defaults.icon_theme = Some(Cow::Borrowed("per-variant"));
1547 let r = theme.resolve(ColorMode::Light).unwrap();
1548 assert_eq!(r.icon_theme.as_deref(), Some("per-variant"));
1549 assert!(r.icon_theme_explicit);
1550 }
1551
1552 #[test]
1553 fn resolve_cross_mode_fallback_picks_available_variant() {
1554 let mut theme = Theme::preset("adwaita").unwrap();
1557 theme.dark = None;
1558 theme.icon_theme = None;
1559 theme.light.as_mut().unwrap().defaults.icon_theme = Some(Cow::Borrowed("only-one"));
1560 let r = theme.resolve(ColorMode::Dark).unwrap();
1561 assert_eq!(r.icon_theme.as_deref(), Some("only-one"));
1562 assert!(r.icon_theme_explicit);
1563 }
1564
1565 #[test]
1566 fn resolve_light_only_asked_dark_reports_light_mode() {
1567 let mut theme = Theme::preset("adwaita").unwrap();
1568 theme.dark = None;
1569 let r = theme.resolve(ColorMode::Dark).unwrap();
1570 assert_eq!(r.mode, ColorMode::Light);
1571 }
1572
1573 #[test]
1574 fn resolve_reports_requested_mode_when_variant_present() {
1575 let theme = Theme::preset("adwaita").unwrap();
1576 assert_eq!(
1577 theme.resolve(ColorMode::Dark).unwrap().mode,
1578 ColorMode::Dark
1579 );
1580 assert_eq!(
1581 theme.resolve(ColorMode::Light).unwrap().mode,
1582 ColorMode::Light
1583 );
1584 }
1585
1586 #[test]
1587 fn resolve_empty_theme_returns_no_variant_error() {
1588 let theme = Theme {
1589 name: "Empty".into(),
1590 ..Theme::default()
1591 };
1592 assert!(matches!(
1593 theme.resolve(ColorMode::Light),
1594 Err(crate::Error::NoVariant {
1595 mode: ColorMode::Light
1596 })
1597 ));
1598 }
1599
1600 #[test]
1601 fn resolve_all_presets_succeed() {
1602 for info in Theme::list_presets() {
1604 let theme = Theme::preset(info.key).unwrap();
1605 for mode in [ColorMode::Light, ColorMode::Dark] {
1606 theme.resolve(mode).unwrap_or_else(|e| {
1607 panic!("preset '{}' failed to resolve({mode:?}): {e}", info.key)
1608 });
1609 }
1610 }
1611 }
1612
1613 #[test]
1616 fn lint_toml_valid_returns_empty() {
1617 let toml = r##"
1618name = "Valid Theme"
1619[light.defaults]
1620accent_color = "#ff0000"
1621background_color = "#ffffff"
1622[light.defaults.font]
1623family = "Inter"
1624size_px = 14.0
1625[light.button]
1626min_height_px = 32.0
1627"##;
1628 let warnings = Theme::lint_toml(toml).unwrap();
1629 assert!(
1630 warnings.is_empty(),
1631 "Expected no warnings, got: {warnings:?}"
1632 );
1633 }
1634
1635 #[test]
1636 fn lint_toml_detects_unknown_top_level() {
1637 let toml = r##"
1638name = "Test"
1639theme_version = 2
1640"##;
1641 let warnings = Theme::lint_toml(toml).unwrap();
1642 assert_eq!(warnings.len(), 1);
1643 assert!(warnings[0].contains("theme_version"));
1644 }
1645
1646 #[test]
1647 fn lint_toml_detects_misspelled_defaults_field() {
1648 let toml = r##"
1649name = "Test"
1650[light.defaults]
1651backround = "#ffffff"
1652"##;
1653 let warnings = Theme::lint_toml(toml).unwrap();
1654 assert_eq!(warnings.len(), 1);
1655 assert!(warnings[0].contains("backround"));
1656 assert!(warnings[0].contains("light.defaults.backround"));
1657 }
1658
1659 #[test]
1660 fn lint_toml_detects_unknown_widget_field() {
1661 let toml = r##"
1662name = "Test"
1663[dark.button]
1664primary_bg = "#0078d7"
1665"##;
1666 let warnings = Theme::lint_toml(toml).unwrap();
1667 assert_eq!(warnings.len(), 1);
1668 assert!(warnings[0].contains("primary_bg"));
1669 }
1670
1671 #[test]
1672 fn lint_toml_detects_unknown_variant_section() {
1673 let toml = r##"
1674name = "Test"
1675[light.badges]
1676color = "#ff0000"
1677"##;
1678 let warnings = Theme::lint_toml(toml).unwrap();
1679 assert_eq!(warnings.len(), 1);
1680 assert!(warnings[0].contains("badges"));
1681 }
1682
1683 #[test]
1684 fn lint_toml_detects_unknown_font_subfield() {
1685 let toml = r##"
1686name = "Test"
1687[light.defaults.font]
1688famly = "Inter"
1689"##;
1690 let warnings = Theme::lint_toml(toml).unwrap();
1691 assert_eq!(warnings.len(), 1);
1692 assert!(warnings[0].contains("famly"));
1693 }
1694
1695 #[test]
1696 fn lint_toml_detects_unknown_border_subfield() {
1697 let toml = r##"
1698name = "Test"
1699[light.defaults.border]
1700radiusss = 4.0
1701"##;
1702 let warnings = Theme::lint_toml(toml).unwrap();
1703 assert_eq!(warnings.len(), 1);
1704 assert!(warnings[0].contains("radiusss"));
1705 }
1706
1707 #[test]
1708 fn lint_toml_detects_unknown_text_scale_entry() {
1709 let toml = r##"
1710name = "Test"
1711[light.text_scale.headline]
1712size = 24.0
1713"##;
1714 let warnings = Theme::lint_toml(toml).unwrap();
1715 assert_eq!(warnings.len(), 1);
1716 assert!(warnings[0].contains("headline"));
1717 }
1718
1719 #[test]
1720 fn lint_toml_detects_unknown_text_scale_entry_field() {
1721 let toml = r##"
1722name = "Test"
1723[light.text_scale.caption]
1724font_size = 12.0
1725"##;
1726 let warnings = Theme::lint_toml(toml).unwrap();
1727 assert_eq!(warnings.len(), 1);
1728 assert!(warnings[0].contains("font_size"));
1729 }
1730
1731 #[test]
1732 fn lint_toml_multiple_errors() {
1733 let toml = r##"
1734name = "Test"
1735author = "Me"
1736[light.defaults]
1737backround = "#ffffff"
1738[light.button]
1739primay_bg = "#0078d7"
1740"##;
1741 let warnings = Theme::lint_toml(toml).unwrap();
1742 assert_eq!(warnings.len(), 3);
1743 }
1744
1745 #[test]
1746 fn lint_toml_invalid_toml_returns_error() {
1747 let result = Theme::lint_toml("{{{{invalid");
1748 assert!(result.is_err());
1749 }
1750
1751 #[test]
1752 fn lint_toml_preset_has_no_warnings() {
1753 let theme = Theme::preset("material-3").expect("material-3 preset should load");
1755 let toml_str = theme.to_toml().expect("should serialize");
1756 let warnings = Theme::lint_toml(&toml_str).expect("should parse");
1757 assert!(
1758 warnings.is_empty(),
1759 "material-3 preset should have no lint warnings, got: {warnings:?}"
1760 );
1761 }
1762
1763 #[test]
1764 fn lint_toml_all_presets_clean() {
1765 for info in Theme::list_presets() {
1766 let name = info.key;
1767 let theme = Theme::preset(name).unwrap_or_else(|e| {
1770 panic!("preset {name} should load: {e}");
1771 });
1772 let toml_str = theme.to_toml().unwrap_or_else(|e| {
1773 panic!("preset {name} should serialize: {e}");
1774 });
1775 let warnings = Theme::lint_toml(&toml_str).unwrap_or_else(|e| {
1776 panic!("preset {name} should lint: {e}");
1777 });
1778 assert!(
1779 warnings.is_empty(),
1780 "preset {name} should have no lint warnings, got: {warnings:?}"
1781 );
1782 }
1783 }
1784
1785 #[test]
1786 fn lint_toml_accepts_padding_sides_and_shorthand() {
1787 let toml = r##"
1788name = "Test"
1789[light.button.border]
1790padding_top_px = 1.0
1791padding_right_px = 2.0
1792padding_bottom_px = 3.0
1793padding_left_px = 4.0
1794[light.input.border]
1795padding_horizontal_px = 6.0
1796padding_vertical_px = 0.0
1797"##;
1798 let warnings = Theme::lint_toml(toml).unwrap();
1799 assert!(warnings.is_empty(), "got: {warnings:?}");
1800 let warnings =
1801 Theme::lint_toml("name = \"T\"\n[light.input.border]\npadding_sideways_px = 1.0\n")
1802 .unwrap();
1803 assert_eq!(warnings.len(), 1, "got: {warnings:?}");
1804 }
1805
1806 #[test]
1807 fn lint_toml_rejects_unknown_field_on_registered_widget() {
1808 let toml = r##"
1812name = "Test"
1813[light.button]
1814nonexistent_field = "#ff0000"
1815"##;
1816 let warnings = Theme::lint_toml(toml).unwrap();
1817 assert_eq!(warnings.len(), 1);
1818 assert!(warnings[0].contains("nonexistent_field"));
1819 assert!(warnings[0].contains("light.button"));
1820 }
1821
1822 #[test]
1823 fn lint_toml_recognizes_all_registered_widgets() {
1824 for entry in inventory::iter::<crate::resolve::WidgetFieldInfo> {
1827 let toml_str = format!("name = \"Test\"\n[light.{}]\n", entry.widget_name,);
1828 let warnings = Theme::lint_toml(&toml_str).unwrap();
1829 assert!(
1830 warnings.is_empty(),
1831 "widget '{}' should be recognized, got: {:?}",
1832 entry.widget_name,
1833 warnings,
1834 );
1835 }
1836 }
1837
1838 #[test]
1841 fn theme_spec_layout_merge() {
1842 let mut base = Theme {
1843 name: "Base".into(),
1844 ..Theme::default()
1845 };
1846 base.layout.widget_gap = Some(6.0);
1847
1848 let mut overlay = Theme {
1849 name: "Overlay".into(),
1850 ..Theme::default()
1851 };
1852 overlay.layout.container_margin = Some(8.0);
1853
1854 base.merge(&overlay);
1855 assert_eq!(base.layout.widget_gap, Some(6.0));
1856 assert_eq!(base.layout.container_margin, Some(8.0));
1857 }
1858
1859 #[test]
1860 fn theme_spec_layout_toml_round_trip() {
1861 let mut theme = Theme {
1862 name: "Layout Test".into(),
1863 ..Theme::default()
1864 };
1865 theme.layout.widget_gap = Some(8.0);
1866 theme.layout.container_margin = Some(12.0);
1867 theme.layout.window_margin = Some(16.0);
1868 theme.layout.section_gap = Some(24.0);
1869
1870 let toml_str = theme.to_toml().unwrap();
1871 let theme2 = Theme::from_toml(&toml_str).unwrap();
1872 assert_eq!(theme.layout, theme2.layout);
1873 }
1874
1875 #[test]
1876 fn theme_spec_is_empty_with_layout() {
1877 let mut theme = Theme {
1878 name: "Layout Only".into(),
1879 ..Theme::default()
1880 };
1881 assert!(theme.is_empty()); theme.layout.widget_gap = Some(8.0);
1883 assert!(!theme.is_empty());
1884 }
1885
1886 #[test]
1887 fn theme_spec_layout_top_level_toml() {
1888 let mut theme = Theme {
1889 name: "Top Level".into(),
1890 ..Theme::default()
1891 };
1892 theme.layout.widget_gap = Some(8.0);
1893
1894 let toml_str = theme.to_toml().unwrap();
1895 assert!(
1897 toml_str.contains("[layout]"),
1898 "TOML should have [layout] section"
1899 );
1900 assert!(!toml_str.contains("[light.layout]"));
1901 assert!(!toml_str.contains("[dark.layout]"));
1902 }
1903
1904 fn field_info_entry(name: &'static str) -> Option<&'static [&'static str]> {
1913 inventory::iter::<crate::resolve::FieldInfo>()
1914 .find(|info| info.struct_name == name)
1915 .map(|info| info.field_names)
1916 }
1917
1918 #[test]
1919 fn font_spec_field_info_matches_baseline() {
1920 let baseline: &[&str] = &["family", "size_pt", "size_px", "weight", "style", "color"];
1921 assert_eq!(field_info_entry("FontSpec"), Some(baseline));
1922 }
1923
1924 #[test]
1925 fn text_scale_entry_field_info_matches_baseline() {
1926 let baseline: &[&str] = &[
1927 "size_pt",
1928 "size_px",
1929 "weight",
1930 "line_height_pt",
1931 "line_height_px",
1932 ];
1933 assert_eq!(field_info_entry("TextScaleEntry"), Some(baseline));
1934 }
1935
1936 #[test]
1937 fn text_scale_field_info_matches_baseline() {
1938 let baseline: &[&str] = &["caption", "section_heading", "dialog_title", "display"];
1939 assert_eq!(field_info_entry("TextScale"), Some(baseline));
1940 }
1941
1942 #[test]
1943 fn defaults_border_spec_field_info_matches_baseline() {
1944 let baseline: &[&str] = &[
1945 "color",
1946 "corner_radius_px",
1947 "corner_radius_lg_px",
1948 "line_width_px",
1949 "opacity",
1950 "shadow_enabled",
1951 ];
1952 assert_eq!(field_info_entry("DefaultsBorderSpec"), Some(baseline));
1953 }
1954
1955 #[test]
1956 fn widget_border_spec_field_info_matches_baseline() {
1957 let baseline: &[&str] = &[
1958 "color",
1959 "corner_radius_px",
1960 "line_width_px",
1961 "shadow_enabled",
1962 "padding_top_px",
1963 "padding_right_px",
1964 "padding_bottom_px",
1965 "padding_left_px",
1966 "padding_horizontal_px",
1967 "padding_vertical_px",
1968 ];
1969 assert_eq!(field_info_entry("WidgetBorderSpec"), Some(baseline));
1970 }
1971
1972 #[test]
1973 fn theme_defaults_field_info_matches_baseline() {
1974 let baseline: &[&str] = &[
1975 "font",
1976 "line_height",
1977 "mono_font",
1978 "background_color",
1979 "text_color",
1980 "accent_color",
1981 "accent_text_color",
1982 "surface_color",
1983 "muted_color",
1984 "shadow_color",
1985 "link_color",
1986 "selection_background",
1987 "selection_text_color",
1988 "selection_inactive_background",
1989 "text_selection_background",
1990 "text_selection_color",
1991 "disabled_text_color",
1992 "danger_color",
1993 "danger_text_color",
1994 "warning_color",
1995 "warning_text_color",
1996 "success_color",
1997 "success_text_color",
1998 "info_color",
1999 "info_text_color",
2000 "border",
2001 "disabled_opacity",
2002 "focus_ring_color",
2003 "focus_ring_width_px",
2004 "focus_ring_offset_px",
2005 "icon_sizes",
2006 "icon_theme",
2007 ];
2008 assert_eq!(field_info_entry("ThemeDefaults"), Some(baseline));
2009 }
2010
2011 #[test]
2012 fn icon_sizes_field_info_matches_baseline() {
2013 let baseline: &[&str] = &[
2014 "toolbar_px",
2015 "small_px",
2016 "large_px",
2017 "dialog_px",
2018 "panel_px",
2019 ];
2020 assert_eq!(field_info_entry("IconSizes"), Some(baseline));
2021 }
2022
2023 #[test]
2024 fn layout_theme_field_info_matches_baseline() {
2025 let baseline: &[&str] = &[
2026 "widget_gap_px",
2027 "container_margin_px",
2028 "window_margin_px",
2029 "section_gap_px",
2030 ];
2031 assert_eq!(field_info_entry("LayoutTheme"), Some(baseline));
2032 }
2033
2034 #[test]
2035 fn widget_registry_still_has_all_widgets() {
2036 let widget_count = inventory::iter::<crate::resolve::WidgetFieldInfo>().count();
2041 assert!(
2042 widget_count >= 25,
2043 "expected >=25 widgets in WidgetFieldInfo, got {widget_count}"
2044 );
2045 }
2046
2047 #[test]
2055 fn property_registry_keys_match_derive_inventory() {
2056 use std::collections::BTreeSet;
2057
2058 let registry: toml::Table = include_str!("../../../docs/property-registry.toml")
2059 .parse()
2060 .expect("docs/property-registry.toml is valid TOML");
2061
2062 let struct_fields = |names: &[&'static str]| -> BTreeSet<String> {
2063 names
2064 .iter()
2065 .filter_map(|name| field_info_entry(name))
2066 .flat_map(|fields| fields.iter().map(|f| (*f).to_string()))
2067 .collect()
2068 };
2069 let table_keys = |value: Option<&toml::Value>| -> Option<BTreeSet<String>> {
2070 value
2071 .and_then(|v| v.as_table())
2072 .map(|t| t.keys().cloned().collect())
2073 };
2074
2075 const STRUCTURES: &[(&str, &[&str])] = &[
2078 ("Font", &["FontSpec"]),
2079 ("Border", &["DefaultsBorderSpec", "WidgetBorderSpec"]),
2080 ("IconSizes", &["IconSizes"]),
2081 ("TextScaleEntry", &["TextScaleEntry"]),
2082 ];
2083 const STRUCT_TABLES: &[(&str, &[&str])] = &[
2084 ("defaults", &["ThemeDefaults"]),
2085 ("text_scale", &["TextScale"]),
2086 ("layout", &["LayoutTheme"]),
2087 ];
2088 const SKIPPED_TABLES: &[&str] = &["theme_variant"];
2089
2090 fn compare(
2091 drift: &mut Vec<String>,
2092 table: &str,
2093 registry: Option<BTreeSet<String>>,
2094 code: &BTreeSet<String>,
2095 ) {
2096 let Some(registry) = registry else {
2097 drift.push(format!("[{table}] is missing"));
2098 return;
2099 };
2100 for key in registry.difference(code) {
2101 drift.push(format!("[{table}] {key}: in the registry, not in the code"));
2102 }
2103 for key in code.difference(®istry) {
2104 drift.push(format!("[{table}] {key}: in the code, not in the registry"));
2105 }
2106 }
2107
2108 let mut drift: Vec<String> = Vec::new();
2109
2110 let structures = registry
2111 .get("_structures")
2112 .and_then(|v| v.as_table())
2113 .expect("[_structures] exists");
2114 for name in structures.keys() {
2115 if !STRUCTURES.iter().any(|(n, _)| n == name) {
2116 drift.push(format!(
2117 "[_structures.{name}] maps to no struct in the test"
2118 ));
2119 }
2120 }
2121 for (name, structs) in STRUCTURES {
2122 let code = struct_fields(structs);
2123 assert!(!code.is_empty(), "no FieldInfo entry for {structs:?}");
2124 compare(
2125 &mut drift,
2126 &format!("_structures.{name}"),
2127 table_keys(structures.get(*name)),
2128 &code,
2129 );
2130 }
2131
2132 for (table, structs) in STRUCT_TABLES {
2133 let code = struct_fields(structs);
2134 assert!(!code.is_empty(), "no FieldInfo entry for {structs:?}");
2135 compare(&mut drift, table, table_keys(registry.get(*table)), &code);
2136 }
2137
2138 let mut widget_count = 0usize;
2139 for info in inventory::iter::<crate::resolve::WidgetFieldInfo>() {
2140 widget_count += 1;
2141 let code: BTreeSet<String> =
2142 info.field_names.iter().map(|f| (*f).to_string()).collect();
2143 compare(
2144 &mut drift,
2145 info.widget_name,
2146 table_keys(registry.get(info.widget_name)),
2147 &code,
2148 );
2149 }
2150 assert!(
2151 widget_count >= 25,
2152 "expected >=25 widgets, got {widget_count}"
2153 );
2154
2155 for table in registry.keys() {
2156 let known = table == "_structures"
2157 || SKIPPED_TABLES.contains(&table.as_str())
2158 || STRUCT_TABLES.iter().any(|(t, _)| t == table)
2159 || inventory::iter::<crate::resolve::WidgetFieldInfo>()
2160 .any(|info| info.widget_name == table);
2161 if !known {
2162 drift.push(format!(
2163 "[{table}] is in the registry, but no widget or struct"
2164 ));
2165 }
2166 }
2167
2168 assert!(
2169 drift.is_empty(),
2170 "docs/property-registry.toml diverges from the derive inventory:\n{}",
2171 drift.join("\n")
2172 );
2173 }
2174}