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, subscribe to OS appearance-change events
124/// (D-Bus `SettingChanged` on Linux, `NSAppearance` KVO on macOS,
125/// `UISettings.ColorValuesChanged` on Windows) and call [`crate::SystemTheme::from_system()`]
126/// to get a fresh [`crate::SystemTheme`] with updated resolved variants.
127///
128/// # Platform Behavior
129///
130/// - **Linux:** Checks `GTK_THEME` env var for `:dark` suffix or `-dark`
131///   in name; queries `gsettings` for `color-scheme` (with 2-second
132///   timeout); falls back to KDE `kdeglobals` background luminance (with
133///   `kde` feature); reads `gtk-3.0/settings.ini` for
134///   `gtk-application-prefer-dark-theme=1` as final fallback.
135/// - **macOS:** Reads `AppleInterfaceStyle` via `NSUserDefaults` (with
136///   `macos` feature) or `defaults` subprocess (without).
137/// - **Windows:** Checks foreground color luminance from `UISettings` via
138///   BT.601 coefficients (requires `windows` feature).
139/// - **Other platforms / missing features:** Returns `false` (light).
140#[must_use]
141pub fn system_is_dark() -> bool {
142    system().is_dark()
143}
144
145/// Reset all process-wide caches so the next call to [`system_is_dark()`],
146/// [`prefers_reduced_motion()`], or [`crate::system_icon_theme()`] re-queries the OS.
147///
148/// Call this when you detect that the user has changed system settings (e.g.,
149/// dark mode toggle, icon theme switch, accessibility preferences).
150///
151/// The `detect_*()` family of functions are unaffected — they always query
152/// the OS directly.
153pub fn invalidate_caches() {
154    system().invalidate_all();
155}
156
157/// Detect whether the system is using a dark color scheme without caching.
158///
159/// Unlike [`system_is_dark()`], this function queries the OS every time it is
160/// called and never caches the result. Use this when polling for theme changes
161/// or implementing live dark-mode tracking.
162///
163/// See [`system_is_dark()`] for platform behavior details.
164#[must_use]
165pub fn detect_is_dark() -> bool {
166    detect_is_dark_inner()
167}
168
169/// Run a gsettings command with a 2-second timeout.
170///
171/// Spawns `gsettings` with the given arguments, waits up to 2 seconds
172/// for completion, and returns the trimmed stdout on success.  Returns
173/// `None` if the command fails, times out, or produces empty output.
174///
175/// Used by [`detect_is_dark_inner()`] and [`crate::gnome::read_gsetting()`] to
176/// prevent gsettings from blocking indefinitely when D-Bus is unresponsive.
177#[cfg(target_os = "linux")]
178fn run_gsettings_with_timeout(args: &[&str]) -> Option<String> {
179    use std::io::Read;
180    use std::time::{Duration, Instant};
181
182    let start = Instant::now();
183    let timeout = SUBPROCESS_TIMEOUT;
184    let mut child = std::process::Command::new("gsettings")
185        .args(args)
186        .stdout(std::process::Stdio::piped())
187        .stderr(std::process::Stdio::null())
188        .spawn()
189        .ok()?;
190
191    loop {
192        match child.try_wait() {
193            Ok(Some(status)) if status.success() => {
194                let mut buf = String::new();
195                if let Some(mut stdout) = child.stdout.take() {
196                    let _ = stdout.read_to_string(&mut buf);
197                }
198                let trimmed = buf.trim().to_string();
199                return if trimmed.is_empty() {
200                    None
201                } else {
202                    Some(trimmed)
203                };
204            }
205            Ok(Some(_)) => return None,
206            Ok(None) => {
207                if start.elapsed() >= timeout {
208                    let _ = child.kill();
209                    return None;
210                }
211                std::thread::sleep(Duration::from_millis(50));
212            }
213            Err(_) => return None,
214        }
215    }
216}
217
218/// Read `Xft.dpi` from X resources via `xrdb -query`.
219///
220/// Returns `None` if xrdb is not installed, times out (2 seconds),
221/// or the output does not contain a valid positive `Xft.dpi` value.
222#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
223fn read_xft_dpi() -> Option<f32> {
224    use std::io::Read;
225    use std::time::{Duration, Instant};
226
227    let start = Instant::now();
228    let timeout = SUBPROCESS_TIMEOUT;
229    let mut child = std::process::Command::new("xrdb")
230        .arg("-query")
231        .stdout(std::process::Stdio::piped())
232        .stderr(std::process::Stdio::null())
233        .spawn()
234        .ok()?;
235
236    loop {
237        match child.try_wait() {
238            Ok(Some(status)) if status.success() => {
239                let mut buf = String::new();
240                if let Some(mut stdout) = child.stdout.take() {
241                    let _ = stdout.read_to_string(&mut buf);
242                }
243                // Parse "Xft.dpi:\t96" from multi-line output
244                for line in buf.lines() {
245                    if let Some(rest) = line.strip_prefix("Xft.dpi:")
246                        && let Ok(dpi) = rest.trim().parse::<f32>()
247                        && dpi > 0.0
248                    {
249                        return Some(dpi);
250                    }
251                }
252                return None;
253            }
254            Ok(Some(_)) => return None,
255            Ok(None) => {
256                if start.elapsed() >= timeout {
257                    let _ = child.kill();
258                    return None;
259                }
260                std::thread::sleep(Duration::from_millis(50));
261            }
262            Err(_) => return None,
263        }
264    }
265}
266
267/// Detect physical DPI from display hardware via `xrandr`.
268///
269/// Parses the primary connected output's resolution and physical dimensions
270/// to compute DPI. Falls back to the first connected output if no primary
271/// is found. Returns `None` if `xrandr` is unavailable, times out (2 seconds),
272/// or the output cannot be parsed.
273///
274/// This is a last-resort fallback: prefer `forceFontDPI` (KDE), `Xft.dpi`
275/// (X resources), or `GetDpiForSystem` (Windows) before calling this.
276#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
277fn detect_physical_dpi() -> Option<f32> {
278    use std::io::Read;
279    use std::time::{Duration, Instant};
280
281    let start = Instant::now();
282    let timeout = SUBPROCESS_TIMEOUT;
283    let mut child = std::process::Command::new("xrandr")
284        .stdout(std::process::Stdio::piped())
285        .stderr(std::process::Stdio::null())
286        .spawn()
287        .ok()?;
288
289    loop {
290        match child.try_wait() {
291            Ok(Some(status)) if status.success() => {
292                let mut buf = String::new();
293                if let Some(mut stdout) = child.stdout.take() {
294                    let _ = stdout.read_to_string(&mut buf);
295                }
296                return parse_xrandr_dpi(&buf);
297            }
298            Ok(Some(_)) => return None,
299            Ok(None) => {
300                if start.elapsed() >= timeout {
301                    let _ = child.kill();
302                    return None;
303                }
304                std::thread::sleep(Duration::from_millis(50));
305            }
306            Err(_) => return None,
307        }
308    }
309}
310
311/// Parse DPI from xrandr output.
312///
313/// Looks for lines like:
314/// ```text
315/// DP-1 connected primary 3840x2160+0+0 (...) 700mm x 390mm
316/// ```
317/// Extracts the current resolution from the mode string and the physical
318/// dimensions from the trailing `NNNmm x NNNmm`, then computes average DPI.
319#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
320fn parse_xrandr_dpi(output: &str) -> Option<f32> {
321    // Prefer the primary output; fall back to the first connected output.
322    let line = output
323        .lines()
324        .find(|l| l.contains(" connected") && l.contains("primary"))
325        .or_else(|| {
326            output
327                .lines()
328                .find(|l| l.contains(" connected") && !l.contains("disconnected"))
329        })?;
330
331    // Resolution: "3840x2160+0+0" (digits x digits + offset)
332    let res_token = line
333        .split_whitespace()
334        .find(|s| s.contains('x') && s.contains('+'))?;
335    let (w_str, rest) = res_token.split_once('x')?;
336    let h_str = rest.split('+').next()?;
337    let w_px: f32 = w_str.parse().ok()?;
338    let h_px: f32 = h_str.parse().ok()?;
339
340    // Physical size: "700mm x 390mm" at the end of the line
341    let words: Vec<&str> = line.split_whitespace().collect();
342    let mut w_mm = None;
343    let mut h_mm = None;
344    for window in words.windows(3) {
345        let [prev, cur, next] = window else { continue };
346        if *cur == "x" {
347            w_mm = prev.strip_suffix("mm").and_then(|n| n.parse::<f32>().ok());
348            h_mm = next.strip_suffix("mm").and_then(|n| n.parse::<f32>().ok());
349        }
350    }
351    let w_mm = w_mm.filter(|&v| v > 0.0)?;
352    let h_mm = h_mm.filter(|&v| v > 0.0)?;
353
354    let h_dpi = w_px / (w_mm / 25.4);
355    let v_dpi = h_px / (h_mm / 25.4);
356    let avg = (h_dpi + v_dpi) / 2.0;
357
358    if avg > 0.0 { Some(avg) } else { None }
359}
360
361#[cfg(all(test, target_os = "linux", any(feature = "kde", feature = "portal")))]
362#[allow(clippy::unwrap_used)]
363mod xrandr_dpi_tests {
364    use super::parse_xrandr_dpi;
365
366    #[test]
367    fn primary_4k_display() {
368        // Real xrandr output: 4K display at 700mm wide
369        let output = "Screen 0: minimum 16 x 16, current 3840 x 2160, maximum 32767 x 32767\n\
370                       DP-1 connected primary 3840x2160+0+0 (normal left inverted right x axis y axis) 700mm x 390mm\n\
371                          3840x2160     60.00*+\n";
372        let dpi = parse_xrandr_dpi(output).unwrap();
373        // 3840/(700/25.4) = 139.3, 2160/(390/25.4) = 140.7, avg ~140
374        assert!((dpi - 140.0).abs() < 1.0, "expected ~140 DPI, got {dpi}");
375    }
376
377    #[test]
378    fn standard_1080p_display() {
379        let output = "DP-2 connected primary 1920x1080+0+0 (normal) 530mm x 300mm\n";
380        let dpi = parse_xrandr_dpi(output).unwrap();
381        // 1920/(530/25.4) = 92.0, 1080/(300/25.4) = 91.4, avg ~91.7
382        assert!((dpi - 92.0).abs() < 1.0, "expected ~92 DPI, got {dpi}");
383    }
384
385    #[test]
386    fn no_primary_falls_back_to_first_connected() {
387        let output = "HDMI-1 connected 1920x1080+0+0 (normal) 480mm x 270mm\n\
388                       DP-1 disconnected\n";
389        let dpi = parse_xrandr_dpi(output).unwrap();
390        assert!(dpi > 90.0 && dpi < 110.0, "expected ~100 DPI, got {dpi}");
391    }
392
393    #[test]
394    fn disconnected_only_returns_none() {
395        let output = "DP-1 disconnected\nHDMI-1 disconnected\n";
396        assert!(parse_xrandr_dpi(output).is_none());
397    }
398
399    #[test]
400    fn missing_physical_dimensions_returns_none() {
401        // No "NNNmm x NNNmm" in the line
402        let output = "DP-1 connected primary 1920x1080+0+0 (normal)\n";
403        assert!(parse_xrandr_dpi(output).is_none());
404    }
405
406    #[test]
407    fn zero_mm_returns_none() {
408        let output = "DP-1 connected primary 1920x1080+0+0 (normal) 0mm x 0mm\n";
409        assert!(parse_xrandr_dpi(output).is_none());
410    }
411
412    #[test]
413    fn empty_output_returns_none() {
414        assert!(parse_xrandr_dpi("").is_none());
415    }
416}
417
418/// Detect the font DPI for the current system.
419///
420/// Used by [`ThemeMode::into_resolved()`] as a fallback when no OS reader
421/// has provided `font_dpi`. Returns the platform-appropriate DPI for
422/// converting typographic points to logical pixels.
423///
424/// - **Linux (KDE)**: `forceFontDPI` from kdeglobals/kcmfontsrc → `Xft.dpi` → xrandr → 96.0
425/// - **Linux (other)**: `Xft.dpi` → xrandr → 96.0
426/// - **macOS**: 72.0 (Apple coordinate system: 1pt = 1px)
427/// - **Windows**: `GetDpiForSystem()` → 96.0
428/// - **Other**: 96.0
429#[allow(unreachable_code)]
430fn detect_system_font_dpi() -> f32 {
431    #[cfg(target_os = "macos")]
432    {
433        return 72.0;
434    }
435
436    #[cfg(all(target_os = "windows", feature = "windows"))]
437    {
438        return crate::windows::read_dpi() as f32;
439    }
440
441    // KDE: check forceFontDPI first (same chain as the KDE reader)
442    #[cfg(all(target_os = "linux", feature = "kde"))]
443    {
444        if let Some(dpi) = read_kde_force_font_dpi() {
445            return dpi;
446        }
447    }
448
449    #[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
450    {
451        if let Some(dpi) = read_xft_dpi() {
452            return dpi;
453        }
454        if let Some(dpi) = detect_physical_dpi() {
455            return dpi;
456        }
457    }
458
459    96.0
460}
461
462/// Read KDE's `forceFontDPI` from kdeglobals or kcmfontsrc.
463///
464/// This mirrors the first step of [`crate::kde::detect_font_dpi()`] so that
465/// standalone preset loading (via [`ThemeMode::into_resolved()`]) uses the
466/// same DPI as the full KDE reader pipeline.
467#[cfg(all(target_os = "linux", feature = "kde"))]
468fn read_kde_force_font_dpi() -> Option<f32> {
469    // Try kdeglobals [General] forceFontDPI
470    let path = crate::kde::kdeglobals_path();
471    if let Ok(content) = std::fs::read_to_string(&path) {
472        let mut ini = crate::kde::create_kde_parser();
473        if ini.read(content).is_ok()
474            && let Some(dpi_str) = ini.get("General", "forceFontDPI")
475            && let Ok(dpi) = dpi_str.trim().parse::<f32>()
476            && dpi > 0.0
477        {
478            return Some(dpi);
479        }
480    }
481    // Try kcmfontsrc [General] forceFontDPI
482    if let Some(dpi_str) = crate::kde::read_kcmfontsrc_key("General", "forceFontDPI")
483        && let Ok(dpi) = dpi_str.trim().parse::<f32>()
484        && dpi > 0.0
485    {
486        return Some(dpi);
487    }
488    None
489}
490
491/// Inner detection logic for [`system_is_dark()`].
492///
493/// Separated from the public function to allow caching.
494#[allow(unreachable_code)]
495fn detect_is_dark_inner() -> bool {
496    #[cfg(target_os = "linux")]
497    {
498        // Check GTK_THEME env var (works across all GTK-based DEs)
499        if let Ok(gtk_theme) = std::env::var("GTK_THEME") {
500            let lower = gtk_theme.to_lowercase();
501            if lower.ends_with(":dark") || lower.contains("-dark") {
502                return true;
503            }
504        }
505
506        // On KDE, read kdeglobals directly — gsettings color-scheme is
507        // synced by xdg-desktop-portal-kde and can be stale or inverted.
508        #[cfg(feature = "kde")]
509        {
510            let de = parse_linux_desktop(&xdg_current_desktop());
511            if matches!(de, LinuxDesktop::Kde) {
512                let path = crate::kde::kdeglobals_path();
513                if let Ok(content) = std::fs::read_to_string(&path) {
514                    let mut ini = crate::kde::create_kde_parser();
515                    if ini.read(content).is_ok() {
516                        return crate::kde::is_dark_theme(&ini);
517                    }
518                }
519            }
520        }
521
522        // gsettings color-scheme (reliable on GNOME / GTK-based DEs)
523        if let Some(val) =
524            run_gsettings_with_timeout(&["get", "org.gnome.desktop.interface", "color-scheme"])
525        {
526            if val.contains("prefer-dark") {
527                return true;
528            }
529            if val.contains("prefer-light") || val.contains("default") {
530                return false;
531            }
532        }
533
534        // Fallback: read KDE's kdeglobals background luminance (non-KDE DE
535        // or when the KDE feature is disabled and the gsettings check above
536        // returned no result).
537        #[cfg(feature = "kde")]
538        {
539            let path = crate::kde::kdeglobals_path();
540            if let Ok(content) = std::fs::read_to_string(&path) {
541                let mut ini = crate::kde::create_kde_parser();
542                if ini.read(content).is_ok() {
543                    return crate::kde::is_dark_theme(&ini);
544                }
545            }
546        }
547
548        // Fallback: gtk-3.0/settings.ini for DEs that set the GTK dark preference
549        let config_home = std::env::var("XDG_CONFIG_HOME").unwrap_or_else(|_| {
550            let home = std::env::var("HOME").unwrap_or_default();
551            format!("{home}/.config")
552        });
553        let ini_path = format!("{config_home}/gtk-3.0/settings.ini");
554        if let Ok(content) = std::fs::read_to_string(&ini_path) {
555            for line in content.lines() {
556                let trimmed = line.trim();
557                if trimmed.starts_with("gtk-application-prefer-dark-theme")
558                    && let Some(val) = trimmed.split('=').nth(1)
559                    && (val.trim() == "1" || val.trim().eq_ignore_ascii_case("true"))
560                {
561                    return true;
562                }
563            }
564        }
565
566        false
567    }
568
569    #[cfg(target_os = "macos")]
570    {
571        // AppleInterfaceStyle is "Dark" when dark mode is active.
572        // The key is absent in light mode, so any failure means light.
573        #[cfg(feature = "macos")]
574        {
575            use objc2_foundation::NSUserDefaults;
576            let defaults = NSUserDefaults::standardUserDefaults();
577            let key = objc2_foundation::ns_string!("AppleInterfaceStyle");
578            if let Some(value) = defaults.stringForKey(key) {
579                return value.to_string().eq_ignore_ascii_case("dark");
580            }
581            return false;
582        }
583        #[cfg(not(feature = "macos"))]
584        {
585            if let Ok(output) = std::process::Command::new("defaults")
586                .args(["read", "-g", "AppleInterfaceStyle"])
587                .output()
588                && output.status.success()
589            {
590                let val = String::from_utf8_lossy(&output.stdout);
591                return val.trim().eq_ignore_ascii_case("dark");
592            }
593            return false;
594        }
595    }
596
597    #[cfg(target_os = "windows")]
598    {
599        #[cfg(feature = "windows")]
600        {
601            // BT.601 luminance: light foreground indicates dark background.
602            let Ok(settings) = ::windows::UI::ViewManagement::UISettings::new() else {
603                return false;
604            };
605            let Ok(fg) =
606                settings.GetColorValue(::windows::UI::ViewManagement::UIColorType::Foreground)
607            else {
608                return false;
609            };
610            let luma = 0.299 * (fg.R as f32) + 0.587 * (fg.G as f32) + 0.114 * (fg.B as f32);
611            return luma > 128.0;
612        }
613        #[cfg(not(feature = "windows"))]
614        return false;
615    }
616
617    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
618    {
619        false
620    }
621}
622
623/// Query whether the user prefers reduced motion.
624///
625/// Returns `true` when the OS accessibility setting indicates animations
626/// should be reduced or disabled. Returns `false` (allow animations) on
627/// unsupported platforms or when the query fails.
628///
629/// # Caching
630///
631/// The result is cached after the first call and reused on subsequent calls.
632/// Call [`invalidate_caches()`] to clear the cached value so the next call
633/// re-queries the OS. For live accessibility-change tracking, subscribe to
634/// OS accessibility events and call `invalidate_caches()` when notified.
635///
636/// # Platform Behavior
637///
638/// - **Linux:** Queries `gsettings get org.gnome.desktop.interface enable-animations`.
639///   Returns `true` when animations are disabled (`enable-animations` is `false`).
640/// - **macOS:** Queries `NSWorkspace.accessibilityDisplayShouldReduceMotion`
641///   (requires `macos` feature).
642/// - **Windows:** Queries `UISettings.AnimationsEnabled()` (requires `windows` feature).
643/// - **Other platforms:** Returns `false`.
644///
645/// # Examples
646///
647/// ```
648/// let reduced = native_theme::detect::prefers_reduced_motion();
649/// // On this platform, the result depends on OS accessibility settings.
650/// // The function always returns a bool (false on unsupported platforms).
651/// assert!(reduced == true || reduced == false);
652/// ```
653#[must_use]
654pub fn prefers_reduced_motion() -> bool {
655    system().prefers_reduced_motion()
656}
657
658/// Detect whether the user prefers reduced motion without caching.
659///
660/// Unlike [`prefers_reduced_motion()`], this function queries the OS every time
661/// it is called and never caches the result. Use this when polling for
662/// accessibility preference changes.
663///
664/// See [`prefers_reduced_motion()`] for platform behavior details.
665#[must_use]
666pub fn detect_reduced_motion() -> bool {
667    detect_reduced_motion_inner()
668}
669
670/// Inner detection logic for [`prefers_reduced_motion()`].
671///
672/// Separated from the public function to allow caching.
673#[allow(unreachable_code)]
674fn detect_reduced_motion_inner() -> bool {
675    #[cfg(target_os = "linux")]
676    {
677        // gsettings boolean output is bare "true\n" or "false\n" (no quotes)
678        // enable-animations has INVERTED semantics: false => reduced motion preferred
679        if let Some(val) =
680            run_gsettings_with_timeout(&["get", "org.gnome.desktop.interface", "enable-animations"])
681        {
682            return val.trim() == "false";
683        }
684        false
685    }
686
687    #[cfg(target_os = "macos")]
688    {
689        #[cfg(feature = "macos")]
690        {
691            let workspace = objc2_app_kit::NSWorkspace::sharedWorkspace();
692            // Direct semantics: true = reduce motion preferred (no inversion needed)
693            return workspace.accessibilityDisplayShouldReduceMotion();
694        }
695        #[cfg(not(feature = "macos"))]
696        return false;
697    }
698
699    #[cfg(target_os = "windows")]
700    {
701        #[cfg(feature = "windows")]
702        {
703            let Ok(settings) = ::windows::UI::ViewManagement::UISettings::new() else {
704                return false;
705            };
706            // AnimationsEnabled has INVERTED semantics: false => reduced motion preferred
707            return match settings.AnimationsEnabled() {
708                Ok(enabled) => !enabled,
709                Err(_) => false,
710            };
711        }
712        #[cfg(not(feature = "windows"))]
713        return false;
714    }
715
716    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
717    {
718        false
719    }
720}
721
722// === DetectionContext ===
723
724/// Process-wide detection cache.
725///
726/// Provides "cache on first read" semantics for OS detection queries
727/// (`is_dark`, `reduced_motion`, `icon_theme`, `linux_desktop`) and
728/// per-field invalidation for watchers that need fresh data.
729///
730/// Obtain the process-wide instance via [`system()`].
731///
732/// # Thread Safety
733///
734/// All reads and invalidations are lock-free (backed by
735/// [`arc_swap::ArcSwapOption`]).
736pub struct DetectionContext {
737    is_dark: ArcSwapOption<bool>,
738    reduced_motion: ArcSwapOption<bool>,
739    icon_theme: ArcSwapOption<String>,
740    #[cfg(target_os = "linux")]
741    linux_desktop: ArcSwapOption<LinuxDesktop>,
742}
743
744impl DetectionContext {
745    /// Create an empty context with no cached values.
746    fn new() -> Self {
747        Self {
748            is_dark: ArcSwapOption::empty(),
749            reduced_motion: ArcSwapOption::empty(),
750            icon_theme: ArcSwapOption::empty(),
751            #[cfg(target_os = "linux")]
752            linux_desktop: ArcSwapOption::empty(),
753        }
754    }
755
756    /// Whether the system is using a dark color scheme (cached).
757    ///
758    /// The first call queries the OS and caches the result.
759    /// Subsequent calls return the cached value.
760    /// Call [`invalidate_is_dark()`](Self::invalidate_is_dark) to
761    /// force a re-read on the next call.
762    #[must_use]
763    pub fn is_dark(&self) -> bool {
764        if let Some(v) = self.is_dark.load().as_deref() {
765            return *v;
766        }
767        let value = detect_is_dark_inner();
768        self.is_dark.store(Some(Arc::new(value)));
769        value
770    }
771
772    /// Whether the user prefers reduced motion (cached).
773    ///
774    /// The first call queries the OS and caches the result.
775    /// Call [`invalidate_reduced_motion()`](Self::invalidate_reduced_motion)
776    /// to force a re-read.
777    #[must_use]
778    pub fn prefers_reduced_motion(&self) -> bool {
779        if let Some(v) = self.reduced_motion.load().as_deref() {
780            return *v;
781        }
782        let value = detect_reduced_motion_inner();
783        self.reduced_motion.store(Some(Arc::new(value)));
784        value
785    }
786
787    /// The current icon theme name (cached).
788    ///
789    /// Returns a clone of the cached `String`. The first call
790    /// detects the theme from the OS; subsequent calls return the
791    /// cached value. Call
792    /// [`invalidate_icon_theme()`](Self::invalidate_icon_theme) to
793    /// force a re-read.
794    #[must_use]
795    pub fn icon_theme(&self) -> Arc<String> {
796        if let Some(v) = self.icon_theme.load_full() {
797            return v;
798        }
799        let value = Arc::new(detect_icon_theme_inner());
800        self.icon_theme.store(Some(Arc::clone(&value)));
801        value
802    }
803
804    /// The current Linux desktop environment (cached).
805    ///
806    /// The first call reads `XDG_CURRENT_DESKTOP` and caches the
807    /// result. Call
808    /// [`invalidate_linux_desktop()`](Self::invalidate_linux_desktop)
809    /// to force a re-read.
810    #[cfg(target_os = "linux")]
811    #[must_use]
812    pub fn linux_desktop(&self) -> LinuxDesktop {
813        if let Some(v) = self.linux_desktop.load().as_deref() {
814            return *v;
815        }
816        let value = detect_linux_desktop();
817        self.linux_desktop.store(Some(Arc::new(value)));
818        value
819    }
820
821    /// Clear the cached dark-mode value.
822    pub fn invalidate_is_dark(&self) {
823        self.is_dark.store(None);
824    }
825
826    /// Clear the cached reduced-motion value.
827    pub fn invalidate_reduced_motion(&self) {
828        self.reduced_motion.store(None);
829    }
830
831    /// Clear the cached icon theme.
832    pub fn invalidate_icon_theme(&self) {
833        self.icon_theme.store(None);
834    }
835
836    /// Clear the cached Linux desktop environment.
837    #[cfg(target_os = "linux")]
838    pub fn invalidate_linux_desktop(&self) {
839        self.linux_desktop.store(None);
840    }
841
842    /// Clear all cached values.
843    pub fn invalidate_all(&self) {
844        self.invalidate_is_dark();
845        self.invalidate_reduced_motion();
846        self.invalidate_icon_theme();
847        #[cfg(target_os = "linux")]
848        self.invalidate_linux_desktop();
849    }
850}
851
852/// Return the process-wide default [`DetectionContext`].
853///
854/// This is a lazily-initialized singleton. The first call creates it;
855/// all subsequent calls return the same instance.
856pub fn system() -> &'static DetectionContext {
857    static INSTANCE: std::sync::OnceLock<DetectionContext> = std::sync::OnceLock::new();
858    INSTANCE.get_or_init(DetectionContext::new)
859}
860
861/// Inner icon theme detection, delegating to platform-specific logic.
862///
863/// On Linux, dispatches by desktop environment. On macOS/Windows/other,
864/// returns the compile-time constant.
865#[allow(unreachable_code)]
866fn detect_icon_theme_inner() -> String {
867    crate::model::icons::detect_icon_theme()
868}
869
870// === Crate-internal accessors ===
871
872/// Run `gsettings get <schema> <key>` with timeout.
873#[cfg(all(target_os = "linux", feature = "portal"))]
874pub(crate) fn gsettings_get(schema: &str, key: &str) -> Option<String> {
875    run_gsettings_with_timeout(&["get", schema, key])
876}
877
878/// Read Xft.dpi from X resources.
879#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
880pub(crate) fn xft_dpi() -> Option<f32> {
881    read_xft_dpi()
882}
883
884/// Detect physical DPI from xrandr.
885#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
886pub(crate) fn physical_dpi() -> Option<f32> {
887    detect_physical_dpi()
888}
889
890/// Detect the system font DPI (combining multiple sources).
891pub(crate) fn system_font_dpi() -> f32 {
892    detect_system_font_dpi()
893}
894
895#[cfg(test)]
896#[allow(clippy::unwrap_used, clippy::expect_used)]
897mod reduced_motion_tests {
898    use super::*;
899
900    #[test]
901    fn prefers_reduced_motion_smoke_test() {
902        // Smoke test: function should not panic on any platform.
903        // Cannot assert a specific value because caching preserves the first call
904        // and CI environments have varying accessibility settings.
905        let _result = prefers_reduced_motion();
906    }
907
908    #[cfg(target_os = "linux")]
909    #[test]
910    fn detect_reduced_motion_inner_linux() {
911        // Bypass caching to test actual detection logic.
912        // On CI without gsettings, returns false (animations enabled).
913        // On developer machines, depends on accessibility settings.
914        let result = detect_reduced_motion_inner();
915        // Just verify it returns a bool without panicking.
916        let _ = result;
917    }
918
919    #[cfg(target_os = "macos")]
920    #[test]
921    fn detect_reduced_motion_inner_macos() {
922        let result = detect_reduced_motion_inner();
923        let _ = result;
924    }
925
926    #[cfg(target_os = "windows")]
927    #[test]
928    fn detect_reduced_motion_inner_windows() {
929        let result = detect_reduced_motion_inner();
930        let _ = result;
931    }
932}
933
934#[cfg(test)]
935mod detection_context_tests {
936    use super::*;
937
938    #[test]
939    fn system_returns_same_instance() {
940        let a = system() as *const DetectionContext;
941        let b = system() as *const DetectionContext;
942        assert_eq!(a, b);
943    }
944
945    #[test]
946    fn is_dark_caches_result() {
947        let ctx = DetectionContext::new();
948        let first = ctx.is_dark();
949        let second = ctx.is_dark();
950        assert_eq!(first, second);
951    }
952
953    #[test]
954    fn invalidate_is_dark_clears_cache() {
955        let ctx = DetectionContext::new();
956        let _ = ctx.is_dark(); // populate cache
957        ctx.invalidate_is_dark();
958        // After invalidation, next call re-queries (we just verify it doesn't panic)
959        let _ = ctx.is_dark();
960    }
961
962    #[test]
963    fn prefers_reduced_motion_caches_result() {
964        let ctx = DetectionContext::new();
965        let first = ctx.prefers_reduced_motion();
966        let second = ctx.prefers_reduced_motion();
967        assert_eq!(first, second);
968    }
969
970    #[test]
971    fn invalidate_all_clears_all_caches() {
972        let ctx = DetectionContext::new();
973        let _ = ctx.is_dark();
974        let _ = ctx.prefers_reduced_motion();
975        let _ = ctx.icon_theme();
976        ctx.invalidate_all();
977        // Re-read all without panic
978        let _ = ctx.is_dark();
979        let _ = ctx.prefers_reduced_motion();
980        let _ = ctx.icon_theme();
981    }
982
983    #[cfg(target_os = "linux")]
984    #[test]
985    fn linux_desktop_caches_result() {
986        let ctx = DetectionContext::new();
987        let first = ctx.linux_desktop();
988        let second = ctx.linux_desktop();
989        assert_eq!(first, second);
990    }
991
992    #[cfg(target_os = "linux")]
993    #[test]
994    fn invalidate_linux_desktop_clears_cache() {
995        let ctx = DetectionContext::new();
996        let _ = ctx.linux_desktop();
997        ctx.invalidate_linux_desktop();
998        let _ = ctx.linux_desktop(); // re-reads without panic
999    }
1000}