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, xrdb,
14/// xrandr, 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, the icon-theme detection
124/// and the font DPI 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 is the font DPI that
219/// [`ResolutionContext::from_system()`](crate::ResolutionContext::from_system)
220/// and the KDE reader use.
221///
222/// Call this when you detect that the user has changed system settings (e.g.,
223/// dark mode toggle, icon theme switch, accessibility preferences).
224///
225/// The `detect_*()` family of functions are unaffected — they always query
226/// the OS directly. The installed freedesktop icon themes are not re-read:
227/// the icon lookup reads them once per process, and so do
228/// [`is_freedesktop_theme_available()`](crate::icons::is_freedesktop_theme_available)
229/// and [`list_freedesktop_themes()`](crate::icons::list_freedesktop_themes).
230pub fn invalidate_caches() {
231    system().invalidate_all();
232}
233
234/// Detect whether the system is using a dark color scheme without caching.
235///
236/// Unlike [`system_is_dark()`], this function queries the OS every time it is
237/// called and never caches the result. Use this when polling for theme changes
238/// or implementing live dark-mode tracking.
239///
240/// See [`system_is_dark()`] for platform behavior details.
241#[must_use]
242pub fn detect_is_dark() -> bool {
243    detect_is_dark_inner()
244}
245
246/// The longest pause between two polls of a running command.
247#[cfg(unix)]
248#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
249const POLL_INTERVAL_CAP: std::time::Duration = std::time::Duration::from_millis(50);
250
251/// The pauses between polls of a running command: 1 ms, doubling up to
252/// [`POLL_INTERVAL_CAP`], so a command that exits in a few milliseconds is
253/// seen to exit within a few milliseconds, and a slow one costs a poll per
254/// 50 ms.
255#[cfg(unix)]
256#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
257fn poll_intervals() -> impl Iterator<Item = std::time::Duration> {
258    std::iter::successors(Some(std::time::Duration::from_millis(1)), |pause| {
259        Some(pause.saturating_mul(2).min(POLL_INTERVAL_CAP))
260    })
261}
262
263/// Run `program` with `args` and its stdin closed, waiting up to `timeout`
264/// for it to exit and for its stdout and stderr to close.
265///
266/// Its output is what [`std::process::Command::output`] gives, an
267/// unsuccessful exit included. Both pipes are read while the command runs,
268/// each on a thread of its own, so a command that prints more than a pipe
269/// holds (65,536 bytes on Linux, pipe(7)) is not stalled until it is
270/// killed. The error is the spawn's, a reader thread's that cannot be
271/// started, or one of kind [`std::io::ErrorKind::TimedOut`] when the command
272/// outlives `timeout` or a process it started still holds its output open
273/// at `timeout`. A command that has not exited is killed and reaped on
274/// every error; one the kill fails on is left unreaped rather than waited
275/// for, and a reader still blocked at `timeout` is left to end when the pipe
276/// closes, so `timeout` stays a bound on the call. The command is polled at
277/// [`poll_intervals`].
278#[cfg(unix)]
279#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
280pub(crate) fn run_with_timeout(
281    program: &str,
282    args: &[&str],
283    timeout: std::time::Duration,
284) -> std::io::Result<std::process::Output> {
285    use std::process::{Child, Command, Stdio};
286    use std::sync::mpsc::{Receiver, RecvTimeoutError};
287    use std::time::Instant;
288
289    fn kill_and_reap(child: &mut Child) {
290        if child.kill().is_ok() {
291            let _ = child.wait();
292        }
293    }
294
295    let timed_out = || {
296        std::io::Error::new(
297            std::io::ErrorKind::TimedOut,
298            format!("timed out after {timeout:?}"),
299        )
300    };
301
302    let start = Instant::now();
303    let mut child = Command::new(program)
304        .args(args)
305        .stdin(Stdio::null())
306        .stdout(Stdio::piped())
307        .stderr(Stdio::piped())
308        .spawn()?;
309    let readers = read_on_a_thread(child.stdout.take())
310        .and_then(|stdout| Ok((stdout, read_on_a_thread(child.stderr.take())?)));
311    let (stdout, stderr) = match readers {
312        Ok(readers) => readers,
313        Err(e) => {
314            kill_and_reap(&mut child);
315            return Err(e);
316        }
317    };
318
319    let mut intervals = poll_intervals();
320    let status = loop {
321        match child.try_wait() {
322            Ok(Some(status)) => break status,
323            Ok(None) => {
324                let elapsed = start.elapsed();
325                if elapsed >= timeout {
326                    kill_and_reap(&mut child);
327                    return Err(timed_out());
328                }
329                let pause = intervals.next().unwrap_or(POLL_INTERVAL_CAP);
330                std::thread::sleep(pause.min(timeout.saturating_sub(elapsed)));
331            }
332            Err(e) => {
333                kill_and_reap(&mut child);
334                return Err(e);
335            }
336        }
337    };
338
339    let received = |reader: Receiver<Vec<u8>>| {
340        reader
341            .recv_timeout(timeout.saturating_sub(start.elapsed()))
342            .map_err(|e| match e {
343                RecvTimeoutError::Timeout => timed_out(),
344                RecvTimeoutError::Disconnected => {
345                    std::io::Error::other("the output reader stopped without a result")
346                }
347            })
348    };
349    Ok(std::process::Output {
350        status,
351        stdout: received(stdout)?,
352        stderr: received(stderr)?,
353    })
354}
355
356/// Read `pipe` to its end on a new thread, which sends what it read; an
357/// absent pipe is read as empty. The error is the thread's spawn error.
358#[cfg(unix)]
359#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
360fn read_on_a_thread(
361    pipe: Option<impl std::io::Read + Send + 'static>,
362) -> std::io::Result<std::sync::mpsc::Receiver<Vec<u8>>> {
363    let (sender, receiver) = std::sync::mpsc::channel();
364    match pipe {
365        Some(mut pipe) => {
366            std::thread::Builder::new()
367                .name("native-theme-subprocess-output".to_string())
368                .spawn(move || {
369                    let mut read = Vec::new();
370                    let _ = pipe.read_to_end(&mut read);
371                    let _ = sender.send(read);
372                })?;
373        }
374        None => {
375            let _ = sender.send(Vec::new());
376        }
377    }
378    Ok(receiver)
379}
380
381/// The stdout of `program` run with `args` ([`run_with_timeout`]) when it
382/// exits successfully within `timeout` and prints UTF-8; `None` otherwise.
383#[cfg(unix)]
384#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
385pub(crate) fn stdout_with_timeout(
386    program: &str,
387    args: &[&str],
388    timeout: std::time::Duration,
389) -> Option<String> {
390    let output = run_with_timeout(program, args, timeout).ok()?;
391    if !output.status.success() {
392        return None;
393    }
394    String::from_utf8(output.stdout).ok()
395}
396
397/// The user's config directory: `$XDG_CONFIG_HOME`, else `$HOME/.config`;
398/// `None` without either ([`xdg_config_home_from`] of the environment).
399#[cfg(target_os = "linux")]
400pub(crate) fn xdg_config_home() -> Option<std::path::PathBuf> {
401    xdg_config_home_from(
402        std::env::var_os("XDG_CONFIG_HOME").as_deref(),
403        std::env::var_os("HOME").as_deref(),
404    )
405}
406
407/// The config directory `$XDG_CONFIG_HOME` (`var`) names: itself when it is
408/// absolute, else `<home>/.config` when `home` is non-empty, else `None`.
409///
410/// The XDG Base Directory Specification 0.8: "If `$XDG_CONFIG_HOME` is
411/// either not set or empty, a default equal to `$HOME/.config` should be
412/// used", and "All paths set in these environment variables must be
413/// absolute. If an implementation encounters a relative path in any of
414/// these variables it should consider the path invalid and ignore it"
415/// (<https://specifications.freedesktop.org/basedir-spec/0.8/>).
416#[cfg(target_os = "linux")]
417fn xdg_config_home_from(
418    var: Option<&std::ffi::OsStr>,
419    home: Option<&std::ffi::OsStr>,
420) -> Option<std::path::PathBuf> {
421    var.map(std::path::PathBuf::from)
422        .filter(|dir| dir.is_absolute())
423        .or_else(|| {
424            home.filter(|home| !home.is_empty())
425                .map(|home| std::path::Path::new(home).join(".config"))
426        })
427}
428
429/// Why [`xdg_config_home`] is `None`.
430#[cfg(target_os = "linux")]
431pub(crate) const CONFIG_HOME_UNRESOLVED: &str = "the config directory is unresolved: \
432    $XDG_CONFIG_HOME is not an absolute path and $HOME is unset or empty";
433
434/// Run `gsettings get <schema> <key>`, waiting up to `timeout`.
435///
436/// Returns the trimmed stdout on success; `None` if the command fails, times
437/// out, or produces empty output. The timeout keeps gsettings from blocking
438/// indefinitely when D-Bus is unresponsive.
439#[cfg(target_os = "linux")]
440pub(crate) fn gsettings_get(
441    schema: &str,
442    key: &str,
443    timeout: std::time::Duration,
444) -> Option<String> {
445    let out = stdout_with_timeout("gsettings", &["get", schema, key], timeout)?;
446    let trimmed = out.trim();
447    if trimmed.is_empty() {
448        None
449    } else {
450        Some(trimmed.to_string())
451    }
452}
453
454/// Read `Xft.dpi` from X resources via `xrdb -query`.
455///
456/// Returns `None` if xrdb is not installed, times out (2 seconds),
457/// or the output does not contain a valid positive `Xft.dpi` value.
458#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
459fn read_xft_dpi() -> Option<f32> {
460    let out = stdout_with_timeout("xrdb", &["-query"], SUBPROCESS_TIMEOUT)?;
461    // Parse "Xft.dpi:\t96" from multi-line output
462    for line in out.lines() {
463        if let Some(rest) = line.strip_prefix("Xft.dpi:")
464            && let Ok(dpi) = rest.trim().parse::<f32>()
465            && dpi > 0.0
466        {
467            return Some(dpi);
468        }
469    }
470    None
471}
472
473/// Detect physical DPI from display hardware via `xrandr`.
474///
475/// Parses the primary connected output's resolution and physical dimensions
476/// to compute DPI. Falls back to the first connected output if no primary
477/// is found. Returns `None` if `xrandr` is unavailable, times out (2 seconds),
478/// or the output cannot be parsed.
479///
480/// This is a last-resort fallback: prefer `forceFontDPI` (KDE), `Xft.dpi`
481/// (X resources) before calling this.
482#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
483fn detect_physical_dpi() -> Option<f32> {
484    let out = stdout_with_timeout("xrandr", &[], SUBPROCESS_TIMEOUT)?;
485    parse_xrandr_dpi(&out)
486}
487
488/// Parse DPI from xrandr output.
489///
490/// Looks for lines like:
491/// ```text
492/// DP-1 connected primary 3840x2160+0+0 (...) 700mm x 390mm
493/// ```
494/// Extracts the current resolution from the mode string and the physical
495/// dimensions from the trailing `NNNmm x NNNmm`, then computes average DPI.
496#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
497fn parse_xrandr_dpi(output: &str) -> Option<f32> {
498    // Prefer the primary output; fall back to the first connected output.
499    let line = output
500        .lines()
501        .find(|l| l.contains(" connected") && l.contains("primary"))
502        .or_else(|| {
503            output
504                .lines()
505                .find(|l| l.contains(" connected") && !l.contains("disconnected"))
506        })?;
507
508    // Resolution: "3840x2160+0+0" (digits x digits + offset)
509    let res_token = line
510        .split_whitespace()
511        .find(|s| s.contains('x') && s.contains('+'))?;
512    let (w_str, rest) = res_token.split_once('x')?;
513    let h_str = rest.split('+').next()?;
514    let w_px: f32 = w_str.parse().ok()?;
515    let h_px: f32 = h_str.parse().ok()?;
516
517    // Physical size: "700mm x 390mm" at the end of the line
518    let words: Vec<&str> = line.split_whitespace().collect();
519    let mut w_mm = None;
520    let mut h_mm = None;
521    for window in words.windows(3) {
522        let [prev, cur, next] = window else { continue };
523        if *cur == "x" {
524            w_mm = prev.strip_suffix("mm").and_then(|n| n.parse::<f32>().ok());
525            h_mm = next.strip_suffix("mm").and_then(|n| n.parse::<f32>().ok());
526        }
527    }
528    let w_mm = w_mm.filter(|&v| v > 0.0)?;
529    let h_mm = h_mm.filter(|&v| v > 0.0)?;
530
531    let h_dpi = w_px / (w_mm / 25.4);
532    let v_dpi = h_px / (h_mm / 25.4);
533    let avg = (h_dpi + v_dpi) / 2.0;
534
535    if avg > 0.0 { Some(avg) } else { None }
536}
537
538#[cfg(all(test, target_os = "linux", any(feature = "kde", feature = "portal")))]
539#[allow(clippy::unwrap_used)]
540mod xrandr_dpi_tests {
541    use super::parse_xrandr_dpi;
542
543    #[test]
544    fn primary_4k_display() {
545        // Real xrandr output: 4K display at 700mm wide
546        let output = "Screen 0: minimum 16 x 16, current 3840 x 2160, maximum 32767 x 32767\n\
547                       DP-1 connected primary 3840x2160+0+0 (normal left inverted right x axis y axis) 700mm x 390mm\n\
548                          3840x2160     60.00*+\n";
549        let dpi = parse_xrandr_dpi(output).unwrap();
550        // 3840/(700/25.4) = 139.3, 2160/(390/25.4) = 140.7, avg ~140
551        assert!((dpi - 140.0).abs() < 1.0, "expected ~140 DPI, got {dpi}");
552    }
553
554    #[test]
555    fn standard_1080p_display() {
556        let output = "DP-2 connected primary 1920x1080+0+0 (normal) 530mm x 300mm\n";
557        let dpi = parse_xrandr_dpi(output).unwrap();
558        // 1920/(530/25.4) = 92.0, 1080/(300/25.4) = 91.4, avg ~91.7
559        assert!((dpi - 92.0).abs() < 1.0, "expected ~92 DPI, got {dpi}");
560    }
561
562    #[test]
563    fn no_primary_falls_back_to_first_connected() {
564        let output = "HDMI-1 connected 1920x1080+0+0 (normal) 480mm x 270mm\n\
565                       DP-1 disconnected\n";
566        let dpi = parse_xrandr_dpi(output).unwrap();
567        assert!(dpi > 90.0 && dpi < 110.0, "expected ~100 DPI, got {dpi}");
568    }
569
570    #[test]
571    fn disconnected_only_returns_none() {
572        let output = "DP-1 disconnected\nHDMI-1 disconnected\n";
573        assert!(parse_xrandr_dpi(output).is_none());
574    }
575
576    #[test]
577    fn missing_physical_dimensions_returns_none() {
578        // No "NNNmm x NNNmm" in the line
579        let output = "DP-1 connected primary 1920x1080+0+0 (normal)\n";
580        assert!(parse_xrandr_dpi(output).is_none());
581    }
582
583    #[test]
584    fn zero_mm_returns_none() {
585        let output = "DP-1 connected primary 1920x1080+0+0 (normal) 0mm x 0mm\n";
586        assert!(parse_xrandr_dpi(output).is_none());
587    }
588
589    #[test]
590    fn empty_output_returns_none() {
591        assert!(parse_xrandr_dpi("").is_none());
592    }
593}
594
595/// GNOME's font DPI: 96. gnome-settings-daemon lays fonts out at a fixed 96
596/// (`DPI_FALLBACK`) times `text-scaling-factor`, and GTK on Wayland at the same
597/// 96 × factor (gnome-settings-daemon 51.0
598/// `plugins/xsettings/gsd-xsettings-manager.c:243`, `:583-595`; GTK 4.24.1
599/// `gdk/wayland/gdksettings-wayland.c:166-168`). The factor reaches
600/// [`AccessibilityPreferences::text_scaling_factor`](crate::AccessibilityPreferences::text_scaling_factor),
601/// which the connectors apply, on a Wayland session, and the toolkit's
602/// `Xft.dpi` scale factor on an X11 one, so the font DPI leaves it out.
603/// `Xft.dpi` is not read on GNOME: gnome-settings-daemon sets it to
604/// 96 × factor × the X11 UI scale (`:665-668`, `:797-798`).
605#[cfg(all(target_os = "linux", feature = "portal"))]
606pub(crate) const GNOME_FONT_DPI: f32 = 96.0;
607
608/// The font DPI a desktop fixes: [`GNOME_FONT_DPI`] on GNOME and Budgie, the
609/// desktops the GNOME reader reads (`pipeline::select_reader`, both deciding
610/// by the refined desktop, [`refine_linux_desktop`]); `None` elsewhere, where
611/// the detection chain decides.
612#[cfg(all(target_os = "linux", feature = "portal"))]
613fn desktop_font_dpi(desktop: LinuxDesktop) -> Option<f32> {
614    matches!(desktop, LinuxDesktop::Gnome | LinuxDesktop::Budgie).then_some(GNOME_FONT_DPI)
615}
616
617/// Detect the font DPI for the current system.
618///
619/// Used, through [`system_font_dpi`], by
620/// [`ResolutionContext::from_system()`](crate::ResolutionContext::from_system)
621/// where no OS reader has provided `font_dpi`, and by the KDE reader as its
622/// own. Returns the platform-appropriate DPI for converting typographic
623/// points to logical pixels.
624///
625/// - **Linux, GNOME or Budgie, `portal` feature**: 96.0 (`GNOME_FONT_DPI`);
626///   the desktop is [`DetectionContext::refined_linux_desktop_sync`]'s, so an
627///   unrecognised one counts as the reader's
628/// - **Linux, `kde` feature** (any other desktop): on an X11 session
629///   `kcmfonts`' `forceFontDPI` (`kde_force_font_dpi`), then `Xft.dpi` →
630///   xrandr → 96.0
631/// - **Linux, `portal` feature without `kde`** (any other desktop): `Xft.dpi` → xrandr → 96.0;
632///   neither feature: 96.0
633/// - **macOS**: 72.0 (Apple coordinate system: 1pt = 1px)
634/// - **Windows**: 96.0, the Windows reader's `font_dpi`: a point is 96/72
635///   logical (effective) pixels at any display scale
636/// - **Other**: 96.0
637#[allow(unreachable_code)]
638fn detect_system_font_dpi() -> f32 {
639    #[cfg(target_os = "macos")]
640    {
641        return 72.0;
642    }
643
644    #[cfg(all(target_os = "windows", feature = "windows"))]
645    {
646        return crate::windows::LOGICAL_DPI as f32;
647    }
648
649    // GNOME: a fixed 96, the text scale carried apart (GNOME_FONT_DPI)
650    #[cfg(all(target_os = "linux", feature = "portal"))]
651    {
652        if let Some(dpi) = desktop_font_dpi(system().refined_linux_desktop_sync()) {
653            return dpi;
654        }
655    }
656
657    #[cfg(all(target_os = "linux", feature = "kde"))]
658    {
659        if let Some(dpi) = kde_force_font_dpi(session_type().as_deref(), || {
660            crate::kde::read_kcmfonts_key("General", "forceFontDPI")
661        }) {
662            return dpi;
663        }
664    }
665
666    #[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
667    {
668        if let Some(dpi) = read_xft_dpi() {
669            return dpi;
670        }
671        if let Some(dpi) = detect_physical_dpi() {
672            return dpi;
673        }
674    }
675
676    96.0
677}
678
679/// The session type, `$XDG_SESSION_TYPE` (`x11`, `wayland`, …).
680#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
681pub(crate) fn session_type() -> Option<String> {
682    std::env::var("XDG_SESSION_TYPE").ok()
683}
684
685/// Whether a session of `session_type` reads KDE's `forceFontDPI`: an X11
686/// session only. Plasma 6.7 reads the key on X11 alone (its fonts KCM shows
687/// it only for `xcb`, krdb hands it to X11 as `Xft.dpi` only off Wayland,
688/// `docs/platform-facts.md:717-718`), and Plasma 6.8 drops it; a Wayland
689/// session that kept the key from an X11 one would otherwise scale fonts
690/// Plasma does not.
691#[cfg(all(target_os = "linux", feature = "kde"))]
692pub(crate) fn reads_force_font_dpi(session_type: Option<&str>) -> bool {
693    session_type == Some("x11")
694}
695
696/// A `forceFontDPI` value as a font DPI: Plasma declares the key a UInt
697/// whose default 0 means unset (`docs/platform-facts.md:717`), so it is
698/// parsed as a `u32` and 0 is `None`, as is anything that is not a `u32`.
699#[cfg(all(target_os = "linux", feature = "kde"))]
700pub(crate) fn parse_force_font_dpi(value: &str) -> Option<f32> {
701    let dpi = value.trim().parse::<u32>().ok()?;
702    (dpi > 0).then_some(dpi as f32)
703}
704
705/// KDE's `forceFontDPI` on a session that reads it
706/// ([`reads_force_font_dpi`]), from kcmfonts, where [`parse_force_font_dpi`]
707/// accepts it. Plasma keeps the key in that file alone: the fonts KCM writes
708/// it there and krdb reads it there (`docs/platform-facts.md:717`). The file
709/// is not read on any other session.
710#[cfg(all(target_os = "linux", feature = "kde"))]
711fn kde_force_font_dpi(
712    session_type: Option<&str>,
713    kcmfonts: impl FnOnce() -> Option<String>,
714) -> Option<f32> {
715    if !reads_force_font_dpi(session_type) {
716        return None;
717    }
718    kcmfonts().as_deref().and_then(parse_force_font_dpi)
719}
720
721/// Whether the colour scheme is dark: the portal's answer when it gave one,
722/// else gsettings' `org.gnome.desktop.interface` `color-scheme` read through
723/// `gsetting` (`prefer-dark` dark; `prefer-light` and `default` light);
724/// `None` when neither answers. [`detect_is_dark`] (no portal) and the GNOME
725/// reader both decide through it, so the two cannot disagree.
726#[cfg(target_os = "linux")]
727pub(crate) fn color_scheme_is_dark(
728    portal: Option<bool>,
729    gsetting: impl FnOnce(&str, &str) -> Option<String>,
730) -> Option<bool> {
731    if portal.is_some() {
732        return portal;
733    }
734    let val = gsetting("org.gnome.desktop.interface", "color-scheme")?;
735    if val.contains("prefer-dark") {
736        Some(true)
737    } else if val.contains("prefer-light") || val.contains("default") {
738        Some(false)
739    } else {
740        None
741    }
742}
743
744/// Dark or light from the desktop's settings: on KDE (`detection`'s refined
745/// desktop, the one the KDE reader is chosen by) `kdeglobals` first, as
746/// gsettings `color-scheme` is synced by xdg-desktop-portal-kde and can be
747/// stale or inverted; elsewhere gsettings (reliable on GNOME and GTK-based
748/// desktops), then `kdeglobals`' background luminance.
749#[cfg(target_os = "linux")]
750fn desktop_is_dark(
751    detection: &DetectionContext,
752    kdeglobals: impl FnOnce() -> Option<bool>,
753    gsettings: impl FnOnce() -> Option<bool>,
754) -> Option<bool> {
755    if detection.refined_linux_desktop_sync() == LinuxDesktop::Kde {
756        kdeglobals().or_else(gsettings)
757    } else {
758        gsettings().or_else(kdeglobals)
759    }
760}
761
762/// Inner detection logic for [`system_is_dark()`].
763///
764/// Separated from the public function to allow caching.
765fn detect_is_dark_inner() -> bool {
766    #[cfg(target_os = "linux")]
767    {
768        // Check GTK_THEME env var (works across all GTK-based DEs)
769        if let Ok(gtk_theme) = std::env::var("GTK_THEME") {
770            let lower = gtk_theme.to_lowercase();
771            if lower.ends_with(":dark") || lower.contains("-dark") {
772                return true;
773            }
774        }
775
776        if let Some(dark) = desktop_is_dark(
777            system(),
778            || {
779                #[cfg(feature = "kde")]
780                {
781                    crate::kde::kdeglobals_is_dark()
782                }
783                #[cfg(not(feature = "kde"))]
784                {
785                    None
786                }
787            },
788            || {
789                color_scheme_is_dark(None, |schema, key| {
790                    gsettings_get(schema, key, SUBPROCESS_TIMEOUT)
791                })
792            },
793        ) {
794            return dark;
795        }
796
797        // Fallback: gtk-3.0/settings.ini for DEs that set the GTK dark preference
798        if let Some(content) = xdg_config_home()
799            .and_then(|dir| std::fs::read_to_string(dir.join("gtk-3.0/settings.ini")).ok())
800        {
801            for line in content.lines() {
802                let trimmed = line.trim();
803                if trimmed.starts_with("gtk-application-prefer-dark-theme")
804                    && let Some(val) = trimmed.split('=').nth(1)
805                    && (val.trim() == "1" || val.trim().eq_ignore_ascii_case("true"))
806                {
807                    return true;
808                }
809            }
810        }
811
812        false
813    }
814
815    #[cfg(target_os = "macos")]
816    {
817        // AppleInterfaceStyle is "Dark" when dark mode is active.
818        // The key is absent in light mode, so any failure means light.
819        #[cfg(feature = "macos")]
820        {
821            use objc2_foundation::NSUserDefaults;
822            let defaults = NSUserDefaults::standardUserDefaults();
823            let key = objc2_foundation::ns_string!("AppleInterfaceStyle");
824            defaults
825                .stringForKey(key)
826                .is_some_and(|value| value.to_string().eq_ignore_ascii_case("dark"))
827        }
828        #[cfg(not(feature = "macos"))]
829        {
830            stdout_with_timeout(
831                "defaults",
832                &["read", "-g", "AppleInterfaceStyle"],
833                SUBPROCESS_TIMEOUT,
834            )
835            .is_some_and(|value| value.trim().eq_ignore_ascii_case("dark"))
836        }
837    }
838
839    #[cfg(target_os = "windows")]
840    {
841        #[cfg(feature = "windows")]
842        {
843            let Ok(settings) = ::windows::UI::ViewManagement::UISettings::new() else {
844                return false;
845            };
846            let Ok(fg) =
847                settings.GetColorValue(::windows::UI::ViewManagement::UIColorType::Foreground)
848            else {
849                return false;
850            };
851            crate::windows::is_dark_mode(&crate::windows::win_color_to_rgba(fg))
852        }
853        #[cfg(not(feature = "windows"))]
854        {
855            false
856        }
857    }
858
859    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
860    {
861        false
862    }
863}
864
865/// Query whether the user prefers reduced motion.
866///
867/// Returns `true` when the OS accessibility setting indicates animations
868/// should be reduced or disabled. Returns `false` (allow animations) on
869/// unsupported platforms or when the query fails.
870///
871/// # Caching
872///
873/// The result is cached after the first call and reused on subsequent calls.
874/// Call [`invalidate_caches()`] to clear the cached value so the next call
875/// re-queries the OS. For live accessibility-change tracking, subscribe to
876/// OS accessibility events and call `invalidate_caches()` when notified.
877///
878/// # Platform Behavior
879///
880/// Each platform's read is the one its theme reader makes, so the result is
881/// the `reduce_motion` of
882/// [`AccessibilityPreferences::from_system`](crate::AccessibilityPreferences::from_system)
883/// and of [`SystemTheme::from_system`](crate::SystemTheme::from_system)'s
884/// accessibility block.
885///
886/// - **Linux:** by the desktop the reader is chosen by. KDE (with the `kde`
887///   feature): `kdeglobals`' `[KDE] AnimationDurationFactor` is 0. GNOME and
888///   Budgie: the portal's `reduced-motion` (with the `portal` feature, 2-second
889///   deadline), else `gsettings get org.gnome.desktop.interface enable-animations`
890///   is `false` (2-second timeout). Other desktops, and KDE without the `kde`
891///   feature: that gsettings key alone.
892/// - **macOS:** Queries `NSWorkspace.accessibilityDisplayShouldReduceMotion`
893///   (requires `macos` feature).
894/// - **Windows:** Queries `SystemParametersInfoW(SPI_GETCLIENTAREAANIMATION)`;
895///   `true` when client-area animations are off (requires `windows` feature).
896/// - **Other platforms:** Returns `false`.
897///
898/// # Examples
899///
900/// ```
901/// let reduced = native_theme::detect::prefers_reduced_motion();
902/// // On this platform, the result depends on OS accessibility settings.
903/// // The function always returns a bool (false on unsupported platforms).
904/// assert!(reduced == true || reduced == false);
905/// ```
906#[must_use]
907pub fn prefers_reduced_motion() -> bool {
908    system().prefers_reduced_motion()
909}
910
911/// Detect whether the user prefers reduced motion without caching.
912///
913/// Unlike [`prefers_reduced_motion()`], this function queries the OS every time
914/// it is called and never caches the result. Use this when polling for
915/// accessibility preference changes.
916///
917/// See [`prefers_reduced_motion()`] for platform behavior details.
918#[must_use]
919pub fn detect_reduced_motion() -> bool {
920    detect_reduced_motion_inner()
921}
922
923/// The OS accessibility preferences (cached): what
924/// [`AccessibilityPreferences::from_system`](crate::AccessibilityPreferences::from_system)
925/// reads, without running the platform reader again.
926///
927/// The cache holds the accessibility block of the last platform reader run:
928/// [`SystemTheme::from_system`](crate::SystemTheme::from_system) and
929/// `from_system_async` fill it, and where neither has run since the last
930/// [`invalidate_caches()`], the first call runs the reader itself.
931/// [`invalidate_caches()`] clears it. A reader that fails is not reported:
932/// the preferences used without a reader (the defaults, with the platform's
933/// [`detect_reduced_motion()`]) stay cached until the next invalidation, as a
934/// failure to detect the icon theme does.
935///
936/// For a preset switch, where the OS preferences apply under the preset and
937/// the reader has usually just run. The theme watcher
938/// (`watch::on_theme_change`) reports a change of every accessibility setting
939/// the reader reads but one, Windows' high contrast, which Windows announces
940/// only to top-level windows, as it does the non-client fonts; nothing clears
941/// the cache when it changes. That holds from Windows 10 2004: before it the
942/// watcher has no `AnimationsEnabledChanged`, so a reduced-motion change is
943/// not reported either (and before 1703, with no
944/// `AdvancedEffectsEnabledChanged`, a transparency change). Where the current
945/// setting matters more than the cost, read [`AccessibilityPreferences::from_system`](crate::AccessibilityPreferences::from_system),
946/// which runs the reader every time.
947#[must_use]
948pub fn accessibility_preferences() -> crate::AccessibilityPreferences {
949    system().accessibility_preferences()
950}
951
952/// Whether GNOME asks for reduced motion: the portal's answer when it gave
953/// one, else gsettings' `org.gnome.desktop.interface` `enable-animations`
954/// read through `gsetting` (`false` is reduced motion); `None` when neither
955/// answers. [`detect_reduced_motion`] and the GNOME reader both decide
956/// through it.
957#[cfg(target_os = "linux")]
958pub(crate) fn gnome_reduce_motion(
959    portal: Option<bool>,
960    gsetting: impl FnOnce(&str, &str) -> Option<String>,
961) -> Option<bool> {
962    if portal.is_some() {
963        return portal;
964    }
965    let enabled = gsetting("org.gnome.desktop.interface", "enable-animations")?;
966    enabled.trim().parse::<bool>().ok().map(|enabled| !enabled)
967}
968
969/// Reduced motion as the reader of `desktop` (the refined desktop) reads it:
970/// on KDE `kdeglobals` (`None` without the `kde` feature, which reads no KDE
971/// file), as the KDE reader does; on GNOME and Budgie the `portal`, then
972/// gsettings ([`gnome_reduce_motion`]), as the GNOME reader does; elsewhere,
973/// and on KDE where `kdeglobals` gives `None`, gsettings alone. `false` when
974/// nothing answers.
975#[cfg(target_os = "linux")]
976fn desktop_reduce_motion(
977    desktop: LinuxDesktop,
978    kdeglobals: impl FnOnce() -> Option<bool>,
979    portal: impl FnOnce() -> Option<bool>,
980    gsetting: impl FnOnce(&str, &str) -> Option<String>,
981) -> bool {
982    match desktop {
983        LinuxDesktop::Kde => kdeglobals().or_else(|| gnome_reduce_motion(None, gsetting)),
984        LinuxDesktop::Gnome | LinuxDesktop::Budgie => gnome_reduce_motion(portal(), gsetting),
985        _ => gnome_reduce_motion(None, gsetting),
986    }
987    .unwrap_or(false)
988}
989
990/// Inner detection logic for [`prefers_reduced_motion()`].
991///
992/// Separated from the public function to allow caching.
993fn detect_reduced_motion_inner() -> bool {
994    #[cfg(target_os = "linux")]
995    {
996        desktop_reduce_motion(
997            system().refined_linux_desktop_sync(),
998            || {
999                #[cfg(feature = "kde")]
1000                {
1001                    Some(crate::kde::kdeglobals_reduce_motion())
1002                }
1003                #[cfg(not(feature = "kde"))]
1004                {
1005                    None
1006                }
1007            },
1008            || {
1009                #[cfg(feature = "portal")]
1010                {
1011                    pollster::block_on(crate::gnome::portal_reduce_motion())
1012                }
1013                #[cfg(not(feature = "portal"))]
1014                {
1015                    None
1016                }
1017            },
1018            |schema, key| gsettings_get(schema, key, SUBPROCESS_TIMEOUT),
1019        )
1020    }
1021
1022    #[cfg(target_os = "macos")]
1023    {
1024        #[cfg(feature = "macos")]
1025        {
1026            crate::macos::reduce_motion()
1027        }
1028        #[cfg(not(feature = "macos"))]
1029        {
1030            false
1031        }
1032    }
1033
1034    #[cfg(target_os = "windows")]
1035    {
1036        #[cfg(feature = "windows")]
1037        {
1038            crate::windows::read_reduce_motion().unwrap_or(false)
1039        }
1040        #[cfg(not(feature = "windows"))]
1041        {
1042            false
1043        }
1044    }
1045
1046    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
1047    {
1048        false
1049    }
1050}
1051
1052// === DetectionContext ===
1053
1054/// A value cached with the generation of its slot when its detection began.
1055struct Stamped<T> {
1056    generation: u64,
1057    value: T,
1058}
1059
1060/// One cached detection: the value, and a generation every invalidation
1061/// bumps. A value is cached only if no invalidation landed while it was
1062/// detected, so a fill that began before an OS change and ends after a
1063/// watcher's invalidation does not cache what it read before the change.
1064struct CacheSlot<T> {
1065    value: ArcSwapOption<Stamped<T>>,
1066    generation: AtomicU64,
1067}
1068
1069/// A fill in progress: the slot's generation and entry when it began.
1070pub(crate) struct CacheFill<T> {
1071    generation: u64,
1072    seen: Option<Arc<Stamped<T>>>,
1073}
1074
1075impl<T> CacheFill<T> {
1076    /// The value the slot held for this fill's generation, if any.
1077    fn cached(&self) -> Option<&T> {
1078        self.seen
1079            .as_deref()
1080            .filter(|entry| entry.generation == self.generation)
1081            .map(|entry| &entry.value)
1082    }
1083}
1084
1085impl<T> CacheSlot<T> {
1086    fn empty() -> Self {
1087        Self {
1088            value: ArcSwapOption::empty(),
1089            generation: AtomicU64::new(0),
1090        }
1091    }
1092
1093    // The generation's Acquire loads pair with the Release bump in
1094    // `invalidate`, which follows its clearing store: a fill that reads the
1095    // bumped generation also sees the slot cleared, and an entry stamped with
1096    // an older generation than the one loaded is never returned.
1097    fn begin_fill(&self) -> CacheFill<T> {
1098        let generation = self.generation.load(Ordering::Acquire);
1099        CacheFill {
1100            generation,
1101            seen: self.value.load_full(),
1102        }
1103    }
1104
1105    /// Cache `value` unless an invalidation landed after `fill` began, or
1106    /// another fill stored a value since.
1107    fn finish_fill(&self, fill: CacheFill<T>, value: T) {
1108        if self.generation.load(Ordering::Acquire) != fill.generation {
1109            return;
1110        }
1111        let stamped = Arc::new(Stamped {
1112            generation: fill.generation,
1113            value,
1114        });
1115        let _ = self.value.compare_and_swap(&fill.seen, Some(stamped));
1116    }
1117
1118    /// The cached value, or `detect`'s, cached as [`finish_fill`](Self::finish_fill)
1119    /// caches it.
1120    fn get_or_fill(&self, detect: impl FnOnce() -> T) -> T
1121    where
1122        T: Clone,
1123    {
1124        let fill = self.begin_fill();
1125        if let Some(value) = fill.cached() {
1126            return value.clone();
1127        }
1128        let value = detect();
1129        self.finish_fill(fill, value.clone());
1130        value
1131    }
1132
1133    /// The cached value, if any.
1134    #[cfg(any(test, target_os = "linux"))]
1135    fn get(&self) -> Option<T>
1136    where
1137        T: Clone,
1138    {
1139        self.begin_fill().cached().cloned()
1140    }
1141
1142    fn invalidate(&self) {
1143        self.value.store(None);
1144        self.generation.fetch_add(1, Ordering::Release);
1145    }
1146}
1147
1148/// Process-wide detection cache.
1149///
1150/// Provides "cache on first read" semantics for OS detection queries
1151/// (`is_dark`, `reduced_motion`, `accessibility_preferences`, `icon_theme`,
1152/// `linux_desktop`, the font DPI) and
1153/// per-field invalidation for watchers that need fresh data.
1154///
1155/// Obtain the process-wide instance via [`system()`].
1156///
1157/// # Thread Safety
1158///
1159/// All reads and invalidations are lock-free (backed by
1160/// [`arc_swap::ArcSwapOption`]). A value detected while an invalidation of
1161/// its field lands is returned to its caller but not cached.
1162pub struct DetectionContext {
1163    is_dark: CacheSlot<bool>,
1164    reduced_motion: CacheSlot<bool>,
1165    reader_accessibility: CacheSlot<crate::AccessibilityPreferences>,
1166    icon_theme: CacheSlot<Result<String, IconThemeFailure>>,
1167    #[cfg(target_os = "linux")]
1168    linux_desktop: CacheSlot<LinuxDesktop>,
1169    #[cfg(target_os = "linux")]
1170    refined_linux_desktop: CacheSlot<RefinedDesktop>,
1171    font_dpi: CacheSlot<f32>,
1172}
1173
1174impl DetectionContext {
1175    /// Create an empty context with no cached values.
1176    pub(crate) fn new() -> Self {
1177        Self {
1178            is_dark: CacheSlot::empty(),
1179            reduced_motion: CacheSlot::empty(),
1180            reader_accessibility: CacheSlot::empty(),
1181            icon_theme: CacheSlot::empty(),
1182            #[cfg(target_os = "linux")]
1183            linux_desktop: CacheSlot::empty(),
1184            #[cfg(target_os = "linux")]
1185            refined_linux_desktop: CacheSlot::empty(),
1186            font_dpi: CacheSlot::empty(),
1187        }
1188    }
1189
1190    /// Whether the system is using a dark color scheme (cached).
1191    ///
1192    /// The first call queries the OS and caches the result.
1193    /// Subsequent calls return the cached value.
1194    /// Call [`invalidate_is_dark()`](Self::invalidate_is_dark) to
1195    /// force a re-read on the next call.
1196    #[must_use]
1197    pub fn is_dark(&self) -> bool {
1198        self.is_dark.get_or_fill(detect_is_dark_inner)
1199    }
1200
1201    /// Whether the user prefers reduced motion (cached).
1202    ///
1203    /// The first call queries the OS and caches the result.
1204    /// Call [`invalidate_reduced_motion()`](Self::invalidate_reduced_motion)
1205    /// to force a re-read.
1206    #[must_use]
1207    pub fn prefers_reduced_motion(&self) -> bool {
1208        self.reduced_motion.get_or_fill(detect_reduced_motion_inner)
1209    }
1210
1211    /// The OS accessibility preferences (cached), as
1212    /// [`accessibility_preferences()`](crate::detect::accessibility_preferences)
1213    /// describes: the platform reader's accessibility block, run on the
1214    /// first call unless a system read stored it.
1215    /// Call
1216    /// [`invalidate_accessibility_preferences()`](Self::invalidate_accessibility_preferences)
1217    /// to force a re-read.
1218    #[must_use]
1219    pub fn accessibility_preferences(&self) -> crate::AccessibilityPreferences {
1220        self.reader_accessibility_with(|| {
1221            pollster::block_on(crate::pipeline::reader_accessibility())
1222        })
1223    }
1224
1225    /// The cached reader accessibility block, with `read` run where
1226    /// nothing is cached.
1227    pub(crate) fn reader_accessibility_with(
1228        &self,
1229        read: impl FnOnce() -> crate::AccessibilityPreferences,
1230    ) -> crate::AccessibilityPreferences {
1231        self.reader_accessibility.get_or_fill(read)
1232    }
1233
1234    /// Begin a platform read whose accessibility block
1235    /// [`store_reader_accessibility`](Self::store_reader_accessibility)
1236    /// stores.
1237    pub(crate) fn begin_reader_accessibility(&self) -> CacheFill<crate::AccessibilityPreferences> {
1238        self.reader_accessibility.begin_fill()
1239    }
1240
1241    /// Store the accessibility block a platform reader just returned, unless
1242    /// the cache was invalidated or filled since the read began (`fill`).
1243    pub(crate) fn store_reader_accessibility(
1244        &self,
1245        fill: CacheFill<crate::AccessibilityPreferences>,
1246        prefs: crate::AccessibilityPreferences,
1247    ) {
1248        self.reader_accessibility.finish_fill(fill, prefs);
1249    }
1250
1251    /// The current icon theme name (cached), or why none was detected.
1252    ///
1253    /// The first call detects the theme from the OS and caches the
1254    /// outcome, a failure included, so a failed detection is not
1255    /// repeated on every call; subsequent calls return the cached
1256    /// outcome. Call
1257    /// [`invalidate_icon_theme()`](Self::invalidate_icon_theme) to
1258    /// force a re-read.
1259    ///
1260    /// # Errors
1261    ///
1262    /// As [`system_icon_theme()`]: no theme stands in for one that could
1263    /// not be detected.
1264    pub fn icon_theme(&self) -> crate::Result<String> {
1265        self.icon_theme_with(detect_icon_theme_inner)
1266    }
1267
1268    /// [`icon_theme()`](Self::icon_theme), with `detect` run where
1269    /// nothing is cached.
1270    fn icon_theme_with(
1271        &self,
1272        detect: impl FnOnce() -> Result<String, IconThemeFailure>,
1273    ) -> crate::Result<String> {
1274        self.icon_theme
1275            .get_or_fill(detect)
1276            .map_err(|failure| failure.to_error())
1277    }
1278
1279    /// The current Linux desktop environment (cached).
1280    ///
1281    /// The first call reads `XDG_CURRENT_DESKTOP` and caches the
1282    /// result. Call
1283    /// [`invalidate_linux_desktop()`](Self::invalidate_linux_desktop)
1284    /// to force a re-read.
1285    #[cfg(target_os = "linux")]
1286    #[must_use]
1287    pub fn linux_desktop(&self) -> LinuxDesktop {
1288        self.linux_desktop.get_or_fill(detect_linux_desktop)
1289    }
1290
1291    /// The desktop the reader, the theme watcher, the icon-theme detection
1292    /// and the font DPI decide by ([`refine_linux_desktop`]), cached: on an
1293    /// unrecognised desktop the portal backend is asked over D-Bus (with the
1294    /// `portal` feature), then `kdeglobals` is looked for. The system reads
1295    /// (`SystemTheme::from_system`, `from_system_async`,
1296    /// `AccessibilityPreferences::from_system`) fill the cache.
1297    /// [`invalidate_linux_desktop()`](Self::invalidate_linux_desktop) clears it.
1298    #[cfg(target_os = "linux")]
1299    pub(crate) async fn refined_linux_desktop(&self) -> RefinedDesktop {
1300        let fill = self.refined_linux_desktop.begin_fill();
1301        if let Some(v) = fill.cached() {
1302            return *v;
1303        }
1304        let raw = self.linux_desktop();
1305        #[cfg(feature = "portal")]
1306        let portal_backend = if raw == LinuxDesktop::Unknown {
1307            crate::gnome::detect_portal_backend().await
1308        } else {
1309            None
1310        };
1311        #[cfg(not(feature = "portal"))]
1312        let portal_backend = None;
1313        let refined = refine_desktop(raw, portal_backend, kdeglobals_exists);
1314        let without_portal = refine_linux_desktop(raw, None, kdeglobals_exists);
1315        self.finish_refined_desktop(fill, refined, without_portal);
1316        refined
1317    }
1318
1319    /// Cache `refined`, the desktop a system read refined. Where it is not
1320    /// `without_portal`, the desktop a synchronous caller refines while
1321    /// nothing is cached ([`refined_linux_desktop_sync`](Self::refined_linux_desktop_sync)),
1322    /// the values detected from that desktop are cleared: the font DPI, the
1323    /// icon theme, dark mode and reduced motion.
1324    #[cfg(target_os = "linux")]
1325    fn finish_refined_desktop(
1326        &self,
1327        fill: CacheFill<RefinedDesktop>,
1328        refined: RefinedDesktop,
1329        without_portal: LinuxDesktop,
1330    ) {
1331        self.refined_linux_desktop.finish_fill(fill, refined);
1332        if refined.desktop != without_portal {
1333            self.invalidate_font_dpi();
1334            self.invalidate_icon_theme();
1335            self.invalidate_is_dark();
1336            self.invalidate_reduced_motion();
1337        }
1338    }
1339
1340    /// The desktop the platform readers use: the raw `XDG_CURRENT_DESKTOP`
1341    /// ([`linux_desktop()`](Self::linux_desktop)) where it names a desktop;
1342    /// for [`LinuxDesktop::Unknown`], the desktop the portal backend named at
1343    /// the last system read (`SystemTheme::from_system`, `from_system_async`,
1344    /// `AccessibilityPreferences::from_system`, with the `portal` feature),
1345    /// else KDE where the user's `kdeglobals` exists (with the `kde`
1346    /// feature), else `Unknown`. The reader, the theme watcher, the icon-theme
1347    /// detection and the font DPI decide by it, and the icon enums
1348    /// native-theme-build generates pick their per-desktop names by it.
1349    ///
1350    /// A system read caches the desktop it refined; until one has, this call
1351    /// does not ask the portal and caches nothing, so on an unrecognised
1352    /// desktop whose portal backend names one it can differ from what the
1353    /// next system read caches (a KDE backend without `kdeglobals` is
1354    /// `Unknown` here, a GNOME backend with `kdeglobals` is KDE here); the
1355    /// system read then clears the font DPI, icon theme, dark mode and
1356    /// reduced motion detected from this desktop.
1357    /// [`invalidate_linux_desktop()`](Self::invalidate_linux_desktop) clears
1358    /// the cached desktop.
1359    #[cfg(target_os = "linux")]
1360    #[must_use]
1361    pub fn refined_linux_desktop_sync(&self) -> LinuxDesktop {
1362        if let Some(v) = self.refined_linux_desktop.get() {
1363            return v.desktop;
1364        }
1365        refine_linux_desktop(self.linux_desktop(), None, kdeglobals_exists)
1366    }
1367
1368    /// The system font DPI (cached), from the detection chain of
1369    /// `detect_system_font_dpi`.
1370    ///
1371    /// The first call runs the chain (on Linux `xrdb -query`, maybe
1372    /// `xrandr`) and caches the result. Call
1373    /// [`invalidate_font_dpi()`](Self::invalidate_font_dpi) to force a re-read.
1374    pub(crate) fn font_dpi(&self) -> f32 {
1375        self.font_dpi_with(detect_system_font_dpi)
1376    }
1377
1378    /// [`font_dpi()`](Self::font_dpi), with `detect` run where nothing is
1379    /// cached.
1380    fn font_dpi_with(&self, detect: impl FnOnce() -> f32) -> f32 {
1381        self.font_dpi.get_or_fill(detect)
1382    }
1383
1384    /// Clear the cached dark-mode value.
1385    pub fn invalidate_is_dark(&self) {
1386        self.is_dark.invalidate();
1387    }
1388
1389    /// Clear the cached reduced-motion value.
1390    pub fn invalidate_reduced_motion(&self) {
1391        self.reduced_motion.invalidate();
1392    }
1393
1394    /// Clear the cached accessibility preferences.
1395    pub fn invalidate_accessibility_preferences(&self) {
1396        self.reader_accessibility.invalidate();
1397    }
1398
1399    /// Clear the cached icon theme, or the cached failure to detect one.
1400    pub fn invalidate_icon_theme(&self) {
1401        self.icon_theme.invalidate();
1402    }
1403
1404    /// Clear the cached font DPI.
1405    pub fn invalidate_font_dpi(&self) {
1406        self.font_dpi.invalidate();
1407    }
1408
1409    /// Clear the cached Linux desktop environment, and the desktop refined
1410    /// from it.
1411    #[cfg(target_os = "linux")]
1412    pub fn invalidate_linux_desktop(&self) {
1413        self.linux_desktop.invalidate();
1414        self.refined_linux_desktop.invalidate();
1415    }
1416
1417    /// Clear all cached values.
1418    pub fn invalidate_all(&self) {
1419        self.invalidate_is_dark();
1420        self.invalidate_reduced_motion();
1421        self.invalidate_accessibility_preferences();
1422        self.invalidate_icon_theme();
1423        #[cfg(target_os = "linux")]
1424        self.invalidate_linux_desktop();
1425        self.invalidate_font_dpi();
1426    }
1427}
1428
1429/// Return the process-wide default [`DetectionContext`].
1430///
1431/// This is a lazily-initialized singleton. The first call creates it;
1432/// all subsequent calls return the same instance.
1433pub fn system() -> &'static DetectionContext {
1434    static INSTANCE: std::sync::OnceLock<DetectionContext> = std::sync::OnceLock::new();
1435    INSTANCE.get_or_init(DetectionContext::new)
1436}
1437
1438/// Inner icon theme detection, delegating to platform-specific logic.
1439///
1440/// On Linux, dispatches by desktop environment. On macOS/iOS/Windows,
1441/// returns the compile-time constant; elsewhere, the platform's failure.
1442fn detect_icon_theme_inner() -> Result<String, IconThemeFailure> {
1443    icon_theme::detect_icon_theme_outcome()
1444}
1445
1446// === Crate-internal accessors ===
1447
1448/// The system font DPI, cached ([`DetectionContext::font_dpi`]).
1449pub(crate) fn system_font_dpi() -> f32 {
1450    system().font_dpi()
1451}
1452
1453#[cfg(test)]
1454#[allow(clippy::unwrap_used, clippy::expect_used)]
1455mod reduced_motion_tests {
1456    use super::*;
1457
1458    #[test]
1459    fn prefers_reduced_motion_smoke_test() {
1460        // Smoke test: function should not panic on any platform.
1461        // Cannot assert a specific value because caching preserves the first call
1462        // and CI environments have varying accessibility settings.
1463        let _result = prefers_reduced_motion();
1464    }
1465
1466    #[cfg(target_os = "linux")]
1467    #[test]
1468    fn detect_reduced_motion_inner_linux() {
1469        // Bypass caching to test actual detection logic.
1470        // On CI without gsettings, returns false (animations enabled).
1471        // On developer machines, depends on accessibility settings.
1472        let result = detect_reduced_motion_inner();
1473        // Just verify it returns a bool without panicking.
1474        let _ = result;
1475    }
1476
1477    /// `gsetting` for [`desktop_reduce_motion`]: `enable-animations` is
1478    /// `enabled`; `asked` counts the reads.
1479    #[cfg(target_os = "linux")]
1480    fn animations<'a>(
1481        enabled: &'static str,
1482        asked: &'a std::cell::Cell<u32>,
1483    ) -> impl FnOnce(&str, &str) -> Option<String> + 'a {
1484        move |schema, key| {
1485            asked.set(asked.get() + 1);
1486            ((schema, key) == ("org.gnome.desktop.interface", "enable-animations"))
1487                .then(|| enabled.to_string())
1488        }
1489    }
1490
1491    /// On KDE reduced motion is kdeglobals' `AnimationDurationFactor`, as the
1492    /// KDE reader reads it, not GNOME's `enable-animations`, which may be
1493    /// absent or stale there (M1-T6-04); gsettings answers only where
1494    /// kdeglobals is not read (no `kde` feature).
1495    #[cfg(target_os = "linux")]
1496    #[test]
1497    fn kde_reduced_motion_is_kdeglobals_not_gsettings() {
1498        let asked = std::cell::Cell::new(0);
1499        let portal = || -> Option<bool> { panic!("KDE does not ask the portal") };
1500        assert!(desktop_reduce_motion(
1501            LinuxDesktop::Kde,
1502            || Some(true),
1503            portal,
1504            animations("true", &asked)
1505        ));
1506        assert!(!desktop_reduce_motion(
1507            LinuxDesktop::Kde,
1508            || Some(false),
1509            portal,
1510            animations("false", &asked)
1511        ));
1512        assert_eq!(asked.get(), 0);
1513        assert!(desktop_reduce_motion(
1514            LinuxDesktop::Kde,
1515            || None,
1516            portal,
1517            animations("false", &asked)
1518        ));
1519        assert_eq!(asked.get(), 1);
1520    }
1521
1522    /// On GNOME and Budgie the portal's answer decides, as in the GNOME
1523    /// reader; without one, gsettings' `enable-animations`.
1524    #[cfg(target_os = "linux")]
1525    #[test]
1526    fn gnome_reduced_motion_is_the_portal_then_gsettings() {
1527        let asked = std::cell::Cell::new(0);
1528        let kdeglobals = || -> Option<bool> { panic!("GNOME does not read kdeglobals") };
1529        for desktop in [LinuxDesktop::Gnome, LinuxDesktop::Budgie] {
1530            assert!(desktop_reduce_motion(
1531                desktop,
1532                kdeglobals,
1533                || Some(true),
1534                animations("true", &asked)
1535            ));
1536            assert!(!desktop_reduce_motion(
1537                desktop,
1538                kdeglobals,
1539                || Some(false),
1540                animations("false", &asked)
1541            ));
1542            assert_eq!(asked.get(), 0);
1543            assert!(desktop_reduce_motion(
1544                desktop,
1545                kdeglobals,
1546                || None,
1547                animations("false", &asked)
1548            ));
1549            assert_eq!(asked.get(), 1);
1550            asked.set(0);
1551        }
1552    }
1553
1554    /// A desktop without a reader answers from gsettings alone.
1555    #[cfg(target_os = "linux")]
1556    #[test]
1557    fn other_desktops_reduced_motion_is_gsettings() {
1558        let asked = std::cell::Cell::new(0);
1559        assert!(desktop_reduce_motion(
1560            LinuxDesktop::Xfce,
1561            || -> Option<bool> { panic!("XFCE does not read kdeglobals") },
1562            || -> Option<bool> { panic!("XFCE does not ask the portal") },
1563            animations("false", &asked)
1564        ));
1565        assert!(!desktop_reduce_motion(
1566            LinuxDesktop::Unknown,
1567            || None,
1568            || None,
1569            |_, _| None
1570        ));
1571    }
1572
1573    #[cfg(target_os = "macos")]
1574    #[test]
1575    fn detect_reduced_motion_inner_macos() {
1576        let result = detect_reduced_motion_inner();
1577        let _ = result;
1578    }
1579
1580    #[cfg(target_os = "windows")]
1581    #[test]
1582    fn detect_reduced_motion_inner_windows() {
1583        let result = detect_reduced_motion_inner();
1584        let _ = result;
1585    }
1586}
1587
1588#[cfg(all(test, target_os = "linux", feature = "kde"))]
1589mod force_font_dpi_tests {
1590    use super::*;
1591
1592    #[test]
1593    fn force_font_dpi_is_a_positive_u32() {
1594        assert_eq!(parse_force_font_dpi("120"), Some(120.0));
1595        assert_eq!(parse_force_font_dpi(" 144 "), Some(144.0));
1596        for value in ["0", "inf", "-inf", "NaN", "-96", "96.5", "1e3", ""] {
1597            assert_eq!(parse_force_font_dpi(value), None, "forceFontDPI={value}");
1598        }
1599    }
1600
1601    #[test]
1602    fn only_an_x11_session_reads_force_font_dpi() {
1603        assert!(reads_force_font_dpi(Some("x11")));
1604        for session in [Some("wayland"), Some("tty"), Some(""), None] {
1605            assert!(!reads_force_font_dpi(session), "{session:?}");
1606        }
1607    }
1608
1609    #[test]
1610    fn a_wayland_session_ignores_force_font_dpi() {
1611        let reads = std::cell::Cell::new(0);
1612        let file = || {
1613            reads.set(reads.get() + 1);
1614            Some("120".to_string())
1615        };
1616        for session in [Some("wayland"), None] {
1617            assert_eq!(kde_force_font_dpi(session, file), None, "{session:?}");
1618        }
1619        assert_eq!(reads.get(), 0, "a file was read off X11");
1620    }
1621
1622    #[test]
1623    fn an_x11_session_takes_a_valid_kcmfonts_key() {
1624        assert_eq!(
1625            kde_force_font_dpi(Some("x11"), || Some("144".into())),
1626            Some(144.0)
1627        );
1628        for kcmfonts in [None, Some("0"), Some("inf")] {
1629            assert_eq!(
1630                kde_force_font_dpi(Some("x11"), || kcmfonts.map(String::from)),
1631                None,
1632                "kcmfonts {kcmfonts:?}"
1633            );
1634        }
1635    }
1636}
1637
1638#[cfg(test)]
1639mod cache_slot_tests {
1640    use super::*;
1641
1642    /// The slot every cached field uses ([`DetectionContext::is_dark`],
1643    /// [`DetectionContext::linux_desktop`] and the rest): a value detected
1644    /// across an invalidation is returned, not cached.
1645    #[test]
1646    fn a_value_detected_across_an_invalidation_is_not_cached() {
1647        let slot = CacheSlot::empty();
1648        assert!(slot.get_or_fill(|| {
1649            slot.invalidate();
1650            true
1651        }));
1652        assert!(slot.get().is_none());
1653        assert!(!slot.get_or_fill(|| false));
1654        assert_eq!(slot.get(), Some(false));
1655    }
1656
1657    /// A fill whose generation check passed before an invalidation and whose
1658    /// swap landed after it leaves an entry of the old generation, which no
1659    /// read returns.
1660    #[test]
1661    fn an_entry_stamped_before_an_invalidation_is_not_returned() {
1662        let slot = CacheSlot::empty();
1663        let fill = slot.begin_fill();
1664        slot.invalidate();
1665        let stale = Arc::new(Stamped {
1666            generation: fill.generation,
1667            value: true,
1668        });
1669        let _ = slot.value.compare_and_swap(&fill.seen, Some(stale));
1670        assert!(slot.get().is_none());
1671        assert!(!slot.get_or_fill(|| false));
1672        assert_eq!(slot.get(), Some(false));
1673    }
1674
1675    #[test]
1676    fn a_fill_does_not_replace_a_value_stored_since_it_began() {
1677        let slot = CacheSlot::empty();
1678        let slow = slot.begin_fill();
1679        let _ = slot.get_or_fill(|| 2);
1680        slot.finish_fill(slow, 1);
1681        assert_eq!(slot.get(), Some(2));
1682    }
1683}
1684
1685#[cfg(test)]
1686mod detection_context_tests {
1687    use super::*;
1688
1689    #[test]
1690    fn system_returns_same_instance() {
1691        let a = system() as *const DetectionContext;
1692        let b = system() as *const DetectionContext;
1693        assert_eq!(a, b);
1694    }
1695
1696    /// A context with every slot filled.
1697    fn filled() -> DetectionContext {
1698        let ctx = DetectionContext::new();
1699        ctx.is_dark.get_or_fill(|| true);
1700        ctx.reduced_motion.get_or_fill(|| true);
1701        ctx.reader_accessibility
1702            .get_or_fill(crate::AccessibilityPreferences::default);
1703        let _ = ctx.icon_theme.get_or_fill(|| Ok("breeze".to_string()));
1704        #[cfg(target_os = "linux")]
1705        ctx.linux_desktop.get_or_fill(|| LinuxDesktop::Kde);
1706        #[cfg(target_os = "linux")]
1707        ctx.refined_linux_desktop.get_or_fill(|| RefinedDesktop {
1708            desktop: LinuxDesktop::Kde,
1709            by_kdeglobals: false,
1710        });
1711        ctx.font_dpi.get_or_fill(|| 120.0);
1712        ctx
1713    }
1714
1715    /// `invalidate_all` empties every slot. The pattern names each field, so
1716    /// a slot added to [`DetectionContext`] does not compile until it is
1717    /// checked here.
1718    #[test]
1719    fn invalidate_all_empties_every_slot() {
1720        let ctx = filled();
1721        ctx.invalidate_all();
1722        let DetectionContext {
1723            is_dark,
1724            reduced_motion,
1725            reader_accessibility,
1726            icon_theme,
1727            #[cfg(target_os = "linux")]
1728            linux_desktop,
1729            #[cfg(target_os = "linux")]
1730            refined_linux_desktop,
1731            font_dpi,
1732        } = &ctx;
1733        assert!(is_dark.get().is_none(), "is_dark");
1734        assert!(reduced_motion.get().is_none(), "reduced_motion");
1735        assert!(reader_accessibility.get().is_none(), "reader_accessibility");
1736        assert!(icon_theme.get().is_none(), "icon_theme");
1737        #[cfg(target_os = "linux")]
1738        assert!(linux_desktop.get().is_none(), "linux_desktop");
1739        #[cfg(target_os = "linux")]
1740        assert!(
1741            refined_linux_desktop.get().is_none(),
1742            "refined_linux_desktop"
1743        );
1744        assert!(font_dpi.get().is_none(), "font_dpi");
1745    }
1746
1747    #[test]
1748    fn invalidate_is_dark_empties_only_is_dark() {
1749        let ctx = filled();
1750        ctx.invalidate_is_dark();
1751        assert_eq!(ctx.is_dark.get(), None);
1752        assert_eq!(ctx.font_dpi.get(), Some(120.0));
1753    }
1754
1755    #[test]
1756    fn font_dpi_is_cached_until_invalidate_all() {
1757        let ctx = DetectionContext::new();
1758        let runs = std::cell::Cell::new(0);
1759        let detect = |dpi| {
1760            runs.set(runs.get() + 1);
1761            dpi
1762        };
1763        assert_eq!(ctx.font_dpi_with(|| detect(120.0)), 120.0);
1764        assert_eq!(ctx.font_dpi_with(|| detect(96.0)), 120.0);
1765        assert_eq!(runs.get(), 1, "a cached font DPI was detected again");
1766        ctx.invalidate_all();
1767        assert_eq!(ctx.font_dpi_with(|| detect(96.0)), 96.0);
1768        assert_eq!(runs.get(), 2);
1769    }
1770
1771    fn undetected() -> Result<String, IconThemeFailure> {
1772        Err(IconThemeFailure::for_tests("the test's failing detection"))
1773    }
1774
1775    #[test]
1776    fn a_failed_icon_theme_detection_is_cached_and_reported() {
1777        let ctx = DetectionContext::new();
1778        let runs = std::cell::Cell::new(0);
1779        let detect = || {
1780            runs.set(runs.get() + 1);
1781            undetected()
1782        };
1783        let first = ctx.icon_theme_with(detect);
1784        let second = ctx.icon_theme_with(detect);
1785        assert_eq!(runs.get(), 1, "a failed detection ran again");
1786        for outcome in [first, second] {
1787            match outcome {
1788                Ok(name) => panic!("a failed detection gave the theme {name}"),
1789                Err(e) => assert!(
1790                    e.to_string().contains("the test's failing detection"),
1791                    "got: {e}"
1792                ),
1793            }
1794        }
1795    }
1796
1797    #[test]
1798    fn invalidate_icon_theme_clears_a_cached_failure() {
1799        let ctx = DetectionContext::new();
1800        assert!(ctx.icon_theme_with(undetected).is_err());
1801        ctx.invalidate_icon_theme();
1802        let theme = ctx.icon_theme_with(|| Ok("breeze".to_string()));
1803        assert_eq!(theme.ok().as_deref(), Some("breeze"));
1804    }
1805
1806    #[test]
1807    fn invalidate_all_clears_a_cached_failure() {
1808        let ctx = DetectionContext::new();
1809        assert!(ctx.icon_theme_with(undetected).is_err());
1810        ctx.invalidate_all();
1811        let theme = ctx.icon_theme_with(|| Ok("breeze".to_string()));
1812        assert_eq!(theme.ok().as_deref(), Some("breeze"));
1813    }
1814
1815    fn scaled_by(text_scaling_factor: f32) -> crate::AccessibilityPreferences {
1816        crate::AccessibilityPreferences {
1817            text_scaling_factor,
1818            ..crate::AccessibilityPreferences::default()
1819        }
1820    }
1821
1822    #[test]
1823    fn a_second_accessibility_read_does_not_run_the_reader() {
1824        let ctx = DetectionContext::new();
1825        let runs = std::cell::Cell::new(0);
1826        let read = || {
1827            runs.set(runs.get() + 1);
1828            scaled_by(1.5)
1829        };
1830        assert_eq!(ctx.reader_accessibility_with(read), scaled_by(1.5));
1831        assert_eq!(ctx.reader_accessibility_with(read), scaled_by(1.5));
1832        assert_eq!(runs.get(), 1, "the second call ran the reader");
1833    }
1834
1835    #[test]
1836    fn a_stored_accessibility_block_is_returned_until_invalidated() {
1837        let ctx = DetectionContext::new();
1838        let runs = std::cell::Cell::new(0);
1839        let read = || {
1840            runs.set(runs.get() + 1);
1841            scaled_by(1.25)
1842        };
1843        ctx.store_reader_accessibility(ctx.begin_reader_accessibility(), scaled_by(2.0));
1844        assert_eq!(ctx.reader_accessibility_with(read), scaled_by(2.0));
1845        assert_eq!(runs.get(), 0, "a stored block ran the reader");
1846        ctx.invalidate_all();
1847        assert_eq!(ctx.reader_accessibility_with(read), scaled_by(1.25));
1848        assert_eq!(runs.get(), 1);
1849        ctx.invalidate_accessibility_preferences();
1850        assert_eq!(ctx.reader_accessibility_with(read), scaled_by(1.25));
1851        assert_eq!(runs.get(), 2);
1852    }
1853
1854    /// A font DPI detected before an invalidation that lands mid-detection
1855    /// is not cached: the next read detects again.
1856    #[test]
1857    fn a_font_dpi_detected_across_an_invalidation_is_not_cached() {
1858        let ctx = DetectionContext::new();
1859        let stale = ctx.font_dpi_with(|| {
1860            ctx.invalidate_font_dpi();
1861            120.0
1862        });
1863        assert_eq!(stale, 120.0);
1864        assert_eq!(ctx.font_dpi_with(|| 96.0), 96.0);
1865    }
1866
1867    #[test]
1868    fn an_icon_theme_detected_across_an_invalidation_is_not_cached() {
1869        let ctx = DetectionContext::new();
1870        let stale = ctx.icon_theme_with(|| {
1871            ctx.invalidate_icon_theme();
1872            Ok("breeze".to_string())
1873        });
1874        assert_eq!(stale.ok().as_deref(), Some("breeze"));
1875        let theme = ctx.icon_theme_with(|| Ok("Adwaita".to_string()));
1876        assert_eq!(theme.ok().as_deref(), Some("Adwaita"));
1877    }
1878
1879    #[test]
1880    fn an_accessibility_block_read_across_an_invalidation_is_not_cached() {
1881        let ctx = DetectionContext::new();
1882        let stale = ctx.reader_accessibility_with(|| {
1883            ctx.invalidate_all();
1884            scaled_by(1.5)
1885        });
1886        assert_eq!(stale, scaled_by(1.5));
1887        assert_eq!(
1888            ctx.reader_accessibility_with(|| scaled_by(2.0)),
1889            scaled_by(2.0)
1890        );
1891    }
1892
1893    /// A synchronous caller gets the desktop a system read refined, portal
1894    /// answer included, until it is invalidated.
1895    #[cfg(target_os = "linux")]
1896    #[test]
1897    fn the_sync_refined_desktop_is_the_cached_one() {
1898        let ctx = DetectionContext::new();
1899        let fill = ctx.refined_linux_desktop.begin_fill();
1900        let gnome = refine_desktop(LinuxDesktop::Gnome, None, || false);
1901        ctx.refined_linux_desktop.finish_fill(fill, gnome);
1902        assert_eq!(ctx.refined_linux_desktop_sync(), LinuxDesktop::Gnome);
1903        assert_eq!(pollster::block_on(ctx.refined_linux_desktop()), gnome);
1904        ctx.invalidate_linux_desktop();
1905        assert!(ctx.refined_linux_desktop.get().is_none());
1906    }
1907
1908    /// A context whose raw desktop is `Unknown` and whose system read refined
1909    /// it with `portal_backend`, `kdeglobals` absent.
1910    #[cfg(target_os = "linux")]
1911    fn refined_unknown(portal_backend: Option<LinuxDesktop>) -> DetectionContext {
1912        let ctx = DetectionContext::new();
1913        ctx.linux_desktop
1914            .finish_fill(ctx.linux_desktop.begin_fill(), LinuxDesktop::Unknown);
1915        ctx.finish_refined_desktop(
1916            ctx.refined_linux_desktop.begin_fill(),
1917            refine_desktop(LinuxDesktop::Unknown, portal_backend, || false),
1918            LinuxDesktop::Unknown,
1919        );
1920        ctx
1921    }
1922
1923    /// A font DPI, icon theme, dark mode or reduced motion read before the
1924    /// first system read came from the desktop refined without the portal; a
1925    /// portal answer that names another desktop clears them, so they are read
1926    /// again from the reader's desktop (docs/archive/todo_closed.md, *Closed
1927    /// items from Font DPI*, 'For M4: an unrecognised `XDG_CURRENT_DESKTOP`
1928    /// with a GNOME portal backend', M4-49).
1929    #[cfg(target_os = "linux")]
1930    #[test]
1931    fn a_portal_answer_that_changes_the_desktop_clears_what_was_read_from_it() {
1932        let ctx = DetectionContext::new();
1933        assert_eq!(ctx.font_dpi_with(|| 120.0), 120.0);
1934        assert_eq!(
1935            ctx.icon_theme_with(|| Ok("breeze".to_string()))
1936                .ok()
1937                .as_deref(),
1938            Some("breeze")
1939        );
1940        assert!(ctx.is_dark.get_or_fill(|| true));
1941        assert!(ctx.reduced_motion.get_or_fill(|| true));
1942
1943        let refined = refine_desktop(LinuxDesktop::Unknown, Some(LinuxDesktop::Gnome), || true);
1944        ctx.finish_refined_desktop(
1945            ctx.refined_linux_desktop.begin_fill(),
1946            refined,
1947            LinuxDesktop::Kde,
1948        );
1949        assert_eq!(ctx.refined_linux_desktop_sync(), LinuxDesktop::Gnome);
1950        assert_eq!(ctx.font_dpi_with(|| 96.0), 96.0);
1951        assert_eq!(
1952            ctx.icon_theme_with(|| Ok("Adwaita".to_string()))
1953                .ok()
1954                .as_deref(),
1955            Some("Adwaita")
1956        );
1957        assert_eq!(ctx.is_dark.get(), None);
1958        assert_eq!(ctx.reduced_motion.get(), None);
1959    }
1960
1961    /// A portal answer that names the desktop the synchronous refinement
1962    /// already gave keeps what was read from it.
1963    #[cfg(target_os = "linux")]
1964    #[test]
1965    fn a_portal_answer_that_keeps_the_desktop_keeps_what_was_read() {
1966        let ctx = DetectionContext::new();
1967        assert_eq!(ctx.font_dpi_with(|| 120.0), 120.0);
1968        let refined = refine_desktop(LinuxDesktop::Unknown, Some(LinuxDesktop::Kde), || true);
1969        ctx.finish_refined_desktop(
1970            ctx.refined_linux_desktop.begin_fill(),
1971            refined,
1972            LinuxDesktop::Kde,
1973        );
1974        assert_eq!(ctx.font_dpi_with(|| 96.0), 120.0);
1975    }
1976
1977    /// On an unrecognised desktop a system read refined to KDE, dark mode
1978    /// comes from `kdeglobals` first, as the KDE reader takes it; on one
1979    /// refined to GNOME, from gsettings first.
1980    #[cfg(target_os = "linux")]
1981    #[test]
1982    fn dark_mode_follows_the_refined_desktop() {
1983        let kde = refined_unknown(Some(LinuxDesktop::Kde));
1984        assert_eq!(
1985            desktop_is_dark(&kde, || Some(true), || Some(false)),
1986            Some(true)
1987        );
1988        let gnome = refined_unknown(Some(LinuxDesktop::Gnome));
1989        assert_eq!(
1990            desktop_is_dark(&gnome, || Some(true), || Some(false)),
1991            Some(false)
1992        );
1993        assert_eq!(desktop_is_dark(&gnome, || Some(true), || None), Some(true));
1994    }
1995}
1996
1997#[cfg(all(test, target_os = "linux"))]
1998mod refine_linux_desktop_tests {
1999    use super::*;
2000
2001    fn asked() -> bool {
2002        panic!("kdeglobals asked where the desktop is already decided")
2003    }
2004
2005    /// `XDG_CURRENT_DESKTOP` decides where it names a desktop; the portal
2006    /// backend, then `kdeglobals`, only where it names none.
2007    #[test]
2008    fn the_raw_desktop_then_the_portal_backend_then_kdeglobals() {
2009        let refine = |raw, portal_backend, kdeglobals_exists: fn() -> bool| {
2010            refine_linux_desktop(raw, portal_backend, kdeglobals_exists)
2011        };
2012        assert_eq!(
2013            refine(LinuxDesktop::Gnome, Some(LinuxDesktop::Kde), asked),
2014            LinuxDesktop::Gnome
2015        );
2016        assert_eq!(refine(LinuxDesktop::Xfce, None, asked), LinuxDesktop::Xfce);
2017        assert_eq!(
2018            refine(LinuxDesktop::Unknown, Some(LinuxDesktop::Kde), asked),
2019            LinuxDesktop::Kde
2020        );
2021        assert_eq!(
2022            refine(LinuxDesktop::Unknown, Some(LinuxDesktop::Gnome), asked),
2023            LinuxDesktop::Gnome
2024        );
2025        assert_eq!(
2026            refine(LinuxDesktop::Unknown, None, || true),
2027            LinuxDesktop::Kde
2028        );
2029        assert_eq!(
2030            refine(LinuxDesktop::Unknown, None, || false),
2031            LinuxDesktop::Unknown
2032        );
2033    }
2034}
2035
2036#[cfg(all(test, target_os = "linux"))]
2037#[allow(clippy::unwrap_used, clippy::expect_used)]
2038mod subprocess_tests {
2039    use super::*;
2040    use std::path::PathBuf;
2041    use std::time::{Duration, Instant};
2042
2043    /// The timeout of a test whose command finishes: a loaded machine never
2044    /// takes that long, where it could take `SUBPROCESS_TIMEOUT`'s 2 s, the
2045    /// readers' design value.
2046    const GENEROUS: Duration = Duration::from_secs(10);
2047
2048    /// Whether `program` is an executable file in a `$PATH` directory.
2049    fn on_path(program: &str) -> bool {
2050        std::env::var_os("PATH")
2051            .is_some_and(|path| std::env::split_paths(&path).any(|dir| dir.join(program).is_file()))
2052    }
2053
2054    #[test]
2055    fn poll_intervals_double_from_1_ms_up_to_50_ms() {
2056        let intervals: Vec<Duration> = poll_intervals().take(10).collect();
2057        let expected: Vec<Duration> = [1, 2, 4, 8, 16, 32, 50, 50, 50, 50]
2058            .into_iter()
2059            .map(Duration::from_millis)
2060            .collect();
2061        assert_eq!(intervals, expected);
2062    }
2063
2064    #[test]
2065    fn run_with_timeout_returns_stdout_of_a_successful_command() {
2066        if !on_path("echo") {
2067            eprintln!("skipped: echo is not installed");
2068            return;
2069        }
2070        let out = stdout_with_timeout("echo", &["hi"], GENEROUS);
2071        assert_eq!(out.as_deref().map(str::trim), Some("hi"));
2072    }
2073
2074    /// An unsuccessful exit is an output, with its status and its stderr;
2075    /// [`stdout_with_timeout`] gives `None` for it.
2076    #[test]
2077    fn run_with_timeout_returns_the_status_and_stderr_of_a_failing_command() {
2078        if !on_path("sh") {
2079            eprintln!("skipped: sh is not installed");
2080            return;
2081        }
2082        let output = run_with_timeout("sh", &["-c", "echo oops >&2; exit 3"], GENEROUS).unwrap();
2083        assert_eq!(output.status.code(), Some(3));
2084        assert_eq!(output.stderr, b"oops\n");
2085        assert_eq!(stdout_with_timeout("sh", &["-c", "exit 3"], GENEROUS), None);
2086    }
2087
2088    #[test]
2089    fn run_with_timeout_reports_a_missing_program_as_not_found() {
2090        let error = run_with_timeout("nt-test-no-such-program", &[], GENEROUS).unwrap_err();
2091        assert_eq!(error.kind(), std::io::ErrorKind::NotFound);
2092    }
2093
2094    /// A command that exits at once with no output gives an empty stdout;
2095    /// the time it took is printed (the schedule test is the timing proof).
2096    #[test]
2097    fn run_with_timeout_returns_the_empty_stdout_of_a_quiet_command() {
2098        if !on_path("true") {
2099            eprintln!("skipped: true is not installed");
2100            return;
2101        }
2102        let start = Instant::now();
2103        assert_eq!(
2104            stdout_with_timeout("true", &[], GENEROUS).as_deref(),
2105            Some("")
2106        );
2107        eprintln!("`true` ran in {:?}", start.elapsed());
2108    }
2109
2110    /// Whether a process runs with exactly the command line `cmdline`.
2111    fn running(cmdline: &str) -> Vec<PathBuf> {
2112        std::fs::read_dir("/proc")
2113            .unwrap()
2114            .flatten()
2115            .map(|entry| entry.path().join("cmdline"))
2116            .filter(|path| std::fs::read(path).is_ok_and(|bytes| bytes == cmdline.as_bytes()))
2117            .collect()
2118    }
2119
2120    /// A command that outlives the timeout is killed and reaped, and the
2121    /// call ends at the timeout, not when the command would have: its sleep
2122    /// is 30 s, and the 5 s bound leaves a loaded machine room to stall.
2123    #[test]
2124    fn run_with_timeout_kills_a_command_that_outlives_the_timeout() {
2125        if !on_path("sleep") {
2126            eprintln!("skipped: sleep is not installed");
2127            return;
2128        }
2129        let timeout = Duration::from_millis(100);
2130        let seconds = format!("30.{}", std::process::id());
2131        let start = Instant::now();
2132        let error = run_with_timeout("sleep", &[&seconds], timeout).unwrap_err();
2133        let elapsed = start.elapsed();
2134        assert_eq!(error.kind(), std::io::ErrorKind::TimedOut);
2135        assert_eq!(error.to_string(), "timed out after 100ms");
2136        assert!(
2137            elapsed >= timeout && elapsed < Duration::from_secs(5),
2138            "took {elapsed:?}"
2139        );
2140        let still_running = running(&format!("sleep\0{seconds}\0"));
2141        assert!(still_running.is_empty(), "not killed: {still_running:?}");
2142    }
2143
2144    /// 100 KiB is more than a Linux pipe holds (65,536 bytes, pipe(7)), so
2145    /// the command finishes only if its stdout is read while it runs.
2146    #[test]
2147    fn run_with_timeout_returns_all_of_an_output_larger_than_a_pipe() {
2148        if !on_path("sh") || !on_path("head") {
2149            eprintln!("skipped: sh or head is not installed");
2150            return;
2151        }
2152        let out = stdout_with_timeout("sh", &["-c", "head -c 102400 /dev/zero"], GENEROUS);
2153        assert_eq!(out.map(|out| out.len()), Some(102_400));
2154    }
2155
2156    /// A process the command leaves running with its stdout keeps the pipe
2157    /// open after the command exits; the call still ends at the deadline,
2158    /// not when that process exits: it sleeps 10 s, and the 5 s bound leaves
2159    /// a loaded machine room to stall.
2160    #[test]
2161    fn run_with_timeout_ends_at_the_deadline_when_a_grandchild_holds_stdout() {
2162        if !on_path("sh") || !on_path("sleep") {
2163            eprintln!("skipped: sh or sleep is not installed");
2164            return;
2165        }
2166        let script = format!("sleep 10.{} & echo hi", std::process::id());
2167        let start = Instant::now();
2168        let error =
2169            run_with_timeout("sh", &["-c", &script], Duration::from_millis(100)).unwrap_err();
2170        let elapsed = start.elapsed();
2171        assert_eq!(error.kind(), std::io::ErrorKind::TimedOut);
2172        assert!(elapsed < Duration::from_secs(5), "took {elapsed:?}");
2173    }
2174}
2175
2176#[cfg(all(test, target_os = "linux"))]
2177mod config_home_tests {
2178    use super::*;
2179    use std::ffi::OsStr;
2180    use std::path::PathBuf;
2181
2182    fn config_home(var: Option<&str>, home: Option<&str>) -> Option<PathBuf> {
2183        xdg_config_home_from(var.map(OsStr::new), home.map(OsStr::new))
2184    }
2185
2186    #[test]
2187    fn an_absolute_xdg_config_home_is_the_config_directory() {
2188        assert_eq!(
2189            config_home(Some("/tmp/cfg"), Some("/home/u")),
2190            Some(PathBuf::from("/tmp/cfg"))
2191        );
2192        assert_eq!(
2193            config_home(Some("/tmp/cfg"), None),
2194            Some(PathBuf::from("/tmp/cfg"))
2195        );
2196    }
2197
2198    /// Unset, empty and relative are each "not set" (the XDG Base Directory
2199    /// Specification ignores a relative path).
2200    #[test]
2201    fn an_unset_empty_or_relative_xdg_config_home_falls_back_to_home() {
2202        for var in [None, Some(""), Some("relative/cfg"), Some(".config")] {
2203            assert_eq!(
2204                config_home(var, Some("/home/u")),
2205                Some(PathBuf::from("/home/u/.config")),
2206                "{var:?}"
2207            );
2208        }
2209    }
2210
2211    #[test]
2212    fn without_xdg_config_home_and_home_there_is_no_config_directory() {
2213        for home in [None, Some("")] {
2214            for var in [None, Some(""), Some("relative")] {
2215                assert_eq!(config_home(var, home), None, "{var:?} {home:?}");
2216            }
2217        }
2218    }
2219}
2220
2221#[cfg(all(test, target_os = "linux", feature = "portal"))]
2222mod gnome_font_dpi_tests {
2223    use super::*;
2224
2225    /// GNOME and Budgie, the desktops the GNOME reader reads, lay fonts out at
2226    /// GNOME's 96 whatever `Xft.dpi` says; other desktops keep the chain.
2227    #[test]
2228    fn gnome_desktops_fix_the_font_dpi() {
2229        assert_eq!(desktop_font_dpi(LinuxDesktop::Gnome), Some(96.0));
2230        assert_eq!(desktop_font_dpi(LinuxDesktop::Budgie), Some(96.0));
2231        assert_eq!(desktop_font_dpi(LinuxDesktop::Kde), None);
2232        assert_eq!(desktop_font_dpi(LinuxDesktop::Unknown), None);
2233    }
2234
2235    /// An unrecognised desktop with a GNOME portal backend gets the GNOME
2236    /// reader, so the preset path takes the reader's 96, `kdeglobals` or not.
2237    #[test]
2238    fn an_unknown_desktop_with_a_gnome_portal_has_gnomes_font_dpi() {
2239        for kdeglobals in [false, true] {
2240            let desktop =
2241                refine_linux_desktop(LinuxDesktop::Unknown, Some(LinuxDesktop::Gnome), || {
2242                    kdeglobals
2243                });
2244            assert_eq!(desktop_font_dpi(desktop), Some(GNOME_FONT_DPI));
2245            assert_eq!(GNOME_FONT_DPI, 96.0);
2246        }
2247    }
2248}