1use arc_swap::ArcSwapOption;
5use std::sync::Arc;
6use std::sync::atomic::{AtomicU64, Ordering};
7
8mod icon_theme;
9
10pub(crate) use icon_theme::IconThemeFailure;
11pub use icon_theme::{detect_icon_theme, system_icon_set, system_icon_theme};
12
13#[cfg(unix)]
19#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
20pub(crate) const SUBPROCESS_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
21
22#[cfg(target_os = "linux")]
24#[non_exhaustive]
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
26pub enum LinuxDesktop {
27 Kde,
29 Gnome,
31 Xfce,
33 Cinnamon,
35 Mate,
37 LxQt,
39 Budgie,
41 Hyprland,
43 Sway,
45 River,
47 Niri,
49 Wayfire,
51 CosmicDe,
53 Unknown,
55}
56
57#[cfg(target_os = "linux")]
60pub(crate) fn xdg_current_desktop() -> String {
61 std::env::var("XDG_CURRENT_DESKTOP").unwrap_or_default()
62}
63
64#[cfg(target_os = "linux")]
86#[must_use]
87pub fn detect_linux_desktop() -> LinuxDesktop {
88 parse_linux_desktop(&xdg_current_desktop())
89}
90
91#[cfg(target_os = "linux")]
97#[must_use]
98pub fn parse_linux_desktop(xdg_current_desktop: &str) -> LinuxDesktop {
99 for component in xdg_current_desktop.split(':') {
100 match component {
101 "KDE" => return LinuxDesktop::Kde,
102 "Budgie" => return LinuxDesktop::Budgie,
103 "GNOME" => return LinuxDesktop::Gnome,
104 "XFCE" => return LinuxDesktop::Xfce,
105 "X-Cinnamon" | "Cinnamon" => return LinuxDesktop::Cinnamon,
106 "MATE" => return LinuxDesktop::Mate,
107 "LXQt" => return LinuxDesktop::LxQt,
108 "Hyprland" => return LinuxDesktop::Hyprland,
109 "sway" => return LinuxDesktop::Sway,
110 "river" => return LinuxDesktop::River,
111 "niri" => return LinuxDesktop::Niri,
112 "Wayfire" => return LinuxDesktop::Wayfire,
113 "COSMIC" => return LinuxDesktop::CosmicDe,
114 _ => {}
115 }
116 }
117 LinuxDesktop::Unknown
118}
119
120#[cfg(target_os = "linux")]
128pub(crate) fn refine_linux_desktop(
129 raw: LinuxDesktop,
130 portal_backend: Option<LinuxDesktop>,
131 kdeglobals_exists: impl FnOnce() -> bool,
132) -> LinuxDesktop {
133 refine_desktop(raw, portal_backend, kdeglobals_exists).desktop
134}
135
136#[cfg(target_os = "linux")]
139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
140pub(crate) struct RefinedDesktop {
141 pub(crate) desktop: LinuxDesktop,
143 pub(crate) by_kdeglobals: bool,
146}
147
148#[cfg(target_os = "linux")]
150pub(crate) fn refine_desktop(
151 raw: LinuxDesktop,
152 portal_backend: Option<LinuxDesktop>,
153 kdeglobals_exists: impl FnOnce() -> bool,
154) -> RefinedDesktop {
155 let (desktop, by_kdeglobals) = match (raw, portal_backend) {
156 (LinuxDesktop::Unknown, Some(backend)) => (backend, false),
157 (LinuxDesktop::Unknown, None) if kdeglobals_exists() => (LinuxDesktop::Kde, true),
158 (other, _) => (other, false),
159 };
160 RefinedDesktop {
161 desktop,
162 by_kdeglobals,
163 }
164}
165
166#[cfg(target_os = "linux")]
169fn kdeglobals_exists() -> bool {
170 #[cfg(feature = "kde")]
171 {
172 crate::kde::kdeglobals_path().is_some_and(|path| path.exists())
173 }
174 #[cfg(not(feature = "kde"))]
175 {
176 false
177 }
178}
179
180#[must_use]
211pub fn system_is_dark() -> bool {
212 system().is_dark()
213}
214
215pub fn invalidate_caches() {
231 system().invalidate_all();
232}
233
234#[must_use]
242pub fn detect_is_dark() -> bool {
243 detect_is_dark_inner()
244}
245
246#[cfg(unix)]
248#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
249const POLL_INTERVAL_CAP: std::time::Duration = std::time::Duration::from_millis(50);
250
251#[cfg(unix)]
256#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
257fn poll_intervals() -> impl Iterator<Item = std::time::Duration> {
258 std::iter::successors(Some(std::time::Duration::from_millis(1)), |pause| {
259 Some(pause.saturating_mul(2).min(POLL_INTERVAL_CAP))
260 })
261}
262
263#[cfg(unix)]
279#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
280pub(crate) fn run_with_timeout(
281 program: &str,
282 args: &[&str],
283 timeout: std::time::Duration,
284) -> std::io::Result<std::process::Output> {
285 use std::process::{Child, Command, Stdio};
286 use std::sync::mpsc::{Receiver, RecvTimeoutError};
287 use std::time::Instant;
288
289 fn kill_and_reap(child: &mut Child) {
290 if child.kill().is_ok() {
291 let _ = child.wait();
292 }
293 }
294
295 let timed_out = || {
296 std::io::Error::new(
297 std::io::ErrorKind::TimedOut,
298 format!("timed out after {timeout:?}"),
299 )
300 };
301
302 let start = Instant::now();
303 let mut child = Command::new(program)
304 .args(args)
305 .stdin(Stdio::null())
306 .stdout(Stdio::piped())
307 .stderr(Stdio::piped())
308 .spawn()?;
309 let readers = read_on_a_thread(child.stdout.take())
310 .and_then(|stdout| Ok((stdout, read_on_a_thread(child.stderr.take())?)));
311 let (stdout, stderr) = match readers {
312 Ok(readers) => readers,
313 Err(e) => {
314 kill_and_reap(&mut child);
315 return Err(e);
316 }
317 };
318
319 let mut intervals = poll_intervals();
320 let status = loop {
321 match child.try_wait() {
322 Ok(Some(status)) => break status,
323 Ok(None) => {
324 let elapsed = start.elapsed();
325 if elapsed >= timeout {
326 kill_and_reap(&mut child);
327 return Err(timed_out());
328 }
329 let pause = intervals.next().unwrap_or(POLL_INTERVAL_CAP);
330 std::thread::sleep(pause.min(timeout.saturating_sub(elapsed)));
331 }
332 Err(e) => {
333 kill_and_reap(&mut child);
334 return Err(e);
335 }
336 }
337 };
338
339 let received = |reader: Receiver<Vec<u8>>| {
340 reader
341 .recv_timeout(timeout.saturating_sub(start.elapsed()))
342 .map_err(|e| match e {
343 RecvTimeoutError::Timeout => timed_out(),
344 RecvTimeoutError::Disconnected => {
345 std::io::Error::other("the output reader stopped without a result")
346 }
347 })
348 };
349 Ok(std::process::Output {
350 status,
351 stdout: received(stdout)?,
352 stderr: received(stderr)?,
353 })
354}
355
356#[cfg(unix)]
359#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
360fn read_on_a_thread(
361 pipe: Option<impl std::io::Read + Send + 'static>,
362) -> std::io::Result<std::sync::mpsc::Receiver<Vec<u8>>> {
363 let (sender, receiver) = std::sync::mpsc::channel();
364 match pipe {
365 Some(mut pipe) => {
366 std::thread::Builder::new()
367 .name("native-theme-subprocess-output".to_string())
368 .spawn(move || {
369 let mut read = Vec::new();
370 let _ = pipe.read_to_end(&mut read);
371 let _ = sender.send(read);
372 })?;
373 }
374 None => {
375 let _ = sender.send(Vec::new());
376 }
377 }
378 Ok(receiver)
379}
380
381#[cfg(unix)]
384#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
385pub(crate) fn stdout_with_timeout(
386 program: &str,
387 args: &[&str],
388 timeout: std::time::Duration,
389) -> Option<String> {
390 let output = run_with_timeout(program, args, timeout).ok()?;
391 if !output.status.success() {
392 return None;
393 }
394 String::from_utf8(output.stdout).ok()
395}
396
397#[cfg(target_os = "linux")]
400pub(crate) fn xdg_config_home() -> Option<std::path::PathBuf> {
401 xdg_config_home_from(
402 std::env::var_os("XDG_CONFIG_HOME").as_deref(),
403 std::env::var_os("HOME").as_deref(),
404 )
405}
406
407#[cfg(target_os = "linux")]
417fn xdg_config_home_from(
418 var: Option<&std::ffi::OsStr>,
419 home: Option<&std::ffi::OsStr>,
420) -> Option<std::path::PathBuf> {
421 var.map(std::path::PathBuf::from)
422 .filter(|dir| dir.is_absolute())
423 .or_else(|| {
424 home.filter(|home| !home.is_empty())
425 .map(|home| std::path::Path::new(home).join(".config"))
426 })
427}
428
429#[cfg(target_os = "linux")]
431pub(crate) const CONFIG_HOME_UNRESOLVED: &str = "the config directory is unresolved: \
432 $XDG_CONFIG_HOME is not an absolute path and $HOME is unset or empty";
433
434#[cfg(target_os = "linux")]
440pub(crate) fn gsettings_get(
441 schema: &str,
442 key: &str,
443 timeout: std::time::Duration,
444) -> Option<String> {
445 let out = stdout_with_timeout("gsettings", &["get", schema, key], timeout)?;
446 let trimmed = out.trim();
447 if trimmed.is_empty() {
448 None
449 } else {
450 Some(trimmed.to_string())
451 }
452}
453
454#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
459fn read_xft_dpi() -> Option<f32> {
460 let out = stdout_with_timeout("xrdb", &["-query"], SUBPROCESS_TIMEOUT)?;
461 for line in out.lines() {
463 if let Some(rest) = line.strip_prefix("Xft.dpi:")
464 && let Ok(dpi) = rest.trim().parse::<f32>()
465 && dpi > 0.0
466 {
467 return Some(dpi);
468 }
469 }
470 None
471}
472
473#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
483fn detect_physical_dpi() -> Option<f32> {
484 let out = stdout_with_timeout("xrandr", &[], SUBPROCESS_TIMEOUT)?;
485 parse_xrandr_dpi(&out)
486}
487
488#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
497fn parse_xrandr_dpi(output: &str) -> Option<f32> {
498 let line = output
500 .lines()
501 .find(|l| l.contains(" connected") && l.contains("primary"))
502 .or_else(|| {
503 output
504 .lines()
505 .find(|l| l.contains(" connected") && !l.contains("disconnected"))
506 })?;
507
508 let res_token = line
510 .split_whitespace()
511 .find(|s| s.contains('x') && s.contains('+'))?;
512 let (w_str, rest) = res_token.split_once('x')?;
513 let h_str = rest.split('+').next()?;
514 let w_px: f32 = w_str.parse().ok()?;
515 let h_px: f32 = h_str.parse().ok()?;
516
517 let words: Vec<&str> = line.split_whitespace().collect();
519 let mut w_mm = None;
520 let mut h_mm = None;
521 for window in words.windows(3) {
522 let [prev, cur, next] = window else { continue };
523 if *cur == "x" {
524 w_mm = prev.strip_suffix("mm").and_then(|n| n.parse::<f32>().ok());
525 h_mm = next.strip_suffix("mm").and_then(|n| n.parse::<f32>().ok());
526 }
527 }
528 let w_mm = w_mm.filter(|&v| v > 0.0)?;
529 let h_mm = h_mm.filter(|&v| v > 0.0)?;
530
531 let h_dpi = w_px / (w_mm / 25.4);
532 let v_dpi = h_px / (h_mm / 25.4);
533 let avg = (h_dpi + v_dpi) / 2.0;
534
535 if avg > 0.0 { Some(avg) } else { None }
536}
537
538#[cfg(all(test, target_os = "linux", any(feature = "kde", feature = "portal")))]
539#[allow(clippy::unwrap_used)]
540mod xrandr_dpi_tests {
541 use super::parse_xrandr_dpi;
542
543 #[test]
544 fn primary_4k_display() {
545 let output = "Screen 0: minimum 16 x 16, current 3840 x 2160, maximum 32767 x 32767\n\
547 DP-1 connected primary 3840x2160+0+0 (normal left inverted right x axis y axis) 700mm x 390mm\n\
548 3840x2160 60.00*+\n";
549 let dpi = parse_xrandr_dpi(output).unwrap();
550 assert!((dpi - 140.0).abs() < 1.0, "expected ~140 DPI, got {dpi}");
552 }
553
554 #[test]
555 fn standard_1080p_display() {
556 let output = "DP-2 connected primary 1920x1080+0+0 (normal) 530mm x 300mm\n";
557 let dpi = parse_xrandr_dpi(output).unwrap();
558 assert!((dpi - 92.0).abs() < 1.0, "expected ~92 DPI, got {dpi}");
560 }
561
562 #[test]
563 fn no_primary_falls_back_to_first_connected() {
564 let output = "HDMI-1 connected 1920x1080+0+0 (normal) 480mm x 270mm\n\
565 DP-1 disconnected\n";
566 let dpi = parse_xrandr_dpi(output).unwrap();
567 assert!(dpi > 90.0 && dpi < 110.0, "expected ~100 DPI, got {dpi}");
568 }
569
570 #[test]
571 fn disconnected_only_returns_none() {
572 let output = "DP-1 disconnected\nHDMI-1 disconnected\n";
573 assert!(parse_xrandr_dpi(output).is_none());
574 }
575
576 #[test]
577 fn missing_physical_dimensions_returns_none() {
578 let output = "DP-1 connected primary 1920x1080+0+0 (normal)\n";
580 assert!(parse_xrandr_dpi(output).is_none());
581 }
582
583 #[test]
584 fn zero_mm_returns_none() {
585 let output = "DP-1 connected primary 1920x1080+0+0 (normal) 0mm x 0mm\n";
586 assert!(parse_xrandr_dpi(output).is_none());
587 }
588
589 #[test]
590 fn empty_output_returns_none() {
591 assert!(parse_xrandr_dpi("").is_none());
592 }
593}
594
595#[cfg(all(target_os = "linux", feature = "portal"))]
606pub(crate) const GNOME_FONT_DPI: f32 = 96.0;
607
608#[cfg(all(target_os = "linux", feature = "portal"))]
613fn desktop_font_dpi(desktop: LinuxDesktop) -> Option<f32> {
614 matches!(desktop, LinuxDesktop::Gnome | LinuxDesktop::Budgie).then_some(GNOME_FONT_DPI)
615}
616
617#[allow(unreachable_code)]
638fn detect_system_font_dpi() -> f32 {
639 #[cfg(target_os = "macos")]
640 {
641 return 72.0;
642 }
643
644 #[cfg(all(target_os = "windows", feature = "windows"))]
645 {
646 return crate::windows::LOGICAL_DPI as f32;
647 }
648
649 #[cfg(all(target_os = "linux", feature = "portal"))]
651 {
652 if let Some(dpi) = desktop_font_dpi(system().refined_linux_desktop_sync()) {
653 return dpi;
654 }
655 }
656
657 #[cfg(all(target_os = "linux", feature = "kde"))]
658 {
659 if let Some(dpi) = kde_force_font_dpi(session_type().as_deref(), || {
660 crate::kde::read_kcmfonts_key("General", "forceFontDPI")
661 }) {
662 return dpi;
663 }
664 }
665
666 #[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
667 {
668 if let Some(dpi) = read_xft_dpi() {
669 return dpi;
670 }
671 if let Some(dpi) = detect_physical_dpi() {
672 return dpi;
673 }
674 }
675
676 96.0
677}
678
679#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
681pub(crate) fn session_type() -> Option<String> {
682 std::env::var("XDG_SESSION_TYPE").ok()
683}
684
685#[cfg(all(target_os = "linux", feature = "kde"))]
692pub(crate) fn reads_force_font_dpi(session_type: Option<&str>) -> bool {
693 session_type == Some("x11")
694}
695
696#[cfg(all(target_os = "linux", feature = "kde"))]
700pub(crate) fn parse_force_font_dpi(value: &str) -> Option<f32> {
701 let dpi = value.trim().parse::<u32>().ok()?;
702 (dpi > 0).then_some(dpi as f32)
703}
704
705#[cfg(all(target_os = "linux", feature = "kde"))]
711fn kde_force_font_dpi(
712 session_type: Option<&str>,
713 kcmfonts: impl FnOnce() -> Option<String>,
714) -> Option<f32> {
715 if !reads_force_font_dpi(session_type) {
716 return None;
717 }
718 kcmfonts().as_deref().and_then(parse_force_font_dpi)
719}
720
721#[cfg(target_os = "linux")]
727pub(crate) fn color_scheme_is_dark(
728 portal: Option<bool>,
729 gsetting: impl FnOnce(&str, &str) -> Option<String>,
730) -> Option<bool> {
731 if portal.is_some() {
732 return portal;
733 }
734 let val = gsetting("org.gnome.desktop.interface", "color-scheme")?;
735 if val.contains("prefer-dark") {
736 Some(true)
737 } else if val.contains("prefer-light") || val.contains("default") {
738 Some(false)
739 } else {
740 None
741 }
742}
743
744#[cfg(target_os = "linux")]
750fn desktop_is_dark(
751 detection: &DetectionContext,
752 kdeglobals: impl FnOnce() -> Option<bool>,
753 gsettings: impl FnOnce() -> Option<bool>,
754) -> Option<bool> {
755 if detection.refined_linux_desktop_sync() == LinuxDesktop::Kde {
756 kdeglobals().or_else(gsettings)
757 } else {
758 gsettings().or_else(kdeglobals)
759 }
760}
761
762fn detect_is_dark_inner() -> bool {
766 #[cfg(target_os = "linux")]
767 {
768 if let Ok(gtk_theme) = std::env::var("GTK_THEME") {
770 let lower = gtk_theme.to_lowercase();
771 if lower.ends_with(":dark") || lower.contains("-dark") {
772 return true;
773 }
774 }
775
776 if let Some(dark) = desktop_is_dark(
777 system(),
778 || {
779 #[cfg(feature = "kde")]
780 {
781 crate::kde::kdeglobals_is_dark()
782 }
783 #[cfg(not(feature = "kde"))]
784 {
785 None
786 }
787 },
788 || {
789 color_scheme_is_dark(None, |schema, key| {
790 gsettings_get(schema, key, SUBPROCESS_TIMEOUT)
791 })
792 },
793 ) {
794 return dark;
795 }
796
797 if let Some(content) = xdg_config_home()
799 .and_then(|dir| std::fs::read_to_string(dir.join("gtk-3.0/settings.ini")).ok())
800 {
801 for line in content.lines() {
802 let trimmed = line.trim();
803 if trimmed.starts_with("gtk-application-prefer-dark-theme")
804 && let Some(val) = trimmed.split('=').nth(1)
805 && (val.trim() == "1" || val.trim().eq_ignore_ascii_case("true"))
806 {
807 return true;
808 }
809 }
810 }
811
812 false
813 }
814
815 #[cfg(target_os = "macos")]
816 {
817 #[cfg(feature = "macos")]
820 {
821 use objc2_foundation::NSUserDefaults;
822 let defaults = NSUserDefaults::standardUserDefaults();
823 let key = objc2_foundation::ns_string!("AppleInterfaceStyle");
824 defaults
825 .stringForKey(key)
826 .is_some_and(|value| value.to_string().eq_ignore_ascii_case("dark"))
827 }
828 #[cfg(not(feature = "macos"))]
829 {
830 stdout_with_timeout(
831 "defaults",
832 &["read", "-g", "AppleInterfaceStyle"],
833 SUBPROCESS_TIMEOUT,
834 )
835 .is_some_and(|value| value.trim().eq_ignore_ascii_case("dark"))
836 }
837 }
838
839 #[cfg(target_os = "windows")]
840 {
841 #[cfg(feature = "windows")]
842 {
843 let Ok(settings) = ::windows::UI::ViewManagement::UISettings::new() else {
844 return false;
845 };
846 let Ok(fg) =
847 settings.GetColorValue(::windows::UI::ViewManagement::UIColorType::Foreground)
848 else {
849 return false;
850 };
851 crate::windows::is_dark_mode(&crate::windows::win_color_to_rgba(fg))
852 }
853 #[cfg(not(feature = "windows"))]
854 {
855 false
856 }
857 }
858
859 #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
860 {
861 false
862 }
863}
864
865#[must_use]
907pub fn prefers_reduced_motion() -> bool {
908 system().prefers_reduced_motion()
909}
910
911#[must_use]
919pub fn detect_reduced_motion() -> bool {
920 detect_reduced_motion_inner()
921}
922
923#[must_use]
948pub fn accessibility_preferences() -> crate::AccessibilityPreferences {
949 system().accessibility_preferences()
950}
951
952#[cfg(target_os = "linux")]
958pub(crate) fn gnome_reduce_motion(
959 portal: Option<bool>,
960 gsetting: impl FnOnce(&str, &str) -> Option<String>,
961) -> Option<bool> {
962 if portal.is_some() {
963 return portal;
964 }
965 let enabled = gsetting("org.gnome.desktop.interface", "enable-animations")?;
966 enabled.trim().parse::<bool>().ok().map(|enabled| !enabled)
967}
968
969#[cfg(target_os = "linux")]
976fn desktop_reduce_motion(
977 desktop: LinuxDesktop,
978 kdeglobals: impl FnOnce() -> Option<bool>,
979 portal: impl FnOnce() -> Option<bool>,
980 gsetting: impl FnOnce(&str, &str) -> Option<String>,
981) -> bool {
982 match desktop {
983 LinuxDesktop::Kde => kdeglobals().or_else(|| gnome_reduce_motion(None, gsetting)),
984 LinuxDesktop::Gnome | LinuxDesktop::Budgie => gnome_reduce_motion(portal(), gsetting),
985 _ => gnome_reduce_motion(None, gsetting),
986 }
987 .unwrap_or(false)
988}
989
990fn detect_reduced_motion_inner() -> bool {
994 #[cfg(target_os = "linux")]
995 {
996 desktop_reduce_motion(
997 system().refined_linux_desktop_sync(),
998 || {
999 #[cfg(feature = "kde")]
1000 {
1001 Some(crate::kde::kdeglobals_reduce_motion())
1002 }
1003 #[cfg(not(feature = "kde"))]
1004 {
1005 None
1006 }
1007 },
1008 || {
1009 #[cfg(feature = "portal")]
1010 {
1011 pollster::block_on(crate::gnome::portal_reduce_motion())
1012 }
1013 #[cfg(not(feature = "portal"))]
1014 {
1015 None
1016 }
1017 },
1018 |schema, key| gsettings_get(schema, key, SUBPROCESS_TIMEOUT),
1019 )
1020 }
1021
1022 #[cfg(target_os = "macos")]
1023 {
1024 #[cfg(feature = "macos")]
1025 {
1026 crate::macos::reduce_motion()
1027 }
1028 #[cfg(not(feature = "macos"))]
1029 {
1030 false
1031 }
1032 }
1033
1034 #[cfg(target_os = "windows")]
1035 {
1036 #[cfg(feature = "windows")]
1037 {
1038 crate::windows::read_reduce_motion().unwrap_or(false)
1039 }
1040 #[cfg(not(feature = "windows"))]
1041 {
1042 false
1043 }
1044 }
1045
1046 #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
1047 {
1048 false
1049 }
1050}
1051
1052struct Stamped<T> {
1056 generation: u64,
1057 value: T,
1058}
1059
1060struct CacheSlot<T> {
1065 value: ArcSwapOption<Stamped<T>>,
1066 generation: AtomicU64,
1067}
1068
1069pub(crate) struct CacheFill<T> {
1071 generation: u64,
1072 seen: Option<Arc<Stamped<T>>>,
1073}
1074
1075impl<T> CacheFill<T> {
1076 fn cached(&self) -> Option<&T> {
1078 self.seen
1079 .as_deref()
1080 .filter(|entry| entry.generation == self.generation)
1081 .map(|entry| &entry.value)
1082 }
1083}
1084
1085impl<T> CacheSlot<T> {
1086 fn empty() -> Self {
1087 Self {
1088 value: ArcSwapOption::empty(),
1089 generation: AtomicU64::new(0),
1090 }
1091 }
1092
1093 fn begin_fill(&self) -> CacheFill<T> {
1098 let generation = self.generation.load(Ordering::Acquire);
1099 CacheFill {
1100 generation,
1101 seen: self.value.load_full(),
1102 }
1103 }
1104
1105 fn finish_fill(&self, fill: CacheFill<T>, value: T) {
1108 if self.generation.load(Ordering::Acquire) != fill.generation {
1109 return;
1110 }
1111 let stamped = Arc::new(Stamped {
1112 generation: fill.generation,
1113 value,
1114 });
1115 let _ = self.value.compare_and_swap(&fill.seen, Some(stamped));
1116 }
1117
1118 fn get_or_fill(&self, detect: impl FnOnce() -> T) -> T
1121 where
1122 T: Clone,
1123 {
1124 let fill = self.begin_fill();
1125 if let Some(value) = fill.cached() {
1126 return value.clone();
1127 }
1128 let value = detect();
1129 self.finish_fill(fill, value.clone());
1130 value
1131 }
1132
1133 #[cfg(any(test, target_os = "linux"))]
1135 fn get(&self) -> Option<T>
1136 where
1137 T: Clone,
1138 {
1139 self.begin_fill().cached().cloned()
1140 }
1141
1142 fn invalidate(&self) {
1143 self.value.store(None);
1144 self.generation.fetch_add(1, Ordering::Release);
1145 }
1146}
1147
1148pub struct DetectionContext {
1163 is_dark: CacheSlot<bool>,
1164 reduced_motion: CacheSlot<bool>,
1165 reader_accessibility: CacheSlot<crate::AccessibilityPreferences>,
1166 icon_theme: CacheSlot<Result<String, IconThemeFailure>>,
1167 #[cfg(target_os = "linux")]
1168 linux_desktop: CacheSlot<LinuxDesktop>,
1169 #[cfg(target_os = "linux")]
1170 refined_linux_desktop: CacheSlot<RefinedDesktop>,
1171 font_dpi: CacheSlot<f32>,
1172}
1173
1174impl DetectionContext {
1175 pub(crate) fn new() -> Self {
1177 Self {
1178 is_dark: CacheSlot::empty(),
1179 reduced_motion: CacheSlot::empty(),
1180 reader_accessibility: CacheSlot::empty(),
1181 icon_theme: CacheSlot::empty(),
1182 #[cfg(target_os = "linux")]
1183 linux_desktop: CacheSlot::empty(),
1184 #[cfg(target_os = "linux")]
1185 refined_linux_desktop: CacheSlot::empty(),
1186 font_dpi: CacheSlot::empty(),
1187 }
1188 }
1189
1190 #[must_use]
1197 pub fn is_dark(&self) -> bool {
1198 self.is_dark.get_or_fill(detect_is_dark_inner)
1199 }
1200
1201 #[must_use]
1207 pub fn prefers_reduced_motion(&self) -> bool {
1208 self.reduced_motion.get_or_fill(detect_reduced_motion_inner)
1209 }
1210
1211 #[must_use]
1219 pub fn accessibility_preferences(&self) -> crate::AccessibilityPreferences {
1220 self.reader_accessibility_with(|| {
1221 pollster::block_on(crate::pipeline::reader_accessibility())
1222 })
1223 }
1224
1225 pub(crate) fn reader_accessibility_with(
1228 &self,
1229 read: impl FnOnce() -> crate::AccessibilityPreferences,
1230 ) -> crate::AccessibilityPreferences {
1231 self.reader_accessibility.get_or_fill(read)
1232 }
1233
1234 pub(crate) fn begin_reader_accessibility(&self) -> CacheFill<crate::AccessibilityPreferences> {
1238 self.reader_accessibility.begin_fill()
1239 }
1240
1241 pub(crate) fn store_reader_accessibility(
1244 &self,
1245 fill: CacheFill<crate::AccessibilityPreferences>,
1246 prefs: crate::AccessibilityPreferences,
1247 ) {
1248 self.reader_accessibility.finish_fill(fill, prefs);
1249 }
1250
1251 pub fn icon_theme(&self) -> crate::Result<String> {
1265 self.icon_theme_with(detect_icon_theme_inner)
1266 }
1267
1268 fn icon_theme_with(
1271 &self,
1272 detect: impl FnOnce() -> Result<String, IconThemeFailure>,
1273 ) -> crate::Result<String> {
1274 self.icon_theme
1275 .get_or_fill(detect)
1276 .map_err(|failure| failure.to_error())
1277 }
1278
1279 #[cfg(target_os = "linux")]
1286 #[must_use]
1287 pub fn linux_desktop(&self) -> LinuxDesktop {
1288 self.linux_desktop.get_or_fill(detect_linux_desktop)
1289 }
1290
1291 #[cfg(target_os = "linux")]
1299 pub(crate) async fn refined_linux_desktop(&self) -> RefinedDesktop {
1300 let fill = self.refined_linux_desktop.begin_fill();
1301 if let Some(v) = fill.cached() {
1302 return *v;
1303 }
1304 let raw = self.linux_desktop();
1305 #[cfg(feature = "portal")]
1306 let portal_backend = if raw == LinuxDesktop::Unknown {
1307 crate::gnome::detect_portal_backend().await
1308 } else {
1309 None
1310 };
1311 #[cfg(not(feature = "portal"))]
1312 let portal_backend = None;
1313 let refined = refine_desktop(raw, portal_backend, kdeglobals_exists);
1314 let without_portal = refine_linux_desktop(raw, None, kdeglobals_exists);
1315 self.finish_refined_desktop(fill, refined, without_portal);
1316 refined
1317 }
1318
1319 #[cfg(target_os = "linux")]
1325 fn finish_refined_desktop(
1326 &self,
1327 fill: CacheFill<RefinedDesktop>,
1328 refined: RefinedDesktop,
1329 without_portal: LinuxDesktop,
1330 ) {
1331 self.refined_linux_desktop.finish_fill(fill, refined);
1332 if refined.desktop != without_portal {
1333 self.invalidate_font_dpi();
1334 self.invalidate_icon_theme();
1335 self.invalidate_is_dark();
1336 self.invalidate_reduced_motion();
1337 }
1338 }
1339
1340 #[cfg(target_os = "linux")]
1360 #[must_use]
1361 pub fn refined_linux_desktop_sync(&self) -> LinuxDesktop {
1362 if let Some(v) = self.refined_linux_desktop.get() {
1363 return v.desktop;
1364 }
1365 refine_linux_desktop(self.linux_desktop(), None, kdeglobals_exists)
1366 }
1367
1368 pub(crate) fn font_dpi(&self) -> f32 {
1375 self.font_dpi_with(detect_system_font_dpi)
1376 }
1377
1378 fn font_dpi_with(&self, detect: impl FnOnce() -> f32) -> f32 {
1381 self.font_dpi.get_or_fill(detect)
1382 }
1383
1384 pub fn invalidate_is_dark(&self) {
1386 self.is_dark.invalidate();
1387 }
1388
1389 pub fn invalidate_reduced_motion(&self) {
1391 self.reduced_motion.invalidate();
1392 }
1393
1394 pub fn invalidate_accessibility_preferences(&self) {
1396 self.reader_accessibility.invalidate();
1397 }
1398
1399 pub fn invalidate_icon_theme(&self) {
1401 self.icon_theme.invalidate();
1402 }
1403
1404 pub fn invalidate_font_dpi(&self) {
1406 self.font_dpi.invalidate();
1407 }
1408
1409 #[cfg(target_os = "linux")]
1412 pub fn invalidate_linux_desktop(&self) {
1413 self.linux_desktop.invalidate();
1414 self.refined_linux_desktop.invalidate();
1415 }
1416
1417 pub fn invalidate_all(&self) {
1419 self.invalidate_is_dark();
1420 self.invalidate_reduced_motion();
1421 self.invalidate_accessibility_preferences();
1422 self.invalidate_icon_theme();
1423 #[cfg(target_os = "linux")]
1424 self.invalidate_linux_desktop();
1425 self.invalidate_font_dpi();
1426 }
1427}
1428
1429pub fn system() -> &'static DetectionContext {
1434 static INSTANCE: std::sync::OnceLock<DetectionContext> = std::sync::OnceLock::new();
1435 INSTANCE.get_or_init(DetectionContext::new)
1436}
1437
1438fn detect_icon_theme_inner() -> Result<String, IconThemeFailure> {
1443 icon_theme::detect_icon_theme_outcome()
1444}
1445
1446pub(crate) fn system_font_dpi() -> f32 {
1450 system().font_dpi()
1451}
1452
1453#[cfg(test)]
1454#[allow(clippy::unwrap_used, clippy::expect_used)]
1455mod reduced_motion_tests {
1456 use super::*;
1457
1458 #[test]
1459 fn prefers_reduced_motion_smoke_test() {
1460 let _result = prefers_reduced_motion();
1464 }
1465
1466 #[cfg(target_os = "linux")]
1467 #[test]
1468 fn detect_reduced_motion_inner_linux() {
1469 let result = detect_reduced_motion_inner();
1473 let _ = result;
1475 }
1476
1477 #[cfg(target_os = "linux")]
1480 fn animations<'a>(
1481 enabled: &'static str,
1482 asked: &'a std::cell::Cell<u32>,
1483 ) -> impl FnOnce(&str, &str) -> Option<String> + 'a {
1484 move |schema, key| {
1485 asked.set(asked.get() + 1);
1486 ((schema, key) == ("org.gnome.desktop.interface", "enable-animations"))
1487 .then(|| enabled.to_string())
1488 }
1489 }
1490
1491 #[cfg(target_os = "linux")]
1496 #[test]
1497 fn kde_reduced_motion_is_kdeglobals_not_gsettings() {
1498 let asked = std::cell::Cell::new(0);
1499 let portal = || -> Option<bool> { panic!("KDE does not ask the portal") };
1500 assert!(desktop_reduce_motion(
1501 LinuxDesktop::Kde,
1502 || Some(true),
1503 portal,
1504 animations("true", &asked)
1505 ));
1506 assert!(!desktop_reduce_motion(
1507 LinuxDesktop::Kde,
1508 || Some(false),
1509 portal,
1510 animations("false", &asked)
1511 ));
1512 assert_eq!(asked.get(), 0);
1513 assert!(desktop_reduce_motion(
1514 LinuxDesktop::Kde,
1515 || None,
1516 portal,
1517 animations("false", &asked)
1518 ));
1519 assert_eq!(asked.get(), 1);
1520 }
1521
1522 #[cfg(target_os = "linux")]
1525 #[test]
1526 fn gnome_reduced_motion_is_the_portal_then_gsettings() {
1527 let asked = std::cell::Cell::new(0);
1528 let kdeglobals = || -> Option<bool> { panic!("GNOME does not read kdeglobals") };
1529 for desktop in [LinuxDesktop::Gnome, LinuxDesktop::Budgie] {
1530 assert!(desktop_reduce_motion(
1531 desktop,
1532 kdeglobals,
1533 || Some(true),
1534 animations("true", &asked)
1535 ));
1536 assert!(!desktop_reduce_motion(
1537 desktop,
1538 kdeglobals,
1539 || Some(false),
1540 animations("false", &asked)
1541 ));
1542 assert_eq!(asked.get(), 0);
1543 assert!(desktop_reduce_motion(
1544 desktop,
1545 kdeglobals,
1546 || None,
1547 animations("false", &asked)
1548 ));
1549 assert_eq!(asked.get(), 1);
1550 asked.set(0);
1551 }
1552 }
1553
1554 #[cfg(target_os = "linux")]
1556 #[test]
1557 fn other_desktops_reduced_motion_is_gsettings() {
1558 let asked = std::cell::Cell::new(0);
1559 assert!(desktop_reduce_motion(
1560 LinuxDesktop::Xfce,
1561 || -> Option<bool> { panic!("XFCE does not read kdeglobals") },
1562 || -> Option<bool> { panic!("XFCE does not ask the portal") },
1563 animations("false", &asked)
1564 ));
1565 assert!(!desktop_reduce_motion(
1566 LinuxDesktop::Unknown,
1567 || None,
1568 || None,
1569 |_, _| None
1570 ));
1571 }
1572
1573 #[cfg(target_os = "macos")]
1574 #[test]
1575 fn detect_reduced_motion_inner_macos() {
1576 let result = detect_reduced_motion_inner();
1577 let _ = result;
1578 }
1579
1580 #[cfg(target_os = "windows")]
1581 #[test]
1582 fn detect_reduced_motion_inner_windows() {
1583 let result = detect_reduced_motion_inner();
1584 let _ = result;
1585 }
1586}
1587
1588#[cfg(all(test, target_os = "linux", feature = "kde"))]
1589mod force_font_dpi_tests {
1590 use super::*;
1591
1592 #[test]
1593 fn force_font_dpi_is_a_positive_u32() {
1594 assert_eq!(parse_force_font_dpi("120"), Some(120.0));
1595 assert_eq!(parse_force_font_dpi(" 144 "), Some(144.0));
1596 for value in ["0", "inf", "-inf", "NaN", "-96", "96.5", "1e3", ""] {
1597 assert_eq!(parse_force_font_dpi(value), None, "forceFontDPI={value}");
1598 }
1599 }
1600
1601 #[test]
1602 fn only_an_x11_session_reads_force_font_dpi() {
1603 assert!(reads_force_font_dpi(Some("x11")));
1604 for session in [Some("wayland"), Some("tty"), Some(""), None] {
1605 assert!(!reads_force_font_dpi(session), "{session:?}");
1606 }
1607 }
1608
1609 #[test]
1610 fn a_wayland_session_ignores_force_font_dpi() {
1611 let reads = std::cell::Cell::new(0);
1612 let file = || {
1613 reads.set(reads.get() + 1);
1614 Some("120".to_string())
1615 };
1616 for session in [Some("wayland"), None] {
1617 assert_eq!(kde_force_font_dpi(session, file), None, "{session:?}");
1618 }
1619 assert_eq!(reads.get(), 0, "a file was read off X11");
1620 }
1621
1622 #[test]
1623 fn an_x11_session_takes_a_valid_kcmfonts_key() {
1624 assert_eq!(
1625 kde_force_font_dpi(Some("x11"), || Some("144".into())),
1626 Some(144.0)
1627 );
1628 for kcmfonts in [None, Some("0"), Some("inf")] {
1629 assert_eq!(
1630 kde_force_font_dpi(Some("x11"), || kcmfonts.map(String::from)),
1631 None,
1632 "kcmfonts {kcmfonts:?}"
1633 );
1634 }
1635 }
1636}
1637
1638#[cfg(test)]
1639mod cache_slot_tests {
1640 use super::*;
1641
1642 #[test]
1646 fn a_value_detected_across_an_invalidation_is_not_cached() {
1647 let slot = CacheSlot::empty();
1648 assert!(slot.get_or_fill(|| {
1649 slot.invalidate();
1650 true
1651 }));
1652 assert!(slot.get().is_none());
1653 assert!(!slot.get_or_fill(|| false));
1654 assert_eq!(slot.get(), Some(false));
1655 }
1656
1657 #[test]
1661 fn an_entry_stamped_before_an_invalidation_is_not_returned() {
1662 let slot = CacheSlot::empty();
1663 let fill = slot.begin_fill();
1664 slot.invalidate();
1665 let stale = Arc::new(Stamped {
1666 generation: fill.generation,
1667 value: true,
1668 });
1669 let _ = slot.value.compare_and_swap(&fill.seen, Some(stale));
1670 assert!(slot.get().is_none());
1671 assert!(!slot.get_or_fill(|| false));
1672 assert_eq!(slot.get(), Some(false));
1673 }
1674
1675 #[test]
1676 fn a_fill_does_not_replace_a_value_stored_since_it_began() {
1677 let slot = CacheSlot::empty();
1678 let slow = slot.begin_fill();
1679 let _ = slot.get_or_fill(|| 2);
1680 slot.finish_fill(slow, 1);
1681 assert_eq!(slot.get(), Some(2));
1682 }
1683}
1684
1685#[cfg(test)]
1686mod detection_context_tests {
1687 use super::*;
1688
1689 #[test]
1690 fn system_returns_same_instance() {
1691 let a = system() as *const DetectionContext;
1692 let b = system() as *const DetectionContext;
1693 assert_eq!(a, b);
1694 }
1695
1696 fn filled() -> DetectionContext {
1698 let ctx = DetectionContext::new();
1699 ctx.is_dark.get_or_fill(|| true);
1700 ctx.reduced_motion.get_or_fill(|| true);
1701 ctx.reader_accessibility
1702 .get_or_fill(crate::AccessibilityPreferences::default);
1703 let _ = ctx.icon_theme.get_or_fill(|| Ok("breeze".to_string()));
1704 #[cfg(target_os = "linux")]
1705 ctx.linux_desktop.get_or_fill(|| LinuxDesktop::Kde);
1706 #[cfg(target_os = "linux")]
1707 ctx.refined_linux_desktop.get_or_fill(|| RefinedDesktop {
1708 desktop: LinuxDesktop::Kde,
1709 by_kdeglobals: false,
1710 });
1711 ctx.font_dpi.get_or_fill(|| 120.0);
1712 ctx
1713 }
1714
1715 #[test]
1719 fn invalidate_all_empties_every_slot() {
1720 let ctx = filled();
1721 ctx.invalidate_all();
1722 let DetectionContext {
1723 is_dark,
1724 reduced_motion,
1725 reader_accessibility,
1726 icon_theme,
1727 #[cfg(target_os = "linux")]
1728 linux_desktop,
1729 #[cfg(target_os = "linux")]
1730 refined_linux_desktop,
1731 font_dpi,
1732 } = &ctx;
1733 assert!(is_dark.get().is_none(), "is_dark");
1734 assert!(reduced_motion.get().is_none(), "reduced_motion");
1735 assert!(reader_accessibility.get().is_none(), "reader_accessibility");
1736 assert!(icon_theme.get().is_none(), "icon_theme");
1737 #[cfg(target_os = "linux")]
1738 assert!(linux_desktop.get().is_none(), "linux_desktop");
1739 #[cfg(target_os = "linux")]
1740 assert!(
1741 refined_linux_desktop.get().is_none(),
1742 "refined_linux_desktop"
1743 );
1744 assert!(font_dpi.get().is_none(), "font_dpi");
1745 }
1746
1747 #[test]
1748 fn invalidate_is_dark_empties_only_is_dark() {
1749 let ctx = filled();
1750 ctx.invalidate_is_dark();
1751 assert_eq!(ctx.is_dark.get(), None);
1752 assert_eq!(ctx.font_dpi.get(), Some(120.0));
1753 }
1754
1755 #[test]
1756 fn font_dpi_is_cached_until_invalidate_all() {
1757 let ctx = DetectionContext::new();
1758 let runs = std::cell::Cell::new(0);
1759 let detect = |dpi| {
1760 runs.set(runs.get() + 1);
1761 dpi
1762 };
1763 assert_eq!(ctx.font_dpi_with(|| detect(120.0)), 120.0);
1764 assert_eq!(ctx.font_dpi_with(|| detect(96.0)), 120.0);
1765 assert_eq!(runs.get(), 1, "a cached font DPI was detected again");
1766 ctx.invalidate_all();
1767 assert_eq!(ctx.font_dpi_with(|| detect(96.0)), 96.0);
1768 assert_eq!(runs.get(), 2);
1769 }
1770
1771 fn undetected() -> Result<String, IconThemeFailure> {
1772 Err(IconThemeFailure::for_tests("the test's failing detection"))
1773 }
1774
1775 #[test]
1776 fn a_failed_icon_theme_detection_is_cached_and_reported() {
1777 let ctx = DetectionContext::new();
1778 let runs = std::cell::Cell::new(0);
1779 let detect = || {
1780 runs.set(runs.get() + 1);
1781 undetected()
1782 };
1783 let first = ctx.icon_theme_with(detect);
1784 let second = ctx.icon_theme_with(detect);
1785 assert_eq!(runs.get(), 1, "a failed detection ran again");
1786 for outcome in [first, second] {
1787 match outcome {
1788 Ok(name) => panic!("a failed detection gave the theme {name}"),
1789 Err(e) => assert!(
1790 e.to_string().contains("the test's failing detection"),
1791 "got: {e}"
1792 ),
1793 }
1794 }
1795 }
1796
1797 #[test]
1798 fn invalidate_icon_theme_clears_a_cached_failure() {
1799 let ctx = DetectionContext::new();
1800 assert!(ctx.icon_theme_with(undetected).is_err());
1801 ctx.invalidate_icon_theme();
1802 let theme = ctx.icon_theme_with(|| Ok("breeze".to_string()));
1803 assert_eq!(theme.ok().as_deref(), Some("breeze"));
1804 }
1805
1806 #[test]
1807 fn invalidate_all_clears_a_cached_failure() {
1808 let ctx = DetectionContext::new();
1809 assert!(ctx.icon_theme_with(undetected).is_err());
1810 ctx.invalidate_all();
1811 let theme = ctx.icon_theme_with(|| Ok("breeze".to_string()));
1812 assert_eq!(theme.ok().as_deref(), Some("breeze"));
1813 }
1814
1815 fn scaled_by(text_scaling_factor: f32) -> crate::AccessibilityPreferences {
1816 crate::AccessibilityPreferences {
1817 text_scaling_factor,
1818 ..crate::AccessibilityPreferences::default()
1819 }
1820 }
1821
1822 #[test]
1823 fn a_second_accessibility_read_does_not_run_the_reader() {
1824 let ctx = DetectionContext::new();
1825 let runs = std::cell::Cell::new(0);
1826 let read = || {
1827 runs.set(runs.get() + 1);
1828 scaled_by(1.5)
1829 };
1830 assert_eq!(ctx.reader_accessibility_with(read), scaled_by(1.5));
1831 assert_eq!(ctx.reader_accessibility_with(read), scaled_by(1.5));
1832 assert_eq!(runs.get(), 1, "the second call ran the reader");
1833 }
1834
1835 #[test]
1836 fn a_stored_accessibility_block_is_returned_until_invalidated() {
1837 let ctx = DetectionContext::new();
1838 let runs = std::cell::Cell::new(0);
1839 let read = || {
1840 runs.set(runs.get() + 1);
1841 scaled_by(1.25)
1842 };
1843 ctx.store_reader_accessibility(ctx.begin_reader_accessibility(), scaled_by(2.0));
1844 assert_eq!(ctx.reader_accessibility_with(read), scaled_by(2.0));
1845 assert_eq!(runs.get(), 0, "a stored block ran the reader");
1846 ctx.invalidate_all();
1847 assert_eq!(ctx.reader_accessibility_with(read), scaled_by(1.25));
1848 assert_eq!(runs.get(), 1);
1849 ctx.invalidate_accessibility_preferences();
1850 assert_eq!(ctx.reader_accessibility_with(read), scaled_by(1.25));
1851 assert_eq!(runs.get(), 2);
1852 }
1853
1854 #[test]
1857 fn a_font_dpi_detected_across_an_invalidation_is_not_cached() {
1858 let ctx = DetectionContext::new();
1859 let stale = ctx.font_dpi_with(|| {
1860 ctx.invalidate_font_dpi();
1861 120.0
1862 });
1863 assert_eq!(stale, 120.0);
1864 assert_eq!(ctx.font_dpi_with(|| 96.0), 96.0);
1865 }
1866
1867 #[test]
1868 fn an_icon_theme_detected_across_an_invalidation_is_not_cached() {
1869 let ctx = DetectionContext::new();
1870 let stale = ctx.icon_theme_with(|| {
1871 ctx.invalidate_icon_theme();
1872 Ok("breeze".to_string())
1873 });
1874 assert_eq!(stale.ok().as_deref(), Some("breeze"));
1875 let theme = ctx.icon_theme_with(|| Ok("Adwaita".to_string()));
1876 assert_eq!(theme.ok().as_deref(), Some("Adwaita"));
1877 }
1878
1879 #[test]
1880 fn an_accessibility_block_read_across_an_invalidation_is_not_cached() {
1881 let ctx = DetectionContext::new();
1882 let stale = ctx.reader_accessibility_with(|| {
1883 ctx.invalidate_all();
1884 scaled_by(1.5)
1885 });
1886 assert_eq!(stale, scaled_by(1.5));
1887 assert_eq!(
1888 ctx.reader_accessibility_with(|| scaled_by(2.0)),
1889 scaled_by(2.0)
1890 );
1891 }
1892
1893 #[cfg(target_os = "linux")]
1896 #[test]
1897 fn the_sync_refined_desktop_is_the_cached_one() {
1898 let ctx = DetectionContext::new();
1899 let fill = ctx.refined_linux_desktop.begin_fill();
1900 let gnome = refine_desktop(LinuxDesktop::Gnome, None, || false);
1901 ctx.refined_linux_desktop.finish_fill(fill, gnome);
1902 assert_eq!(ctx.refined_linux_desktop_sync(), LinuxDesktop::Gnome);
1903 assert_eq!(pollster::block_on(ctx.refined_linux_desktop()), gnome);
1904 ctx.invalidate_linux_desktop();
1905 assert!(ctx.refined_linux_desktop.get().is_none());
1906 }
1907
1908 #[cfg(target_os = "linux")]
1911 fn refined_unknown(portal_backend: Option<LinuxDesktop>) -> DetectionContext {
1912 let ctx = DetectionContext::new();
1913 ctx.linux_desktop
1914 .finish_fill(ctx.linux_desktop.begin_fill(), LinuxDesktop::Unknown);
1915 ctx.finish_refined_desktop(
1916 ctx.refined_linux_desktop.begin_fill(),
1917 refine_desktop(LinuxDesktop::Unknown, portal_backend, || false),
1918 LinuxDesktop::Unknown,
1919 );
1920 ctx
1921 }
1922
1923 #[cfg(target_os = "linux")]
1930 #[test]
1931 fn a_portal_answer_that_changes_the_desktop_clears_what_was_read_from_it() {
1932 let ctx = DetectionContext::new();
1933 assert_eq!(ctx.font_dpi_with(|| 120.0), 120.0);
1934 assert_eq!(
1935 ctx.icon_theme_with(|| Ok("breeze".to_string()))
1936 .ok()
1937 .as_deref(),
1938 Some("breeze")
1939 );
1940 assert!(ctx.is_dark.get_or_fill(|| true));
1941 assert!(ctx.reduced_motion.get_or_fill(|| true));
1942
1943 let refined = refine_desktop(LinuxDesktop::Unknown, Some(LinuxDesktop::Gnome), || true);
1944 ctx.finish_refined_desktop(
1945 ctx.refined_linux_desktop.begin_fill(),
1946 refined,
1947 LinuxDesktop::Kde,
1948 );
1949 assert_eq!(ctx.refined_linux_desktop_sync(), LinuxDesktop::Gnome);
1950 assert_eq!(ctx.font_dpi_with(|| 96.0), 96.0);
1951 assert_eq!(
1952 ctx.icon_theme_with(|| Ok("Adwaita".to_string()))
1953 .ok()
1954 .as_deref(),
1955 Some("Adwaita")
1956 );
1957 assert_eq!(ctx.is_dark.get(), None);
1958 assert_eq!(ctx.reduced_motion.get(), None);
1959 }
1960
1961 #[cfg(target_os = "linux")]
1964 #[test]
1965 fn a_portal_answer_that_keeps_the_desktop_keeps_what_was_read() {
1966 let ctx = DetectionContext::new();
1967 assert_eq!(ctx.font_dpi_with(|| 120.0), 120.0);
1968 let refined = refine_desktop(LinuxDesktop::Unknown, Some(LinuxDesktop::Kde), || true);
1969 ctx.finish_refined_desktop(
1970 ctx.refined_linux_desktop.begin_fill(),
1971 refined,
1972 LinuxDesktop::Kde,
1973 );
1974 assert_eq!(ctx.font_dpi_with(|| 96.0), 120.0);
1975 }
1976
1977 #[cfg(target_os = "linux")]
1981 #[test]
1982 fn dark_mode_follows_the_refined_desktop() {
1983 let kde = refined_unknown(Some(LinuxDesktop::Kde));
1984 assert_eq!(
1985 desktop_is_dark(&kde, || Some(true), || Some(false)),
1986 Some(true)
1987 );
1988 let gnome = refined_unknown(Some(LinuxDesktop::Gnome));
1989 assert_eq!(
1990 desktop_is_dark(&gnome, || Some(true), || Some(false)),
1991 Some(false)
1992 );
1993 assert_eq!(desktop_is_dark(&gnome, || Some(true), || None), Some(true));
1994 }
1995}
1996
1997#[cfg(all(test, target_os = "linux"))]
1998mod refine_linux_desktop_tests {
1999 use super::*;
2000
2001 fn asked() -> bool {
2002 panic!("kdeglobals asked where the desktop is already decided")
2003 }
2004
2005 #[test]
2008 fn the_raw_desktop_then_the_portal_backend_then_kdeglobals() {
2009 let refine = |raw, portal_backend, kdeglobals_exists: fn() -> bool| {
2010 refine_linux_desktop(raw, portal_backend, kdeglobals_exists)
2011 };
2012 assert_eq!(
2013 refine(LinuxDesktop::Gnome, Some(LinuxDesktop::Kde), asked),
2014 LinuxDesktop::Gnome
2015 );
2016 assert_eq!(refine(LinuxDesktop::Xfce, None, asked), LinuxDesktop::Xfce);
2017 assert_eq!(
2018 refine(LinuxDesktop::Unknown, Some(LinuxDesktop::Kde), asked),
2019 LinuxDesktop::Kde
2020 );
2021 assert_eq!(
2022 refine(LinuxDesktop::Unknown, Some(LinuxDesktop::Gnome), asked),
2023 LinuxDesktop::Gnome
2024 );
2025 assert_eq!(
2026 refine(LinuxDesktop::Unknown, None, || true),
2027 LinuxDesktop::Kde
2028 );
2029 assert_eq!(
2030 refine(LinuxDesktop::Unknown, None, || false),
2031 LinuxDesktop::Unknown
2032 );
2033 }
2034}
2035
2036#[cfg(all(test, target_os = "linux"))]
2037#[allow(clippy::unwrap_used, clippy::expect_used)]
2038mod subprocess_tests {
2039 use super::*;
2040 use std::path::PathBuf;
2041 use std::time::{Duration, Instant};
2042
2043 const GENEROUS: Duration = Duration::from_secs(10);
2047
2048 fn on_path(program: &str) -> bool {
2050 std::env::var_os("PATH")
2051 .is_some_and(|path| std::env::split_paths(&path).any(|dir| dir.join(program).is_file()))
2052 }
2053
2054 #[test]
2055 fn poll_intervals_double_from_1_ms_up_to_50_ms() {
2056 let intervals: Vec<Duration> = poll_intervals().take(10).collect();
2057 let expected: Vec<Duration> = [1, 2, 4, 8, 16, 32, 50, 50, 50, 50]
2058 .into_iter()
2059 .map(Duration::from_millis)
2060 .collect();
2061 assert_eq!(intervals, expected);
2062 }
2063
2064 #[test]
2065 fn run_with_timeout_returns_stdout_of_a_successful_command() {
2066 if !on_path("echo") {
2067 eprintln!("skipped: echo is not installed");
2068 return;
2069 }
2070 let out = stdout_with_timeout("echo", &["hi"], GENEROUS);
2071 assert_eq!(out.as_deref().map(str::trim), Some("hi"));
2072 }
2073
2074 #[test]
2077 fn run_with_timeout_returns_the_status_and_stderr_of_a_failing_command() {
2078 if !on_path("sh") {
2079 eprintln!("skipped: sh is not installed");
2080 return;
2081 }
2082 let output = run_with_timeout("sh", &["-c", "echo oops >&2; exit 3"], GENEROUS).unwrap();
2083 assert_eq!(output.status.code(), Some(3));
2084 assert_eq!(output.stderr, b"oops\n");
2085 assert_eq!(stdout_with_timeout("sh", &["-c", "exit 3"], GENEROUS), None);
2086 }
2087
2088 #[test]
2089 fn run_with_timeout_reports_a_missing_program_as_not_found() {
2090 let error = run_with_timeout("nt-test-no-such-program", &[], GENEROUS).unwrap_err();
2091 assert_eq!(error.kind(), std::io::ErrorKind::NotFound);
2092 }
2093
2094 #[test]
2097 fn run_with_timeout_returns_the_empty_stdout_of_a_quiet_command() {
2098 if !on_path("true") {
2099 eprintln!("skipped: true is not installed");
2100 return;
2101 }
2102 let start = Instant::now();
2103 assert_eq!(
2104 stdout_with_timeout("true", &[], GENEROUS).as_deref(),
2105 Some("")
2106 );
2107 eprintln!("`true` ran in {:?}", start.elapsed());
2108 }
2109
2110 fn running(cmdline: &str) -> Vec<PathBuf> {
2112 std::fs::read_dir("/proc")
2113 .unwrap()
2114 .flatten()
2115 .map(|entry| entry.path().join("cmdline"))
2116 .filter(|path| std::fs::read(path).is_ok_and(|bytes| bytes == cmdline.as_bytes()))
2117 .collect()
2118 }
2119
2120 #[test]
2124 fn run_with_timeout_kills_a_command_that_outlives_the_timeout() {
2125 if !on_path("sleep") {
2126 eprintln!("skipped: sleep is not installed");
2127 return;
2128 }
2129 let timeout = Duration::from_millis(100);
2130 let seconds = format!("30.{}", std::process::id());
2131 let start = Instant::now();
2132 let error = run_with_timeout("sleep", &[&seconds], timeout).unwrap_err();
2133 let elapsed = start.elapsed();
2134 assert_eq!(error.kind(), std::io::ErrorKind::TimedOut);
2135 assert_eq!(error.to_string(), "timed out after 100ms");
2136 assert!(
2137 elapsed >= timeout && elapsed < Duration::from_secs(5),
2138 "took {elapsed:?}"
2139 );
2140 let still_running = running(&format!("sleep\0{seconds}\0"));
2141 assert!(still_running.is_empty(), "not killed: {still_running:?}");
2142 }
2143
2144 #[test]
2147 fn run_with_timeout_returns_all_of_an_output_larger_than_a_pipe() {
2148 if !on_path("sh") || !on_path("head") {
2149 eprintln!("skipped: sh or head is not installed");
2150 return;
2151 }
2152 let out = stdout_with_timeout("sh", &["-c", "head -c 102400 /dev/zero"], GENEROUS);
2153 assert_eq!(out.map(|out| out.len()), Some(102_400));
2154 }
2155
2156 #[test]
2161 fn run_with_timeout_ends_at_the_deadline_when_a_grandchild_holds_stdout() {
2162 if !on_path("sh") || !on_path("sleep") {
2163 eprintln!("skipped: sh or sleep is not installed");
2164 return;
2165 }
2166 let script = format!("sleep 10.{} & echo hi", std::process::id());
2167 let start = Instant::now();
2168 let error =
2169 run_with_timeout("sh", &["-c", &script], Duration::from_millis(100)).unwrap_err();
2170 let elapsed = start.elapsed();
2171 assert_eq!(error.kind(), std::io::ErrorKind::TimedOut);
2172 assert!(elapsed < Duration::from_secs(5), "took {elapsed:?}");
2173 }
2174}
2175
2176#[cfg(all(test, target_os = "linux"))]
2177mod config_home_tests {
2178 use super::*;
2179 use std::ffi::OsStr;
2180 use std::path::PathBuf;
2181
2182 fn config_home(var: Option<&str>, home: Option<&str>) -> Option<PathBuf> {
2183 xdg_config_home_from(var.map(OsStr::new), home.map(OsStr::new))
2184 }
2185
2186 #[test]
2187 fn an_absolute_xdg_config_home_is_the_config_directory() {
2188 assert_eq!(
2189 config_home(Some("/tmp/cfg"), Some("/home/u")),
2190 Some(PathBuf::from("/tmp/cfg"))
2191 );
2192 assert_eq!(
2193 config_home(Some("/tmp/cfg"), None),
2194 Some(PathBuf::from("/tmp/cfg"))
2195 );
2196 }
2197
2198 #[test]
2201 fn an_unset_empty_or_relative_xdg_config_home_falls_back_to_home() {
2202 for var in [None, Some(""), Some("relative/cfg"), Some(".config")] {
2203 assert_eq!(
2204 config_home(var, Some("/home/u")),
2205 Some(PathBuf::from("/home/u/.config")),
2206 "{var:?}"
2207 );
2208 }
2209 }
2210
2211 #[test]
2212 fn without_xdg_config_home_and_home_there_is_no_config_directory() {
2213 for home in [None, Some("")] {
2214 for var in [None, Some(""), Some("relative")] {
2215 assert_eq!(config_home(var, home), None, "{var:?} {home:?}");
2216 }
2217 }
2218 }
2219}
2220
2221#[cfg(all(test, target_os = "linux", feature = "portal"))]
2222mod gnome_font_dpi_tests {
2223 use super::*;
2224
2225 #[test]
2228 fn gnome_desktops_fix_the_font_dpi() {
2229 assert_eq!(desktop_font_dpi(LinuxDesktop::Gnome), Some(96.0));
2230 assert_eq!(desktop_font_dpi(LinuxDesktop::Budgie), Some(96.0));
2231 assert_eq!(desktop_font_dpi(LinuxDesktop::Kde), None);
2232 assert_eq!(desktop_font_dpi(LinuxDesktop::Unknown), None);
2233 }
2234
2235 #[test]
2238 fn an_unknown_desktop_with_a_gnome_portal_has_gnomes_font_dpi() {
2239 for kdeglobals in [false, true] {
2240 let desktop =
2241 refine_linux_desktop(LinuxDesktop::Unknown, Some(LinuxDesktop::Gnome), || {
2242 kdeglobals
2243 });
2244 assert_eq!(desktop_font_dpi(desktop), Some(GNOME_FONT_DPI));
2245 assert_eq!(GNOME_FONT_DPI, 96.0);
2246 }
2247 }
2248}