Skip to main content

native_theme/
detect.rs

1//! OS detection: dark mode, reduced motion, DPI, desktop environment.
2
3use arc_swap::ArcSwapOption;
4use std::sync::Arc;
5
6/// Timeout for subprocess commands (gsettings, xrdb, xrandr).
7///
8/// Prevents D-Bus-dependent tools from blocking indefinitely when the
9/// session bus is unresponsive or the display server is unavailable.
10#[cfg(target_os = "linux")]
11const SUBPROCESS_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
12
13/// Desktop environments recognized on Linux.
14#[cfg(target_os = "linux")]
15#[non_exhaustive]
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
17pub enum LinuxDesktop {
18    /// KDE Plasma desktop.
19    Kde,
20    /// GNOME desktop.
21    Gnome,
22    /// Xfce desktop.
23    Xfce,
24    /// Cinnamon desktop (Linux Mint).
25    Cinnamon,
26    /// MATE desktop.
27    Mate,
28    /// LXQt desktop.
29    LxQt,
30    /// Budgie desktop.
31    Budgie,
32    /// Hyprland Wayland compositor.
33    Hyprland,
34    /// Sway Wayland compositor (i3-compatible).
35    Sway,
36    /// River Wayland compositor.
37    River,
38    /// Niri scrollable Wayland compositor.
39    Niri,
40    /// Wayfire scene-graph Wayland compositor (wlroots-based).
41    Wayfire,
42    /// COSMIC desktop environment (System76).
43    CosmicDe,
44    /// Unrecognized or unset desktop environment.
45    Unknown,
46}
47
48/// Read the `XDG_CURRENT_DESKTOP` environment variable, returning an
49/// empty string if unset or invalid UTF-8.
50#[cfg(target_os = "linux")]
51pub(crate) fn xdg_current_desktop() -> String {
52    std::env::var("XDG_CURRENT_DESKTOP").unwrap_or_default()
53}
54
55/// Detect the current Linux desktop environment.
56///
57/// Reads `XDG_CURRENT_DESKTOP` and returns the recognized desktop.
58/// Returns [`LinuxDesktop::Unknown`] if the variable is unset or
59/// contains no recognized value.
60///
61/// For testable parsing without environment access, use the
62/// `pub` [`parse_linux_desktop()`] function instead.
63///
64/// # Examples
65///
66/// ```no_run
67/// use native_theme::detect::{detect_linux_desktop, LinuxDesktop};
68///
69/// let de = detect_linux_desktop();
70/// match de {
71///     LinuxDesktop::Kde => println!("KDE Plasma"),
72///     LinuxDesktop::Gnome => println!("GNOME"),
73///     _ => println!("Other: {de:?}"),
74/// }
75/// ```
76#[cfg(target_os = "linux")]
77#[must_use]
78pub fn detect_linux_desktop() -> LinuxDesktop {
79    parse_linux_desktop(&xdg_current_desktop())
80}
81
82/// Parse `XDG_CURRENT_DESKTOP` (a colon-separated list) and return
83/// the recognized desktop environment.
84///
85/// Checks components in order; first recognized DE wins. Budgie is checked
86/// before GNOME because Budgie sets `Budgie:GNOME`.
87#[cfg(target_os = "linux")]
88#[must_use]
89pub fn parse_linux_desktop(xdg_current_desktop: &str) -> LinuxDesktop {
90    for component in xdg_current_desktop.split(':') {
91        match component {
92            "KDE" => return LinuxDesktop::Kde,
93            "Budgie" => return LinuxDesktop::Budgie,
94            "GNOME" => return LinuxDesktop::Gnome,
95            "XFCE" => return LinuxDesktop::Xfce,
96            "X-Cinnamon" | "Cinnamon" => return LinuxDesktop::Cinnamon,
97            "MATE" => return LinuxDesktop::Mate,
98            "LXQt" => return LinuxDesktop::LxQt,
99            "Hyprland" => return LinuxDesktop::Hyprland,
100            "sway" => return LinuxDesktop::Sway,
101            "river" => return LinuxDesktop::River,
102            "niri" => return LinuxDesktop::Niri,
103            "Wayfire" => return LinuxDesktop::Wayfire,
104            "COSMIC" => return LinuxDesktop::CosmicDe,
105            _ => {}
106        }
107    }
108    LinuxDesktop::Unknown
109}
110
111/// Detect whether the system is using a dark color scheme.
112///
113/// Uses synchronous, platform-specific checks so the result is available
114/// immediately at window creation time (before any async portal response).
115///
116/// # Caching
117///
118/// The result is cached after the first call and reused on subsequent calls.
119/// Call [`invalidate_caches()`] to clear the cached value so the next call
120/// re-queries the OS. For a fresh reading without affecting the cache, use
121/// [`detect_is_dark()`] instead.
122///
123/// For live dark-mode tracking, use `watch::on_theme_change` (feature
124/// `watch`): on each event call [`invalidate_caches()`] and re-read
125/// [`crate::SystemTheme::from_system()`].
126///
127/// # Platform Behavior
128///
129/// - **Linux:** Checks `GTK_THEME` for `:dark` or `-dark`; on KDE (with the
130///   `kde` feature) reads `kdeglobals`' background luminance; then
131///   `gsettings` `color-scheme` (2-second timeout); then `kdeglobals` on
132///   other desktops (with `kde`); finally `gtk-3.0/settings.ini`
133///   `gtk-application-prefer-dark-theme`.
134/// - **macOS:** Reads `AppleInterfaceStyle` via `NSUserDefaults` (with
135///   `macos` feature) or `defaults` subprocess (without).
136/// - **Windows:** Checks foreground color luminance from `UISettings` via
137///   BT.601 coefficients (requires `windows` feature).
138/// - **Other platforms / missing features:** Returns `false` (light).
139#[must_use]
140pub fn system_is_dark() -> bool {
141    system().is_dark()
142}
143
144/// Reset all process-wide caches so the next call to [`system_is_dark()`],
145/// [`prefers_reduced_motion()`], or
146/// [`system_icon_theme()`](crate::theme::system_icon_theme) re-queries the OS; a
147/// cached failure to detect the icon theme is cleared too.
148///
149/// Call this when you detect that the user has changed system settings (e.g.,
150/// dark mode toggle, icon theme switch, accessibility preferences).
151///
152/// The `detect_*()` family of functions are unaffected — they always query
153/// the OS directly.
154pub fn invalidate_caches() {
155    system().invalidate_all();
156}
157
158/// Detect whether the system is using a dark color scheme without caching.
159///
160/// Unlike [`system_is_dark()`], this function queries the OS every time it is
161/// called and never caches the result. Use this when polling for theme changes
162/// or implementing live dark-mode tracking.
163///
164/// See [`system_is_dark()`] for platform behavior details.
165#[must_use]
166pub fn detect_is_dark() -> bool {
167    detect_is_dark_inner()
168}
169
170/// The longest pause between two polls of a running command.
171#[cfg(target_os = "linux")]
172const POLL_INTERVAL_CAP: std::time::Duration = std::time::Duration::from_millis(50);
173
174/// The pauses between polls of a running command: 1 ms, doubling up to
175/// [`POLL_INTERVAL_CAP`], so a command that exits in a few milliseconds is
176/// seen to exit within a few milliseconds, and a slow one costs a poll per
177/// 50 ms.
178#[cfg(target_os = "linux")]
179fn poll_intervals() -> impl Iterator<Item = std::time::Duration> {
180    std::iter::successors(Some(std::time::Duration::from_millis(1)), |pause| {
181        Some(pause.saturating_mul(2).min(POLL_INTERVAL_CAP))
182    })
183}
184
185/// Run `program` with `args`, waiting up to `timeout` for it to exit.
186///
187/// Returns its stdout when it exits successfully; `None` when it cannot be
188/// spawned, exits unsuccessfully or outlives `timeout`, in which case it
189/// is killed. The command is polled at [`poll_intervals`]. A killed command
190/// is reaped; one the kill fails on is left unreaped rather than waited
191/// for, so `timeout` stays a bound on the call.
192#[cfg(target_os = "linux")]
193fn run_with_timeout(program: &str, args: &[&str], timeout: std::time::Duration) -> Option<String> {
194    use std::io::Read;
195    use std::time::Instant;
196
197    let start = Instant::now();
198    let mut child = std::process::Command::new(program)
199        .args(args)
200        .stdout(std::process::Stdio::piped())
201        .stderr(std::process::Stdio::null())
202        .spawn()
203        .ok()?;
204
205    let mut intervals = poll_intervals();
206    loop {
207        match child.try_wait() {
208            Ok(Some(status)) if status.success() => {
209                let mut buf = String::new();
210                if let Some(mut stdout) = child.stdout.take() {
211                    let _ = stdout.read_to_string(&mut buf);
212                }
213                return Some(buf);
214            }
215            Ok(Some(_)) => return None,
216            Ok(None) => {
217                let elapsed = start.elapsed();
218                if elapsed >= timeout {
219                    if child.kill().is_ok() {
220                        let _ = child.wait();
221                    }
222                    return None;
223                }
224                let pause = intervals.next().unwrap_or(POLL_INTERVAL_CAP);
225                std::thread::sleep(pause.min(timeout.saturating_sub(elapsed)));
226            }
227            Err(_) => return None,
228        }
229    }
230}
231
232/// Run a gsettings command with a 2-second timeout.
233///
234/// Spawns `gsettings` with the given arguments, waits up to 2 seconds
235/// for completion, and returns the trimmed stdout on success.  Returns
236/// `None` if the command fails, times out, or produces empty output.
237///
238/// Used by [`detect_is_dark_inner()`] and [`crate::gnome::read_gsetting()`] to
239/// prevent gsettings from blocking indefinitely when D-Bus is unresponsive.
240#[cfg(target_os = "linux")]
241fn run_gsettings_with_timeout(args: &[&str]) -> Option<String> {
242    let out = run_with_timeout("gsettings", args, SUBPROCESS_TIMEOUT)?;
243    let trimmed = out.trim();
244    if trimmed.is_empty() {
245        None
246    } else {
247        Some(trimmed.to_string())
248    }
249}
250
251/// Read `Xft.dpi` from X resources via `xrdb -query`.
252///
253/// Returns `None` if xrdb is not installed, times out (2 seconds),
254/// or the output does not contain a valid positive `Xft.dpi` value.
255#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
256fn read_xft_dpi() -> Option<f32> {
257    let out = run_with_timeout("xrdb", &["-query"], SUBPROCESS_TIMEOUT)?;
258    // Parse "Xft.dpi:\t96" from multi-line output
259    for line in out.lines() {
260        if let Some(rest) = line.strip_prefix("Xft.dpi:")
261            && let Ok(dpi) = rest.trim().parse::<f32>()
262            && dpi > 0.0
263        {
264            return Some(dpi);
265        }
266    }
267    None
268}
269
270/// Detect physical DPI from display hardware via `xrandr`.
271///
272/// Parses the primary connected output's resolution and physical dimensions
273/// to compute DPI. Falls back to the first connected output if no primary
274/// is found. Returns `None` if `xrandr` is unavailable, times out (2 seconds),
275/// or the output cannot be parsed.
276///
277/// This is a last-resort fallback: prefer `forceFontDPI` (KDE), `Xft.dpi`
278/// (X resources) before calling this.
279#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
280fn detect_physical_dpi() -> Option<f32> {
281    let out = run_with_timeout("xrandr", &[], SUBPROCESS_TIMEOUT)?;
282    parse_xrandr_dpi(&out)
283}
284
285/// Parse DPI from xrandr output.
286///
287/// Looks for lines like:
288/// ```text
289/// DP-1 connected primary 3840x2160+0+0 (...) 700mm x 390mm
290/// ```
291/// Extracts the current resolution from the mode string and the physical
292/// dimensions from the trailing `NNNmm x NNNmm`, then computes average DPI.
293#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
294fn parse_xrandr_dpi(output: &str) -> Option<f32> {
295    // Prefer the primary output; fall back to the first connected output.
296    let line = output
297        .lines()
298        .find(|l| l.contains(" connected") && l.contains("primary"))
299        .or_else(|| {
300            output
301                .lines()
302                .find(|l| l.contains(" connected") && !l.contains("disconnected"))
303        })?;
304
305    // Resolution: "3840x2160+0+0" (digits x digits + offset)
306    let res_token = line
307        .split_whitespace()
308        .find(|s| s.contains('x') && s.contains('+'))?;
309    let (w_str, rest) = res_token.split_once('x')?;
310    let h_str = rest.split('+').next()?;
311    let w_px: f32 = w_str.parse().ok()?;
312    let h_px: f32 = h_str.parse().ok()?;
313
314    // Physical size: "700mm x 390mm" at the end of the line
315    let words: Vec<&str> = line.split_whitespace().collect();
316    let mut w_mm = None;
317    let mut h_mm = None;
318    for window in words.windows(3) {
319        let [prev, cur, next] = window else { continue };
320        if *cur == "x" {
321            w_mm = prev.strip_suffix("mm").and_then(|n| n.parse::<f32>().ok());
322            h_mm = next.strip_suffix("mm").and_then(|n| n.parse::<f32>().ok());
323        }
324    }
325    let w_mm = w_mm.filter(|&v| v > 0.0)?;
326    let h_mm = h_mm.filter(|&v| v > 0.0)?;
327
328    let h_dpi = w_px / (w_mm / 25.4);
329    let v_dpi = h_px / (h_mm / 25.4);
330    let avg = (h_dpi + v_dpi) / 2.0;
331
332    if avg > 0.0 { Some(avg) } else { None }
333}
334
335#[cfg(all(test, target_os = "linux", any(feature = "kde", feature = "portal")))]
336#[allow(clippy::unwrap_used)]
337mod xrandr_dpi_tests {
338    use super::parse_xrandr_dpi;
339
340    #[test]
341    fn primary_4k_display() {
342        // Real xrandr output: 4K display at 700mm wide
343        let output = "Screen 0: minimum 16 x 16, current 3840 x 2160, maximum 32767 x 32767\n\
344                       DP-1 connected primary 3840x2160+0+0 (normal left inverted right x axis y axis) 700mm x 390mm\n\
345                          3840x2160     60.00*+\n";
346        let dpi = parse_xrandr_dpi(output).unwrap();
347        // 3840/(700/25.4) = 139.3, 2160/(390/25.4) = 140.7, avg ~140
348        assert!((dpi - 140.0).abs() < 1.0, "expected ~140 DPI, got {dpi}");
349    }
350
351    #[test]
352    fn standard_1080p_display() {
353        let output = "DP-2 connected primary 1920x1080+0+0 (normal) 530mm x 300mm\n";
354        let dpi = parse_xrandr_dpi(output).unwrap();
355        // 1920/(530/25.4) = 92.0, 1080/(300/25.4) = 91.4, avg ~91.7
356        assert!((dpi - 92.0).abs() < 1.0, "expected ~92 DPI, got {dpi}");
357    }
358
359    #[test]
360    fn no_primary_falls_back_to_first_connected() {
361        let output = "HDMI-1 connected 1920x1080+0+0 (normal) 480mm x 270mm\n\
362                       DP-1 disconnected\n";
363        let dpi = parse_xrandr_dpi(output).unwrap();
364        assert!(dpi > 90.0 && dpi < 110.0, "expected ~100 DPI, got {dpi}");
365    }
366
367    #[test]
368    fn disconnected_only_returns_none() {
369        let output = "DP-1 disconnected\nHDMI-1 disconnected\n";
370        assert!(parse_xrandr_dpi(output).is_none());
371    }
372
373    #[test]
374    fn missing_physical_dimensions_returns_none() {
375        // No "NNNmm x NNNmm" in the line
376        let output = "DP-1 connected primary 1920x1080+0+0 (normal)\n";
377        assert!(parse_xrandr_dpi(output).is_none());
378    }
379
380    #[test]
381    fn zero_mm_returns_none() {
382        let output = "DP-1 connected primary 1920x1080+0+0 (normal) 0mm x 0mm\n";
383        assert!(parse_xrandr_dpi(output).is_none());
384    }
385
386    #[test]
387    fn empty_output_returns_none() {
388        assert!(parse_xrandr_dpi("").is_none());
389    }
390}
391
392/// Detect the font DPI for the current system.
393///
394/// Used by [`ThemeMode::into_resolved()`] as a fallback when no OS reader
395/// has provided `font_dpi`. Returns the platform-appropriate DPI for
396/// converting typographic points to logical pixels.
397///
398/// - **Linux, `kde` feature** (any desktop): `forceFontDPI` → `Xft.dpi` → xrandr → 96.0
399/// - **Linux, `portal` feature without `kde`**: `Xft.dpi` → xrandr → 96.0; neither: 96.0
400/// - **macOS**: 72.0 (Apple coordinate system: 1pt = 1px)
401/// - **Windows**: 96.0, the Windows reader's `font_dpi`: a point is 96/72
402///   logical (effective) pixels at any display scale
403/// - **Other**: 96.0
404#[allow(unreachable_code)]
405fn detect_system_font_dpi() -> f32 {
406    #[cfg(target_os = "macos")]
407    {
408        return 72.0;
409    }
410
411    #[cfg(all(target_os = "windows", feature = "windows"))]
412    {
413        return crate::windows::LOGICAL_DPI as f32;
414    }
415
416    // KDE: check forceFontDPI first (same chain as the KDE reader)
417    #[cfg(all(target_os = "linux", feature = "kde"))]
418    {
419        if let Some(dpi) = read_kde_force_font_dpi() {
420            return dpi;
421        }
422    }
423
424    #[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
425    {
426        if let Some(dpi) = read_xft_dpi() {
427            return dpi;
428        }
429        if let Some(dpi) = detect_physical_dpi() {
430            return dpi;
431        }
432    }
433
434    96.0
435}
436
437/// Read KDE's `forceFontDPI` from kdeglobals or kcmfontsrc.
438///
439/// This mirrors the first step of [`crate::kde::detect_font_dpi()`] so that
440/// standalone preset loading (via [`ThemeMode::into_resolved()`]) uses the
441/// same DPI as the full KDE reader pipeline.
442#[cfg(all(target_os = "linux", feature = "kde"))]
443fn read_kde_force_font_dpi() -> Option<f32> {
444    // Try kdeglobals [General] forceFontDPI
445    let path = crate::kde::kdeglobals_path();
446    if let Ok(content) = std::fs::read_to_string(&path) {
447        let mut ini = crate::kde::create_kde_parser();
448        if ini.read(content).is_ok()
449            && let Some(dpi_str) = ini.get("General", "forceFontDPI")
450            && let Ok(dpi) = dpi_str.trim().parse::<f32>()
451            && dpi > 0.0
452        {
453            return Some(dpi);
454        }
455    }
456    // Try kcmfontsrc [General] forceFontDPI
457    if let Some(dpi_str) = crate::kde::read_kcmfontsrc_key("General", "forceFontDPI")
458        && let Ok(dpi) = dpi_str.trim().parse::<f32>()
459        && dpi > 0.0
460    {
461        return Some(dpi);
462    }
463    None
464}
465
466/// Inner detection logic for [`system_is_dark()`].
467///
468/// Separated from the public function to allow caching.
469#[allow(unreachable_code)]
470fn detect_is_dark_inner() -> bool {
471    #[cfg(target_os = "linux")]
472    {
473        // Check GTK_THEME env var (works across all GTK-based DEs)
474        if let Ok(gtk_theme) = std::env::var("GTK_THEME") {
475            let lower = gtk_theme.to_lowercase();
476            if lower.ends_with(":dark") || lower.contains("-dark") {
477                return true;
478            }
479        }
480
481        // On KDE, read kdeglobals directly — gsettings color-scheme is
482        // synced by xdg-desktop-portal-kde and can be stale or inverted.
483        #[cfg(feature = "kde")]
484        {
485            let de = parse_linux_desktop(&xdg_current_desktop());
486            if matches!(de, LinuxDesktop::Kde) {
487                let path = crate::kde::kdeglobals_path();
488                if let Ok(content) = std::fs::read_to_string(&path) {
489                    let mut ini = crate::kde::create_kde_parser();
490                    if ini.read(content).is_ok() {
491                        return crate::kde::is_dark_theme(&ini);
492                    }
493                }
494            }
495        }
496
497        // gsettings color-scheme (reliable on GNOME / GTK-based DEs)
498        if let Some(val) =
499            run_gsettings_with_timeout(&["get", "org.gnome.desktop.interface", "color-scheme"])
500        {
501            if val.contains("prefer-dark") {
502                return true;
503            }
504            if val.contains("prefer-light") || val.contains("default") {
505                return false;
506            }
507        }
508
509        // Fallback: read KDE's kdeglobals background luminance (non-KDE DE
510        // or when the KDE feature is disabled and the gsettings check above
511        // returned no result).
512        #[cfg(feature = "kde")]
513        {
514            let path = crate::kde::kdeglobals_path();
515            if let Ok(content) = std::fs::read_to_string(&path) {
516                let mut ini = crate::kde::create_kde_parser();
517                if ini.read(content).is_ok() {
518                    return crate::kde::is_dark_theme(&ini);
519                }
520            }
521        }
522
523        // Fallback: gtk-3.0/settings.ini for DEs that set the GTK dark preference
524        let config_home = std::env::var("XDG_CONFIG_HOME").unwrap_or_else(|_| {
525            let home = std::env::var("HOME").unwrap_or_default();
526            format!("{home}/.config")
527        });
528        let ini_path = format!("{config_home}/gtk-3.0/settings.ini");
529        if let Ok(content) = std::fs::read_to_string(&ini_path) {
530            for line in content.lines() {
531                let trimmed = line.trim();
532                if trimmed.starts_with("gtk-application-prefer-dark-theme")
533                    && let Some(val) = trimmed.split('=').nth(1)
534                    && (val.trim() == "1" || val.trim().eq_ignore_ascii_case("true"))
535                {
536                    return true;
537                }
538            }
539        }
540
541        false
542    }
543
544    #[cfg(target_os = "macos")]
545    {
546        // AppleInterfaceStyle is "Dark" when dark mode is active.
547        // The key is absent in light mode, so any failure means light.
548        #[cfg(feature = "macos")]
549        {
550            use objc2_foundation::NSUserDefaults;
551            let defaults = NSUserDefaults::standardUserDefaults();
552            let key = objc2_foundation::ns_string!("AppleInterfaceStyle");
553            if let Some(value) = defaults.stringForKey(key) {
554                return value.to_string().eq_ignore_ascii_case("dark");
555            }
556            return false;
557        }
558        #[cfg(not(feature = "macos"))]
559        {
560            if let Ok(output) = std::process::Command::new("defaults")
561                .args(["read", "-g", "AppleInterfaceStyle"])
562                .output()
563                && output.status.success()
564            {
565                let val = String::from_utf8_lossy(&output.stdout);
566                return val.trim().eq_ignore_ascii_case("dark");
567            }
568            return false;
569        }
570    }
571
572    #[cfg(target_os = "windows")]
573    {
574        #[cfg(feature = "windows")]
575        {
576            // BT.601 luminance: light foreground indicates dark background.
577            let Ok(settings) = ::windows::UI::ViewManagement::UISettings::new() else {
578                return false;
579            };
580            let Ok(fg) =
581                settings.GetColorValue(::windows::UI::ViewManagement::UIColorType::Foreground)
582            else {
583                return false;
584            };
585            let luma = 0.299 * (fg.R as f32) + 0.587 * (fg.G as f32) + 0.114 * (fg.B as f32);
586            return luma > 128.0;
587        }
588        #[cfg(not(feature = "windows"))]
589        return false;
590    }
591
592    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
593    {
594        false
595    }
596}
597
598/// Query whether the user prefers reduced motion.
599///
600/// Returns `true` when the OS accessibility setting indicates animations
601/// should be reduced or disabled. Returns `false` (allow animations) on
602/// unsupported platforms or when the query fails.
603///
604/// # Caching
605///
606/// The result is cached after the first call and reused on subsequent calls.
607/// Call [`invalidate_caches()`] to clear the cached value so the next call
608/// re-queries the OS. For live accessibility-change tracking, subscribe to
609/// OS accessibility events and call `invalidate_caches()` when notified.
610///
611/// # Platform Behavior
612///
613/// - **Linux:** Queries `gsettings get org.gnome.desktop.interface enable-animations`.
614///   Returns `true` when animations are disabled (`enable-animations` is `false`).
615/// - **macOS:** Queries `NSWorkspace.accessibilityDisplayShouldReduceMotion`
616///   (requires `macos` feature).
617/// - **Windows:** Queries `UISettings.AnimationsEnabled()` (requires `windows` feature).
618/// - **Other platforms:** Returns `false`.
619///
620/// # Examples
621///
622/// ```
623/// let reduced = native_theme::detect::prefers_reduced_motion();
624/// // On this platform, the result depends on OS accessibility settings.
625/// // The function always returns a bool (false on unsupported platforms).
626/// assert!(reduced == true || reduced == false);
627/// ```
628#[must_use]
629pub fn prefers_reduced_motion() -> bool {
630    system().prefers_reduced_motion()
631}
632
633/// Detect whether the user prefers reduced motion without caching.
634///
635/// Unlike [`prefers_reduced_motion()`], this function queries the OS every time
636/// it is called and never caches the result. Use this when polling for
637/// accessibility preference changes.
638///
639/// See [`prefers_reduced_motion()`] for platform behavior details.
640#[must_use]
641pub fn detect_reduced_motion() -> bool {
642    detect_reduced_motion_inner()
643}
644
645/// Inner detection logic for [`prefers_reduced_motion()`].
646///
647/// Separated from the public function to allow caching.
648#[allow(unreachable_code)]
649fn detect_reduced_motion_inner() -> bool {
650    #[cfg(target_os = "linux")]
651    {
652        // gsettings boolean output is bare "true\n" or "false\n" (no quotes)
653        // enable-animations has INVERTED semantics: false => reduced motion preferred
654        if let Some(val) =
655            run_gsettings_with_timeout(&["get", "org.gnome.desktop.interface", "enable-animations"])
656        {
657            return val.trim() == "false";
658        }
659        false
660    }
661
662    #[cfg(target_os = "macos")]
663    {
664        #[cfg(feature = "macos")]
665        {
666            let workspace = objc2_app_kit::NSWorkspace::sharedWorkspace();
667            // Direct semantics: true = reduce motion preferred (no inversion needed)
668            return workspace.accessibilityDisplayShouldReduceMotion();
669        }
670        #[cfg(not(feature = "macos"))]
671        return false;
672    }
673
674    #[cfg(target_os = "windows")]
675    {
676        #[cfg(feature = "windows")]
677        {
678            let Ok(settings) = ::windows::UI::ViewManagement::UISettings::new() else {
679                return false;
680            };
681            // AnimationsEnabled has INVERTED semantics: false => reduced motion preferred
682            return match settings.AnimationsEnabled() {
683                Ok(enabled) => !enabled,
684                Err(_) => false,
685            };
686        }
687        #[cfg(not(feature = "windows"))]
688        return false;
689    }
690
691    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
692    {
693        false
694    }
695}
696
697// === DetectionContext ===
698
699/// Process-wide detection cache.
700///
701/// Provides "cache on first read" semantics for OS detection queries
702/// (`is_dark`, `reduced_motion`, `icon_theme`, `linux_desktop`) and
703/// per-field invalidation for watchers that need fresh data.
704///
705/// Obtain the process-wide instance via [`system()`].
706///
707/// # Thread Safety
708///
709/// All reads and invalidations are lock-free (backed by
710/// [`arc_swap::ArcSwapOption`]).
711pub struct DetectionContext {
712    is_dark: ArcSwapOption<bool>,
713    reduced_motion: ArcSwapOption<bool>,
714    icon_theme: ArcSwapOption<Result<String, crate::model::icons::IconThemeFailure>>,
715    #[cfg(target_os = "linux")]
716    linux_desktop: ArcSwapOption<LinuxDesktop>,
717}
718
719impl DetectionContext {
720    /// Create an empty context with no cached values.
721    fn new() -> Self {
722        Self {
723            is_dark: ArcSwapOption::empty(),
724            reduced_motion: ArcSwapOption::empty(),
725            icon_theme: ArcSwapOption::empty(),
726            #[cfg(target_os = "linux")]
727            linux_desktop: ArcSwapOption::empty(),
728        }
729    }
730
731    /// Whether the system is using a dark color scheme (cached).
732    ///
733    /// The first call queries the OS and caches the result.
734    /// Subsequent calls return the cached value.
735    /// Call [`invalidate_is_dark()`](Self::invalidate_is_dark) to
736    /// force a re-read on the next call.
737    #[must_use]
738    pub fn is_dark(&self) -> bool {
739        if let Some(v) = self.is_dark.load().as_deref() {
740            return *v;
741        }
742        let value = detect_is_dark_inner();
743        self.is_dark.store(Some(Arc::new(value)));
744        value
745    }
746
747    /// Whether the user prefers reduced motion (cached).
748    ///
749    /// The first call queries the OS and caches the result.
750    /// Call [`invalidate_reduced_motion()`](Self::invalidate_reduced_motion)
751    /// to force a re-read.
752    #[must_use]
753    pub fn prefers_reduced_motion(&self) -> bool {
754        if let Some(v) = self.reduced_motion.load().as_deref() {
755            return *v;
756        }
757        let value = detect_reduced_motion_inner();
758        self.reduced_motion.store(Some(Arc::new(value)));
759        value
760    }
761
762    /// The current icon theme name (cached), or why none was detected.
763    ///
764    /// The first call detects the theme from the OS and caches the
765    /// outcome, a failure included, so a failed detection is not
766    /// repeated on every call; subsequent calls return the cached
767    /// outcome. Call
768    /// [`invalidate_icon_theme()`](Self::invalidate_icon_theme) to
769    /// force a re-read.
770    ///
771    /// # Errors
772    ///
773    /// As [`system_icon_theme()`](crate::theme::system_icon_theme): no
774    /// theme stands in for one that could not be detected.
775    pub fn icon_theme(&self) -> crate::Result<String> {
776        self.icon_theme_with(detect_icon_theme_inner)
777    }
778
779    /// [`icon_theme()`](Self::icon_theme), with `detect` run where
780    /// nothing is cached.
781    fn icon_theme_with(
782        &self,
783        detect: impl FnOnce() -> Result<String, crate::model::icons::IconThemeFailure>,
784    ) -> crate::Result<String> {
785        let outcome = match self.icon_theme.load_full() {
786            Some(cached) => cached,
787            None => {
788                let detected = Arc::new(detect());
789                self.icon_theme.store(Some(Arc::clone(&detected)));
790                detected
791            }
792        };
793        match outcome.as_ref() {
794            Ok(theme) => Ok(theme.clone()),
795            Err(failure) => Err(failure.to_error()),
796        }
797    }
798
799    /// The current Linux desktop environment (cached).
800    ///
801    /// The first call reads `XDG_CURRENT_DESKTOP` and caches the
802    /// result. Call
803    /// [`invalidate_linux_desktop()`](Self::invalidate_linux_desktop)
804    /// to force a re-read.
805    #[cfg(target_os = "linux")]
806    #[must_use]
807    pub fn linux_desktop(&self) -> LinuxDesktop {
808        if let Some(v) = self.linux_desktop.load().as_deref() {
809            return *v;
810        }
811        let value = detect_linux_desktop();
812        self.linux_desktop.store(Some(Arc::new(value)));
813        value
814    }
815
816    /// Clear the cached dark-mode value.
817    pub fn invalidate_is_dark(&self) {
818        self.is_dark.store(None);
819    }
820
821    /// Clear the cached reduced-motion value.
822    pub fn invalidate_reduced_motion(&self) {
823        self.reduced_motion.store(None);
824    }
825
826    /// Clear the cached icon theme, or the cached failure to detect one.
827    pub fn invalidate_icon_theme(&self) {
828        self.icon_theme.store(None);
829    }
830
831    /// Clear the cached Linux desktop environment.
832    #[cfg(target_os = "linux")]
833    pub fn invalidate_linux_desktop(&self) {
834        self.linux_desktop.store(None);
835    }
836
837    /// Clear all cached values.
838    pub fn invalidate_all(&self) {
839        self.invalidate_is_dark();
840        self.invalidate_reduced_motion();
841        self.invalidate_icon_theme();
842        #[cfg(target_os = "linux")]
843        self.invalidate_linux_desktop();
844    }
845}
846
847/// Return the process-wide default [`DetectionContext`].
848///
849/// This is a lazily-initialized singleton. The first call creates it;
850/// all subsequent calls return the same instance.
851pub fn system() -> &'static DetectionContext {
852    static INSTANCE: std::sync::OnceLock<DetectionContext> = std::sync::OnceLock::new();
853    INSTANCE.get_or_init(DetectionContext::new)
854}
855
856/// Inner icon theme detection, delegating to platform-specific logic.
857///
858/// On Linux, dispatches by desktop environment. On macOS/iOS/Windows,
859/// returns the compile-time constant; elsewhere, the platform's failure.
860fn detect_icon_theme_inner() -> Result<String, crate::model::icons::IconThemeFailure> {
861    crate::model::icons::detect_icon_theme_outcome()
862}
863
864// === Crate-internal accessors ===
865
866/// Run `gsettings get <schema> <key>` with timeout.
867#[cfg(all(target_os = "linux", feature = "portal"))]
868pub(crate) fn gsettings_get(schema: &str, key: &str) -> Option<String> {
869    run_gsettings_with_timeout(&["get", schema, key])
870}
871
872/// Read Xft.dpi from X resources.
873#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
874pub(crate) fn xft_dpi() -> Option<f32> {
875    read_xft_dpi()
876}
877
878/// Detect physical DPI from xrandr.
879#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
880pub(crate) fn physical_dpi() -> Option<f32> {
881    detect_physical_dpi()
882}
883
884/// Detect the system font DPI (combining multiple sources).
885pub(crate) fn system_font_dpi() -> f32 {
886    detect_system_font_dpi()
887}
888
889#[cfg(test)]
890#[allow(clippy::unwrap_used, clippy::expect_used)]
891mod reduced_motion_tests {
892    use super::*;
893
894    #[test]
895    fn prefers_reduced_motion_smoke_test() {
896        // Smoke test: function should not panic on any platform.
897        // Cannot assert a specific value because caching preserves the first call
898        // and CI environments have varying accessibility settings.
899        let _result = prefers_reduced_motion();
900    }
901
902    #[cfg(target_os = "linux")]
903    #[test]
904    fn detect_reduced_motion_inner_linux() {
905        // Bypass caching to test actual detection logic.
906        // On CI without gsettings, returns false (animations enabled).
907        // On developer machines, depends on accessibility settings.
908        let result = detect_reduced_motion_inner();
909        // Just verify it returns a bool without panicking.
910        let _ = result;
911    }
912
913    #[cfg(target_os = "macos")]
914    #[test]
915    fn detect_reduced_motion_inner_macos() {
916        let result = detect_reduced_motion_inner();
917        let _ = result;
918    }
919
920    #[cfg(target_os = "windows")]
921    #[test]
922    fn detect_reduced_motion_inner_windows() {
923        let result = detect_reduced_motion_inner();
924        let _ = result;
925    }
926}
927
928#[cfg(test)]
929mod detection_context_tests {
930    use super::*;
931
932    #[test]
933    fn system_returns_same_instance() {
934        let a = system() as *const DetectionContext;
935        let b = system() as *const DetectionContext;
936        assert_eq!(a, b);
937    }
938
939    #[test]
940    fn is_dark_caches_result() {
941        let ctx = DetectionContext::new();
942        let first = ctx.is_dark();
943        let second = ctx.is_dark();
944        assert_eq!(first, second);
945    }
946
947    #[test]
948    fn invalidate_is_dark_clears_cache() {
949        let ctx = DetectionContext::new();
950        let _ = ctx.is_dark(); // populate cache
951        ctx.invalidate_is_dark();
952        // After invalidation, next call re-queries (we just verify it doesn't panic)
953        let _ = ctx.is_dark();
954    }
955
956    #[test]
957    fn prefers_reduced_motion_caches_result() {
958        let ctx = DetectionContext::new();
959        let first = ctx.prefers_reduced_motion();
960        let second = ctx.prefers_reduced_motion();
961        assert_eq!(first, second);
962    }
963
964    #[test]
965    fn invalidate_all_clears_all_caches() {
966        let ctx = DetectionContext::new();
967        let _ = ctx.is_dark();
968        let _ = ctx.prefers_reduced_motion();
969        let _ = ctx.icon_theme();
970        ctx.invalidate_all();
971        // Re-read all without panic
972        let _ = ctx.is_dark();
973        let _ = ctx.prefers_reduced_motion();
974        let _ = ctx.icon_theme();
975    }
976
977    fn undetected() -> Result<String, crate::model::icons::IconThemeFailure> {
978        Err(crate::model::icons::IconThemeFailure::for_tests(
979            "the test's failing detection",
980        ))
981    }
982
983    #[test]
984    fn a_failed_icon_theme_detection_is_cached_and_reported() {
985        let ctx = DetectionContext::new();
986        let runs = std::cell::Cell::new(0);
987        let detect = || {
988            runs.set(runs.get() + 1);
989            undetected()
990        };
991        let first = ctx.icon_theme_with(detect);
992        let second = ctx.icon_theme_with(detect);
993        assert_eq!(runs.get(), 1, "a failed detection ran again");
994        for outcome in [first, second] {
995            match outcome {
996                Ok(name) => panic!("a failed detection gave the theme {name}"),
997                Err(e) => assert!(
998                    e.to_string().contains("the test's failing detection"),
999                    "got: {e}"
1000                ),
1001            }
1002        }
1003    }
1004
1005    #[test]
1006    fn invalidate_icon_theme_clears_a_cached_failure() {
1007        let ctx = DetectionContext::new();
1008        assert!(ctx.icon_theme_with(undetected).is_err());
1009        ctx.invalidate_icon_theme();
1010        let theme = ctx.icon_theme_with(|| Ok("breeze".to_string()));
1011        assert_eq!(theme.ok().as_deref(), Some("breeze"));
1012    }
1013
1014    #[test]
1015    fn invalidate_all_clears_a_cached_failure() {
1016        let ctx = DetectionContext::new();
1017        assert!(ctx.icon_theme_with(undetected).is_err());
1018        ctx.invalidate_all();
1019        let theme = ctx.icon_theme_with(|| Ok("breeze".to_string()));
1020        assert_eq!(theme.ok().as_deref(), Some("breeze"));
1021    }
1022
1023    #[cfg(target_os = "linux")]
1024    #[test]
1025    fn linux_desktop_caches_result() {
1026        let ctx = DetectionContext::new();
1027        let first = ctx.linux_desktop();
1028        let second = ctx.linux_desktop();
1029        assert_eq!(first, second);
1030    }
1031
1032    #[cfg(target_os = "linux")]
1033    #[test]
1034    fn invalidate_linux_desktop_clears_cache() {
1035        let ctx = DetectionContext::new();
1036        let _ = ctx.linux_desktop();
1037        ctx.invalidate_linux_desktop();
1038        let _ = ctx.linux_desktop(); // re-reads without panic
1039    }
1040}
1041
1042#[cfg(all(test, target_os = "linux"))]
1043#[allow(clippy::unwrap_used, clippy::expect_used)]
1044mod subprocess_tests {
1045    use super::*;
1046    use std::path::PathBuf;
1047    use std::time::{Duration, Instant};
1048
1049    /// Whether `program` is an executable file in a `$PATH` directory.
1050    fn on_path(program: &str) -> bool {
1051        std::env::var_os("PATH")
1052            .is_some_and(|path| std::env::split_paths(&path).any(|dir| dir.join(program).is_file()))
1053    }
1054
1055    #[test]
1056    fn poll_intervals_double_from_1_ms_up_to_50_ms() {
1057        let intervals: Vec<Duration> = poll_intervals().take(10).collect();
1058        let expected: Vec<Duration> = [1, 2, 4, 8, 16, 32, 50, 50, 50, 50]
1059            .into_iter()
1060            .map(Duration::from_millis)
1061            .collect();
1062        assert_eq!(intervals, expected);
1063    }
1064
1065    #[test]
1066    fn run_with_timeout_returns_stdout_of_a_successful_command() {
1067        if !on_path("echo") {
1068            eprintln!("skipped: echo is not installed");
1069            return;
1070        }
1071        let out = run_with_timeout("echo", &["hi"], SUBPROCESS_TIMEOUT);
1072        assert_eq!(out.as_deref().map(str::trim), Some("hi"));
1073    }
1074
1075    #[test]
1076    fn run_with_timeout_returns_none_for_a_failing_command() {
1077        if !on_path("false") {
1078            eprintln!("skipped: false is not installed");
1079            return;
1080        }
1081        assert_eq!(run_with_timeout("false", &[], SUBPROCESS_TIMEOUT), None);
1082    }
1083
1084    #[test]
1085    fn run_with_timeout_returns_none_for_a_missing_program() {
1086        assert_eq!(
1087            run_with_timeout("nt-test-no-such-program", &[], SUBPROCESS_TIMEOUT),
1088            None
1089        );
1090    }
1091
1092    /// A command that exits at once with no output gives an empty stdout;
1093    /// the time it took is printed (the schedule test is the timing proof).
1094    #[test]
1095    fn run_with_timeout_returns_the_empty_stdout_of_a_quiet_command() {
1096        if !on_path("true") {
1097            eprintln!("skipped: true is not installed");
1098            return;
1099        }
1100        let start = Instant::now();
1101        assert_eq!(
1102            run_with_timeout("true", &[], SUBPROCESS_TIMEOUT).as_deref(),
1103            Some("")
1104        );
1105        eprintln!("`true` ran in {:?}", start.elapsed());
1106    }
1107
1108    #[test]
1109    fn run_with_timeout_kills_a_command_that_outlives_the_timeout() {
1110        if !on_path("sleep") {
1111            eprintln!("skipped: sleep is not installed");
1112            return;
1113        }
1114        let seconds = format!("5.{}", std::process::id());
1115        let start = Instant::now();
1116        let out = run_with_timeout("sleep", &[&seconds], Duration::from_millis(100));
1117        let elapsed = start.elapsed();
1118        assert_eq!(out, None);
1119        assert!(elapsed < Duration::from_secs(1), "took {elapsed:?}");
1120        let cmdline = format!("sleep\0{seconds}\0");
1121        let still_running: Vec<PathBuf> = std::fs::read_dir("/proc")
1122            .unwrap()
1123            .flatten()
1124            .map(|entry| entry.path().join("cmdline"))
1125            .filter(|path| std::fs::read(path).is_ok_and(|bytes| bytes == cmdline.as_bytes()))
1126            .collect();
1127        assert!(still_running.is_empty(), "not killed: {still_running:?}");
1128    }
1129}