native-theme 0.7.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
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
//! OS detection: dark mode, reduced motion, accessibility preferences, icon
//! theme and set, desktop environment.

use arc_swap::ArcSwapOption;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};

mod icon_theme;

pub(crate) use icon_theme::IconThemeFailure;
pub use icon_theme::{detect_icon_theme, system_icon_set, system_icon_theme};

/// Timeout for subprocess commands ([`run_with_timeout`]: gsettings,
/// xfconf-query, fc-match, macOS `defaults`).
///
/// Prevents D-Bus-dependent tools from blocking indefinitely when the
/// session bus is unresponsive or the display server is unavailable.
#[cfg(unix)]
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
pub(crate) 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
}

/// The desktop a theme is read by: `raw` ([`parse_linux_desktop`] of
/// `XDG_CURRENT_DESKTOP`) where it names one; for `Unknown`, the desktop of
/// the portal backend (`portal_backend`), else KDE where `kdeglobals_exists`,
/// else `Unknown`. The reader, the theme watcher and the icon-theme
/// detection all decide by it ([`DetectionContext::refined_linux_desktop`]),
/// so they agree. `kdeglobals_exists` is asked only where nothing before it
/// decides.
#[cfg(target_os = "linux")]
pub(crate) fn refine_linux_desktop(
    raw: LinuxDesktop,
    portal_backend: Option<LinuxDesktop>,
    kdeglobals_exists: impl FnOnce() -> bool,
) -> LinuxDesktop {
    refine_desktop(raw, portal_backend, kdeglobals_exists).desktop
}

/// A refined desktop ([`refine_linux_desktop`]), and whether only
/// `kdeglobals` named it.
#[cfg(target_os = "linux")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct RefinedDesktop {
    /// The desktop.
    pub(crate) desktop: LinuxDesktop,
    /// KDE named by the user's `kdeglobals` alone: `XDG_CURRENT_DESKTOP`
    /// names no desktop and no portal backend answered.
    pub(crate) by_kdeglobals: bool,
}

/// [`refine_linux_desktop`], with what named the desktop.
#[cfg(target_os = "linux")]
pub(crate) fn refine_desktop(
    raw: LinuxDesktop,
    portal_backend: Option<LinuxDesktop>,
    kdeglobals_exists: impl FnOnce() -> bool,
) -> RefinedDesktop {
    let (desktop, by_kdeglobals) = match (raw, portal_backend) {
        (LinuxDesktop::Unknown, Some(backend)) => (backend, false),
        (LinuxDesktop::Unknown, None) if kdeglobals_exists() => (LinuxDesktop::Kde, true),
        (other, _) => (other, false),
    };
    RefinedDesktop {
        desktop,
        by_kdeglobals,
    }
}

/// Whether the user's `kdeglobals` exists, with the `kde` feature; `false`
/// without it, as no KDE file is read then.
#[cfg(target_os = "linux")]
fn kdeglobals_exists() -> bool {
    #[cfg(feature = "kde")]
    {
        crate::kde::kdeglobals_path().is_some_and(|path| path.exists())
    }
    #[cfg(not(feature = "kde"))]
    {
        false
    }
}

/// 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; the desktop the KDE reader is chosen by, so an
///   unrecognised one with a KDE portal backend or a `kdeglobals` counts)
///   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()`], [`accessibility_preferences()`], or
/// [`system_icon_theme()`] re-queries the OS; a cached failure to detect the
/// icon theme is cleared too, and so, on Linux, is the detected desktop
/// environment, with the desktop refined from it. The font DPI is not cached:
/// since 0.7.1 it is a constant per platform, which
/// [`ResolutionContext::from_system()`](crate::ResolutionContext::from_system) uses.
///
/// 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. The installed freedesktop icon themes are not re-read:
/// the icon lookup reads them once per process, and so do
/// [`is_freedesktop_theme_available()`](crate::icons::is_freedesktop_theme_available)
/// and [`list_freedesktop_themes()`](crate::icons::list_freedesktop_themes).
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(unix)]
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
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(unix)]
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
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` and its stdin closed, waiting up to `timeout`
/// for it to exit and for its stdout and stderr to close.
///
/// Its output is what [`std::process::Command::output`] gives, an
/// unsuccessful exit included. Both pipes are read while the command runs,
/// each on a thread of its own, so a command that prints more than a pipe
/// holds (65,536 bytes on Linux, pipe(7)) is not stalled until it is
/// killed. The error is the spawn's, a reader thread's that cannot be
/// started, or one of kind [`std::io::ErrorKind::TimedOut`] when the command
/// outlives `timeout` or a process it started still holds its output open
/// at `timeout`. A command that has not exited is killed and reaped on
/// every error; one the kill fails on is left unreaped rather than waited
/// for, and a reader still blocked at `timeout` is left to end when the pipe
/// closes, so `timeout` stays a bound on the call. The command is polled at
/// [`poll_intervals`].
#[cfg(unix)]
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
pub(crate) fn run_with_timeout(
    program: &str,
    args: &[&str],
    timeout: std::time::Duration,
) -> std::io::Result<std::process::Output> {
    use std::process::{Child, Command, Stdio};
    use std::sync::mpsc::{Receiver, RecvTimeoutError};
    use std::time::Instant;

    fn kill_and_reap(child: &mut Child) {
        if child.kill().is_ok() {
            let _ = child.wait();
        }
    }

    let timed_out = || {
        std::io::Error::new(
            std::io::ErrorKind::TimedOut,
            format!("timed out after {timeout:?}"),
        )
    };

    let start = Instant::now();
    let mut child = Command::new(program)
        .args(args)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()?;
    let readers = read_on_a_thread(child.stdout.take())
        .and_then(|stdout| Ok((stdout, read_on_a_thread(child.stderr.take())?)));
    let (stdout, stderr) = match readers {
        Ok(readers) => readers,
        Err(e) => {
            kill_and_reap(&mut child);
            return Err(e);
        }
    };

    let mut intervals = poll_intervals();
    let status = loop {
        match child.try_wait() {
            Ok(Some(status)) => break status,
            Ok(None) => {
                let elapsed = start.elapsed();
                if elapsed >= timeout {
                    kill_and_reap(&mut child);
                    return Err(timed_out());
                }
                let pause = intervals.next().unwrap_or(POLL_INTERVAL_CAP);
                std::thread::sleep(pause.min(timeout.saturating_sub(elapsed)));
            }
            Err(e) => {
                kill_and_reap(&mut child);
                return Err(e);
            }
        }
    };

    let received = |reader: Receiver<Vec<u8>>| {
        reader
            .recv_timeout(timeout.saturating_sub(start.elapsed()))
            .map_err(|e| match e {
                RecvTimeoutError::Timeout => timed_out(),
                RecvTimeoutError::Disconnected => {
                    std::io::Error::other("the output reader stopped without a result")
                }
            })
    };
    Ok(std::process::Output {
        status,
        stdout: received(stdout)?,
        stderr: received(stderr)?,
    })
}

/// Read `pipe` to its end on a new thread, which sends what it read; an
/// absent pipe is read as empty. The error is the thread's spawn error.
#[cfg(unix)]
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
fn read_on_a_thread(
    pipe: Option<impl std::io::Read + Send + 'static>,
) -> std::io::Result<std::sync::mpsc::Receiver<Vec<u8>>> {
    let (sender, receiver) = std::sync::mpsc::channel();
    match pipe {
        Some(mut pipe) => {
            std::thread::Builder::new()
                .name("native-theme-subprocess-output".to_string())
                .spawn(move || {
                    let mut read = Vec::new();
                    let _ = pipe.read_to_end(&mut read);
                    let _ = sender.send(read);
                })?;
        }
        None => {
            let _ = sender.send(Vec::new());
        }
    }
    Ok(receiver)
}

/// The stdout of `program` run with `args` ([`run_with_timeout`]) when it
/// exits successfully within `timeout` and prints UTF-8; `None` otherwise.
#[cfg(unix)]
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
pub(crate) fn stdout_with_timeout(
    program: &str,
    args: &[&str],
    timeout: std::time::Duration,
) -> Option<String> {
    let output = run_with_timeout(program, args, timeout).ok()?;
    if !output.status.success() {
        return None;
    }
    String::from_utf8(output.stdout).ok()
}

/// The user's config directory: `$XDG_CONFIG_HOME`, else `$HOME/.config`;
/// `None` without either ([`xdg_config_home_from`] of the environment).
#[cfg(target_os = "linux")]
pub(crate) fn xdg_config_home() -> Option<std::path::PathBuf> {
    xdg_config_home_from(
        std::env::var_os("XDG_CONFIG_HOME").as_deref(),
        std::env::var_os("HOME").as_deref(),
    )
}

/// The config directory `$XDG_CONFIG_HOME` (`var`) names: itself when it is
/// absolute, else `<home>/.config` when `home` is non-empty, else `None`.
///
/// The XDG Base Directory Specification 0.8: "If `$XDG_CONFIG_HOME` is
/// either not set or empty, a default equal to `$HOME/.config` should be
/// used", and "All paths set in these environment variables must be
/// absolute. If an implementation encounters a relative path in any of
/// these variables it should consider the path invalid and ignore it"
/// (<https://specifications.freedesktop.org/basedir-spec/0.8/>).
#[cfg(target_os = "linux")]
fn xdg_config_home_from(
    var: Option<&std::ffi::OsStr>,
    home: Option<&std::ffi::OsStr>,
) -> Option<std::path::PathBuf> {
    var.map(std::path::PathBuf::from)
        .filter(|dir| dir.is_absolute())
        .or_else(|| {
            home.filter(|home| !home.is_empty())
                .map(|home| std::path::Path::new(home).join(".config"))
        })
}

/// Why [`xdg_config_home`] is `None`.
#[cfg(target_os = "linux")]
pub(crate) const CONFIG_HOME_UNRESOLVED: &str = "the config directory is unresolved: \
    $XDG_CONFIG_HOME is not an absolute path and $HOME is unset or empty";

/// Run `gsettings get <schema> <key>`, waiting up to `timeout`.
///
/// Returns the trimmed stdout on success; `None` if the command fails, times
/// out, or produces empty output. The timeout keeps gsettings from blocking
/// indefinitely when D-Bus is unresponsive.
#[cfg(target_os = "linux")]
pub(crate) fn gsettings_get(
    schema: &str,
    key: &str,
    timeout: std::time::Duration,
) -> Option<String> {
    let out = stdout_with_timeout("gsettings", &["get", schema, key], timeout)?;
    let trimmed = out.trim();
    if trimmed.is_empty() {
        None
    } else {
        Some(trimmed.to_string())
    }
}

/// The font DPI on every Linux desktop: 96. The toolkit's scale factor
/// already carries the display's scale: gpui and winit take it from the
/// compositor on Wayland (gpui-pre-linux 0.3.12
/// `src/linux/wayland/window.rs:1218-1222`; winit 0.30.13
/// `src/platform_impl/linux/wayland/types/wp_fractional_scaling.rs:71-72`) and
/// from `Xft.dpi` / 96 on X11 (gpui-pre-linux `src/linux/x11/client.rs:2674-2681`;
/// winit `src/platform_impl/linux/x11/util/randr.rs:40-53`, `:145-151`), and
/// Plasma writes `Xft.dpi` on Wayland as the largest output's scale × 96, so a
/// font DPI taken from `Xft.dpi` scaled text a second time. Qt lays a point
/// out at a logical DPI of 96 on both (qtbase v6.10.1 `qwaylandscreen.cpp:149-160`,
/// `qhighdpiscaling.cpp:241-256`, `:362-383`); GNOME at a fixed 96
/// (`DPI_FALLBACK`, gnome-settings-daemon 51.0
/// `plugins/xsettings/gsd-xsettings-manager.c:243`, `:583-595`; GTK 4.24.1
/// `gdk/wayland/gdksettings-wayland.c:166-168`), its text-scaling factor
/// carried in
/// [`AccessibilityPreferences::text_scaling_factor`](crate::AccessibilityPreferences::text_scaling_factor)
/// on Wayland and in the toolkit's `Xft.dpi` scale factor on X11
/// (`docs/issues/0004_kde-hand-overrides-rationale.md` §4.1).
#[cfg(target_os = "linux")]
pub(crate) const LINUX_FONT_DPI: f32 = 96.0;

/// The font DPI of the platform, at which a point size becomes logical pixels.
///
/// Used, through [`system_font_dpi`], by
/// [`ResolutionContext::from_system()`](crate::ResolutionContext::from_system)
/// where no OS reader has provided `font_dpi`. A constant per platform since
/// 0.7.1: nothing is read.
///
/// - **Linux**, every desktop: 96.0 (`LINUX_FONT_DPI`)
/// - **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;
    }

    #[cfg(target_os = "linux")]
    {
        return LINUX_FONT_DPI;
    }

    96.0
}

/// The session type, `$XDG_SESSION_TYPE` (`x11`, `wayland`, …).
#[cfg(all(target_os = "linux", feature = "portal"))]
pub(crate) fn session_type() -> Option<String> {
    std::env::var("XDG_SESSION_TYPE").ok()
}

/// Whether the colour scheme is dark: the portal's answer when it gave one,
/// else gsettings' `org.gnome.desktop.interface` `color-scheme` read through
/// `gsetting` (`prefer-dark` dark; `prefer-light` and `default` light);
/// `None` when neither answers. [`detect_is_dark`] (no portal) and the GNOME
/// reader both decide through it, so the two cannot disagree.
#[cfg(target_os = "linux")]
pub(crate) fn color_scheme_is_dark(
    portal: Option<bool>,
    gsetting: impl FnOnce(&str, &str) -> Option<String>,
) -> Option<bool> {
    if portal.is_some() {
        return portal;
    }
    let val = gsetting("org.gnome.desktop.interface", "color-scheme")?;
    if val.contains("prefer-dark") {
        Some(true)
    } else if val.contains("prefer-light") || val.contains("default") {
        Some(false)
    } else {
        None
    }
}

/// Dark or light from the desktop's settings: on KDE (`detection`'s refined
/// desktop, the one the KDE reader is chosen by) `kdeglobals` first, as
/// gsettings `color-scheme` is synced by xdg-desktop-portal-kde and can be
/// stale or inverted; elsewhere gsettings (reliable on GNOME and GTK-based
/// desktops), then `kdeglobals`' background luminance.
#[cfg(target_os = "linux")]
fn desktop_is_dark(
    detection: &DetectionContext,
    kdeglobals: impl FnOnce() -> Option<bool>,
    gsettings: impl FnOnce() -> Option<bool>,
) -> Option<bool> {
    if detection.refined_linux_desktop_sync() == LinuxDesktop::Kde {
        kdeglobals().or_else(gsettings)
    } else {
        gsettings().or_else(kdeglobals)
    }
}

/// Inner detection logic for [`system_is_dark()`].
///
/// Separated from the public function to allow caching.
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;
            }
        }

        if let Some(dark) = desktop_is_dark(
            system(),
            || {
                #[cfg(feature = "kde")]
                {
                    crate::kde::kdeglobals_is_dark()
                }
                #[cfg(not(feature = "kde"))]
                {
                    None
                }
            },
            || {
                color_scheme_is_dark(None, |schema, key| {
                    gsettings_get(schema, key, SUBPROCESS_TIMEOUT)
                })
            },
        ) {
            return dark;
        }

        // Fallback: gtk-3.0/settings.ini for DEs that set the GTK dark preference
        if let Some(content) = xdg_config_home()
            .and_then(|dir| std::fs::read_to_string(dir.join("gtk-3.0/settings.ini")).ok())
        {
            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");
            defaults
                .stringForKey(key)
                .is_some_and(|value| value.to_string().eq_ignore_ascii_case("dark"))
        }
        #[cfg(not(feature = "macos"))]
        {
            stdout_with_timeout(
                "defaults",
                &["read", "-g", "AppleInterfaceStyle"],
                SUBPROCESS_TIMEOUT,
            )
            .is_some_and(|value| value.trim().eq_ignore_ascii_case("dark"))
        }
    }

    #[cfg(target_os = "windows")]
    {
        #[cfg(feature = "windows")]
        {
            let Ok(settings) = ::windows::UI::ViewManagement::UISettings::new() else {
                return false;
            };
            let Ok(fg) =
                settings.GetColorValue(::windows::UI::ViewManagement::UIColorType::Foreground)
            else {
                return false;
            };
            crate::windows::is_dark_mode(&crate::windows::win_color_to_rgba(fg))
        }
        #[cfg(not(feature = "windows"))]
        {
            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
///
/// Each platform's read is the one its theme reader makes, so the result is
/// the `reduce_motion` of
/// [`AccessibilityPreferences::from_system`](crate::AccessibilityPreferences::from_system)
/// and of [`SystemTheme::from_system`](crate::SystemTheme::from_system)'s
/// accessibility block.
///
/// - **Linux:** by the desktop the reader is chosen by. KDE (with the `kde`
///   feature): `kdeglobals`' `[KDE] AnimationDurationFactor` is 0. GNOME and
///   Budgie: the portal's `reduced-motion` (with the `portal` feature, 2-second
///   deadline), else `gsettings get org.gnome.desktop.interface enable-animations`
///   is `false` (2-second timeout). Other desktops, and KDE without the `kde`
///   feature: that gsettings key alone.
/// - **macOS:** Queries `NSWorkspace.accessibilityDisplayShouldReduceMotion`
///   (requires `macos` feature).
/// - **Windows:** Queries `SystemParametersInfoW(SPI_GETCLIENTAREAANIMATION)`;
///   `true` when client-area animations are off (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()
}

/// The OS accessibility preferences (cached): what
/// [`AccessibilityPreferences::from_system`](crate::AccessibilityPreferences::from_system)
/// reads, without running the platform reader again.
///
/// The cache holds the accessibility block of the last platform reader run:
/// [`SystemTheme::from_system`](crate::SystemTheme::from_system) and
/// `from_system_async` fill it, and where neither has run since the last
/// [`invalidate_caches()`], the first call runs the reader itself.
/// [`invalidate_caches()`] clears it. A reader that fails is not reported:
/// the preferences used without a reader (the defaults, with the platform's
/// [`detect_reduced_motion()`]) stay cached until the next invalidation, as a
/// failure to detect the icon theme does.
///
/// For a preset switch, where the OS preferences apply under the preset and
/// the reader has usually just run. The theme watcher
/// (`watch::on_theme_change`) reports a change of every accessibility setting
/// the reader reads but one, Windows' high contrast, which Windows announces
/// only to top-level windows, as it does the non-client fonts; nothing clears
/// the cache when it changes. That holds from Windows 10 2004: before it the
/// watcher has no `AnimationsEnabledChanged`, so a reduced-motion change is
/// not reported either (and before 1703, with no
/// `AdvancedEffectsEnabledChanged`, a transparency change). Where the current
/// setting matters more than the cost, read [`AccessibilityPreferences::from_system`](crate::AccessibilityPreferences::from_system),
/// which runs the reader every time.
#[must_use]
pub fn accessibility_preferences() -> crate::AccessibilityPreferences {
    system().accessibility_preferences()
}

/// Whether GNOME asks for reduced motion: the portal's answer when it gave
/// one, else gsettings' `org.gnome.desktop.interface` `enable-animations`
/// read through `gsetting` (`false` is reduced motion); `None` when neither
/// answers. [`detect_reduced_motion`] and the GNOME reader both decide
/// through it.
#[cfg(target_os = "linux")]
pub(crate) fn gnome_reduce_motion(
    portal: Option<bool>,
    gsetting: impl FnOnce(&str, &str) -> Option<String>,
) -> Option<bool> {
    if portal.is_some() {
        return portal;
    }
    let enabled = gsetting("org.gnome.desktop.interface", "enable-animations")?;
    enabled.trim().parse::<bool>().ok().map(|enabled| !enabled)
}

/// Reduced motion as the reader of `desktop` (the refined desktop) reads it:
/// on KDE `kdeglobals` (`None` without the `kde` feature, which reads no KDE
/// file), as the KDE reader does; on GNOME and Budgie the `portal`, then
/// gsettings ([`gnome_reduce_motion`]), as the GNOME reader does; elsewhere,
/// and on KDE where `kdeglobals` gives `None`, gsettings alone. `false` when
/// nothing answers.
#[cfg(target_os = "linux")]
fn desktop_reduce_motion(
    desktop: LinuxDesktop,
    kdeglobals: impl FnOnce() -> Option<bool>,
    portal: impl FnOnce() -> Option<bool>,
    gsetting: impl FnOnce(&str, &str) -> Option<String>,
) -> bool {
    match desktop {
        LinuxDesktop::Kde => kdeglobals().or_else(|| gnome_reduce_motion(None, gsetting)),
        LinuxDesktop::Gnome | LinuxDesktop::Budgie => gnome_reduce_motion(portal(), gsetting),
        _ => gnome_reduce_motion(None, gsetting),
    }
    .unwrap_or(false)
}

/// Inner detection logic for [`prefers_reduced_motion()`].
///
/// Separated from the public function to allow caching.
fn detect_reduced_motion_inner() -> bool {
    #[cfg(target_os = "linux")]
    {
        desktop_reduce_motion(
            system().refined_linux_desktop_sync(),
            || {
                #[cfg(feature = "kde")]
                {
                    Some(crate::kde::kdeglobals_reduce_motion())
                }
                #[cfg(not(feature = "kde"))]
                {
                    None
                }
            },
            || {
                #[cfg(feature = "portal")]
                {
                    pollster::block_on(crate::gnome::portal_reduce_motion())
                }
                #[cfg(not(feature = "portal"))]
                {
                    None
                }
            },
            |schema, key| gsettings_get(schema, key, SUBPROCESS_TIMEOUT),
        )
    }

    #[cfg(target_os = "macos")]
    {
        #[cfg(feature = "macos")]
        {
            crate::macos::reduce_motion()
        }
        #[cfg(not(feature = "macos"))]
        {
            false
        }
    }

    #[cfg(target_os = "windows")]
    {
        #[cfg(feature = "windows")]
        {
            crate::windows::read_reduce_motion().unwrap_or(false)
        }
        #[cfg(not(feature = "windows"))]
        {
            false
        }
    }

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

// === DetectionContext ===

/// A value cached with the generation of its slot when its detection began.
struct Stamped<T> {
    generation: u64,
    value: T,
}

/// One cached detection: the value, and a generation every invalidation
/// bumps. A value is cached only if no invalidation landed while it was
/// detected, so a fill that began before an OS change and ends after a
/// watcher's invalidation does not cache what it read before the change.
struct CacheSlot<T> {
    value: ArcSwapOption<Stamped<T>>,
    generation: AtomicU64,
}

/// A fill in progress: the slot's generation and entry when it began.
pub(crate) struct CacheFill<T> {
    generation: u64,
    seen: Option<Arc<Stamped<T>>>,
}

impl<T> CacheFill<T> {
    /// The value the slot held for this fill's generation, if any.
    fn cached(&self) -> Option<&T> {
        self.seen
            .as_deref()
            .filter(|entry| entry.generation == self.generation)
            .map(|entry| &entry.value)
    }
}

impl<T> CacheSlot<T> {
    fn empty() -> Self {
        Self {
            value: ArcSwapOption::empty(),
            generation: AtomicU64::new(0),
        }
    }

    // The generation's Acquire loads pair with the Release bump in
    // `invalidate`, which follows its clearing store: a fill that reads the
    // bumped generation also sees the slot cleared, and an entry stamped with
    // an older generation than the one loaded is never returned.
    fn begin_fill(&self) -> CacheFill<T> {
        let generation = self.generation.load(Ordering::Acquire);
        CacheFill {
            generation,
            seen: self.value.load_full(),
        }
    }

    /// Cache `value` unless an invalidation landed after `fill` began, or
    /// another fill stored a value since.
    fn finish_fill(&self, fill: CacheFill<T>, value: T) {
        if self.generation.load(Ordering::Acquire) != fill.generation {
            return;
        }
        let stamped = Arc::new(Stamped {
            generation: fill.generation,
            value,
        });
        let _ = self.value.compare_and_swap(&fill.seen, Some(stamped));
    }

    /// The cached value, or `detect`'s, cached as [`finish_fill`](Self::finish_fill)
    /// caches it.
    fn get_or_fill(&self, detect: impl FnOnce() -> T) -> T
    where
        T: Clone,
    {
        let fill = self.begin_fill();
        if let Some(value) = fill.cached() {
            return value.clone();
        }
        let value = detect();
        self.finish_fill(fill, value.clone());
        value
    }

    /// The cached value, if any.
    #[cfg(any(test, target_os = "linux"))]
    fn get(&self) -> Option<T>
    where
        T: Clone,
    {
        self.begin_fill().cached().cloned()
    }

    fn invalidate(&self) {
        self.value.store(None);
        self.generation.fetch_add(1, Ordering::Release);
    }
}

/// Process-wide detection cache.
///
/// Provides "cache on first read" semantics for OS detection queries
/// (`is_dark`, `reduced_motion`, `accessibility_preferences`, `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`]). A value detected while an invalidation of
/// its field lands is returned to its caller but not cached.
pub struct DetectionContext {
    is_dark: CacheSlot<bool>,
    reduced_motion: CacheSlot<bool>,
    reader_accessibility: CacheSlot<crate::AccessibilityPreferences>,
    icon_theme: CacheSlot<Result<String, IconThemeFailure>>,
    #[cfg(target_os = "linux")]
    linux_desktop: CacheSlot<LinuxDesktop>,
    #[cfg(target_os = "linux")]
    refined_linux_desktop: CacheSlot<RefinedDesktop>,
}

impl DetectionContext {
    /// Create an empty context with no cached values.
    pub(crate) fn new() -> Self {
        Self {
            is_dark: CacheSlot::empty(),
            reduced_motion: CacheSlot::empty(),
            reader_accessibility: CacheSlot::empty(),
            icon_theme: CacheSlot::empty(),
            #[cfg(target_os = "linux")]
            linux_desktop: CacheSlot::empty(),
            #[cfg(target_os = "linux")]
            refined_linux_desktop: CacheSlot::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 {
        self.is_dark.get_or_fill(detect_is_dark_inner)
    }

    /// 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 {
        self.reduced_motion.get_or_fill(detect_reduced_motion_inner)
    }

    /// The OS accessibility preferences (cached), as
    /// [`accessibility_preferences()`](crate::detect::accessibility_preferences)
    /// describes: the platform reader's accessibility block, run on the
    /// first call unless a system read stored it.
    /// Call
    /// [`invalidate_accessibility_preferences()`](Self::invalidate_accessibility_preferences)
    /// to force a re-read.
    #[must_use]
    pub fn accessibility_preferences(&self) -> crate::AccessibilityPreferences {
        self.reader_accessibility_with(|| {
            pollster::block_on(crate::pipeline::reader_accessibility())
        })
    }

    /// The cached reader accessibility block, with `read` run where
    /// nothing is cached.
    pub(crate) fn reader_accessibility_with(
        &self,
        read: impl FnOnce() -> crate::AccessibilityPreferences,
    ) -> crate::AccessibilityPreferences {
        self.reader_accessibility.get_or_fill(read)
    }

    /// Begin a platform read whose accessibility block
    /// [`store_reader_accessibility`](Self::store_reader_accessibility)
    /// stores.
    pub(crate) fn begin_reader_accessibility(&self) -> CacheFill<crate::AccessibilityPreferences> {
        self.reader_accessibility.begin_fill()
    }

    /// Store the accessibility block a platform reader just returned, unless
    /// the cache was invalidated or filled since the read began (`fill`).
    pub(crate) fn store_reader_accessibility(
        &self,
        fill: CacheFill<crate::AccessibilityPreferences>,
        prefs: crate::AccessibilityPreferences,
    ) {
        self.reader_accessibility.finish_fill(fill, prefs);
    }

    /// 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()`]: 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, IconThemeFailure>,
    ) -> crate::Result<String> {
        self.icon_theme
            .get_or_fill(detect)
            .map_err(|failure| 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 {
        self.linux_desktop.get_or_fill(detect_linux_desktop)
    }

    /// The desktop the reader, the theme watcher and the icon-theme detection
    /// decide by ([`refine_linux_desktop`]), cached: on an
    /// unrecognised desktop the portal backend is asked over D-Bus (with the
    /// `portal` feature), then `kdeglobals` is looked for. The system reads
    /// (`SystemTheme::from_system`, `from_system_async`,
    /// `AccessibilityPreferences::from_system`) fill the cache.
    /// [`invalidate_linux_desktop()`](Self::invalidate_linux_desktop) clears it.
    #[cfg(target_os = "linux")]
    pub(crate) async fn refined_linux_desktop(&self) -> RefinedDesktop {
        let fill = self.refined_linux_desktop.begin_fill();
        if let Some(v) = fill.cached() {
            return *v;
        }
        let raw = self.linux_desktop();
        #[cfg(feature = "portal")]
        let portal_backend = if raw == LinuxDesktop::Unknown {
            crate::gnome::detect_portal_backend().await
        } else {
            None
        };
        #[cfg(not(feature = "portal"))]
        let portal_backend = None;
        let refined = refine_desktop(raw, portal_backend, kdeglobals_exists);
        let without_portal = refine_linux_desktop(raw, None, kdeglobals_exists);
        self.finish_refined_desktop(fill, refined, without_portal);
        refined
    }

    /// Cache `refined`, the desktop a system read refined. Where it is not
    /// `without_portal`, the desktop a synchronous caller refines while
    /// nothing is cached ([`refined_linux_desktop_sync`](Self::refined_linux_desktop_sync)),
    /// the values detected from that desktop are cleared: the
    /// icon theme, dark mode and reduced motion.
    #[cfg(target_os = "linux")]
    fn finish_refined_desktop(
        &self,
        fill: CacheFill<RefinedDesktop>,
        refined: RefinedDesktop,
        without_portal: LinuxDesktop,
    ) {
        self.refined_linux_desktop.finish_fill(fill, refined);
        if refined.desktop != without_portal {
            self.invalidate_icon_theme();
            self.invalidate_is_dark();
            self.invalidate_reduced_motion();
        }
    }

    /// The desktop the platform readers use: the raw `XDG_CURRENT_DESKTOP`
    /// ([`linux_desktop()`](Self::linux_desktop)) where it names a desktop;
    /// for [`LinuxDesktop::Unknown`], the desktop the portal backend named at
    /// the last system read (`SystemTheme::from_system`, `from_system_async`,
    /// `AccessibilityPreferences::from_system`, with the `portal` feature),
    /// else KDE where the user's `kdeglobals` exists (with the `kde`
    /// feature), else `Unknown`. The reader, the theme watcher and the icon-theme
    /// detection decide by it, and the icon enums
    /// native-theme-build generates pick their per-desktop names by it.
    ///
    /// A system read caches the desktop it refined; until one has, this call
    /// does not ask the portal and caches nothing, so on an unrecognised
    /// desktop whose portal backend names one it can differ from what the
    /// next system read caches (a KDE backend without `kdeglobals` is
    /// `Unknown` here, a GNOME backend with `kdeglobals` is KDE here); the
    /// system read then clears the icon theme, dark mode and reduced
    /// motion detected from this desktop.
    /// [`invalidate_linux_desktop()`](Self::invalidate_linux_desktop) clears
    /// the cached desktop.
    #[cfg(target_os = "linux")]
    #[must_use]
    pub fn refined_linux_desktop_sync(&self) -> LinuxDesktop {
        if let Some(v) = self.refined_linux_desktop.get() {
            return v.desktop;
        }
        refine_linux_desktop(self.linux_desktop(), None, kdeglobals_exists)
    }

    /// The font DPI: 72.0 on macOS, 96.0 everywhere else, every Linux desktop
    /// included (`detect_system_font_dpi`). A constant per platform since 0.7.1:
    /// nothing is read and nothing is cached.
    pub(crate) fn font_dpi(&self) -> f32 {
        detect_system_font_dpi()
    }

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

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

    /// Clear the cached accessibility preferences.
    pub fn invalidate_accessibility_preferences(&self) {
        self.reader_accessibility.invalidate();
    }

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

    /// Does nothing. Since 0.7.1 the font DPI is a constant per platform (72 on
    /// macOS, 96 elsewhere), which nothing caches; the method stays so that code
    /// calling it still builds.
    pub fn invalidate_font_dpi(&self) {}

    /// Clear the cached Linux desktop environment, and the desktop refined
    /// from it.
    #[cfg(target_os = "linux")]
    pub fn invalidate_linux_desktop(&self) {
        self.linux_desktop.invalidate();
        self.refined_linux_desktop.invalidate();
    }

    /// Clear all cached values.
    pub fn invalidate_all(&self) {
        self.invalidate_is_dark();
        self.invalidate_reduced_motion();
        self.invalidate_accessibility_preferences();
        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, IconThemeFailure> {
    icon_theme::detect_icon_theme_outcome()
}

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

/// The platform's font DPI ([`DetectionContext::font_dpi`]).
pub(crate) fn system_font_dpi() -> f32 {
    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;
    }

    /// `gsetting` for [`desktop_reduce_motion`]: `enable-animations` is
    /// `enabled`; `asked` counts the reads.
    #[cfg(target_os = "linux")]
    fn animations<'a>(
        enabled: &'static str,
        asked: &'a std::cell::Cell<u32>,
    ) -> impl FnOnce(&str, &str) -> Option<String> + 'a {
        move |schema, key| {
            asked.set(asked.get() + 1);
            ((schema, key) == ("org.gnome.desktop.interface", "enable-animations"))
                .then(|| enabled.to_string())
        }
    }

    /// On KDE reduced motion is kdeglobals' `AnimationDurationFactor`, as the
    /// KDE reader reads it, not GNOME's `enable-animations`, which may be
    /// absent or stale there (M1-T6-04); gsettings answers only where
    /// kdeglobals is not read (no `kde` feature).
    #[cfg(target_os = "linux")]
    #[test]
    fn kde_reduced_motion_is_kdeglobals_not_gsettings() {
        let asked = std::cell::Cell::new(0);
        let portal = || -> Option<bool> { panic!("KDE does not ask the portal") };
        assert!(desktop_reduce_motion(
            LinuxDesktop::Kde,
            || Some(true),
            portal,
            animations("true", &asked)
        ));
        assert!(!desktop_reduce_motion(
            LinuxDesktop::Kde,
            || Some(false),
            portal,
            animations("false", &asked)
        ));
        assert_eq!(asked.get(), 0);
        assert!(desktop_reduce_motion(
            LinuxDesktop::Kde,
            || None,
            portal,
            animations("false", &asked)
        ));
        assert_eq!(asked.get(), 1);
    }

    /// On GNOME and Budgie the portal's answer decides, as in the GNOME
    /// reader; without one, gsettings' `enable-animations`.
    #[cfg(target_os = "linux")]
    #[test]
    fn gnome_reduced_motion_is_the_portal_then_gsettings() {
        let asked = std::cell::Cell::new(0);
        let kdeglobals = || -> Option<bool> { panic!("GNOME does not read kdeglobals") };
        for desktop in [LinuxDesktop::Gnome, LinuxDesktop::Budgie] {
            assert!(desktop_reduce_motion(
                desktop,
                kdeglobals,
                || Some(true),
                animations("true", &asked)
            ));
            assert!(!desktop_reduce_motion(
                desktop,
                kdeglobals,
                || Some(false),
                animations("false", &asked)
            ));
            assert_eq!(asked.get(), 0);
            assert!(desktop_reduce_motion(
                desktop,
                kdeglobals,
                || None,
                animations("false", &asked)
            ));
            assert_eq!(asked.get(), 1);
            asked.set(0);
        }
    }

    /// A desktop without a reader answers from gsettings alone.
    #[cfg(target_os = "linux")]
    #[test]
    fn other_desktops_reduced_motion_is_gsettings() {
        let asked = std::cell::Cell::new(0);
        assert!(desktop_reduce_motion(
            LinuxDesktop::Xfce,
            || -> Option<bool> { panic!("XFCE does not read kdeglobals") },
            || -> Option<bool> { panic!("XFCE does not ask the portal") },
            animations("false", &asked)
        ));
        assert!(!desktop_reduce_motion(
            LinuxDesktop::Unknown,
            || None,
            || None,
            |_, _| None
        ));
    }

    #[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 cache_slot_tests {
    use super::*;

    /// The slot every cached field uses ([`DetectionContext::is_dark`],
    /// [`DetectionContext::linux_desktop`] and the rest): a value detected
    /// across an invalidation is returned, not cached.
    #[test]
    fn a_value_detected_across_an_invalidation_is_not_cached() {
        let slot = CacheSlot::empty();
        assert!(slot.get_or_fill(|| {
            slot.invalidate();
            true
        }));
        assert!(slot.get().is_none());
        assert!(!slot.get_or_fill(|| false));
        assert_eq!(slot.get(), Some(false));
    }

    /// A fill whose generation check passed before an invalidation and whose
    /// swap landed after it leaves an entry of the old generation, which no
    /// read returns.
    #[test]
    fn an_entry_stamped_before_an_invalidation_is_not_returned() {
        let slot = CacheSlot::empty();
        let fill = slot.begin_fill();
        slot.invalidate();
        let stale = Arc::new(Stamped {
            generation: fill.generation,
            value: true,
        });
        let _ = slot.value.compare_and_swap(&fill.seen, Some(stale));
        assert!(slot.get().is_none());
        assert!(!slot.get_or_fill(|| false));
        assert_eq!(slot.get(), Some(false));
    }

    #[test]
    fn a_fill_does_not_replace_a_value_stored_since_it_began() {
        let slot = CacheSlot::empty();
        let slow = slot.begin_fill();
        let _ = slot.get_or_fill(|| 2);
        slot.finish_fill(slow, 1);
        assert_eq!(slot.get(), Some(2));
    }
}

#[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);
    }

    /// A context with every slot filled.
    fn filled() -> DetectionContext {
        let ctx = DetectionContext::new();
        ctx.is_dark.get_or_fill(|| true);
        ctx.reduced_motion.get_or_fill(|| true);
        ctx.reader_accessibility
            .get_or_fill(crate::AccessibilityPreferences::default);
        let _ = ctx.icon_theme.get_or_fill(|| Ok("breeze".to_string()));
        #[cfg(target_os = "linux")]
        ctx.linux_desktop.get_or_fill(|| LinuxDesktop::Kde);
        #[cfg(target_os = "linux")]
        ctx.refined_linux_desktop.get_or_fill(|| RefinedDesktop {
            desktop: LinuxDesktop::Kde,
            by_kdeglobals: false,
        });
        ctx
    }

    /// `invalidate_all` empties every slot. The pattern names each field, so
    /// a slot added to [`DetectionContext`] does not compile until it is
    /// checked here.
    #[test]
    fn invalidate_all_empties_every_slot() {
        let ctx = filled();
        ctx.invalidate_all();
        let DetectionContext {
            is_dark,
            reduced_motion,
            reader_accessibility,
            icon_theme,
            #[cfg(target_os = "linux")]
            linux_desktop,
            #[cfg(target_os = "linux")]
            refined_linux_desktop,
        } = &ctx;
        assert!(is_dark.get().is_none(), "is_dark");
        assert!(reduced_motion.get().is_none(), "reduced_motion");
        assert!(reader_accessibility.get().is_none(), "reader_accessibility");
        assert!(icon_theme.get().is_none(), "icon_theme");
        #[cfg(target_os = "linux")]
        assert!(linux_desktop.get().is_none(), "linux_desktop");
        #[cfg(target_os = "linux")]
        assert!(
            refined_linux_desktop.get().is_none(),
            "refined_linux_desktop"
        );
    }

    #[test]
    fn invalidate_is_dark_empties_only_is_dark() {
        let ctx = filled();
        ctx.invalidate_is_dark();
        assert_eq!(ctx.is_dark.get(), None);
        assert_eq!(ctx.reduced_motion.get(), Some(true));
    }

    /// `invalidate_font_dpi` does nothing: the font DPI is a constant per
    /// platform, which nothing caches.
    #[test]
    fn invalidate_font_dpi_clears_nothing() {
        let ctx = filled();
        ctx.invalidate_font_dpi();
        assert!(ctx.is_dark.get().is_some(), "is_dark");
        assert!(ctx.reduced_motion.get().is_some(), "reduced_motion");
        assert!(
            ctx.reader_accessibility.get().is_some(),
            "reader_accessibility"
        );
        assert!(ctx.icon_theme.get().is_some(), "icon_theme");
        #[cfg(target_os = "linux")]
        assert!(ctx.linux_desktop.get().is_some(), "linux_desktop");
        #[cfg(target_os = "linux")]
        assert!(
            ctx.refined_linux_desktop.get().is_some(),
            "refined_linux_desktop"
        );
        assert_eq!(ctx.font_dpi(), detect_system_font_dpi());
    }

    fn undetected() -> Result<String, IconThemeFailure> {
        Err(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"));
    }

    fn scaled_by(text_scaling_factor: f32) -> crate::AccessibilityPreferences {
        crate::AccessibilityPreferences {
            text_scaling_factor,
            ..crate::AccessibilityPreferences::default()
        }
    }

    #[test]
    fn a_second_accessibility_read_does_not_run_the_reader() {
        let ctx = DetectionContext::new();
        let runs = std::cell::Cell::new(0);
        let read = || {
            runs.set(runs.get() + 1);
            scaled_by(1.5)
        };
        assert_eq!(ctx.reader_accessibility_with(read), scaled_by(1.5));
        assert_eq!(ctx.reader_accessibility_with(read), scaled_by(1.5));
        assert_eq!(runs.get(), 1, "the second call ran the reader");
    }

    #[test]
    fn a_stored_accessibility_block_is_returned_until_invalidated() {
        let ctx = DetectionContext::new();
        let runs = std::cell::Cell::new(0);
        let read = || {
            runs.set(runs.get() + 1);
            scaled_by(1.25)
        };
        ctx.store_reader_accessibility(ctx.begin_reader_accessibility(), scaled_by(2.0));
        assert_eq!(ctx.reader_accessibility_with(read), scaled_by(2.0));
        assert_eq!(runs.get(), 0, "a stored block ran the reader");
        ctx.invalidate_all();
        assert_eq!(ctx.reader_accessibility_with(read), scaled_by(1.25));
        assert_eq!(runs.get(), 1);
        ctx.invalidate_accessibility_preferences();
        assert_eq!(ctx.reader_accessibility_with(read), scaled_by(1.25));
        assert_eq!(runs.get(), 2);
    }

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

    #[test]
    fn an_accessibility_block_read_across_an_invalidation_is_not_cached() {
        let ctx = DetectionContext::new();
        let stale = ctx.reader_accessibility_with(|| {
            ctx.invalidate_all();
            scaled_by(1.5)
        });
        assert_eq!(stale, scaled_by(1.5));
        assert_eq!(
            ctx.reader_accessibility_with(|| scaled_by(2.0)),
            scaled_by(2.0)
        );
    }

    /// A synchronous caller gets the desktop a system read refined, portal
    /// answer included, until it is invalidated.
    #[cfg(target_os = "linux")]
    #[test]
    fn the_sync_refined_desktop_is_the_cached_one() {
        let ctx = DetectionContext::new();
        let fill = ctx.refined_linux_desktop.begin_fill();
        let gnome = refine_desktop(LinuxDesktop::Gnome, None, || false);
        ctx.refined_linux_desktop.finish_fill(fill, gnome);
        assert_eq!(ctx.refined_linux_desktop_sync(), LinuxDesktop::Gnome);
        assert_eq!(pollster::block_on(ctx.refined_linux_desktop()), gnome);
        ctx.invalidate_linux_desktop();
        assert!(ctx.refined_linux_desktop.get().is_none());
    }

    /// A context whose raw desktop is `Unknown` and whose system read refined
    /// it with `portal_backend`, `kdeglobals` absent.
    #[cfg(target_os = "linux")]
    fn refined_unknown(portal_backend: Option<LinuxDesktop>) -> DetectionContext {
        let ctx = DetectionContext::new();
        ctx.linux_desktop
            .finish_fill(ctx.linux_desktop.begin_fill(), LinuxDesktop::Unknown);
        ctx.finish_refined_desktop(
            ctx.refined_linux_desktop.begin_fill(),
            refine_desktop(LinuxDesktop::Unknown, portal_backend, || false),
            LinuxDesktop::Unknown,
        );
        ctx
    }

    /// An icon theme, dark mode or reduced motion read before the
    /// first system read came from the desktop refined without the portal; a
    /// portal answer that names another desktop clears them, so they are read
    /// again from the reader's desktop (docs/archive/todo_closed.md, *Closed
    /// items from Font DPI*, 'For M4: an unrecognised `XDG_CURRENT_DESKTOP`
    /// with a GNOME portal backend', M4-49).
    #[cfg(target_os = "linux")]
    #[test]
    fn a_portal_answer_that_changes_the_desktop_clears_what_was_read_from_it() {
        let ctx = DetectionContext::new();
        assert_eq!(
            ctx.icon_theme_with(|| Ok("breeze".to_string()))
                .ok()
                .as_deref(),
            Some("breeze")
        );
        assert!(ctx.is_dark.get_or_fill(|| true));
        assert!(ctx.reduced_motion.get_or_fill(|| true));

        let refined = refine_desktop(LinuxDesktop::Unknown, Some(LinuxDesktop::Gnome), || true);
        ctx.finish_refined_desktop(
            ctx.refined_linux_desktop.begin_fill(),
            refined,
            LinuxDesktop::Kde,
        );
        assert_eq!(ctx.refined_linux_desktop_sync(), LinuxDesktop::Gnome);
        assert_eq!(
            ctx.icon_theme_with(|| Ok("Adwaita".to_string()))
                .ok()
                .as_deref(),
            Some("Adwaita")
        );
        assert_eq!(ctx.is_dark.get(), None);
        assert_eq!(ctx.reduced_motion.get(), None);
    }

    /// A portal answer that names the desktop the synchronous refinement
    /// already gave keeps what was read from it.
    #[cfg(target_os = "linux")]
    #[test]
    fn a_portal_answer_that_keeps_the_desktop_keeps_what_was_read() {
        let ctx = DetectionContext::new();
        assert_eq!(
            ctx.icon_theme_with(|| Ok("breeze".to_string()))
                .ok()
                .as_deref(),
            Some("breeze")
        );
        let refined = refine_desktop(LinuxDesktop::Unknown, Some(LinuxDesktop::Kde), || true);
        ctx.finish_refined_desktop(
            ctx.refined_linux_desktop.begin_fill(),
            refined,
            LinuxDesktop::Kde,
        );
        assert_eq!(
            ctx.icon_theme_with(|| Ok("Adwaita".to_string()))
                .ok()
                .as_deref(),
            Some("breeze")
        );
    }

    /// On an unrecognised desktop a system read refined to KDE, dark mode
    /// comes from `kdeglobals` first, as the KDE reader takes it; on one
    /// refined to GNOME, from gsettings first.
    #[cfg(target_os = "linux")]
    #[test]
    fn dark_mode_follows_the_refined_desktop() {
        let kde = refined_unknown(Some(LinuxDesktop::Kde));
        assert_eq!(
            desktop_is_dark(&kde, || Some(true), || Some(false)),
            Some(true)
        );
        let gnome = refined_unknown(Some(LinuxDesktop::Gnome));
        assert_eq!(
            desktop_is_dark(&gnome, || Some(true), || Some(false)),
            Some(false)
        );
        assert_eq!(desktop_is_dark(&gnome, || Some(true), || None), Some(true));
    }
}

#[cfg(all(test, target_os = "linux"))]
mod refine_linux_desktop_tests {
    use super::*;

    fn asked() -> bool {
        panic!("kdeglobals asked where the desktop is already decided")
    }

    /// `XDG_CURRENT_DESKTOP` decides where it names a desktop; the portal
    /// backend, then `kdeglobals`, only where it names none.
    #[test]
    fn the_raw_desktop_then_the_portal_backend_then_kdeglobals() {
        let refine = |raw, portal_backend, kdeglobals_exists: fn() -> bool| {
            refine_linux_desktop(raw, portal_backend, kdeglobals_exists)
        };
        assert_eq!(
            refine(LinuxDesktop::Gnome, Some(LinuxDesktop::Kde), asked),
            LinuxDesktop::Gnome
        );
        assert_eq!(refine(LinuxDesktop::Xfce, None, asked), LinuxDesktop::Xfce);
        assert_eq!(
            refine(LinuxDesktop::Unknown, Some(LinuxDesktop::Kde), asked),
            LinuxDesktop::Kde
        );
        assert_eq!(
            refine(LinuxDesktop::Unknown, Some(LinuxDesktop::Gnome), asked),
            LinuxDesktop::Gnome
        );
        assert_eq!(
            refine(LinuxDesktop::Unknown, None, || true),
            LinuxDesktop::Kde
        );
        assert_eq!(
            refine(LinuxDesktop::Unknown, None, || false),
            LinuxDesktop::Unknown
        );
    }
}

#[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};

    /// The timeout of a test whose command finishes: a loaded machine never
    /// takes that long, where it could take `SUBPROCESS_TIMEOUT`'s 2 s, the
    /// readers' design value.
    const GENEROUS: Duration = Duration::from_secs(10);

    /// 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 = stdout_with_timeout("echo", &["hi"], GENEROUS);
        assert_eq!(out.as_deref().map(str::trim), Some("hi"));
    }

    /// An unsuccessful exit is an output, with its status and its stderr;
    /// [`stdout_with_timeout`] gives `None` for it.
    #[test]
    fn run_with_timeout_returns_the_status_and_stderr_of_a_failing_command() {
        if !on_path("sh") {
            eprintln!("skipped: sh is not installed");
            return;
        }
        let output = run_with_timeout("sh", &["-c", "echo oops >&2; exit 3"], GENEROUS).unwrap();
        assert_eq!(output.status.code(), Some(3));
        assert_eq!(output.stderr, b"oops\n");
        assert_eq!(stdout_with_timeout("sh", &["-c", "exit 3"], GENEROUS), None);
    }

    #[test]
    fn run_with_timeout_reports_a_missing_program_as_not_found() {
        let error = run_with_timeout("nt-test-no-such-program", &[], GENEROUS).unwrap_err();
        assert_eq!(error.kind(), std::io::ErrorKind::NotFound);
    }

    /// 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!(
            stdout_with_timeout("true", &[], GENEROUS).as_deref(),
            Some("")
        );
        eprintln!("`true` ran in {:?}", start.elapsed());
    }

    /// Whether a process runs with exactly the command line `cmdline`.
    fn running(cmdline: &str) -> 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()
    }

    /// A command that outlives the timeout is killed and reaped, and the
    /// call ends at the timeout, not when the command would have: its sleep
    /// is 30 s, and the 5 s bound leaves a loaded machine room to stall.
    #[test]
    fn run_with_timeout_kills_a_command_that_outlives_the_timeout() {
        if !on_path("sleep") {
            eprintln!("skipped: sleep is not installed");
            return;
        }
        let timeout = Duration::from_millis(100);
        let seconds = format!("30.{}", std::process::id());
        let start = Instant::now();
        let error = run_with_timeout("sleep", &[&seconds], timeout).unwrap_err();
        let elapsed = start.elapsed();
        assert_eq!(error.kind(), std::io::ErrorKind::TimedOut);
        assert_eq!(error.to_string(), "timed out after 100ms");
        assert!(
            elapsed >= timeout && elapsed < Duration::from_secs(5),
            "took {elapsed:?}"
        );
        let still_running = running(&format!("sleep\0{seconds}\0"));
        assert!(still_running.is_empty(), "not killed: {still_running:?}");
    }

    /// 100 KiB is more than a Linux pipe holds (65,536 bytes, pipe(7)), so
    /// the command finishes only if its stdout is read while it runs.
    #[test]
    fn run_with_timeout_returns_all_of_an_output_larger_than_a_pipe() {
        if !on_path("sh") || !on_path("head") {
            eprintln!("skipped: sh or head is not installed");
            return;
        }
        let out = stdout_with_timeout("sh", &["-c", "head -c 102400 /dev/zero"], GENEROUS);
        assert_eq!(out.map(|out| out.len()), Some(102_400));
    }

    /// A process the command leaves running with its stdout keeps the pipe
    /// open after the command exits; the call still ends at the deadline,
    /// not when that process exits: it sleeps 10 s, and the 5 s bound leaves
    /// a loaded machine room to stall.
    #[test]
    fn run_with_timeout_ends_at_the_deadline_when_a_grandchild_holds_stdout() {
        if !on_path("sh") || !on_path("sleep") {
            eprintln!("skipped: sh or sleep is not installed");
            return;
        }
        let script = format!("sleep 10.{} & echo hi", std::process::id());
        let start = Instant::now();
        let error =
            run_with_timeout("sh", &["-c", &script], Duration::from_millis(100)).unwrap_err();
        let elapsed = start.elapsed();
        assert_eq!(error.kind(), std::io::ErrorKind::TimedOut);
        assert!(elapsed < Duration::from_secs(5), "took {elapsed:?}");
    }
}

#[cfg(all(test, target_os = "linux"))]
mod config_home_tests {
    use super::*;
    use std::ffi::OsStr;
    use std::path::PathBuf;

    fn config_home(var: Option<&str>, home: Option<&str>) -> Option<PathBuf> {
        xdg_config_home_from(var.map(OsStr::new), home.map(OsStr::new))
    }

    #[test]
    fn an_absolute_xdg_config_home_is_the_config_directory() {
        assert_eq!(
            config_home(Some("/tmp/cfg"), Some("/home/u")),
            Some(PathBuf::from("/tmp/cfg"))
        );
        assert_eq!(
            config_home(Some("/tmp/cfg"), None),
            Some(PathBuf::from("/tmp/cfg"))
        );
    }

    /// Unset, empty and relative are each "not set" (the XDG Base Directory
    /// Specification ignores a relative path).
    #[test]
    fn an_unset_empty_or_relative_xdg_config_home_falls_back_to_home() {
        for var in [None, Some(""), Some("relative/cfg"), Some(".config")] {
            assert_eq!(
                config_home(var, Some("/home/u")),
                Some(PathBuf::from("/home/u/.config")),
                "{var:?}"
            );
        }
    }

    #[test]
    fn without_xdg_config_home_and_home_there_is_no_config_directory() {
        for home in [None, Some("")] {
            for var in [None, Some(""), Some("relative")] {
                assert_eq!(config_home(var, home), None, "{var:?} {home:?}");
            }
        }
    }
}

#[cfg(all(test, target_os = "linux"))]
mod linux_font_dpi_tests {
    use super::*;

    #[test]
    fn the_font_dpi_is_96_on_every_linux_desktop() {
        assert_eq!(LINUX_FONT_DPI, 96.0);
        assert_eq!(detect_system_font_dpi(), 96.0);
        assert_eq!(DetectionContext::new().font_dpi(), 96.0);
        assert_eq!(system_font_dpi(), 96.0);
    }
}