1use std::fmt;
4
5#[cfg(target_os = "linux")]
6use crate::detect::{LinuxDesktop, parse_linux_desktop};
7
8#[cfg(any(target_os = "linux", test))]
9use crate::ReaderOutput;
10use crate::model::Theme;
11use crate::{OverlaySource, ReaderResult, SystemTheme};
12
13pub(crate) fn run_pipeline(reader: ReaderResult, preset_name: &str) -> crate::Result<SystemTheme> {
24 let mode = reader.output.mode();
25 let ReaderResult {
26 output: reader_output,
27 name: reader_name,
28 icon_set: reader_icon_set,
29 layout: reader_layout,
30 font_dpi,
31 accessibility,
32 } = reader;
33
34 let context = match font_dpi {
39 Some(dpi) => crate::resolve::ResolutionContext::with_font_dpi(
40 dpi,
41 crate::detect::system_icon_theme(),
42 ),
43 None => crate::resolve::ResolutionContext::from_system(),
44 };
45
46 let source = OverlaySource {
47 reader_output,
48 name: reader_name,
49 icon_set: reader_icon_set,
50 layout: reader_layout,
51 preset_name: preset_name.to_string(),
52 context,
53 overlay: None,
54 };
55 replay(source, mode, accessibility)
56}
57
58pub(crate) fn replay(
64 source: OverlaySource,
65 mode: crate::ColorMode,
66 accessibility: crate::AccessibilityPreferences,
67) -> crate::Result<SystemTheme> {
68 let mut merged = Theme::preset(&source.preset_name)?;
71 merged.merge(
72 &source
73 .reader_output
74 .to_theme(&source.name, source.icon_set, &source.layout),
75 );
76 if let Some(overlay) = &source.overlay {
77 merged.merge(overlay);
78 }
79
80 let name = if source.name.is_empty() {
82 merged.name.clone()
83 } else {
84 source.name.clone()
85 };
86
87 let icon_set = merged
89 .icon_set
90 .unwrap_or_else(crate::detect::system_icon_set);
91
92 let icon_theme_of =
102 |variant: &Option<crate::model::ThemeMode>| -> Option<std::borrow::Cow<'static, str>> {
103 variant
104 .as_ref()
105 .and_then(|v| v.defaults.icon_theme.clone()) .or_else(|| merged.icon_theme.clone()) .or_else(|| source.context.icon_theme.clone()) };
109 let light_icon_theme = icon_theme_of(&merged.light);
110 let dark_icon_theme = icon_theme_of(&merged.dark);
111 let icon_theme = match mode {
112 crate::ColorMode::Light => light_icon_theme.clone(),
113 crate::ColorMode::Dark => dark_icon_theme.clone(),
114 };
115
116 crate::resolve::validate_helpers::check_font_dpi(source.context.font_dpi)?;
118 crate::resolve::validate_helpers::check_layout(&merged.layout)?;
119
120 let light = merged
121 .light
122 .unwrap_or_default()
123 .into_resolved(&source.context)
124 .map_err(|e| e.in_variant(crate::ColorMode::Light))?;
125 let dark = merged
126 .dark
127 .unwrap_or_default()
128 .into_resolved(&source.context)
129 .map_err(|e| e.in_variant(crate::ColorMode::Dark))?;
130
131 Ok(SystemTheme {
132 name,
133 mode,
134 light,
135 dark,
136 preset: source.preset_name.clone(),
137 overlay_source: source,
138 version_match: None,
139 icon_set,
140 icon_theme,
141 light_icon_theme,
142 dark_icon_theme,
143 layout: merged.layout,
144 accessibility,
145 })
146}
147
148#[derive(Clone, Debug, PartialEq, Eq)]
172#[non_exhaustive]
173pub enum DiagnosticEntry {
174 Platform(&'static str),
176 #[cfg(target_os = "linux")]
178 DesktopEnv(crate::detect::LinuxDesktop),
179 EnvVar {
181 name: &'static str,
183 value: String,
185 },
186 EnvVarMissing(&'static str),
188 ToolAvailable {
190 name: &'static str,
192 version: String,
194 },
195 ToolError(&'static str),
197 ToolMissing {
199 name: &'static str,
201 impact: &'static str,
203 },
204 ConfigFound {
206 name: &'static str,
208 path: std::path::PathBuf,
210 },
211 ConfigMissing {
213 name: &'static str,
215 path: std::path::PathBuf,
217 },
218 FeatureEnabled(&'static str),
220 FeatureDisabled {
222 feature: &'static str,
224 impact: &'static str,
226 },
227 OsGeneration {
230 version: String,
232 preset: &'static str,
234 version_match: VersionMatch,
236 },
237}
238
239impl DiagnosticEntry {
240 #[must_use]
245 pub fn name(&self) -> &str {
246 match self {
247 Self::Platform(_) => "Platform",
248 #[cfg(target_os = "linux")]
249 Self::DesktopEnv(_) => "Detected DE",
250 Self::EnvVar { name, .. } | Self::EnvVarMissing(name) => name,
251 Self::ToolAvailable { name, .. }
252 | Self::ToolError(name)
253 | Self::ToolMissing { name, .. } => name,
254 Self::ConfigFound { name, .. } | Self::ConfigMissing { name, .. } => name,
255 Self::FeatureEnabled(feature) | Self::FeatureDisabled { feature, .. } => feature,
256 Self::OsGeneration { .. } => "OS version",
257 }
258 }
259
260 #[must_use]
263 pub fn status(&self) -> &str {
264 match self {
265 Self::Platform(p) => p,
266 #[cfg(target_os = "linux")]
267 Self::DesktopEnv(_) => "detected",
268 Self::EnvVar { value, .. } => value.as_str(),
269 Self::EnvVarMissing(_) => "not set",
270 Self::ToolAvailable { .. } => "available",
271 Self::ToolError(_) => "found but returned error",
272 Self::ToolMissing { .. } => "not found",
273 Self::ConfigFound { .. } => "found",
274 Self::ConfigMissing { .. } => "not found",
275 Self::FeatureEnabled(_) => "enabled",
276 Self::FeatureDisabled { .. } => "disabled",
277 Self::OsGeneration { version, .. } => version.as_str(),
278 }
279 }
280
281 #[must_use]
283 pub fn detail(&self) -> Option<String> {
284 match self {
285 #[cfg(target_os = "linux")]
286 Self::DesktopEnv(de) => Some(format!("{de:?}")),
287 Self::ToolAvailable { version, .. } => Some(version.clone()),
288 Self::ToolMissing { impact, .. } => Some((*impact).to_string()),
289 Self::FeatureDisabled { impact, .. } => Some((*impact).to_string()),
290 Self::ConfigFound { path, .. } | Self::ConfigMissing { path, .. } => {
291 Some(path.display().to_string())
292 }
293 Self::OsGeneration {
294 preset,
295 version_match,
296 ..
297 } => Some(format!("{preset}, {version_match}")),
298 _ => None,
299 }
300 }
301}
302
303impl fmt::Display for DiagnosticEntry {
304 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
305 match self {
306 Self::Platform(p) => write!(f, "Platform: {p}"),
307 #[cfg(target_os = "linux")]
308 Self::DesktopEnv(de) => write!(f, "Detected DE: {de:?}"),
309 Self::EnvVar { name, value } => write!(f, "{name}: {value}"),
310 Self::EnvVarMissing(name) => write!(f, "{name}: not set"),
311 Self::ToolAvailable { name, version } => {
312 write!(f, "{name}: available ({version})")
313 }
314 Self::ToolError(name) => write!(f, "{name}: found but returned error"),
315 Self::ToolMissing { name, impact } => write!(f, "{name}: not found ({impact})"),
316 Self::ConfigFound { name, path } => {
317 write!(f, "{name}: found at {}", path.display())
318 }
319 Self::ConfigMissing { name, path } => {
320 write!(f, "{name}: not found at {}", path.display())
321 }
322 Self::FeatureEnabled(feature) => write!(f, "{feature} support: enabled"),
323 Self::FeatureDisabled { feature, impact } => {
324 write!(f, "{feature} support: disabled ({impact})")
325 }
326 Self::OsGeneration {
327 version,
328 preset,
329 version_match,
330 } => write!(f, "OS version: {version} ({preset}, {version_match})"),
331 }
332 }
333}
334
335#[derive(Clone, Debug, PartialEq, Eq)]
343pub struct PlatformPreset {
344 pub name: &'static str,
346}
347
348impl fmt::Display for PlatformPreset {
349 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
350 f.write_str(self.name)
351 }
352}
353
354#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
362#[non_exhaustive]
363pub enum VersionMatch {
364 Exact,
367 PresetOlder,
371 PresetNewer,
374}
375
376impl VersionMatch {
377 #[must_use]
380 pub fn as_str(self) -> &'static str {
381 match self {
382 Self::Exact => "exact",
383 Self::PresetOlder => "preset older than the OS",
384 Self::PresetNewer => "preset newer than the OS",
385 }
386 }
387}
388
389impl fmt::Display for VersionMatch {
390 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
391 f.write_str(self.as_str())
392 }
393}
394
395#[cfg_attr(
398 not(any(
399 all(target_os = "macos", feature = "macos"),
400 all(target_os = "windows", feature = "windows")
401 )),
402 allow(dead_code)
403)]
404#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
405pub(crate) struct OsVersion {
406 pub(crate) major: u32,
407 pub(crate) minor: u32,
408 pub(crate) build: u32,
409}
410
411impl OsVersion {
412 #[cfg_attr(
413 not(any(
414 all(target_os = "macos", feature = "macos"),
415 all(target_os = "windows", feature = "windows")
416 )),
417 allow(dead_code)
418 )]
419 pub(crate) const fn new(major: u32, minor: u32, build: u32) -> Self {
420 Self {
421 major,
422 minor,
423 build,
424 }
425 }
426}
427
428impl fmt::Display for OsVersion {
429 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
430 write!(f, "{}.{}.{}", self.major, self.minor, self.build)
431 }
432}
433
434#[cfg_attr(
438 not(any(
439 all(target_os = "macos", feature = "macos"),
440 all(target_os = "windows", feature = "windows")
441 )),
442 allow(dead_code)
443)]
444#[derive(Clone, Copy, Debug, PartialEq, Eq)]
445pub(crate) struct Generation {
446 pub(crate) preset: &'static str,
447 pub(crate) first: OsVersion,
448 pub(crate) last_verified: OsVersion,
449}
450
451#[cfg_attr(
453 not(any(
454 all(target_os = "macos", feature = "macos"),
455 all(target_os = "windows", feature = "windows")
456 )),
457 allow(dead_code)
458)]
459#[derive(Clone, Copy, Debug)]
460pub(crate) struct GenerationTable {
461 pub(crate) oldest: Generation,
462 pub(crate) newer: &'static [Generation],
464 pub(crate) keys: &'static [&'static str],
468}
469
470#[cfg_attr(
471 not(any(
472 all(target_os = "macos", feature = "macos"),
473 all(target_os = "windows", feature = "windows")
474 )),
475 allow(dead_code)
476)]
477impl GenerationTable {
478 fn rows(&self) -> impl Iterator<Item = Generation> + '_ {
480 std::iter::once(self.oldest).chain(self.newer.iter().copied())
481 }
482
483 fn row(&self, preset: &str) -> Option<Generation> {
485 self.rows().find(|g| g.preset == preset)
486 }
487}
488
489#[cfg_attr(not(all(target_os = "macos", feature = "macos")), allow(dead_code))]
510pub(crate) const MACOS_GENERATIONS: GenerationTable = GenerationTable {
511 oldest: Generation {
512 preset: "macos-monterey",
513 first: OsVersion::new(12, 0, 0),
514 last_verified: OsVersion::new(15, 0, 0),
515 },
516 newer: &[Generation {
517 preset: "macos-tahoe",
518 first: OsVersion::new(26, 0, 0),
519 last_verified: OsVersion::new(26, 0, 0),
520 }],
521 keys: &["macos-monterey", "macos-tahoe"],
522};
523
524#[cfg_attr(not(all(target_os = "windows", feature = "windows")), allow(dead_code))]
530pub(crate) const WINDOWS_GENERATIONS: GenerationTable = GenerationTable {
531 oldest: Generation {
532 preset: "windows-11",
533 first: OsVersion::new(10, 0, 22000),
534 last_verified: OsVersion::new(10, 0, 26200),
535 },
536 newer: &[],
537 keys: &["windows-11"],
538};
539
540#[cfg_attr(
542 not(any(
543 all(target_os = "macos", feature = "macos"),
544 all(target_os = "windows", feature = "windows")
545 )),
546 allow(dead_code)
547)]
548pub(crate) fn version_match(row: &Generation, running: OsVersion) -> VersionMatch {
549 if running < row.first {
550 VersionMatch::PresetNewer
551 } else if running > row.last_verified {
552 VersionMatch::PresetOlder
553 } else {
554 VersionMatch::Exact
555 }
556}
557
558#[cfg_attr(
562 not(any(
563 all(target_os = "macos", feature = "macos"),
564 all(target_os = "windows", feature = "windows")
565 )),
566 allow(dead_code)
567)]
568pub(crate) fn preset_for_version(
569 table: &GenerationTable,
570 running: OsVersion,
571) -> (PlatformPreset, VersionMatch) {
572 let row = table
573 .newer
574 .iter()
575 .rev()
576 .find(|g| g.first <= running)
577 .copied()
578 .unwrap_or(table.oldest);
579 (
580 PlatformPreset { name: row.preset },
581 version_match(&row, running),
582 )
583}
584
585#[cfg_attr(not(all(target_os = "macos", feature = "macos")), allow(dead_code))]
587pub(crate) fn macos_major(running: OsVersion) -> OsVersion {
588 OsVersion::new(running.major, 0, 0)
589}
590
591#[cfg_attr(not(all(target_os = "macos", feature = "macos")), allow(dead_code))]
593pub(crate) fn macos_generation(running: OsVersion) -> (PlatformPreset, VersionMatch) {
594 preset_for_version(&MACOS_GENERATIONS, macos_major(running))
595}
596
597#[cfg_attr(not(all(target_os = "windows", feature = "windows")), allow(dead_code))]
599pub(crate) fn windows_generation(running: OsVersion) -> (PlatformPreset, VersionMatch) {
600 preset_for_version(&WINDOWS_GENERATIONS, running)
601}
602
603#[cfg(target_os = "linux")]
622pub(crate) fn linux_preset_for_de(de: LinuxDesktop) -> PlatformPreset {
623 match de {
624 LinuxDesktop::Kde => PlatformPreset { name: "kde-breeze" },
625 _ => PlatformPreset { name: "adwaita" },
626 }
627}
628
629#[must_use]
666pub fn platform_preset_name() -> PlatformPreset {
667 #[cfg(all(target_os = "macos", feature = "macos"))]
668 {
669 macos_generation(crate::macos::os_version()).0
670 }
671 #[cfg(all(target_os = "macos", not(feature = "macos")))]
674 {
675 PlatformPreset {
676 name: MACOS_GENERATIONS.oldest.preset,
677 }
678 }
679 #[cfg(all(target_os = "windows", feature = "windows"))]
680 {
681 windows_generation(crate::windows::os_version()).0
682 }
683 #[cfg(all(target_os = "windows", not(feature = "windows")))]
684 {
685 PlatformPreset {
686 name: WINDOWS_GENERATIONS.oldest.preset,
687 }
688 }
689 #[cfg(target_os = "linux")]
690 {
691 linux_preset_for_de(crate::detect::system().refined_linux_desktop_sync())
692 }
693 #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
694 {
695 PlatformPreset { name: "adwaita" }
696 }
697}
698
699#[must_use]
731pub fn diagnose_platform_support() -> Vec<DiagnosticEntry> {
732 let mut diagnostics = Vec::new();
733
734 #[cfg(target_os = "linux")]
735 {
736 diagnostics.push(DiagnosticEntry::Platform("Linux"));
737
738 match std::env::var("XDG_CURRENT_DESKTOP") {
740 Ok(val) if !val.is_empty() => {
741 let de = parse_linux_desktop(&val);
742 diagnostics.push(DiagnosticEntry::EnvVar {
743 name: "XDG_CURRENT_DESKTOP",
744 value: val,
745 });
746 diagnostics.push(DiagnosticEntry::DesktopEnv(de));
747 }
748 _ => {
749 diagnostics.push(DiagnosticEntry::EnvVarMissing("XDG_CURRENT_DESKTOP"));
750 diagnostics.push(DiagnosticEntry::DesktopEnv(LinuxDesktop::Unknown));
751 }
752 }
753
754 match crate::detect::run_with_timeout(
756 "gsettings",
757 &["--version"],
758 crate::detect::SUBPROCESS_TIMEOUT,
759 ) {
760 Ok(output) if output.status.success() => {
761 let version = String::from_utf8_lossy(&output.stdout).trim().to_string();
762 diagnostics.push(DiagnosticEntry::ToolAvailable {
763 name: "gsettings",
764 version,
765 });
766 }
767 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
768 diagnostics.push(DiagnosticEntry::ToolMissing {
769 name: "gsettings",
770 impact: "dark mode and icon theme detection may be limited",
771 });
772 }
773 Ok(_) | Err(_) => {
774 diagnostics.push(DiagnosticEntry::ToolError("gsettings"));
775 }
776 }
777
778 #[cfg(feature = "kde")]
780 {
781 match crate::kde::kdeglobals_path() {
782 Some(path) if path.exists() => {
783 diagnostics.push(DiagnosticEntry::ConfigFound {
784 name: "KDE kdeglobals",
785 path,
786 });
787 }
788 Some(path) => {
789 diagnostics.push(DiagnosticEntry::ConfigMissing {
790 name: "KDE kdeglobals",
791 path,
792 });
793 }
794 None => diagnostics.push(DiagnosticEntry::EnvVarMissing("HOME")),
795 }
796 }
797
798 #[cfg(not(feature = "kde"))]
799 {
800 diagnostics.push(DiagnosticEntry::FeatureDisabled {
801 feature: "KDE",
802 impact: "kde feature not enabled",
803 });
804 }
805
806 #[cfg(feature = "portal")]
808 diagnostics.push(DiagnosticEntry::FeatureEnabled("Portal"));
809
810 #[cfg(not(feature = "portal"))]
811 diagnostics.push(DiagnosticEntry::FeatureDisabled {
812 feature: "Portal",
813 impact: "portal feature not enabled",
814 });
815 }
816
817 #[cfg(target_os = "macos")]
818 {
819 diagnostics.push(DiagnosticEntry::Platform("macOS"));
820
821 #[cfg(feature = "macos")]
822 {
823 diagnostics.push(DiagnosticEntry::FeatureEnabled("macOS theme detection"));
824 let running = crate::macos::os_version();
825 let (preset, version_match) = macos_generation(running);
826 diagnostics.push(DiagnosticEntry::OsGeneration {
827 version: running.to_string(),
828 preset: preset.name,
829 version_match,
830 });
831 }
832
833 #[cfg(not(feature = "macos"))]
834 diagnostics.push(DiagnosticEntry::FeatureDisabled {
835 feature: "macOS theme detection",
836 impact: "macos feature not enabled, using subprocess fallback",
837 });
838 }
839
840 #[cfg(target_os = "windows")]
841 {
842 diagnostics.push(DiagnosticEntry::Platform("Windows"));
843
844 #[cfg(feature = "windows")]
845 {
846 diagnostics.push(DiagnosticEntry::FeatureEnabled("Windows theme detection"));
847 let running = crate::windows::os_version();
848 let (preset, version_match) = windows_generation(running);
849 diagnostics.push(DiagnosticEntry::OsGeneration {
850 version: running.to_string(),
851 preset: preset.name,
852 version_match,
853 });
854 }
855
856 #[cfg(not(feature = "windows"))]
857 diagnostics.push(DiagnosticEntry::FeatureDisabled {
858 feature: "Windows theme detection",
859 impact: "windows feature not enabled",
860 });
861 }
862
863 #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
864 {
865 diagnostics.push(DiagnosticEntry::Platform(
866 "unsupported (no native theme detection available)",
867 ));
868 }
869
870 diagnostics
871}
872
873#[cfg(any(target_os = "linux", test))]
876fn preset_as_reader(preset_name: &str, mode: crate::ColorMode) -> crate::Result<ReaderResult> {
877 let theme = Theme::preset(preset_name)?;
878 let is_dark = mode == crate::ColorMode::Dark;
879 let output = if is_dark {
880 ReaderOutput::Single {
881 mode: Box::new(theme.dark.unwrap_or_default()),
882 is_dark: true,
883 }
884 } else {
885 ReaderOutput::Single {
886 mode: Box::new(theme.light.unwrap_or_default()),
887 is_dark: false,
888 }
889 };
890 Ok(ReaderResult {
891 output,
892 name: theme.name,
893 icon_set: theme.icon_set,
894 layout: theme.layout,
895 font_dpi: None,
896 accessibility: crate::AccessibilityPreferences::default(),
897 })
898}
899
900pub(crate) struct SelectedReader {
903 pub(crate) reader: Box<dyn crate::reader::ThemeReader>,
905 pub(crate) preset: &'static str,
907 pub(crate) version_match: Option<VersionMatch>,
909}
910
911impl SelectedReader {
912 #[cfg_attr(
914 not(all(target_os = "linux", any(feature = "kde", feature = "portal"))),
915 allow(dead_code)
916 )]
917 fn unversioned(reader: Box<dyn crate::reader::ThemeReader>, preset: &'static str) -> Self {
918 Self {
919 reader,
920 preset,
921 version_match: None,
922 }
923 }
924}
925
926#[allow(unreachable_code)]
941#[allow(clippy::unnecessary_wraps)] #[allow(clippy::needless_return)] pub(crate) async fn select_reader() -> Option<SelectedReader> {
944 #[cfg(target_os = "macos")]
945 {
946 #[cfg(feature = "macos")]
947 {
948 let (preset, matched) = macos_generation(crate::macos::os_version());
949 return Some(SelectedReader {
950 reader: Box::new(crate::macos::MacosReader),
951 preset: preset.name,
952 version_match: Some(matched),
953 });
954 }
955 #[cfg(not(feature = "macos"))]
956 return None;
957 }
958
959 #[cfg(target_os = "windows")]
960 {
961 #[cfg(feature = "windows")]
962 {
963 let (preset, matched) = windows_generation(crate::windows::os_version());
964 return Some(SelectedReader {
965 reader: Box::new(crate::windows::WindowsReader),
966 preset: preset.name,
967 version_match: Some(matched),
968 });
969 }
970 #[cfg(not(feature = "windows"))]
971 return None;
972 }
973
974 #[cfg(target_os = "linux")]
975 {
976 return linux_reader(crate::detect::system().refined_linux_desktop().await);
977 }
978
979 #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
980 {
981 None
982 }
983}
984
985#[cfg(target_os = "linux")]
987#[derive(Debug, Clone, Copy, PartialEq, Eq)]
988enum LinuxReader {
989 #[cfg(feature = "kde")]
991 Kde,
992 #[cfg(all(feature = "kde", feature = "portal"))]
995 PortalKde,
996 #[cfg(feature = "portal")]
998 Gnome,
999}
1000
1001#[cfg(target_os = "linux")]
1010fn linux_reader_kind(refined: crate::detect::RefinedDesktop) -> Option<LinuxReader> {
1011 match refined.desktop {
1012 #[cfg(all(feature = "kde", feature = "portal"))]
1013 LinuxDesktop::Kde if refined.by_kdeglobals => Some(LinuxReader::Kde),
1014 #[cfg(all(feature = "kde", feature = "portal"))]
1015 LinuxDesktop::Kde => Some(LinuxReader::PortalKde),
1016 #[cfg(all(feature = "kde", not(feature = "portal")))]
1017 LinuxDesktop::Kde => Some(LinuxReader::Kde),
1018 #[cfg(not(feature = "kde"))]
1019 LinuxDesktop::Kde => None,
1020 #[cfg(feature = "portal")]
1021 LinuxDesktop::Gnome | LinuxDesktop::Budgie => Some(LinuxReader::Gnome),
1022 #[cfg(not(feature = "portal"))]
1023 LinuxDesktop::Gnome | LinuxDesktop::Budgie => None,
1024 LinuxDesktop::Xfce
1025 | LinuxDesktop::Cinnamon
1026 | LinuxDesktop::Mate
1027 | LinuxDesktop::LxQt
1028 | LinuxDesktop::Hyprland
1029 | LinuxDesktop::Sway
1030 | LinuxDesktop::River
1031 | LinuxDesktop::Niri
1032 | LinuxDesktop::Wayfire
1033 | LinuxDesktop::CosmicDe
1034 | LinuxDesktop::Unknown => None,
1035 }
1036}
1037
1038#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
1040fn linux_reader(refined: crate::detect::RefinedDesktop) -> Option<SelectedReader> {
1041 let reader: Box<dyn crate::reader::ThemeReader> = match linux_reader_kind(refined)? {
1042 #[cfg(feature = "kde")]
1043 LinuxReader::Kde => Box::new(crate::kde::KdeReader),
1044 #[cfg(all(feature = "kde", feature = "portal"))]
1045 LinuxReader::PortalKde => Box::new(crate::gnome::GnomePortalKdeReader),
1046 #[cfg(feature = "portal")]
1047 LinuxReader::Gnome => Box::new(crate::gnome::GnomeReader),
1048 };
1049 Some(SelectedReader::unversioned(
1050 reader,
1051 linux_preset_for_de(refined.desktop).name,
1052 ))
1053}
1054
1055#[cfg(all(target_os = "linux", not(any(feature = "kde", feature = "portal"))))]
1058fn linux_reader(refined: crate::detect::RefinedDesktop) -> Option<SelectedReader> {
1059 match linux_reader_kind(refined)? {}
1060}
1061
1062#[allow(unreachable_code)]
1074#[allow(clippy::needless_return)] pub(crate) async fn from_system_inner() -> crate::Result<SystemTheme> {
1076 if let Some(selected) = select_reader().await {
1077 let mut theme = read_through_pipeline(
1078 selected.reader.as_ref(),
1079 selected.preset,
1080 crate::detect::system(),
1081 )
1082 .await?;
1083 theme.version_match = selected.version_match;
1084 return Ok(theme);
1085 }
1086
1087 #[cfg(target_os = "macos")]
1090 {
1091 return Err(crate::Error::FeatureDisabled {
1092 name: "macos",
1093 needed_for: "macOS theme detection",
1094 });
1095 }
1096 #[cfg(target_os = "windows")]
1097 {
1098 return Err(crate::Error::FeatureDisabled {
1099 name: "windows",
1100 needed_for: "Windows theme detection",
1101 });
1102 }
1103 #[cfg(target_os = "linux")]
1104 {
1105 return linux_fallback(
1106 platform_preset_name(),
1107 crate::detect::detect_is_dark(),
1108 readerless_accessibility(),
1109 );
1110 }
1111 #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
1112 {
1113 Err(crate::Error::PlatformUnsupported {
1114 platform: std::env::consts::OS,
1115 })
1116 }
1117}
1118
1119#[cfg(target_os = "linux")]
1125fn linux_fallback(
1126 preset: PlatformPreset,
1127 is_dark: bool,
1128 accessibility: crate::AccessibilityPreferences,
1129) -> crate::Result<SystemTheme> {
1130 let mode = if is_dark {
1131 crate::ColorMode::Dark
1132 } else {
1133 crate::ColorMode::Light
1134 };
1135 let mut reader = preset_as_reader(preset.name, mode)?;
1136 reader.accessibility = accessibility;
1137 run_pipeline(reader, preset.name)
1138}
1139
1140async fn read_through_pipeline(
1144 reader: &dyn crate::reader::ThemeReader,
1145 preset: &str,
1146 detection: &crate::detect::DetectionContext,
1147) -> crate::Result<SystemTheme> {
1148 let fill = detection.begin_reader_accessibility();
1149 let result = reader.read().await?;
1150 detection.store_reader_accessibility(fill, result.accessibility.clone());
1151 run_pipeline(result, preset)
1152}
1153
1154#[allow(unreachable_code)]
1157#[allow(clippy::needless_return)]
1158#[cfg_attr(
1161 any(
1162 all(target_os = "macos", not(feature = "macos")),
1163 all(target_os = "windows", not(feature = "windows"))
1164 ),
1165 allow(unused_variables)
1166)]
1167pub(crate) async fn from_system_with_preset_inner(preset: &str) -> crate::Result<SystemTheme> {
1168 #[cfg(all(target_os = "macos", feature = "macos"))]
1169 {
1170 return pinned_pipeline(
1171 &MACOS_GENERATIONS,
1172 macos_major(crate::macos::os_version()),
1173 preset,
1174 &crate::macos::MacosReader,
1175 crate::detect::system(),
1176 )
1177 .await;
1178 }
1179 #[cfg(all(target_os = "windows", feature = "windows"))]
1180 {
1181 return pinned_pipeline(
1182 &WINDOWS_GENERATIONS,
1183 crate::windows::os_version(),
1184 preset,
1185 &crate::windows::WindowsReader,
1186 crate::detect::system(),
1187 )
1188 .await;
1189 }
1190 #[cfg(all(target_os = "macos", not(feature = "macos")))]
1191 {
1192 return Err(crate::Error::FeatureDisabled {
1193 name: "macos",
1194 needed_for: "macOS theme detection",
1195 });
1196 }
1197 #[cfg(all(target_os = "windows", not(feature = "windows")))]
1198 {
1199 return Err(crate::Error::FeatureDisabled {
1200 name: "windows",
1201 needed_for: "Windows theme detection",
1202 });
1203 }
1204 Err(crate::Error::UnknownPreset {
1207 name: preset.to_string(),
1208 known: &[],
1209 })
1210}
1211
1212#[cfg_attr(
1215 not(any(
1216 all(target_os = "macos", feature = "macos"),
1217 all(target_os = "windows", feature = "windows")
1218 )),
1219 allow(dead_code)
1220)]
1221async fn pinned_pipeline(
1222 table: &GenerationTable,
1223 running: OsVersion,
1224 preset: &str,
1225 reader: &dyn crate::reader::ThemeReader,
1226 detection: &crate::detect::DetectionContext,
1227) -> crate::Result<SystemTheme> {
1228 let Some(row) = table.row(preset) else {
1229 return Err(crate::Error::UnknownPreset {
1230 name: preset.to_string(),
1231 known: table.keys,
1232 });
1233 };
1234 let mut theme = read_through_pipeline(reader, row.preset, detection).await?;
1235 theme.version_match = Some(version_match(&row, running));
1236 Ok(theme)
1237}
1238
1239pub(crate) async fn reader_accessibility() -> crate::AccessibilityPreferences {
1243 match select_reader().await {
1244 Some(selected) => match selected.reader.read().await {
1245 Ok(result) => result.accessibility,
1246 Err(_) => readerless_accessibility(),
1247 },
1248 None => readerless_accessibility(),
1249 }
1250}
1251
1252fn readerless_accessibility() -> crate::AccessibilityPreferences {
1256 crate::AccessibilityPreferences {
1257 reduce_motion: crate::detect::detect_reduced_motion(),
1258 ..Default::default()
1259 }
1260}
1261
1262#[cfg(all(test, target_os = "linux"))]
1267#[allow(clippy::unwrap_used, clippy::expect_used)]
1268mod dispatch_tests {
1269 use super::*;
1270
1271 #[test]
1274 fn detect_kde_simple() {
1275 assert_eq!(parse_linux_desktop("KDE"), LinuxDesktop::Kde);
1276 }
1277
1278 #[test]
1279 fn detect_kde_colon_separated_after() {
1280 assert_eq!(parse_linux_desktop("ubuntu:KDE"), LinuxDesktop::Kde);
1281 }
1282
1283 #[test]
1284 fn detect_kde_colon_separated_before() {
1285 assert_eq!(parse_linux_desktop("KDE:plasma"), LinuxDesktop::Kde);
1286 }
1287
1288 #[test]
1289 fn detect_gnome_simple() {
1290 assert_eq!(parse_linux_desktop("GNOME"), LinuxDesktop::Gnome);
1291 }
1292
1293 #[test]
1294 fn detect_gnome_ubuntu() {
1295 assert_eq!(parse_linux_desktop("ubuntu:GNOME"), LinuxDesktop::Gnome);
1296 }
1297
1298 #[test]
1299 fn detect_xfce() {
1300 assert_eq!(parse_linux_desktop("XFCE"), LinuxDesktop::Xfce);
1301 }
1302
1303 #[test]
1304 fn detect_cinnamon() {
1305 assert_eq!(parse_linux_desktop("X-Cinnamon"), LinuxDesktop::Cinnamon);
1306 }
1307
1308 #[test]
1309 fn detect_cinnamon_short() {
1310 assert_eq!(parse_linux_desktop("Cinnamon"), LinuxDesktop::Cinnamon);
1311 }
1312
1313 #[test]
1314 fn detect_mate() {
1315 assert_eq!(parse_linux_desktop("MATE"), LinuxDesktop::Mate);
1316 }
1317
1318 #[test]
1319 fn detect_lxqt() {
1320 assert_eq!(parse_linux_desktop("LXQt"), LinuxDesktop::LxQt);
1321 }
1322
1323 #[test]
1324 fn detect_budgie() {
1325 assert_eq!(parse_linux_desktop("Budgie:GNOME"), LinuxDesktop::Budgie);
1326 }
1327
1328 #[test]
1329 fn detect_empty_string() {
1330 assert_eq!(parse_linux_desktop(""), LinuxDesktop::Unknown);
1331 }
1332
1333 #[test]
1336 fn from_linux_non_kde_returns_adwaita() -> crate::Result<()> {
1337 let preset = linux_preset_for_de(LinuxDesktop::Gnome);
1339 let result = preset_as_reader("adwaita", crate::ColorMode::Light)?;
1340 let theme = run_pipeline(result, preset.name)?;
1341 assert_eq!(theme.name, "Adwaita");
1342 Ok(())
1343 }
1344
1345 #[test]
1346 #[cfg(feature = "kde")]
1347 fn from_linux_unknown_de_with_kdeglobals_fallback() -> crate::Result<()> {
1348 const MINIMAL_KDE_FIXTURE: &str = "\
1351[General]
1352ColorScheme=TestTheme
1353
1354[Colors:Window]
1355BackgroundNormal=239,240,241
1356
1357[Colors:View]
1358BackgroundNormal=252,252,252
1359ForegroundNormal=35,38,41
1360DecorationFocus=61,174,233
1361BackgroundAlternate=239,240,241
1362ForegroundLink=41,128,185";
1363
1364 let (reader_theme, dpi, acc) =
1365 crate::kde::from_kde_content_pure(MINIMAL_KDE_FIXTURE, None)?;
1366 let is_dark = reader_theme.dark.is_some() && reader_theme.light.is_none();
1367 let output = if is_dark {
1368 ReaderOutput::Single {
1369 mode: Box::new(reader_theme.dark.unwrap_or_default()),
1370 is_dark: true,
1371 }
1372 } else {
1373 ReaderOutput::Single {
1374 mode: Box::new(reader_theme.light.unwrap_or_default()),
1375 is_dark: false,
1376 }
1377 };
1378 let result = ReaderResult {
1379 output,
1380 name: reader_theme.name,
1381 icon_set: reader_theme.icon_set,
1382 layout: reader_theme.layout,
1383 font_dpi: dpi,
1384 accessibility: acc,
1385 };
1386 let preset = linux_preset_for_de(LinuxDesktop::Kde);
1387 let theme = run_pipeline(result, preset.name)?;
1388 assert_eq!(
1389 theme.name, "TestTheme",
1390 "should use KDE theme name from reader output"
1391 );
1392 Ok(())
1393 }
1394
1395 #[test]
1396 fn from_linux_unknown_de_without_kdeglobals_returns_adwaita() -> crate::Result<()> {
1397 let preset = linux_preset_for_de(LinuxDesktop::Unknown);
1399 let result = preset_as_reader("adwaita", crate::ColorMode::Light)?;
1400 let theme = run_pipeline(result, preset.name)?;
1401 assert_eq!(
1402 theme.name, "Adwaita",
1403 "should fall back to Adwaita without kdeglobals"
1404 );
1405 Ok(())
1406 }
1407
1408 fn preset_theme(preset: &str) -> SystemTheme {
1410 let theme = Theme::preset(preset).unwrap();
1411 let reader = ReaderResult {
1412 output: ReaderOutput::Dual {
1413 light: Box::new(theme.light.unwrap_or_default()),
1414 dark: Box::new(theme.dark.unwrap_or_default()),
1415 is_dark: false,
1416 },
1417 name: theme.name,
1418 icon_set: theme.icon_set,
1419 layout: theme.layout,
1420 font_dpi: None,
1421 accessibility: crate::AccessibilityPreferences::default(),
1422 };
1423 run_pipeline(reader, preset).unwrap()
1424 }
1425
1426 #[test]
1427 fn the_fallback_on_kde_is_the_whole_breeze_preset() {
1428 let expected = preset_theme("kde-breeze");
1429 for is_dark in [false, true] {
1430 let st = linux_fallback(
1431 linux_preset_for_de(LinuxDesktop::Kde),
1432 is_dark,
1433 crate::AccessibilityPreferences::default(),
1434 )
1435 .unwrap();
1436 assert_eq!(st.preset, "kde-breeze");
1437 assert_eq!(st.name, expected.name, "is_dark {is_dark}");
1438 assert_eq!(st.light, expected.light, "is_dark {is_dark}");
1439 assert_eq!(st.dark, expected.dark, "is_dark {is_dark}");
1440 assert_eq!(
1441 st.icon_theme_for(crate::ColorMode::Light),
1442 expected.icon_theme_for(crate::ColorMode::Light)
1443 );
1444 assert_eq!(
1445 st.icon_theme_for(crate::ColorMode::Dark),
1446 expected.icon_theme_for(crate::ColorMode::Dark)
1447 );
1448 }
1449 }
1450
1451 #[test]
1452 fn the_fallback_on_other_desktops_is_the_whole_adwaita_preset() {
1453 let expected = preset_theme("adwaita");
1454 let st = linux_fallback(
1455 linux_preset_for_de(LinuxDesktop::Xfce),
1456 true,
1457 crate::AccessibilityPreferences::default(),
1458 )
1459 .unwrap();
1460 assert_eq!(st.preset, "adwaita");
1461 assert_eq!(st.name, expected.name);
1462 assert_eq!(st.light, expected.light);
1463 assert_eq!(st.dark, expected.dark);
1464 }
1465
1466 #[test]
1467 fn the_fallback_mode_is_the_dark_reading_it_is_given() {
1468 let preset = || linux_preset_for_de(LinuxDesktop::Unknown);
1469 let none = crate::AccessibilityPreferences::default;
1470 assert_eq!(
1471 linux_fallback(preset(), true, none()).unwrap().mode,
1472 crate::ColorMode::Dark
1473 );
1474 assert_eq!(
1475 linux_fallback(preset(), false, none()).unwrap().mode,
1476 crate::ColorMode::Light
1477 );
1478 }
1479
1480 #[test]
1484 fn the_fallback_carries_the_accessibility_it_is_given() {
1485 let reduced = crate::AccessibilityPreferences {
1486 reduce_motion: true,
1487 ..Default::default()
1488 };
1489 let st = linux_fallback(
1490 linux_preset_for_de(LinuxDesktop::Xfce),
1491 false,
1492 reduced.clone(),
1493 )
1494 .unwrap();
1495 assert_eq!(st.accessibility, reduced);
1496 }
1497
1498 #[test]
1499 fn an_unknown_desktop_with_kdeglobals_maps_to_breeze() {
1500 let preset = |de, exists| {
1501 linux_preset_for_de(crate::detect::refine_linux_desktop(de, None, || exists)).name
1502 };
1503 assert_eq!(preset(LinuxDesktop::Unknown, true), "kde-breeze");
1504 assert_eq!(preset(LinuxDesktop::Unknown, false), "adwaita");
1505 assert_eq!(preset(LinuxDesktop::Kde, false), "kde-breeze");
1506 assert_eq!(preset(LinuxDesktop::Gnome, true), "adwaita");
1507 assert_eq!(preset(LinuxDesktop::Xfce, true), "adwaita");
1508 }
1509
1510 fn unknown_desktop_reader(
1513 portal_backend: Option<LinuxDesktop>,
1514 kdeglobals: bool,
1515 ) -> Option<LinuxReader> {
1516 linux_reader_kind(crate::detect::refine_desktop(
1517 LinuxDesktop::Unknown,
1518 portal_backend,
1519 || kdeglobals,
1520 ))
1521 }
1522
1523 #[test]
1526 #[cfg(all(feature = "kde", feature = "portal"))]
1527 fn an_unknown_desktop_with_a_kde_portal_gets_the_kde_reader() {
1528 for kdeglobals in [false, true] {
1529 assert_eq!(
1530 unknown_desktop_reader(Some(LinuxDesktop::Kde), kdeglobals),
1531 Some(LinuxReader::PortalKde)
1532 );
1533 }
1534 assert_eq!(
1535 linux_reader_kind(crate::detect::refine_desktop(
1536 LinuxDesktop::Kde,
1537 None,
1538 || false
1539 )),
1540 Some(LinuxReader::PortalKde)
1541 );
1542 }
1543
1544 #[test]
1546 #[cfg(feature = "portal")]
1547 fn an_unknown_desktop_with_a_gnome_portal_gets_the_gnome_reader() {
1548 for kdeglobals in [false, true] {
1549 assert_eq!(
1550 unknown_desktop_reader(Some(LinuxDesktop::Gnome), kdeglobals),
1551 Some(LinuxReader::Gnome)
1552 );
1553 }
1554 }
1555
1556 #[test]
1559 fn an_unknown_desktop_without_a_portal_answer() {
1560 #[cfg(feature = "kde")]
1561 assert_eq!(unknown_desktop_reader(None, true), Some(LinuxReader::Kde));
1562 assert_eq!(unknown_desktop_reader(None, false), None);
1563 }
1564
1565 #[test]
1567 #[cfg(all(feature = "kde", feature = "portal"))]
1568 fn the_linux_readers_presets() {
1569 let preset = |portal_backend, kdeglobals| {
1570 linux_reader(crate::detect::refine_desktop(
1571 LinuxDesktop::Unknown,
1572 portal_backend,
1573 || kdeglobals,
1574 ))
1575 .map(|selected| selected.preset)
1576 };
1577 assert_eq!(preset(Some(LinuxDesktop::Kde), false), Some("kde-breeze"));
1578 assert_eq!(preset(None, true), Some("kde-breeze"));
1579 assert_eq!(preset(Some(LinuxDesktop::Gnome), true), Some("adwaita"));
1580 }
1581
1582 #[test]
1585 fn detect_hyprland() {
1586 assert_eq!(parse_linux_desktop("Hyprland"), LinuxDesktop::Hyprland);
1587 }
1588
1589 #[test]
1590 fn detect_sway() {
1591 assert_eq!(parse_linux_desktop("sway"), LinuxDesktop::Sway);
1592 }
1593
1594 #[test]
1595 fn detect_cosmic() {
1596 assert_eq!(parse_linux_desktop("COSMIC"), LinuxDesktop::CosmicDe);
1597 }
1598
1599 #[test]
1600 fn detect_river() {
1601 assert_eq!(parse_linux_desktop("river"), LinuxDesktop::River);
1602 }
1603
1604 #[test]
1605 fn detect_niri() {
1606 assert_eq!(parse_linux_desktop("niri"), LinuxDesktop::Niri);
1607 }
1608
1609 #[test]
1610 fn parses_xdg_wayfire() {
1611 assert_eq!(parse_linux_desktop("Wayfire"), LinuxDesktop::Wayfire);
1612 assert_eq!(parse_linux_desktop("Wayfire:GNOME"), LinuxDesktop::Wayfire);
1613 }
1614
1615 #[test]
1616 fn parses_xdg_empty_is_unknown() {
1617 assert_eq!(parse_linux_desktop(""), LinuxDesktop::Unknown);
1620 }
1621
1622 #[test]
1623 fn detect_cosmic_full_desktop() {
1624 assert_eq!(
1625 parse_linux_desktop("COSMIC:Freedesktop"),
1626 LinuxDesktop::CosmicDe
1627 );
1628 }
1629
1630 #[test]
1633 fn from_system_returns_result() {
1634 let result = preset_as_reader("adwaita", crate::ColorMode::Light).unwrap();
1636 let theme = run_pipeline(result, "adwaita")
1637 .expect("run_pipeline should succeed with adwaita preset");
1638 assert_eq!(theme.name, "Adwaita");
1639 }
1640}
1641
1642#[cfg(test)]
1646#[allow(
1647 clippy::unwrap_used,
1648 clippy::expect_used,
1649 clippy::field_reassign_with_default
1650)]
1651mod pipeline_tests {
1652 use crate::color::Rgba;
1653 use crate::model::{LayoutTheme, Theme, ThemeMode};
1654 use crate::{ReaderOutput, ReaderResult};
1655
1656 use super::{preset_as_reader, read_through_pipeline, run_pipeline};
1657
1658 fn reader_from_preset(preset_name: &str) -> ReaderResult {
1660 let preset = Theme::preset(preset_name).unwrap();
1661 ReaderResult {
1662 output: ReaderOutput::Dual {
1663 light: Box::new(preset.light.clone().unwrap_or_default()),
1664 dark: Box::new(preset.dark.clone().unwrap_or_default()),
1665 is_dark: false,
1666 },
1667 name: preset.name,
1668 icon_set: preset.icon_set,
1669 layout: preset.layout,
1670 font_dpi: None,
1671 accessibility: crate::AccessibilityPreferences::default(),
1672 }
1673 }
1674
1675 #[test]
1681 fn run_pipeline_rejects_a_bad_reader_font_dpi_once() {
1682 for font_dpi in [0.0, -1.0, f32::NAN] {
1683 let reader = ReaderResult {
1684 font_dpi: Some(font_dpi),
1685 ..reader_from_preset("kde-breeze")
1686 };
1687 let result = run_pipeline(reader, "kde-breeze");
1688 let Err(crate::Error::ResolutionInvalid { errors }) = result else {
1689 panic!("font_dpi {font_dpi}: expected ResolutionInvalid");
1690 };
1691 let paths: Vec<&str> = errors.iter().map(|rv| rv.path.as_str()).collect();
1692 assert_eq!(paths, ["context.font_dpi"], "font_dpi {font_dpi}");
1693 }
1694 }
1695
1696 #[test]
1697 fn test_run_pipeline_produces_both_variants() {
1698 let reader = reader_from_preset("catppuccin-mocha");
1699 let result = run_pipeline(reader, "catppuccin-mocha");
1700 assert!(result.is_ok(), "run_pipeline should succeed");
1701 let st = result.unwrap();
1702 assert!(!st.name.is_empty(), "name should be populated");
1704 }
1706
1707 #[test]
1708 fn test_run_pipeline_reader_values_win() {
1709 let custom_accent = Rgba::rgb(42, 100, 200);
1712 let mut variant = ThemeMode::default();
1713 variant.defaults.accent_color = Some(custom_accent);
1714
1715 let reader = ReaderResult {
1716 output: ReaderOutput::Single {
1717 mode: Box::new(variant),
1718 is_dark: false,
1719 },
1720 name: "CustomTheme".into(),
1721 icon_set: None,
1722 layout: LayoutTheme::default(),
1723 font_dpi: None,
1724 accessibility: crate::AccessibilityPreferences::default(),
1725 };
1726
1727 let result = run_pipeline(reader, "catppuccin-mocha");
1728 assert!(result.is_ok(), "run_pipeline should succeed");
1729 let st = result.unwrap();
1730 assert_eq!(
1732 st.light.defaults.accent_color, custom_accent,
1733 "reader accent should win over preset accent"
1734 );
1735 assert_eq!(st.name, "CustomTheme", "reader name should win");
1736 }
1737
1738 #[test]
1739 fn test_run_pipeline_single_variant() {
1740 let full = Theme::preset("kde-breeze").unwrap();
1743 let mut dark_v = full.dark.clone().unwrap();
1744 dark_v.defaults.accent_color = Some(Rgba::rgb(200, 50, 50));
1746
1747 let reader = ReaderResult {
1748 output: ReaderOutput::Single {
1749 mode: Box::new(dark_v),
1750 is_dark: true,
1751 },
1752 name: std::borrow::Cow::Borrowed(""),
1753 icon_set: None,
1754 layout: LayoutTheme::default(),
1755 font_dpi: None,
1756 accessibility: crate::AccessibilityPreferences::default(),
1757 };
1758
1759 let result = run_pipeline(reader, "kde-breeze");
1760 assert!(
1761 result.is_ok(),
1762 "run_pipeline should succeed with single variant"
1763 );
1764 let st = result.unwrap();
1765 assert_eq!(
1767 st.dark.defaults.accent_color,
1768 Rgba::rgb(200, 50, 50),
1769 "dark variant should have reader accent"
1770 );
1771 assert_eq!(st.preset, "kde-breeze");
1774 }
1775
1776 #[test]
1777 fn test_run_pipeline_inactive_variant_from_full_preset() {
1778 let full = Theme::preset("kde-breeze").unwrap();
1780
1781 let reader = ReaderResult {
1782 output: ReaderOutput::Single {
1783 mode: Box::new(full.dark.clone().unwrap_or_default()),
1784 is_dark: true,
1785 },
1786 name: std::borrow::Cow::Borrowed(""),
1787 icon_set: None,
1788 layout: LayoutTheme::default(),
1789 font_dpi: None,
1790 accessibility: crate::AccessibilityPreferences::default(),
1791 };
1792
1793 let st = run_pipeline(reader, "kde-breeze").unwrap();
1794
1795 let full_light = full.light.unwrap();
1797 assert_eq!(
1798 st.light.defaults.accent_color,
1799 full_light.defaults.accent_color.unwrap(),
1800 "inactive light variant should get accent from full preset"
1801 );
1802 assert_eq!(
1803 st.light.defaults.background_color,
1804 full_light.defaults.background_color.unwrap(),
1805 "inactive light variant should get background from full preset"
1806 );
1807 }
1808
1809 #[test]
1812 fn test_run_pipeline_with_preset_as_reader() {
1813 let reader = reader_from_preset("adwaita");
1816 let result = run_pipeline(reader, "adwaita");
1817 assert!(
1818 result.is_ok(),
1819 "double-merge with same preset should succeed"
1820 );
1821 let st = result.unwrap();
1822 assert_eq!(st.name, "Adwaita");
1823 }
1824
1825 #[test]
1828 fn with_overlay_keeps_an_earlier_overlay() -> crate::Result<()> {
1829 let st = run_pipeline(reader_from_preset("adwaita"), "adwaita")?;
1830 let a = Theme::from_toml("[light.defaults]\naccent_color = \"#ff0000\"")?;
1831 let b = Theme::from_toml("[light.defaults]\nbackground_color = \"#00ff00\"")?;
1832 let both = st.with_overlay(&a)?.with_overlay(&b)?;
1833 assert_eq!(both.light.defaults.accent_color, Rgba::rgb(255, 0, 0));
1834 assert_eq!(both.light.defaults.background_color, Rgba::rgb(0, 255, 0));
1835
1836 let c = Theme::from_toml("[light.defaults]\naccent_color = \"#0000ff\"")?;
1837 let all = both.with_overlay(&c)?;
1838 assert_eq!(all.light.defaults.accent_color, Rgba::rgb(0, 0, 255));
1839 assert_eq!(all.light.defaults.background_color, Rgba::rgb(0, 255, 0));
1840 Ok(())
1841 }
1842
1843 #[test]
1846 fn test_single_variant_fills_inactive_from_preset() {
1847 let full = Theme::preset("kde-breeze").unwrap();
1850 let dark_v = full.dark.clone().unwrap();
1851 let reader = ReaderResult {
1852 output: ReaderOutput::Single {
1853 mode: Box::new(dark_v),
1854 is_dark: true,
1855 },
1856 name: "Breeze Dark".into(),
1857 icon_set: full.icon_set,
1858 layout: full.layout.clone(),
1859 font_dpi: None,
1860 accessibility: crate::AccessibilityPreferences::default(),
1861 };
1862
1863 let st = run_pipeline(reader, "kde-breeze").unwrap();
1864
1865 let full_light = Theme::preset("kde-breeze").unwrap().light.unwrap();
1868 assert_eq!(
1869 st.light.defaults.accent_color,
1870 full_light.defaults.accent_color.unwrap(),
1871 "Single: inactive light variant should come from full preset"
1872 );
1873 assert_eq!(st.mode, crate::ColorMode::Dark);
1874 }
1875
1876 #[test]
1877 fn test_dual_variant_uses_both_from_reader() {
1878 let full = Theme::preset("macos-monterey").unwrap();
1881 let custom_light_accent = Rgba::rgb(42, 100, 200);
1882 let custom_dark_accent = Rgba::rgb(200, 50, 50);
1883
1884 let mut light_v = full.light.clone().unwrap();
1885 light_v.defaults.accent_color = Some(custom_light_accent);
1886 let mut dark_v = full.dark.clone().unwrap();
1887 dark_v.defaults.accent_color = Some(custom_dark_accent);
1888
1889 let reader = ReaderResult {
1890 output: ReaderOutput::Dual {
1891 light: Box::new(light_v),
1892 dark: Box::new(dark_v),
1893 is_dark: false,
1894 },
1895 name: "macOS Sonoma".into(),
1896 icon_set: full.icon_set,
1897 layout: full.layout.clone(),
1898 font_dpi: Some(72.0),
1899 accessibility: crate::AccessibilityPreferences::default(),
1900 };
1901
1902 let st = run_pipeline(reader, "macos-monterey").unwrap();
1903
1904 assert_eq!(
1906 st.light.defaults.accent_color, custom_light_accent,
1907 "Dual: light variant should have reader's light accent"
1908 );
1909 assert_eq!(
1910 st.dark.defaults.accent_color, custom_dark_accent,
1911 "Dual: dark variant should have reader's dark accent"
1912 );
1913 }
1914
1915 struct DarkDualReader;
1918
1919 #[async_trait::async_trait]
1920 impl crate::reader::ThemeReader for DarkDualReader {
1921 async fn read(&self) -> crate::Result<ReaderResult> {
1922 let mut reader = reader_from_preset("macos-monterey");
1923 if let ReaderOutput::Dual { is_dark, .. } = &mut reader.output {
1924 *is_dark = true;
1925 }
1926 Ok(reader)
1927 }
1928 }
1929
1930 #[test]
1931 fn dual_reader_mode_follows_is_dark() {
1932 let detection = crate::detect::DetectionContext::new();
1933 let st = pollster::block_on(read_through_pipeline(
1934 &DarkDualReader,
1935 "macos-monterey",
1936 &detection,
1937 ))
1938 .unwrap();
1939 assert_eq!(
1940 st.mode,
1941 crate::ColorMode::Dark,
1942 "a Dual reader reporting is_dark must give SystemTheme::mode Dark"
1943 );
1944 }
1945
1946 #[test]
1947 fn a_pinned_older_generation_reports_preset_older() {
1948 let detection = crate::detect::DetectionContext::new();
1949 let st = pollster::block_on(super::pinned_pipeline(
1950 &super::MACOS_GENERATIONS,
1951 super::OsVersion::new(26, 0, 0),
1952 "macos-monterey",
1953 &DarkDualReader,
1954 &detection,
1955 ))
1956 .unwrap();
1957 assert_eq!(st.preset, "macos-monterey");
1958 assert_eq!(st.version_match, Some(super::VersionMatch::PresetOlder));
1959 let overlaid = st
1961 .with_overlay(&Theme::from_toml("name = \"overlay\"").unwrap())
1962 .unwrap();
1963 assert_eq!(overlaid.version_match, st.version_match);
1964 }
1965
1966 #[test]
1967 fn a_pinned_name_outside_the_table_is_unknown() {
1968 let detection = crate::detect::DetectionContext::new();
1969 let result = pollster::block_on(super::pinned_pipeline(
1970 &super::MACOS_GENERATIONS,
1971 super::OsVersion::new(26, 0, 0),
1972 "kde-breeze",
1973 &DarkDualReader,
1974 &detection,
1975 ));
1976 assert!(matches!(
1977 result,
1978 Err(crate::Error::UnknownPreset { known, .. }) if known == super::MACOS_GENERATIONS.keys
1979 ));
1980 }
1981
1982 #[cfg(target_os = "linux")]
1983 #[test]
1984 fn linux_has_no_generation_to_pin() {
1985 let result = pollster::block_on(super::from_system_with_preset_inner("adwaita"));
1986 let err = result.err();
1987 assert!(matches!(
1988 err,
1989 Some(crate::Error::UnknownPreset { known: [], .. })
1990 ));
1991 assert!(
1992 err.is_some_and(|e| e
1993 .to_string()
1994 .contains("no OS generations to choose between")),
1995 "pinning a preset on Linux says the platform has no OS generations to choose between"
1996 );
1997 }
1998
1999 struct ScaledTextReader;
2002
2003 #[async_trait::async_trait]
2004 impl crate::reader::ThemeReader for ScaledTextReader {
2005 async fn read(&self) -> crate::Result<ReaderResult> {
2006 let mut reader = reader_from_preset("adwaita");
2007 reader.accessibility.text_scaling_factor = 1.5;
2008 Ok(reader)
2009 }
2010 }
2011
2012 #[test]
2013 fn the_system_read_fills_the_accessibility_cache() {
2014 let detection = crate::detect::DetectionContext::new();
2015 let st = pollster::block_on(read_through_pipeline(
2016 &ScaledTextReader,
2017 "adwaita",
2018 &detection,
2019 ))
2020 .unwrap();
2021 let runs = std::cell::Cell::new(0);
2022 let cached = detection.reader_accessibility_with(|| {
2023 runs.set(runs.get() + 1);
2024 crate::AccessibilityPreferences::default()
2025 });
2026 assert_eq!(runs.get(), 0, "the cache was empty after the system read");
2027 assert_eq!(cached, st.accessibility);
2028 assert_eq!(cached.text_scaling_factor, 1.5);
2029 }
2030
2031 struct InvalidatedReader<'a>(&'a crate::detect::DetectionContext);
2034
2035 #[async_trait::async_trait]
2036 impl crate::reader::ThemeReader for InvalidatedReader<'_> {
2037 async fn read(&self) -> crate::Result<ReaderResult> {
2038 self.0.invalidate_accessibility_preferences();
2039 ScaledTextReader.read().await
2040 }
2041 }
2042
2043 #[test]
2044 fn a_system_read_across_an_invalidation_leaves_the_cache_empty() {
2045 let detection = crate::detect::DetectionContext::new();
2046 pollster::block_on(read_through_pipeline(
2047 &InvalidatedReader(&detection),
2048 "adwaita",
2049 &detection,
2050 ))
2051 .unwrap();
2052 let runs = std::cell::Cell::new(0);
2053 let _ = detection.reader_accessibility_with(|| {
2054 runs.set(runs.get() + 1);
2055 crate::AccessibilityPreferences::default()
2056 });
2057 assert_eq!(
2058 runs.get(),
2059 1,
2060 "a block read before the invalidation was cached"
2061 );
2062 }
2063
2064 fn reader_with_empty_variant(is_dark: bool) -> ReaderResult {
2075 ReaderResult {
2076 output: ReaderOutput::Single {
2077 mode: Box::new(ThemeMode::default()),
2078 is_dark,
2079 },
2080 name: std::borrow::Cow::Borrowed(""),
2081 icon_set: None,
2082 layout: LayoutTheme::default(),
2083 font_dpi: None,
2084 accessibility: crate::AccessibilityPreferences::default(),
2085 }
2086 }
2087
2088 #[test]
2089 fn icon_theme_tier2_theme_level_used_when_per_variant_none() {
2090 let reader = reader_with_empty_variant(false);
2095 let st = run_pipeline(reader, "adwaita").unwrap();
2096 assert_eq!(
2097 st.icon_theme.as_deref(),
2098 Some("Adwaita"),
2099 "tier 2: Theme.icon_theme should be used when per-variant is None"
2100 );
2101 }
2102
2103 #[test]
2104 fn icon_theme_tier1_per_variant_wins_over_theme_level() {
2105 let mut variant = ThemeMode::default();
2109 variant.defaults.icon_theme = Some(std::borrow::Cow::Borrowed("custom-override"));
2110 let reader = ReaderResult {
2111 output: ReaderOutput::Single {
2112 mode: Box::new(variant),
2113 is_dark: false,
2114 },
2115 name: std::borrow::Cow::Borrowed(""),
2116 icon_set: None,
2117 layout: LayoutTheme::default(),
2118 font_dpi: None,
2119 accessibility: crate::AccessibilityPreferences::default(),
2120 };
2121 let st = run_pipeline(reader, "adwaita").unwrap();
2123 assert_eq!(
2124 st.icon_theme.as_deref(),
2125 Some("custom-override"),
2126 "tier 1: per-variant icon_theme override must win over Theme-level"
2127 );
2128 }
2129
2130 #[test]
2134 fn with_overlay_applies_the_overlays_icon_theme_and_layout() -> crate::Result<()> {
2135 let st = run_pipeline(reader_from_preset("adwaita"), "adwaita")?;
2136 let kept = st.with_overlay(&Theme::default())?;
2137 assert_eq!(kept.icon_theme, st.icon_theme);
2138 assert_eq!(kept.layout.widget_gap, st.layout.widget_gap);
2139
2140 let overlay =
2141 Theme::from_toml("icon_theme = \"custom-override\"\n[layout]\nwidget_gap_px = 9.0")?;
2142 let changed = st.with_overlay(&overlay)?;
2143 assert_eq!(changed.icon_theme.as_deref(), Some("custom-override"));
2144 assert_eq!(
2145 changed.icon_theme_for(crate::ColorMode::Dark),
2146 Some("custom-override")
2147 );
2148 assert_eq!(changed.layout.widget_gap, Some(9.0));
2149 Ok(())
2150 }
2151
2152 #[test]
2153 fn icon_theme_kde_per_variant_values_still_win() {
2154 let kde_full = Theme::preset("kde-breeze").unwrap();
2158 let dark_v = kde_full.dark.clone().unwrap();
2160 assert_eq!(
2161 dark_v.defaults.icon_theme.as_deref(),
2162 Some("breeze-dark"),
2163 "precondition: kde-breeze dark variant must carry breeze-dark"
2164 );
2165 let reader = ReaderResult {
2166 output: ReaderOutput::Single {
2167 mode: Box::new(dark_v),
2168 is_dark: true,
2169 },
2170 name: std::borrow::Cow::Borrowed(""),
2171 icon_set: None,
2172 layout: LayoutTheme::default(),
2173 font_dpi: None,
2174 accessibility: crate::AccessibilityPreferences::default(),
2175 };
2176 let st = run_pipeline(reader, "kde-breeze").unwrap();
2177 assert_eq!(
2178 st.icon_theme.as_deref(),
2179 Some("breeze-dark"),
2180 "KDE per-variant icon_theme must still win (Phase 80-fix invariant)"
2181 );
2182 }
2183
2184 #[test]
2185 fn theme_icon_theme_round_trips_when_some() {
2186 let theme = Theme {
2189 name: std::borrow::Cow::Borrowed("RoundTrip"),
2190 light: Some(ThemeMode::default()),
2191 dark: None,
2192 layout: LayoutTheme::default(),
2193 icon_set: None,
2194 icon_theme: Some(std::borrow::Cow::Borrowed("lucide")),
2195 };
2196 let toml_str = theme.to_toml().expect("serialize");
2197 let reparsed = Theme::from_toml(&toml_str).expect("deserialize");
2198 assert_eq!(
2199 reparsed.icon_theme.as_deref(),
2200 Some("lucide"),
2201 "Theme.icon_theme must round-trip through TOML"
2202 );
2203 assert!(
2205 toml_str.contains("icon_theme = \"lucide\""),
2206 "serialized TOML should contain top-level icon_theme, got:\n{toml_str}"
2207 );
2208 }
2209
2210 #[test]
2211 fn theme_icon_theme_skipped_when_none() {
2212 let theme = Theme {
2215 name: std::borrow::Cow::Borrowed("NoIcon"),
2216 light: Some(ThemeMode::default()),
2217 dark: None,
2218 layout: LayoutTheme::default(),
2219 icon_set: None,
2220 icon_theme: None,
2221 };
2222 let toml_str = theme.to_toml().expect("serialize");
2223 assert!(
2224 !toml_str.contains("icon_theme"),
2225 "serialized TOML should NOT contain icon_theme when None, got:\n{toml_str}"
2226 );
2227 }
2228
2229 #[test]
2230 fn lint_toml_accepts_top_level_icon_theme() {
2231 let toml_str = r##"
2234name = "Test"
2235icon_theme = "lucide"
2236
2237[light.defaults]
2238accent_color = "#0066cc"
2239"##;
2240 let warnings = Theme::lint_toml(toml_str).expect("lint");
2241 assert!(
2242 !warnings.iter().any(|w| w.contains("icon_theme")),
2243 "lint_toml must not flag top-level icon_theme as unknown; warnings: {warnings:?}"
2244 );
2245 }
2246
2247 #[test]
2251 fn system_theme_layout_is_the_merged_preset_layout() -> crate::Result<()> {
2252 let reader = preset_as_reader("adwaita", crate::ColorMode::Light)?;
2253 let sys = run_pipeline(reader, "adwaita")?;
2254
2255 let mut expected = Theme::preset("adwaita")?.layout;
2256 expected.merge(&Theme::preset("adwaita")?.layout);
2257
2258 assert_eq!(sys.layout, expected);
2259 assert!(
2260 sys.layout.widget_gap.is_some(),
2261 "adwaita defines all four layout keys (spec §1.3)"
2262 );
2263 Ok(())
2264 }
2265
2266 #[test]
2270 fn system_theme_layout_out_of_range_is_invalid() -> crate::Result<()> {
2271 let mut reader = preset_as_reader("adwaita", crate::ColorMode::Light)?;
2272 reader.layout.widget_gap = Some(-8.0);
2273 let Err(crate::Error::ResolutionInvalid { errors }) = run_pipeline(reader, "adwaita")
2274 else {
2275 panic!("expected ResolutionInvalid");
2276 };
2277 let paths: Vec<&str> = errors.iter().map(|rv| rv.path.as_str()).collect();
2278 assert_eq!(paths, ["layout.widget_gap_px"]);
2279
2280 let reader = preset_as_reader("adwaita", crate::ColorMode::Light)?;
2281 let mut sys = run_pipeline(reader, "adwaita")?;
2282 sys.overlay_source.layout.section_gap = Some(f32::NAN);
2283 let Err(crate::Error::ResolutionInvalid { errors }) = sys.with_overlay(&Theme::default())
2284 else {
2285 panic!("expected ResolutionInvalid");
2286 };
2287 let paths: Vec<&str> = errors.iter().map(|rv| rv.path.as_str()).collect();
2288 assert_eq!(paths, ["layout.section_gap_px"]);
2289 Ok(())
2290 }
2291
2292 #[test]
2296 fn icon_loads_from_the_modes_icon_theme() -> crate::Result<()> {
2297 let mut theme = run_pipeline(reader_from_preset("kde-breeze"), "kde-breeze")?;
2298 for active in [crate::ColorMode::Light, crate::ColorMode::Dark] {
2299 theme.mode = active;
2300 for (mode, expected) in [
2301 (crate::ColorMode::Light, "breeze"),
2302 (crate::ColorMode::Dark, "breeze-dark"),
2303 ] {
2304 let source =
2305 theme.with_icon_source(mode, |set, theme| (set, theme.map(str::to_owned)));
2306 assert_eq!(
2307 source,
2308 (crate::IconSet::Freedesktop, Some(expected.to_owned())),
2309 "kde-breeze.toml:16 and :601 (active mode {active:?}, asked {mode:?})"
2310 );
2311 assert_eq!(theme.icon_theme_for(mode), Some(expected));
2312 }
2313 }
2314 Ok(())
2315 }
2316
2317 #[test]
2322 #[cfg(all(target_os = "linux", feature = "system-icons"))]
2323 fn icon_and_indicator_load_from_the_modes_freedesktop_theme() -> crate::Result<()> {
2324 use crate::icons::{FreedesktopLoader, IconRole, is_freedesktop_theme_available};
2325
2326 const MISSING: &str = "native-theme-no-such-theme";
2327 assert!(!is_freedesktop_theme_available(MISSING));
2328 let mut theme = run_pipeline(reader_from_preset("kde-breeze"), "kde-breeze")?;
2329 theme.light_icon_theme = Some(std::borrow::Cow::Borrowed(MISSING));
2330 let role = IconRole::ActionCopy;
2331 for active in [crate::ColorMode::Light, crate::ColorMode::Dark] {
2332 theme.mode = active;
2333 assert_eq!(
2334 theme.icon(role, crate::ColorMode::Light, None),
2335 None,
2336 "light icon from {MISSING} (active mode {active:?})"
2337 );
2338 assert_eq!(
2339 theme.icon_indicator(crate::ColorMode::Light),
2340 None,
2341 "light spinner from {MISSING} (active mode {active:?})"
2342 );
2343 assert_eq!(
2344 theme.icon(role, crate::ColorMode::Dark, None),
2345 FreedesktopLoader::new(role).theme("breeze-dark").load(),
2346 "dark icon from breeze-dark, kde-breeze.toml:601 (active mode {active:?})"
2347 );
2348 assert_eq!(
2349 theme.icon_indicator(crate::ColorMode::Dark),
2350 FreedesktopLoader::load_indicator(Some("breeze-dark")),
2351 "dark spinner from breeze-dark (active mode {active:?})"
2352 );
2353 }
2354 Ok(())
2355 }
2356
2357 #[test]
2359 #[cfg(feature = "material-icons")]
2360 fn icon_of_a_material_theme_comes_back_in_the_colour() -> crate::Result<()> {
2361 let theme = run_pipeline(reader_from_preset("material-3"), "material-3")?;
2362 assert_eq!(
2363 theme.icon_set,
2364 crate::IconSet::Material,
2365 "material-3.toml:9"
2366 );
2367 let color = Rgba::rgb(0x12, 0x34, 0x56);
2369 for mode in [crate::ColorMode::Light, crate::ColorMode::Dark] {
2370 match theme.icon(crate::IconRole::ActionCopy, mode, Some(color)) {
2371 Some(crate::IconData::Svg(svg)) => {
2372 let svg = String::from_utf8(svg.into_owned()).unwrap();
2373 assert!(svg.contains("#123456"), "{mode:?}: {svg}");
2374 }
2375 other => panic!("expected an SVG for {mode:?}, got {other:?}"),
2376 }
2377 assert!(
2378 theme.icon_indicator(mode).is_some(),
2379 "Material's spinner ({mode:?})"
2380 );
2381 }
2382 Ok(())
2383 }
2384
2385 #[test]
2389 fn icon_theme_for_gives_each_variants_name() -> crate::Result<()> {
2390 for mode in [crate::ColorMode::Light, crate::ColorMode::Dark] {
2391 let reader = ReaderResult {
2394 output: ReaderOutput::Single {
2395 mode: Box::new(crate::model::ThemeMode::default()),
2396 is_dark: mode == crate::ColorMode::Dark,
2397 },
2398 name: std::borrow::Cow::Borrowed(""),
2399 icon_set: None,
2400 layout: crate::theme::LayoutTheme::default(),
2401 font_dpi: None,
2402 accessibility: crate::AccessibilityPreferences::default(),
2403 };
2404 let theme = run_pipeline(reader, "kde-breeze")?;
2405 assert_eq!(
2406 theme.icon_theme_for(crate::ColorMode::Light),
2407 Some("breeze"),
2408 "kde-breeze.toml:16 names breeze for light (active mode {mode:?})"
2409 );
2410 assert_eq!(
2411 theme.icon_theme_for(crate::ColorMode::Dark),
2412 Some("breeze-dark"),
2413 "kde-breeze.toml:601 names breeze-dark for dark (active mode {mode:?})"
2414 );
2415 assert_eq!(
2416 theme.icon_theme_for(mode),
2417 theme.icon_theme.as_deref(),
2418 "the active mode's name is `icon_theme` itself"
2419 );
2420 let mut flipped = theme;
2422 flipped.mode = match mode {
2423 crate::ColorMode::Light => crate::ColorMode::Dark,
2424 crate::ColorMode::Dark => crate::ColorMode::Light,
2425 };
2426 assert_eq!(
2427 flipped.icon_theme_for(crate::ColorMode::Light),
2428 Some("breeze"),
2429 "built in {mode:?}, mode flipped"
2430 );
2431 assert_eq!(
2432 flipped.icon_theme_for(crate::ColorMode::Dark),
2433 Some("breeze-dark"),
2434 "built in {mode:?}, mode flipped"
2435 );
2436 }
2437 Ok(())
2438 }
2439}
2440
2441#[cfg(test)]
2459#[allow(clippy::unwrap_used, clippy::expect_used)]
2460mod theme_reader_trait_tests {
2461 #[test]
2466 fn theme_reader_trait_exists_and_is_object_safe() {
2467 #[allow(dead_code)]
2474 fn assert_object_safe<T: ?Sized>(_: &T) {}
2475
2476 #[cfg(all(target_os = "linux", feature = "kde"))]
2479 {
2480 let r: Box<dyn crate::reader::ThemeReader> = Box::new(crate::kde::KdeReader);
2481 assert_object_safe(&r);
2482 }
2483 #[cfg(all(target_os = "macos", feature = "macos"))]
2484 {
2485 let r: Box<dyn crate::reader::ThemeReader> = Box::new(crate::macos::MacosReader);
2486 assert_object_safe(&r);
2487 }
2488 #[cfg(all(target_os = "windows", feature = "windows"))]
2489 {
2490 let r: Box<dyn crate::reader::ThemeReader> = Box::new(crate::windows::WindowsReader);
2491 assert_object_safe(&r);
2492 }
2493 let _: Option<&dyn crate::reader::ThemeReader> = None;
2497 }
2498
2499 #[test]
2511 fn select_reader_returns_platform_specific_impl() {
2512 let picked: Option<super::SelectedReader> = pollster::block_on(super::select_reader());
2516
2517 #[cfg(all(target_os = "macos", feature = "macos"))]
2521 {
2522 assert!(
2523 picked.is_some(),
2524 "select_reader must return Some on macOS+macos"
2525 );
2526 if let Some(selected) = &picked {
2527 let (preset, matched) = super::macos_generation(crate::macos::os_version());
2528 assert_eq!(selected.preset, preset.name);
2529 assert_eq!(selected.version_match, Some(matched));
2530 }
2531 }
2532 #[cfg(all(target_os = "windows", feature = "windows"))]
2533 {
2534 assert!(
2535 picked.is_some(),
2536 "select_reader must return Some on windows+windows"
2537 );
2538 if let Some(selected) = &picked {
2539 let (preset, matched) = super::windows_generation(crate::windows::os_version());
2540 assert_eq!(selected.preset, preset.name);
2541 assert_eq!(selected.version_match, Some(matched));
2542 }
2543 }
2544 #[cfg(all(target_os = "linux", feature = "kde", feature = "portal"))]
2545 {
2546 if let Some(selected) = &picked {
2550 assert!(
2551 selected.preset == "kde-breeze" || selected.preset == "adwaita",
2552 "select_reader on linux must return a known platform preset, got: {}",
2553 selected.preset
2554 );
2555 assert_eq!(selected.version_match, None);
2556 }
2557 }
2558 #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
2559 {
2560 assert!(
2561 picked.is_none(),
2562 "select_reader() must return None on unsupported platforms"
2563 );
2564 }
2565 drop(picked);
2566 }
2567}
2568
2569#[cfg(test)]
2572#[allow(clippy::unwrap_used, clippy::expect_used)]
2573mod generation_tests {
2574 use super::*;
2575
2576 fn macos_preset_for_version(major: u32) -> &'static str {
2578 macos_generation(OsVersion::new(major, 0, 0)).0.name
2579 }
2580
2581 #[test]
2582 fn macos_preset_follows_the_os_generation() {
2583 assert_eq!(macos_preset_for_version(12), "macos-monterey");
2584 assert_eq!(macos_preset_for_version(14), "macos-monterey");
2585 assert_eq!(macos_preset_for_version(15), "macos-monterey");
2586 assert_eq!(macos_preset_for_version(26), "macos-tahoe");
2587 assert_eq!(macos_preset_for_version(27), "macos-tahoe");
2589 assert_eq!(
2590 macos_generation(OsVersion::new(27, 0, 1)).1,
2591 VersionMatch::PresetOlder
2592 );
2593 assert_eq!(
2595 macos_generation(OsVersion::new(16, 0, 0)),
2596 (
2597 PlatformPreset {
2598 name: "macos-monterey"
2599 },
2600 VersionMatch::PresetOlder
2601 )
2602 );
2603 assert_eq!(
2605 macos_generation(OsVersion::new(0, 0, 0)),
2606 (
2607 PlatformPreset {
2608 name: "macos-monterey"
2609 },
2610 VersionMatch::PresetNewer
2611 )
2612 );
2613 }
2614
2615 #[test]
2616 fn macos_versions_inside_a_generation_match_exactly() {
2617 for v in [
2618 OsVersion::new(12, 0, 0),
2619 OsVersion::new(14, 8, 9),
2620 OsVersion::new(15, 7, 9),
2621 OsVersion::new(26, 6, 2),
2622 ] {
2623 assert_eq!(macos_generation(v).1, VersionMatch::Exact, "{v}");
2624 }
2625 assert_eq!(
2627 macos_generation(OsVersion::new(11, 7, 10)),
2628 (
2629 PlatformPreset {
2630 name: "macos-monterey"
2631 },
2632 VersionMatch::PresetNewer
2633 )
2634 );
2635 }
2636
2637 #[test]
2638 fn windows_preset_follows_the_build() {
2639 assert_eq!(
2641 windows_generation(OsVersion::new(10, 0, 19045)),
2642 (
2643 PlatformPreset { name: "windows-11" },
2644 VersionMatch::PresetNewer
2645 )
2646 );
2647 assert_eq!(
2648 windows_generation(OsVersion::new(10, 0, 22000)).1,
2649 VersionMatch::Exact
2650 );
2651 assert_eq!(
2652 windows_generation(OsVersion::new(10, 0, 26200)).1,
2653 VersionMatch::Exact
2654 );
2655 assert_eq!(
2657 windows_generation(OsVersion::new(10, 0, 26300)).1,
2658 VersionMatch::PresetOlder
2659 );
2660 assert_eq!(
2662 windows_generation(OsVersion::new(10, 0, 28000)),
2663 (
2664 PlatformPreset { name: "windows-11" },
2665 VersionMatch::PresetOlder
2666 )
2667 );
2668 assert_eq!(
2670 windows_generation(OsVersion::new(0, 0, 0)),
2671 (
2672 PlatformPreset { name: "windows-11" },
2673 VersionMatch::PresetNewer
2674 )
2675 );
2676 }
2677
2678 #[test]
2679 fn every_table_is_ordered_and_lists_its_keys() {
2680 for table in [MACOS_GENERATIONS, WINDOWS_GENERATIONS] {
2681 let rows: Vec<Generation> = table.rows().collect();
2682 let keys: Vec<&str> = rows.iter().map(|g| g.preset).collect();
2683 assert_eq!(keys, table.keys);
2684 for g in &rows {
2685 assert!(g.first <= g.last_verified, "{}", g.preset);
2686 }
2687 for (older, newer) in rows.iter().zip(rows.iter().skip(1)) {
2688 assert!(
2689 older.last_verified < newer.first,
2690 "{} / {}",
2691 older.preset,
2692 newer.preset
2693 );
2694 }
2695 }
2696 }
2697
2698 #[test]
2699 fn every_generation_is_a_bundled_preset_of_its_platform() {
2700 for (table, platform) in [
2701 (MACOS_GENERATIONS, "macos"),
2702 (WINDOWS_GENERATIONS, "windows"),
2703 ] {
2704 for key in table.keys {
2705 assert!(crate::Theme::preset(key).is_ok(), "{key}");
2706 let offered = crate::Theme::list_presets()
2707 .iter()
2708 .any(|p| p.key == *key && p.platforms.contains(&platform));
2709 assert!(offered, "{key} is not offered on {platform}");
2710 }
2711 }
2712 }
2713
2714 #[test]
2715 fn the_diagnostic_names_the_version_and_its_preset() {
2716 let entry = DiagnosticEntry::OsGeneration {
2717 version: OsVersion::new(27, 0, 1).to_string(),
2718 preset: "macos-tahoe",
2719 version_match: VersionMatch::PresetOlder,
2720 };
2721 assert_eq!(entry.name(), "OS version");
2722 assert_eq!(entry.status(), "27.0.1");
2723 assert_eq!(
2724 entry.to_string(),
2725 "OS version: 27.0.1 (macos-tahoe, preset older than the OS)"
2726 );
2727 }
2728}