native-theme 0.7.0

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
// Linux freedesktop icon theme lookup
//
// Resolves IconRole variants to SVG bytes from the user's active desktop
// icon theme (Adwaita, Breeze, Papirus, etc.) using the freedesktop-icons
// crate. Returns None when the role has no freedesktop mapping or the
// icon is not found in the active theme or a theme it inherits from;
// hicolor, loose files and pixmaps never stand in for a missing icon.

use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::ffi::OsStr;
use std::num::NonZeroU32;
use std::sync::{Arc, Mutex, OnceLock};

use crate::IconData;
use crate::icons::{
    MAX_ICON_DECODE_BYTES, has_theme_index, icon_base_dirs, ini_value, installed_themes,
    theme_index,
};
use crate::model::animated::{AnimatedIcon, TransformAnimation};
use std::path::{Component, Path, PathBuf};

/// Frame duration for freedesktop sprite sheet animations (80ms per frame).
const FREEDESKTOP_FRAME_DURATION_MS: u32 = 80;

/// Spin duration for single-frame icons animated with rotation (1 second).
const FREEDESKTOP_SPIN_DURATION_MS: u32 = 1000;

/// The themes listed by the `Inherits=` key of an `index.theme`'s
/// `[Icon Theme]` group, in order.
fn inherits(index: &str) -> Vec<&str> {
    ini_value(index, "Icon Theme", "Inherits").map_or_else(Vec::new, |value| {
        value
            .split(',')
            .map(str::trim)
            .filter(|parent| !parent.is_empty())
            .collect()
    })
}

/// The parents `theme` declares in the `Inherits=` of its
/// [`theme_index`] in `bases`, the one `index.theme` the specification
/// reads.
fn declared_parents(theme: &str, bases: &[PathBuf]) -> Vec<String> {
    theme_index(theme, bases).map_or_else(Vec::new, |index| {
        inherits(&index).into_iter().map(str::to_string).collect()
    })
}

/// The themes an icon for `theme` may come from, in the order the Icon
/// Theme Specification's `FindIconHelper` searches them: `theme`, then
/// each parent it declares in `Inherits=`, in declared order, each
/// followed depth-first by its own parents. A theme reached twice is
/// searched once, so a cycle ends. `hicolor` is left out unless it is
/// `theme` itself, and so is a parent that is not installed.
///
/// `None` when `theme` is not installed: nothing may stand in for it.
fn theme_chain(theme: &str, bases: &[PathBuf]) -> Option<Vec<String>> {
    if !has_theme_index(theme, bases) {
        return None;
    }
    let mut chain: Vec<String> = Vec::new();
    let mut pending = vec![theme.to_string()];
    while let Some(name) = pending.pop() {
        if chain.contains(&name) {
            continue;
        }
        let parents = declared_parents(&name, bases);
        chain.push(name);
        pending.extend(
            parents
                .into_iter()
                .rev()
                .filter(|parent| parent != "hicolor" && has_theme_index(parent, bases)),
        );
    }
    Some(chain)
}

/// [`theme_chain`] over [`icon_base_dirs`] for a theme of the
/// [`installed_themes`] snapshot, kept per theme name for the life of the
/// process, as freedesktop-icons keeps its theme list.
fn cached_theme_chain(theme: &str) -> Option<Vec<String>> {
    if !installed_themes().contains(theme) {
        return None;
    }
    type Chains = Mutex<HashMap<String, Option<Vec<String>>>>;
    static CHAINS: OnceLock<Chains> = OnceLock::new();
    let chains = CHAINS.get_or_init(Chains::default);
    if let Ok(known) = chains.lock()
        && let Some(chain) = known.get(theme)
    {
        return chain.clone();
    }
    let chain = theme_chain(theme, icon_base_dirs());
    if let Ok(mut known) = chains.lock() {
        known.insert(theme.to_string(), chain.clone());
    }
    chain
}

/// Whether `path` lies inside `theme`'s own directory under one of
/// `bases`, compared by path component, so `breeze` does not take a file
/// of `breeze-dark`. The path is not canonicalized: the theme directory
/// freedesktop-icons searched is what decides, even where it links into
/// another theme. A path with a `..` component is refused, as it could
/// leave the directory it names.
fn is_in_theme_dir(path: &Path, theme: &str, bases: &[PathBuf]) -> bool {
    if path
        .components()
        .any(|component| component == Component::ParentDir)
    {
        return false;
    }
    bases.iter().any(|base| {
        let Ok(rest) = path.strip_prefix(base) else {
            return false;
        };
        let mut rest = rest.components();
        let in_theme = matches!(
            rest.next(),
            Some(Component::Normal(dir)) if dir == OsStr::new(theme)
        );
        in_theme && rest.next().is_some()
    })
}

/// The first icon `lookup` finds for a theme of `chain`, in chain order,
/// counting only a file in the directory of the theme it was looked up
/// in.
///
/// freedesktop-icons, asked for one theme, goes on to its direct parents
/// (not theirs), then to `hicolor`, loose files in the icon base dirs and
/// `/usr/share/pixmaps` (`freedesktop-icons-0.4.0/src/lib.rs:297-347`).
/// Asking it for each theme of the chain in turn and keeping only that
/// theme's own files reaches every depth of the chain in the
/// specification's order, and none of those fallbacks.
fn first_in_chain(
    chain: &[String],
    bases: &[PathBuf],
    mut lookup: impl FnMut(&str) -> Option<PathBuf>,
) -> Option<PathBuf> {
    chain
        .iter()
        .find_map(|theme| lookup(theme).filter(|path| is_in_theme_dir(path, theme, bases)))
}

/// The file name endings freedesktop-icons 0.4.0 tries for a name in a
/// theme directory: `.svg`, `.png` and `.xmp` (sic,
/// `freedesktop-icons-0.4.0/src/theme/mod.rs:107-150`). It never tries
/// `.xpm`, the extension the Icon Theme Specification names, so a name a
/// theme has only as `.xpm` cannot be found there.
const ICON_FILE_ENDINGS: [&str; 3] = [".svg", ".png", ".xmp"];

/// Every name an icon file in `theme`'s directories under `bases` could be
/// found by: the file name of each `.svg`, `.png` or `.xmp` file at any
/// depth, without that ending.
///
/// freedesktop-icons builds a theme's candidates as `<base>/<theme>/
/// <index.theme section>/<name>.<ending>`, and [`first_in_chain`] keeps a
/// candidate only inside `<base>/<theme>`, so every file it can return for
/// `theme` lies under one of the directories walked here: the set is a
/// superset of the names it can find there, and a name missing from it
/// cannot be found in `theme`. Symlinked directories are followed, as
/// freedesktop-icons' path joins follow them, each directory once by its
/// canonical path, so a link cycle ends; a directory that cannot be
/// canonicalized or read is skipped.
///
/// Two cases fall outside the superset: a directory that can be entered
/// but not listed, and a case-insensitive filesystem (where `Name.SVG`
/// answers for `name.svg`), could each hide a file the unfiltered lookup
/// would find.
fn theme_icon_stems(theme: &str, bases: &[PathBuf]) -> HashSet<String> {
    let mut stems = HashSet::new();
    let mut visited: HashSet<PathBuf> = HashSet::new();
    let mut pending: Vec<PathBuf> = bases.iter().map(|base| base.join(theme)).collect();
    while let Some(dir) = pending.pop() {
        let Ok(canonical) = std::fs::canonicalize(&dir) else {
            continue;
        };
        if !visited.insert(canonical) {
            continue;
        }
        let Ok(entries) = std::fs::read_dir(&dir) else {
            continue;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            let is_dir = match entry.file_type() {
                Ok(kind) if kind.is_symlink() => path.is_dir(),
                Ok(kind) => kind.is_dir(),
                Err(_) => path.is_dir(),
            };
            if is_dir {
                pending.push(path);
            } else if let Some(stem) = entry.file_name().to_str().and_then(|file| {
                ICON_FILE_ENDINGS
                    .iter()
                    .find_map(|ending| file.strip_suffix(ending))
            }) {
                stems.insert(stem.to_string());
            }
        }
    }
    stems
}

/// [`theme_icon_stems`] over [`icon_base_dirs`], kept per theme name for
/// the life of the process, as [`cached_theme_chain`] keeps the chains.
///
/// An icon added to an installed theme while the process runs is therefore
/// not found until it restarts, where freedesktop-icons alone re-checked
/// the filesystem on every lookup.
fn cached_theme_icon_stems(theme: &str) -> Arc<HashSet<String>> {
    type Stems = Mutex<HashMap<String, Arc<HashSet<String>>>>;
    static STEMS: OnceLock<Stems> = OnceLock::new();
    let known_stems = STEMS.get_or_init(Stems::default);
    if let Ok(known) = known_stems.lock()
        && let Some(stems) = known.get(theme)
    {
        return Arc::clone(stems);
    }
    let stems = Arc::new(theme_icon_stems(theme, icon_base_dirs()));
    if let Ok(mut known) = known_stems.lock() {
        known.insert(theme.to_string(), Arc::clone(&stems));
    }
    stems
}

/// The themes of `chain`, in order, that may have an icon called `name`:
/// those whose [`theme_icon_stems`] (from `stems`) contain it. A name with
/// a `/` reaches below the directory a stem is read from, so for it every
/// theme is kept.
fn themes_that_may_have(
    name: &str,
    chain: &[String],
    mut stems: impl FnMut(&str) -> Arc<HashSet<String>>,
) -> Vec<String> {
    if name.contains('/') {
        return chain.to_vec();
    }
    chain
        .iter()
        .filter(|theme| stems(theme).contains(name))
        .cloned()
        .collect()
}

/// Look `name` up at `size` in the themes of `chain` (see
/// [`theme_chain`] and [`first_in_chain`]).
///
/// freedesktop-icons is asked only for the themes whose files include
/// `name` (see [`themes_that_may_have`]): asked for a name a theme lacks,
/// it re-reads every `index.theme` and searches the theme's parents,
/// `hicolor`, the base dirs and `/usr/share/pixmaps`, testing three
/// endings per directory, a search [`first_in_chain`] then discards: a
/// missing name's load took 47-66 ms against 0.02-0.07 ms for a hit
/// (medians of 20 `FreedesktopLoader` loads in a dev build, on Breeze and
/// Adwaita).
fn lookup_in_chain(name: &str, size: u16, chain: &[String]) -> Option<PathBuf> {
    let themes = themes_that_may_have(name, chain, cached_theme_icon_stems);
    first_in_chain(&themes, icon_base_dirs(), |theme| {
        freedesktop_icons::lookup(name)
            .with_theme(theme)
            .with_size(size)
            .force_svg()
            .find()
    })
}

/// Look up an icon by freedesktop name using a two-pass strategy.
///
/// First tries the `-symbolic` suffix (single-frame static icons), then
/// falls back to the plain name. This order avoids animation sprite
/// sheets (e.g. Breeze's `animations/process-working.svg` is a 15-frame
/// vertical strip) which render incorrectly as static images.
///
/// The symbolic-first order also naturally handles Adwaita, which stores
/// most action icons only as `*-symbolic.svg`.
///
/// Each pass searches `theme` and the themes of its `Inherits=` chain, in
/// the specification's order, never `hicolor` unless `theme` is `hicolor`
/// (see [`theme_chain`]); the symbolic pass searches the whole chain
/// before the plain pass starts. `None` when `theme` is not installed.
fn find_icon(name: &str, theme: &str, size: u16) -> Option<(PathBuf, bool)> {
    find_icon_with(name, theme, size, lookup_in_chain)
}

/// [`find_icon`], with `lookup_in_chain` looking a name up in the chain.
fn find_icon_with(
    name: &str,
    theme: &str,
    size: u16,
    lookup_in_chain: impl Fn(&str, u16, &[String]) -> Option<PathBuf>,
) -> Option<(PathBuf, bool)> {
    let chain = cached_theme_chain(theme)?;
    // First try: symbolic variant (e.g., "edit-copy-symbolic")
    // Symbolic icons are always single-frame, avoiding sprite sheets
    // in themes like Breeze that put animation strips under plain names.
    let symbolic = format!("{name}-symbolic");
    if let Some(path) = lookup_in_chain(&symbolic, size, &chain) {
        return Some((path, true));
    }
    // Second try: plain name (e.g., "edit-copy")
    // If the name itself already ends with "-symbolic" (caller passed it
    // explicitly via load_freedesktop_icon_by_name), mark as symbolic.
    lookup_in_chain(name, size, &chain).map(|path| (path, name.ends_with("-symbolic")))
}

/// [`find_icon`] for the first of several names: each theme of `theme`'s
/// chain is searched for every name, in order, before the next theme of
/// the chain, so the theme's own icon under a later name wins over a
/// parent's icon under an earlier one (Adwaita has `starred-symbolic`, its
/// parent AdwaitaLegacy the raster `emblem-favorite`). Within a theme each
/// name is tried as `<name>-symbolic`, then as itself, as [`find_icon`]
/// tries it.
///
/// GTK 3.24.41's lookup of several names searches theme by theme in the
/// same way, names in order within a theme (`gtk/gtkicontheme.c:1752-1762`,
/// `real_choose_icon`); it first searches every theme for the names that
/// end in `-symbolic` (`:1740-1750`). Here a name's symbolic form is tried
/// with the name, so a later name's symbolic icon does not displace an
/// earlier name's icon in the same theme: Breeze's `cpu` stays the `Cpu`
/// icon over its `computer-symbolic`. With one name the order differs from
/// [`find_icon`]'s only where a theme has the plain name and a parent the
/// symbolic one: [`find_icon`] takes the parent's.
fn find_any_icon(names: &[&str], theme: &str, size: u16) -> Option<(PathBuf, bool)> {
    let chain = cached_theme_chain(theme)?;
    first_of_names(names, &chain, |name, theme| {
        lookup_in_chain(name, size, std::slice::from_ref(theme))
    })
}

/// The first icon `lookup` finds in a theme of `chain` for one of `names`,
/// in [`find_any_icon`]'s order, with whether it is symbolic.
fn first_of_names(
    names: &[&str],
    chain: &[String],
    mut lookup: impl FnMut(&str, &String) -> Option<PathBuf>,
) -> Option<(PathBuf, bool)> {
    chain.iter().find_map(|theme| {
        names.iter().find_map(|&name| {
            lookup(&format!("{name}-symbolic"), theme)
                .map(|path| (path, true))
                .or_else(|| lookup(name, theme).map(|path| (path, name.ends_with("-symbolic"))))
        })
    })
}

/// [`load_freedesktop_icon_by_name`] for the first of `names` the theme
/// has, in [`find_any_icon`]'s order.
#[must_use]
pub(crate) fn load_freedesktop_icon_by_names(
    names: &[&str],
    theme: &str,
    size: u32,
    fg_color: Option<[u8; 3]>,
) -> Option<IconData> {
    let (path, is_symbolic) = find_any_icon(names, theme, lookup_size(size))?;
    load_icon_file(&path, is_symbolic, fg_color)
}

/// Load a freedesktop icon by name from the given theme.
///
/// Looks up the name in the specified theme directory (with `-symbolic`
/// suffix fallback for Adwaita-style themes), then dispatches on file
/// extension:
///
/// - `.svg` → returns [`IconData::Svg`]. For GTK-convention symbolic
///   icons (Adwaita, Yaru, elementary), hardcoded foreground placeholders
///   are replaced with `fg_color` so the SVG renders correctly on both
///   light and dark themes. Pass `None` to fall back to `currentColor`
///   (requires connector colorization).
/// - `.png` → decodes the PNG to RGBA and returns [`IconData::Rgba`]
///   (raster-only legacy themes like `AdwaitaLegacy`).
/// - Any other extension → `None`.
///
/// Returns `None` if the icon is not found in the theme or if the
/// decoded file cannot be parsed.
///
/// `size` is clamped to [`lookup_size`]'s bound before the lookup.
///
/// **Performance note:** Each call reads the icon file from disk. Callers
/// that load the same icon repeatedly should cache the returned `IconData`.
#[must_use]
pub(crate) fn load_freedesktop_icon_by_name(
    name: &str,
    theme: &str,
    size: u32,
    fg_color: Option<[u8; 3]>,
) -> Option<IconData> {
    let (path, is_symbolic) = find_icon(name, theme, lookup_size(size))?;
    load_icon_file(&path, is_symbolic, fg_color)
}

/// The size freedesktop-icons looks `size` up at: its `with_size` takes a
/// `u16` (freedesktop-icons-0.4.0 `src/lib.rs:192`) that it casts to `i16`
/// to compare with each directory's size (`src/theme/directories.rs:15`,
/// `:35`), so a size past `i16::MAX` would wrap negative and overflow its
/// distance arithmetic (`:39`); it looks up as `i16::MAX`, past the
/// largest directory.
fn lookup_size(size: u32) -> u16 {
    const LARGEST: u16 = i16::MAX.unsigned_abs();
    u16::try_from(size).map_or(LARGEST, |size| size.min(LARGEST))
}

/// Read and decode an icon file, branching on its extension.
///
/// Split out from [`load_freedesktop_icon_by_name`] so format handling
/// is testable without the freedesktop-icons lookup and is easy to
/// extend (e.g. future XPM support).
fn load_icon_file(path: &Path, is_symbolic: bool, fg_color: Option<[u8; 3]>) -> Option<IconData> {
    let ext = path
        .extension()
        .and_then(|e| e.to_str())
        .map(str::to_ascii_lowercase);
    match ext.as_deref() {
        Some("svg") => {
            let bytes = std::fs::read(path).ok()?;
            let bytes = if is_symbolic {
                let replacement = fg_to_replacement(fg_color);
                normalize_gtk_symbolic(bytes, &replacement)
            } else {
                bytes
            };
            Some(IconData::Svg(Cow::Owned(bytes)))
        }
        Some("png") => {
            let bytes = std::fs::read(path).ok()?;
            decode_png_to_rgba(&bytes)
        }
        _ => None,
    }
}

/// Decode a PNG byte slice to an 8-bit RGBA [`IconData`].
///
/// Uses `png` crate transformations to normalise palette, grayscale, and
/// 16-bit inputs to 8-bit. Non-RGBA outputs (RGB, Grayscale, GrayscaleAlpha)
/// are expanded to RGBA in-place so downstream renderers only ever see
/// 4-byte-per-pixel data.
///
/// Returns `None` if the input is not a valid PNG, decoding fails, the
/// decoded or RGBA buffer would exceed [`MAX_ICON_DECODE_BYTES`], or the
/// output buffer shape does not match `width * height * 4`.
fn decode_png_to_rgba(bytes: &[u8]) -> Option<IconData> {
    let mut decoder = png::Decoder::new(std::io::Cursor::new(bytes));
    decoder.set_transformations(
        png::Transformations::EXPAND | png::Transformations::STRIP_16 | png::Transformations::ALPHA,
    );
    let mut reader = decoder.read_info().ok()?;
    let buf_len = reader.output_buffer_size()?;
    if buf_len > MAX_ICON_DECODE_BYTES {
        return None;
    }
    let mut buf = Vec::new();
    buf.try_reserve_exact(buf_len).ok()?;
    buf.resize(buf_len, 0);
    let info = reader.next_frame(&mut buf).ok()?;
    buf.truncate(info.buffer_size());

    let (width, height) = (info.width, info.height);
    let pixel_count = (width as usize).checked_mul(height as usize)?;
    let rgba_len = pixel_count.checked_mul(4)?;
    if rgba_len > MAX_ICON_DECODE_BYTES {
        return None;
    }

    let rgba = match info.color_type {
        png::ColorType::Rgba => buf,
        png::ColorType::Rgb => expand_to_rgba(&buf, 3, |p, out| {
            // `expand_to_rgba` passes chunks of exactly `sample_stride` bytes (3 here).
            if let [r, g, b] = p {
                out.extend_from_slice(&[*r, *g, *b, 0xff]);
            }
        })?,
        png::ColorType::GrayscaleAlpha => expand_to_rgba(&buf, 2, |p, out| {
            if let [gray, alpha] = p {
                out.extend_from_slice(&[*gray, *gray, *gray, *alpha]);
            }
        })?,
        png::ColorType::Grayscale => expand_to_rgba(&buf, 1, |p, out| {
            if let [gray] = p {
                out.extend_from_slice(&[*gray, *gray, *gray, 0xff]);
            }
        })?,
        // Indexed is converted to RGB/RGBA by EXPAND + ALPHA transformations,
        // so we should never see it here. Treat as unsupported if we do.
        png::ColorType::Indexed => return None,
    };

    IconData::rgba(width, height, rgba)
}

/// Expand a packed pixel buffer to RGBA using the caller-provided per-pixel writer.
///
/// `sample_stride` is the number of bytes per pixel in the input (1 for
/// Grayscale, 2 for GrayscaleAlpha, 3 for Rgb). Returns `None` if `buf`
/// length is not a multiple of `sample_stride`.
fn expand_to_rgba<F>(buf: &[u8], sample_stride: usize, mut write: F) -> Option<Vec<u8>>
where
    F: FnMut(&[u8], &mut Vec<u8>),
{
    if sample_stride == 0 || !buf.len().is_multiple_of(sample_stride) {
        return None;
    }
    // sample_stride > 0 verified above; checked_div cannot return None here.
    let pixel_count = buf.len().checked_div(sample_stride)?;
    let mut out = Vec::with_capacity(pixel_count.saturating_mul(4));
    for chunk in buf.chunks_exact(sample_stride) {
        write(chunk, &mut out);
    }
    Some(out)
}

/// Convert an optional RGB foreground color to a replacement string
/// for GTK symbolic icon normalization.
fn fg_to_replacement(fg_color: Option<[u8; 3]>) -> String {
    match fg_color {
        Some([r, g, b]) => format!("#{r:02x}{g:02x}{b:02x}"),
        None => "currentColor".to_string(),
    }
}

/// Parse a vertical SVG sprite sheet into individual frame SVGs.
///
/// Detection: if the viewBox height > width and is an exact multiple,
/// the SVG is treated as a sprite sheet with `height/width` frames.
/// Each frame's SVG is the original with viewBox rewritten to window
/// into the correct vertical slice.
///
/// Returns `None` if the SVG is not a sprite sheet (single-frame,
/// non-multiple dimensions, a non-finite viewBox or a width below 1, or
/// parse error), or if its frames would exceed [`MAX_ICON_DECODE_BYTES`].
fn parse_sprite_sheet(svg_bytes: &[u8]) -> Option<Vec<Vec<u8>>> {
    let svg_str = std::str::from_utf8(svg_bytes).ok()?;

    // Find viewBox attribute (handle both double and single quotes)
    let (vb_attr_start, vb_val_start, quote) = svg_str
        .find("viewBox=\"")
        .map(|i| (i, i.saturating_add(9), '"'))
        .or_else(|| {
            svg_str
                .find("viewBox='")
                .map(|i| (i, i.saturating_add(9), '\''))
        })?;

    let tail = svg_str.get(vb_val_start..)?;
    let vb_val_end = tail.find(quote)?.saturating_add(vb_val_start);
    let vb_value = svg_str.get(vb_val_start..vb_val_end)?;

    // Split on whitespace or commas
    let parts: Vec<f64> = vb_value
        .split(|c: char| c.is_whitespace() || c == ',')
        .filter(|s| !s.is_empty())
        .filter_map(|s| s.parse().ok())
        .collect();

    let [_, _, width, height] = parts.as_slice() else {
        return None;
    };
    if !parts.iter().all(|v| v.is_finite()) {
        return None;
    }
    let (width, height) = (*width, *height);
    if width < 1.0 || height <= width {
        return None; // Degenerate, or single-frame: not a sprite sheet
    }

    let frames_exact = height / width;
    let frame_count = frames_exact.round() as usize;
    if frame_count < 2 {
        return None;
    }

    // Verify exact division (within floating-point tolerance, in frames)
    if (frames_exact - frame_count as f64).abs() > 0.01 {
        return None;
    }

    if frame_count.checked_mul(svg_bytes.len())? > MAX_ICON_DECODE_BYTES {
        return None;
    }

    // Build the full original viewBox attribute string for replacement
    let original_vb_attr = svg_str.get(vb_attr_start..vb_val_end.saturating_add(1))?; // includes closing quote

    let frames = (0..frame_count)
        .map(|i| {
            let y_offset = width * i as f64;
            let new_vb = format!("viewBox={quote}0 {y_offset} {width} {width}{quote}");
            svg_str.replacen(original_vb_attr, &new_vb, 1).into_bytes()
        })
        .collect();

    Some(frames)
}

/// Load the freedesktop loading spinner from the active icon theme.
///
/// Strategy:
/// 1. Try "process-working" (plain) at size 22 -- may be a sprite sheet -> Frames
/// 2. If found but single-frame (parse_sprite_sheet returns None) -> Transform::Spin
/// 3. Try "process-working-symbolic" at size 22 -- single frame -> Transform::Spin,
///    its GTK foreground placeholders turned into `currentColor` as for any
///    symbolic icon ([`normalize_gtk_symbolic`])
/// 4. Return None if neither found; no other icon set stands in
///
/// Each pass searches the theme and the themes of its `Inherits=` chain,
/// in the specification's order, never `hicolor` unless the theme is
/// `hicolor` (see [`theme_chain`]); the plain pass searches the whole
/// chain before the symbolic pass starts.
///
/// A `theme` of `None` is the system's icon theme, and where that cannot be
/// detected there is no spinner.
pub(crate) fn load_freedesktop_spinner(theme: Option<&str>) -> Option<AnimatedIcon> {
    load_freedesktop_spinner_with(theme, crate::system_icon_theme)
}

/// [`load_freedesktop_spinner`], with `detect` giving the system's icon
/// theme where `theme` is `None`.
fn load_freedesktop_spinner_with(
    theme: Option<&str>,
    detect: impl FnOnce() -> crate::Result<String>,
) -> Option<AnimatedIcon> {
    let detected;
    let theme: &str = match theme {
        Some(t) => t,
        None => {
            detected = detect().ok()?;
            &detected
        }
    };
    let chain = cached_theme_chain(theme)?;
    spinner_in_chain(&chain, lookup_in_chain)
}

/// The spinner [`load_freedesktop_spinner`] finds in the themes of
/// `chain`, with `lookup_in_chain` looking a name up in it.
fn spinner_in_chain(
    chain: &[String],
    lookup_in_chain: impl Fn(&str, u16, &[String]) -> Option<PathBuf>,
) -> Option<AnimatedIcon> {
    // First pass: plain name (finds sprite sheets in animations/ dirs)
    if let Some(path) = lookup_in_chain("process-working", 22, chain) {
        let bytes = std::fs::read(&path).ok()?;
        let frame_dur = NonZeroU32::new(FREEDESKTOP_FRAME_DURATION_MS)?;
        let spin_dur = NonZeroU32::new(FREEDESKTOP_SPIN_DURATION_MS)?;
        if let Some(frames) = parse_sprite_sheet(&bytes) {
            let frame_icons: Vec<IconData> = frames
                .into_iter()
                .map(|b| IconData::Svg(Cow::Owned(b)))
                .collect();
            return AnimatedIcon::frames(frame_icons, frame_dur).ok();
        }
        // Not a sprite sheet -- treat as single frame with spin
        return Some(AnimatedIcon::transform(
            IconData::Svg(Cow::Owned(bytes)),
            TransformAnimation::Spin {
                duration_ms: spin_dur,
            },
        ));
    }

    // Second pass: symbolic name (always single frame)
    if let Some(path) = lookup_in_chain("process-working-symbolic", 22, chain) {
        let bytes = normalize_gtk_symbolic(std::fs::read(&path).ok()?, "currentColor");
        let spin_dur = NonZeroU32::new(FREEDESKTOP_SPIN_DURATION_MS)?;
        return Some(AnimatedIcon::transform(
            IconData::Svg(Cow::Owned(bytes)),
            TransformAnimation::Spin {
                duration_ms: spin_dur,
            },
        ));
    }

    None
}

/// The GTK symbolic icon foreground placeholder colors.
///
/// GTK's icon rendering pipeline replaces these at paint time with the
/// widget's CSS `color` property (the text/foreground color). We replace
/// them with the caller-provided foreground color so the SVG is
/// self-contained and renders correctly without connector colorization.
///
/// Measured from `/usr/share/icons/Adwaita/symbolic/`:
/// - `#2e3436`: 483 fill attrs + 8 CSS style fills + 1 stroke (Tango Aluminium 6)
/// - `#2e3434`: 118 files (68 primary, 50 with fill-opacity)
/// - `#222222`: 27 occurrences (primary + dimmed)
/// - `#474747`: 50 emote/legacy icons (monochrome, never mixed with above)
const GTK_FG_COLORS: &[&str] = &["#2e3436", "#2e3434", "#222222", "#474747"];

/// Recolor a GTK-convention symbolic SVG by replacing foreground placeholders.
///
/// GTK symbolic icons use hardcoded dark fill colors (e.g., `#2e3436`)
/// that GTK replaces at render time with the widget's CSS text color.
/// This function does the same: it replaces those placeholders with
/// `replacement`, which should be either a hex color (e.g., `#ffffff`)
/// or `currentColor` as a fallback.
///
/// Handles three placement patterns found in Adwaita:
/// - XML attributes: `fill="#2e3436"`, `stroke="#2e3436"`
/// - CSS style attributes: `style="fill:#2e3436;..."`
///
/// Only foreground placeholder colors are replaced. Semantic colors
/// (success green `#33d17a`, warning orange `#ff7800`, error red
/// `#e01b24`/`#ed333b`) are preserved.
///
/// Returns the original bytes unchanged if the SVG already uses
/// `currentColor` (Breeze-style) or is not valid UTF-8.
fn normalize_gtk_symbolic(svg_bytes: Vec<u8>, replacement: &str) -> Vec<u8> {
    let Ok(svg_str) = std::str::from_utf8(&svg_bytes) else {
        return svg_bytes;
    };

    // Already uses currentColor (Breeze convention) -- no normalization needed
    if svg_str.contains("currentColor") {
        return svg_bytes;
    }

    // Check if any GTK foreground colors are present
    if !GTK_FG_COLORS.iter().any(|c| svg_str.contains(c)) {
        return svg_bytes;
    }

    let mut result = svg_str.to_string();
    for color in GTK_FG_COLORS {
        // XML attributes: fill="..." and stroke="..."
        result = result.replace(
            &format!("fill=\"{color}\""),
            &format!("fill=\"{replacement}\""),
        );
        result = result.replace(
            &format!("stroke=\"{color}\""),
            &format!("stroke=\"{replacement}\""),
        );
        // CSS style attributes: fill:#2e3436 (8 icons use this form)
        result = result.replace(&format!("fill:{color}"), &format!("fill:{replacement}"));
        result = result.replace(&format!("stroke:{color}"), &format!("stroke:{replacement}"));
    }
    result.into_bytes()
}

#[cfg(test)]
#[cfg(feature = "system-icons")]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::{IconRole, IconSet, icon_name};

    #[test]
    fn lookup_size_clamps_to_i16() {
        const LARGEST: u16 = i16::MAX as u16;
        assert_eq!(lookup_size(24), 24);
        assert_eq!(lookup_size(u32::from(LARGEST)), LARGEST);
        assert_eq!(lookup_size(32_768), LARGEST);
        assert_eq!(lookup_size(u32::from(u16::MAX)), LARGEST);
        assert_eq!(lookup_size(u32::MAX), LARGEST);
    }

    /// A size past `i16::MAX` misses every Breeze directory, so
    /// freedesktop-icons measures its distance to each: in a debug build
    /// that subtraction overflowed `i16` and panicked. Breeze is looked for
    /// where the lookup searches, [`icon_base_dirs`].
    #[test]
    fn a_size_past_i16_loads_without_overflow() {
        if !has_theme_index("breeze", icon_base_dirs()) {
            eprintln!("skipped: the breeze theme is not installed");
            return;
        }
        for size in [32_768, 32_784, u32::from(u16::MAX)] {
            let _ = load_freedesktop_icon_by_name("edit-copy", "breeze", size, None);
        }
    }

    /// `dialog-error.svg` and `edit-copy.svg` of the icon theme `fixture`.
    const FIXTURE_DIALOG_ERROR: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><circle fill="#da4453" cx="8" cy="8" r="7"/></svg>"##;
    const FIXTURE_EDIT_COPY: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill="#232629" d="M2 2h9v9H2zM5 5h9v9H5z"/></svg>"##;

    /// Writes the icon theme `fixture`, which holds `dialog-error.svg` and
    /// `edit-copy.svg`, into `icons`.
    fn write_fixture_theme(icons: &Path) -> std::io::Result<()> {
        native_theme_test_fixtures::write_scalable_theme(
            icons,
            "fixture",
            &[
                ("dialog-error", FIXTURE_DIALOG_ERROR),
                ("edit-copy", FIXTURE_EDIT_COPY),
            ],
        )
    }

    /// Runs the test `test_path` again in a child process whose system icon
    /// theme is `fixture` ([`write_fixture_theme`],
    /// [`native_theme_test_fixtures`]).
    fn in_fixture_theme(test_path: &str) -> std::io::Result<()> {
        let child = native_theme_test_fixtures::Child::kde("fixture");
        native_theme_test_fixtures::run(test_path, child, write_fixture_theme)
    }

    #[test]
    fn load_icon_returns_some_for_dialog_error() -> std::io::Result<()> {
        if !native_theme_test_fixtures::in_child() {
            return in_fixture_theme("freedesktop::tests::load_icon_returns_some_for_dialog_error");
        }
        let theme = crate::system_icon_theme().expect("the fixture names the icon theme");
        assert_eq!(theme, "fixture");
        let name = icon_name(IconRole::DialogError, IconSet::Freedesktop).unwrap();
        let result = load_freedesktop_icon_by_name(name, &theme, 24, None);
        assert_eq!(
            result,
            Some(IconData::Svg(Cow::Borrowed(
                FIXTURE_DIALOG_ERROR.as_bytes()
            ))),
            "DialogError should resolve to the theme's SVG"
        );
        Ok(())
    }

    /// Notification is looked up as `notification-active` (KDE's name): a
    /// theme holding it gives its SVG, and `fixture`, which lacks it, gives
    /// `None`, not Material's icon. Both themes are fixtures in a child
    /// process ([`native_theme_test_fixtures`]).
    #[test]
    fn load_icon_notification_attempts_native_lookup() -> std::io::Result<()> {
        const NAME: &str = "freedesktop::tests::load_icon_notification_attempts_native_lookup";
        const NOTIFICATION: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill="#232629" d="M3 3h10v10H3z"/></svg>"##;
        if native_theme_test_fixtures::in_child() {
            let name = icon_name(IconRole::Notification, IconSet::Freedesktop).unwrap();
            assert_eq!(name, "notification-active");
            assert_eq!(
                load_freedesktop_icon_by_name(name, "notifying", 24, None),
                Some(IconData::Svg(Cow::Borrowed(NOTIFICATION.as_bytes())))
            );
            assert_eq!(
                load_freedesktop_icon_by_name(name, "fixture", 24, None),
                None,
                "a theme without notification-active"
            );
            return Ok(());
        }
        let child = native_theme_test_fixtures::Child::kde("fixture");
        native_theme_test_fixtures::run(NAME, child, |icons| {
            write_fixture_theme(icons)?;
            native_theme_test_fixtures::write_scalable_theme(
                icons,
                "notifying",
                &[("notification-active", NOTIFICATION)],
            )
        })
    }

    #[test]
    fn load_icon_returns_svg_variant() -> std::io::Result<()> {
        if !native_theme_test_fixtures::in_child() {
            return in_fixture_theme("freedesktop::tests::load_icon_returns_svg_variant");
        }
        let theme = crate::system_icon_theme().expect("the fixture names the icon theme");
        let name = icon_name(IconRole::ActionCopy, IconSet::Freedesktop).unwrap();
        let result = load_freedesktop_icon_by_name(name, &theme, 24, None);
        assert!(result.is_some(), "ActionCopy should resolve to an icon");
        assert!(
            matches!(result.unwrap(), IconData::Svg(_)),
            "Expected Svg variant"
        );
        Ok(())
    }

    /// With no theme given and no icon theme detected, there is no spinner:
    /// no theme stands in for the one that could not be detected.
    #[test]
    fn spinner_without_a_detected_theme_is_none() {
        let spinner = load_freedesktop_spinner_with(None, || {
            Err(crate::Error::PlatformUnsupported {
                platform: "the test's failing detection",
            })
        });
        assert!(
            spinner.is_none(),
            "a spinner loaded though no icon theme was detected"
        );
    }

    #[test]
    fn find_icon_nonexistent_returns_none() {
        let result = find_icon("totally-nonexistent-icon-xyz", "hicolor", 24);
        assert!(result.is_none(), "Nonexistent icon should return None");
    }

    #[test]
    fn load_icon_by_name_finds_edit_copy() -> std::io::Result<()> {
        if !native_theme_test_fixtures::in_child() {
            return in_fixture_theme("freedesktop::tests::load_icon_by_name_finds_edit_copy");
        }
        let theme = crate::system_icon_theme().expect("the fixture names the icon theme");
        let result = load_freedesktop_icon_by_name("edit-copy", &theme, 24, None);
        assert_eq!(
            result,
            Some(IconData::Svg(Cow::Borrowed(FIXTURE_EDIT_COPY.as_bytes()))),
            "edit-copy should be found in system theme"
        );
        Ok(())
    }

    // === Theme directory filter (fixture base dirs) ===

    /// A throwaway tree of icon base dirs, removed on drop:
    ///
    /// - `share/icons/`: `child` (`Inherits=parent,hicolor`), `parent`
    ///   (`Inherits=grand`), `grand`, `hicolor`, `breeze`, `breeze-dark`,
    ///   `cycle-a` and `cycle-b` (each inheriting the other), `fork`
    ///   (`Inherits=left,right`), `left` (`Inherits=deep`), `right`,
    ///   `deep`, and a loose `loose.svg`;
    /// - `home/.icons/`: `child/` again, without an `index.theme`;
    /// - `share/pixmaps/`: `pixmap.svg`, outside every base dir.
    struct Fixture {
        root: PathBuf,
        bases: Vec<PathBuf>,
    }

    impl Fixture {
        fn new(tag: &str) -> Self {
            let root = std::env::temp_dir().join(format!(
                "native-theme-icon-dirs-{}-{tag}",
                std::process::id()
            ));
            let _ = std::fs::remove_dir_all(&root);
            let icons = root.join("share/icons");
            let home_icons = root.join("home/.icons");
            let theme = |base: &Path, name: &str, inherits: Option<&str>| {
                let dir = base.join(name);
                std::fs::create_dir_all(dir.join("actions")).unwrap();
                let inherits = inherits.map_or(String::new(), |i| format!("Inherits={i}\n"));
                std::fs::write(
                    dir.join("index.theme"),
                    format!("[Icon Theme]\nName={name}\n{inherits}Directories=actions\n"),
                )
                .unwrap();
            };
            theme(&icons, "child", Some("parent,hicolor"));
            theme(&icons, "parent", Some("grand"));
            theme(&icons, "grand", None);
            theme(&icons, "fork", Some("left,right"));
            theme(&icons, "left", Some("deep"));
            theme(&icons, "right", None);
            theme(&icons, "deep", None);
            theme(&icons, "hicolor", None);
            theme(&icons, "breeze", None);
            theme(&icons, "breeze-dark", None);
            theme(&icons, "cycle-a", Some("cycle-b"));
            theme(&icons, "cycle-b", Some("cycle-a"));
            std::fs::create_dir_all(home_icons.join("child/actions")).unwrap();
            std::fs::write(icons.join("loose.svg"), "<svg/>").unwrap();
            std::fs::create_dir_all(root.join("share/pixmaps")).unwrap();
            std::fs::write(root.join("share/pixmaps/pixmap.svg"), "<svg/>").unwrap();
            Self {
                bases: vec![icons, home_icons],
                root,
            }
        }

        fn icons(&self, rest: &str) -> PathBuf {
            self.root.join("share/icons").join(rest)
        }

        /// Whether `path` lies in the own directory of a theme of
        /// `theme`'s chain.
        fn accepts(&self, theme: &str, path: &Path) -> bool {
            theme_chain(theme, &self.bases).is_some_and(|names| {
                names
                    .iter()
                    .any(|name| is_in_theme_dir(path, name, &self.bases))
            })
        }

        /// Put `<name>.svg` in `theme`'s `actions` directory.
        fn add_icon(&self, theme: &str, name: &str) -> PathBuf {
            let path = self.icons(&format!("{theme}/actions/{name}.svg"));
            std::fs::write(&path, "<svg/>").unwrap();
            path
        }

        /// What freedesktop-icons 0.4.0 returns for `name` asked of
        /// `theme`: the file in `theme`, else in a theme it names in
        /// `Inherits=` (not their parents), else in `hicolor`.
        fn freedesktop_icons_lookup(&self, name: &str, theme: &str) -> Option<PathBuf> {
            let mut searched = vec![theme.to_string()];
            searched.extend(declared_parents(theme, &self.bases));
            searched.push("hicolor".to_string());
            searched
                .iter()
                .flat_map(|t| {
                    self.bases
                        .iter()
                        .map(move |base| base.join(t).join("actions").join(format!("{name}.svg")))
                })
                .find(|path| path.exists())
        }

        /// [`first_in_chain`] for `name` over `theme`'s chain, with
        /// [`Self::freedesktop_icons_lookup`] as the lookup.
        fn find(&self, name: &str, theme: &str) -> Option<PathBuf> {
            let chain = theme_chain(theme, &self.bases)?;
            first_in_chain(&chain, &self.bases, |t| {
                self.freedesktop_icons_lookup(name, t)
            })
        }
    }

    impl Drop for Fixture {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.root);
        }
    }

    #[test]
    fn theme_dirs_accept_the_theme_itself() {
        let fx = Fixture::new("own");
        assert!(fx.accepts("child", &fx.icons("child/actions/edit-copy.svg")));
        assert!(fx.accepts(
            "child",
            &fx.root.join("home/.icons/child/actions/edit-copy.svg")
        ));
    }

    #[test]
    fn theme_dirs_accept_a_declared_parent() {
        let fx = Fixture::new("parent");
        assert!(fx.accepts("child", &fx.icons("parent/actions/edit-copy.svg")));
    }

    #[test]
    fn theme_dirs_reject_hicolor_even_when_declared() {
        let fx = Fixture::new("hicolor");
        assert!(!fx.accepts("child", &fx.icons("hicolor/actions/edit-copy.svg")));
        assert!(!fx.accepts("parent", &fx.icons("hicolor/actions/edit-copy.svg")));
    }

    #[test]
    fn theme_dirs_accept_hicolor_when_it_is_the_theme() {
        let fx = Fixture::new("hicolor-chosen");
        assert!(fx.accepts("hicolor", &fx.icons("hicolor/actions/edit-copy.svg")));
    }

    #[test]
    fn theme_dirs_reject_loose_and_pixmaps_files() {
        let fx = Fixture::new("loose");
        assert!(!fx.accepts("child", &fx.icons("loose.svg")));
        assert!(!fx.accepts("child", &fx.root.join("home/.icons/loose.svg")));
        assert!(!fx.accepts("child", &fx.root.join("share/pixmaps/pixmap.svg")));
        assert!(!fx.accepts(
            "child",
            &fx.root.join("share/pixmaps/child/actions/edit-copy.svg")
        ));
    }

    #[test]
    fn theme_dirs_match_whole_components() {
        let fx = Fixture::new("components");
        assert!(!fx.accepts("breeze", &fx.icons("breeze-dark/actions/edit-copy.svg")));
        assert!(!fx.accepts("breeze-dark", &fx.icons("breeze/actions/edit-copy.svg")));
        assert!(fx.accepts("breeze", &fx.icons("breeze/actions/edit-copy.svg")));
    }

    #[test]
    fn theme_dirs_reject_a_path_climbing_out_of_the_theme() {
        let fx = Fixture::new("climb");
        assert!(!fx.accepts("child", &fx.icons("child/../hicolor/actions/edit-copy.svg")));
    }

    #[test]
    fn theme_chain_is_depth_first_in_declared_order() {
        let fx = Fixture::new("order");
        assert_eq!(
            theme_chain("child", &fx.bases).unwrap(),
            ["child", "parent", "grand"]
        );
        assert_eq!(
            theme_chain("fork", &fx.bases).unwrap(),
            ["fork", "left", "deep", "right"]
        );
    }

    #[test]
    fn chain_lookup_reaches_a_grandparent() {
        let fx = Fixture::new("grand");
        let grand = fx.add_icon("grand", "grand-only");
        fx.add_icon("hicolor", "grand-only");
        assert_eq!(fx.find("grand-only", "child"), Some(grand));
    }

    #[test]
    fn chain_lookup_takes_a_theme_s_own_file_only() {
        let fx = Fixture::new("own-file");
        fx.add_icon("parent", "parent-only");
        fx.add_icon("hicolor", "hicolor-only");
        let child_only = ["child".to_string()];
        let lookup = |t: &str| fx.freedesktop_icons_lookup("parent-only", t);
        assert_eq!(first_in_chain(&child_only, &fx.bases, lookup), None);
        let lookup = |t: &str| fx.freedesktop_icons_lookup("hicolor-only", t);
        assert_eq!(first_in_chain(&child_only, &fx.bases, lookup), None);
        assert_eq!(fx.find("hicolor-only", "child"), None);
    }

    #[test]
    fn chain_lookup_takes_the_nearer_theme() {
        let fx = Fixture::new("nearer");
        let parent = fx.add_icon("parent", "both");
        fx.add_icon("grand", "both");
        assert_eq!(fx.find("both", "child"), Some(parent));
        let deep = fx.add_icon("deep", "split");
        fx.add_icon("right", "split");
        assert_eq!(fx.find("split", "fork"), Some(deep));
    }

    /// `name` looked up over `theme`'s chain as [`lookup_in_chain`] does,
    /// with the fixture's stem index and [`Fixture::freedesktop_icons_lookup`]
    /// as the library; the themes the library was asked for go to `asked`.
    fn find_indexed(
        fx: &Fixture,
        name: &str,
        theme: &str,
        asked: &mut Vec<String>,
    ) -> Option<PathBuf> {
        let chain = theme_chain(theme, &fx.bases)?;
        let candidates =
            themes_that_may_have(name, &chain, |t| Arc::new(theme_icon_stems(t, &fx.bases)));
        first_in_chain(&candidates, &fx.bases, |t| {
            asked.push(t.to_string());
            fx.freedesktop_icons_lookup(name, t)
        })
    }

    #[test]
    fn chain_lookup_never_asks_a_theme_without_the_name() {
        let fx = Fixture::new("indexed-miss");
        let mut asked = Vec::new();
        assert_eq!(find_indexed(&fx, "nowhere", "child", &mut asked), None);
        assert!(asked.is_empty(), "asked {asked:?}");
        fx.add_icon("hicolor", "hicolor-only");
        assert_eq!(find_indexed(&fx, "hicolor-only", "child", &mut asked), None);
        assert!(asked.is_empty(), "asked {asked:?}");
    }

    #[test]
    fn chain_lookup_asks_only_the_themes_with_the_name() {
        let fx = Fixture::new("indexed-hit");
        let grand = fx.add_icon("grand", "grand-only");
        let mut asked = Vec::new();
        assert_eq!(
            find_indexed(&fx, "grand-only", "child", &mut asked),
            Some(grand)
        );
        assert_eq!(asked, ["grand"]);
        let parent = fx.add_icon("parent", "both");
        fx.add_icon("grand", "both");
        let mut asked = Vec::new();
        let found = find_indexed(&fx, "both", "child", &mut asked);
        assert_eq!(found, Some(parent));
        assert_eq!(found, fx.find("both", "child"));
        assert_eq!(asked, ["parent"]);
    }

    #[test]
    fn chain_lookup_asks_every_theme_for_a_name_with_a_separator() {
        let fx = Fixture::new("indexed-separator");
        let mut asked = Vec::new();
        assert_eq!(find_indexed(&fx, "actions/x", "child", &mut asked), None);
        assert_eq!(asked, ["child", "parent", "grand"]);
    }

    #[cfg(unix)]
    #[test]
    fn theme_icon_stems_walk_nested_and_linked_dirs() {
        use std::os::unix::fs::symlink;
        let fx = Fixture::new("stems");
        let child = fx.icons("child");
        fx.add_icon("child", "flat");
        std::fs::create_dir_all(child.join("16x16/apps/deeper")).unwrap();
        std::fs::write(child.join("16x16/apps/deeper/nested.png"), "").unwrap();
        std::fs::write(child.join("actions/pixmap.xpm"), "").unwrap();
        std::fs::write(child.join("actions/upstream.xmp"), "").unwrap();
        std::fs::write(child.join("actions/notes.txt"), "").unwrap();
        std::fs::write(child.join("actions/backup.svg.bak"), "").unwrap();
        std::fs::write(child.join("icon-theme.cache"), "").unwrap();
        let elsewhere = fx.root.join("elsewhere");
        std::fs::create_dir_all(elsewhere.join("linked")).unwrap();
        std::fs::write(elsewhere.join("linked/via-dir.svg"), "").unwrap();
        std::fs::write(elsewhere.join("target.svg"), "").unwrap();
        symlink(elsewhere.join("linked"), child.join("linked")).unwrap();
        symlink(
            elsewhere.join("target.svg"),
            child.join("actions/via-file.svg"),
        )
        .unwrap();
        symlink(&child, child.join("actions/loop")).unwrap();
        symlink("..", child.join("16x16/up")).unwrap();
        symlink(child.join("missing"), child.join("dangling")).unwrap();
        std::fs::write(fx.root.join("home/.icons/child/actions/home.svg"), "").unwrap();
        let mut stems: Vec<String> = theme_icon_stems("child", &fx.bases).into_iter().collect();
        stems.sort();
        assert_eq!(
            stems,
            ["flat", "home", "nested", "upstream", "via-dir", "via-file"]
        );
        assert!(theme_icon_stems("no-such-theme", &fx.bases).is_empty());
    }

    /// A theme installed both for the user (in `~/.local/share/icons`, as
    /// "Get New Icons" installs it) and system-wide is read from the user's
    /// copy, the first `index.theme` in the specification's order: its
    /// `Inherits=` alone decides the chain.
    #[test]
    fn the_user_s_copy_of_a_theme_decides_its_chain() {
        let root = std::env::temp_dir().join(format!(
            "native-theme-icon-user-copy-{}",
            std::process::id()
        ));
        let _ = std::fs::remove_dir_all(&root);
        let home = root.join("home");
        let system = root.join("usr/share");
        let theme = |base: &Path, name: &str, inherits: &str| {
            std::fs::create_dir_all(base.join(name)).unwrap();
            std::fs::write(
                base.join(name).join("index.theme"),
                format!("[Icon Theme]\nName={name}\nInherits={inherits}\nDirectories=actions\n"),
            )
            .unwrap();
        };
        theme(&home.join(".local/share/icons"), "copied", "user-parent");
        theme(&system.join("icons"), "copied", "system-parent");
        theme(&system.join("icons"), "user-parent", "");
        theme(&system.join("icons"), "system-parent", "");
        let bases = crate::icons::icon_base_dirs_in(Some(&home), None, Some(system.as_os_str()));
        let chain = theme_chain("copied", &bases);
        let _ = std::fs::remove_dir_all(&root);
        assert_eq!(chain.unwrap(), ["copied", "user-parent"]);
    }

    #[test]
    fn theme_chain_terminates_on_a_cycle() {
        let fx = Fixture::new("cycle");
        let mut names = theme_chain("cycle-a", &fx.bases).unwrap();
        names.sort();
        assert_eq!(names, ["cycle-a", "cycle-b"]);
    }

    #[test]
    fn theme_chain_of_a_missing_theme_is_none() {
        let fx = Fixture::new("missing");
        assert_eq!(theme_chain("no-such-theme", &fx.bases), None);
        assert_eq!(theme_chain("../share/icons/child", &fx.bases), None);
    }

    /// A loose file in an icon base directory (`/usr/share/icons/cachyos.svg`
    /// on CachyOS) belongs to no theme, so a theme lookup must not return it.
    /// The file and breeze are looked for where the lookup searches,
    /// [`icon_base_dirs`].
    #[test]
    fn find_icon_rejects_a_loose_base_dir_file() {
        let bases = icon_base_dirs();
        let loose = bases.iter().any(|base| base.join("cachyos.svg").is_file());
        if !loose || !has_theme_index("breeze", bases) {
            eprintln!("skipped: needs cachyos.svg in an icon base directory and the breeze theme");
            return;
        }
        assert_eq!(find_icon("cachyos", "breeze", 24), None);
    }

    /// An icon breeze lacks is not taken from `hicolor`. hicolor's
    /// `scalable/apps` and breeze are looked for where the lookup searches,
    /// [`icon_base_dirs`], and a found path is refused in hicolor's
    /// directory under any of them.
    #[test]
    fn find_icon_never_returns_hicolor_for_another_theme() {
        let bases = icon_base_dirs();
        let entries = bases
            .iter()
            .find_map(|base| std::fs::read_dir(base.join("hicolor/scalable/apps")).ok());
        let (Some(entries), true) = (entries, has_theme_index("breeze", bases)) else {
            eprintln!("skipped: needs hicolor's scalable/apps and the breeze theme");
            return;
        };
        let names: Vec<String> = entries
            .filter_map(Result::ok)
            .filter_map(|e| {
                let path = e.path();
                (path.extension()? == "svg").then_some(())?;
                Some(path.file_stem()?.to_str()?.to_string())
            })
            .take(20)
            .collect();
        for name in &names {
            if let Some((path, _)) = find_icon(name, "breeze", 24) {
                assert!(
                    !is_in_theme_dir(&path, "hicolor", bases),
                    "{name} for breeze came from hicolor: {}",
                    path.display()
                );
            }
        }
    }

    /// A lookup over `files`, the (theme, name) pairs a fake chain has, that
    /// answers with the path `theme/name`.
    fn fake_lookup<'a>(
        files: &'a [(&'a str, &'a str)],
    ) -> impl FnMut(&str, &String) -> Option<PathBuf> + 'a {
        move |name, theme| {
            files
                .iter()
                .any(|&(t, n)| t == theme && n == name)
                .then(|| PathBuf::from(theme).join(name))
        }
    }

    /// The theme's own icon under a later name wins over its parent's under
    /// an earlier name: Adwaita's shape, whose parent AdwaitaLegacy has
    /// Breeze's `emblem-favorite` as a raster.
    #[test]
    fn first_of_names_searches_a_theme_for_every_name_before_its_parent() {
        let chain = ["Adwaita".to_string(), "AdwaitaLegacy".to_string()];
        let files = [
            ("AdwaitaLegacy", "emblem-favorite"),
            ("Adwaita", "starred-symbolic"),
        ];
        assert_eq!(
            first_of_names(&["emblem-favorite", "starred"], &chain, fake_lookup(&files)),
            Some((PathBuf::from("Adwaita/starred-symbolic"), true))
        );
        assert_eq!(
            first_of_names(&["emblem-favorite", "no-such"], &chain, fake_lookup(&files)),
            Some((PathBuf::from("AdwaitaLegacy/emblem-favorite"), false))
        );
        assert_eq!(first_of_names(&[], &chain, fake_lookup(&files)), None);
    }

    /// Within a theme the names keep their order, each tried as its
    /// symbolic form and then as itself: a later name's symbolic icon does
    /// not displace an earlier name's plain one (Breeze has both `cpu` and
    /// `computer-symbolic`), and a name's own symbolic form wins over it.
    #[test]
    fn first_of_names_keeps_the_names_order_within_a_theme() {
        let chain = ["breeze".to_string()];
        let files = [
            ("breeze", "cpu"),
            ("breeze", "computer-symbolic"),
            ("breeze", "edit-copy"),
            ("breeze", "edit-copy-symbolic"),
        ];
        assert_eq!(
            first_of_names(&["cpu", "computer"], &chain, fake_lookup(&files)),
            Some((PathBuf::from("breeze/cpu"), false))
        );
        assert_eq!(
            first_of_names(&["edit-copy"], &chain, fake_lookup(&files)),
            Some((PathBuf::from("breeze/edit-copy-symbolic"), true))
        );
        assert_eq!(
            first_of_names(&["computer-symbolic"], &chain, fake_lookup(&files)),
            Some((PathBuf::from("breeze/computer-symbolic"), true))
        );
    }

    /// On the installed Adwaita, `Heart`'s names in the gpui connector's
    /// order, Breeze's `emblem-favorite` first, load Adwaita's own
    /// `starred-symbolic`, not AdwaitaLegacy's `emblem-favorite` raster.
    /// Skipped where the two themes are not installed; the hermetic test of
    /// the order is the gpui connector's fixture test
    /// (`the_theme_s_own_name_wins_in_each_convention_s_theme`).
    #[test]
    fn find_any_icon_takes_adwaita_s_own_icon_over_adwaita_legacy_s() {
        let bases = icon_base_dirs();
        if !has_theme_index("Adwaita", bases)
            || !theme_icon_stems("AdwaitaLegacy", bases).contains("emblem-favorite")
            || !theme_icon_stems("Adwaita", bases).contains("starred-symbolic")
        {
            eprintln!(
                "skipped: needs Adwaita's starred-symbolic and AdwaitaLegacy's emblem-favorite"
            );
            return;
        }
        let (path, symbolic) = find_any_icon(&["emblem-favorite", "starred"], "Adwaita", 24)
            .expect("Adwaita has starred-symbolic");
        assert!(
            symbolic && is_in_theme_dir(&path, "Adwaita", bases),
            "loaded {}",
            path.display()
        );
        assert!(
            find_icon("emblem-favorite", "Adwaita", 24).is_some_and(|(path, _)| is_in_theme_dir(
                &path,
                "AdwaitaLegacy",
                bases
            )),
            "the name-by-name lookup this replaces takes AdwaitaLegacy's raster"
        );
    }

    /// Adwaita inherits AdwaitaLegacy: an icon only AdwaitaLegacy has is
    /// found for Adwaita. `default` inherits Adwaita but lists no
    /// `Directories`, so it is no icon theme, and nothing is found for it.
    /// The themes are looked for where the lookup searches,
    /// [`icon_base_dirs`], so the test runs exactly where the lookup can
    /// find them.
    #[test]
    fn find_icon_reaches_a_parent_theme_and_not_through_default() {
        let bases = icon_base_dirs();
        let inherits_adwaita = theme_index("default", bases)
            .is_some_and(|index| inherits(&index).contains(&"Adwaita"));
        if !inherits_adwaita || !has_theme_index("AdwaitaLegacy", bases) {
            eprintln!("skipped: needs `default` inheriting Adwaita, and AdwaitaLegacy");
            return;
        }
        fn stems(dir: &Path, out: &mut std::collections::BTreeSet<String>) {
            for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() {
                let path = entry.path();
                if path.is_dir() {
                    stems(&path, out);
                } else if let (Some(stem), Some("png" | "svg")) = (
                    path.file_stem().and_then(|s| s.to_str()),
                    path.extension().and_then(|e| e.to_str()),
                ) {
                    out.insert(stem.to_string());
                }
            }
        }
        let mut legacy_names = std::collections::BTreeSet::new();
        let mut adwaita_names = std::collections::BTreeSet::new();
        for base in bases {
            stems(&base.join("AdwaitaLegacy"), &mut legacy_names);
            stems(&base.join("Adwaita"), &mut adwaita_names);
            stems(&base.join("default"), &mut adwaita_names);
        }
        let legacy_only: Vec<&String> = legacy_names
            .iter()
            .filter(|name| {
                !name.ends_with("-symbolic")
                    && !adwaita_names.contains(name.as_str())
                    && !adwaita_names.contains(&format!("{name}-symbolic"))
            })
            .take(20)
            .collect();
        assert!(!legacy_only.is_empty(), "no AdwaitaLegacy-only icon found");
        for name in legacy_only {
            let found = find_icon(name, "Adwaita", 24);
            assert!(
                found.as_ref().is_some_and(|(path, _)| is_in_theme_dir(
                    path,
                    "AdwaitaLegacy",
                    bases
                )),
                "{name} for Adwaita: {found:?}"
            );
            assert_eq!(find_icon(name, "default", 24), None, "{name} for default");
        }
    }

    /// The fix must not lose an icon the theme has. Breeze is looked for
    /// where the lookup searches, [`icon_base_dirs`].
    #[test]
    fn find_icon_still_finds_breeze_edit_copy() {
        let bases = icon_base_dirs();
        if !has_theme_index("breeze", bases) {
            eprintln!("skipped: the breeze theme is not installed");
            return;
        }
        let (path, _) = find_icon("edit-copy", "breeze", 24).expect("breeze has edit-copy");
        assert!(
            is_in_theme_dir(&path, "breeze", bases),
            "{}",
            path.display()
        );
    }

    /// [`lookup_in_chain`] before the stem index: freedesktop-icons asked
    /// for every theme of the chain.
    fn lookup_in_chain_unfiltered(name: &str, size: u16, chain: &[String]) -> Option<PathBuf> {
        first_in_chain(chain, icon_base_dirs(), |theme| {
            freedesktop_icons::lookup(name)
                .with_theme(theme)
                .with_size(size)
                .force_svg()
                .find()
        })
    }

    /// Over the installed Breeze and Adwaita themes, the indexed lookup
    /// returns exactly what asking freedesktop-icons for every theme of the
    /// chain returns: for every name an `IconRole` maps to, the spinner's
    /// names, a spread of the theme's own names, names no theme has, and
    /// each of those with `-symbolic`.
    #[cfg(target_os = "linux")]
    #[test]
    #[ignore = "slow (~30-50 s): compares the indexed lookup with freedesktop-icons' unfiltered one on the installed icon themes; run with --ignored"]
    fn indexed_lookup_matches_the_unfiltered_lookup_on_installed_themes() {
        const SIZES: [u16; 4] = [16, 22, 24, 32];
        let mut checked = 0;
        for theme in ["breeze", "breeze-dark", "Adwaita"] {
            if !has_theme_index(theme, icon_base_dirs()) {
                eprintln!("skipped {theme}: not installed");
                continue;
            }
            let mut names: std::collections::BTreeSet<String> = IconRole::ALL
                .iter()
                .filter_map(|role| icon_name(*role, IconSet::Freedesktop))
                .chain(["process-working", "process-working-symbolic"])
                .map(str::to_string)
                .collect();
            let mut own: Vec<String> = theme_icon_stems(theme, icon_base_dirs())
                .into_iter()
                .collect();
            own.sort();
            let step = own.len().div_ceil(300).max(1);
            names.extend(own.into_iter().step_by(step));
            names.extend((0..20).map(|i| format!("nt-test-missing-{i}")));
            let symbolic: Vec<String> = names.iter().map(|n| format!("{n}-symbolic")).collect();
            names.extend(symbolic);
            let names: Vec<String> = names.into_iter().collect();
            let mismatches: Vec<String> = std::thread::scope(|scope| {
                let workers: Vec<_> = SIZES
                    .iter()
                    .map(|&size| {
                        let names = &names;
                        scope.spawn(move || {
                            names
                                .iter()
                                .filter_map(|name| {
                                    let new = find_icon(name, theme, size);
                                    let old = find_icon_with(
                                        name,
                                        theme,
                                        size,
                                        lookup_in_chain_unfiltered,
                                    );
                                    (new != old).then(|| {
                                        format!("{theme} {name}@{size}: {new:?} != {old:?}")
                                    })
                                })
                                .collect::<Vec<_>>()
                        })
                    })
                    .collect();
                workers
                    .into_iter()
                    .flat_map(|worker| worker.join().unwrap())
                    .collect()
            });
            assert!(mismatches.is_empty(), "{mismatches:#?}");
            eprintln!(
                "{theme}: {} names x {} sizes compared",
                names.len(),
                SIZES.len()
            );
            checked += 1;
        }
        if checked == 0 {
            eprintln!("skipped: none of breeze, breeze-dark, Adwaita is installed");
        }
    }

    #[test]
    fn load_icon_by_name_returns_none_for_nonexistent() {
        let result = load_freedesktop_icon_by_name("zzz-nonexistent-icon", "hicolor", 24, None);
        assert!(result.is_none());
    }

    // === Sprite sheet parser tests ===

    #[test]
    fn test_parse_sprite_sheet_two_frames() {
        // 10x20 viewBox = 2 frames of 10x10
        let svg = br#"<svg viewBox="0 0 10 20" xmlns="http://www.w3.org/2000/svg">
            <rect x="0" y="0" width="10" height="10" fill="red"/>
            <rect x="0" y="10" width="10" height="10" fill="blue"/>
        </svg>"#;

        let frames = parse_sprite_sheet(svg).expect("should parse 2-frame sprite sheet");
        assert_eq!(frames.len(), 2);

        let frame0 = std::str::from_utf8(&frames[0]).unwrap();
        assert!(
            frame0.contains(r#"viewBox="0 0 10 10""#),
            "frame 0 viewBox: {frame0}"
        );

        let frame1 = std::str::from_utf8(&frames[1]).unwrap();
        assert!(
            frame1.contains(r#"viewBox="0 10 10 10""#),
            "frame 1 viewBox: {frame1}"
        );
    }

    #[test]
    fn test_parse_sprite_sheet_fifteen_frames() {
        // 22x330 viewBox = 15 frames (Breeze-like)
        let svg = br#"<svg viewBox="0 0 22 330" xmlns="http://www.w3.org/2000/svg">
            <path d="M0 0"/>
        </svg>"#;

        let frames = parse_sprite_sheet(svg).expect("should parse 15-frame sprite sheet");
        assert_eq!(frames.len(), 15);

        // Verify first and last frame viewBox values
        let first = std::str::from_utf8(&frames[0]).unwrap();
        assert!(first.contains(r#"viewBox="0 0 22 22""#));

        let last = std::str::from_utf8(&frames[14]).unwrap();
        assert!(last.contains(r#"viewBox="0 308 22 22""#));
    }

    #[test]
    fn test_parse_sprite_sheet_single_frame_returns_none() {
        // 22x22 = single frame, not a sprite sheet
        let svg = br#"<svg viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg">
            <circle cx="11" cy="11" r="10"/>
        </svg>"#;
        assert!(parse_sprite_sheet(svg).is_none());
    }

    #[test]
    fn test_parse_sprite_sheet_non_multiple_returns_none() {
        // 22x33: height is not an exact multiple of width
        let svg = br#"<svg viewBox="0 0 22 33" xmlns="http://www.w3.org/2000/svg">
            <path d="M0 0"/>
        </svg>"#;
        assert!(parse_sprite_sheet(svg).is_none());
    }

    #[test]
    fn test_parse_sprite_sheet_invalid_svg_returns_none() {
        assert!(parse_sprite_sheet(b"not svg at all").is_none());
    }

    #[test]
    fn test_parse_sprite_sheet_comma_separated_viewbox() {
        // viewBox with commas instead of spaces
        let svg = br#"<svg viewBox="0,0,10,20" xmlns="http://www.w3.org/2000/svg">
            <rect x="0" y="0" width="10" height="10" fill="red"/>
        </svg>"#;

        let frames = parse_sprite_sheet(svg).expect("should parse comma-separated viewBox");
        assert_eq!(frames.len(), 2);

        let frame0 = std::str::from_utf8(&frames[0]).unwrap();
        assert!(frame0.contains(r#"viewBox="0 0 10 10""#));
    }

    #[test]
    fn test_parse_sprite_sheet_preserves_svg_content() {
        let svg = br#"<svg viewBox="0 0 10 20" xmlns="http://www.w3.org/2000/svg">
            <rect x="0" y="0" width="10" height="10" fill="red" id="unique-marker"/>
            <rect x="0" y="10" width="10" height="10" fill="blue"/>
        </svg>"#;

        let frames = parse_sprite_sheet(svg).unwrap();
        // Both frames should preserve the full SVG content
        for frame in &frames {
            let s = std::str::from_utf8(frame).unwrap();
            assert!(
                s.contains("unique-marker"),
                "SVG content should be preserved in all frames"
            );
            assert!(s.contains("<rect"), "rect elements should be preserved");
            assert!(s.contains("xmlns="), "namespace should be preserved");
        }
    }

    #[test]
    fn test_parse_sprite_sheet_zero_width_returns_none() {
        assert!(parse_sprite_sheet(br#"<svg viewBox="0 0 0 0.005"/>"#).is_none());
    }

    #[test]
    fn test_parse_sprite_sheet_frames_over_decode_bound_returns_none() {
        assert!(parse_sprite_sheet(br#"<svg viewBox="0 0 1 1000000000"/>"#).is_none());
    }

    #[test]
    fn test_parse_sprite_sheet_non_finite_viewbox_returns_none() {
        assert!(parse_sprite_sheet(br#"<svg viewBox="0 0 1 inf"/>"#).is_none());
        assert!(parse_sprite_sheet(br#"<svg viewBox="0 0 NaN 20"/>"#).is_none());
    }

    /// A GTK-convention theme's symbolic spinner fills with a placeholder
    /// (`#2e3436`); it comes back as `currentColor`, as every other symbolic
    /// icon does, for the connectors to colour.
    #[test]
    fn a_symbolic_spinner_s_placeholder_becomes_current_color() {
        let dir = std::env::temp_dir().join(format!(
            "native-theme-symbolic-spinner-{}",
            std::process::id()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("process-working-symbolic.svg");
        std::fs::write(
            &path,
            r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill="#2e3436" d="M0 0h16v16H0z"/></svg>"##,
        )
        .unwrap();
        let spinner = spinner_in_chain(&["gtk-like".to_string()], |name, _, _| {
            (name == "process-working-symbolic").then(|| path.clone())
        });
        let _ = std::fs::remove_dir_all(&dir);
        let spinner = spinner.expect("the symbolic spinner loads");
        let IconData::Svg(bytes) = spinner.first_frame() else {
            panic!("the symbolic spinner is not an SVG");
        };
        let svg = std::str::from_utf8(bytes).unwrap();
        assert!(
            svg.contains(r#"fill="currentColor""#) && !svg.contains("#2e3436"),
            "{svg}"
        );
    }

    #[test]
    fn test_load_freedesktop_spinner_no_panic() {
        // Just verify the function doesn't panic -- result is theme-dependent
        let _result = load_freedesktop_spinner(None);
    }

    // === GTK symbolic icon normalization tests ===

    #[test]
    fn normalize_gtk_symbolic_replaces_2e3436() {
        let svg = br##"<svg><path fill="#2e3436" d="M0 0"/></svg>"##.to_vec();
        let result = normalize_gtk_symbolic(svg, "#ffffff");
        let s = std::str::from_utf8(&result).unwrap();
        assert!(s.contains(r##"fill="#ffffff""##));
        assert!(!s.contains("#2e3436"));
    }

    #[test]
    fn normalize_gtk_symbolic_replaces_2e3434_preserves_opacity() {
        let svg = br##"<svg><path fill="#2e3434" fill-opacity="0.35" d="M0 0"/></svg>"##.to_vec();
        let result = normalize_gtk_symbolic(svg, "#ffffff");
        let s = std::str::from_utf8(&result).unwrap();
        assert!(s.contains(r##"fill="#ffffff""##));
        assert!(s.contains(r#"fill-opacity="0.35""#));
    }

    #[test]
    fn normalize_gtk_symbolic_replaces_222222() {
        let svg = br##"<svg><path fill="#222222" d="M0 0"/></svg>"##.to_vec();
        let result = normalize_gtk_symbolic(svg, "#ffffff");
        let s = std::str::from_utf8(&result).unwrap();
        assert!(s.contains(r##"fill="#ffffff""##));
        assert!(!s.contains("#222222"));
    }

    #[test]
    fn normalize_gtk_symbolic_replaces_474747() {
        let svg = br##"<svg><path fill="#474747" d="M0 0"/></svg>"##.to_vec();
        let result = normalize_gtk_symbolic(svg, "#ffffff");
        let s = std::str::from_utf8(&result).unwrap();
        assert!(s.contains(r##"fill="#ffffff""##));
        assert!(!s.contains("#474747"));
    }

    #[test]
    fn normalize_gtk_symbolic_replaces_stroke() {
        let svg = br##"<svg><path stroke="#2e3436" fill="none" d="M1 1l14 14"/></svg>"##.to_vec();
        let result = normalize_gtk_symbolic(svg, "#ffffff");
        let s = std::str::from_utf8(&result).unwrap();
        assert!(s.contains(r##"stroke="#ffffff""##));
        assert!(!s.contains("#2e3436"));
    }

    #[test]
    fn normalize_gtk_symbolic_replaces_css_style_fill() {
        let svg = br##"<svg><path style="fill:#2e3436;fill-opacity:1" d="M0 0"/></svg>"##.to_vec();
        let result = normalize_gtk_symbolic(svg, "#ffffff");
        let s = std::str::from_utf8(&result).unwrap();
        assert!(s.contains("fill:#ffffff"));
        assert!(!s.contains("#2e3436"));
    }

    #[test]
    fn normalize_gtk_symbolic_preserves_semantic_colors() {
        let svg = br##"<svg><path fill="#2e3436"/><path fill="#ff7800"/><path fill="#33d17a"/><path fill="#e01b24"/></svg>"##.to_vec();
        let result = normalize_gtk_symbolic(svg, "#ffffff");
        let s = std::str::from_utf8(&result).unwrap();
        assert!(s.contains("#ffffff"));
        assert!(s.contains("#ff7800"), "warning color must be preserved");
        assert!(s.contains("#33d17a"), "success color must be preserved");
        assert!(s.contains("#e01b24"), "error color must be preserved");
    }

    #[test]
    fn normalize_gtk_symbolic_skips_currentcolor_svgs() {
        let svg = br##"<svg><defs><style>.ColorScheme-Text{color:#232629}</style></defs><path fill="currentColor"/></svg>"##.to_vec();
        let original = svg.clone();
        let result = normalize_gtk_symbolic(svg, "#ffffff");
        assert_eq!(
            result, original,
            "Breeze-style SVGs should pass through unchanged"
        );
    }

    #[test]
    fn normalize_gtk_symbolic_skips_non_gtk_svgs() {
        let svg = br#"<svg><path fill="red"/></svg>"#.to_vec();
        let original = svg.clone();
        let result = normalize_gtk_symbolic(svg, "#ffffff");
        assert_eq!(
            result, original,
            "non-GTK SVGs should pass through unchanged"
        );
    }

    // === PNG decode path (for raster-only legacy themes like AdwaitaLegacy) ===

    /// Encode a minimal in-memory PNG with a known pixel pattern for
    /// round-trip tests. Returns `None` on encode error.
    fn encode_test_png(
        width: u32,
        height: u32,
        color: png::ColorType,
        pixels: &[u8],
    ) -> Option<Vec<u8>> {
        let mut out = Vec::new();
        let mut encoder = png::Encoder::new(&mut out, width, height);
        encoder.set_color(color);
        encoder.set_depth(png::BitDepth::Eight);
        let mut writer = encoder.write_header().ok()?;
        writer.write_image_data(pixels).ok()?;
        drop(writer);
        Some(out)
    }

    #[test]
    fn decode_png_to_rgba_roundtrips_2x2_rgba() {
        // Known pixel pattern: 4 distinct RGBA pixels
        let pixels: [u8; 16] = [
            0xff, 0x00, 0x00, 0xff, // red, opaque
            0x00, 0xff, 0x00, 0x80, // green, half-alpha
            0x00, 0x00, 0xff, 0xff, // blue, opaque
            0x11, 0x22, 0x33, 0x44, // arbitrary
        ];
        let bytes = encode_test_png(2, 2, png::ColorType::Rgba, &pixels).expect("test PNG encode");

        let result = decode_png_to_rgba(&bytes);
        match result {
            Some(IconData::Rgba(rgba)) => {
                assert_eq!(rgba.width(), 2);
                assert_eq!(rgba.height(), 2);
                assert_eq!(rgba.data(), pixels.as_slice());
            }
            other => panic!("expected Rgba, got {other:?}"),
        }
    }

    #[test]
    fn decode_png_to_rgba_expands_rgb_to_rgba() {
        // RGB (no alpha) input must come out as RGBA with alpha=0xff.
        let pixels: [u8; 6] = [
            0xab, 0xcd, 0xef, // pixel 0
            0x11, 0x22, 0x33, // pixel 1
        ];
        let bytes = encode_test_png(2, 1, png::ColorType::Rgb, &pixels).expect("test PNG encode");

        match decode_png_to_rgba(&bytes) {
            Some(IconData::Rgba(rgba)) => {
                assert_eq!((rgba.width(), rgba.height()), (2, 1));
                assert_eq!(
                    rgba.into_data(),
                    vec![0xab, 0xcd, 0xef, 0xff, 0x11, 0x22, 0x33, 0xff]
                );
            }
            other => panic!("expected Rgba, got {other:?}"),
        }
    }

    #[test]
    fn decode_png_to_rgba_expands_grayscale_to_rgba() {
        let pixels: [u8; 2] = [0x40, 0xc0];
        let bytes =
            encode_test_png(2, 1, png::ColorType::Grayscale, &pixels).expect("test PNG encode");

        match decode_png_to_rgba(&bytes) {
            Some(IconData::Rgba(rgba)) => {
                assert_eq!(
                    rgba.into_data(),
                    vec![0x40, 0x40, 0x40, 0xff, 0xc0, 0xc0, 0xc0, 0xff]
                );
            }
            other => panic!("expected Rgba, got {other:?}"),
        }
    }

    #[test]
    fn decode_png_to_rgba_rejects_non_png_bytes() {
        assert!(decode_png_to_rgba(b"not a png at all").is_none());
        assert!(decode_png_to_rgba(&[]).is_none());
    }

    /// CRC-32 (ISO 3309, as PNG chunks use it), bitwise.
    fn png_crc32(bytes: &[u8]) -> u32 {
        let mut crc = 0xffff_ffff_u32;
        for &byte in bytes {
            crc ^= u32::from(byte);
            for _ in 0..8 {
                crc = if crc & 1 == 1 {
                    (crc >> 1) ^ 0xedb8_8320
                } else {
                    crc >> 1
                };
            }
        }
        !crc
    }

    /// Append a PNG chunk (length, type, data, CRC over type and data).
    fn push_png_chunk(out: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
        out.extend_from_slice(&u32::try_from(data.len()).unwrap().to_be_bytes());
        let start = out.len();
        out.extend_from_slice(kind);
        out.extend_from_slice(data);
        let crc = png_crc32(&out[start..]);
        out.extend_from_slice(&crc.to_be_bytes());
    }

    #[test]
    fn decode_png_to_rgba_rejects_huge_ihdr_dimensions() {
        // A few bytes whose IHDR declares 1 000 000 x 1 000 000 8-bit RGBA.
        let mut ihdr = Vec::new();
        ihdr.extend_from_slice(&1_000_000_u32.to_be_bytes());
        ihdr.extend_from_slice(&1_000_000_u32.to_be_bytes());
        ihdr.extend_from_slice(&[8, 6, 0, 0, 0]);
        let mut bytes = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
        push_png_chunk(&mut bytes, b"IHDR", &ihdr);
        push_png_chunk(&mut bytes, b"IDAT", &[]);
        push_png_chunk(&mut bytes, b"IEND", &[]);

        assert!(decode_png_to_rgba(&bytes).is_none());
    }

    #[test]
    fn png_crc32_matches_encoder_output() {
        let bytes = encode_test_png(1, 1, png::ColorType::Rgba, &[1, 2, 3, 4]).unwrap();
        // The IHDR chunk follows the 8-byte signature: length (4), type and data (17), CRC (4).
        let crc = u32::from_be_bytes(bytes[29..33].try_into().unwrap());
        assert_eq!(png_crc32(&bytes[12..29]), crc);
    }

    /// A raster-only theme's icon, laid out as AdwaitaLegacy's
    /// (`24x24/legacy`), decodes to RGBA, not raw PNG bytes inside
    /// `IconData::Svg`. The theme is a fixture in a child process
    /// ([`native_theme_test_fixtures`]) whose `edit-copy` is
    /// [`encode_test_png`]'s.
    #[test]
    fn load_icon_from_png_only_theme_returns_rgba() -> std::io::Result<()> {
        const NAME: &str = "freedesktop::tests::load_icon_from_png_only_theme_returns_rgba";
        let pixels: [u8; 16] = [
            0xff, 0x00, 0x00, 0xff, // red, opaque
            0x00, 0xff, 0x00, 0x80, // green, half-alpha
            0x00, 0x00, 0xff, 0xff, // blue, opaque
            0x11, 0x22, 0x33, 0x44, // arbitrary
        ];
        if native_theme_test_fixtures::in_child() {
            let result = load_freedesktop_icon_by_name("edit-copy", "raster-only", 24, None);
            let data = result.expect("edit-copy exists in raster-only 24x24/legacy");
            match data {
                IconData::Rgba(rgba) => {
                    assert_eq!((rgba.width(), rgba.height()), (2, 2));
                    assert_eq!(rgba.data(), &pixels[..]);
                }
                IconData::Svg(bytes) => {
                    let head: Vec<u8> = bytes.iter().take(8).copied().collect();
                    panic!(
                        "expected Rgba, got Svg with {} bytes starting {:x?} \
                         (PNG magic is 89 50 4e 47)",
                        bytes.len(),
                        head
                    );
                }
            }
            return Ok(());
        }
        let child = native_theme_test_fixtures::Child {
            desktop: "KDE",
            icon_theme: None,
        };
        native_theme_test_fixtures::run(NAME, child, |icons| {
            let theme = icons.join("raster-only");
            std::fs::create_dir_all(theme.join("24x24/legacy"))?;
            std::fs::write(
                theme.join("index.theme"),
                "[Icon Theme]\nName=raster-only\nDirectories=24x24/legacy\n\n\
                 [24x24/legacy]\nSize=24\nType=Fixed\n",
            )?;
            let png = encode_test_png(2, 2, png::ColorType::Rgba, &pixels)
                .ok_or_else(|| std::io::Error::other("test PNG encode"))?;
            std::fs::write(theme.join("24x24/legacy/edit-copy.png"), png)
        })
    }
}