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() {
232 system().invalidate_all();
233}
234
235#[must_use]
243pub fn detect_is_dark() -> bool {
244 detect_is_dark_inner()
245}
246
247#[cfg(unix)]
249#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
250const POLL_INTERVAL_CAP: std::time::Duration = std::time::Duration::from_millis(50);
251
252#[cfg(unix)]
257#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
258fn poll_intervals() -> impl Iterator<Item = std::time::Duration> {
259 std::iter::successors(Some(std::time::Duration::from_millis(1)), |pause| {
260 Some(pause.saturating_mul(2).min(POLL_INTERVAL_CAP))
261 })
262}
263
264#[cfg(unix)]
280#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
281pub(crate) fn run_with_timeout(
282 program: &str,
283 args: &[&str],
284 timeout: std::time::Duration,
285) -> std::io::Result<std::process::Output> {
286 use std::process::{Child, Command, Stdio};
287 use std::sync::mpsc::{Receiver, RecvTimeoutError};
288 use std::time::Instant;
289
290 fn kill_and_reap(child: &mut Child) {
291 if child.kill().is_ok() {
292 let _ = child.wait();
293 }
294 }
295
296 let timed_out = || {
297 std::io::Error::new(
298 std::io::ErrorKind::TimedOut,
299 format!("timed out after {timeout:?}"),
300 )
301 };
302
303 let start = Instant::now();
304 let mut child = Command::new(program)
305 .args(args)
306 .stdin(Stdio::null())
307 .stdout(Stdio::piped())
308 .stderr(Stdio::piped())
309 .spawn()?;
310 let readers = read_on_a_thread(child.stdout.take())
311 .and_then(|stdout| Ok((stdout, read_on_a_thread(child.stderr.take())?)));
312 let (stdout, stderr) = match readers {
313 Ok(readers) => readers,
314 Err(e) => {
315 kill_and_reap(&mut child);
316 return Err(e);
317 }
318 };
319
320 let mut intervals = poll_intervals();
321 let status = loop {
322 match child.try_wait() {
323 Ok(Some(status)) => break status,
324 Ok(None) => {
325 let elapsed = start.elapsed();
326 if elapsed >= timeout {
327 kill_and_reap(&mut child);
328 return Err(timed_out());
329 }
330 let pause = intervals.next().unwrap_or(POLL_INTERVAL_CAP);
331 std::thread::sleep(pause.min(timeout.saturating_sub(elapsed)));
332 }
333 Err(e) => {
334 kill_and_reap(&mut child);
335 return Err(e);
336 }
337 }
338 };
339
340 let received = |reader: Receiver<Vec<u8>>| {
341 reader
342 .recv_timeout(timeout.saturating_sub(start.elapsed()))
343 .map_err(|e| match e {
344 RecvTimeoutError::Timeout => timed_out(),
345 RecvTimeoutError::Disconnected => {
346 std::io::Error::other("the output reader stopped without a result")
347 }
348 })
349 };
350 Ok(std::process::Output {
351 status,
352 stdout: received(stdout)?,
353 stderr: received(stderr)?,
354 })
355}
356
357#[cfg(unix)]
360#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
361fn read_on_a_thread(
362 pipe: Option<impl std::io::Read + Send + 'static>,
363) -> std::io::Result<std::sync::mpsc::Receiver<Vec<u8>>> {
364 let (sender, receiver) = std::sync::mpsc::channel();
365 match pipe {
366 Some(mut pipe) => {
367 std::thread::Builder::new()
368 .name("native-theme-subprocess-output".to_string())
369 .spawn(move || {
370 let mut read = Vec::new();
371 let _ = pipe.read_to_end(&mut read);
372 let _ = sender.send(read);
373 })?;
374 }
375 None => {
376 let _ = sender.send(Vec::new());
377 }
378 }
379 Ok(receiver)
380}
381
382#[cfg(unix)]
385#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
386pub(crate) fn stdout_with_timeout(
387 program: &str,
388 args: &[&str],
389 timeout: std::time::Duration,
390) -> Option<String> {
391 let output = run_with_timeout(program, args, timeout).ok()?;
392 if !output.status.success() {
393 return None;
394 }
395 String::from_utf8(output.stdout).ok()
396}
397
398#[cfg(target_os = "linux")]
401pub(crate) fn xdg_config_home() -> Option<std::path::PathBuf> {
402 xdg_config_home_from(
403 std::env::var_os("XDG_CONFIG_HOME").as_deref(),
404 std::env::var_os("HOME").as_deref(),
405 )
406}
407
408#[cfg(target_os = "linux")]
418fn xdg_config_home_from(
419 var: Option<&std::ffi::OsStr>,
420 home: Option<&std::ffi::OsStr>,
421) -> Option<std::path::PathBuf> {
422 var.map(std::path::PathBuf::from)
423 .filter(|dir| dir.is_absolute())
424 .or_else(|| {
425 home.filter(|home| !home.is_empty())
426 .map(|home| std::path::Path::new(home).join(".config"))
427 })
428}
429
430#[cfg(target_os = "linux")]
432pub(crate) const CONFIG_HOME_UNRESOLVED: &str = "the config directory is unresolved: \
433 $XDG_CONFIG_HOME is not an absolute path and $HOME is unset or empty";
434
435#[cfg(target_os = "linux")]
441pub(crate) fn gsettings_get(
442 schema: &str,
443 key: &str,
444 timeout: std::time::Duration,
445) -> Option<String> {
446 let out = stdout_with_timeout("gsettings", &["get", schema, key], timeout)?;
447 let trimmed = out.trim();
448 if trimmed.is_empty() {
449 None
450 } else {
451 Some(trimmed.to_string())
452 }
453}
454
455#[cfg(target_os = "linux")]
474pub(crate) const LINUX_FONT_DPI: f32 = 96.0;
475
476#[allow(unreachable_code)]
489fn detect_system_font_dpi() -> f32 {
490 #[cfg(target_os = "macos")]
491 {
492 return 72.0;
493 }
494
495 #[cfg(all(target_os = "windows", feature = "windows"))]
496 {
497 return crate::windows::LOGICAL_DPI as f32;
498 }
499
500 #[cfg(target_os = "linux")]
501 {
502 return LINUX_FONT_DPI;
503 }
504
505 96.0
506}
507
508#[cfg(all(target_os = "linux", feature = "portal"))]
510pub(crate) fn session_type() -> Option<String> {
511 std::env::var("XDG_SESSION_TYPE").ok()
512}
513
514#[cfg(target_os = "linux")]
520pub(crate) fn color_scheme_is_dark(
521 portal: Option<bool>,
522 gsetting: impl FnOnce(&str, &str) -> Option<String>,
523) -> Option<bool> {
524 if portal.is_some() {
525 return portal;
526 }
527 let val = gsetting("org.gnome.desktop.interface", "color-scheme")?;
528 if val.contains("prefer-dark") {
529 Some(true)
530 } else if val.contains("prefer-light") || val.contains("default") {
531 Some(false)
532 } else {
533 None
534 }
535}
536
537#[cfg(target_os = "linux")]
543fn desktop_is_dark(
544 detection: &DetectionContext,
545 kdeglobals: impl FnOnce() -> Option<bool>,
546 gsettings: impl FnOnce() -> Option<bool>,
547) -> Option<bool> {
548 if detection.refined_linux_desktop_sync() == LinuxDesktop::Kde {
549 kdeglobals().or_else(gsettings)
550 } else {
551 gsettings().or_else(kdeglobals)
552 }
553}
554
555fn detect_is_dark_inner() -> bool {
559 #[cfg(target_os = "linux")]
560 {
561 if let Ok(gtk_theme) = std::env::var("GTK_THEME") {
563 let lower = gtk_theme.to_lowercase();
564 if lower.ends_with(":dark") || lower.contains("-dark") {
565 return true;
566 }
567 }
568
569 if let Some(dark) = desktop_is_dark(
570 system(),
571 || {
572 #[cfg(feature = "kde")]
573 {
574 crate::kde::kdeglobals_is_dark()
575 }
576 #[cfg(not(feature = "kde"))]
577 {
578 None
579 }
580 },
581 || {
582 color_scheme_is_dark(None, |schema, key| {
583 gsettings_get(schema, key, SUBPROCESS_TIMEOUT)
584 })
585 },
586 ) {
587 return dark;
588 }
589
590 if let Some(content) = xdg_config_home()
592 .and_then(|dir| std::fs::read_to_string(dir.join("gtk-3.0/settings.ini")).ok())
593 {
594 for line in content.lines() {
595 let trimmed = line.trim();
596 if trimmed.starts_with("gtk-application-prefer-dark-theme")
597 && let Some(val) = trimmed.split('=').nth(1)
598 && (val.trim() == "1" || val.trim().eq_ignore_ascii_case("true"))
599 {
600 return true;
601 }
602 }
603 }
604
605 false
606 }
607
608 #[cfg(target_os = "macos")]
609 {
610 #[cfg(feature = "macos")]
613 {
614 use objc2_foundation::NSUserDefaults;
615 let defaults = NSUserDefaults::standardUserDefaults();
616 let key = objc2_foundation::ns_string!("AppleInterfaceStyle");
617 defaults
618 .stringForKey(key)
619 .is_some_and(|value| value.to_string().eq_ignore_ascii_case("dark"))
620 }
621 #[cfg(not(feature = "macos"))]
622 {
623 stdout_with_timeout(
624 "defaults",
625 &["read", "-g", "AppleInterfaceStyle"],
626 SUBPROCESS_TIMEOUT,
627 )
628 .is_some_and(|value| value.trim().eq_ignore_ascii_case("dark"))
629 }
630 }
631
632 #[cfg(target_os = "windows")]
633 {
634 #[cfg(feature = "windows")]
635 {
636 let Ok(settings) = ::windows::UI::ViewManagement::UISettings::new() else {
637 return false;
638 };
639 let Ok(fg) =
640 settings.GetColorValue(::windows::UI::ViewManagement::UIColorType::Foreground)
641 else {
642 return false;
643 };
644 crate::windows::is_dark_mode(&crate::windows::win_color_to_rgba(fg))
645 }
646 #[cfg(not(feature = "windows"))]
647 {
648 false
649 }
650 }
651
652 #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
653 {
654 false
655 }
656}
657
658#[must_use]
700pub fn prefers_reduced_motion() -> bool {
701 system().prefers_reduced_motion()
702}
703
704#[must_use]
712pub fn detect_reduced_motion() -> bool {
713 detect_reduced_motion_inner()
714}
715
716#[must_use]
741pub fn accessibility_preferences() -> crate::AccessibilityPreferences {
742 system().accessibility_preferences()
743}
744
745#[cfg(target_os = "linux")]
751pub(crate) fn gnome_reduce_motion(
752 portal: Option<bool>,
753 gsetting: impl FnOnce(&str, &str) -> Option<String>,
754) -> Option<bool> {
755 if portal.is_some() {
756 return portal;
757 }
758 let enabled = gsetting("org.gnome.desktop.interface", "enable-animations")?;
759 enabled.trim().parse::<bool>().ok().map(|enabled| !enabled)
760}
761
762#[cfg(target_os = "linux")]
769fn desktop_reduce_motion(
770 desktop: LinuxDesktop,
771 kdeglobals: impl FnOnce() -> Option<bool>,
772 portal: impl FnOnce() -> Option<bool>,
773 gsetting: impl FnOnce(&str, &str) -> Option<String>,
774) -> bool {
775 match desktop {
776 LinuxDesktop::Kde => kdeglobals().or_else(|| gnome_reduce_motion(None, gsetting)),
777 LinuxDesktop::Gnome | LinuxDesktop::Budgie => gnome_reduce_motion(portal(), gsetting),
778 _ => gnome_reduce_motion(None, gsetting),
779 }
780 .unwrap_or(false)
781}
782
783fn detect_reduced_motion_inner() -> bool {
787 #[cfg(target_os = "linux")]
788 {
789 desktop_reduce_motion(
790 system().refined_linux_desktop_sync(),
791 || {
792 #[cfg(feature = "kde")]
793 {
794 Some(crate::kde::kdeglobals_reduce_motion())
795 }
796 #[cfg(not(feature = "kde"))]
797 {
798 None
799 }
800 },
801 || {
802 #[cfg(feature = "portal")]
803 {
804 pollster::block_on(crate::gnome::portal_reduce_motion())
805 }
806 #[cfg(not(feature = "portal"))]
807 {
808 None
809 }
810 },
811 |schema, key| gsettings_get(schema, key, SUBPROCESS_TIMEOUT),
812 )
813 }
814
815 #[cfg(target_os = "macos")]
816 {
817 #[cfg(feature = "macos")]
818 {
819 crate::macos::reduce_motion()
820 }
821 #[cfg(not(feature = "macos"))]
822 {
823 false
824 }
825 }
826
827 #[cfg(target_os = "windows")]
828 {
829 #[cfg(feature = "windows")]
830 {
831 crate::windows::read_reduce_motion().unwrap_or(false)
832 }
833 #[cfg(not(feature = "windows"))]
834 {
835 false
836 }
837 }
838
839 #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
840 {
841 false
842 }
843}
844
845struct Stamped<T> {
849 generation: u64,
850 value: T,
851}
852
853struct CacheSlot<T> {
858 value: ArcSwapOption<Stamped<T>>,
859 generation: AtomicU64,
860}
861
862pub(crate) struct CacheFill<T> {
864 generation: u64,
865 seen: Option<Arc<Stamped<T>>>,
866}
867
868impl<T> CacheFill<T> {
869 fn cached(&self) -> Option<&T> {
871 self.seen
872 .as_deref()
873 .filter(|entry| entry.generation == self.generation)
874 .map(|entry| &entry.value)
875 }
876}
877
878impl<T> CacheSlot<T> {
879 fn empty() -> Self {
880 Self {
881 value: ArcSwapOption::empty(),
882 generation: AtomicU64::new(0),
883 }
884 }
885
886 fn begin_fill(&self) -> CacheFill<T> {
891 let generation = self.generation.load(Ordering::Acquire);
892 CacheFill {
893 generation,
894 seen: self.value.load_full(),
895 }
896 }
897
898 fn finish_fill(&self, fill: CacheFill<T>, value: T) {
901 if self.generation.load(Ordering::Acquire) != fill.generation {
902 return;
903 }
904 let stamped = Arc::new(Stamped {
905 generation: fill.generation,
906 value,
907 });
908 let _ = self.value.compare_and_swap(&fill.seen, Some(stamped));
909 }
910
911 fn get_or_fill(&self, detect: impl FnOnce() -> T) -> T
914 where
915 T: Clone,
916 {
917 let fill = self.begin_fill();
918 if let Some(value) = fill.cached() {
919 return value.clone();
920 }
921 let value = detect();
922 self.finish_fill(fill, value.clone());
923 value
924 }
925
926 #[cfg(any(test, target_os = "linux"))]
928 fn get(&self) -> Option<T>
929 where
930 T: Clone,
931 {
932 self.begin_fill().cached().cloned()
933 }
934
935 fn invalidate(&self) {
936 self.value.store(None);
937 self.generation.fetch_add(1, Ordering::Release);
938 }
939}
940
941pub struct DetectionContext {
956 is_dark: CacheSlot<bool>,
957 reduced_motion: CacheSlot<bool>,
958 reader_accessibility: CacheSlot<crate::AccessibilityPreferences>,
959 icon_theme: CacheSlot<Result<String, IconThemeFailure>>,
960 #[cfg(target_os = "linux")]
961 linux_desktop: CacheSlot<LinuxDesktop>,
962 #[cfg(target_os = "linux")]
963 refined_linux_desktop: CacheSlot<RefinedDesktop>,
964}
965
966impl DetectionContext {
967 pub(crate) fn new() -> Self {
969 Self {
970 is_dark: CacheSlot::empty(),
971 reduced_motion: CacheSlot::empty(),
972 reader_accessibility: CacheSlot::empty(),
973 icon_theme: CacheSlot::empty(),
974 #[cfg(target_os = "linux")]
975 linux_desktop: CacheSlot::empty(),
976 #[cfg(target_os = "linux")]
977 refined_linux_desktop: CacheSlot::empty(),
978 }
979 }
980
981 #[must_use]
988 pub fn is_dark(&self) -> bool {
989 self.is_dark.get_or_fill(detect_is_dark_inner)
990 }
991
992 #[must_use]
998 pub fn prefers_reduced_motion(&self) -> bool {
999 self.reduced_motion.get_or_fill(detect_reduced_motion_inner)
1000 }
1001
1002 #[must_use]
1010 pub fn accessibility_preferences(&self) -> crate::AccessibilityPreferences {
1011 self.reader_accessibility_with(|| {
1012 pollster::block_on(crate::pipeline::reader_accessibility())
1013 })
1014 }
1015
1016 pub(crate) fn reader_accessibility_with(
1019 &self,
1020 read: impl FnOnce() -> crate::AccessibilityPreferences,
1021 ) -> crate::AccessibilityPreferences {
1022 self.reader_accessibility.get_or_fill(read)
1023 }
1024
1025 pub(crate) fn begin_reader_accessibility(&self) -> CacheFill<crate::AccessibilityPreferences> {
1029 self.reader_accessibility.begin_fill()
1030 }
1031
1032 pub(crate) fn store_reader_accessibility(
1035 &self,
1036 fill: CacheFill<crate::AccessibilityPreferences>,
1037 prefs: crate::AccessibilityPreferences,
1038 ) {
1039 self.reader_accessibility.finish_fill(fill, prefs);
1040 }
1041
1042 pub fn icon_theme(&self) -> crate::Result<String> {
1056 self.icon_theme_with(detect_icon_theme_inner)
1057 }
1058
1059 fn icon_theme_with(
1062 &self,
1063 detect: impl FnOnce() -> Result<String, IconThemeFailure>,
1064 ) -> crate::Result<String> {
1065 self.icon_theme
1066 .get_or_fill(detect)
1067 .map_err(|failure| failure.to_error())
1068 }
1069
1070 #[cfg(target_os = "linux")]
1077 #[must_use]
1078 pub fn linux_desktop(&self) -> LinuxDesktop {
1079 self.linux_desktop.get_or_fill(detect_linux_desktop)
1080 }
1081
1082 #[cfg(target_os = "linux")]
1090 pub(crate) async fn refined_linux_desktop(&self) -> RefinedDesktop {
1091 let fill = self.refined_linux_desktop.begin_fill();
1092 if let Some(v) = fill.cached() {
1093 return *v;
1094 }
1095 let raw = self.linux_desktop();
1096 #[cfg(feature = "portal")]
1097 let portal_backend = if raw == LinuxDesktop::Unknown {
1098 crate::gnome::detect_portal_backend().await
1099 } else {
1100 None
1101 };
1102 #[cfg(not(feature = "portal"))]
1103 let portal_backend = None;
1104 let refined = refine_desktop(raw, portal_backend, kdeglobals_exists);
1105 let without_portal = refine_linux_desktop(raw, None, kdeglobals_exists);
1106 self.finish_refined_desktop(fill, refined, without_portal);
1107 refined
1108 }
1109
1110 #[cfg(target_os = "linux")]
1116 fn finish_refined_desktop(
1117 &self,
1118 fill: CacheFill<RefinedDesktop>,
1119 refined: RefinedDesktop,
1120 without_portal: LinuxDesktop,
1121 ) {
1122 self.refined_linux_desktop.finish_fill(fill, refined);
1123 if refined.desktop != without_portal {
1124 self.invalidate_icon_theme();
1125 self.invalidate_is_dark();
1126 self.invalidate_reduced_motion();
1127 }
1128 }
1129
1130 #[cfg(target_os = "linux")]
1150 #[must_use]
1151 pub fn refined_linux_desktop_sync(&self) -> LinuxDesktop {
1152 if let Some(v) = self.refined_linux_desktop.get() {
1153 return v.desktop;
1154 }
1155 refine_linux_desktop(self.linux_desktop(), None, kdeglobals_exists)
1156 }
1157
1158 pub(crate) fn font_dpi(&self) -> f32 {
1162 detect_system_font_dpi()
1163 }
1164
1165 pub fn invalidate_is_dark(&self) {
1167 self.is_dark.invalidate();
1168 }
1169
1170 pub fn invalidate_reduced_motion(&self) {
1172 self.reduced_motion.invalidate();
1173 }
1174
1175 pub fn invalidate_accessibility_preferences(&self) {
1177 self.reader_accessibility.invalidate();
1178 }
1179
1180 pub fn invalidate_icon_theme(&self) {
1182 self.icon_theme.invalidate();
1183 }
1184
1185 pub fn invalidate_font_dpi(&self) {}
1189
1190 #[cfg(target_os = "linux")]
1193 pub fn invalidate_linux_desktop(&self) {
1194 self.linux_desktop.invalidate();
1195 self.refined_linux_desktop.invalidate();
1196 }
1197
1198 pub fn invalidate_all(&self) {
1200 self.invalidate_is_dark();
1201 self.invalidate_reduced_motion();
1202 self.invalidate_accessibility_preferences();
1203 self.invalidate_icon_theme();
1204 #[cfg(target_os = "linux")]
1205 self.invalidate_linux_desktop();
1206 }
1207}
1208
1209pub fn system() -> &'static DetectionContext {
1214 static INSTANCE: std::sync::OnceLock<DetectionContext> = std::sync::OnceLock::new();
1215 INSTANCE.get_or_init(DetectionContext::new)
1216}
1217
1218fn detect_icon_theme_inner() -> Result<String, IconThemeFailure> {
1223 icon_theme::detect_icon_theme_outcome()
1224}
1225
1226pub(crate) fn system_font_dpi() -> f32 {
1230 system().font_dpi()
1231}
1232
1233#[cfg(test)]
1234#[allow(clippy::unwrap_used, clippy::expect_used)]
1235mod reduced_motion_tests {
1236 use super::*;
1237
1238 #[test]
1239 fn prefers_reduced_motion_smoke_test() {
1240 let _result = prefers_reduced_motion();
1244 }
1245
1246 #[cfg(target_os = "linux")]
1247 #[test]
1248 fn detect_reduced_motion_inner_linux() {
1249 let result = detect_reduced_motion_inner();
1253 let _ = result;
1255 }
1256
1257 #[cfg(target_os = "linux")]
1260 fn animations<'a>(
1261 enabled: &'static str,
1262 asked: &'a std::cell::Cell<u32>,
1263 ) -> impl FnOnce(&str, &str) -> Option<String> + 'a {
1264 move |schema, key| {
1265 asked.set(asked.get() + 1);
1266 ((schema, key) == ("org.gnome.desktop.interface", "enable-animations"))
1267 .then(|| enabled.to_string())
1268 }
1269 }
1270
1271 #[cfg(target_os = "linux")]
1276 #[test]
1277 fn kde_reduced_motion_is_kdeglobals_not_gsettings() {
1278 let asked = std::cell::Cell::new(0);
1279 let portal = || -> Option<bool> { panic!("KDE does not ask the portal") };
1280 assert!(desktop_reduce_motion(
1281 LinuxDesktop::Kde,
1282 || Some(true),
1283 portal,
1284 animations("true", &asked)
1285 ));
1286 assert!(!desktop_reduce_motion(
1287 LinuxDesktop::Kde,
1288 || Some(false),
1289 portal,
1290 animations("false", &asked)
1291 ));
1292 assert_eq!(asked.get(), 0);
1293 assert!(desktop_reduce_motion(
1294 LinuxDesktop::Kde,
1295 || None,
1296 portal,
1297 animations("false", &asked)
1298 ));
1299 assert_eq!(asked.get(), 1);
1300 }
1301
1302 #[cfg(target_os = "linux")]
1305 #[test]
1306 fn gnome_reduced_motion_is_the_portal_then_gsettings() {
1307 let asked = std::cell::Cell::new(0);
1308 let kdeglobals = || -> Option<bool> { panic!("GNOME does not read kdeglobals") };
1309 for desktop in [LinuxDesktop::Gnome, LinuxDesktop::Budgie] {
1310 assert!(desktop_reduce_motion(
1311 desktop,
1312 kdeglobals,
1313 || Some(true),
1314 animations("true", &asked)
1315 ));
1316 assert!(!desktop_reduce_motion(
1317 desktop,
1318 kdeglobals,
1319 || Some(false),
1320 animations("false", &asked)
1321 ));
1322 assert_eq!(asked.get(), 0);
1323 assert!(desktop_reduce_motion(
1324 desktop,
1325 kdeglobals,
1326 || None,
1327 animations("false", &asked)
1328 ));
1329 assert_eq!(asked.get(), 1);
1330 asked.set(0);
1331 }
1332 }
1333
1334 #[cfg(target_os = "linux")]
1336 #[test]
1337 fn other_desktops_reduced_motion_is_gsettings() {
1338 let asked = std::cell::Cell::new(0);
1339 assert!(desktop_reduce_motion(
1340 LinuxDesktop::Xfce,
1341 || -> Option<bool> { panic!("XFCE does not read kdeglobals") },
1342 || -> Option<bool> { panic!("XFCE does not ask the portal") },
1343 animations("false", &asked)
1344 ));
1345 assert!(!desktop_reduce_motion(
1346 LinuxDesktop::Unknown,
1347 || None,
1348 || None,
1349 |_, _| None
1350 ));
1351 }
1352
1353 #[cfg(target_os = "macos")]
1354 #[test]
1355 fn detect_reduced_motion_inner_macos() {
1356 let result = detect_reduced_motion_inner();
1357 let _ = result;
1358 }
1359
1360 #[cfg(target_os = "windows")]
1361 #[test]
1362 fn detect_reduced_motion_inner_windows() {
1363 let result = detect_reduced_motion_inner();
1364 let _ = result;
1365 }
1366}
1367
1368#[cfg(test)]
1369mod cache_slot_tests {
1370 use super::*;
1371
1372 #[test]
1376 fn a_value_detected_across_an_invalidation_is_not_cached() {
1377 let slot = CacheSlot::empty();
1378 assert!(slot.get_or_fill(|| {
1379 slot.invalidate();
1380 true
1381 }));
1382 assert!(slot.get().is_none());
1383 assert!(!slot.get_or_fill(|| false));
1384 assert_eq!(slot.get(), Some(false));
1385 }
1386
1387 #[test]
1391 fn an_entry_stamped_before_an_invalidation_is_not_returned() {
1392 let slot = CacheSlot::empty();
1393 let fill = slot.begin_fill();
1394 slot.invalidate();
1395 let stale = Arc::new(Stamped {
1396 generation: fill.generation,
1397 value: true,
1398 });
1399 let _ = slot.value.compare_and_swap(&fill.seen, Some(stale));
1400 assert!(slot.get().is_none());
1401 assert!(!slot.get_or_fill(|| false));
1402 assert_eq!(slot.get(), Some(false));
1403 }
1404
1405 #[test]
1406 fn a_fill_does_not_replace_a_value_stored_since_it_began() {
1407 let slot = CacheSlot::empty();
1408 let slow = slot.begin_fill();
1409 let _ = slot.get_or_fill(|| 2);
1410 slot.finish_fill(slow, 1);
1411 assert_eq!(slot.get(), Some(2));
1412 }
1413}
1414
1415#[cfg(test)]
1416mod detection_context_tests {
1417 use super::*;
1418
1419 #[test]
1420 fn system_returns_same_instance() {
1421 let a = system() as *const DetectionContext;
1422 let b = system() as *const DetectionContext;
1423 assert_eq!(a, b);
1424 }
1425
1426 fn filled() -> DetectionContext {
1428 let ctx = DetectionContext::new();
1429 ctx.is_dark.get_or_fill(|| true);
1430 ctx.reduced_motion.get_or_fill(|| true);
1431 ctx.reader_accessibility
1432 .get_or_fill(crate::AccessibilityPreferences::default);
1433 let _ = ctx.icon_theme.get_or_fill(|| Ok("breeze".to_string()));
1434 #[cfg(target_os = "linux")]
1435 ctx.linux_desktop.get_or_fill(|| LinuxDesktop::Kde);
1436 #[cfg(target_os = "linux")]
1437 ctx.refined_linux_desktop.get_or_fill(|| RefinedDesktop {
1438 desktop: LinuxDesktop::Kde,
1439 by_kdeglobals: false,
1440 });
1441 ctx
1442 }
1443
1444 #[test]
1448 fn invalidate_all_empties_every_slot() {
1449 let ctx = filled();
1450 ctx.invalidate_all();
1451 let DetectionContext {
1452 is_dark,
1453 reduced_motion,
1454 reader_accessibility,
1455 icon_theme,
1456 #[cfg(target_os = "linux")]
1457 linux_desktop,
1458 #[cfg(target_os = "linux")]
1459 refined_linux_desktop,
1460 } = &ctx;
1461 assert!(is_dark.get().is_none(), "is_dark");
1462 assert!(reduced_motion.get().is_none(), "reduced_motion");
1463 assert!(reader_accessibility.get().is_none(), "reader_accessibility");
1464 assert!(icon_theme.get().is_none(), "icon_theme");
1465 #[cfg(target_os = "linux")]
1466 assert!(linux_desktop.get().is_none(), "linux_desktop");
1467 #[cfg(target_os = "linux")]
1468 assert!(
1469 refined_linux_desktop.get().is_none(),
1470 "refined_linux_desktop"
1471 );
1472 }
1473
1474 #[test]
1475 fn invalidate_is_dark_empties_only_is_dark() {
1476 let ctx = filled();
1477 ctx.invalidate_is_dark();
1478 assert_eq!(ctx.is_dark.get(), None);
1479 assert_eq!(ctx.reduced_motion.get(), Some(true));
1480 }
1481
1482 #[test]
1485 fn invalidate_font_dpi_clears_nothing() {
1486 let ctx = filled();
1487 ctx.invalidate_font_dpi();
1488 assert!(ctx.is_dark.get().is_some(), "is_dark");
1489 assert!(ctx.reduced_motion.get().is_some(), "reduced_motion");
1490 assert!(
1491 ctx.reader_accessibility.get().is_some(),
1492 "reader_accessibility"
1493 );
1494 assert!(ctx.icon_theme.get().is_some(), "icon_theme");
1495 #[cfg(target_os = "linux")]
1496 assert!(ctx.linux_desktop.get().is_some(), "linux_desktop");
1497 #[cfg(target_os = "linux")]
1498 assert!(
1499 ctx.refined_linux_desktop.get().is_some(),
1500 "refined_linux_desktop"
1501 );
1502 assert_eq!(ctx.font_dpi(), detect_system_font_dpi());
1503 }
1504
1505 fn undetected() -> Result<String, IconThemeFailure> {
1506 Err(IconThemeFailure::for_tests("the test's failing detection"))
1507 }
1508
1509 #[test]
1510 fn a_failed_icon_theme_detection_is_cached_and_reported() {
1511 let ctx = DetectionContext::new();
1512 let runs = std::cell::Cell::new(0);
1513 let detect = || {
1514 runs.set(runs.get() + 1);
1515 undetected()
1516 };
1517 let first = ctx.icon_theme_with(detect);
1518 let second = ctx.icon_theme_with(detect);
1519 assert_eq!(runs.get(), 1, "a failed detection ran again");
1520 for outcome in [first, second] {
1521 match outcome {
1522 Ok(name) => panic!("a failed detection gave the theme {name}"),
1523 Err(e) => assert!(
1524 e.to_string().contains("the test's failing detection"),
1525 "got: {e}"
1526 ),
1527 }
1528 }
1529 }
1530
1531 #[test]
1532 fn invalidate_icon_theme_clears_a_cached_failure() {
1533 let ctx = DetectionContext::new();
1534 assert!(ctx.icon_theme_with(undetected).is_err());
1535 ctx.invalidate_icon_theme();
1536 let theme = ctx.icon_theme_with(|| Ok("breeze".to_string()));
1537 assert_eq!(theme.ok().as_deref(), Some("breeze"));
1538 }
1539
1540 #[test]
1541 fn invalidate_all_clears_a_cached_failure() {
1542 let ctx = DetectionContext::new();
1543 assert!(ctx.icon_theme_with(undetected).is_err());
1544 ctx.invalidate_all();
1545 let theme = ctx.icon_theme_with(|| Ok("breeze".to_string()));
1546 assert_eq!(theme.ok().as_deref(), Some("breeze"));
1547 }
1548
1549 fn scaled_by(text_scaling_factor: f32) -> crate::AccessibilityPreferences {
1550 crate::AccessibilityPreferences {
1551 text_scaling_factor,
1552 ..crate::AccessibilityPreferences::default()
1553 }
1554 }
1555
1556 #[test]
1557 fn a_second_accessibility_read_does_not_run_the_reader() {
1558 let ctx = DetectionContext::new();
1559 let runs = std::cell::Cell::new(0);
1560 let read = || {
1561 runs.set(runs.get() + 1);
1562 scaled_by(1.5)
1563 };
1564 assert_eq!(ctx.reader_accessibility_with(read), scaled_by(1.5));
1565 assert_eq!(ctx.reader_accessibility_with(read), scaled_by(1.5));
1566 assert_eq!(runs.get(), 1, "the second call ran the reader");
1567 }
1568
1569 #[test]
1570 fn a_stored_accessibility_block_is_returned_until_invalidated() {
1571 let ctx = DetectionContext::new();
1572 let runs = std::cell::Cell::new(0);
1573 let read = || {
1574 runs.set(runs.get() + 1);
1575 scaled_by(1.25)
1576 };
1577 ctx.store_reader_accessibility(ctx.begin_reader_accessibility(), scaled_by(2.0));
1578 assert_eq!(ctx.reader_accessibility_with(read), scaled_by(2.0));
1579 assert_eq!(runs.get(), 0, "a stored block ran the reader");
1580 ctx.invalidate_all();
1581 assert_eq!(ctx.reader_accessibility_with(read), scaled_by(1.25));
1582 assert_eq!(runs.get(), 1);
1583 ctx.invalidate_accessibility_preferences();
1584 assert_eq!(ctx.reader_accessibility_with(read), scaled_by(1.25));
1585 assert_eq!(runs.get(), 2);
1586 }
1587
1588 #[test]
1589 fn an_icon_theme_detected_across_an_invalidation_is_not_cached() {
1590 let ctx = DetectionContext::new();
1591 let stale = ctx.icon_theme_with(|| {
1592 ctx.invalidate_icon_theme();
1593 Ok("breeze".to_string())
1594 });
1595 assert_eq!(stale.ok().as_deref(), Some("breeze"));
1596 let theme = ctx.icon_theme_with(|| Ok("Adwaita".to_string()));
1597 assert_eq!(theme.ok().as_deref(), Some("Adwaita"));
1598 }
1599
1600 #[test]
1601 fn an_accessibility_block_read_across_an_invalidation_is_not_cached() {
1602 let ctx = DetectionContext::new();
1603 let stale = ctx.reader_accessibility_with(|| {
1604 ctx.invalidate_all();
1605 scaled_by(1.5)
1606 });
1607 assert_eq!(stale, scaled_by(1.5));
1608 assert_eq!(
1609 ctx.reader_accessibility_with(|| scaled_by(2.0)),
1610 scaled_by(2.0)
1611 );
1612 }
1613
1614 #[cfg(target_os = "linux")]
1617 #[test]
1618 fn the_sync_refined_desktop_is_the_cached_one() {
1619 let ctx = DetectionContext::new();
1620 let fill = ctx.refined_linux_desktop.begin_fill();
1621 let gnome = refine_desktop(LinuxDesktop::Gnome, None, || false);
1622 ctx.refined_linux_desktop.finish_fill(fill, gnome);
1623 assert_eq!(ctx.refined_linux_desktop_sync(), LinuxDesktop::Gnome);
1624 assert_eq!(pollster::block_on(ctx.refined_linux_desktop()), gnome);
1625 ctx.invalidate_linux_desktop();
1626 assert!(ctx.refined_linux_desktop.get().is_none());
1627 }
1628
1629 #[cfg(target_os = "linux")]
1632 fn refined_unknown(portal_backend: Option<LinuxDesktop>) -> DetectionContext {
1633 let ctx = DetectionContext::new();
1634 ctx.linux_desktop
1635 .finish_fill(ctx.linux_desktop.begin_fill(), LinuxDesktop::Unknown);
1636 ctx.finish_refined_desktop(
1637 ctx.refined_linux_desktop.begin_fill(),
1638 refine_desktop(LinuxDesktop::Unknown, portal_backend, || false),
1639 LinuxDesktop::Unknown,
1640 );
1641 ctx
1642 }
1643
1644 #[cfg(target_os = "linux")]
1651 #[test]
1652 fn a_portal_answer_that_changes_the_desktop_clears_what_was_read_from_it() {
1653 let ctx = DetectionContext::new();
1654 assert_eq!(
1655 ctx.icon_theme_with(|| Ok("breeze".to_string()))
1656 .ok()
1657 .as_deref(),
1658 Some("breeze")
1659 );
1660 assert!(ctx.is_dark.get_or_fill(|| true));
1661 assert!(ctx.reduced_motion.get_or_fill(|| true));
1662
1663 let refined = refine_desktop(LinuxDesktop::Unknown, Some(LinuxDesktop::Gnome), || true);
1664 ctx.finish_refined_desktop(
1665 ctx.refined_linux_desktop.begin_fill(),
1666 refined,
1667 LinuxDesktop::Kde,
1668 );
1669 assert_eq!(ctx.refined_linux_desktop_sync(), LinuxDesktop::Gnome);
1670 assert_eq!(
1671 ctx.icon_theme_with(|| Ok("Adwaita".to_string()))
1672 .ok()
1673 .as_deref(),
1674 Some("Adwaita")
1675 );
1676 assert_eq!(ctx.is_dark.get(), None);
1677 assert_eq!(ctx.reduced_motion.get(), None);
1678 }
1679
1680 #[cfg(target_os = "linux")]
1683 #[test]
1684 fn a_portal_answer_that_keeps_the_desktop_keeps_what_was_read() {
1685 let ctx = DetectionContext::new();
1686 assert_eq!(
1687 ctx.icon_theme_with(|| Ok("breeze".to_string()))
1688 .ok()
1689 .as_deref(),
1690 Some("breeze")
1691 );
1692 let refined = refine_desktop(LinuxDesktop::Unknown, Some(LinuxDesktop::Kde), || true);
1693 ctx.finish_refined_desktop(
1694 ctx.refined_linux_desktop.begin_fill(),
1695 refined,
1696 LinuxDesktop::Kde,
1697 );
1698 assert_eq!(
1699 ctx.icon_theme_with(|| Ok("Adwaita".to_string()))
1700 .ok()
1701 .as_deref(),
1702 Some("breeze")
1703 );
1704 }
1705
1706 #[cfg(target_os = "linux")]
1710 #[test]
1711 fn dark_mode_follows_the_refined_desktop() {
1712 let kde = refined_unknown(Some(LinuxDesktop::Kde));
1713 assert_eq!(
1714 desktop_is_dark(&kde, || Some(true), || Some(false)),
1715 Some(true)
1716 );
1717 let gnome = refined_unknown(Some(LinuxDesktop::Gnome));
1718 assert_eq!(
1719 desktop_is_dark(&gnome, || Some(true), || Some(false)),
1720 Some(false)
1721 );
1722 assert_eq!(desktop_is_dark(&gnome, || Some(true), || None), Some(true));
1723 }
1724}
1725
1726#[cfg(all(test, target_os = "linux"))]
1727mod refine_linux_desktop_tests {
1728 use super::*;
1729
1730 fn asked() -> bool {
1731 panic!("kdeglobals asked where the desktop is already decided")
1732 }
1733
1734 #[test]
1737 fn the_raw_desktop_then_the_portal_backend_then_kdeglobals() {
1738 let refine = |raw, portal_backend, kdeglobals_exists: fn() -> bool| {
1739 refine_linux_desktop(raw, portal_backend, kdeglobals_exists)
1740 };
1741 assert_eq!(
1742 refine(LinuxDesktop::Gnome, Some(LinuxDesktop::Kde), asked),
1743 LinuxDesktop::Gnome
1744 );
1745 assert_eq!(refine(LinuxDesktop::Xfce, None, asked), LinuxDesktop::Xfce);
1746 assert_eq!(
1747 refine(LinuxDesktop::Unknown, Some(LinuxDesktop::Kde), asked),
1748 LinuxDesktop::Kde
1749 );
1750 assert_eq!(
1751 refine(LinuxDesktop::Unknown, Some(LinuxDesktop::Gnome), asked),
1752 LinuxDesktop::Gnome
1753 );
1754 assert_eq!(
1755 refine(LinuxDesktop::Unknown, None, || true),
1756 LinuxDesktop::Kde
1757 );
1758 assert_eq!(
1759 refine(LinuxDesktop::Unknown, None, || false),
1760 LinuxDesktop::Unknown
1761 );
1762 }
1763}
1764
1765#[cfg(all(test, target_os = "linux"))]
1766#[allow(clippy::unwrap_used, clippy::expect_used)]
1767mod subprocess_tests {
1768 use super::*;
1769 use std::path::PathBuf;
1770 use std::time::{Duration, Instant};
1771
1772 const GENEROUS: Duration = Duration::from_secs(10);
1776
1777 fn on_path(program: &str) -> bool {
1779 std::env::var_os("PATH")
1780 .is_some_and(|path| std::env::split_paths(&path).any(|dir| dir.join(program).is_file()))
1781 }
1782
1783 #[test]
1784 fn poll_intervals_double_from_1_ms_up_to_50_ms() {
1785 let intervals: Vec<Duration> = poll_intervals().take(10).collect();
1786 let expected: Vec<Duration> = [1, 2, 4, 8, 16, 32, 50, 50, 50, 50]
1787 .into_iter()
1788 .map(Duration::from_millis)
1789 .collect();
1790 assert_eq!(intervals, expected);
1791 }
1792
1793 #[test]
1794 fn run_with_timeout_returns_stdout_of_a_successful_command() {
1795 if !on_path("echo") {
1796 eprintln!("skipped: echo is not installed");
1797 return;
1798 }
1799 let out = stdout_with_timeout("echo", &["hi"], GENEROUS);
1800 assert_eq!(out.as_deref().map(str::trim), Some("hi"));
1801 }
1802
1803 #[test]
1806 fn run_with_timeout_returns_the_status_and_stderr_of_a_failing_command() {
1807 if !on_path("sh") {
1808 eprintln!("skipped: sh is not installed");
1809 return;
1810 }
1811 let output = run_with_timeout("sh", &["-c", "echo oops >&2; exit 3"], GENEROUS).unwrap();
1812 assert_eq!(output.status.code(), Some(3));
1813 assert_eq!(output.stderr, b"oops\n");
1814 assert_eq!(stdout_with_timeout("sh", &["-c", "exit 3"], GENEROUS), None);
1815 }
1816
1817 #[test]
1818 fn run_with_timeout_reports_a_missing_program_as_not_found() {
1819 let error = run_with_timeout("nt-test-no-such-program", &[], GENEROUS).unwrap_err();
1820 assert_eq!(error.kind(), std::io::ErrorKind::NotFound);
1821 }
1822
1823 #[test]
1826 fn run_with_timeout_returns_the_empty_stdout_of_a_quiet_command() {
1827 if !on_path("true") {
1828 eprintln!("skipped: true is not installed");
1829 return;
1830 }
1831 let start = Instant::now();
1832 assert_eq!(
1833 stdout_with_timeout("true", &[], GENEROUS).as_deref(),
1834 Some("")
1835 );
1836 eprintln!("`true` ran in {:?}", start.elapsed());
1837 }
1838
1839 fn running(cmdline: &str) -> Vec<PathBuf> {
1841 std::fs::read_dir("/proc")
1842 .unwrap()
1843 .flatten()
1844 .map(|entry| entry.path().join("cmdline"))
1845 .filter(|path| std::fs::read(path).is_ok_and(|bytes| bytes == cmdline.as_bytes()))
1846 .collect()
1847 }
1848
1849 #[test]
1853 fn run_with_timeout_kills_a_command_that_outlives_the_timeout() {
1854 if !on_path("sleep") {
1855 eprintln!("skipped: sleep is not installed");
1856 return;
1857 }
1858 let timeout = Duration::from_millis(100);
1859 let seconds = format!("30.{}", std::process::id());
1860 let start = Instant::now();
1861 let error = run_with_timeout("sleep", &[&seconds], timeout).unwrap_err();
1862 let elapsed = start.elapsed();
1863 assert_eq!(error.kind(), std::io::ErrorKind::TimedOut);
1864 assert_eq!(error.to_string(), "timed out after 100ms");
1865 assert!(
1866 elapsed >= timeout && elapsed < Duration::from_secs(5),
1867 "took {elapsed:?}"
1868 );
1869 let still_running = running(&format!("sleep\0{seconds}\0"));
1870 assert!(still_running.is_empty(), "not killed: {still_running:?}");
1871 }
1872
1873 #[test]
1876 fn run_with_timeout_returns_all_of_an_output_larger_than_a_pipe() {
1877 if !on_path("sh") || !on_path("head") {
1878 eprintln!("skipped: sh or head is not installed");
1879 return;
1880 }
1881 let out = stdout_with_timeout("sh", &["-c", "head -c 102400 /dev/zero"], GENEROUS);
1882 assert_eq!(out.map(|out| out.len()), Some(102_400));
1883 }
1884
1885 #[test]
1890 fn run_with_timeout_ends_at_the_deadline_when_a_grandchild_holds_stdout() {
1891 if !on_path("sh") || !on_path("sleep") {
1892 eprintln!("skipped: sh or sleep is not installed");
1893 return;
1894 }
1895 let script = format!("sleep 10.{} & echo hi", std::process::id());
1896 let start = Instant::now();
1897 let error =
1898 run_with_timeout("sh", &["-c", &script], Duration::from_millis(100)).unwrap_err();
1899 let elapsed = start.elapsed();
1900 assert_eq!(error.kind(), std::io::ErrorKind::TimedOut);
1901 assert!(elapsed < Duration::from_secs(5), "took {elapsed:?}");
1902 }
1903}
1904
1905#[cfg(all(test, target_os = "linux"))]
1906mod config_home_tests {
1907 use super::*;
1908 use std::ffi::OsStr;
1909 use std::path::PathBuf;
1910
1911 fn config_home(var: Option<&str>, home: Option<&str>) -> Option<PathBuf> {
1912 xdg_config_home_from(var.map(OsStr::new), home.map(OsStr::new))
1913 }
1914
1915 #[test]
1916 fn an_absolute_xdg_config_home_is_the_config_directory() {
1917 assert_eq!(
1918 config_home(Some("/tmp/cfg"), Some("/home/u")),
1919 Some(PathBuf::from("/tmp/cfg"))
1920 );
1921 assert_eq!(
1922 config_home(Some("/tmp/cfg"), None),
1923 Some(PathBuf::from("/tmp/cfg"))
1924 );
1925 }
1926
1927 #[test]
1930 fn an_unset_empty_or_relative_xdg_config_home_falls_back_to_home() {
1931 for var in [None, Some(""), Some("relative/cfg"), Some(".config")] {
1932 assert_eq!(
1933 config_home(var, Some("/home/u")),
1934 Some(PathBuf::from("/home/u/.config")),
1935 "{var:?}"
1936 );
1937 }
1938 }
1939
1940 #[test]
1941 fn without_xdg_config_home_and_home_there_is_no_config_directory() {
1942 for home in [None, Some("")] {
1943 for var in [None, Some(""), Some("relative")] {
1944 assert_eq!(config_home(var, home), None, "{var:?} {home:?}");
1945 }
1946 }
1947 }
1948}
1949
1950#[cfg(all(test, target_os = "linux"))]
1951mod linux_font_dpi_tests {
1952 use super::*;
1953
1954 #[test]
1955 fn the_font_dpi_is_96_on_every_linux_desktop() {
1956 assert_eq!(LINUX_FONT_DPI, 96.0);
1957 assert_eq!(detect_system_font_dpi(), 96.0);
1958 assert_eq!(DetectionContext::new().font_dpi(), 96.0);
1959 assert_eq!(system_font_dpi(), 96.0);
1960 }
1961}