native-theme 0.6.1

Cross-platform native theme detection and loading for Rust GUI applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
//! OS detection: dark mode, reduced motion, DPI, desktop environment.

use arc_swap::ArcSwapOption;
use std::sync::Arc;

/// Timeout for subprocess commands (gsettings, xrdb, xrandr).
///
/// Prevents D-Bus-dependent tools from blocking indefinitely when the
/// session bus is unresponsive or the display server is unavailable.
#[cfg(target_os = "linux")]
const SUBPROCESS_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);

/// Desktop environments recognized on Linux.
#[cfg(target_os = "linux")]
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LinuxDesktop {
    /// KDE Plasma desktop.
    Kde,
    /// GNOME desktop.
    Gnome,
    /// Xfce desktop.
    Xfce,
    /// Cinnamon desktop (Linux Mint).
    Cinnamon,
    /// MATE desktop.
    Mate,
    /// LXQt desktop.
    LxQt,
    /// Budgie desktop.
    Budgie,
    /// Hyprland Wayland compositor.
    Hyprland,
    /// Sway Wayland compositor (i3-compatible).
    Sway,
    /// River Wayland compositor.
    River,
    /// Niri scrollable Wayland compositor.
    Niri,
    /// Wayfire scene-graph Wayland compositor (wlroots-based).
    Wayfire,
    /// COSMIC desktop environment (System76).
    CosmicDe,
    /// Unrecognized or unset desktop environment.
    Unknown,
}

/// Read the `XDG_CURRENT_DESKTOP` environment variable, returning an
/// empty string if unset or invalid UTF-8.
#[cfg(target_os = "linux")]
pub(crate) fn xdg_current_desktop() -> String {
    std::env::var("XDG_CURRENT_DESKTOP").unwrap_or_default()
}

/// Detect the current Linux desktop environment.
///
/// Reads `XDG_CURRENT_DESKTOP` and returns the recognized desktop.
/// Returns [`LinuxDesktop::Unknown`] if the variable is unset or
/// contains no recognized value.
///
/// For testable parsing without environment access, use the
/// `pub` [`parse_linux_desktop()`] function instead.
///
/// # Examples
///
/// ```no_run
/// use native_theme::detect::{detect_linux_desktop, LinuxDesktop};
///
/// let de = detect_linux_desktop();
/// match de {
///     LinuxDesktop::Kde => println!("KDE Plasma"),
///     LinuxDesktop::Gnome => println!("GNOME"),
///     _ => println!("Other: {de:?}"),
/// }
/// ```
#[cfg(target_os = "linux")]
#[must_use]
pub fn detect_linux_desktop() -> LinuxDesktop {
    parse_linux_desktop(&xdg_current_desktop())
}

/// Parse `XDG_CURRENT_DESKTOP` (a colon-separated list) and return
/// the recognized desktop environment.
///
/// Checks components in order; first recognized DE wins. Budgie is checked
/// before GNOME because Budgie sets `Budgie:GNOME`.
#[cfg(target_os = "linux")]
#[must_use]
pub fn parse_linux_desktop(xdg_current_desktop: &str) -> LinuxDesktop {
    for component in xdg_current_desktop.split(':') {
        match component {
            "KDE" => return LinuxDesktop::Kde,
            "Budgie" => return LinuxDesktop::Budgie,
            "GNOME" => return LinuxDesktop::Gnome,
            "XFCE" => return LinuxDesktop::Xfce,
            "X-Cinnamon" | "Cinnamon" => return LinuxDesktop::Cinnamon,
            "MATE" => return LinuxDesktop::Mate,
            "LXQt" => return LinuxDesktop::LxQt,
            "Hyprland" => return LinuxDesktop::Hyprland,
            "sway" => return LinuxDesktop::Sway,
            "river" => return LinuxDesktop::River,
            "niri" => return LinuxDesktop::Niri,
            "Wayfire" => return LinuxDesktop::Wayfire,
            "COSMIC" => return LinuxDesktop::CosmicDe,
            _ => {}
        }
    }
    LinuxDesktop::Unknown
}

/// Detect whether the system is using a dark color scheme.
///
/// Uses synchronous, platform-specific checks so the result is available
/// immediately at window creation time (before any async portal response).
///
/// # Caching
///
/// The result is cached after the first call and reused on subsequent calls.
/// Call [`invalidate_caches()`] to clear the cached value so the next call
/// re-queries the OS. For a fresh reading without affecting the cache, use
/// [`detect_is_dark()`] instead.
///
/// For live dark-mode tracking, use `watch::on_theme_change` (feature
/// `watch`): on each event call [`invalidate_caches()`] and re-read
/// [`crate::SystemTheme::from_system()`].
///
/// # Platform Behavior
///
/// - **Linux:** Checks `GTK_THEME` for `:dark` or `-dark`; on KDE (with the
///   `kde` feature) reads `kdeglobals`' background luminance; then
///   `gsettings` `color-scheme` (2-second timeout); then `kdeglobals` on
///   other desktops (with `kde`); finally `gtk-3.0/settings.ini`
///   `gtk-application-prefer-dark-theme`.
/// - **macOS:** Reads `AppleInterfaceStyle` via `NSUserDefaults` (with
///   `macos` feature) or `defaults` subprocess (without).
/// - **Windows:** Checks foreground color luminance from `UISettings` via
///   BT.601 coefficients (requires `windows` feature).
/// - **Other platforms / missing features:** Returns `false` (light).
#[must_use]
pub fn system_is_dark() -> bool {
    system().is_dark()
}

/// Reset all process-wide caches so the next call to [`system_is_dark()`],
/// [`prefers_reduced_motion()`], or
/// [`system_icon_theme()`](crate::theme::system_icon_theme) re-queries the OS; a
/// cached failure to detect the icon theme is cleared too.
///
/// Call this when you detect that the user has changed system settings (e.g.,
/// dark mode toggle, icon theme switch, accessibility preferences).
///
/// The `detect_*()` family of functions are unaffected — they always query
/// the OS directly.
pub fn invalidate_caches() {
    system().invalidate_all();
}

/// Detect whether the system is using a dark color scheme without caching.
///
/// Unlike [`system_is_dark()`], this function queries the OS every time it is
/// called and never caches the result. Use this when polling for theme changes
/// or implementing live dark-mode tracking.
///
/// See [`system_is_dark()`] for platform behavior details.
#[must_use]
pub fn detect_is_dark() -> bool {
    detect_is_dark_inner()
}

/// The longest pause between two polls of a running command.
#[cfg(target_os = "linux")]
const POLL_INTERVAL_CAP: std::time::Duration = std::time::Duration::from_millis(50);

/// The pauses between polls of a running command: 1 ms, doubling up to
/// [`POLL_INTERVAL_CAP`], so a command that exits in a few milliseconds is
/// seen to exit within a few milliseconds, and a slow one costs a poll per
/// 50 ms.
#[cfg(target_os = "linux")]
fn poll_intervals() -> impl Iterator<Item = std::time::Duration> {
    std::iter::successors(Some(std::time::Duration::from_millis(1)), |pause| {
        Some(pause.saturating_mul(2).min(POLL_INTERVAL_CAP))
    })
}

/// Run `program` with `args`, waiting up to `timeout` for it to exit.
///
/// Returns its stdout when it exits successfully; `None` when it cannot be
/// spawned, exits unsuccessfully or outlives `timeout`, in which case it
/// is killed. The command is polled at [`poll_intervals`]. A killed command
/// is reaped; one the kill fails on is left unreaped rather than waited
/// for, so `timeout` stays a bound on the call.
#[cfg(target_os = "linux")]
fn run_with_timeout(program: &str, args: &[&str], timeout: std::time::Duration) -> Option<String> {
    use std::io::Read;
    use std::time::Instant;

    let start = Instant::now();
    let mut child = std::process::Command::new(program)
        .args(args)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::null())
        .spawn()
        .ok()?;

    let mut intervals = poll_intervals();
    loop {
        match child.try_wait() {
            Ok(Some(status)) if status.success() => {
                let mut buf = String::new();
                if let Some(mut stdout) = child.stdout.take() {
                    let _ = stdout.read_to_string(&mut buf);
                }
                return Some(buf);
            }
            Ok(Some(_)) => return None,
            Ok(None) => {
                let elapsed = start.elapsed();
                if elapsed >= timeout {
                    if child.kill().is_ok() {
                        let _ = child.wait();
                    }
                    return None;
                }
                let pause = intervals.next().unwrap_or(POLL_INTERVAL_CAP);
                std::thread::sleep(pause.min(timeout.saturating_sub(elapsed)));
            }
            Err(_) => return None,
        }
    }
}

/// Run a gsettings command with a 2-second timeout.
///
/// Spawns `gsettings` with the given arguments, waits up to 2 seconds
/// for completion, and returns the trimmed stdout on success.  Returns
/// `None` if the command fails, times out, or produces empty output.
///
/// Used by [`detect_is_dark_inner()`] and [`crate::gnome::read_gsetting()`] to
/// prevent gsettings from blocking indefinitely when D-Bus is unresponsive.
#[cfg(target_os = "linux")]
fn run_gsettings_with_timeout(args: &[&str]) -> Option<String> {
    let out = run_with_timeout("gsettings", args, SUBPROCESS_TIMEOUT)?;
    let trimmed = out.trim();
    if trimmed.is_empty() {
        None
    } else {
        Some(trimmed.to_string())
    }
}

/// Read `Xft.dpi` from X resources via `xrdb -query`.
///
/// Returns `None` if xrdb is not installed, times out (2 seconds),
/// or the output does not contain a valid positive `Xft.dpi` value.
#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
fn read_xft_dpi() -> Option<f32> {
    let out = run_with_timeout("xrdb", &["-query"], SUBPROCESS_TIMEOUT)?;
    // Parse "Xft.dpi:\t96" from multi-line output
    for line in out.lines() {
        if let Some(rest) = line.strip_prefix("Xft.dpi:")
            && let Ok(dpi) = rest.trim().parse::<f32>()
            && dpi > 0.0
        {
            return Some(dpi);
        }
    }
    None
}

/// Detect physical DPI from display hardware via `xrandr`.
///
/// Parses the primary connected output's resolution and physical dimensions
/// to compute DPI. Falls back to the first connected output if no primary
/// is found. Returns `None` if `xrandr` is unavailable, times out (2 seconds),
/// or the output cannot be parsed.
///
/// This is a last-resort fallback: prefer `forceFontDPI` (KDE), `Xft.dpi`
/// (X resources) before calling this.
#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
fn detect_physical_dpi() -> Option<f32> {
    let out = run_with_timeout("xrandr", &[], SUBPROCESS_TIMEOUT)?;
    parse_xrandr_dpi(&out)
}

/// Parse DPI from xrandr output.
///
/// Looks for lines like:
/// ```text
/// DP-1 connected primary 3840x2160+0+0 (...) 700mm x 390mm
/// ```
/// Extracts the current resolution from the mode string and the physical
/// dimensions from the trailing `NNNmm x NNNmm`, then computes average DPI.
#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
fn parse_xrandr_dpi(output: &str) -> Option<f32> {
    // Prefer the primary output; fall back to the first connected output.
    let line = output
        .lines()
        .find(|l| l.contains(" connected") && l.contains("primary"))
        .or_else(|| {
            output
                .lines()
                .find(|l| l.contains(" connected") && !l.contains("disconnected"))
        })?;

    // Resolution: "3840x2160+0+0" (digits x digits + offset)
    let res_token = line
        .split_whitespace()
        .find(|s| s.contains('x') && s.contains('+'))?;
    let (w_str, rest) = res_token.split_once('x')?;
    let h_str = rest.split('+').next()?;
    let w_px: f32 = w_str.parse().ok()?;
    let h_px: f32 = h_str.parse().ok()?;

    // Physical size: "700mm x 390mm" at the end of the line
    let words: Vec<&str> = line.split_whitespace().collect();
    let mut w_mm = None;
    let mut h_mm = None;
    for window in words.windows(3) {
        let [prev, cur, next] = window else { continue };
        if *cur == "x" {
            w_mm = prev.strip_suffix("mm").and_then(|n| n.parse::<f32>().ok());
            h_mm = next.strip_suffix("mm").and_then(|n| n.parse::<f32>().ok());
        }
    }
    let w_mm = w_mm.filter(|&v| v > 0.0)?;
    let h_mm = h_mm.filter(|&v| v > 0.0)?;

    let h_dpi = w_px / (w_mm / 25.4);
    let v_dpi = h_px / (h_mm / 25.4);
    let avg = (h_dpi + v_dpi) / 2.0;

    if avg > 0.0 { Some(avg) } else { None }
}

#[cfg(all(test, target_os = "linux", any(feature = "kde", feature = "portal")))]
#[allow(clippy::unwrap_used)]
mod xrandr_dpi_tests {
    use super::parse_xrandr_dpi;

    #[test]
    fn primary_4k_display() {
        // Real xrandr output: 4K display at 700mm wide
        let output = "Screen 0: minimum 16 x 16, current 3840 x 2160, maximum 32767 x 32767\n\
                       DP-1 connected primary 3840x2160+0+0 (normal left inverted right x axis y axis) 700mm x 390mm\n\
                          3840x2160     60.00*+\n";
        let dpi = parse_xrandr_dpi(output).unwrap();
        // 3840/(700/25.4) = 139.3, 2160/(390/25.4) = 140.7, avg ~140
        assert!((dpi - 140.0).abs() < 1.0, "expected ~140 DPI, got {dpi}");
    }

    #[test]
    fn standard_1080p_display() {
        let output = "DP-2 connected primary 1920x1080+0+0 (normal) 530mm x 300mm\n";
        let dpi = parse_xrandr_dpi(output).unwrap();
        // 1920/(530/25.4) = 92.0, 1080/(300/25.4) = 91.4, avg ~91.7
        assert!((dpi - 92.0).abs() < 1.0, "expected ~92 DPI, got {dpi}");
    }

    #[test]
    fn no_primary_falls_back_to_first_connected() {
        let output = "HDMI-1 connected 1920x1080+0+0 (normal) 480mm x 270mm\n\
                       DP-1 disconnected\n";
        let dpi = parse_xrandr_dpi(output).unwrap();
        assert!(dpi > 90.0 && dpi < 110.0, "expected ~100 DPI, got {dpi}");
    }

    #[test]
    fn disconnected_only_returns_none() {
        let output = "DP-1 disconnected\nHDMI-1 disconnected\n";
        assert!(parse_xrandr_dpi(output).is_none());
    }

    #[test]
    fn missing_physical_dimensions_returns_none() {
        // No "NNNmm x NNNmm" in the line
        let output = "DP-1 connected primary 1920x1080+0+0 (normal)\n";
        assert!(parse_xrandr_dpi(output).is_none());
    }

    #[test]
    fn zero_mm_returns_none() {
        let output = "DP-1 connected primary 1920x1080+0+0 (normal) 0mm x 0mm\n";
        assert!(parse_xrandr_dpi(output).is_none());
    }

    #[test]
    fn empty_output_returns_none() {
        assert!(parse_xrandr_dpi("").is_none());
    }
}

/// Detect the font DPI for the current system.
///
/// Used by [`ThemeMode::into_resolved()`] as a fallback when no OS reader
/// has provided `font_dpi`. Returns the platform-appropriate DPI for
/// converting typographic points to logical pixels.
///
/// - **Linux, `kde` feature** (any desktop): `forceFontDPI` → `Xft.dpi` → xrandr → 96.0
/// - **Linux, `portal` feature without `kde`**: `Xft.dpi` → xrandr → 96.0; neither: 96.0
/// - **macOS**: 72.0 (Apple coordinate system: 1pt = 1px)
/// - **Windows**: 96.0, the Windows reader's `font_dpi`: a point is 96/72
///   logical (effective) pixels at any display scale
/// - **Other**: 96.0
#[allow(unreachable_code)]
fn detect_system_font_dpi() -> f32 {
    #[cfg(target_os = "macos")]
    {
        return 72.0;
    }

    #[cfg(all(target_os = "windows", feature = "windows"))]
    {
        return crate::windows::LOGICAL_DPI as f32;
    }

    // KDE: check forceFontDPI first (same chain as the KDE reader)
    #[cfg(all(target_os = "linux", feature = "kde"))]
    {
        if let Some(dpi) = read_kde_force_font_dpi() {
            return dpi;
        }
    }

    #[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
    {
        if let Some(dpi) = read_xft_dpi() {
            return dpi;
        }
        if let Some(dpi) = detect_physical_dpi() {
            return dpi;
        }
    }

    96.0
}

/// Read KDE's `forceFontDPI` from kdeglobals or kcmfontsrc.
///
/// This mirrors the first step of [`crate::kde::detect_font_dpi()`] so that
/// standalone preset loading (via [`ThemeMode::into_resolved()`]) uses the
/// same DPI as the full KDE reader pipeline.
#[cfg(all(target_os = "linux", feature = "kde"))]
fn read_kde_force_font_dpi() -> Option<f32> {
    // Try kdeglobals [General] forceFontDPI
    let path = crate::kde::kdeglobals_path();
    if let Ok(content) = std::fs::read_to_string(&path) {
        let mut ini = crate::kde::create_kde_parser();
        if ini.read(content).is_ok()
            && let Some(dpi_str) = ini.get("General", "forceFontDPI")
            && let Ok(dpi) = dpi_str.trim().parse::<f32>()
            && dpi > 0.0
        {
            return Some(dpi);
        }
    }
    // Try kcmfontsrc [General] forceFontDPI
    if let Some(dpi_str) = crate::kde::read_kcmfontsrc_key("General", "forceFontDPI")
        && let Ok(dpi) = dpi_str.trim().parse::<f32>()
        && dpi > 0.0
    {
        return Some(dpi);
    }
    None
}

/// Inner detection logic for [`system_is_dark()`].
///
/// Separated from the public function to allow caching.
#[allow(unreachable_code)]
fn detect_is_dark_inner() -> bool {
    #[cfg(target_os = "linux")]
    {
        // Check GTK_THEME env var (works across all GTK-based DEs)
        if let Ok(gtk_theme) = std::env::var("GTK_THEME") {
            let lower = gtk_theme.to_lowercase();
            if lower.ends_with(":dark") || lower.contains("-dark") {
                return true;
            }
        }

        // On KDE, read kdeglobals directly — gsettings color-scheme is
        // synced by xdg-desktop-portal-kde and can be stale or inverted.
        #[cfg(feature = "kde")]
        {
            let de = parse_linux_desktop(&xdg_current_desktop());
            if matches!(de, LinuxDesktop::Kde) {
                let path = crate::kde::kdeglobals_path();
                if let Ok(content) = std::fs::read_to_string(&path) {
                    let mut ini = crate::kde::create_kde_parser();
                    if ini.read(content).is_ok() {
                        return crate::kde::is_dark_theme(&ini);
                    }
                }
            }
        }

        // gsettings color-scheme (reliable on GNOME / GTK-based DEs)
        if let Some(val) =
            run_gsettings_with_timeout(&["get", "org.gnome.desktop.interface", "color-scheme"])
        {
            if val.contains("prefer-dark") {
                return true;
            }
            if val.contains("prefer-light") || val.contains("default") {
                return false;
            }
        }

        // Fallback: read KDE's kdeglobals background luminance (non-KDE DE
        // or when the KDE feature is disabled and the gsettings check above
        // returned no result).
        #[cfg(feature = "kde")]
        {
            let path = crate::kde::kdeglobals_path();
            if let Ok(content) = std::fs::read_to_string(&path) {
                let mut ini = crate::kde::create_kde_parser();
                if ini.read(content).is_ok() {
                    return crate::kde::is_dark_theme(&ini);
                }
            }
        }

        // Fallback: gtk-3.0/settings.ini for DEs that set the GTK dark preference
        let config_home = std::env::var("XDG_CONFIG_HOME").unwrap_or_else(|_| {
            let home = std::env::var("HOME").unwrap_or_default();
            format!("{home}/.config")
        });
        let ini_path = format!("{config_home}/gtk-3.0/settings.ini");
        if let Ok(content) = std::fs::read_to_string(&ini_path) {
            for line in content.lines() {
                let trimmed = line.trim();
                if trimmed.starts_with("gtk-application-prefer-dark-theme")
                    && let Some(val) = trimmed.split('=').nth(1)
                    && (val.trim() == "1" || val.trim().eq_ignore_ascii_case("true"))
                {
                    return true;
                }
            }
        }

        false
    }

    #[cfg(target_os = "macos")]
    {
        // AppleInterfaceStyle is "Dark" when dark mode is active.
        // The key is absent in light mode, so any failure means light.
        #[cfg(feature = "macos")]
        {
            use objc2_foundation::NSUserDefaults;
            let defaults = NSUserDefaults::standardUserDefaults();
            let key = objc2_foundation::ns_string!("AppleInterfaceStyle");
            if let Some(value) = defaults.stringForKey(key) {
                return value.to_string().eq_ignore_ascii_case("dark");
            }
            return false;
        }
        #[cfg(not(feature = "macos"))]
        {
            if let Ok(output) = std::process::Command::new("defaults")
                .args(["read", "-g", "AppleInterfaceStyle"])
                .output()
                && output.status.success()
            {
                let val = String::from_utf8_lossy(&output.stdout);
                return val.trim().eq_ignore_ascii_case("dark");
            }
            return false;
        }
    }

    #[cfg(target_os = "windows")]
    {
        #[cfg(feature = "windows")]
        {
            // BT.601 luminance: light foreground indicates dark background.
            let Ok(settings) = ::windows::UI::ViewManagement::UISettings::new() else {
                return false;
            };
            let Ok(fg) =
                settings.GetColorValue(::windows::UI::ViewManagement::UIColorType::Foreground)
            else {
                return false;
            };
            let luma = 0.299 * (fg.R as f32) + 0.587 * (fg.G as f32) + 0.114 * (fg.B as f32);
            return luma > 128.0;
        }
        #[cfg(not(feature = "windows"))]
        return false;
    }

    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
    {
        false
    }
}

/// Query whether the user prefers reduced motion.
///
/// Returns `true` when the OS accessibility setting indicates animations
/// should be reduced or disabled. Returns `false` (allow animations) on
/// unsupported platforms or when the query fails.
///
/// # Caching
///
/// The result is cached after the first call and reused on subsequent calls.
/// Call [`invalidate_caches()`] to clear the cached value so the next call
/// re-queries the OS. For live accessibility-change tracking, subscribe to
/// OS accessibility events and call `invalidate_caches()` when notified.
///
/// # Platform Behavior
///
/// - **Linux:** Queries `gsettings get org.gnome.desktop.interface enable-animations`.
///   Returns `true` when animations are disabled (`enable-animations` is `false`).
/// - **macOS:** Queries `NSWorkspace.accessibilityDisplayShouldReduceMotion`
///   (requires `macos` feature).
/// - **Windows:** Queries `UISettings.AnimationsEnabled()` (requires `windows` feature).
/// - **Other platforms:** Returns `false`.
///
/// # Examples
///
/// ```
/// let reduced = native_theme::detect::prefers_reduced_motion();
/// // On this platform, the result depends on OS accessibility settings.
/// // The function always returns a bool (false on unsupported platforms).
/// assert!(reduced == true || reduced == false);
/// ```
#[must_use]
pub fn prefers_reduced_motion() -> bool {
    system().prefers_reduced_motion()
}

/// Detect whether the user prefers reduced motion without caching.
///
/// Unlike [`prefers_reduced_motion()`], this function queries the OS every time
/// it is called and never caches the result. Use this when polling for
/// accessibility preference changes.
///
/// See [`prefers_reduced_motion()`] for platform behavior details.
#[must_use]
pub fn detect_reduced_motion() -> bool {
    detect_reduced_motion_inner()
}

/// Inner detection logic for [`prefers_reduced_motion()`].
///
/// Separated from the public function to allow caching.
#[allow(unreachable_code)]
fn detect_reduced_motion_inner() -> bool {
    #[cfg(target_os = "linux")]
    {
        // gsettings boolean output is bare "true\n" or "false\n" (no quotes)
        // enable-animations has INVERTED semantics: false => reduced motion preferred
        if let Some(val) =
            run_gsettings_with_timeout(&["get", "org.gnome.desktop.interface", "enable-animations"])
        {
            return val.trim() == "false";
        }
        false
    }

    #[cfg(target_os = "macos")]
    {
        #[cfg(feature = "macos")]
        {
            let workspace = objc2_app_kit::NSWorkspace::sharedWorkspace();
            // Direct semantics: true = reduce motion preferred (no inversion needed)
            return workspace.accessibilityDisplayShouldReduceMotion();
        }
        #[cfg(not(feature = "macos"))]
        return false;
    }

    #[cfg(target_os = "windows")]
    {
        #[cfg(feature = "windows")]
        {
            let Ok(settings) = ::windows::UI::ViewManagement::UISettings::new() else {
                return false;
            };
            // AnimationsEnabled has INVERTED semantics: false => reduced motion preferred
            return match settings.AnimationsEnabled() {
                Ok(enabled) => !enabled,
                Err(_) => false,
            };
        }
        #[cfg(not(feature = "windows"))]
        return false;
    }

    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
    {
        false
    }
}

// === DetectionContext ===

/// Process-wide detection cache.
///
/// Provides "cache on first read" semantics for OS detection queries
/// (`is_dark`, `reduced_motion`, `icon_theme`, `linux_desktop`) and
/// per-field invalidation for watchers that need fresh data.
///
/// Obtain the process-wide instance via [`system()`].
///
/// # Thread Safety
///
/// All reads and invalidations are lock-free (backed by
/// [`arc_swap::ArcSwapOption`]).
pub struct DetectionContext {
    is_dark: ArcSwapOption<bool>,
    reduced_motion: ArcSwapOption<bool>,
    icon_theme: ArcSwapOption<Result<String, crate::model::icons::IconThemeFailure>>,
    #[cfg(target_os = "linux")]
    linux_desktop: ArcSwapOption<LinuxDesktop>,
}

impl DetectionContext {
    /// Create an empty context with no cached values.
    fn new() -> Self {
        Self {
            is_dark: ArcSwapOption::empty(),
            reduced_motion: ArcSwapOption::empty(),
            icon_theme: ArcSwapOption::empty(),
            #[cfg(target_os = "linux")]
            linux_desktop: ArcSwapOption::empty(),
        }
    }

    /// Whether the system is using a dark color scheme (cached).
    ///
    /// The first call queries the OS and caches the result.
    /// Subsequent calls return the cached value.
    /// Call [`invalidate_is_dark()`](Self::invalidate_is_dark) to
    /// force a re-read on the next call.
    #[must_use]
    pub fn is_dark(&self) -> bool {
        if let Some(v) = self.is_dark.load().as_deref() {
            return *v;
        }
        let value = detect_is_dark_inner();
        self.is_dark.store(Some(Arc::new(value)));
        value
    }

    /// Whether the user prefers reduced motion (cached).
    ///
    /// The first call queries the OS and caches the result.
    /// Call [`invalidate_reduced_motion()`](Self::invalidate_reduced_motion)
    /// to force a re-read.
    #[must_use]
    pub fn prefers_reduced_motion(&self) -> bool {
        if let Some(v) = self.reduced_motion.load().as_deref() {
            return *v;
        }
        let value = detect_reduced_motion_inner();
        self.reduced_motion.store(Some(Arc::new(value)));
        value
    }

    /// The current icon theme name (cached), or why none was detected.
    ///
    /// The first call detects the theme from the OS and caches the
    /// outcome, a failure included, so a failed detection is not
    /// repeated on every call; subsequent calls return the cached
    /// outcome. Call
    /// [`invalidate_icon_theme()`](Self::invalidate_icon_theme) to
    /// force a re-read.
    ///
    /// # Errors
    ///
    /// As [`system_icon_theme()`](crate::theme::system_icon_theme): no
    /// theme stands in for one that could not be detected.
    pub fn icon_theme(&self) -> crate::Result<String> {
        self.icon_theme_with(detect_icon_theme_inner)
    }

    /// [`icon_theme()`](Self::icon_theme), with `detect` run where
    /// nothing is cached.
    fn icon_theme_with(
        &self,
        detect: impl FnOnce() -> Result<String, crate::model::icons::IconThemeFailure>,
    ) -> crate::Result<String> {
        let outcome = match self.icon_theme.load_full() {
            Some(cached) => cached,
            None => {
                let detected = Arc::new(detect());
                self.icon_theme.store(Some(Arc::clone(&detected)));
                detected
            }
        };
        match outcome.as_ref() {
            Ok(theme) => Ok(theme.clone()),
            Err(failure) => Err(failure.to_error()),
        }
    }

    /// The current Linux desktop environment (cached).
    ///
    /// The first call reads `XDG_CURRENT_DESKTOP` and caches the
    /// result. Call
    /// [`invalidate_linux_desktop()`](Self::invalidate_linux_desktop)
    /// to force a re-read.
    #[cfg(target_os = "linux")]
    #[must_use]
    pub fn linux_desktop(&self) -> LinuxDesktop {
        if let Some(v) = self.linux_desktop.load().as_deref() {
            return *v;
        }
        let value = detect_linux_desktop();
        self.linux_desktop.store(Some(Arc::new(value)));
        value
    }

    /// Clear the cached dark-mode value.
    pub fn invalidate_is_dark(&self) {
        self.is_dark.store(None);
    }

    /// Clear the cached reduced-motion value.
    pub fn invalidate_reduced_motion(&self) {
        self.reduced_motion.store(None);
    }

    /// Clear the cached icon theme, or the cached failure to detect one.
    pub fn invalidate_icon_theme(&self) {
        self.icon_theme.store(None);
    }

    /// Clear the cached Linux desktop environment.
    #[cfg(target_os = "linux")]
    pub fn invalidate_linux_desktop(&self) {
        self.linux_desktop.store(None);
    }

    /// Clear all cached values.
    pub fn invalidate_all(&self) {
        self.invalidate_is_dark();
        self.invalidate_reduced_motion();
        self.invalidate_icon_theme();
        #[cfg(target_os = "linux")]
        self.invalidate_linux_desktop();
    }
}

/// Return the process-wide default [`DetectionContext`].
///
/// This is a lazily-initialized singleton. The first call creates it;
/// all subsequent calls return the same instance.
pub fn system() -> &'static DetectionContext {
    static INSTANCE: std::sync::OnceLock<DetectionContext> = std::sync::OnceLock::new();
    INSTANCE.get_or_init(DetectionContext::new)
}

/// Inner icon theme detection, delegating to platform-specific logic.
///
/// On Linux, dispatches by desktop environment. On macOS/iOS/Windows,
/// returns the compile-time constant; elsewhere, the platform's failure.
fn detect_icon_theme_inner() -> Result<String, crate::model::icons::IconThemeFailure> {
    crate::model::icons::detect_icon_theme_outcome()
}

// === Crate-internal accessors ===

/// Run `gsettings get <schema> <key>` with timeout.
#[cfg(all(target_os = "linux", feature = "portal"))]
pub(crate) fn gsettings_get(schema: &str, key: &str) -> Option<String> {
    run_gsettings_with_timeout(&["get", schema, key])
}

/// Read Xft.dpi from X resources.
#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
pub(crate) fn xft_dpi() -> Option<f32> {
    read_xft_dpi()
}

/// Detect physical DPI from xrandr.
#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
pub(crate) fn physical_dpi() -> Option<f32> {
    detect_physical_dpi()
}

/// Detect the system font DPI (combining multiple sources).
pub(crate) fn system_font_dpi() -> f32 {
    detect_system_font_dpi()
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod reduced_motion_tests {
    use super::*;

    #[test]
    fn prefers_reduced_motion_smoke_test() {
        // Smoke test: function should not panic on any platform.
        // Cannot assert a specific value because caching preserves the first call
        // and CI environments have varying accessibility settings.
        let _result = prefers_reduced_motion();
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn detect_reduced_motion_inner_linux() {
        // Bypass caching to test actual detection logic.
        // On CI without gsettings, returns false (animations enabled).
        // On developer machines, depends on accessibility settings.
        let result = detect_reduced_motion_inner();
        // Just verify it returns a bool without panicking.
        let _ = result;
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn detect_reduced_motion_inner_macos() {
        let result = detect_reduced_motion_inner();
        let _ = result;
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn detect_reduced_motion_inner_windows() {
        let result = detect_reduced_motion_inner();
        let _ = result;
    }
}

#[cfg(test)]
mod detection_context_tests {
    use super::*;

    #[test]
    fn system_returns_same_instance() {
        let a = system() as *const DetectionContext;
        let b = system() as *const DetectionContext;
        assert_eq!(a, b);
    }

    #[test]
    fn is_dark_caches_result() {
        let ctx = DetectionContext::new();
        let first = ctx.is_dark();
        let second = ctx.is_dark();
        assert_eq!(first, second);
    }

    #[test]
    fn invalidate_is_dark_clears_cache() {
        let ctx = DetectionContext::new();
        let _ = ctx.is_dark(); // populate cache
        ctx.invalidate_is_dark();
        // After invalidation, next call re-queries (we just verify it doesn't panic)
        let _ = ctx.is_dark();
    }

    #[test]
    fn prefers_reduced_motion_caches_result() {
        let ctx = DetectionContext::new();
        let first = ctx.prefers_reduced_motion();
        let second = ctx.prefers_reduced_motion();
        assert_eq!(first, second);
    }

    #[test]
    fn invalidate_all_clears_all_caches() {
        let ctx = DetectionContext::new();
        let _ = ctx.is_dark();
        let _ = ctx.prefers_reduced_motion();
        let _ = ctx.icon_theme();
        ctx.invalidate_all();
        // Re-read all without panic
        let _ = ctx.is_dark();
        let _ = ctx.prefers_reduced_motion();
        let _ = ctx.icon_theme();
    }

    fn undetected() -> Result<String, crate::model::icons::IconThemeFailure> {
        Err(crate::model::icons::IconThemeFailure::for_tests(
            "the test's failing detection",
        ))
    }

    #[test]
    fn a_failed_icon_theme_detection_is_cached_and_reported() {
        let ctx = DetectionContext::new();
        let runs = std::cell::Cell::new(0);
        let detect = || {
            runs.set(runs.get() + 1);
            undetected()
        };
        let first = ctx.icon_theme_with(detect);
        let second = ctx.icon_theme_with(detect);
        assert_eq!(runs.get(), 1, "a failed detection ran again");
        for outcome in [first, second] {
            match outcome {
                Ok(name) => panic!("a failed detection gave the theme {name}"),
                Err(e) => assert!(
                    e.to_string().contains("the test's failing detection"),
                    "got: {e}"
                ),
            }
        }
    }

    #[test]
    fn invalidate_icon_theme_clears_a_cached_failure() {
        let ctx = DetectionContext::new();
        assert!(ctx.icon_theme_with(undetected).is_err());
        ctx.invalidate_icon_theme();
        let theme = ctx.icon_theme_with(|| Ok("breeze".to_string()));
        assert_eq!(theme.ok().as_deref(), Some("breeze"));
    }

    #[test]
    fn invalidate_all_clears_a_cached_failure() {
        let ctx = DetectionContext::new();
        assert!(ctx.icon_theme_with(undetected).is_err());
        ctx.invalidate_all();
        let theme = ctx.icon_theme_with(|| Ok("breeze".to_string()));
        assert_eq!(theme.ok().as_deref(), Some("breeze"));
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn linux_desktop_caches_result() {
        let ctx = DetectionContext::new();
        let first = ctx.linux_desktop();
        let second = ctx.linux_desktop();
        assert_eq!(first, second);
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn invalidate_linux_desktop_clears_cache() {
        let ctx = DetectionContext::new();
        let _ = ctx.linux_desktop();
        ctx.invalidate_linux_desktop();
        let _ = ctx.linux_desktop(); // re-reads without panic
    }
}

#[cfg(all(test, target_os = "linux"))]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod subprocess_tests {
    use super::*;
    use std::path::PathBuf;
    use std::time::{Duration, Instant};

    /// Whether `program` is an executable file in a `$PATH` directory.
    fn on_path(program: &str) -> bool {
        std::env::var_os("PATH")
            .is_some_and(|path| std::env::split_paths(&path).any(|dir| dir.join(program).is_file()))
    }

    #[test]
    fn poll_intervals_double_from_1_ms_up_to_50_ms() {
        let intervals: Vec<Duration> = poll_intervals().take(10).collect();
        let expected: Vec<Duration> = [1, 2, 4, 8, 16, 32, 50, 50, 50, 50]
            .into_iter()
            .map(Duration::from_millis)
            .collect();
        assert_eq!(intervals, expected);
    }

    #[test]
    fn run_with_timeout_returns_stdout_of_a_successful_command() {
        if !on_path("echo") {
            eprintln!("skipped: echo is not installed");
            return;
        }
        let out = run_with_timeout("echo", &["hi"], SUBPROCESS_TIMEOUT);
        assert_eq!(out.as_deref().map(str::trim), Some("hi"));
    }

    #[test]
    fn run_with_timeout_returns_none_for_a_failing_command() {
        if !on_path("false") {
            eprintln!("skipped: false is not installed");
            return;
        }
        assert_eq!(run_with_timeout("false", &[], SUBPROCESS_TIMEOUT), None);
    }

    #[test]
    fn run_with_timeout_returns_none_for_a_missing_program() {
        assert_eq!(
            run_with_timeout("nt-test-no-such-program", &[], SUBPROCESS_TIMEOUT),
            None
        );
    }

    /// A command that exits at once with no output gives an empty stdout;
    /// the time it took is printed (the schedule test is the timing proof).
    #[test]
    fn run_with_timeout_returns_the_empty_stdout_of_a_quiet_command() {
        if !on_path("true") {
            eprintln!("skipped: true is not installed");
            return;
        }
        let start = Instant::now();
        assert_eq!(
            run_with_timeout("true", &[], SUBPROCESS_TIMEOUT).as_deref(),
            Some("")
        );
        eprintln!("`true` ran in {:?}", start.elapsed());
    }

    #[test]
    fn run_with_timeout_kills_a_command_that_outlives_the_timeout() {
        if !on_path("sleep") {
            eprintln!("skipped: sleep is not installed");
            return;
        }
        let seconds = format!("5.{}", std::process::id());
        let start = Instant::now();
        let out = run_with_timeout("sleep", &[&seconds], Duration::from_millis(100));
        let elapsed = start.elapsed();
        assert_eq!(out, None);
        assert!(elapsed < Duration::from_secs(1), "took {elapsed:?}");
        let cmdline = format!("sleep\0{seconds}\0");
        let still_running: Vec<PathBuf> = std::fs::read_dir("/proc")
            .unwrap()
            .flatten()
            .map(|entry| entry.path().join("cmdline"))
            .filter(|path| std::fs::read(path).is_ok_and(|bytes| bytes == cmdline.as_bytes()))
            .collect();
        assert!(still_running.is_empty(), "not killed: {still_running:?}");
    }
}