1use arc_swap::ArcSwapOption;
4use std::sync::Arc;
5
6#[cfg(target_os = "linux")]
11const SUBPROCESS_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
12
13#[cfg(target_os = "linux")]
15#[non_exhaustive]
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
17pub enum LinuxDesktop {
18 Kde,
20 Gnome,
22 Xfce,
24 Cinnamon,
26 Mate,
28 LxQt,
30 Budgie,
32 Hyprland,
34 Sway,
36 River,
38 Niri,
40 Wayfire,
42 CosmicDe,
44 Unknown,
46}
47
48#[cfg(target_os = "linux")]
51pub(crate) fn xdg_current_desktop() -> String {
52 std::env::var("XDG_CURRENT_DESKTOP").unwrap_or_default()
53}
54
55#[cfg(target_os = "linux")]
77#[must_use]
78pub fn detect_linux_desktop() -> LinuxDesktop {
79 parse_linux_desktop(&xdg_current_desktop())
80}
81
82#[cfg(target_os = "linux")]
88#[must_use]
89pub fn parse_linux_desktop(xdg_current_desktop: &str) -> LinuxDesktop {
90 for component in xdg_current_desktop.split(':') {
91 match component {
92 "KDE" => return LinuxDesktop::Kde,
93 "Budgie" => return LinuxDesktop::Budgie,
94 "GNOME" => return LinuxDesktop::Gnome,
95 "XFCE" => return LinuxDesktop::Xfce,
96 "X-Cinnamon" | "Cinnamon" => return LinuxDesktop::Cinnamon,
97 "MATE" => return LinuxDesktop::Mate,
98 "LXQt" => return LinuxDesktop::LxQt,
99 "Hyprland" => return LinuxDesktop::Hyprland,
100 "sway" => return LinuxDesktop::Sway,
101 "river" => return LinuxDesktop::River,
102 "niri" => return LinuxDesktop::Niri,
103 "Wayfire" => return LinuxDesktop::Wayfire,
104 "COSMIC" => return LinuxDesktop::CosmicDe,
105 _ => {}
106 }
107 }
108 LinuxDesktop::Unknown
109}
110
111#[must_use]
140pub fn system_is_dark() -> bool {
141 system().is_dark()
142}
143
144pub fn invalidate_caches() {
155 system().invalidate_all();
156}
157
158#[must_use]
166pub fn detect_is_dark() -> bool {
167 detect_is_dark_inner()
168}
169
170#[cfg(target_os = "linux")]
172const POLL_INTERVAL_CAP: std::time::Duration = std::time::Duration::from_millis(50);
173
174#[cfg(target_os = "linux")]
179fn poll_intervals() -> impl Iterator<Item = std::time::Duration> {
180 std::iter::successors(Some(std::time::Duration::from_millis(1)), |pause| {
181 Some(pause.saturating_mul(2).min(POLL_INTERVAL_CAP))
182 })
183}
184
185#[cfg(target_os = "linux")]
193fn run_with_timeout(program: &str, args: &[&str], timeout: std::time::Duration) -> Option<String> {
194 use std::io::Read;
195 use std::time::Instant;
196
197 let start = Instant::now();
198 let mut child = std::process::Command::new(program)
199 .args(args)
200 .stdout(std::process::Stdio::piped())
201 .stderr(std::process::Stdio::null())
202 .spawn()
203 .ok()?;
204
205 let mut intervals = poll_intervals();
206 loop {
207 match child.try_wait() {
208 Ok(Some(status)) if status.success() => {
209 let mut buf = String::new();
210 if let Some(mut stdout) = child.stdout.take() {
211 let _ = stdout.read_to_string(&mut buf);
212 }
213 return Some(buf);
214 }
215 Ok(Some(_)) => return None,
216 Ok(None) => {
217 let elapsed = start.elapsed();
218 if elapsed >= timeout {
219 if child.kill().is_ok() {
220 let _ = child.wait();
221 }
222 return None;
223 }
224 let pause = intervals.next().unwrap_or(POLL_INTERVAL_CAP);
225 std::thread::sleep(pause.min(timeout.saturating_sub(elapsed)));
226 }
227 Err(_) => return None,
228 }
229 }
230}
231
232#[cfg(target_os = "linux")]
241fn run_gsettings_with_timeout(args: &[&str]) -> Option<String> {
242 let out = run_with_timeout("gsettings", args, SUBPROCESS_TIMEOUT)?;
243 let trimmed = out.trim();
244 if trimmed.is_empty() {
245 None
246 } else {
247 Some(trimmed.to_string())
248 }
249}
250
251#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
256fn read_xft_dpi() -> Option<f32> {
257 let out = run_with_timeout("xrdb", &["-query"], SUBPROCESS_TIMEOUT)?;
258 for line in out.lines() {
260 if let Some(rest) = line.strip_prefix("Xft.dpi:")
261 && let Ok(dpi) = rest.trim().parse::<f32>()
262 && dpi > 0.0
263 {
264 return Some(dpi);
265 }
266 }
267 None
268}
269
270#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
280fn detect_physical_dpi() -> Option<f32> {
281 let out = run_with_timeout("xrandr", &[], SUBPROCESS_TIMEOUT)?;
282 parse_xrandr_dpi(&out)
283}
284
285#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
294fn parse_xrandr_dpi(output: &str) -> Option<f32> {
295 let line = output
297 .lines()
298 .find(|l| l.contains(" connected") && l.contains("primary"))
299 .or_else(|| {
300 output
301 .lines()
302 .find(|l| l.contains(" connected") && !l.contains("disconnected"))
303 })?;
304
305 let res_token = line
307 .split_whitespace()
308 .find(|s| s.contains('x') && s.contains('+'))?;
309 let (w_str, rest) = res_token.split_once('x')?;
310 let h_str = rest.split('+').next()?;
311 let w_px: f32 = w_str.parse().ok()?;
312 let h_px: f32 = h_str.parse().ok()?;
313
314 let words: Vec<&str> = line.split_whitespace().collect();
316 let mut w_mm = None;
317 let mut h_mm = None;
318 for window in words.windows(3) {
319 let [prev, cur, next] = window else { continue };
320 if *cur == "x" {
321 w_mm = prev.strip_suffix("mm").and_then(|n| n.parse::<f32>().ok());
322 h_mm = next.strip_suffix("mm").and_then(|n| n.parse::<f32>().ok());
323 }
324 }
325 let w_mm = w_mm.filter(|&v| v > 0.0)?;
326 let h_mm = h_mm.filter(|&v| v > 0.0)?;
327
328 let h_dpi = w_px / (w_mm / 25.4);
329 let v_dpi = h_px / (h_mm / 25.4);
330 let avg = (h_dpi + v_dpi) / 2.0;
331
332 if avg > 0.0 { Some(avg) } else { None }
333}
334
335#[cfg(all(test, target_os = "linux", any(feature = "kde", feature = "portal")))]
336#[allow(clippy::unwrap_used)]
337mod xrandr_dpi_tests {
338 use super::parse_xrandr_dpi;
339
340 #[test]
341 fn primary_4k_display() {
342 let output = "Screen 0: minimum 16 x 16, current 3840 x 2160, maximum 32767 x 32767\n\
344 DP-1 connected primary 3840x2160+0+0 (normal left inverted right x axis y axis) 700mm x 390mm\n\
345 3840x2160 60.00*+\n";
346 let dpi = parse_xrandr_dpi(output).unwrap();
347 assert!((dpi - 140.0).abs() < 1.0, "expected ~140 DPI, got {dpi}");
349 }
350
351 #[test]
352 fn standard_1080p_display() {
353 let output = "DP-2 connected primary 1920x1080+0+0 (normal) 530mm x 300mm\n";
354 let dpi = parse_xrandr_dpi(output).unwrap();
355 assert!((dpi - 92.0).abs() < 1.0, "expected ~92 DPI, got {dpi}");
357 }
358
359 #[test]
360 fn no_primary_falls_back_to_first_connected() {
361 let output = "HDMI-1 connected 1920x1080+0+0 (normal) 480mm x 270mm\n\
362 DP-1 disconnected\n";
363 let dpi = parse_xrandr_dpi(output).unwrap();
364 assert!(dpi > 90.0 && dpi < 110.0, "expected ~100 DPI, got {dpi}");
365 }
366
367 #[test]
368 fn disconnected_only_returns_none() {
369 let output = "DP-1 disconnected\nHDMI-1 disconnected\n";
370 assert!(parse_xrandr_dpi(output).is_none());
371 }
372
373 #[test]
374 fn missing_physical_dimensions_returns_none() {
375 let output = "DP-1 connected primary 1920x1080+0+0 (normal)\n";
377 assert!(parse_xrandr_dpi(output).is_none());
378 }
379
380 #[test]
381 fn zero_mm_returns_none() {
382 let output = "DP-1 connected primary 1920x1080+0+0 (normal) 0mm x 0mm\n";
383 assert!(parse_xrandr_dpi(output).is_none());
384 }
385
386 #[test]
387 fn empty_output_returns_none() {
388 assert!(parse_xrandr_dpi("").is_none());
389 }
390}
391
392#[allow(unreachable_code)]
405fn detect_system_font_dpi() -> f32 {
406 #[cfg(target_os = "macos")]
407 {
408 return 72.0;
409 }
410
411 #[cfg(all(target_os = "windows", feature = "windows"))]
412 {
413 return crate::windows::LOGICAL_DPI as f32;
414 }
415
416 #[cfg(all(target_os = "linux", feature = "kde"))]
418 {
419 if let Some(dpi) = read_kde_force_font_dpi() {
420 return dpi;
421 }
422 }
423
424 #[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
425 {
426 if let Some(dpi) = read_xft_dpi() {
427 return dpi;
428 }
429 if let Some(dpi) = detect_physical_dpi() {
430 return dpi;
431 }
432 }
433
434 96.0
435}
436
437#[cfg(all(target_os = "linux", feature = "kde"))]
443fn read_kde_force_font_dpi() -> Option<f32> {
444 let path = crate::kde::kdeglobals_path();
446 if let Ok(content) = std::fs::read_to_string(&path) {
447 let mut ini = crate::kde::create_kde_parser();
448 if ini.read(content).is_ok()
449 && let Some(dpi_str) = ini.get("General", "forceFontDPI")
450 && let Ok(dpi) = dpi_str.trim().parse::<f32>()
451 && dpi > 0.0
452 {
453 return Some(dpi);
454 }
455 }
456 if let Some(dpi_str) = crate::kde::read_kcmfontsrc_key("General", "forceFontDPI")
458 && let Ok(dpi) = dpi_str.trim().parse::<f32>()
459 && dpi > 0.0
460 {
461 return Some(dpi);
462 }
463 None
464}
465
466#[allow(unreachable_code)]
470fn detect_is_dark_inner() -> bool {
471 #[cfg(target_os = "linux")]
472 {
473 if let Ok(gtk_theme) = std::env::var("GTK_THEME") {
475 let lower = gtk_theme.to_lowercase();
476 if lower.ends_with(":dark") || lower.contains("-dark") {
477 return true;
478 }
479 }
480
481 #[cfg(feature = "kde")]
484 {
485 let de = parse_linux_desktop(&xdg_current_desktop());
486 if matches!(de, LinuxDesktop::Kde) {
487 let path = crate::kde::kdeglobals_path();
488 if let Ok(content) = std::fs::read_to_string(&path) {
489 let mut ini = crate::kde::create_kde_parser();
490 if ini.read(content).is_ok() {
491 return crate::kde::is_dark_theme(&ini);
492 }
493 }
494 }
495 }
496
497 if let Some(val) =
499 run_gsettings_with_timeout(&["get", "org.gnome.desktop.interface", "color-scheme"])
500 {
501 if val.contains("prefer-dark") {
502 return true;
503 }
504 if val.contains("prefer-light") || val.contains("default") {
505 return false;
506 }
507 }
508
509 #[cfg(feature = "kde")]
513 {
514 let path = crate::kde::kdeglobals_path();
515 if let Ok(content) = std::fs::read_to_string(&path) {
516 let mut ini = crate::kde::create_kde_parser();
517 if ini.read(content).is_ok() {
518 return crate::kde::is_dark_theme(&ini);
519 }
520 }
521 }
522
523 let config_home = std::env::var("XDG_CONFIG_HOME").unwrap_or_else(|_| {
525 let home = std::env::var("HOME").unwrap_or_default();
526 format!("{home}/.config")
527 });
528 let ini_path = format!("{config_home}/gtk-3.0/settings.ini");
529 if let Ok(content) = std::fs::read_to_string(&ini_path) {
530 for line in content.lines() {
531 let trimmed = line.trim();
532 if trimmed.starts_with("gtk-application-prefer-dark-theme")
533 && let Some(val) = trimmed.split('=').nth(1)
534 && (val.trim() == "1" || val.trim().eq_ignore_ascii_case("true"))
535 {
536 return true;
537 }
538 }
539 }
540
541 false
542 }
543
544 #[cfg(target_os = "macos")]
545 {
546 #[cfg(feature = "macos")]
549 {
550 use objc2_foundation::NSUserDefaults;
551 let defaults = NSUserDefaults::standardUserDefaults();
552 let key = objc2_foundation::ns_string!("AppleInterfaceStyle");
553 if let Some(value) = defaults.stringForKey(key) {
554 return value.to_string().eq_ignore_ascii_case("dark");
555 }
556 return false;
557 }
558 #[cfg(not(feature = "macos"))]
559 {
560 if let Ok(output) = std::process::Command::new("defaults")
561 .args(["read", "-g", "AppleInterfaceStyle"])
562 .output()
563 && output.status.success()
564 {
565 let val = String::from_utf8_lossy(&output.stdout);
566 return val.trim().eq_ignore_ascii_case("dark");
567 }
568 return false;
569 }
570 }
571
572 #[cfg(target_os = "windows")]
573 {
574 #[cfg(feature = "windows")]
575 {
576 let Ok(settings) = ::windows::UI::ViewManagement::UISettings::new() else {
578 return false;
579 };
580 let Ok(fg) =
581 settings.GetColorValue(::windows::UI::ViewManagement::UIColorType::Foreground)
582 else {
583 return false;
584 };
585 let luma = 0.299 * (fg.R as f32) + 0.587 * (fg.G as f32) + 0.114 * (fg.B as f32);
586 return luma > 128.0;
587 }
588 #[cfg(not(feature = "windows"))]
589 return false;
590 }
591
592 #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
593 {
594 false
595 }
596}
597
598#[must_use]
629pub fn prefers_reduced_motion() -> bool {
630 system().prefers_reduced_motion()
631}
632
633#[must_use]
641pub fn detect_reduced_motion() -> bool {
642 detect_reduced_motion_inner()
643}
644
645#[allow(unreachable_code)]
649fn detect_reduced_motion_inner() -> bool {
650 #[cfg(target_os = "linux")]
651 {
652 if let Some(val) =
655 run_gsettings_with_timeout(&["get", "org.gnome.desktop.interface", "enable-animations"])
656 {
657 return val.trim() == "false";
658 }
659 false
660 }
661
662 #[cfg(target_os = "macos")]
663 {
664 #[cfg(feature = "macos")]
665 {
666 let workspace = objc2_app_kit::NSWorkspace::sharedWorkspace();
667 return workspace.accessibilityDisplayShouldReduceMotion();
669 }
670 #[cfg(not(feature = "macos"))]
671 return false;
672 }
673
674 #[cfg(target_os = "windows")]
675 {
676 #[cfg(feature = "windows")]
677 {
678 let Ok(settings) = ::windows::UI::ViewManagement::UISettings::new() else {
679 return false;
680 };
681 return match settings.AnimationsEnabled() {
683 Ok(enabled) => !enabled,
684 Err(_) => false,
685 };
686 }
687 #[cfg(not(feature = "windows"))]
688 return false;
689 }
690
691 #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
692 {
693 false
694 }
695}
696
697pub struct DetectionContext {
712 is_dark: ArcSwapOption<bool>,
713 reduced_motion: ArcSwapOption<bool>,
714 icon_theme: ArcSwapOption<Result<String, crate::model::icons::IconThemeFailure>>,
715 #[cfg(target_os = "linux")]
716 linux_desktop: ArcSwapOption<LinuxDesktop>,
717}
718
719impl DetectionContext {
720 fn new() -> Self {
722 Self {
723 is_dark: ArcSwapOption::empty(),
724 reduced_motion: ArcSwapOption::empty(),
725 icon_theme: ArcSwapOption::empty(),
726 #[cfg(target_os = "linux")]
727 linux_desktop: ArcSwapOption::empty(),
728 }
729 }
730
731 #[must_use]
738 pub fn is_dark(&self) -> bool {
739 if let Some(v) = self.is_dark.load().as_deref() {
740 return *v;
741 }
742 let value = detect_is_dark_inner();
743 self.is_dark.store(Some(Arc::new(value)));
744 value
745 }
746
747 #[must_use]
753 pub fn prefers_reduced_motion(&self) -> bool {
754 if let Some(v) = self.reduced_motion.load().as_deref() {
755 return *v;
756 }
757 let value = detect_reduced_motion_inner();
758 self.reduced_motion.store(Some(Arc::new(value)));
759 value
760 }
761
762 pub fn icon_theme(&self) -> crate::Result<String> {
776 self.icon_theme_with(detect_icon_theme_inner)
777 }
778
779 fn icon_theme_with(
782 &self,
783 detect: impl FnOnce() -> Result<String, crate::model::icons::IconThemeFailure>,
784 ) -> crate::Result<String> {
785 let outcome = match self.icon_theme.load_full() {
786 Some(cached) => cached,
787 None => {
788 let detected = Arc::new(detect());
789 self.icon_theme.store(Some(Arc::clone(&detected)));
790 detected
791 }
792 };
793 match outcome.as_ref() {
794 Ok(theme) => Ok(theme.clone()),
795 Err(failure) => Err(failure.to_error()),
796 }
797 }
798
799 #[cfg(target_os = "linux")]
806 #[must_use]
807 pub fn linux_desktop(&self) -> LinuxDesktop {
808 if let Some(v) = self.linux_desktop.load().as_deref() {
809 return *v;
810 }
811 let value = detect_linux_desktop();
812 self.linux_desktop.store(Some(Arc::new(value)));
813 value
814 }
815
816 pub fn invalidate_is_dark(&self) {
818 self.is_dark.store(None);
819 }
820
821 pub fn invalidate_reduced_motion(&self) {
823 self.reduced_motion.store(None);
824 }
825
826 pub fn invalidate_icon_theme(&self) {
828 self.icon_theme.store(None);
829 }
830
831 #[cfg(target_os = "linux")]
833 pub fn invalidate_linux_desktop(&self) {
834 self.linux_desktop.store(None);
835 }
836
837 pub fn invalidate_all(&self) {
839 self.invalidate_is_dark();
840 self.invalidate_reduced_motion();
841 self.invalidate_icon_theme();
842 #[cfg(target_os = "linux")]
843 self.invalidate_linux_desktop();
844 }
845}
846
847pub fn system() -> &'static DetectionContext {
852 static INSTANCE: std::sync::OnceLock<DetectionContext> = std::sync::OnceLock::new();
853 INSTANCE.get_or_init(DetectionContext::new)
854}
855
856fn detect_icon_theme_inner() -> Result<String, crate::model::icons::IconThemeFailure> {
861 crate::model::icons::detect_icon_theme_outcome()
862}
863
864#[cfg(all(target_os = "linux", feature = "portal"))]
868pub(crate) fn gsettings_get(schema: &str, key: &str) -> Option<String> {
869 run_gsettings_with_timeout(&["get", schema, key])
870}
871
872#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
874pub(crate) fn xft_dpi() -> Option<f32> {
875 read_xft_dpi()
876}
877
878#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
880pub(crate) fn physical_dpi() -> Option<f32> {
881 detect_physical_dpi()
882}
883
884pub(crate) fn system_font_dpi() -> f32 {
886 detect_system_font_dpi()
887}
888
889#[cfg(test)]
890#[allow(clippy::unwrap_used, clippy::expect_used)]
891mod reduced_motion_tests {
892 use super::*;
893
894 #[test]
895 fn prefers_reduced_motion_smoke_test() {
896 let _result = prefers_reduced_motion();
900 }
901
902 #[cfg(target_os = "linux")]
903 #[test]
904 fn detect_reduced_motion_inner_linux() {
905 let result = detect_reduced_motion_inner();
909 let _ = result;
911 }
912
913 #[cfg(target_os = "macos")]
914 #[test]
915 fn detect_reduced_motion_inner_macos() {
916 let result = detect_reduced_motion_inner();
917 let _ = result;
918 }
919
920 #[cfg(target_os = "windows")]
921 #[test]
922 fn detect_reduced_motion_inner_windows() {
923 let result = detect_reduced_motion_inner();
924 let _ = result;
925 }
926}
927
928#[cfg(test)]
929mod detection_context_tests {
930 use super::*;
931
932 #[test]
933 fn system_returns_same_instance() {
934 let a = system() as *const DetectionContext;
935 let b = system() as *const DetectionContext;
936 assert_eq!(a, b);
937 }
938
939 #[test]
940 fn is_dark_caches_result() {
941 let ctx = DetectionContext::new();
942 let first = ctx.is_dark();
943 let second = ctx.is_dark();
944 assert_eq!(first, second);
945 }
946
947 #[test]
948 fn invalidate_is_dark_clears_cache() {
949 let ctx = DetectionContext::new();
950 let _ = ctx.is_dark(); ctx.invalidate_is_dark();
952 let _ = ctx.is_dark();
954 }
955
956 #[test]
957 fn prefers_reduced_motion_caches_result() {
958 let ctx = DetectionContext::new();
959 let first = ctx.prefers_reduced_motion();
960 let second = ctx.prefers_reduced_motion();
961 assert_eq!(first, second);
962 }
963
964 #[test]
965 fn invalidate_all_clears_all_caches() {
966 let ctx = DetectionContext::new();
967 let _ = ctx.is_dark();
968 let _ = ctx.prefers_reduced_motion();
969 let _ = ctx.icon_theme();
970 ctx.invalidate_all();
971 let _ = ctx.is_dark();
973 let _ = ctx.prefers_reduced_motion();
974 let _ = ctx.icon_theme();
975 }
976
977 fn undetected() -> Result<String, crate::model::icons::IconThemeFailure> {
978 Err(crate::model::icons::IconThemeFailure::for_tests(
979 "the test's failing detection",
980 ))
981 }
982
983 #[test]
984 fn a_failed_icon_theme_detection_is_cached_and_reported() {
985 let ctx = DetectionContext::new();
986 let runs = std::cell::Cell::new(0);
987 let detect = || {
988 runs.set(runs.get() + 1);
989 undetected()
990 };
991 let first = ctx.icon_theme_with(detect);
992 let second = ctx.icon_theme_with(detect);
993 assert_eq!(runs.get(), 1, "a failed detection ran again");
994 for outcome in [first, second] {
995 match outcome {
996 Ok(name) => panic!("a failed detection gave the theme {name}"),
997 Err(e) => assert!(
998 e.to_string().contains("the test's failing detection"),
999 "got: {e}"
1000 ),
1001 }
1002 }
1003 }
1004
1005 #[test]
1006 fn invalidate_icon_theme_clears_a_cached_failure() {
1007 let ctx = DetectionContext::new();
1008 assert!(ctx.icon_theme_with(undetected).is_err());
1009 ctx.invalidate_icon_theme();
1010 let theme = ctx.icon_theme_with(|| Ok("breeze".to_string()));
1011 assert_eq!(theme.ok().as_deref(), Some("breeze"));
1012 }
1013
1014 #[test]
1015 fn invalidate_all_clears_a_cached_failure() {
1016 let ctx = DetectionContext::new();
1017 assert!(ctx.icon_theme_with(undetected).is_err());
1018 ctx.invalidate_all();
1019 let theme = ctx.icon_theme_with(|| Ok("breeze".to_string()));
1020 assert_eq!(theme.ok().as_deref(), Some("breeze"));
1021 }
1022
1023 #[cfg(target_os = "linux")]
1024 #[test]
1025 fn linux_desktop_caches_result() {
1026 let ctx = DetectionContext::new();
1027 let first = ctx.linux_desktop();
1028 let second = ctx.linux_desktop();
1029 assert_eq!(first, second);
1030 }
1031
1032 #[cfg(target_os = "linux")]
1033 #[test]
1034 fn invalidate_linux_desktop_clears_cache() {
1035 let ctx = DetectionContext::new();
1036 let _ = ctx.linux_desktop();
1037 ctx.invalidate_linux_desktop();
1038 let _ = ctx.linux_desktop(); }
1040}
1041
1042#[cfg(all(test, target_os = "linux"))]
1043#[allow(clippy::unwrap_used, clippy::expect_used)]
1044mod subprocess_tests {
1045 use super::*;
1046 use std::path::PathBuf;
1047 use std::time::{Duration, Instant};
1048
1049 fn on_path(program: &str) -> bool {
1051 std::env::var_os("PATH")
1052 .is_some_and(|path| std::env::split_paths(&path).any(|dir| dir.join(program).is_file()))
1053 }
1054
1055 #[test]
1056 fn poll_intervals_double_from_1_ms_up_to_50_ms() {
1057 let intervals: Vec<Duration> = poll_intervals().take(10).collect();
1058 let expected: Vec<Duration> = [1, 2, 4, 8, 16, 32, 50, 50, 50, 50]
1059 .into_iter()
1060 .map(Duration::from_millis)
1061 .collect();
1062 assert_eq!(intervals, expected);
1063 }
1064
1065 #[test]
1066 fn run_with_timeout_returns_stdout_of_a_successful_command() {
1067 if !on_path("echo") {
1068 eprintln!("skipped: echo is not installed");
1069 return;
1070 }
1071 let out = run_with_timeout("echo", &["hi"], SUBPROCESS_TIMEOUT);
1072 assert_eq!(out.as_deref().map(str::trim), Some("hi"));
1073 }
1074
1075 #[test]
1076 fn run_with_timeout_returns_none_for_a_failing_command() {
1077 if !on_path("false") {
1078 eprintln!("skipped: false is not installed");
1079 return;
1080 }
1081 assert_eq!(run_with_timeout("false", &[], SUBPROCESS_TIMEOUT), None);
1082 }
1083
1084 #[test]
1085 fn run_with_timeout_returns_none_for_a_missing_program() {
1086 assert_eq!(
1087 run_with_timeout("nt-test-no-such-program", &[], SUBPROCESS_TIMEOUT),
1088 None
1089 );
1090 }
1091
1092 #[test]
1095 fn run_with_timeout_returns_the_empty_stdout_of_a_quiet_command() {
1096 if !on_path("true") {
1097 eprintln!("skipped: true is not installed");
1098 return;
1099 }
1100 let start = Instant::now();
1101 assert_eq!(
1102 run_with_timeout("true", &[], SUBPROCESS_TIMEOUT).as_deref(),
1103 Some("")
1104 );
1105 eprintln!("`true` ran in {:?}", start.elapsed());
1106 }
1107
1108 #[test]
1109 fn run_with_timeout_kills_a_command_that_outlives_the_timeout() {
1110 if !on_path("sleep") {
1111 eprintln!("skipped: sleep is not installed");
1112 return;
1113 }
1114 let seconds = format!("5.{}", std::process::id());
1115 let start = Instant::now();
1116 let out = run_with_timeout("sleep", &[&seconds], Duration::from_millis(100));
1117 let elapsed = start.elapsed();
1118 assert_eq!(out, None);
1119 assert!(elapsed < Duration::from_secs(1), "took {elapsed:?}");
1120 let cmdline = format!("sleep\0{seconds}\0");
1121 let still_running: Vec<PathBuf> = std::fs::read_dir("/proc")
1122 .unwrap()
1123 .flatten()
1124 .map(|entry| entry.path().join("cmdline"))
1125 .filter(|path| std::fs::read(path).is_ok_and(|bytes| bytes == cmdline.as_bytes()))
1126 .collect();
1127 assert!(still_running.is_empty(), "not killed: {still_running:?}");
1128 }
1129}