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
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
//! Theme pipeline: reader -> preset merge -> resolve -> validate.

use std::fmt;

#[cfg(target_os = "linux")]
use crate::detect::{LinuxDesktop, parse_linux_desktop};

#[cfg(any(target_os = "linux", test))]
use crate::ReaderOutput;
use crate::model::Theme;
use crate::{OverlaySource, ReaderResult, SystemTheme};

/// Run the OS-first pipeline: merge reader output onto a platform
/// preset, resolve both light and dark variants, validate.
///
/// Accepts a [`ReaderResult`] containing the reader's variant data
/// and metadata (name, icon_set, layout, font_dpi, accessibility).
///
/// `ReaderOutput::Single` readers provide one variant; the pipeline
/// fills the other from the full platform preset. `ReaderOutput::Dual`
/// readers provide both; the pipeline uses both after merging. Both kinds
/// report which variant is OS-active through `is_dark`, which decides `mode`.
pub(crate) fn run_pipeline(reader: ReaderResult, preset_name: &str) -> crate::Result<SystemTheme> {
    let mode = reader.output.mode();
    let ReaderResult {
        output: reader_output,
        name: reader_name,
        icon_set: reader_icon_set,
        layout: reader_layout,
        font_dpi,
        accessibility,
    } = reader;

    // Build ONE resolution-time context for this theme-build. The reader
    // may have supplied its font_dpi (each platform reader does: 96 on Linux and
    // Windows, 72 on macOS); when it does, the context takes it.
    // button_order + icon_theme are platform-detected as from_system()'s.
    let context = match font_dpi {
        Some(dpi) => crate::resolve::ResolutionContext::with_font_dpi(
            dpi,
            crate::detect::system_icon_theme(),
        ),
        None => crate::resolve::ResolutionContext::from_system(),
    };

    let source = OverlaySource {
        reader_output,
        name: reader_name,
        icon_set: reader_icon_set,
        layout: reader_layout,
        preset_name: preset_name.to_string(),
        context,
        overlay: None,
    };
    replay(source, mode, accessibility)
}

/// Merge and resolve what `source` holds: the platform preset provides the
/// defaults, the reader output live OS data on top, the app's overlays (if
/// any) their changes over both. Shared by [`run_pipeline`] and
/// [`SystemTheme::with_overlay`], which replays its source with one more
/// overlay.
pub(crate) fn replay(
    source: OverlaySource,
    mode: crate::ColorMode,
    accessibility: crate::AccessibilityPreferences,
) -> crate::Result<SystemTheme> {
    // A `Single` reader states no inactive variant, so the merge keeps the
    // preset's own there; a `Dual` reader's two variants go over the preset's.
    let mut merged = Theme::preset(&source.preset_name)?;
    merged.merge(
        &source
            .reader_output
            .to_theme(&source.name, source.icon_set, &source.layout),
    );
    if let Some(overlay) = &source.overlay {
        merged.merge(overlay);
    }

    // Keep reader name if non-empty, else use preset name
    let name = if source.name.is_empty() {
        merged.name.clone()
    } else {
        source.name.clone()
    };

    // Resolve icon_set from Theme level (shared across variants)
    let icon_set = merged
        .icon_set
        .unwrap_or_else(crate::detect::system_icon_set);

    // Resolve icon_theme with three-tier precedence (per §G4 / doc 1 §20 Option C):
    //   Tier 1: per-variant override (`ThemeMode::defaults.icon_theme`)
    //   Tier 2: shared Theme-level value (`Theme::icon_theme`)
    //   Tier 3: runtime system detect (from `context.icon_theme`)
    // Must read before variants are consumed by unwrap_or_default().
    // None where no tier names a theme: the TOML states none and detection
    // failed (`context.icon_theme` is then None). No theme stands in for it.
    // Both variants are resolved, kept by variant (`SystemTheme::icon_theme_for`);
    // `icon_theme` is the active mode's copy.
    let icon_theme_of =
        |variant: &Option<crate::model::ThemeMode>| -> Option<std::borrow::Cow<'static, str>> {
            variant
                .as_ref()
                .and_then(|v| v.defaults.icon_theme.clone()) // tier 1: per-variant override
                .or_else(|| merged.icon_theme.clone()) // tier 2: Theme-level shared
                .or_else(|| source.context.icon_theme.clone()) // tier 3: pre-detected system
        };
    let light_icon_theme = icon_theme_of(&merged.light);
    let dark_icon_theme = icon_theme_of(&merged.dark);
    let icon_theme = match mode {
        crate::ColorMode::Light => light_icon_theme.clone(),
        crate::ColorMode::Dark => dark_icon_theme.clone(),
    };

    // Shared across variants.
    crate::resolve::validate_helpers::check_font_dpi(source.context.font_dpi)?;
    crate::resolve::validate_helpers::check_layout(&merged.layout)?;

    let light = merged
        .light
        .unwrap_or_default()
        .into_resolved(&source.context)
        .map_err(|e| e.in_variant(crate::ColorMode::Light))?;
    let dark = merged
        .dark
        .unwrap_or_default()
        .into_resolved(&source.context)
        .map_err(|e| e.in_variant(crate::ColorMode::Dark))?;

    Ok(SystemTheme {
        name,
        mode,
        light,
        dark,
        preset: source.preset_name.clone(),
        overlay_source: source,
        version_match: None,
        icon_set,
        icon_theme,
        light_icon_theme,
        dark_icon_theme,
        layout: merged.layout,
        accessibility,
    })
}

// =============================================================================
// Structured return types
// =============================================================================

/// A single diagnostic observation about platform theme support.
///
/// Returned by [`diagnose_platform_support()`]. Each variant represents
/// a specific category of diagnostic information. Use `Display` to get
/// a human-readable string, or pattern-match for programmatic inspection.
///
/// For simple tabular output, use the [`name()`](Self::name),
/// [`status()`](Self::status), and [`detail()`](Self::detail) accessors:
///
/// ```
/// let diagnostics = native_theme::pipeline::diagnose_platform_support();
/// for entry in &diagnostics {
///     print!("{}: {}", entry.name(), entry.status());
///     if let Some(detail) = entry.detail() {
///         print!(" ({})", detail);
///     }
///     println!();
/// }
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum DiagnosticEntry {
    /// Platform identification (e.g. "Linux", "macOS", "Windows").
    Platform(&'static str),
    /// Detected desktop environment (Linux only).
    #[cfg(target_os = "linux")]
    DesktopEnv(crate::detect::LinuxDesktop),
    /// An environment variable was read successfully.
    EnvVar {
        /// Variable name (e.g. `"XDG_CURRENT_DESKTOP"`).
        name: &'static str,
        /// Variable value as read from the environment.
        value: String,
    },
    /// An environment variable was missing or empty.
    EnvVarMissing(&'static str),
    /// An external tool was found and operational.
    ToolAvailable {
        /// Tool binary name (e.g. `"gsettings"`).
        name: &'static str,
        /// Version string reported by the tool.
        version: String,
    },
    /// An external tool was found but returned an error.
    ToolError(&'static str),
    /// An external tool was not found on PATH.
    ToolMissing {
        /// Tool binary name.
        name: &'static str,
        /// Human-readable description of what is lost.
        impact: &'static str,
    },
    /// A config file was found at the given path.
    ConfigFound {
        /// Logical config name (e.g. `"KDE kdeglobals"`).
        name: &'static str,
        /// Filesystem path where the file was found.
        path: std::path::PathBuf,
    },
    /// A config file was not found at the expected path.
    ConfigMissing {
        /// Logical config name.
        name: &'static str,
        /// Filesystem path that was checked.
        path: std::path::PathBuf,
    },
    /// A cargo feature is enabled.
    FeatureEnabled(&'static str),
    /// A cargo feature is disabled.
    FeatureDisabled {
        /// Feature name (e.g. `"KDE"`, `"Portal"`).
        feature: &'static str,
        /// Human-readable description of what is lost.
        impact: &'static str,
    },
    /// The running OS version and the preset of its generation (macOS and
    /// Windows, with their reader feature).
    OsGeneration {
        /// The running OS version: macOS `major.minor.patch`, Windows `10.0.build`.
        version: String,
        /// The preset of that version's generation.
        preset: &'static str,
        /// How the version relates to the preset's generation.
        version_match: VersionMatch,
    },
}

impl DiagnosticEntry {
    /// A short label identifying what is being diagnosed.
    ///
    /// Examples: `"Platform"`, `"XDG_CURRENT_DESKTOP"`, `"gsettings"`,
    /// `"KDE kdeglobals"`, `"Portal support"`.
    #[must_use]
    pub fn name(&self) -> &str {
        match self {
            Self::Platform(_) => "Platform",
            #[cfg(target_os = "linux")]
            Self::DesktopEnv(_) => "Detected DE",
            Self::EnvVar { name, .. } | Self::EnvVarMissing(name) => name,
            Self::ToolAvailable { name, .. }
            | Self::ToolError(name)
            | Self::ToolMissing { name, .. } => name,
            Self::ConfigFound { name, .. } | Self::ConfigMissing { name, .. } => name,
            Self::FeatureEnabled(feature) | Self::FeatureDisabled { feature, .. } => feature,
            Self::OsGeneration { .. } => "OS version",
        }
    }

    /// A short status string: the detected value or a state like
    /// `"not set"`, `"available"`, `"found"`, `"enabled"`, etc.
    #[must_use]
    pub fn status(&self) -> &str {
        match self {
            Self::Platform(p) => p,
            #[cfg(target_os = "linux")]
            Self::DesktopEnv(_) => "detected",
            Self::EnvVar { value, .. } => value.as_str(),
            Self::EnvVarMissing(_) => "not set",
            Self::ToolAvailable { .. } => "available",
            Self::ToolError(_) => "found but returned error",
            Self::ToolMissing { .. } => "not found",
            Self::ConfigFound { .. } => "found",
            Self::ConfigMissing { .. } => "not found",
            Self::FeatureEnabled(_) => "enabled",
            Self::FeatureDisabled { .. } => "disabled",
            Self::OsGeneration { version, .. } => version.as_str(),
        }
    }

    /// Optional extra detail (version string, file path, impact note, DE variant).
    #[must_use]
    pub fn detail(&self) -> Option<String> {
        match self {
            #[cfg(target_os = "linux")]
            Self::DesktopEnv(de) => Some(format!("{de:?}")),
            Self::ToolAvailable { version, .. } => Some(version.clone()),
            Self::ToolMissing { impact, .. } => Some((*impact).to_string()),
            Self::FeatureDisabled { impact, .. } => Some((*impact).to_string()),
            Self::ConfigFound { path, .. } | Self::ConfigMissing { path, .. } => {
                Some(path.display().to_string())
            }
            Self::OsGeneration {
                preset,
                version_match,
                ..
            } => Some(format!("{preset}, {version_match}")),
            _ => None,
        }
    }
}

impl fmt::Display for DiagnosticEntry {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Platform(p) => write!(f, "Platform: {p}"),
            #[cfg(target_os = "linux")]
            Self::DesktopEnv(de) => write!(f, "Detected DE: {de:?}"),
            Self::EnvVar { name, value } => write!(f, "{name}: {value}"),
            Self::EnvVarMissing(name) => write!(f, "{name}: not set"),
            Self::ToolAvailable { name, version } => {
                write!(f, "{name}: available ({version})")
            }
            Self::ToolError(name) => write!(f, "{name}: found but returned error"),
            Self::ToolMissing { name, impact } => write!(f, "{name}: not found ({impact})"),
            Self::ConfigFound { name, path } => {
                write!(f, "{name}: found at {}", path.display())
            }
            Self::ConfigMissing { name, path } => {
                write!(f, "{name}: not found at {}", path.display())
            }
            Self::FeatureEnabled(feature) => write!(f, "{feature} support: enabled"),
            Self::FeatureDisabled { feature, impact } => {
                write!(f, "{feature} support: disabled ({impact})")
            }
            Self::OsGeneration {
                version,
                preset,
                version_match,
            } => write!(f, "OS version: {version} ({preset}, {version_match})"),
        }
    }
}

/// Structured information about the platform's default preset.
///
/// Returned by [`platform_preset_name()`]. The `name` field is the
/// user-facing preset name (e.g. `"macos-monterey"`), the preset the OS-first
/// pipeline merges the platform reader's output over.
///
/// `Display` returns the user-facing name.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PlatformPreset {
    /// User-facing preset name (e.g. "kde-breeze", "adwaita", "macos-monterey").
    pub name: &'static str,
}

impl fmt::Display for PlatformPreset {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.name)
    }
}

// =============================================================================
// OS generations (M1-T1-01)
// =============================================================================

/// How the running OS version relates to the generation of the preset the
/// pipeline merged the platform reader's output over
/// ([`SystemTheme::version_match`](crate::SystemTheme::version_match)).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum VersionMatch {
    /// The running version lies between the first version of the preset's
    /// generation and the newest version its values were verified on.
    Exact,
    /// The running OS is newer than any version the preset was verified on:
    /// the preset may carry an older look than the OS draws (macOS 27 under
    /// `macos-tahoe`).
    PresetOlder,
    /// The running OS predates the preset's generation: the preset carries a
    /// newer look than the OS draws (Windows 10 under `windows-11`).
    PresetNewer,
}

impl VersionMatch {
    /// A short label: `"exact"`, `"preset older than the OS"` or
    /// `"preset newer than the OS"`.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Exact => "exact",
            Self::PresetOlder => "preset older than the OS",
            Self::PresetNewer => "preset newer than the OS",
        }
    }
}

impl fmt::Display for VersionMatch {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// An OS version as the generation tables compare it: macOS
/// `major.minor.patch`, Windows `10.0.build`.
#[cfg_attr(
    not(any(
        all(target_os = "macos", feature = "macos"),
        all(target_os = "windows", feature = "windows")
    )),
    allow(dead_code)
)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) struct OsVersion {
    pub(crate) major: u32,
    pub(crate) minor: u32,
    pub(crate) build: u32,
}

impl OsVersion {
    #[cfg_attr(
        not(any(
            all(target_os = "macos", feature = "macos"),
            all(target_os = "windows", feature = "windows")
        )),
        allow(dead_code)
    )]
    pub(crate) const fn new(major: u32, minor: u32, build: u32) -> Self {
        Self {
            major,
            minor,
            build,
        }
    }
}

impl fmt::Display for OsVersion {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}.{}.{}", self.major, self.minor, self.build)
    }
}

/// One visual generation of a platform: the preset that carries its look,
/// the first OS version of that look, and the newest version its values were
/// verified on.
#[cfg_attr(
    not(any(
        all(target_os = "macos", feature = "macos"),
        all(target_os = "windows", feature = "windows")
    )),
    allow(dead_code)
)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Generation {
    pub(crate) preset: &'static str,
    pub(crate) first: OsVersion,
    pub(crate) last_verified: OsVersion,
}

/// A platform's generations, oldest first; never empty, `oldest` being a field.
#[cfg_attr(
    not(any(
        all(target_os = "macos", feature = "macos"),
        all(target_os = "windows", feature = "windows")
    )),
    allow(dead_code)
)]
#[derive(Clone, Copy, Debug)]
pub(crate) struct GenerationTable {
    pub(crate) oldest: Generation,
    /// The newer generations, in ascending order of `first`.
    pub(crate) newer: &'static [Generation],
    /// Every row's preset, oldest first: the names
    /// [`SystemTheme::from_system_with_preset`](crate::SystemTheme::from_system_with_preset)
    /// accepts on the platform.
    pub(crate) keys: &'static [&'static str],
}

#[cfg_attr(
    not(any(
        all(target_os = "macos", feature = "macos"),
        all(target_os = "windows", feature = "windows")
    )),
    allow(dead_code)
)]
impl GenerationTable {
    /// The rows, oldest first.
    fn rows(&self) -> impl Iterator<Item = Generation> + '_ {
        std::iter::once(self.oldest).chain(self.newer.iter().copied())
    }

    /// The row whose preset is `preset`.
    fn row(&self, preset: &str) -> Option<Generation> {
        self.rows().find(|g| g.preset == preset)
    }
}

/// macOS. `macos-monterey`: the look from macOS 12, whose AppKit release notes
/// end the accent highlight of a clicked button (M2a Step 7, plan D8), verified
/// on 14.8.9 and 15.7.9 by the OS probe; `macos-tahoe`: Liquid Glass from 26
/// (M2a Step 1's version map), verified on 26.6.2 (`docs/evidence/os-probe/
/// 2026-10-11-run-38129819806`). Apple's generations change at a major version,
/// so [`macos_generation`] compares majors. macOS 27 refines Liquid Glass and
/// gets no row until a preset is verified on it (plan D4): it maps to
/// `macos-tahoe`, reported as [`VersionMatch::PresetOlder`].
///
/// Major version 16: early macOS 26 betas reported 16 to a binary built
/// against the macOS 15 SDK ("When built against the 15 SDK or earlier, Tahoe
/// returns 16 for compatibility with previous numbering and all existing
/// apps", <https://eclecticlight.co/2025/06/13/is-tahoe-really-macos-26-or-16/>,
/// 2025-06-13). From beta 3, `NSOperatingSystemVersion` reports 26 even for
/// such a build (that page's comments, 2025-07-28); Apple Developer Forums
/// thread 791906 reports the same for the `kern.osproductversion` sysctl
/// (<https://developer.apple.com/forums/thread/791906>). No
/// source covers what the released OS reports. If a major version 16 is ever
/// read, this table gives `macos-monterey` with [`VersionMatch::PresetOlder`]
/// (no OS probe verified 16), which `generation_tests` pins.
#[cfg_attr(not(all(target_os = "macos", feature = "macos")), allow(dead_code))]
pub(crate) const MACOS_GENERATIONS: GenerationTable = GenerationTable {
    oldest: Generation {
        preset: "macos-monterey",
        first: OsVersion::new(12, 0, 0),
        last_verified: OsVersion::new(15, 0, 0),
    },
    newer: &[Generation {
        preset: "macos-tahoe",
        first: OsVersion::new(26, 0, 0),
        last_verified: OsVersion::new(26, 0, 0),
    }],
    keys: &["macos-monterey", "macos-tahoe"],
};

/// Windows. `windows-11`: the Fluent / WinUI 3 look from build 22000 (21H2;
/// M2b Step 1's version map), verified on build 26200 (25H2, the OS probe's
/// `windows-11-arm` image). Windows 10 has no preset of its own (M2b Step 7,
/// plan D9: a documented limit): it gets `windows-11`, reported as
/// [`VersionMatch::PresetNewer`].
#[cfg_attr(not(all(target_os = "windows", feature = "windows")), allow(dead_code))]
pub(crate) const WINDOWS_GENERATIONS: GenerationTable = GenerationTable {
    oldest: Generation {
        preset: "windows-11",
        first: OsVersion::new(10, 0, 22000),
        last_verified: OsVersion::new(10, 0, 26200),
    },
    newer: &[],
    keys: &["windows-11"],
};

/// How `running` relates to `row`'s generation.
#[cfg_attr(
    not(any(
        all(target_os = "macos", feature = "macos"),
        all(target_os = "windows", feature = "windows")
    )),
    allow(dead_code)
)]
pub(crate) fn version_match(row: &Generation, running: OsVersion) -> VersionMatch {
    if running < row.first {
        VersionMatch::PresetNewer
    } else if running > row.last_verified {
        VersionMatch::PresetOlder
    } else {
        VersionMatch::Exact
    }
}

/// The generation of `running` in `table`: the newest row whose first version
/// is not newer than `running`, or the oldest row where `running` predates
/// them all; with how `running` relates to it.
#[cfg_attr(
    not(any(
        all(target_os = "macos", feature = "macos"),
        all(target_os = "windows", feature = "windows")
    )),
    allow(dead_code)
)]
pub(crate) fn preset_for_version(
    table: &GenerationTable,
    running: OsVersion,
) -> (PlatformPreset, VersionMatch) {
    let row = table
        .newer
        .iter()
        .rev()
        .find(|g| g.first <= running)
        .copied()
        .unwrap_or(table.oldest);
    (
        PlatformPreset { name: row.preset },
        version_match(&row, running),
    )
}

/// `running` reduced to its major version, the macOS table's granularity.
#[cfg_attr(not(all(target_os = "macos", feature = "macos")), allow(dead_code))]
pub(crate) fn macos_major(running: OsVersion) -> OsVersion {
    OsVersion::new(running.major, 0, 0)
}

/// The macOS generation of a running macOS version, by its major version.
#[cfg_attr(not(all(target_os = "macos", feature = "macos")), allow(dead_code))]
pub(crate) fn macos_generation(running: OsVersion) -> (PlatformPreset, VersionMatch) {
    preset_for_version(&MACOS_GENERATIONS, macos_major(running))
}

/// The Windows generation of a running Windows build.
#[cfg_attr(not(all(target_os = "windows", feature = "windows")), allow(dead_code))]
pub(crate) fn windows_generation(running: OsVersion) -> (PlatformPreset, VersionMatch) {
    preset_for_version(&WINDOWS_GENERATIONS, running)
}

/// Map a Linux desktop environment to its matching platform preset.
///
/// [`select_reader`] and [`platform_preset_name()`] both map the refined
/// desktop through it ([`crate::detect::refine_linux_desktop`]). For
/// `Unknown`, [`select_reader`] first asks the portal backend (async D-Bus,
/// with the `portal` feature) and uses its answer, KDE or GNOME, either way;
/// only where no portal backend answers does it check for `kdeglobals`.
/// [`platform_preset_name()`] cannot ask the portal: it takes the desktop a
/// system read refined, and before one only the `kdeglobals` check, so with
/// the `kde` and `portal` features the two can differ until then, in both
/// directions where a portal backend answers: a KDE backend without
/// `kdeglobals` gives `kde-breeze` in `from_system` and `adwaita` in
/// [`platform_preset_name()`], a GNOME backend with `kdeglobals` gives
/// `adwaita` in `from_system` and `kde-breeze` in [`platform_preset_name()`].
///
/// - KDE -> `PlatformPreset { name: "kde-breeze" }`
/// - All others (GNOME, XFCE, Cinnamon, MATE, LXQt, Budgie, Unknown)
///   -> `PlatformPreset { name: "adwaita" }`
#[cfg(target_os = "linux")]
pub(crate) fn linux_preset_for_de(de: LinuxDesktop) -> PlatformPreset {
    match de {
        LinuxDesktop::Kde => PlatformPreset { name: "kde-breeze" },
        _ => PlatformPreset { name: "adwaita" },
    }
}

/// Map the current platform to its matching platform preset.
///
/// The preset is the merge base in the OS-first pipeline: the platform
/// reader's output is merged over it.
///
/// - macOS -> the running version's generation: `macos-monterey` on 12 to 15,
///   `macos-tahoe` on 26 and later; `macos-monterey` without the `macos`
///   feature, which reads the version
/// - Windows -> `PlatformPreset { name: "windows-11" }`, the one Windows generation
/// - Linux KDE -> `PlatformPreset { name: "kde-breeze" }`; an unrecognised
///   desktop with a `kdeglobals` file counts as KDE (with the `kde` feature)
/// - Linux other/GNOME -> `PlatformPreset { name: "adwaita" }`
/// - Unknown platform -> `PlatformPreset { name: "adwaita" }`
///
/// On an unrecognised Linux desktop `from_system` first asks the portal
/// backend over D-Bus (with the `portal` feature) and uses its answer, KDE
/// or GNOME, either way; only where no portal backend answers does it check
/// for `kdeglobals`. This synchronous function does not ask the portal: it
/// takes the desktop the last system read (`from_system`, `from_system_async`,
/// [`AccessibilityPreferences::from_system`](crate::AccessibilityPreferences::from_system))
/// refined, until [`invalidate_caches()`](crate::detect::invalidate_caches);
/// before one it runs only the `kdeglobals` check, so with the `kde` and
/// `portal` features the two can then differ in both directions where a
/// portal backend answers: a KDE backend without `kdeglobals` gives
/// `kde-breeze` in `from_system` and `adwaita` here, a GNOME backend with
/// `kdeglobals` gives `adwaita` in `from_system` and `kde-breeze` here.
///
/// Returns a [`PlatformPreset`] with the user-facing preset name. Showcase
/// UIs use `preset.name` to build the "default (...)" label.
///
/// # Examples
///
/// ```
/// let preset = native_theme::pipeline::platform_preset_name();
/// println!("Platform preset: {}", preset.name);
/// ```
#[must_use]
pub fn platform_preset_name() -> PlatformPreset {
    #[cfg(all(target_os = "macos", feature = "macos"))]
    {
        macos_generation(crate::macos::os_version()).0
    }
    // Without the reader feature the version cannot be read: the oldest
    // generation's preset.
    #[cfg(all(target_os = "macos", not(feature = "macos")))]
    {
        PlatformPreset {
            name: MACOS_GENERATIONS.oldest.preset,
        }
    }
    #[cfg(all(target_os = "windows", feature = "windows"))]
    {
        windows_generation(crate::windows::os_version()).0
    }
    #[cfg(all(target_os = "windows", not(feature = "windows")))]
    {
        PlatformPreset {
            name: WINDOWS_GENERATIONS.oldest.preset,
        }
    }
    #[cfg(target_os = "linux")]
    {
        linux_preset_for_de(crate::detect::system().refined_linux_desktop_sync())
    }
    #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
    {
        PlatformPreset { name: "adwaita" }
    }
}

/// Check whether OS theme detection is available on this platform.
///
/// Returns a list of [`DiagnosticEntry`] values describing what detection
/// capabilities are available and what might be missing. Useful for
/// debugging theme detection failures in end-user applications.
///
/// Each entry can be printed directly via its `Display` impl, or
/// inspected programmatically via [`DiagnosticEntry::name()`],
/// [`DiagnosticEntry::status()`], and [`DiagnosticEntry::detail()`].
///
/// # Platform Behavior
///
/// - **Linux:** Reports detected desktop environment, `gsettings`
///   availability, `XDG_CURRENT_DESKTOP` value, and KDE config file
///   presence (when the `kde` feature is enabled).
/// - **macOS:** Reports whether the `macos` feature is enabled and, with it,
///   the running version and its generation's preset
///   ([`DiagnosticEntry::OsGeneration`]).
/// - **Windows:** Reports whether the `windows` feature is enabled and, with
///   it, the running version and its generation's preset
///   ([`DiagnosticEntry::OsGeneration`]).
/// - **Other:** Reports that no platform detection is available.
///
/// # Examples
///
/// ```
/// let diagnostics = native_theme::pipeline::diagnose_platform_support();
/// for entry in &diagnostics {
///     println!("{entry}");
/// }
/// ```
#[must_use]
pub fn diagnose_platform_support() -> Vec<DiagnosticEntry> {
    let mut diagnostics = Vec::new();

    #[cfg(target_os = "linux")]
    {
        diagnostics.push(DiagnosticEntry::Platform("Linux"));

        // Check XDG_CURRENT_DESKTOP
        match std::env::var("XDG_CURRENT_DESKTOP") {
            Ok(val) if !val.is_empty() => {
                let de = parse_linux_desktop(&val);
                diagnostics.push(DiagnosticEntry::EnvVar {
                    name: "XDG_CURRENT_DESKTOP",
                    value: val,
                });
                diagnostics.push(DiagnosticEntry::DesktopEnv(de));
            }
            _ => {
                diagnostics.push(DiagnosticEntry::EnvVarMissing("XDG_CURRENT_DESKTOP"));
                diagnostics.push(DiagnosticEntry::DesktopEnv(LinuxDesktop::Unknown));
            }
        }

        // Check gsettings availability
        match crate::detect::run_with_timeout(
            "gsettings",
            &["--version"],
            crate::detect::SUBPROCESS_TIMEOUT,
        ) {
            Ok(output) if output.status.success() => {
                let version = String::from_utf8_lossy(&output.stdout).trim().to_string();
                diagnostics.push(DiagnosticEntry::ToolAvailable {
                    name: "gsettings",
                    version,
                });
            }
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                diagnostics.push(DiagnosticEntry::ToolMissing {
                    name: "gsettings",
                    impact: "dark mode and icon theme detection may be limited",
                });
            }
            Ok(_) | Err(_) => {
                diagnostics.push(DiagnosticEntry::ToolError("gsettings"));
            }
        }

        // Check KDE config files
        #[cfg(feature = "kde")]
        {
            match crate::kde::kdeglobals_path() {
                Some(path) if path.exists() => {
                    diagnostics.push(DiagnosticEntry::ConfigFound {
                        name: "KDE kdeglobals",
                        path,
                    });
                }
                Some(path) => {
                    diagnostics.push(DiagnosticEntry::ConfigMissing {
                        name: "KDE kdeglobals",
                        path,
                    });
                }
                None => diagnostics.push(DiagnosticEntry::EnvVarMissing("HOME")),
            }
        }

        #[cfg(not(feature = "kde"))]
        {
            diagnostics.push(DiagnosticEntry::FeatureDisabled {
                feature: "KDE",
                impact: "kde feature not enabled",
            });
        }

        // Report portal feature status
        #[cfg(feature = "portal")]
        diagnostics.push(DiagnosticEntry::FeatureEnabled("Portal"));

        #[cfg(not(feature = "portal"))]
        diagnostics.push(DiagnosticEntry::FeatureDisabled {
            feature: "Portal",
            impact: "portal feature not enabled",
        });
    }

    #[cfg(target_os = "macos")]
    {
        diagnostics.push(DiagnosticEntry::Platform("macOS"));

        #[cfg(feature = "macos")]
        {
            diagnostics.push(DiagnosticEntry::FeatureEnabled("macOS theme detection"));
            let running = crate::macos::os_version();
            let (preset, version_match) = macos_generation(running);
            diagnostics.push(DiagnosticEntry::OsGeneration {
                version: running.to_string(),
                preset: preset.name,
                version_match,
            });
        }

        #[cfg(not(feature = "macos"))]
        diagnostics.push(DiagnosticEntry::FeatureDisabled {
            feature: "macOS theme detection",
            impact: "macos feature not enabled, using subprocess fallback",
        });
    }

    #[cfg(target_os = "windows")]
    {
        diagnostics.push(DiagnosticEntry::Platform("Windows"));

        #[cfg(feature = "windows")]
        {
            diagnostics.push(DiagnosticEntry::FeatureEnabled("Windows theme detection"));
            let running = crate::windows::os_version();
            let (preset, version_match) = windows_generation(running);
            diagnostics.push(DiagnosticEntry::OsGeneration {
                version: running.to_string(),
                preset: preset.name,
                version_match,
            });
        }

        #[cfg(not(feature = "windows"))]
        diagnostics.push(DiagnosticEntry::FeatureDisabled {
            feature: "Windows theme detection",
            impact: "windows feature not enabled",
        });
    }

    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
    {
        diagnostics.push(DiagnosticEntry::Platform(
            "unsupported (no native theme detection available)",
        ));
    }

    diagnostics
}

/// Build a `ReaderResult` from a preset (for fallback paths where no
/// platform reader is available).
#[cfg(any(target_os = "linux", test))]
fn preset_as_reader(preset_name: &str, mode: crate::ColorMode) -> crate::Result<ReaderResult> {
    let theme = Theme::preset(preset_name)?;
    let is_dark = mode == crate::ColorMode::Dark;
    let output = if is_dark {
        ReaderOutput::Single {
            mode: Box::new(theme.dark.unwrap_or_default()),
            is_dark: true,
        }
    } else {
        ReaderOutput::Single {
            mode: Box::new(theme.light.unwrap_or_default()),
            is_dark: false,
        }
    };
    Ok(ReaderResult {
        output,
        name: theme.name,
        icon_set: theme.icon_set,
        layout: theme.layout,
        font_dpi: None,
        accessibility: crate::AccessibilityPreferences::default(),
    })
}

/// The platform reader [`select_reader`] picked, the preset its output merges
/// over, and how the running OS version relates to that preset's generation.
pub(crate) struct SelectedReader {
    /// The platform reader.
    pub(crate) reader: Box<dyn crate::reader::ThemeReader>,
    /// The platform preset [`run_pipeline`] merges the reader's output over.
    pub(crate) preset: &'static str,
    /// `None` where the platform has no generation table (Linux).
    pub(crate) version_match: Option<VersionMatch>,
}

impl SelectedReader {
    /// A reader of a platform without a generation table (Linux).
    #[cfg_attr(
        not(all(target_os = "linux", any(feature = "kde", feature = "portal"))),
        allow(dead_code)
    )]
    fn unversioned(reader: Box<dyn crate::reader::ThemeReader>, preset: &'static str) -> Self {
        Self {
            reader,
            preset,
            version_match: None,
        }
    }
}

/// Platform + DE + feature cascade that picks the appropriate
/// [`crate::reader::ThemeReader`] impl for the current system.
///
/// Returns `None` when no reader is available and the caller must fall back
/// to a preset-only pipeline (non-KDE/GNOME Linux, unsupported platforms, or
/// platforms whose reader feature is disabled). When `Some`, the
/// [`SelectedReader`] names the platform preset to pass to [`run_pipeline`] —
/// the reader and the preset are tied because the preset is chosen from the
/// detected DE on Linux and from the running version's generation on macOS
/// and Windows ([`preset_for_version`]).
///
/// Per plan 94-03 §G8: the `Box<dyn ThemeReader>` trait object is object-safe
/// only because the trait carries a `#[async_trait::async_trait]` annotation
/// (see [`crate::reader`] module docs for the full rationale).
#[allow(unreachable_code)]
#[allow(clippy::unnecessary_wraps)] // Option is part of the public contract.
#[allow(clippy::needless_return)] // Explicit returns clarify cfg-gated dispatch.
pub(crate) async fn select_reader() -> Option<SelectedReader> {
    #[cfg(target_os = "macos")]
    {
        #[cfg(feature = "macos")]
        {
            let (preset, matched) = macos_generation(crate::macos::os_version());
            return Some(SelectedReader {
                reader: Box::new(crate::macos::MacosReader),
                preset: preset.name,
                version_match: Some(matched),
            });
        }
        #[cfg(not(feature = "macos"))]
        return None;
    }

    #[cfg(target_os = "windows")]
    {
        #[cfg(feature = "windows")]
        {
            let (preset, matched) = windows_generation(crate::windows::os_version());
            return Some(SelectedReader {
                reader: Box::new(crate::windows::WindowsReader),
                preset: preset.name,
                version_match: Some(matched),
            });
        }
        #[cfg(not(feature = "windows"))]
        return None;
    }

    #[cfg(target_os = "linux")]
    {
        return linux_reader(crate::detect::system().refined_linux_desktop().await);
    }

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

/// A Linux platform reader.
#[cfg(target_os = "linux")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LinuxReader {
    /// [`crate::kde::KdeReader`].
    #[cfg(feature = "kde")]
    Kde,
    /// [`crate::gnome::GnomePortalKdeReader`]: the KDE reader with the
    /// portal's accent colour.
    #[cfg(all(feature = "kde", feature = "portal"))]
    PortalKde,
    /// [`crate::gnome::GnomeReader`].
    #[cfg(feature = "portal")]
    Gnome,
}

/// The reader of `refined`, the refined desktop
/// ([`crate::detect::refine_desktop`]) the watcher and the icon-theme
/// detection also decide by: KDE's, with the portal's accent colour where the
/// `portal` feature is on and `XDG_CURRENT_DESKTOP` or the portal backend
/// named KDE; GNOME's for GNOME and Budgie; `None` for the other desktops and
/// where the reader's feature is off. A KDE named by `kdeglobals` alone gets
/// the plain KDE reader: no portal backend answered, so an accent read would
/// ask a portal that is not KDE's, or wait out a second deadline.
#[cfg(target_os = "linux")]
fn linux_reader_kind(refined: crate::detect::RefinedDesktop) -> Option<LinuxReader> {
    match refined.desktop {
        #[cfg(all(feature = "kde", feature = "portal"))]
        LinuxDesktop::Kde if refined.by_kdeglobals => Some(LinuxReader::Kde),
        #[cfg(all(feature = "kde", feature = "portal"))]
        LinuxDesktop::Kde => Some(LinuxReader::PortalKde),
        #[cfg(all(feature = "kde", not(feature = "portal")))]
        LinuxDesktop::Kde => Some(LinuxReader::Kde),
        #[cfg(not(feature = "kde"))]
        LinuxDesktop::Kde => None,
        #[cfg(feature = "portal")]
        LinuxDesktop::Gnome | LinuxDesktop::Budgie => Some(LinuxReader::Gnome),
        #[cfg(not(feature = "portal"))]
        LinuxDesktop::Gnome | LinuxDesktop::Budgie => None,
        LinuxDesktop::Xfce
        | LinuxDesktop::Cinnamon
        | LinuxDesktop::Mate
        | LinuxDesktop::LxQt
        | LinuxDesktop::Hyprland
        | LinuxDesktop::Sway
        | LinuxDesktop::River
        | LinuxDesktop::Niri
        | LinuxDesktop::Wayfire
        | LinuxDesktop::CosmicDe
        | LinuxDesktop::Unknown => None,
    }
}

/// [`linux_reader_kind`]'s reader, with the preset of `refined`'s desktop.
#[cfg(all(target_os = "linux", any(feature = "kde", feature = "portal")))]
fn linux_reader(refined: crate::detect::RefinedDesktop) -> Option<SelectedReader> {
    let reader: Box<dyn crate::reader::ThemeReader> = match linux_reader_kind(refined)? {
        #[cfg(feature = "kde")]
        LinuxReader::Kde => Box::new(crate::kde::KdeReader),
        #[cfg(all(feature = "kde", feature = "portal"))]
        LinuxReader::PortalKde => Box::new(crate::gnome::GnomePortalKdeReader),
        #[cfg(feature = "portal")]
        LinuxReader::Gnome => Box::new(crate::gnome::GnomeReader),
    };
    Some(SelectedReader::unversioned(
        reader,
        linux_preset_for_de(refined.desktop).name,
    ))
}

/// [`linux_reader_kind`]'s reader: none without `kde` and `portal`, where
/// `LinuxReader` has no variant.
#[cfg(all(target_os = "linux", not(any(feature = "kde", feature = "portal"))))]
fn linux_reader(refined: crate::detect::RefinedDesktop) -> Option<SelectedReader> {
    match linux_reader_kind(refined)? {}
}

/// Single async implementation for all platforms. On Linux this may contain
/// `.await` points (portal D-Bus calls); on macOS/Windows the future resolves
/// immediately (no `.await` points).
///
/// Called by:
/// - `from_system()` via `pollster::block_on`.
/// - `from_system_async()` via `.await`.
///
/// Delegates platform detection to [`select_reader`]: when a reader is
/// available, its output feeds [`run_pipeline`]; when no reader is available,
/// falls back to a preset-only pipeline or returns a feature/platform error.
#[allow(unreachable_code)]
#[allow(clippy::needless_return)] // Explicit returns clarify cfg-gated fallback.
pub(crate) async fn from_system_inner() -> crate::Result<SystemTheme> {
    if let Some(selected) = select_reader().await {
        let mut theme = read_through_pipeline(
            selected.reader.as_ref(),
            selected.preset,
            crate::detect::system(),
        )
        .await?;
        theme.version_match = selected.version_match;
        return Ok(theme);
    }

    // Preset-only fallback paths — no reader available for this
    // platform+feature combination.
    #[cfg(target_os = "macos")]
    {
        return Err(crate::Error::FeatureDisabled {
            name: "macos",
            needed_for: "macOS theme detection",
        });
    }
    #[cfg(target_os = "windows")]
    {
        return Err(crate::Error::FeatureDisabled {
            name: "windows",
            needed_for: "Windows theme detection",
        });
    }
    #[cfg(target_os = "linux")]
    {
        return linux_fallback(
            platform_preset_name(),
            crate::detect::detect_is_dark(),
            readerless_accessibility(),
        );
    }
    #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
    {
        Err(crate::Error::PlatformUnsupported {
            platform: std::env::consts::OS,
        })
    }
}

/// The Linux theme where no reader is available: `preset` alone, as both
/// the reader's output and the base it merges over, in the mode `is_dark`
/// names, with `accessibility`. [`from_system_inner`] passes the uncached
/// [`crate::detect::detect_is_dark`], as the readers read the mode fresh, and
/// [`readerless_accessibility`], as [`reader_accessibility`] does.
#[cfg(target_os = "linux")]
fn linux_fallback(
    preset: PlatformPreset,
    is_dark: bool,
    accessibility: crate::AccessibilityPreferences,
) -> crate::Result<SystemTheme> {
    let mode = if is_dark {
        crate::ColorMode::Dark
    } else {
        crate::ColorMode::Light
    };
    let mut reader = preset_as_reader(preset.name, mode)?;
    reader.accessibility = accessibility;
    run_pipeline(reader, preset.name)
}

/// Run `reader` and feed its output through [`run_pipeline`] onto `preset`.
/// The reader's accessibility block is stored in `detection`, so
/// [`crate::detect::accessibility_preferences`] need not run it again.
async fn read_through_pipeline(
    reader: &dyn crate::reader::ThemeReader,
    preset: &str,
    detection: &crate::detect::DetectionContext,
) -> crate::Result<SystemTheme> {
    let fill = detection.begin_reader_accessibility();
    let result = reader.read().await?;
    detection.store_reader_accessibility(fill, result.accessibility.clone());
    run_pipeline(result, preset)
}

/// [`crate::SystemTheme::from_system_with_preset`]'s body: `preset` must be a
/// generation of the running platform's table (M1-T1-04).
#[allow(unreachable_code)]
#[allow(clippy::needless_return)]
// Explicit returns clarify cfg-gated dispatch.
// Without the reader feature the name is never read: the feature error comes first.
#[cfg_attr(
    any(
        all(target_os = "macos", not(feature = "macos")),
        all(target_os = "windows", not(feature = "windows"))
    ),
    allow(unused_variables)
)]
pub(crate) async fn from_system_with_preset_inner(preset: &str) -> crate::Result<SystemTheme> {
    #[cfg(all(target_os = "macos", feature = "macos"))]
    {
        return pinned_pipeline(
            &MACOS_GENERATIONS,
            macos_major(crate::macos::os_version()),
            preset,
            &crate::macos::MacosReader,
            crate::detect::system(),
        )
        .await;
    }
    #[cfg(all(target_os = "windows", feature = "windows"))]
    {
        return pinned_pipeline(
            &WINDOWS_GENERATIONS,
            crate::windows::os_version(),
            preset,
            &crate::windows::WindowsReader,
            crate::detect::system(),
        )
        .await;
    }
    #[cfg(all(target_os = "macos", not(feature = "macos")))]
    {
        return Err(crate::Error::FeatureDisabled {
            name: "macos",
            needed_for: "macOS theme detection",
        });
    }
    #[cfg(all(target_os = "windows", not(feature = "windows")))]
    {
        return Err(crate::Error::FeatureDisabled {
            name: "windows",
            needed_for: "Windows theme detection",
        });
    }
    // No generation table, so no OS generations to choose between: Linux,
    // whose readers read the installed style, BSD and other platforms.
    Err(crate::Error::UnknownPreset {
        name: preset.to_string(),
        known: &[],
    })
}

/// Run `reader` through the pipeline onto `preset`, a row of `table`, and
/// report that row's generation against `running`.
#[cfg_attr(
    not(any(
        all(target_os = "macos", feature = "macos"),
        all(target_os = "windows", feature = "windows")
    )),
    allow(dead_code)
)]
async fn pinned_pipeline(
    table: &GenerationTable,
    running: OsVersion,
    preset: &str,
    reader: &dyn crate::reader::ThemeReader,
    detection: &crate::detect::DetectionContext,
) -> crate::Result<SystemTheme> {
    let Some(row) = table.row(preset) else {
        return Err(crate::Error::UnknownPreset {
            name: preset.to_string(),
            known: table.keys,
        });
    };
    let mut theme = read_through_pipeline(reader, row.preset, detection).await?;
    theme.version_match = Some(version_match(&row, running));
    Ok(theme)
}

/// Runs the same platform reader `from_system_inner` would run and returns its
/// accessibility block without merging or resolving a theme. Where no reader
/// is available (or it fails) [`readerless_accessibility`] is used.
pub(crate) async fn reader_accessibility() -> crate::AccessibilityPreferences {
    match select_reader().await {
        Some(selected) => match selected.reader.read().await {
            Ok(result) => result.accessibility,
            Err(_) => readerless_accessibility(),
        },
        None => readerless_accessibility(),
    }
}

/// The accessibility block where no reader supplies one: the defaults, with
/// `reduce_motion` the platform's reduced-motion read, the one the readers
/// make ([`crate::detect::detect_reduced_motion`]).
fn readerless_accessibility() -> crate::AccessibilityPreferences {
    crate::AccessibilityPreferences {
        reduce_motion: crate::detect::detect_reduced_motion(),
        ..Default::default()
    }
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(all(test, target_os = "linux"))]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod dispatch_tests {
    use super::*;

    // -- parse_linux_desktop() pure function tests --

    #[test]
    fn detect_kde_simple() {
        assert_eq!(parse_linux_desktop("KDE"), LinuxDesktop::Kde);
    }

    #[test]
    fn detect_kde_colon_separated_after() {
        assert_eq!(parse_linux_desktop("ubuntu:KDE"), LinuxDesktop::Kde);
    }

    #[test]
    fn detect_kde_colon_separated_before() {
        assert_eq!(parse_linux_desktop("KDE:plasma"), LinuxDesktop::Kde);
    }

    #[test]
    fn detect_gnome_simple() {
        assert_eq!(parse_linux_desktop("GNOME"), LinuxDesktop::Gnome);
    }

    #[test]
    fn detect_gnome_ubuntu() {
        assert_eq!(parse_linux_desktop("ubuntu:GNOME"), LinuxDesktop::Gnome);
    }

    #[test]
    fn detect_xfce() {
        assert_eq!(parse_linux_desktop("XFCE"), LinuxDesktop::Xfce);
    }

    #[test]
    fn detect_cinnamon() {
        assert_eq!(parse_linux_desktop("X-Cinnamon"), LinuxDesktop::Cinnamon);
    }

    #[test]
    fn detect_cinnamon_short() {
        assert_eq!(parse_linux_desktop("Cinnamon"), LinuxDesktop::Cinnamon);
    }

    #[test]
    fn detect_mate() {
        assert_eq!(parse_linux_desktop("MATE"), LinuxDesktop::Mate);
    }

    #[test]
    fn detect_lxqt() {
        assert_eq!(parse_linux_desktop("LXQt"), LinuxDesktop::LxQt);
    }

    #[test]
    fn detect_budgie() {
        assert_eq!(parse_linux_desktop("Budgie:GNOME"), LinuxDesktop::Budgie);
    }

    #[test]
    fn detect_empty_string() {
        assert_eq!(parse_linux_desktop(""), LinuxDesktop::Unknown);
    }

    // -- Pure pipeline dispatch tests (no env var manipulation) --

    #[test]
    fn from_linux_non_kde_returns_adwaita() -> crate::Result<()> {
        // GNOME desktop produces an Adwaita-named theme via the pure pipeline
        let preset = linux_preset_for_de(LinuxDesktop::Gnome);
        let result = preset_as_reader("adwaita", crate::ColorMode::Light)?;
        let theme = run_pipeline(result, preset.name)?;
        assert_eq!(theme.name, "Adwaita");
        Ok(())
    }

    #[test]
    #[cfg(feature = "kde")]
    fn from_linux_unknown_de_with_kdeglobals_fallback() -> crate::Result<()> {
        // Unknown DE with a kdeglobals file uses KDE reader -- test the dispatch
        // branch by calling from_kde_content_pure directly with minimal fixture.
        const MINIMAL_KDE_FIXTURE: &str = "\
[General]
ColorScheme=TestTheme

[Colors:Window]
BackgroundNormal=239,240,241

[Colors:View]
BackgroundNormal=252,252,252
ForegroundNormal=35,38,41
DecorationFocus=61,174,233
BackgroundAlternate=239,240,241
ForegroundLink=41,128,185";

        let (reader_theme, dpi, acc) =
            crate::kde::from_kde_content_pure(MINIMAL_KDE_FIXTURE, None)?;
        let is_dark = reader_theme.dark.is_some() && reader_theme.light.is_none();
        let output = if is_dark {
            ReaderOutput::Single {
                mode: Box::new(reader_theme.dark.unwrap_or_default()),
                is_dark: true,
            }
        } else {
            ReaderOutput::Single {
                mode: Box::new(reader_theme.light.unwrap_or_default()),
                is_dark: false,
            }
        };
        let result = ReaderResult {
            output,
            name: reader_theme.name,
            icon_set: reader_theme.icon_set,
            layout: reader_theme.layout,
            font_dpi: dpi,
            accessibility: acc,
        };
        let preset = linux_preset_for_de(LinuxDesktop::Kde);
        let theme = run_pipeline(result, preset.name)?;
        assert_eq!(
            theme.name, "TestTheme",
            "should use KDE theme name from reader output"
        );
        Ok(())
    }

    #[test]
    fn from_linux_unknown_de_without_kdeglobals_returns_adwaita() -> crate::Result<()> {
        // Unknown DE without kdeglobals falls back to Adwaita preset
        let preset = linux_preset_for_de(LinuxDesktop::Unknown);
        let result = preset_as_reader("adwaita", crate::ColorMode::Light)?;
        let theme = run_pipeline(result, preset.name)?;
        assert_eq!(
            theme.name, "Adwaita",
            "should fall back to Adwaita without kdeglobals"
        );
        Ok(())
    }

    /// The preset's own theme: both variants straight from the preset.
    fn preset_theme(preset: &str) -> SystemTheme {
        let theme = Theme::preset(preset).unwrap();
        let reader = ReaderResult {
            output: ReaderOutput::Dual {
                light: Box::new(theme.light.unwrap_or_default()),
                dark: Box::new(theme.dark.unwrap_or_default()),
                is_dark: false,
            },
            name: theme.name,
            icon_set: theme.icon_set,
            layout: theme.layout,
            font_dpi: None,
            accessibility: crate::AccessibilityPreferences::default(),
        };
        run_pipeline(reader, preset).unwrap()
    }

    #[test]
    fn the_fallback_on_kde_is_the_whole_breeze_preset() {
        let expected = preset_theme("kde-breeze");
        for is_dark in [false, true] {
            let st = linux_fallback(
                linux_preset_for_de(LinuxDesktop::Kde),
                is_dark,
                crate::AccessibilityPreferences::default(),
            )
            .unwrap();
            assert_eq!(st.preset, "kde-breeze");
            assert_eq!(st.name, expected.name, "is_dark {is_dark}");
            assert_eq!(st.light, expected.light, "is_dark {is_dark}");
            assert_eq!(st.dark, expected.dark, "is_dark {is_dark}");
            assert_eq!(
                st.icon_theme_for(crate::ColorMode::Light),
                expected.icon_theme_for(crate::ColorMode::Light)
            );
            assert_eq!(
                st.icon_theme_for(crate::ColorMode::Dark),
                expected.icon_theme_for(crate::ColorMode::Dark)
            );
        }
    }

    #[test]
    fn the_fallback_on_other_desktops_is_the_whole_adwaita_preset() {
        let expected = preset_theme("adwaita");
        let st = linux_fallback(
            linux_preset_for_de(LinuxDesktop::Xfce),
            true,
            crate::AccessibilityPreferences::default(),
        )
        .unwrap();
        assert_eq!(st.preset, "adwaita");
        assert_eq!(st.name, expected.name);
        assert_eq!(st.light, expected.light);
        assert_eq!(st.dark, expected.dark);
    }

    #[test]
    fn the_fallback_mode_is_the_dark_reading_it_is_given() {
        let preset = || linux_preset_for_de(LinuxDesktop::Unknown);
        let none = crate::AccessibilityPreferences::default;
        assert_eq!(
            linux_fallback(preset(), true, none()).unwrap().mode,
            crate::ColorMode::Dark
        );
        assert_eq!(
            linux_fallback(preset(), false, none()).unwrap().mode,
            crate::ColorMode::Light
        );
    }

    /// Without a reader the theme carries the accessibility block
    /// `AccessibilityPreferences::from_system` reads there
    /// (`readerless_accessibility`), so the two agree on reduced motion.
    #[test]
    fn the_fallback_carries_the_accessibility_it_is_given() {
        let reduced = crate::AccessibilityPreferences {
            reduce_motion: true,
            ..Default::default()
        };
        let st = linux_fallback(
            linux_preset_for_de(LinuxDesktop::Xfce),
            false,
            reduced.clone(),
        )
        .unwrap();
        assert_eq!(st.accessibility, reduced);
    }

    #[test]
    fn an_unknown_desktop_with_kdeglobals_maps_to_breeze() {
        let preset = |de, exists| {
            linux_preset_for_de(crate::detect::refine_linux_desktop(de, None, || exists)).name
        };
        assert_eq!(preset(LinuxDesktop::Unknown, true), "kde-breeze");
        assert_eq!(preset(LinuxDesktop::Unknown, false), "adwaita");
        assert_eq!(preset(LinuxDesktop::Kde, false), "kde-breeze");
        assert_eq!(preset(LinuxDesktop::Gnome, true), "adwaita");
        assert_eq!(preset(LinuxDesktop::Xfce, true), "adwaita");
    }

    /// The reader `linux_reader_kind` picks for an unrecognised desktop with
    /// `portal_backend` and, or without, `kdeglobals`.
    fn unknown_desktop_reader(
        portal_backend: Option<LinuxDesktop>,
        kdeglobals: bool,
    ) -> Option<LinuxReader> {
        linux_reader_kind(crate::detect::refine_desktop(
            LinuxDesktop::Unknown,
            portal_backend,
            || kdeglobals,
        ))
    }

    /// A KDE portal backend gets the KDE reader with the portal's accent,
    /// `kdeglobals` or not, as `XDG_CURRENT_DESKTOP=KDE` does.
    #[test]
    #[cfg(all(feature = "kde", feature = "portal"))]
    fn an_unknown_desktop_with_a_kde_portal_gets_the_kde_reader() {
        for kdeglobals in [false, true] {
            assert_eq!(
                unknown_desktop_reader(Some(LinuxDesktop::Kde), kdeglobals),
                Some(LinuxReader::PortalKde)
            );
        }
        assert_eq!(
            linux_reader_kind(crate::detect::refine_desktop(
                LinuxDesktop::Kde,
                None,
                || false
            )),
            Some(LinuxReader::PortalKde)
        );
    }

    /// A GNOME portal backend gets the GNOME reader, `kdeglobals` or not.
    #[test]
    #[cfg(feature = "portal")]
    fn an_unknown_desktop_with_a_gnome_portal_gets_the_gnome_reader() {
        for kdeglobals in [false, true] {
            assert_eq!(
                unknown_desktop_reader(Some(LinuxDesktop::Gnome), kdeglobals),
                Some(LinuxReader::Gnome)
            );
        }
    }

    /// Without a portal answer, `kdeglobals` gets the plain KDE reader, with
    /// or without the `portal` feature; with neither there is no reader.
    #[test]
    fn an_unknown_desktop_without_a_portal_answer() {
        #[cfg(feature = "kde")]
        assert_eq!(unknown_desktop_reader(None, true), Some(LinuxReader::Kde));
        assert_eq!(unknown_desktop_reader(None, false), None);
    }

    /// A KDE reader merges over kde-breeze, the GNOME reader over adwaita.
    #[test]
    #[cfg(all(feature = "kde", feature = "portal"))]
    fn the_linux_readers_presets() {
        let preset = |portal_backend, kdeglobals| {
            linux_reader(crate::detect::refine_desktop(
                LinuxDesktop::Unknown,
                portal_backend,
                || kdeglobals,
            ))
            .map(|selected| selected.preset)
        };
        assert_eq!(preset(Some(LinuxDesktop::Kde), false), Some("kde-breeze"));
        assert_eq!(preset(None, true), Some("kde-breeze"));
        assert_eq!(preset(Some(LinuxDesktop::Gnome), true), Some("adwaita"));
    }

    // -- LNXDE-03: Hyprland, Sway, COSMIC, River, Niri map to their own variants --

    #[test]
    fn detect_hyprland() {
        assert_eq!(parse_linux_desktop("Hyprland"), LinuxDesktop::Hyprland);
    }

    #[test]
    fn detect_sway() {
        assert_eq!(parse_linux_desktop("sway"), LinuxDesktop::Sway);
    }

    #[test]
    fn detect_cosmic() {
        assert_eq!(parse_linux_desktop("COSMIC"), LinuxDesktop::CosmicDe);
    }

    #[test]
    fn detect_river() {
        assert_eq!(parse_linux_desktop("river"), LinuxDesktop::River);
    }

    #[test]
    fn detect_niri() {
        assert_eq!(parse_linux_desktop("niri"), LinuxDesktop::Niri);
    }

    #[test]
    fn parses_xdg_wayfire() {
        assert_eq!(parse_linux_desktop("Wayfire"), LinuxDesktop::Wayfire);
        assert_eq!(parse_linux_desktop("Wayfire:GNOME"), LinuxDesktop::Wayfire);
    }

    #[test]
    fn parses_xdg_empty_is_unknown() {
        // Regression guard -- empty XDG_CURRENT_DESKTOP must keep mapping to Unknown
        // even after the Wayfire variant addition.
        assert_eq!(parse_linux_desktop(""), LinuxDesktop::Unknown);
    }

    #[test]
    fn detect_cosmic_full_desktop() {
        assert_eq!(
            parse_linux_desktop("COSMIC:Freedesktop"),
            LinuxDesktop::CosmicDe
        );
    }

    // -- Pure pipeline smoke test (replaces from_system env var test) --

    #[test]
    fn from_system_returns_result() {
        // Test the pure pipeline directly instead of mocking env vars for from_system()
        let result = preset_as_reader("adwaita", crate::ColorMode::Light).unwrap();
        let theme = run_pipeline(result, "adwaita")
            .expect("run_pipeline should succeed with adwaita preset");
        assert_eq!(theme.name, "Adwaita");
    }
}

/// Tests for run_pipeline() -- internal pipeline functions.
/// These test functions moved from system_theme_tests in lib.rs since they
/// directly test pipeline internals rather than the SystemTheme public API.
#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::field_reassign_with_default
)]
mod pipeline_tests {
    use crate::color::Rgba;
    use crate::model::{LayoutTheme, Theme, ThemeMode};
    use crate::{ReaderOutput, ReaderResult};

    use super::{preset_as_reader, read_through_pipeline, run_pipeline};

    /// Helper: build a ReaderResult from a preset for testing.
    fn reader_from_preset(preset_name: &str) -> ReaderResult {
        let preset = Theme::preset(preset_name).unwrap();
        ReaderResult {
            output: ReaderOutput::Dual {
                light: Box::new(preset.light.clone().unwrap_or_default()),
                dark: Box::new(preset.dark.clone().unwrap_or_default()),
                is_dark: false,
            },
            name: preset.name,
            icon_set: preset.icon_set,
            layout: preset.layout,
            font_dpi: None,
            accessibility: crate::AccessibilityPreferences::default(),
        }
    }

    // --- run_pipeline() tests ---

    /// The reader's font DPI goes into the context both variants share: one
    /// that is not finite and positive is one violation, on
    /// `context.font_dpi`, with no variant table.
    #[test]
    fn run_pipeline_rejects_a_bad_reader_font_dpi_once() {
        for font_dpi in [0.0, -1.0, f32::NAN] {
            let reader = ReaderResult {
                font_dpi: Some(font_dpi),
                ..reader_from_preset("kde-breeze")
            };
            let result = run_pipeline(reader, "kde-breeze");
            let Err(crate::Error::ResolutionInvalid { errors }) = result else {
                panic!("font_dpi {font_dpi}: expected ResolutionInvalid");
            };
            let paths: Vec<&str> = errors.iter().map(|rv| rv.path.as_str()).collect();
            assert_eq!(paths, ["context.font_dpi"], "font_dpi {font_dpi}");
        }
    }

    #[test]
    fn test_run_pipeline_produces_both_variants() {
        let reader = reader_from_preset("catppuccin-mocha");
        let result = run_pipeline(reader, "catppuccin-mocha");
        assert!(result.is_ok(), "run_pipeline should succeed");
        let st = result.unwrap();
        // Both light and dark exist as ResolvedTheme (non-Option)
        assert!(!st.name.is_empty(), "name should be populated");
        // If we get here, both variants validated successfully
    }

    #[test]
    fn test_run_pipeline_reader_values_win() {
        // Create a reader output where the reader provides a custom accent
        // (simulating a platform reader that detected this accent from the OS)
        let custom_accent = Rgba::rgb(42, 100, 200);
        let mut variant = ThemeMode::default();
        variant.defaults.accent_color = Some(custom_accent);

        let reader = ReaderResult {
            output: ReaderOutput::Single {
                mode: Box::new(variant),
                is_dark: false,
            },
            name: "CustomTheme".into(),
            icon_set: None,
            layout: LayoutTheme::default(),
            font_dpi: None,
            accessibility: crate::AccessibilityPreferences::default(),
        };

        let result = run_pipeline(reader, "catppuccin-mocha");
        assert!(result.is_ok(), "run_pipeline should succeed");
        let st = result.unwrap();
        // The reader's accent should win over the preset's accent
        assert_eq!(
            st.light.defaults.accent_color, custom_accent,
            "reader accent should win over preset accent"
        );
        assert_eq!(st.name, "CustomTheme", "reader name should win");
    }

    #[test]
    fn test_run_pipeline_single_variant() {
        // Simulate a real OS reader that provides a complete dark variant
        // (like KDE's from_kde() would) but no light variant.
        let full = Theme::preset("kde-breeze").unwrap();
        let mut dark_v = full.dark.clone().unwrap();
        // Override accent to prove reader values win (simulating OS-detected accent)
        dark_v.defaults.accent_color = Some(Rgba::rgb(200, 50, 50));

        let reader = ReaderResult {
            output: ReaderOutput::Single {
                mode: Box::new(dark_v),
                is_dark: true,
            },
            name: std::borrow::Cow::Borrowed(""),
            icon_set: None,
            layout: LayoutTheme::default(),
            font_dpi: None,
            accessibility: crate::AccessibilityPreferences::default(),
        };

        let result = run_pipeline(reader, "kde-breeze");
        assert!(
            result.is_ok(),
            "run_pipeline should succeed with single variant"
        );
        let st = result.unwrap();
        // Dark should have the reader's overridden accent
        assert_eq!(
            st.dark.defaults.accent_color,
            Rgba::rgb(200, 50, 50),
            "dark variant should have reader accent"
        );
        // Light should still exist (from full preset, which has colors)
        // If we get here, both variants validated successfully
        assert_eq!(st.preset, "kde-breeze");
    }

    #[test]
    fn test_run_pipeline_inactive_variant_from_full_preset() {
        // When reader provides only dark, light must come from the full preset.
        let full = Theme::preset("kde-breeze").unwrap();

        let reader = ReaderResult {
            output: ReaderOutput::Single {
                mode: Box::new(full.dark.clone().unwrap_or_default()),
                is_dark: true,
            },
            name: std::borrow::Cow::Borrowed(""),
            icon_set: None,
            layout: LayoutTheme::default(),
            font_dpi: None,
            accessibility: crate::AccessibilityPreferences::default(),
        };

        let st = run_pipeline(reader, "kde-breeze").unwrap();

        // The light variant should have colors from the full "kde-breeze" preset
        let full_light = full.light.unwrap();
        assert_eq!(
            st.light.defaults.accent_color,
            full_light.defaults.accent_color.unwrap(),
            "inactive light variant should get accent from full preset"
        );
        assert_eq!(
            st.light.defaults.background_color,
            full_light.defaults.background_color.unwrap(),
            "inactive light variant should get background from full preset"
        );
    }

    // --- run_pipeline with preset-as-reader (GNOME double-merge test) ---

    #[test]
    fn test_run_pipeline_with_preset_as_reader() {
        // Simulates GNOME sync fallback: adwaita used as both reader and preset.
        // Double-merge is harmless: merge is idempotent for matching values.
        let reader = reader_from_preset("adwaita");
        let result = run_pipeline(reader, "adwaita");
        assert!(
            result.is_ok(),
            "double-merge with same preset should succeed"
        );
        let st = result.unwrap();
        assert_eq!(st.name, "Adwaita");
    }

    /// Overlays stack: a later `with_overlay` keeps what an earlier one
    /// stated (M3-10), and wins on a field both state.
    #[test]
    fn with_overlay_keeps_an_earlier_overlay() -> crate::Result<()> {
        let st = run_pipeline(reader_from_preset("adwaita"), "adwaita")?;
        let a = Theme::from_toml("[light.defaults]\naccent_color = \"#ff0000\"")?;
        let b = Theme::from_toml("[light.defaults]\nbackground_color = \"#00ff00\"")?;
        let both = st.with_overlay(&a)?.with_overlay(&b)?;
        assert_eq!(both.light.defaults.accent_color, Rgba::rgb(255, 0, 0));
        assert_eq!(both.light.defaults.background_color, Rgba::rgb(0, 255, 0));

        let c = Theme::from_toml("[light.defaults]\naccent_color = \"#0000ff\"")?;
        let all = both.with_overlay(&c)?;
        assert_eq!(all.light.defaults.accent_color, Rgba::rgb(0, 0, 255));
        assert_eq!(all.light.defaults.background_color, Rgba::rgb(0, 255, 0));
        Ok(())
    }

    // --- Single/Dual contract tests ---

    #[test]
    fn test_single_variant_fills_inactive_from_preset() {
        // Simulate KDE-style single-variant reader: only dark variant provided.
        // The pipeline should fill light from the full preset.
        let full = Theme::preset("kde-breeze").unwrap();
        let dark_v = full.dark.clone().unwrap();
        let reader = ReaderResult {
            output: ReaderOutput::Single {
                mode: Box::new(dark_v),
                is_dark: true,
            },
            name: "Breeze Dark".into(),
            icon_set: full.icon_set,
            layout: full.layout.clone(),
            font_dpi: None,
            accessibility: crate::AccessibilityPreferences::default(),
        };

        let st = run_pipeline(reader, "kde-breeze").unwrap();

        // Dark variant should have reader's data (merged with preset).
        // Light variant should come from the full preset (kde-breeze).
        let full_light = Theme::preset("kde-breeze").unwrap().light.unwrap();
        assert_eq!(
            st.light.defaults.accent_color,
            full_light.defaults.accent_color.unwrap(),
            "Single: inactive light variant should come from full preset"
        );
        assert_eq!(st.mode, crate::ColorMode::Dark);
    }

    #[test]
    fn test_dual_variant_uses_both_from_reader() {
        // Simulate macOS-style dual-variant reader: both variants provided.
        // The pipeline should use BOTH reader variants (merged with preset).
        let full = Theme::preset("macos-monterey").unwrap();
        let custom_light_accent = Rgba::rgb(42, 100, 200);
        let custom_dark_accent = Rgba::rgb(200, 50, 50);

        let mut light_v = full.light.clone().unwrap();
        light_v.defaults.accent_color = Some(custom_light_accent);
        let mut dark_v = full.dark.clone().unwrap();
        dark_v.defaults.accent_color = Some(custom_dark_accent);

        let reader = ReaderResult {
            output: ReaderOutput::Dual {
                light: Box::new(light_v),
                dark: Box::new(dark_v),
                is_dark: false,
            },
            name: "macOS Sonoma".into(),
            icon_set: full.icon_set,
            layout: full.layout.clone(),
            font_dpi: Some(72.0),
            accessibility: crate::AccessibilityPreferences::default(),
        };

        let st = run_pipeline(reader, "macos-monterey").unwrap();

        // Both variants should reflect the reader's custom accents (merged).
        assert_eq!(
            st.light.defaults.accent_color, custom_light_accent,
            "Dual: light variant should have reader's light accent"
        );
        assert_eq!(
            st.dark.defaults.accent_color, custom_dark_accent,
            "Dual: dark variant should have reader's dark accent"
        );
    }

    /// A dual-variant reader in dark mode, standing in for the macOS reader
    /// on an OS set to dark: both variants from the preset, `is_dark` true.
    struct DarkDualReader;

    #[async_trait::async_trait]
    impl crate::reader::ThemeReader for DarkDualReader {
        async fn read(&self) -> crate::Result<ReaderResult> {
            let mut reader = reader_from_preset("macos-monterey");
            if let ReaderOutput::Dual { is_dark, .. } = &mut reader.output {
                *is_dark = true;
            }
            Ok(reader)
        }
    }

    #[test]
    fn dual_reader_mode_follows_is_dark() {
        let detection = crate::detect::DetectionContext::new();
        let st = pollster::block_on(read_through_pipeline(
            &DarkDualReader,
            "macos-monterey",
            &detection,
        ))
        .unwrap();
        assert_eq!(
            st.mode,
            crate::ColorMode::Dark,
            "a Dual reader reporting is_dark must give SystemTheme::mode Dark"
        );
    }

    #[test]
    fn a_pinned_older_generation_reports_preset_older() {
        let detection = crate::detect::DetectionContext::new();
        let st = pollster::block_on(super::pinned_pipeline(
            &super::MACOS_GENERATIONS,
            super::OsVersion::new(26, 0, 0),
            "macos-monterey",
            &DarkDualReader,
            &detection,
        ))
        .unwrap();
        assert_eq!(st.preset, "macos-monterey");
        assert_eq!(st.version_match, Some(super::VersionMatch::PresetOlder));
        // with_overlay keeps the match (M1-T1-01 change 2)
        let overlaid = st
            .with_overlay(&Theme::from_toml("name = \"overlay\"").unwrap())
            .unwrap();
        assert_eq!(overlaid.version_match, st.version_match);
    }

    #[test]
    fn a_pinned_name_outside_the_table_is_unknown() {
        let detection = crate::detect::DetectionContext::new();
        let result = pollster::block_on(super::pinned_pipeline(
            &super::MACOS_GENERATIONS,
            super::OsVersion::new(26, 0, 0),
            "kde-breeze",
            &DarkDualReader,
            &detection,
        ));
        assert!(matches!(
            result,
            Err(crate::Error::UnknownPreset { known, .. }) if known == super::MACOS_GENERATIONS.keys
        ));
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn linux_has_no_generation_to_pin() {
        let result = pollster::block_on(super::from_system_with_preset_inner("adwaita"));
        let err = result.err();
        assert!(matches!(
            err,
            Some(crate::Error::UnknownPreset { known: [], .. })
        ));
        assert!(
            err.is_some_and(|e| e
                .to_string()
                .contains("no OS generations to choose between")),
            "pinning a preset on Linux says the platform has no OS generations to choose between"
        );
    }

    /// A reader reporting a text-scaling factor of 1.5, standing in for any
    /// platform reader.
    struct ScaledTextReader;

    #[async_trait::async_trait]
    impl crate::reader::ThemeReader for ScaledTextReader {
        async fn read(&self) -> crate::Result<ReaderResult> {
            let mut reader = reader_from_preset("adwaita");
            reader.accessibility.text_scaling_factor = 1.5;
            Ok(reader)
        }
    }

    #[test]
    fn the_system_read_fills_the_accessibility_cache() {
        let detection = crate::detect::DetectionContext::new();
        let st = pollster::block_on(read_through_pipeline(
            &ScaledTextReader,
            "adwaita",
            &detection,
        ))
        .unwrap();
        let runs = std::cell::Cell::new(0);
        let cached = detection.reader_accessibility_with(|| {
            runs.set(runs.get() + 1);
            crate::AccessibilityPreferences::default()
        });
        assert_eq!(runs.get(), 0, "the cache was empty after the system read");
        assert_eq!(cached, st.accessibility);
        assert_eq!(cached.text_scaling_factor, 1.5);
    }

    /// [`ScaledTextReader`], with the accessibility cache invalidated while
    /// it reads, as a watcher does when the OS changes mid-read.
    struct InvalidatedReader<'a>(&'a crate::detect::DetectionContext);

    #[async_trait::async_trait]
    impl crate::reader::ThemeReader for InvalidatedReader<'_> {
        async fn read(&self) -> crate::Result<ReaderResult> {
            self.0.invalidate_accessibility_preferences();
            ScaledTextReader.read().await
        }
    }

    #[test]
    fn a_system_read_across_an_invalidation_leaves_the_cache_empty() {
        let detection = crate::detect::DetectionContext::new();
        pollster::block_on(read_through_pipeline(
            &InvalidatedReader(&detection),
            "adwaita",
            &detection,
        ))
        .unwrap();
        let runs = std::cell::Cell::new(0);
        let _ = detection.reader_accessibility_with(|| {
            runs.set(runs.get() + 1);
            crate::AccessibilityPreferences::default()
        });
        assert_eq!(
            runs.get(),
            1,
            "a block read before the invalidation was cached"
        );
    }

    // --- Phase 93-04 G4: Theme.icon_theme + three-tier precedence ---
    //
    // Per docs/archive/v0.5.7_gaps.md §G4 and doc 1 §20 Option C:
    //   Tier 1 (highest): ThemeMode::defaults.icon_theme (per-variant override)
    //   Tier 2:           Theme::icon_theme (shared across variants)
    //   Tier 3 (fallback): system_icon_theme() (runtime detect), none where it fails

    /// Helper: construct a ReaderResult that carries only the active variant
    /// (light) with no per-variant icon_theme. The pipeline must then consult
    /// the preset's Theme-level icon_theme (tier 2) or system detect (tier 3).
    fn reader_with_empty_variant(is_dark: bool) -> ReaderResult {
        ReaderResult {
            output: ReaderOutput::Single {
                mode: Box::new(ThemeMode::default()),
                is_dark,
            },
            name: std::borrow::Cow::Borrowed(""),
            icon_set: None,
            layout: LayoutTheme::default(),
            font_dpi: None,
            accessibility: crate::AccessibilityPreferences::default(),
        }
    }

    #[test]
    fn icon_theme_tier2_theme_level_used_when_per_variant_none() {
        // Adwaita preset (after G4 migration) carries icon_theme = "Adwaita"
        // at the Theme level, and None on both variant defaults.
        // With a reader that provides an empty variant (no per-variant override),
        // the resolver must fall through to tier 2 and produce "Adwaita".
        let reader = reader_with_empty_variant(false);
        let st = run_pipeline(reader, "adwaita").unwrap();
        assert_eq!(
            st.icon_theme.as_deref(),
            Some("Adwaita"),
            "tier 2: Theme.icon_theme should be used when per-variant is None"
        );
    }

    #[test]
    fn icon_theme_tier1_per_variant_wins_over_theme_level() {
        // Construct a reader whose active variant explicitly sets a per-variant
        // icon_theme override. Even with a preset that carries a Theme-level
        // icon_theme, the per-variant override must win.
        let mut variant = ThemeMode::default();
        variant.defaults.icon_theme = Some(std::borrow::Cow::Borrowed("custom-override"));
        let reader = ReaderResult {
            output: ReaderOutput::Single {
                mode: Box::new(variant),
                is_dark: false,
            },
            name: std::borrow::Cow::Borrowed(""),
            icon_set: None,
            layout: LayoutTheme::default(),
            font_dpi: None,
            accessibility: crate::AccessibilityPreferences::default(),
        };
        // Adwaita preset has Theme.icon_theme = "Adwaita" after migration.
        let st = run_pipeline(reader, "adwaita").unwrap();
        assert_eq!(
            st.icon_theme.as_deref(),
            Some("custom-override"),
            "tier 1: per-variant icon_theme override must win over Theme-level"
        );
    }

    /// `with_overlay` replays the overlay through the same tiers and layout
    /// as `run_pipeline`: an icon theme or a layout gap the overlay states
    /// wins, and an overlay that states none keeps the base's.
    #[test]
    fn with_overlay_applies_the_overlays_icon_theme_and_layout() -> crate::Result<()> {
        let st = run_pipeline(reader_from_preset("adwaita"), "adwaita")?;
        let kept = st.with_overlay(&Theme::default())?;
        assert_eq!(kept.icon_theme, st.icon_theme);
        assert_eq!(kept.layout.widget_gap, st.layout.widget_gap);

        let overlay =
            Theme::from_toml("icon_theme = \"custom-override\"\n[layout]\nwidget_gap_px = 9.0")?;
        let changed = st.with_overlay(&overlay)?;
        assert_eq!(changed.icon_theme.as_deref(), Some("custom-override"));
        assert_eq!(
            changed.icon_theme_for(crate::ColorMode::Dark),
            Some("custom-override")
        );
        assert_eq!(changed.layout.widget_gap, Some(9.0));
        Ok(())
    }

    #[test]
    fn icon_theme_kde_per_variant_values_still_win() {
        // Regression guard for Phase 80-fix: KDE Breeze uses per-variant icon_theme
        // values ("breeze" light / "breeze-dark" dark) that MUST continue to win
        // over any Theme-level value. The kde-breeze preset keeps per-variant-only.
        let kde_full = Theme::preset("kde-breeze").unwrap();
        // Simulate KDE reader providing the dark variant with its per-variant value.
        let dark_v = kde_full.dark.clone().unwrap();
        assert_eq!(
            dark_v.defaults.icon_theme.as_deref(),
            Some("breeze-dark"),
            "precondition: kde-breeze dark variant must carry breeze-dark"
        );
        let reader = ReaderResult {
            output: ReaderOutput::Single {
                mode: Box::new(dark_v),
                is_dark: true,
            },
            name: std::borrow::Cow::Borrowed(""),
            icon_set: None,
            layout: LayoutTheme::default(),
            font_dpi: None,
            accessibility: crate::AccessibilityPreferences::default(),
        };
        let st = run_pipeline(reader, "kde-breeze").unwrap();
        assert_eq!(
            st.icon_theme.as_deref(),
            Some("breeze-dark"),
            "KDE per-variant icon_theme must still win (Phase 80-fix invariant)"
        );
    }

    #[test]
    fn theme_icon_theme_round_trips_when_some() {
        // Serialize a Theme with icon_theme: Some(...) and assert the
        // deserialized round-trip preserves the value.
        let theme = Theme {
            name: std::borrow::Cow::Borrowed("RoundTrip"),
            light: Some(ThemeMode::default()),
            dark: None,
            layout: LayoutTheme::default(),
            icon_set: None,
            icon_theme: Some(std::borrow::Cow::Borrowed("lucide")),
        };
        let toml_str = theme.to_toml().expect("serialize");
        let reparsed = Theme::from_toml(&toml_str).expect("deserialize");
        assert_eq!(
            reparsed.icon_theme.as_deref(),
            Some("lucide"),
            "Theme.icon_theme must round-trip through TOML"
        );
        // Verify the serialized form contains the key at the top level.
        assert!(
            toml_str.contains("icon_theme = \"lucide\""),
            "serialized TOML should contain top-level icon_theme, got:\n{toml_str}"
        );
    }

    #[test]
    fn theme_icon_theme_skipped_when_none() {
        // Serialize a Theme with icon_theme: None and assert the TOML does NOT
        // emit the key (skip_serializing_if = Option::is_none).
        let theme = Theme {
            name: std::borrow::Cow::Borrowed("NoIcon"),
            light: Some(ThemeMode::default()),
            dark: None,
            layout: LayoutTheme::default(),
            icon_set: None,
            icon_theme: None,
        };
        let toml_str = theme.to_toml().expect("serialize");
        assert!(
            !toml_str.contains("icon_theme"),
            "serialized TOML should NOT contain icon_theme when None, got:\n{toml_str}"
        );
    }

    #[test]
    fn lint_toml_accepts_top_level_icon_theme() {
        // lint_toml() must NOT warn about icon_theme at the top level.
        // Raw string uses ##"..."## because the TOML body contains `"#` hex colors.
        let toml_str = r##"
name = "Test"
icon_theme = "lucide"

[light.defaults]
accent_color = "#0066cc"
"##;
        let warnings = Theme::lint_toml(toml_str).expect("lint");
        assert!(
            !warnings.iter().any(|w| w.contains("icon_theme")),
            "lint_toml must not flag top-level icon_theme as unknown; warnings: {warnings:?}"
        );
    }

    /// §11.1: `SystemTheme.layout` is the reader's layout merged field-wise over
    /// the preset's. On the preset-only path the reader *is* the full preset, so
    /// the result equals full ⊕ full.
    #[test]
    fn system_theme_layout_is_the_merged_preset_layout() -> crate::Result<()> {
        let reader = preset_as_reader("adwaita", crate::ColorMode::Light)?;
        let sys = run_pipeline(reader, "adwaita")?;

        let mut expected = Theme::preset("adwaita")?.layout;
        expected.merge(&Theme::preset("adwaita")?.layout);

        assert_eq!(sys.layout, expected);
        assert!(
            sys.layout.widget_gap.is_some(),
            "adwaita defines all four layout keys (spec §1.3)"
        );
        Ok(())
    }

    /// A layout value out of range fails the build, in `run_pipeline` and in
    /// `with_overlay`. Layout is shared by both variants: the path has no
    /// variant table.
    #[test]
    fn system_theme_layout_out_of_range_is_invalid() -> crate::Result<()> {
        let mut reader = preset_as_reader("adwaita", crate::ColorMode::Light)?;
        reader.layout.widget_gap = Some(-8.0);
        let Err(crate::Error::ResolutionInvalid { errors }) = run_pipeline(reader, "adwaita")
        else {
            panic!("expected ResolutionInvalid");
        };
        let paths: Vec<&str> = errors.iter().map(|rv| rv.path.as_str()).collect();
        assert_eq!(paths, ["layout.widget_gap_px"]);

        let reader = preset_as_reader("adwaita", crate::ColorMode::Light)?;
        let mut sys = run_pipeline(reader, "adwaita")?;
        sys.overlay_source.layout.section_gap = Some(f32::NAN);
        let Err(crate::Error::ResolutionInvalid { errors }) = sys.with_overlay(&Theme::default())
        else {
            panic!("expected ResolutionInvalid");
        };
        let paths: Vec<&str> = errors.iter().map(|rv| rv.path.as_str()).collect();
        assert_eq!(paths, ["layout.section_gap_px"]);
        Ok(())
    }

    /// `SystemTheme::icon` and `icon_indicator` load a freedesktop icon from
    /// the asked mode's variant theme, not the active one's, and keep doing so
    /// when the public `mode` field is changed.
    #[test]
    fn icon_loads_from_the_modes_icon_theme() -> crate::Result<()> {
        let mut theme = run_pipeline(reader_from_preset("kde-breeze"), "kde-breeze")?;
        for active in [crate::ColorMode::Light, crate::ColorMode::Dark] {
            theme.mode = active;
            for (mode, expected) in [
                (crate::ColorMode::Light, "breeze"),
                (crate::ColorMode::Dark, "breeze-dark"),
            ] {
                let source =
                    theme.with_icon_source(mode, |set, theme| (set, theme.map(str::to_owned)));
                assert_eq!(
                    source,
                    (crate::IconSet::Freedesktop, Some(expected.to_owned())),
                    "kde-breeze.toml:16 and :601 (active mode {active:?}, asked {mode:?})"
                );
                assert_eq!(theme.icon_theme_for(mode), Some(expected));
            }
        }
        Ok(())
    }

    /// `SystemTheme::icon` and `icon_indicator` hand the mode's icon theme to
    /// the freedesktop loader: under a light variant theme that is not
    /// installed both load nothing (the loader searches no other theme), and
    /// the dark mode loads what `breeze-dark` itself gives, installed or not.
    #[test]
    #[cfg(all(target_os = "linux", feature = "system-icons"))]
    fn icon_and_indicator_load_from_the_modes_freedesktop_theme() -> crate::Result<()> {
        use crate::icons::{FreedesktopLoader, IconRole, is_freedesktop_theme_available};

        const MISSING: &str = "native-theme-no-such-theme";
        assert!(!is_freedesktop_theme_available(MISSING));
        let mut theme = run_pipeline(reader_from_preset("kde-breeze"), "kde-breeze")?;
        theme.light_icon_theme = Some(std::borrow::Cow::Borrowed(MISSING));
        let role = IconRole::ActionCopy;
        for active in [crate::ColorMode::Light, crate::ColorMode::Dark] {
            theme.mode = active;
            assert_eq!(
                theme.icon(role, crate::ColorMode::Light, None),
                None,
                "light icon from {MISSING} (active mode {active:?})"
            );
            assert_eq!(
                theme.icon_indicator(crate::ColorMode::Light),
                None,
                "light spinner from {MISSING} (active mode {active:?})"
            );
            assert_eq!(
                theme.icon(role, crate::ColorMode::Dark, None),
                FreedesktopLoader::new(role).theme("breeze-dark").load(),
                "dark icon from breeze-dark, kde-breeze.toml:601 (active mode {active:?})"
            );
            assert_eq!(
                theme.icon_indicator(crate::ColorMode::Dark),
                FreedesktopLoader::load_indicator(Some("breeze-dark")),
                "dark spinner from breeze-dark (active mode {active:?})"
            );
        }
        Ok(())
    }

    /// A Material system theme's icon comes back with the colour in its bytes.
    #[test]
    #[cfg(feature = "material-icons")]
    fn icon_of_a_material_theme_comes_back_in_the_colour() -> crate::Result<()> {
        let theme = run_pipeline(reader_from_preset("material-3"), "material-3")?;
        assert_eq!(
            theme.icon_set,
            crate::IconSet::Material,
            "material-3.toml:9"
        );
        // Test fixture colour, not a theme value.
        let color = Rgba::rgb(0x12, 0x34, 0x56);
        for mode in [crate::ColorMode::Light, crate::ColorMode::Dark] {
            match theme.icon(crate::IconRole::ActionCopy, mode, Some(color)) {
                Some(crate::IconData::Svg(svg)) => {
                    let svg = String::from_utf8(svg.into_owned()).unwrap();
                    assert!(svg.contains("#123456"), "{mode:?}: {svg}");
                }
                other => panic!("expected an SVG for {mode:?}, got {other:?}"),
            }
            assert!(
                theme.icon_indicator(mode).is_some(),
                "Material's spinner ({mode:?})"
            );
        }
        Ok(())
    }

    /// Both variants' icon themes are known whichever mode is active: the
    /// egui connector needs the name per `egui::Theme`, because egui draws
    /// either style after a scheme change (egui spec §4.2, §9).
    #[test]
    fn icon_theme_for_gives_each_variants_name() -> crate::Result<()> {
        for mode in [crate::ColorMode::Light, crate::ColorMode::Dark] {
            // A reader that names no icon theme: tier 1 (the reader's own
            // variant) is empty, so the preset's variants decide.
            let reader = ReaderResult {
                output: ReaderOutput::Single {
                    mode: Box::new(crate::model::ThemeMode::default()),
                    is_dark: mode == crate::ColorMode::Dark,
                },
                name: std::borrow::Cow::Borrowed(""),
                icon_set: None,
                layout: crate::theme::LayoutTheme::default(),
                font_dpi: None,
                accessibility: crate::AccessibilityPreferences::default(),
            };
            let theme = run_pipeline(reader, "kde-breeze")?;
            assert_eq!(
                theme.icon_theme_for(crate::ColorMode::Light),
                Some("breeze"),
                "kde-breeze.toml:16 names breeze for light (active mode {mode:?})"
            );
            assert_eq!(
                theme.icon_theme_for(crate::ColorMode::Dark),
                Some("breeze-dark"),
                "kde-breeze.toml:601 names breeze-dark for dark (active mode {mode:?})"
            );
            assert_eq!(
                theme.icon_theme_for(mode),
                theme.icon_theme.as_deref(),
                "the active mode's name is `icon_theme` itself"
            );
            // `mode` is a public field: changing it after the build must not swap the names.
            let mut flipped = theme;
            flipped.mode = match mode {
                crate::ColorMode::Light => crate::ColorMode::Dark,
                crate::ColorMode::Dark => crate::ColorMode::Light,
            };
            assert_eq!(
                flipped.icon_theme_for(crate::ColorMode::Light),
                Some("breeze"),
                "built in {mode:?}, mode flipped"
            );
            assert_eq!(
                flipped.icon_theme_for(crate::ColorMode::Dark),
                Some("breeze-dark"),
                "built in {mode:?}, mode flipped"
            );
        }
        Ok(())
    }
}

// =============================================================================
// Plan 94-03 (G8): ThemeReader trait + select_reader regression tests
// =============================================================================
//
// These tests lock the contract of the G8 ThemeReader refactor:
// - the `ThemeReader` trait exists under `crate::reader` and is object-safe
// - `select_reader()` exists and returns the correct platform-specific impl
//
// Object-safety is the load-bearing property: `select_reader()` is declared
// to return `Option<Box<dyn ThemeReader>>`, which only compiles if the trait
// is object-safe. On current stable Rust (1.95), native `async fn` in traits
// is NOT object-safe for `dyn Trait`; the trait definition must use
// `#[async_trait::async_trait]` to produce a `Pin<Box<dyn Future + Send>>`
// return type that vtables can hold. If an implementer deviates from the
// async-trait strategy (e.g., tries native async-fn-in-trait), the coercion
// below fails to compile with "the trait cannot be made into an object" —
// this is the structural enforcement of Option A (see plan 94-03 objective).
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod theme_reader_trait_tests {
    /// Trait object-safety probe. With `#[async_trait::async_trait]` on the
    /// trait definition, this coercion compiles because the macro rewrite
    /// produces `Pin<Box<dyn Future + Send + '_>>` return types
    /// (vtable-compatible).
    #[test]
    fn theme_reader_trait_exists_and_is_object_safe() {
        // Plain function that requires its argument to be ?Sized — compile-time
        // proof that `Box<dyn ThemeReader>` is a valid trait object.
        //
        // `#[allow(dead_code)]` is required because on cfg permutations that
        // exclude every concrete reader (e.g. linux without kde feature) the
        // function is only name-resolved by the compiler but never called.
        #[allow(dead_code)]
        fn assert_object_safe<T: ?Sized>(_: &T) {}

        // Use one of the concrete readers to construct the trait object on
        // the platforms where one exists.
        #[cfg(all(target_os = "linux", feature = "kde"))]
        {
            let r: Box<dyn crate::reader::ThemeReader> = Box::new(crate::kde::KdeReader);
            assert_object_safe(&r);
        }
        #[cfg(all(target_os = "macos", feature = "macos"))]
        {
            let r: Box<dyn crate::reader::ThemeReader> = Box::new(crate::macos::MacosReader);
            assert_object_safe(&r);
        }
        #[cfg(all(target_os = "windows", feature = "windows"))]
        {
            let r: Box<dyn crate::reader::ThemeReader> = Box::new(crate::windows::WindowsReader);
            assert_object_safe(&r);
        }
        // Without any active-platform feature we still want the test body to
        // compile; reference the trait path once so name resolution fires
        // regardless of cfg.
        let _: Option<&dyn crate::reader::ThemeReader> = None;
    }

    /// `select_reader()` exists, is async, and returns an
    /// `Option<SelectedReader>`.
    ///
    /// On each platform with an available backend we expect `Some(selected)`;
    /// on platforms without one (non-Linux/macOS/Windows, or Linux with no
    /// compiled-in backend, or Linux-other-DE without portal) we expect `None`.
    ///
    /// The selected reader carries the platform preset name that `run_pipeline`
    /// should use — kept in the same return type because the preset is chosen
    /// from the DE detected by `select_reader` (KDE -> kde-breeze, GNOME ->
    /// adwaita, macOS -> the running version's generation, Windows -> windows-11).
    #[test]
    fn select_reader_returns_platform_specific_impl() {
        // Call select_reader and observe the Option. The structural invariant
        // is that the function exists, is callable from a sync context via
        // `pollster::block_on`, and returns the selected reader and its preset.
        let picked: Option<super::SelectedReader> = pollster::block_on(super::select_reader());

        // Every cfg branch borrows `picked` (via `&picked`) rather than moving
        // it, so the final `drop(picked)` consumes it uniformly on all
        // permutations -- including linux-without-kde, which has no branch.
        #[cfg(all(target_os = "macos", feature = "macos"))]
        {
            assert!(
                picked.is_some(),
                "select_reader must return Some on macOS+macos"
            );
            if let Some(selected) = &picked {
                let (preset, matched) = super::macos_generation(crate::macos::os_version());
                assert_eq!(selected.preset, preset.name);
                assert_eq!(selected.version_match, Some(matched));
            }
        }
        #[cfg(all(target_os = "windows", feature = "windows"))]
        {
            assert!(
                picked.is_some(),
                "select_reader must return Some on windows+windows"
            );
            if let Some(selected) = &picked {
                let (preset, matched) = super::windows_generation(crate::windows::os_version());
                assert_eq!(selected.preset, preset.name);
                assert_eq!(selected.version_match, Some(matched));
            }
        }
        #[cfg(all(target_os = "linux", feature = "kde", feature = "portal"))]
        {
            // On linux+kde+portal, select_reader returns Some(GnomePortalKdeReader, "kde-breeze")
            // whenever the active DE is KDE; for non-KDE DEs it may legitimately
            // return None (preset fallback). Assert the tuple shape regardless.
            if let Some(selected) = &picked {
                assert!(
                    selected.preset == "kde-breeze" || selected.preset == "adwaita",
                    "select_reader on linux must return a known platform preset, got: {}",
                    selected.preset
                );
                assert_eq!(selected.version_match, None);
            }
        }
        #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
        {
            assert!(
                picked.is_none(),
                "select_reader() must return None on unsupported platforms"
            );
        }
        drop(picked);
    }
}

/// The generation tables (M1-T1-01): pure functions of the version, tested on
/// every platform; CI's macOS and Windows legs run the readers against them.
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod generation_tests {
    use super::*;

    /// The macOS preset of a running major version, as `select_reader` picks it.
    fn macos_preset_for_version(major: u32) -> &'static str {
        macos_generation(OsVersion::new(major, 0, 0)).0.name
    }

    #[test]
    fn macos_preset_follows_the_os_generation() {
        assert_eq!(macos_preset_for_version(12), "macos-monterey");
        assert_eq!(macos_preset_for_version(14), "macos-monterey");
        assert_eq!(macos_preset_for_version(15), "macos-monterey");
        assert_eq!(macos_preset_for_version(26), "macos-tahoe");
        // macOS 27 until a macos-golden-gate preset exists (D4)
        assert_eq!(macos_preset_for_version(27), "macos-tahoe");
        assert_eq!(
            macos_generation(OsVersion::new(27, 0, 1)).1,
            VersionMatch::PresetOlder
        );
        // 16: what early macOS 26 betas reported to a macOS 15 SDK build
        assert_eq!(
            macos_generation(OsVersion::new(16, 0, 0)),
            (
                PlatformPreset {
                    name: "macos-monterey"
                },
                VersionMatch::PresetOlder
            )
        );
        // An unreadable version reads as 0.0.0
        assert_eq!(
            macos_generation(OsVersion::new(0, 0, 0)),
            (
                PlatformPreset {
                    name: "macos-monterey"
                },
                VersionMatch::PresetNewer
            )
        );
    }

    #[test]
    fn macos_versions_inside_a_generation_match_exactly() {
        for v in [
            OsVersion::new(12, 0, 0),
            OsVersion::new(14, 8, 9),
            OsVersion::new(15, 7, 9),
            OsVersion::new(26, 6, 2),
        ] {
            assert_eq!(macos_generation(v).1, VersionMatch::Exact, "{v}");
        }
        // Big Sur began the look, before Monterey's change to a clicked button
        assert_eq!(
            macos_generation(OsVersion::new(11, 7, 10)),
            (
                PlatformPreset {
                    name: "macos-monterey"
                },
                VersionMatch::PresetNewer
            )
        );
    }

    #[test]
    fn windows_preset_follows_the_build() {
        // Windows 10 22H2: no preset of its own (M2b Step 7, D9)
        assert_eq!(
            windows_generation(OsVersion::new(10, 0, 19045)),
            (
                PlatformPreset { name: "windows-11" },
                VersionMatch::PresetNewer
            )
        );
        assert_eq!(
            windows_generation(OsVersion::new(10, 0, 22000)).1,
            VersionMatch::Exact
        );
        assert_eq!(
            windows_generation(OsVersion::new(10, 0, 26200)).1,
            VersionMatch::Exact
        );
        // 26H2 (26300): newer than the build the preset was verified on
        assert_eq!(
            windows_generation(OsVersion::new(10, 0, 26300)).1,
            VersionMatch::PresetOlder
        );
        // 26H1 (28000)
        assert_eq!(
            windows_generation(OsVersion::new(10, 0, 28000)),
            (
                PlatformPreset { name: "windows-11" },
                VersionMatch::PresetOlder
            )
        );
        // A failed version read gives 0.0.0
        assert_eq!(
            windows_generation(OsVersion::new(0, 0, 0)),
            (
                PlatformPreset { name: "windows-11" },
                VersionMatch::PresetNewer
            )
        );
    }

    #[test]
    fn every_table_is_ordered_and_lists_its_keys() {
        for table in [MACOS_GENERATIONS, WINDOWS_GENERATIONS] {
            let rows: Vec<Generation> = table.rows().collect();
            let keys: Vec<&str> = rows.iter().map(|g| g.preset).collect();
            assert_eq!(keys, table.keys);
            for g in &rows {
                assert!(g.first <= g.last_verified, "{}", g.preset);
            }
            for (older, newer) in rows.iter().zip(rows.iter().skip(1)) {
                assert!(
                    older.last_verified < newer.first,
                    "{} / {}",
                    older.preset,
                    newer.preset
                );
            }
        }
    }

    #[test]
    fn every_generation_is_a_bundled_preset_of_its_platform() {
        for (table, platform) in [
            (MACOS_GENERATIONS, "macos"),
            (WINDOWS_GENERATIONS, "windows"),
        ] {
            for key in table.keys {
                assert!(crate::Theme::preset(key).is_ok(), "{key}");
                let offered = crate::Theme::list_presets()
                    .iter()
                    .any(|p| p.key == *key && p.platforms.contains(&platform));
                assert!(offered, "{key} is not offered on {platform}");
            }
        }
    }

    #[test]
    fn the_diagnostic_names_the_version_and_its_preset() {
        let entry = DiagnosticEntry::OsGeneration {
            version: OsVersion::new(27, 0, 1).to_string(),
            preset: "macos-tahoe",
            version_match: VersionMatch::PresetOlder,
        };
        assert_eq!(entry.name(), "OS version");
        assert_eq!(entry.status(), "27.0.1");
        assert_eq!(
            entry.to_string(),
            "OS version: 27.0.1 (macos-tahoe, preset older than the OS)"
        );
    }
}