Skip to main content

native_theme/
detect.rs

1//! OS detection: dark mode, reduced motion, accessibility preferences, icon
2//! theme and set, desktop environment.
3
4use 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/// Timeout for subprocess commands ([`run_with_timeout`]: gsettings,
14/// xfconf-query, fc-match, macOS `defaults`).
15///
16/// Prevents D-Bus-dependent tools from blocking indefinitely when the
17/// session bus is unresponsive or the display server is unavailable.
18#[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/// Desktop environments recognized on Linux.
23#[cfg(target_os = "linux")]
24#[non_exhaustive]
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
26pub enum LinuxDesktop {
27    /// KDE Plasma desktop.
28    Kde,
29    /// GNOME desktop.
30    Gnome,
31    /// Xfce desktop.
32    Xfce,
33    /// Cinnamon desktop (Linux Mint).
34    Cinnamon,
35    /// MATE desktop.
36    Mate,
37    /// LXQt desktop.
38    LxQt,
39    /// Budgie desktop.
40    Budgie,
41    /// Hyprland Wayland compositor.
42    Hyprland,
43    /// Sway Wayland compositor (i3-compatible).
44    Sway,
45    /// River Wayland compositor.
46    River,
47    /// Niri scrollable Wayland compositor.
48    Niri,
49    /// Wayfire scene-graph Wayland compositor (wlroots-based).
50    Wayfire,
51    /// COSMIC desktop environment (System76).
52    CosmicDe,
53    /// Unrecognized or unset desktop environment.
54    Unknown,
55}
56
57/// Read the `XDG_CURRENT_DESKTOP` environment variable, returning an
58/// empty string if unset or invalid UTF-8.
59#[cfg(target_os = "linux")]
60pub(crate) fn xdg_current_desktop() -> String {
61    std::env::var("XDG_CURRENT_DESKTOP").unwrap_or_default()
62}
63
64/// Detect the current Linux desktop environment.
65///
66/// Reads `XDG_CURRENT_DESKTOP` and returns the recognized desktop.
67/// Returns [`LinuxDesktop::Unknown`] if the variable is unset or
68/// contains no recognized value.
69///
70/// For testable parsing without environment access, use the
71/// `pub` [`parse_linux_desktop()`] function instead.
72///
73/// # Examples
74///
75/// ```no_run
76/// use native_theme::detect::{detect_linux_desktop, LinuxDesktop};
77///
78/// let de = detect_linux_desktop();
79/// match de {
80///     LinuxDesktop::Kde => println!("KDE Plasma"),
81///     LinuxDesktop::Gnome => println!("GNOME"),
82///     _ => println!("Other: {de:?}"),
83/// }
84/// ```
85#[cfg(target_os = "linux")]
86#[must_use]
87pub fn detect_linux_desktop() -> LinuxDesktop {
88    parse_linux_desktop(&xdg_current_desktop())
89}
90
91/// Parse `XDG_CURRENT_DESKTOP` (a colon-separated list) and return
92/// the recognized desktop environment.
93///
94/// Checks components in order; first recognized DE wins. Budgie is checked
95/// before GNOME because Budgie sets `Budgie:GNOME`.
96#[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/// The desktop a theme is read by: `raw` ([`parse_linux_desktop`] of
121/// `XDG_CURRENT_DESKTOP`) where it names one; for `Unknown`, the desktop of
122/// the portal backend (`portal_backend`), else KDE where `kdeglobals_exists`,
123/// else `Unknown`. The reader, the theme watcher and the icon-theme
124/// detection all decide by it ([`DetectionContext::refined_linux_desktop`]),
125/// so they agree. `kdeglobals_exists` is asked only where nothing before it
126/// decides.
127#[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/// A refined desktop ([`refine_linux_desktop`]), and whether only
137/// `kdeglobals` named it.
138#[cfg(target_os = "linux")]
139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
140pub(crate) struct RefinedDesktop {
141    /// The desktop.
142    pub(crate) desktop: LinuxDesktop,
143    /// KDE named by the user's `kdeglobals` alone: `XDG_CURRENT_DESKTOP`
144    /// names no desktop and no portal backend answered.
145    pub(crate) by_kdeglobals: bool,
146}
147
148/// [`refine_linux_desktop`], with what named the desktop.
149#[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/// Whether the user's `kdeglobals` exists, with the `kde` feature; `false`
167/// without it, as no KDE file is read then.
168#[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/// Detect whether the system is using a dark color scheme.
181///
182/// Uses synchronous, platform-specific checks so the result is available
183/// immediately at window creation time (before any async portal response).
184///
185/// # Caching
186///
187/// The result is cached after the first call and reused on subsequent calls.
188/// Call [`invalidate_caches()`] to clear the cached value so the next call
189/// re-queries the OS. For a fresh reading without affecting the cache, use
190/// [`detect_is_dark()`] instead.
191///
192/// For live dark-mode tracking, use `watch::on_theme_change` (feature
193/// `watch`): on each event call [`invalidate_caches()`] and re-read
194/// [`crate::SystemTheme::from_system()`].
195///
196/// # Platform Behavior
197///
198/// - **Linux:** Checks `GTK_THEME` for `:dark` or `-dark`; on KDE (with the
199///   `kde` feature; the desktop the KDE reader is chosen by, so an
200///   unrecognised one with a KDE portal backend or a `kdeglobals` counts)
201///   reads `kdeglobals`' background luminance; then
202///   `gsettings` `color-scheme` (2-second timeout); then `kdeglobals` on
203///   other desktops (with `kde`); finally `gtk-3.0/settings.ini`
204///   `gtk-application-prefer-dark-theme`.
205/// - **macOS:** Reads `AppleInterfaceStyle` via `NSUserDefaults` (with
206///   `macos` feature) or `defaults` subprocess (without).
207/// - **Windows:** Checks foreground color luminance from `UISettings` via
208///   BT.601 coefficients (requires `windows` feature).
209/// - **Other platforms / missing features:** Returns `false` (light).
210#[must_use]
211pub fn system_is_dark() -> bool {
212    system().is_dark()
213}
214
215/// Reset all process-wide caches so the next call to [`system_is_dark()`],
216/// [`prefers_reduced_motion()`], [`accessibility_preferences()`], or
217/// [`system_icon_theme()`] re-queries the OS; a cached failure to detect the
218/// icon theme is cleared too, and so, on Linux, is the detected desktop
219/// environment, with the desktop refined from it. The font DPI is not cached:
220/// since 0.7.1 it is a constant per platform, which
221/// [`ResolutionContext::from_system()`](crate::ResolutionContext::from_system) uses.
222///
223/// Call this when you detect that the user has changed system settings (e.g.,
224/// dark mode toggle, icon theme switch, accessibility preferences).
225///
226/// The `detect_*()` family of functions are unaffected — they always query
227/// the OS directly. The installed freedesktop icon themes are not re-read:
228/// the icon lookup reads them once per process, and so do
229/// [`is_freedesktop_theme_available()`](crate::icons::is_freedesktop_theme_available)
230/// and [`list_freedesktop_themes()`](crate::icons::list_freedesktop_themes).
231pub fn invalidate_caches() {
232    system().invalidate_all();
233}
234
235/// Detect whether the system is using a dark color scheme without caching.
236///
237/// Unlike [`system_is_dark()`], this function queries the OS every time it is
238/// called and never caches the result. Use this when polling for theme changes
239/// or implementing live dark-mode tracking.
240///
241/// See [`system_is_dark()`] for platform behavior details.
242#[must_use]
243pub fn detect_is_dark() -> bool {
244    detect_is_dark_inner()
245}
246
247/// The longest pause between two polls of a running command.
248#[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/// The pauses between polls of a running command: 1 ms, doubling up to
253/// [`POLL_INTERVAL_CAP`], so a command that exits in a few milliseconds is
254/// seen to exit within a few milliseconds, and a slow one costs a poll per
255/// 50 ms.
256#[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/// Run `program` with `args` and its stdin closed, waiting up to `timeout`
265/// for it to exit and for its stdout and stderr to close.
266///
267/// Its output is what [`std::process::Command::output`] gives, an
268/// unsuccessful exit included. Both pipes are read while the command runs,
269/// each on a thread of its own, so a command that prints more than a pipe
270/// holds (65,536 bytes on Linux, pipe(7)) is not stalled until it is
271/// killed. The error is the spawn's, a reader thread's that cannot be
272/// started, or one of kind [`std::io::ErrorKind::TimedOut`] when the command
273/// outlives `timeout` or a process it started still holds its output open
274/// at `timeout`. A command that has not exited is killed and reaped on
275/// every error; one the kill fails on is left unreaped rather than waited
276/// for, and a reader still blocked at `timeout` is left to end when the pipe
277/// closes, so `timeout` stays a bound on the call. The command is polled at
278/// [`poll_intervals`].
279#[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/// Read `pipe` to its end on a new thread, which sends what it read; an
358/// absent pipe is read as empty. The error is the thread's spawn error.
359#[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/// The stdout of `program` run with `args` ([`run_with_timeout`]) when it
383/// exits successfully within `timeout` and prints UTF-8; `None` otherwise.
384#[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/// The user's config directory: `$XDG_CONFIG_HOME`, else `$HOME/.config`;
399/// `None` without either ([`xdg_config_home_from`] of the environment).
400#[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/// The config directory `$XDG_CONFIG_HOME` (`var`) names: itself when it is
409/// absolute, else `<home>/.config` when `home` is non-empty, else `None`.
410///
411/// The XDG Base Directory Specification 0.8: "If `$XDG_CONFIG_HOME` is
412/// either not set or empty, a default equal to `$HOME/.config` should be
413/// used", and "All paths set in these environment variables must be
414/// absolute. If an implementation encounters a relative path in any of
415/// these variables it should consider the path invalid and ignore it"
416/// (<https://specifications.freedesktop.org/basedir-spec/0.8/>).
417#[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/// Why [`xdg_config_home`] is `None`.
431#[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/// Run `gsettings get <schema> <key>`, waiting up to `timeout`.
436///
437/// Returns the trimmed stdout on success; `None` if the command fails, times
438/// out, or produces empty output. The timeout keeps gsettings from blocking
439/// indefinitely when D-Bus is unresponsive.
440#[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/// The font DPI on every Linux desktop: 96. The toolkit's scale factor
456/// already carries the display's scale: gpui and winit take it from the
457/// compositor on Wayland (gpui-pre-linux 0.3.12
458/// `src/linux/wayland/window.rs:1218-1222`; winit 0.30.13
459/// `src/platform_impl/linux/wayland/types/wp_fractional_scaling.rs:71-72`) and
460/// from `Xft.dpi` / 96 on X11 (gpui-pre-linux `src/linux/x11/client.rs:2674-2681`;
461/// winit `src/platform_impl/linux/x11/util/randr.rs:40-53`, `:145-151`), and
462/// Plasma writes `Xft.dpi` on Wayland as the largest output's scale × 96, so a
463/// font DPI taken from `Xft.dpi` scaled text a second time. Qt lays a point
464/// out at a logical DPI of 96 on both (qtbase v6.10.1 `qwaylandscreen.cpp:149-160`,
465/// `qhighdpiscaling.cpp:241-256`, `:362-383`); GNOME at a fixed 96
466/// (`DPI_FALLBACK`, gnome-settings-daemon 51.0
467/// `plugins/xsettings/gsd-xsettings-manager.c:243`, `:583-595`; GTK 4.24.1
468/// `gdk/wayland/gdksettings-wayland.c:166-168`), its text-scaling factor
469/// carried in
470/// [`AccessibilityPreferences::text_scaling_factor`](crate::AccessibilityPreferences::text_scaling_factor)
471/// on Wayland and in the toolkit's `Xft.dpi` scale factor on X11
472/// (`docs/issues/0004_kde-hand-overrides-rationale.md` §4.1).
473#[cfg(target_os = "linux")]
474pub(crate) const LINUX_FONT_DPI: f32 = 96.0;
475
476/// The font DPI of the platform, at which a point size becomes logical pixels.
477///
478/// Used, through [`system_font_dpi`], by
479/// [`ResolutionContext::from_system()`](crate::ResolutionContext::from_system)
480/// where no OS reader has provided `font_dpi`. A constant per platform since
481/// 0.7.1: nothing is read.
482///
483/// - **Linux**, every desktop: 96.0 (`LINUX_FONT_DPI`)
484/// - **macOS**: 72.0 (Apple coordinate system: 1pt = 1px)
485/// - **Windows**: 96.0, the Windows reader's `font_dpi`: a point is 96/72
486///   logical (effective) pixels at any display scale
487/// - **Other**: 96.0
488#[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/// The session type, `$XDG_SESSION_TYPE` (`x11`, `wayland`, …).
509#[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/// Whether the colour scheme is dark: the portal's answer when it gave one,
515/// else gsettings' `org.gnome.desktop.interface` `color-scheme` read through
516/// `gsetting` (`prefer-dark` dark; `prefer-light` and `default` light);
517/// `None` when neither answers. [`detect_is_dark`] (no portal) and the GNOME
518/// reader both decide through it, so the two cannot disagree.
519#[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/// Dark or light from the desktop's settings: on KDE (`detection`'s refined
538/// desktop, the one the KDE reader is chosen by) `kdeglobals` first, as
539/// gsettings `color-scheme` is synced by xdg-desktop-portal-kde and can be
540/// stale or inverted; elsewhere gsettings (reliable on GNOME and GTK-based
541/// desktops), then `kdeglobals`' background luminance.
542#[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
555/// Inner detection logic for [`system_is_dark()`].
556///
557/// Separated from the public function to allow caching.
558fn detect_is_dark_inner() -> bool {
559    #[cfg(target_os = "linux")]
560    {
561        // Check GTK_THEME env var (works across all GTK-based DEs)
562        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        // Fallback: gtk-3.0/settings.ini for DEs that set the GTK dark preference
591        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        // AppleInterfaceStyle is "Dark" when dark mode is active.
611        // The key is absent in light mode, so any failure means light.
612        #[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/// Query whether the user prefers reduced motion.
659///
660/// Returns `true` when the OS accessibility setting indicates animations
661/// should be reduced or disabled. Returns `false` (allow animations) on
662/// unsupported platforms or when the query fails.
663///
664/// # Caching
665///
666/// The result is cached after the first call and reused on subsequent calls.
667/// Call [`invalidate_caches()`] to clear the cached value so the next call
668/// re-queries the OS. For live accessibility-change tracking, subscribe to
669/// OS accessibility events and call `invalidate_caches()` when notified.
670///
671/// # Platform Behavior
672///
673/// Each platform's read is the one its theme reader makes, so the result is
674/// the `reduce_motion` of
675/// [`AccessibilityPreferences::from_system`](crate::AccessibilityPreferences::from_system)
676/// and of [`SystemTheme::from_system`](crate::SystemTheme::from_system)'s
677/// accessibility block.
678///
679/// - **Linux:** by the desktop the reader is chosen by. KDE (with the `kde`
680///   feature): `kdeglobals`' `[KDE] AnimationDurationFactor` is 0. GNOME and
681///   Budgie: the portal's `reduced-motion` (with the `portal` feature, 2-second
682///   deadline), else `gsettings get org.gnome.desktop.interface enable-animations`
683///   is `false` (2-second timeout). Other desktops, and KDE without the `kde`
684///   feature: that gsettings key alone.
685/// - **macOS:** Queries `NSWorkspace.accessibilityDisplayShouldReduceMotion`
686///   (requires `macos` feature).
687/// - **Windows:** Queries `SystemParametersInfoW(SPI_GETCLIENTAREAANIMATION)`;
688///   `true` when client-area animations are off (requires `windows` feature).
689/// - **Other platforms:** Returns `false`.
690///
691/// # Examples
692///
693/// ```
694/// let reduced = native_theme::detect::prefers_reduced_motion();
695/// // On this platform, the result depends on OS accessibility settings.
696/// // The function always returns a bool (false on unsupported platforms).
697/// assert!(reduced == true || reduced == false);
698/// ```
699#[must_use]
700pub fn prefers_reduced_motion() -> bool {
701    system().prefers_reduced_motion()
702}
703
704/// Detect whether the user prefers reduced motion without caching.
705///
706/// Unlike [`prefers_reduced_motion()`], this function queries the OS every time
707/// it is called and never caches the result. Use this when polling for
708/// accessibility preference changes.
709///
710/// See [`prefers_reduced_motion()`] for platform behavior details.
711#[must_use]
712pub fn detect_reduced_motion() -> bool {
713    detect_reduced_motion_inner()
714}
715
716/// The OS accessibility preferences (cached): what
717/// [`AccessibilityPreferences::from_system`](crate::AccessibilityPreferences::from_system)
718/// reads, without running the platform reader again.
719///
720/// The cache holds the accessibility block of the last platform reader run:
721/// [`SystemTheme::from_system`](crate::SystemTheme::from_system) and
722/// `from_system_async` fill it, and where neither has run since the last
723/// [`invalidate_caches()`], the first call runs the reader itself.
724/// [`invalidate_caches()`] clears it. A reader that fails is not reported:
725/// the preferences used without a reader (the defaults, with the platform's
726/// [`detect_reduced_motion()`]) stay cached until the next invalidation, as a
727/// failure to detect the icon theme does.
728///
729/// For a preset switch, where the OS preferences apply under the preset and
730/// the reader has usually just run. The theme watcher
731/// (`watch::on_theme_change`) reports a change of every accessibility setting
732/// the reader reads but one, Windows' high contrast, which Windows announces
733/// only to top-level windows, as it does the non-client fonts; nothing clears
734/// the cache when it changes. That holds from Windows 10 2004: before it the
735/// watcher has no `AnimationsEnabledChanged`, so a reduced-motion change is
736/// not reported either (and before 1703, with no
737/// `AdvancedEffectsEnabledChanged`, a transparency change). Where the current
738/// setting matters more than the cost, read [`AccessibilityPreferences::from_system`](crate::AccessibilityPreferences::from_system),
739/// which runs the reader every time.
740#[must_use]
741pub fn accessibility_preferences() -> crate::AccessibilityPreferences {
742    system().accessibility_preferences()
743}
744
745/// Whether GNOME asks for reduced motion: the portal's answer when it gave
746/// one, else gsettings' `org.gnome.desktop.interface` `enable-animations`
747/// read through `gsetting` (`false` is reduced motion); `None` when neither
748/// answers. [`detect_reduced_motion`] and the GNOME reader both decide
749/// through it.
750#[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/// Reduced motion as the reader of `desktop` (the refined desktop) reads it:
763/// on KDE `kdeglobals` (`None` without the `kde` feature, which reads no KDE
764/// file), as the KDE reader does; on GNOME and Budgie the `portal`, then
765/// gsettings ([`gnome_reduce_motion`]), as the GNOME reader does; elsewhere,
766/// and on KDE where `kdeglobals` gives `None`, gsettings alone. `false` when
767/// nothing answers.
768#[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
783/// Inner detection logic for [`prefers_reduced_motion()`].
784///
785/// Separated from the public function to allow caching.
786fn 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
845// === DetectionContext ===
846
847/// A value cached with the generation of its slot when its detection began.
848struct Stamped<T> {
849    generation: u64,
850    value: T,
851}
852
853/// One cached detection: the value, and a generation every invalidation
854/// bumps. A value is cached only if no invalidation landed while it was
855/// detected, so a fill that began before an OS change and ends after a
856/// watcher's invalidation does not cache what it read before the change.
857struct CacheSlot<T> {
858    value: ArcSwapOption<Stamped<T>>,
859    generation: AtomicU64,
860}
861
862/// A fill in progress: the slot's generation and entry when it began.
863pub(crate) struct CacheFill<T> {
864    generation: u64,
865    seen: Option<Arc<Stamped<T>>>,
866}
867
868impl<T> CacheFill<T> {
869    /// The value the slot held for this fill's generation, if any.
870    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    // The generation's Acquire loads pair with the Release bump in
887    // `invalidate`, which follows its clearing store: a fill that reads the
888    // bumped generation also sees the slot cleared, and an entry stamped with
889    // an older generation than the one loaded is never returned.
890    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    /// Cache `value` unless an invalidation landed after `fill` began, or
899    /// another fill stored a value since.
900    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    /// The cached value, or `detect`'s, cached as [`finish_fill`](Self::finish_fill)
912    /// caches it.
913    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    /// The cached value, if any.
927    #[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
941/// Process-wide detection cache.
942///
943/// Provides "cache on first read" semantics for OS detection queries
944/// (`is_dark`, `reduced_motion`, `accessibility_preferences`, `icon_theme`,
945/// `linux_desktop`) and
946/// per-field invalidation for watchers that need fresh data.
947///
948/// Obtain the process-wide instance via [`system()`].
949///
950/// # Thread Safety
951///
952/// All reads and invalidations are lock-free (backed by
953/// [`arc_swap::ArcSwapOption`]). A value detected while an invalidation of
954/// its field lands is returned to its caller but not cached.
955pub 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    /// Create an empty context with no cached values.
968    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    /// Whether the system is using a dark color scheme (cached).
982    ///
983    /// The first call queries the OS and caches the result.
984    /// Subsequent calls return the cached value.
985    /// Call [`invalidate_is_dark()`](Self::invalidate_is_dark) to
986    /// force a re-read on the next call.
987    #[must_use]
988    pub fn is_dark(&self) -> bool {
989        self.is_dark.get_or_fill(detect_is_dark_inner)
990    }
991
992    /// Whether the user prefers reduced motion (cached).
993    ///
994    /// The first call queries the OS and caches the result.
995    /// Call [`invalidate_reduced_motion()`](Self::invalidate_reduced_motion)
996    /// to force a re-read.
997    #[must_use]
998    pub fn prefers_reduced_motion(&self) -> bool {
999        self.reduced_motion.get_or_fill(detect_reduced_motion_inner)
1000    }
1001
1002    /// The OS accessibility preferences (cached), as
1003    /// [`accessibility_preferences()`](crate::detect::accessibility_preferences)
1004    /// describes: the platform reader's accessibility block, run on the
1005    /// first call unless a system read stored it.
1006    /// Call
1007    /// [`invalidate_accessibility_preferences()`](Self::invalidate_accessibility_preferences)
1008    /// to force a re-read.
1009    #[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    /// The cached reader accessibility block, with `read` run where
1017    /// nothing is cached.
1018    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    /// Begin a platform read whose accessibility block
1026    /// [`store_reader_accessibility`](Self::store_reader_accessibility)
1027    /// stores.
1028    pub(crate) fn begin_reader_accessibility(&self) -> CacheFill<crate::AccessibilityPreferences> {
1029        self.reader_accessibility.begin_fill()
1030    }
1031
1032    /// Store the accessibility block a platform reader just returned, unless
1033    /// the cache was invalidated or filled since the read began (`fill`).
1034    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    /// The current icon theme name (cached), or why none was detected.
1043    ///
1044    /// The first call detects the theme from the OS and caches the
1045    /// outcome, a failure included, so a failed detection is not
1046    /// repeated on every call; subsequent calls return the cached
1047    /// outcome. Call
1048    /// [`invalidate_icon_theme()`](Self::invalidate_icon_theme) to
1049    /// force a re-read.
1050    ///
1051    /// # Errors
1052    ///
1053    /// As [`system_icon_theme()`]: no theme stands in for one that could
1054    /// not be detected.
1055    pub fn icon_theme(&self) -> crate::Result<String> {
1056        self.icon_theme_with(detect_icon_theme_inner)
1057    }
1058
1059    /// [`icon_theme()`](Self::icon_theme), with `detect` run where
1060    /// nothing is cached.
1061    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    /// The current Linux desktop environment (cached).
1071    ///
1072    /// The first call reads `XDG_CURRENT_DESKTOP` and caches the
1073    /// result. Call
1074    /// [`invalidate_linux_desktop()`](Self::invalidate_linux_desktop)
1075    /// to force a re-read.
1076    #[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    /// The desktop the reader, the theme watcher and the icon-theme detection
1083    /// decide by ([`refine_linux_desktop`]), cached: on an
1084    /// unrecognised desktop the portal backend is asked over D-Bus (with the
1085    /// `portal` feature), then `kdeglobals` is looked for. The system reads
1086    /// (`SystemTheme::from_system`, `from_system_async`,
1087    /// `AccessibilityPreferences::from_system`) fill the cache.
1088    /// [`invalidate_linux_desktop()`](Self::invalidate_linux_desktop) clears it.
1089    #[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    /// Cache `refined`, the desktop a system read refined. Where it is not
1111    /// `without_portal`, the desktop a synchronous caller refines while
1112    /// nothing is cached ([`refined_linux_desktop_sync`](Self::refined_linux_desktop_sync)),
1113    /// the values detected from that desktop are cleared: the
1114    /// icon theme, dark mode and reduced motion.
1115    #[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    /// The desktop the platform readers use: the raw `XDG_CURRENT_DESKTOP`
1131    /// ([`linux_desktop()`](Self::linux_desktop)) where it names a desktop;
1132    /// for [`LinuxDesktop::Unknown`], the desktop the portal backend named at
1133    /// the last system read (`SystemTheme::from_system`, `from_system_async`,
1134    /// `AccessibilityPreferences::from_system`, with the `portal` feature),
1135    /// else KDE where the user's `kdeglobals` exists (with the `kde`
1136    /// feature), else `Unknown`. The reader, the theme watcher and the icon-theme
1137    /// detection decide by it, and the icon enums
1138    /// native-theme-build generates pick their per-desktop names by it.
1139    ///
1140    /// A system read caches the desktop it refined; until one has, this call
1141    /// does not ask the portal and caches nothing, so on an unrecognised
1142    /// desktop whose portal backend names one it can differ from what the
1143    /// next system read caches (a KDE backend without `kdeglobals` is
1144    /// `Unknown` here, a GNOME backend with `kdeglobals` is KDE here); the
1145    /// system read then clears the icon theme, dark mode and reduced
1146    /// motion detected from this desktop.
1147    /// [`invalidate_linux_desktop()`](Self::invalidate_linux_desktop) clears
1148    /// the cached desktop.
1149    #[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    /// The font DPI: 72.0 on macOS, 96.0 everywhere else, every Linux desktop
1159    /// included (`detect_system_font_dpi`). A constant per platform since 0.7.1:
1160    /// nothing is read and nothing is cached.
1161    pub(crate) fn font_dpi(&self) -> f32 {
1162        detect_system_font_dpi()
1163    }
1164
1165    /// Clear the cached dark-mode value.
1166    pub fn invalidate_is_dark(&self) {
1167        self.is_dark.invalidate();
1168    }
1169
1170    /// Clear the cached reduced-motion value.
1171    pub fn invalidate_reduced_motion(&self) {
1172        self.reduced_motion.invalidate();
1173    }
1174
1175    /// Clear the cached accessibility preferences.
1176    pub fn invalidate_accessibility_preferences(&self) {
1177        self.reader_accessibility.invalidate();
1178    }
1179
1180    /// Clear the cached icon theme, or the cached failure to detect one.
1181    pub fn invalidate_icon_theme(&self) {
1182        self.icon_theme.invalidate();
1183    }
1184
1185    /// Does nothing. Since 0.7.1 the font DPI is a constant per platform (72 on
1186    /// macOS, 96 elsewhere), which nothing caches; the method stays so that code
1187    /// calling it still builds.
1188    pub fn invalidate_font_dpi(&self) {}
1189
1190    /// Clear the cached Linux desktop environment, and the desktop refined
1191    /// from it.
1192    #[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    /// Clear all cached values.
1199    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
1209/// Return the process-wide default [`DetectionContext`].
1210///
1211/// This is a lazily-initialized singleton. The first call creates it;
1212/// all subsequent calls return the same instance.
1213pub fn system() -> &'static DetectionContext {
1214    static INSTANCE: std::sync::OnceLock<DetectionContext> = std::sync::OnceLock::new();
1215    INSTANCE.get_or_init(DetectionContext::new)
1216}
1217
1218/// Inner icon theme detection, delegating to platform-specific logic.
1219///
1220/// On Linux, dispatches by desktop environment. On macOS/iOS/Windows,
1221/// returns the compile-time constant; elsewhere, the platform's failure.
1222fn detect_icon_theme_inner() -> Result<String, IconThemeFailure> {
1223    icon_theme::detect_icon_theme_outcome()
1224}
1225
1226// === Crate-internal accessors ===
1227
1228/// The platform's font DPI ([`DetectionContext::font_dpi`]).
1229pub(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        // Smoke test: function should not panic on any platform.
1241        // Cannot assert a specific value because caching preserves the first call
1242        // and CI environments have varying accessibility settings.
1243        let _result = prefers_reduced_motion();
1244    }
1245
1246    #[cfg(target_os = "linux")]
1247    #[test]
1248    fn detect_reduced_motion_inner_linux() {
1249        // Bypass caching to test actual detection logic.
1250        // On CI without gsettings, returns false (animations enabled).
1251        // On developer machines, depends on accessibility settings.
1252        let result = detect_reduced_motion_inner();
1253        // Just verify it returns a bool without panicking.
1254        let _ = result;
1255    }
1256
1257    /// `gsetting` for [`desktop_reduce_motion`]: `enable-animations` is
1258    /// `enabled`; `asked` counts the reads.
1259    #[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    /// On KDE reduced motion is kdeglobals' `AnimationDurationFactor`, as the
1272    /// KDE reader reads it, not GNOME's `enable-animations`, which may be
1273    /// absent or stale there (M1-T6-04); gsettings answers only where
1274    /// kdeglobals is not read (no `kde` feature).
1275    #[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    /// On GNOME and Budgie the portal's answer decides, as in the GNOME
1303    /// reader; without one, gsettings' `enable-animations`.
1304    #[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    /// A desktop without a reader answers from gsettings alone.
1335    #[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    /// The slot every cached field uses ([`DetectionContext::is_dark`],
1373    /// [`DetectionContext::linux_desktop`] and the rest): a value detected
1374    /// across an invalidation is returned, not cached.
1375    #[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    /// A fill whose generation check passed before an invalidation and whose
1388    /// swap landed after it leaves an entry of the old generation, which no
1389    /// read returns.
1390    #[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    /// A context with every slot filled.
1427    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    /// `invalidate_all` empties every slot. The pattern names each field, so
1445    /// a slot added to [`DetectionContext`] does not compile until it is
1446    /// checked here.
1447    #[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    /// `invalidate_font_dpi` does nothing: the font DPI is a constant per
1483    /// platform, which nothing caches.
1484    #[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    /// A synchronous caller gets the desktop a system read refined, portal
1615    /// answer included, until it is invalidated.
1616    #[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    /// A context whose raw desktop is `Unknown` and whose system read refined
1630    /// it with `portal_backend`, `kdeglobals` absent.
1631    #[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    /// An icon theme, dark mode or reduced motion read before the
1645    /// first system read came from the desktop refined without the portal; a
1646    /// portal answer that names another desktop clears them, so they are read
1647    /// again from the reader's desktop (docs/archive/todo_closed.md, *Closed
1648    /// items from Font DPI*, 'For M4: an unrecognised `XDG_CURRENT_DESKTOP`
1649    /// with a GNOME portal backend', M4-49).
1650    #[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    /// A portal answer that names the desktop the synchronous refinement
1681    /// already gave keeps what was read from it.
1682    #[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    /// On an unrecognised desktop a system read refined to KDE, dark mode
1707    /// comes from `kdeglobals` first, as the KDE reader takes it; on one
1708    /// refined to GNOME, from gsettings first.
1709    #[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    /// `XDG_CURRENT_DESKTOP` decides where it names a desktop; the portal
1735    /// backend, then `kdeglobals`, only where it names none.
1736    #[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    /// The timeout of a test whose command finishes: a loaded machine never
1773    /// takes that long, where it could take `SUBPROCESS_TIMEOUT`'s 2 s, the
1774    /// readers' design value.
1775    const GENEROUS: Duration = Duration::from_secs(10);
1776
1777    /// Whether `program` is an executable file in a `$PATH` directory.
1778    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    /// An unsuccessful exit is an output, with its status and its stderr;
1804    /// [`stdout_with_timeout`] gives `None` for it.
1805    #[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    /// A command that exits at once with no output gives an empty stdout;
1824    /// the time it took is printed (the schedule test is the timing proof).
1825    #[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    /// Whether a process runs with exactly the command line `cmdline`.
1840    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    /// A command that outlives the timeout is killed and reaped, and the
1850    /// call ends at the timeout, not when the command would have: its sleep
1851    /// is 30 s, and the 5 s bound leaves a loaded machine room to stall.
1852    #[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    /// 100 KiB is more than a Linux pipe holds (65,536 bytes, pipe(7)), so
1874    /// the command finishes only if its stdout is read while it runs.
1875    #[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    /// A process the command leaves running with its stdout keeps the pipe
1886    /// open after the command exits; the call still ends at the deadline,
1887    /// not when that process exits: it sleeps 10 s, and the 5 s bound leaves
1888    /// a loaded machine room to stall.
1889    #[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    /// Unset, empty and relative are each "not set" (the XDG Base Directory
1928    /// Specification ignores a relative path).
1929    #[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}