native-theme 0.6.1

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

use std::fmt;

#[allow(unused_imports)]
use std::borrow::Cow;

#[allow(unused_imports)]
use crate::model::icons::{icon_name, system_icon_set, system_icon_theme};
use crate::model::{AnimatedIcon, IconData, IconProvider, IconRole, IconSet};
#[allow(unused_imports)]
use crate::model::{bundled_icon_by_name, bundled_icon_svg};

/// Identifies what icon to load: a semantic role, a platform-specific name,
/// or a custom provider.
///
/// Constructed via [`From`] impls -- users rarely reference this type directly.
/// Pass an [`IconRole`], `&str`, or `&dyn IconProvider` to a per-set loader's
/// `new()` constructor (e.g. [`FreedesktopLoader::new`] or [`MaterialLoader::new`]).
///
/// # Examples
///
/// ```
/// use native_theme::icons::IconId;
/// use native_theme::theme::IconRole;
///
/// // All of these work via Into<IconId>:
/// let _: IconId = IconRole::ActionSave.into();
/// let _: IconId = "edit-copy".into();
/// ```
#[derive(Debug)]
#[non_exhaustive]
pub enum IconId<'a> {
    /// Load by semantic role (most common).
    Role(IconRole),
    /// Load by platform-specific name string.
    Name(&'a str),
    /// Load via a custom [`IconProvider`] implementation.
    Custom(&'a dyn IconProvider),
}

impl From<IconRole> for IconId<'_> {
    fn from(role: IconRole) -> Self {
        IconId::Role(role)
    }
}

impl<'a> From<&'a str> for IconId<'a> {
    fn from(name: &'a str) -> Self {
        IconId::Name(name)
    }
}

impl<'a> From<&'a dyn IconProvider> for IconId<'a> {
    fn from(provider: &'a dyn IconProvider) -> Self {
        IconId::Custom(provider)
    }
}

/// A provider by reference, such as a variant of the icon enum
/// `native-theme-build` generates: `MaterialLoader::new(&AppIcon::PlayPause)`.
impl<'a, T: IconProvider> From<&'a T> for IconId<'a> {
    fn from(provider: &'a T) -> Self {
        IconId::Custom(provider)
    }
}

// =============================================================================
// Typed per-set icon loaders
// =============================================================================
//
// Each set has its own loader struct exposing only the methods meaningful
// for that set. This eliminates the silent-ignore bug class where a method
// like `.theme()` could be called on a non-freedesktop loader and have no
// effect. Calling a set-specific method on the wrong loader is now a
// compile error.
//
// For runtime-set dispatch (common in connector code), use the free
// functions `load_icon(id, set)` and `load_icon_indicator(set)` at the
// bottom of this section.

/// Loader for freedesktop.org icon themes (GTK / Linux).
///
/// Honors `.theme()` for BOTH role-based and name-based lookups โ€” unlike
/// the previous single-struct design, no dispatch layer can silently
/// drop the theme override.
///
/// An icon comes only from the theme or from a theme in the `Inherits=`
/// chain its `index.theme` declares, searched depth-first in declared
/// order as the Icon Theme Specification's lookup does, never from
/// `hicolor` unless `hicolor` is the theme asked for, nor from a loose
/// file in an icon directory or `/usr/share/pixmaps`. An icon the theme
/// and its parents lack is `None`, and so is every icon of a theme that
/// is not installed.
///
/// The installed themes are read once, at the process's first freedesktop
/// lookup (freedesktop-icons caches them the same way), and a theme's
/// `Inherits=` chain at its own first lookup, so a theme installed after
/// that is not searched, and a changed `Inherits=` is not seen, until the
/// process restarts.
///
/// ```
/// # #[cfg(all(target_os = "linux", feature = "system-icons"))]
/// # {
/// use native_theme::icons::FreedesktopLoader;
/// use native_theme::theme::IconRole;
///
/// // By role, system theme:
/// let _icon = FreedesktopLoader::new(IconRole::ActionCopy).load();
///
/// // By name, explicit theme + size + symbolic fg color:
/// let _icon = FreedesktopLoader::new("edit-copy")
///     .theme("Adwaita")
///     .size(48)
///     .color([0, 0, 0])
///     .load();
/// # }
/// ```
#[derive(Debug)]
#[must_use]
pub struct FreedesktopLoader<'a> {
    // Fields read only in the Linux + system-icons cfg branch of `load`.
    #[allow(dead_code)]
    id: IconId<'a>,
    #[allow(dead_code)]
    size: u16,
    #[allow(dead_code)]
    fg_color: Option<[u8; 3]>,
    #[allow(dead_code)]
    theme: Option<&'a str>,
}

impl<'a> FreedesktopLoader<'a> {
    /// Create a freedesktop loader. Defaults: size 24, no fg_color, system theme.
    pub fn new(id: impl Into<IconId<'a>>) -> Self {
        Self {
            id: id.into(),
            size: 24,
            fg_color: None,
            theme: None,
        }
    }

    /// Set the requested icon size in pixels (default 24).
    pub fn size(mut self, size: u16) -> Self {
        self.size = size;
        self
    }

    /// Set the foreground color for GTK symbolic icon colorization.
    pub fn color(mut self, rgb: [u8; 3]) -> Self {
        self.fg_color = Some(rgb);
        self
    }

    /// Set the foreground color if `Some`, leave default if `None`.
    pub fn color_opt(mut self, rgb: Option<[u8; 3]>) -> Self {
        self.fg_color = rgb;
        self
    }

    /// Override the freedesktop icon theme (e.g. "Adwaita", "breeze").
    /// When unset, uses the system-detected theme, and searches no theme
    /// where detection fails (see [`Self::load`]).
    pub fn theme(mut self, theme: &'a str) -> Self {
        self.theme = Some(theme);
        self
    }

    /// Load the icon, returning its data.
    ///
    /// `None` when neither the theme nor a theme it inherits from has the
    /// icon (see [`FreedesktopLoader`]).
    ///
    /// With no [`theme`](Self::theme) set, the icon comes from the system's
    /// icon theme, and where that cannot be detected no theme is searched,
    /// as none stands in for the undetected one: a role or a name gives
    /// `None`, and a custom [`IconProvider`] gives only its own freedesktop
    /// SVG ([`IconProvider::icon_svg`]), which depends on no theme, where it
    /// has one. [`system_icon_theme()`](crate::theme::system_icon_theme)
    /// gives the reason.
    ///
    /// Requires the `system-icons` feature, and Linux; `None` otherwise.
    #[must_use]
    pub fn load(self) -> Option<IconData> {
        self.load_with(system_icon_theme)
    }

    /// [`Self::load`], with `detect` giving the system's icon theme where no
    /// theme is set.
    #[allow(unused_variables)]
    fn load_with(self, detect: impl FnOnce() -> crate::Result<String>) -> Option<IconData> {
        #[cfg(all(target_os = "linux", feature = "system-icons"))]
        {
            let detected;
            let theme: Option<&str> = match self.theme {
                Some(t) => Some(t),
                None => {
                    detected = detect().ok();
                    detected.as_deref()
                }
            };
            match self.id {
                IconId::Role(role) => {
                    let name = icon_name(role, IconSet::Freedesktop)?;
                    crate::freedesktop::load_freedesktop_icon_by_name(
                        name,
                        theme?,
                        self.size,
                        self.fg_color,
                    )
                }
                IconId::Name(name) => crate::freedesktop::load_freedesktop_icon_by_name(
                    name,
                    theme?,
                    self.size,
                    self.fg_color,
                ),
                IconId::Custom(provider) => {
                    if let Some(theme) = theme
                        && let Some(name) = provider.icon_name(IconSet::Freedesktop)
                        && let Some(data) = crate::freedesktop::load_freedesktop_icon_by_name(
                            name,
                            theme,
                            self.size,
                            self.fg_color,
                        )
                    {
                        return Some(data);
                    }
                    provider.icon_svg(IconSet::Freedesktop).map(IconData::Svg)
                }
            }
        }
        #[cfg(not(all(target_os = "linux", feature = "system-icons")))]
        {
            None
        }
    }

    /// Load the theme's animated process-working spinner.
    ///
    /// `theme` of `None` uses the system-detected theme, and gives `None`
    /// where detection fails โ€” no theme stands in for the undetected one;
    /// `Some(t)` overrides.
    /// Associated function (no `self`) โ€” the spinner is a property of the
    /// theme, not of any particular icon id. Found only where
    /// [`Self::load`] would find an icon: in the theme or a theme it
    /// inherits from, never in `hicolor` unless that is the theme.
    ///
    /// Requires the `system-icons` feature, and Linux; `None` otherwise.
    #[must_use]
    #[allow(unused_variables)]
    pub fn load_indicator(theme: Option<&str>) -> Option<AnimatedIcon> {
        #[cfg(all(target_os = "linux", feature = "system-icons"))]
        {
            crate::freedesktop::load_freedesktop_spinner(theme)
        }
        #[cfg(not(all(target_os = "linux", feature = "system-icons")))]
        {
            None
        }
    }
}

/// Loader for Apple SF Symbols (macOS only).
///
/// SF Symbols has no concept of themes. A symbol is a monochrome template,
/// drawn black unless [`Self::color`] gives it a foreground colour.
#[derive(Debug)]
#[must_use]
pub struct SfSymbolsLoader<'a> {
    #[allow(dead_code)] // read only in the macOS cfg branch of `load`
    id: IconId<'a>,
    #[allow(dead_code)] // read only in the macOS cfg branch of `load`
    fg_color: Option<[u8; 3]>,
}

impl<'a> SfSymbolsLoader<'a> {
    /// Construct a new SF Symbols loader for the given icon id. Defaults:
    /// no fg_color.
    pub fn new(id: impl Into<IconId<'a>>) -> Self {
        Self {
            id: id.into(),
            fg_color: None,
        }
    }

    /// Set the foreground color the monochrome symbol is drawn in; its
    /// alpha is kept.
    pub fn color(mut self, rgb: [u8; 3]) -> Self {
        self.fg_color = Some(rgb);
        self
    }

    /// Set the foreground color if `Some`, leave default if `None`.
    pub fn color_opt(mut self, rgb: Option<[u8; 3]>) -> Self {
        self.fg_color = rgb;
        self
    }

    /// Load the icon, returning its data.
    ///
    /// Requires the `system-icons` feature, and macOS; `None` otherwise.
    #[must_use]
    #[allow(unused_variables)]
    pub fn load(self) -> Option<IconData> {
        #[cfg(all(target_os = "macos", feature = "system-icons"))]
        {
            match self.id {
                IconId::Role(role) => {
                    let name = icon_name(role, IconSet::SfSymbols)?;
                    crate::sficons::load_sf_icon_by_name(name, self.fg_color)
                }
                IconId::Name(n) => crate::sficons::load_sf_icon_by_name(n, self.fg_color),
                IconId::Custom(p) => {
                    if let Some(n) = p.icon_name(IconSet::SfSymbols)
                        && let Some(data) = crate::sficons::load_sf_icon_by_name(n, self.fg_color)
                    {
                        return Some(data);
                    }
                    p.icon_svg(IconSet::SfSymbols).map(IconData::Svg)
                }
            }
        }
        #[cfg(not(all(target_os = "macos", feature = "system-icons")))]
        {
            None
        }
    }
    // No load_indicator: SF Symbols has no animated spinner primitive.
}

/// Loader for Windows Segoe Fluent Icons (Windows only).
///
/// Segoe icons have no themes. A Segoe Fluent glyph is monochrome, drawn
/// white unless [`Self::color`] gives it a foreground colour; a stock shell
/// icon (the `SIID_*` and `IDI_QUESTION` names) is full-colour and keeps its
/// own colours.
#[derive(Debug)]
#[must_use]
pub struct SegoeIconsLoader<'a> {
    #[allow(dead_code)] // read only in the Windows cfg branch of `load`
    id: IconId<'a>,
    #[allow(dead_code)] // read only in the Windows cfg branch of `load`
    fg_color: Option<[u8; 3]>,
}

impl<'a> SegoeIconsLoader<'a> {
    /// Construct a new Segoe Fluent loader for the given icon id. Defaults:
    /// no fg_color.
    pub fn new(id: impl Into<IconId<'a>>) -> Self {
        Self {
            id: id.into(),
            fg_color: None,
        }
    }

    /// Set the foreground color a monochrome glyph is drawn in; its alpha
    /// is kept. A full-colour stock icon is unchanged.
    pub fn color(mut self, rgb: [u8; 3]) -> Self {
        self.fg_color = Some(rgb);
        self
    }

    /// Set the foreground color if `Some`, leave default if `None`.
    pub fn color_opt(mut self, rgb: Option<[u8; 3]>) -> Self {
        self.fg_color = rgb;
        self
    }

    /// Load the icon, returning its data.
    ///
    /// Requires the `system-icons` feature, and Windows; `None` otherwise.
    #[must_use]
    #[allow(unused_variables)]
    pub fn load(self) -> Option<IconData> {
        #[cfg(all(target_os = "windows", feature = "system-icons"))]
        {
            match self.id {
                IconId::Role(role) => {
                    let name = icon_name(role, IconSet::SegoeIcons)?;
                    crate::winicons::load_windows_icon_by_name(name, self.fg_color)
                }
                IconId::Name(n) => crate::winicons::load_windows_icon_by_name(n, self.fg_color),
                IconId::Custom(p) => {
                    if let Some(n) = p.icon_name(IconSet::SegoeIcons)
                        && let Some(data) =
                            crate::winicons::load_windows_icon_by_name(n, self.fg_color)
                    {
                        return Some(data);
                    }
                    p.icon_svg(IconSet::SegoeIcons).map(IconData::Svg)
                }
            }
        }
        #[cfg(not(all(target_os = "windows", feature = "system-icons")))]
        {
            None
        }
    }
    // No load_indicator: Segoe has no animated spinner primitive.
}

/// Loader for Google Material Symbols (bundled SVG).
///
/// Material SVGs are scalable at render time, so no `size` method.
#[derive(Debug)]
#[must_use]
pub struct MaterialLoader<'a> {
    #[allow(dead_code)] // read only in the material-icons feature cfg branch of `load`
    id: IconId<'a>,
}

impl<'a> MaterialLoader<'a> {
    /// Construct a new Material Symbols loader for the given icon id.
    pub fn new(id: impl Into<IconId<'a>>) -> Self {
        Self { id: id.into() }
    }

    /// Load the icon, returning its data.
    ///
    /// Requires the `material-icons` feature; `None` otherwise.
    #[must_use]
    #[allow(unused_variables)]
    pub fn load(self) -> Option<IconData> {
        #[cfg(feature = "material-icons")]
        {
            match self.id {
                IconId::Role(role) => bundled_icon_svg(role, IconSet::Material)
                    .map(|b| IconData::Svg(Cow::Borrowed(b))),
                IconId::Name(n) => bundled_icon_by_name(n, IconSet::Material)
                    .map(|b| IconData::Svg(Cow::Borrowed(b))),
                IconId::Custom(p) => {
                    if let Some(n) = p.icon_name(IconSet::Material)
                        && let Some(b) = bundled_icon_by_name(n, IconSet::Material)
                    {
                        return Some(IconData::Svg(Cow::Borrowed(b)));
                    }
                    p.icon_svg(IconSet::Material).map(IconData::Svg)
                }
            }
        }
        #[cfg(not(feature = "material-icons"))]
        {
            None
        }
    }

    /// Load the Material animated spinner. Associated function; no `self`.
    ///
    /// Requires the `material-icons` feature; `None` otherwise.
    #[must_use]
    pub fn load_indicator() -> Option<AnimatedIcon> {
        #[cfg(feature = "material-icons")]
        {
            Some(crate::spinners::material_spinner())
        }
        #[cfg(not(feature = "material-icons"))]
        {
            None
        }
    }
}

/// Loader for Lucide Icons (bundled SVG).
#[derive(Debug)]
#[must_use]
pub struct LucideLoader<'a> {
    #[allow(dead_code)] // read only in the lucide-icons feature cfg branch of `load`
    id: IconId<'a>,
}

impl<'a> LucideLoader<'a> {
    /// Construct a new Lucide Icons loader for the given icon id.
    pub fn new(id: impl Into<IconId<'a>>) -> Self {
        Self { id: id.into() }
    }

    /// Load the icon, returning its data.
    ///
    /// Requires the `lucide-icons` feature; `None` otherwise.
    #[must_use]
    #[allow(unused_variables)]
    pub fn load(self) -> Option<IconData> {
        #[cfg(feature = "lucide-icons")]
        {
            match self.id {
                IconId::Role(role) => {
                    bundled_icon_svg(role, IconSet::Lucide).map(|b| IconData::Svg(Cow::Borrowed(b)))
                }
                IconId::Name(n) => bundled_icon_by_name(n, IconSet::Lucide)
                    .map(|b| IconData::Svg(Cow::Borrowed(b))),
                IconId::Custom(p) => {
                    if let Some(n) = p.icon_name(IconSet::Lucide)
                        && let Some(b) = bundled_icon_by_name(n, IconSet::Lucide)
                    {
                        return Some(IconData::Svg(Cow::Borrowed(b)));
                    }
                    p.icon_svg(IconSet::Lucide).map(IconData::Svg)
                }
            }
        }
        #[cfg(not(feature = "lucide-icons"))]
        {
            None
        }
    }

    /// Load the Lucide animated spinner. Associated function; no `self`.
    ///
    /// Requires the `lucide-icons` feature; `None` otherwise.
    #[must_use]
    pub fn load_indicator() -> Option<AnimatedIcon> {
        #[cfg(feature = "lucide-icons")]
        {
            Some(crate::spinners::lucide_spinner())
        }
        #[cfg(not(feature = "lucide-icons"))]
        {
            None
        }
    }
}

// =============================================================================
// Runtime-set dispatch helpers
// =============================================================================

/// Load an icon using the given set with default per-set options.
///
/// For set-specific options (freedesktop theme, fg_color), construct the
/// specific loader directly and chain the relevant methods.
///
/// Each set needs its loader's feature (see the loaders); `None` without it.
#[must_use]
pub fn load_icon<'a>(id: impl Into<IconId<'a>>, set: IconSet) -> Option<IconData> {
    let id = id.into();
    match set {
        IconSet::Freedesktop => FreedesktopLoader::new(id).load(),
        IconSet::SfSymbols => SfSymbolsLoader::new(id).load(),
        IconSet::SegoeIcons => SegoeIconsLoader::new(id).load(),
        IconSet::Material => MaterialLoader::new(id).load(),
        IconSet::Lucide => LucideLoader::new(id).load(),
    }
}

/// Load the animated loading indicator for the given set.
///
/// Returns `None` for sets without an animated spinner (SfSymbols, SegoeIcons).
/// For a freedesktop spinner from a specific theme, use
/// [`FreedesktopLoader::load_indicator`] directly.
///
/// Each set needs its loader's feature (see the loaders); `None` without it.
#[must_use]
pub fn load_icon_indicator(set: IconSet) -> Option<AnimatedIcon> {
    match set {
        IconSet::Freedesktop => FreedesktopLoader::load_indicator(None),
        IconSet::Material => MaterialLoader::load_indicator(),
        IconSet::Lucide => LucideLoader::load_indicator(),
        IconSet::SfSymbols | IconSet::SegoeIcons => None,
    }
}

/// Colour a monochrome SVG icon in its bytes.
///
/// A rasteriser given no `color` draws an implicit fill and an unresolved
/// `currentColor` black, and a draw-time tint multiplies, which leaves black
/// black โ€” so a Material or Lucide icon would draw black on a dark scheme.
/// This writes `color` into the bytes instead, with gpui's algorithm:
///
/// 1. `currentColor` becomes the colour's `#rrggbb` (Lucide-style SVGs);
/// 2. explicit black fills โ€” `fill="black"`, `fill="#000000"`, `fill="#000"` โ€”
///    and explicit black strokes โ€” `stroke="black"`, `stroke="#000000"`,
///    `stroke="#000"` โ€” become the hex (third-party SVGs with hardcoded black);
/// 3. where none of those occurs, `fill="#rrggbb"` is injected into a root
///    `<svg>` tag that has no `fill=` attribute (Material-style SVGs), before
///    the `/` of a self-closing tag.
///
/// Bytes that are not UTF-8 come back unchanged (a lossy replacement would
/// corrupt them). The colour's alpha is discarded: an SVG `fill` or `stroke`
/// attribute takes opaque hex. Not handled, as in gpui: CSS inline styles
/// (`style="fill:black"`), `fill="rgb(0,0,0)"`, and explicit black on a child
/// element when the root tag has another fill. For monochrome icon sets; a
/// full-colour SVG should not be passed through it.
#[must_use]
pub fn colorize_monochrome_svg(svg: &[u8], color: crate::color::Rgba) -> Vec<u8> {
    let hex = format!("#{:02x}{:02x}{:02x}", color.r, color.g, color.b);

    let Ok(svg_str) = std::str::from_utf8(svg) else {
        return svg.to_vec();
    };

    // 1. currentColor
    let replaced = if svg_str.contains("currentColor") {
        svg_str.replace("currentColor", &hex)
    } else {
        svg_str.to_owned()
    };

    // 2. explicit black fills and strokes
    let fill_hex = format!("fill=\"{hex}\"");
    let replaced = replaced
        .replace("fill=\"black\"", &fill_hex)
        .replace("fill=\"#000000\"", &fill_hex)
        .replace("fill=\"#000\"", &fill_hex);
    let stroke_hex = format!("stroke=\"{hex}\"");
    let replaced = replaced
        .replace("stroke=\"black\"", &stroke_hex)
        .replace("stroke=\"#000000\"", &stroke_hex)
        .replace("stroke=\"#000\"", &stroke_hex);

    if replaced != svg_str {
        return replaced.into_bytes();
    }

    // 3. No currentColor and no explicit black: inject a fill into a root
    // <svg> tag that has none (implicit black fill).
    if let Some(pos) = svg_str.find("<svg")
        && let Some(tail) = svg_str.get(pos..)
        && let Some(close) = tail.find('>')
    {
        let tag_end = pos.saturating_add(close);
        if let Some(tag) = svg_str.get(pos..tag_end)
            && !tag.contains("fill=")
        {
            // A self-closing tag: inject before the '/' of '<svg .../>'.
            let is_self_closing = tag_end > 0
                && svg_str
                    .as_bytes()
                    .get(tag_end.saturating_sub(1))
                    .is_some_and(|&b| b == b'/');
            let inject_pos = if is_self_closing {
                tag_end.saturating_sub(1)
            } else {
                tag_end
            };
            if let Some(before) = svg_str.get(..inject_pos)
                && let Some(after) = svg_str.get(inject_pos..)
            {
                let mut result = String::with_capacity(svg_str.len().saturating_add(20));
                result.push_str(before);
                result.push_str(&format!(" fill=\"{hex}\""));
                result.push_str(after);
                return result.into_bytes();
            }
        }
    }

    // A non-black fill and no currentColor: unchanged.
    svg.to_vec()
}

/// The icon base directories freedesktop-icons 0.4.0 searches for themes,
/// in its order (`freedesktop-icons-0.4.0/src/theme/paths.rs:13-32`): each
/// `$XDG_DATA_DIRS` entry's `icons`, `$XDG_DATA_HOME/icons`, then
/// `~/.icons`, keeping those that exist. freedesktop-icons also searches
/// the `pixmaps` directory beside each `icons` one; no UI icon may come
/// from there, so it is left out.
///
/// The freedesktop icon lookup, [`is_freedesktop_theme_available`] and
/// [`list_freedesktop_themes`] all read this one list, so a theme listed
/// or available is one the lookup searches. Read once per process, as
/// freedesktop-icons reads its own list once.
#[cfg(target_os = "linux")]
pub(crate) fn icon_base_dirs() -> &'static [std::path::PathBuf] {
    static DIRS: std::sync::OnceLock<Vec<std::path::PathBuf>> = std::sync::OnceLock::new();
    DIRS.get_or_init(xdg_icon_base_dirs)
}

/// Build [`icon_base_dirs`] from the environment the way freedesktop-icons'
/// `xdg` 2.5.2 does (`xdg-2.5.2/src/base_directories.rs:268-309`): a
/// relative or unset `$XDG_DATA_HOME` is `~/.local/share`, relative
/// `$XDG_DATA_DIRS` entries are dropped, and none left is
/// `/usr/local/share:/usr/share`. Without a home directory `xdg` gives no
/// data dirs at all, and there is no `~/.icons` either.
#[cfg(target_os = "linux")]
fn xdg_icon_base_dirs() -> Vec<std::path::PathBuf> {
    use std::path::PathBuf;

    let Some(home) = std::env::home_dir() else {
        return Vec::new();
    };
    let data_dirs: Vec<PathBuf> = std::env::var_os("XDG_DATA_DIRS")
        .map(|dirs| {
            std::env::split_paths(&dirs)
                .filter(|dir| dir.is_absolute())
                .collect::<Vec<_>>()
        })
        .filter(|dirs| !dirs.is_empty())
        .unwrap_or_else(|| {
            vec![
                PathBuf::from("/usr/local/share"),
                PathBuf::from("/usr/share"),
            ]
        });
    let data_home = std::env::var_os("XDG_DATA_HOME")
        .map(PathBuf::from)
        .filter(|dir| dir.is_absolute())
        .unwrap_or_else(|| home.join(".local/share"));
    let mut dirs: Vec<PathBuf> = data_dirs.iter().map(|dir| dir.join("icons")).collect();
    dirs.push(data_home.join("icons"));
    dirs.push(home.join(".icons"));
    dirs.retain(|dir| dir.exists());
    dirs
}

/// Whether `name` can name a theme directory: one plain path component,
/// so joining it to a base dir stays inside that base dir.
#[cfg(target_os = "linux")]
fn is_theme_name(name: &str) -> bool {
    use std::path::{Component, Path};

    let mut components = Path::new(name).components();
    matches!(
        (components.next(), components.next()),
        (Some(Component::Normal(_)), None)
    )
}

/// Whether `theme` is installed: a theme name with an `index.theme` in
/// one of `bases`.
#[cfg(target_os = "linux")]
pub(crate) fn has_theme_index(theme: &str, bases: &[std::path::PathBuf]) -> bool {
    is_theme_name(theme)
        && bases
            .iter()
            .any(|base| base.join(theme).join("index.theme").exists())
}

/// Check whether a freedesktop icon theme is installed on this system.
///
/// Looks for the theme's `index.theme` file in the icon base directories
/// the freedesktop icon lookup searches: `$XDG_DATA_DIRS/icons/<theme>/`,
/// `$XDG_DATA_HOME/icons/<theme>/` and `~/.icons/<theme>/`.
///
/// Always returns `false` on non-Linux platforms.
#[must_use]
pub fn is_freedesktop_theme_available(theme: &str) -> bool {
    #[cfg(target_os = "linux")]
    {
        has_theme_index(theme, icon_base_dirs())
    }
    #[cfg(not(target_os = "linux"))]
    {
        let _ = theme;
        false
    }
}

// =============================================================================
// IconSetChoice: user's icon set selection intent
// =============================================================================

/// The user's icon set selection mode.
///
/// Represents the user's intent for which icons to display.  The key
/// invariant: only [`Default`](Self::Default) is re-derived on theme changes.
/// All other variants represent an explicit user choice that is preserved
/// across theme re-applications.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum IconSetChoice {
    /// Follow the theme preset's recommendation.
    ///
    /// The `String` is the preset's `icon_theme` name (e.g. "Adwaita"),
    /// used for display ("default (Adwaita)") and for loading when the
    /// icon set is `Freedesktop`.
    ///
    /// This is the ONLY variant that gets overwritten on theme change.
    /// It is only constructed via [`default_icon_choice()`], which
    /// guarantees the theme is available (bundled sets are always
    /// available; freedesktop themes are checked via
    /// [`is_freedesktop_theme_available`] before returning this variant).
    Default(String),

    /// Use the OS-configured icon theme.
    ///
    /// Resolved at load time via [`system_icon_set()`](crate::model::icons::system_icon_set).
    /// The display label ("system (breeze-dark)") is computed dynamically
    /// from [`system_icon_theme()`](crate::model::icons::system_icon_theme),
    /// so it tracks runtime OS theme changes. Where detection fails the
    /// label gives the reason, `system (unavailable: <reason>)`, and the
    /// freedesktop loaders search no theme for this choice.
    System,

    /// User explicitly picked a specific installed freedesktop icon theme.
    ///
    /// The `String` is the theme directory name (e.g. "char-white",
    /// "breeze", "Papirus").  Loaded via `IconSet::Freedesktop` with
    /// `.theme(name)`.
    Freedesktop(String),

    /// Google Material Symbols (bundled).
    Material,

    /// Lucide Icons (bundled).
    Lucide,
}

impl fmt::Display for IconSetChoice {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Default(name) => write!(f, "default ({name})"),
            Self::System => f.write_str(&system_choice_label(&system_icon_theme())),
            Self::Freedesktop(name) => write!(f, "{name}"),
            Self::Material => write!(f, "Material (bundled)"),
            Self::Lucide => write!(f, "Lucide (bundled)"),
        }
    }
}

/// [`IconSetChoice::System`]'s label for the `detected` system icon theme:
/// its name, or why there is none.
fn system_choice_label(detected: &crate::Result<String>) -> String {
    match detected {
        Ok(name) => format!("system ({name})"),
        Err(e) => format!("system (unavailable: {e})"),
    }
}

impl IconSetChoice {
    /// The effective [`IconSet`] loading mechanism for this choice.
    ///
    /// For [`Default`](Self::Default), returns the theme's icon set
    /// (caller passes it in).
    /// For [`Freedesktop`](Self::Freedesktop), always returns
    /// [`IconSet::Freedesktop`].
    /// For others, returns the corresponding bundled or system set.
    #[must_use]
    pub fn effective_icon_set(&self, theme_icon_set: IconSet) -> IconSet {
        match self {
            Self::Default(_) => theme_icon_set,
            Self::System => system_icon_set(),
            Self::Freedesktop(_) => IconSet::Freedesktop,
            Self::Material => IconSet::Material,
            Self::Lucide => IconSet::Lucide,
        }
    }

    /// The freedesktop theme name to pass to [`FreedesktopLoader::theme`], if any.
    ///
    /// Returns `Some(name)` for [`Default`](Self::Default) and
    /// [`Freedesktop`](Self::Freedesktop) variants.
    /// Returns `None` for [`System`](Self::System), [`Material`](Self::Material),
    /// [`Lucide`](Self::Lucide).
    ///
    /// The caller is responsible for only passing the result to
    /// [`FreedesktopLoader::theme`] when the effective icon set is
    /// [`IconSet::Freedesktop`].  For bundled sets (Material, Lucide),
    /// the theme name is not used by the loader.
    #[must_use]
    pub fn freedesktop_theme(&self) -> Option<&str> {
        match self {
            Self::Default(name) | Self::Freedesktop(name) => Some(name),
            Self::System | Self::Material | Self::Lucide => None,
        }
    }

    /// Whether this choice should be re-derived when the theme changes.
    ///
    /// Only [`Default`](Self::Default) follows the preset.  All others
    /// are explicit user choices that must be preserved.
    #[must_use]
    pub fn follows_preset(&self) -> bool {
        matches!(self, Self::Default(_))
    }
}

/// Determine the default icon set choice for a theme.
///
/// When the TOML specifies `icon_theme` (`Some`) and the theme is
/// available (bundled sets are always available; freedesktop themes are
/// checked via [`is_freedesktop_theme_available`]), returns
/// [`IconSetChoice::Default(icon_theme)`](IconSetChoice::Default).
///
/// When the TOML does not specify `icon_theme` (`None`), or the
/// specified freedesktop theme is not installed, returns
/// [`IconSetChoice::System`].
#[must_use]
pub fn default_icon_choice(icon_set: IconSet, icon_theme: Option<&str>) -> IconSetChoice {
    let Some(theme) = icon_theme else {
        return IconSetChoice::System;
    };
    // All five IconSet variants listed explicitly -- no wildcard.
    // Adding a new variant produces a compiler error, forcing the author
    // to decide whether the new set's theme is "always available" or
    // needs a runtime check.
    let available = match icon_set {
        IconSet::Material | IconSet::Lucide => true,
        IconSet::Freedesktop => is_freedesktop_theme_available(theme),
        IconSet::SfSymbols | IconSet::SegoeIcons => true,
    };
    if available {
        IconSetChoice::Default(theme.to_string())
    } else {
        IconSetChoice::System
    }
}

/// List installed freedesktop icon themes.
///
/// Scans the icon base directories the freedesktop icon lookup searches
/// (`$XDG_DATA_DIRS/icons/`, `$XDG_DATA_HOME/icons/` and `~/.icons/`) for
/// subdirectories containing an `index.theme` file with a `Directories=`
/// line (per the freedesktop Icon Theme Specification).  This filters
/// out cursor-only themes that lack application icons.
///
/// Excludes `hicolor` (the specification's shared theme for application
/// icons, which native-theme's icon lookup never falls back to) and `default` (typically a
/// symlink).  Returns a sorted, deduplicated list of theme directory
/// names.
///
/// Silently skips entries on IO errors (e.g. permission denied).
/// Returns an empty `Vec` on non-Linux platforms.
///
/// Note: themes installed via Flatpak or Snap may reside outside
/// standard XDG paths and will not be discovered.
#[must_use]
pub fn list_freedesktop_themes() -> Vec<String> {
    #[cfg(target_os = "linux")]
    {
        use std::collections::BTreeSet;
        use std::io::BufRead;

        let mut themes = BTreeSet::new();

        for icon_dir in icon_base_dirs() {
            let entries = match std::fs::read_dir(icon_dir) {
                Ok(e) => e,
                Err(_) => continue,
            };
            for entry in entries.filter_map(|e| e.ok()) {
                let path = entry.path();
                if !path.is_dir() {
                    continue;
                }
                let name = match entry.file_name().into_string() {
                    Ok(n) => n,
                    Err(_) => continue,
                };

                // Exclude hicolor (application icons, never a UI set) and
                // default (symlink).
                if name == "hicolor" || name == "default" {
                    continue;
                }

                let index_path = path.join("index.theme");
                let file = match std::fs::File::open(&index_path) {
                    Ok(f) => f,
                    Err(_) => continue,
                };

                // Check if index.theme contains a Directories= line.
                // Cursor-only themes omit this line.
                let reader = std::io::BufReader::new(file);
                let has_directories = reader
                    .lines()
                    .map_while(Result::ok)
                    .any(|line| line.starts_with("Directories="));

                if has_directories {
                    themes.insert(name);
                }
            }
        }

        themes.into_iter().collect()
    }
    #[cfg(not(target_os = "linux"))]
    {
        Vec::new()
    }
}

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

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

    #[cfg(all(target_os = "linux", feature = "system-icons"))]
    fn undetected() -> crate::Result<String> {
        Err(crate::Error::PlatformUnsupported {
            platform: "the test's failing detection",
        })
    }

    /// With no theme set and no icon theme detected, nothing loads: no
    /// theme stands in for the one that could not be detected.
    #[test]
    #[cfg(all(target_os = "linux", feature = "system-icons"))]
    fn freedesktop_loader_without_a_detected_theme_loads_nothing() {
        let custom: &dyn IconProvider = &IconRole::ActionCopy;
        for id in [
            IconId::Role(IconRole::ActionCopy),
            IconId::Name("edit-copy"),
            IconId::Custom(custom),
        ] {
            assert!(
                FreedesktopLoader::new(id).load_with(undetected).is_none(),
                "an icon loaded though no icon theme was detected"
            );
        }
    }

    /// A custom provider's own freedesktop SVG depends on no theme, so it
    /// still loads where no icon theme was detected; only the lookup of its
    /// freedesktop name in a theme is skipped.
    #[test]
    #[cfg(all(target_os = "linux", feature = "system-icons"))]
    fn freedesktop_loader_without_a_detected_theme_gives_a_providers_own_svg() {
        #[derive(Debug)]
        struct AppIcon;
        impl IconProvider for AppIcon {
            fn icon_name(&self, _set: IconSet) -> Option<&str> {
                Some("edit-copy")
            }
            fn icon_svg(&self, set: IconSet) -> Option<Cow<'static, [u8]>> {
                (set == IconSet::Freedesktop).then_some(Cow::Borrowed(b"<svg>app</svg>"))
            }
        }

        let provider: &dyn IconProvider = &AppIcon;
        assert_eq!(
            FreedesktopLoader::new(provider).load_with(undetected),
            Some(IconData::Svg(Cow::Borrowed(b"<svg>app</svg>"))),
            "the provider's own SVG did not load without a detected icon theme"
        );
    }

    /// A generated icon enum (native-theme-build) is handed to a loader by
    /// reference, as its README shows: `MaterialLoader::new(&AppIcon::X)`.
    #[test]
    #[cfg(feature = "material-icons")]
    fn a_provider_is_passed_to_a_loader_by_reference() {
        #[derive(Debug)]
        struct AppIcon;
        impl IconProvider for AppIcon {
            fn icon_name(&self, _set: IconSet) -> Option<&str> {
                None
            }
            fn icon_svg(&self, set: IconSet) -> Option<Cow<'static, [u8]>> {
                (set == IconSet::Material).then_some(Cow::Borrowed(b"<svg>app</svg>"))
            }
        }

        assert_eq!(
            MaterialLoader::new(&AppIcon).load(),
            Some(IconData::Svg(Cow::Borrowed(b"<svg>app</svg>"))),
            "a provider passed by reference did not load its own SVG"
        );
    }

    /// An explicit theme needs no detection: the detector never runs.
    #[test]
    #[cfg(all(target_os = "linux", feature = "system-icons"))]
    fn freedesktop_loader_with_a_theme_does_not_detect() {
        let runs = std::cell::Cell::new(0);
        let _ = FreedesktopLoader::new("edit-copy")
            .theme("Adwaita")
            .load_with(|| {
                runs.set(runs.get() + 1);
                undetected()
            });
        assert_eq!(runs.get(), 0, "an explicit theme ran the detection");
    }

    #[test]
    #[cfg(all(target_os = "linux", feature = "system-icons"))]
    fn freedesktop_loader_theme_override_honored_for_name_lookup() {
        // Regression pin for Phase 93-03 silent-ignore bug (Plan 93-09 fix).
        // The old IconLoader dispatched IconId::Name to a path that silently
        // dropped `.theme()`. FreedesktopLoader has a single `load()` method
        // that honors `.theme()` uniformly across Role/Name/Custom.
        //
        // Requires the Adwaita icon theme installed on the test host.
        let result = FreedesktopLoader::new("format-text-rich")
            .theme("Adwaita")
            .size(24)
            .load();
        assert!(
            result.is_some(),
            "theme('Adwaita') must resolve 'format-text-rich' in Adwaita, regardless of system theme"
        );
    }

    #[test]
    #[cfg(feature = "material-icons")]
    fn load_icon_material_returns_svg() {
        let result = MaterialLoader::new(IconRole::ActionCopy).load();
        assert!(result.is_some(), "material ActionCopy should return Some");
        match result.unwrap() {
            IconData::Svg(ref cow) => {
                let s = String::from_utf8_lossy(cow);
                assert!(s.contains("<svg"), "should contain SVG data");
            }
            _ => panic!("expected IconData::Svg for bundled material icon"),
        }
    }

    #[test]
    #[cfg(feature = "lucide-icons")]
    fn load_icon_lucide_returns_svg() {
        let result = LucideLoader::new(IconRole::ActionCopy).load();
        assert!(result.is_some(), "lucide ActionCopy should return Some");
        match result.unwrap() {
            IconData::Svg(ref cow) => {
                let s = String::from_utf8_lossy(cow);
                assert!(s.contains("<svg"), "should contain SVG data");
            }
            _ => panic!("expected IconData::Svg for bundled lucide icon"),
        }
    }

    #[test]
    #[cfg(feature = "material-icons")]
    fn load_icon_unknown_theme_no_cross_set_fallback() {
        // On Linux (test platform), unknown theme resolves to system_icon_set() = Freedesktop.
        // Without system-icons feature, Freedesktop falls through to wildcard -> None.
        // No cross-set Material fallback.
        let result = FreedesktopLoader::new(IconRole::ActionCopy).load();
        // Without system-icons, this falls to wildcard which returns None
        // With system-icons, this dispatches to load_freedesktop_icon which may return Some
        // Either way, no panic
        let _ = result;
    }

    #[test]
    #[cfg(feature = "material-icons")]
    fn load_icon_all_roles_material() {
        // Material has 42 of 42 roles mapped, all return Some
        let mut some_count = 0;
        for role in IconRole::ALL {
            if MaterialLoader::new(role).load().is_some() {
                some_count += 1;
            }
        }
        // bundled_icon_svg covers all 42 roles for Material
        assert_eq!(
            some_count, 42,
            "Material should cover all 42 roles via bundled SVGs"
        );
    }

    #[test]
    #[cfg(feature = "lucide-icons")]
    fn load_icon_all_roles_lucide() {
        let mut some_count = 0;
        for role in IconRole::ALL {
            if LucideLoader::new(role).load().is_some() {
                some_count += 1;
            }
        }
        // bundled_icon_svg covers all 42 roles for Lucide
        assert_eq!(
            some_count, 42,
            "Lucide should cover all 42 roles via bundled SVGs"
        );
    }

    #[test]
    fn sf_symbols_loader_stores_the_colour() {
        let loader = SfSymbolsLoader::new(IconRole::ActionCopy).color([10, 20, 30]);
        assert_eq!(loader.fg_color, Some([10, 20, 30]));
        let loader = loader.color_opt(None);
        assert_eq!(loader.fg_color, None);
        let loader = loader.color_opt(Some([40, 50, 60]));
        assert_eq!(loader.fg_color, Some([40, 50, 60]));
        assert_eq!(SfSymbolsLoader::new(IconRole::ActionCopy).fg_color, None);
    }

    #[test]
    fn segoe_icons_loader_stores_the_colour() {
        let loader = SegoeIconsLoader::new(IconRole::ActionCopy).color([10, 20, 30]);
        assert_eq!(loader.fg_color, Some([10, 20, 30]));
        let loader = loader.color_opt(None);
        assert_eq!(loader.fg_color, None);
        let loader = loader.color_opt(Some([40, 50, 60]));
        assert_eq!(loader.fg_color, Some([40, 50, 60]));
        assert_eq!(SegoeIconsLoader::new(IconRole::ActionCopy).fg_color, None);
    }

    #[test]
    fn load_icon_unrecognized_set_no_features() {
        // SfSymbols on Linux without system-icons: falls through to wildcard -> None
        let _result = SfSymbolsLoader::new(IconRole::ActionCopy).load();
        // Just verifying it doesn't panic
    }

    #[test]
    #[cfg(feature = "material-icons")]
    fn bundled_icon_load_produces_cow_borrowed() {
        let result = MaterialLoader::new(IconRole::ActionCopy).load();
        assert!(
            matches!(result, Some(IconData::Svg(Cow::Borrowed(_)))),
            "bundled icon should produce Some(IconData::Svg(Cow::Borrowed(_)))"
        );
    }
}

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

    #[test]
    #[cfg(feature = "material-icons")]
    fn system_icon_by_name_material() {
        let result = MaterialLoader::new("content_copy").load();
        assert!(
            result.is_some(),
            "content_copy should be found in Material set"
        );
        assert!(matches!(result.unwrap(), IconData::Svg(_)));
    }

    #[test]
    #[cfg(feature = "lucide-icons")]
    fn system_icon_by_name_lucide() {
        let result = LucideLoader::new("copy").load();
        assert!(result.is_some(), "copy should be found in Lucide set");
        assert!(matches!(result.unwrap(), IconData::Svg(_)));
    }

    #[test]
    #[cfg(feature = "material-icons")]
    fn system_icon_by_name_unknown_returns_none() {
        let result = MaterialLoader::new("nonexistent_xyz").load();
        assert!(result.is_none(), "nonexistent name should return None");
    }

    #[test]
    fn system_icon_by_name_sf_on_linux_returns_none() {
        // On Linux, SfSymbols set is not available (cfg-gated to macOS)
        #[cfg(not(target_os = "macos"))]
        {
            let result = SfSymbolsLoader::new("doc.on.doc").load();
            assert!(
                result.is_none(),
                "SF Symbols should return None on non-macOS"
            );
        }
    }
}

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

    #[test]
    #[cfg(feature = "material-icons")]
    fn custom_icon_with_icon_role_material() {
        let provider: &dyn IconProvider = &IconRole::ActionCopy;
        let result = MaterialLoader::new(provider).load();
        assert!(
            result.is_some(),
            "IconRole::ActionCopy should load via material"
        );
    }

    #[test]
    #[cfg(feature = "lucide-icons")]
    fn custom_icon_with_icon_role_lucide() {
        let provider: &dyn IconProvider = &IconRole::ActionCopy;
        let result = LucideLoader::new(provider).load();
        assert!(
            result.is_some(),
            "IconRole::ActionCopy should load via lucide"
        );
    }

    #[test]
    fn custom_icon_no_cross_set_fallback() {
        // Provider that returns None for all sets -- should NOT fall back
        #[derive(Debug)]
        struct NullProvider;
        impl IconProvider for NullProvider {
            fn icon_name(&self, _set: IconSet) -> Option<&str> {
                None
            }
            fn icon_svg(&self, _set: IconSet) -> Option<Cow<'static, [u8]>> {
                None
            }
        }

        let provider: &dyn IconProvider = &NullProvider;
        let result = MaterialLoader::new(provider).load();
        assert!(
            result.is_none(),
            "NullProvider should return None (no cross-set fallback)"
        );
    }

    #[test]
    fn custom_icon_unknown_set_uses_system() {
        // "unknown-set" is not a known IconSet name, falls through to system_icon_set()
        #[derive(Debug)]
        struct NullProvider;
        impl IconProvider for NullProvider {
            fn icon_name(&self, _set: IconSet) -> Option<&str> {
                None
            }
            fn icon_svg(&self, _set: IconSet) -> Option<Cow<'static, [u8]>> {
                None
            }
        }

        // Just verify it doesn't panic -- the actual set chosen depends on platform
        let provider: &dyn IconProvider = &NullProvider;
        let _result = FreedesktopLoader::new(provider).load();
    }

    #[test]
    #[cfg(feature = "material-icons")]
    fn custom_icon_via_dyn_dispatch() {
        let boxed: Box<dyn IconProvider> = Box::new(IconRole::ActionCopy);
        let provider: &dyn IconProvider = &*boxed;
        let result = MaterialLoader::new(provider).load();
        assert!(
            result.is_some(),
            "dyn dispatch through Box<dyn IconProvider> should work"
        );
    }

    #[test]
    #[cfg(feature = "material-icons")]
    fn custom_icon_bundled_svg_fallback() {
        // Provider that returns None from icon_name but Some from icon_svg
        #[derive(Debug)]
        struct SvgOnlyProvider;
        impl IconProvider for SvgOnlyProvider {
            fn icon_name(&self, _set: IconSet) -> Option<&str> {
                None
            }
            fn icon_svg(&self, _set: IconSet) -> Option<Cow<'static, [u8]>> {
                Some(Cow::Borrowed(b"<svg>test</svg>"))
            }
        }

        let provider: &dyn IconProvider = &SvgOnlyProvider;
        let result = MaterialLoader::new(provider).load();
        assert!(
            result.is_some(),
            "provider with icon_svg should return Some"
        );
        match result.unwrap() {
            IconData::Svg(ref cow) => {
                assert_eq!(cow.as_ref(), b"<svg>test</svg>");
            }
            _ => panic!("expected IconData::Svg"),
        }
    }
}

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

    // === Dispatch tests (through per-set loader API) ===

    #[test]
    #[cfg(feature = "lucide-icons")]
    fn loading_indicator_lucide_returns_frames() {
        let anim = LucideLoader::load_indicator();
        assert!(anim.is_some(), "lucide should return Some");
        let anim = anim.unwrap();
        assert!(
            matches!(anim, AnimatedIcon::Frames(_)),
            "lucide should be pre-rotated Frames"
        );
        if let AnimatedIcon::Frames(data) = &anim {
            assert_eq!(data.frames().len(), 24);
            assert_eq!(data.frame_duration_ms().get(), 42);
        }
    }

    /// Freedesktop loading_indicator returns Some if the active icon theme
    /// has a `process-working` sprite sheet (e.g. Breeze), None otherwise.
    #[test]
    #[cfg(all(target_os = "linux", feature = "system-icons"))]
    fn loading_indicator_freedesktop_depends_on_theme() {
        let anim = FreedesktopLoader::load_indicator(None);
        // Result depends on installed icon theme -- Some if process-working exists
        if let Some(anim) = anim {
            match anim {
                AnimatedIcon::Frames(data) => {
                    assert!(
                        !data.frames().is_empty(),
                        "Frames variant should have at least one frame"
                    );
                }
                AnimatedIcon::Transform(_) => {
                    // Single-frame theme icon with Spin -- valid result
                }
            }
        }
    }

    /// Freedesktop spinner depends on platform and icon theme.
    #[test]
    fn loading_indicator_freedesktop_does_not_panic() {
        let _result = FreedesktopLoader::load_indicator(None);
    }

    // === Direct spinner construction tests (any platform) ===

    #[test]
    #[cfg(feature = "lucide-icons")]
    fn lucide_spinner_is_frames() {
        let anim = crate::spinners::lucide_spinner();
        assert!(
            matches!(anim, AnimatedIcon::Frames(_)),
            "lucide should be pre-rotated Frames"
        );
    }
}

// === New builder API tests ===

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

    #[test]
    #[cfg(feature = "material-icons")]
    fn icon_loader_basic_role() {
        let icon = MaterialLoader::new(IconRole::ActionCopy).load();
        assert!(icon.is_some());
    }

    #[test]
    #[cfg(feature = "material-icons")]
    fn icon_loader_by_name() {
        let icon = MaterialLoader::new("content_copy").load();
        assert!(icon.is_some());
    }

    #[test]
    #[cfg(feature = "material-icons")]
    fn icon_loader_custom_provider() {
        let provider: &dyn IconProvider = &IconRole::ActionCopy;
        let icon = MaterialLoader::new(provider).load();
        assert!(icon.is_some());
    }

    #[test]
    #[cfg(all(target_os = "linux", feature = "system-icons"))]
    fn freedesktop_loader_builder_chain_compiles() {
        // Smoke test: the builder chain constructs without runtime errors.
        // Size propagates through; the actual load result depends on the
        // system theme having 'document-save' at size 48.
        let _ = FreedesktopLoader::new(IconRole::ActionSave)
            .size(48)
            .color([0, 0, 0])
            .theme("Adwaita")
            .load();
    }

    #[test]
    #[cfg(feature = "material-icons")]
    fn icon_loader_load_indicator() {
        let anim = MaterialLoader::load_indicator();
        assert!(anim.is_some());
    }

    #[test]
    fn load_icon_free_fn_dispatches() {
        // load_icon() free function routes to the right per-set loader.
        // SfSymbols on Linux is cfg-gated to macOS => None, no panic.
        let _ = load_icon(IconRole::ActionCopy, IconSet::SfSymbols);
    }

    #[test]
    fn load_icon_indicator_free_fn_dispatches() {
        // SfSymbols and SegoeIcons have no spinner primitive.
        assert!(load_icon_indicator(IconSet::SfSymbols).is_none());
        assert!(load_icon_indicator(IconSet::SegoeIcons).is_none());
    }
}

#[cfg(all(test, feature = "svg-rasterize"))]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod spinner_rasterize_tests {
    use super::*;

    #[test]
    #[cfg(feature = "lucide-icons")]
    fn lucide_spinner_icon_rasterizes() {
        let anim = crate::spinners::lucide_spinner();
        if let AnimatedIcon::Frames(data) = &anim {
            let first = data.frames().first();
            if let IconData::Svg(cow) = first {
                let result = crate::rasterize::rasterize_svg(cow, 24);
                assert!(result.is_ok(), "lucide loader should rasterize");
                if let Ok(IconData::Rgba { data, .. }) = &result {
                    assert!(
                        data.iter().any(|&b| b != 0),
                        "lucide loader rasterized to empty image"
                    );
                }
            } else {
                panic!("lucide spinner frame should be Svg");
            }
        } else {
            panic!("lucide spinner should be Frames");
        }
    }
}

// =============================================================================
// IconSetChoice tests
// =============================================================================

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

    #[test]
    fn system_choice_names_the_detected_theme() {
        assert_eq!(
            system_choice_label(&Ok("breeze-dark".to_string())),
            "system (breeze-dark)"
        );
    }

    #[test]
    fn system_choice_shows_a_failed_detection_as_unavailable() {
        let label = system_choice_label(&Err(crate::Error::PlatformUnsupported {
            platform: "the test's failing detection",
        }));
        assert_eq!(
            label,
            "system (unavailable: platform not supported: the test's failing detection)"
        );
    }

    #[test]
    fn test_icon_set_choice_display_default() {
        let choice = IconSetChoice::Default("Adwaita".to_string());
        assert_eq!(choice.to_string(), "default (Adwaita)");
    }

    #[test]
    fn test_icon_set_choice_display_material() {
        assert_eq!(IconSetChoice::Material.to_string(), "Material (bundled)");
    }

    #[test]
    fn test_icon_set_choice_display_lucide() {
        assert_eq!(IconSetChoice::Lucide.to_string(), "Lucide (bundled)");
    }

    #[test]
    fn test_icon_set_choice_display_freedesktop() {
        let choice = IconSetChoice::Freedesktop("breeze".to_string());
        assert_eq!(choice.to_string(), "breeze");
    }

    #[test]
    fn test_icon_set_choice_follows_preset() {
        assert!(IconSetChoice::Default("Adwaita".to_string()).follows_preset());
        assert!(!IconSetChoice::System.follows_preset());
        assert!(!IconSetChoice::Freedesktop("breeze".to_string()).follows_preset());
        assert!(!IconSetChoice::Material.follows_preset());
        assert!(!IconSetChoice::Lucide.follows_preset());
    }

    #[test]
    fn test_icon_set_choice_effective_icon_set() {
        // Default returns whatever the theme specifies
        let choice = IconSetChoice::Default("Adwaita".to_string());
        assert_eq!(
            choice.effective_icon_set(IconSet::Freedesktop),
            IconSet::Freedesktop
        );
        assert_eq!(
            choice.effective_icon_set(IconSet::Material),
            IconSet::Material
        );

        // System returns the platform's icon set
        let sys = IconSetChoice::System.effective_icon_set(IconSet::Material);
        assert_eq!(sys, system_icon_set());

        // Freedesktop always returns Freedesktop
        let choice = IconSetChoice::Freedesktop("breeze".to_string());
        assert_eq!(
            choice.effective_icon_set(IconSet::Material),
            IconSet::Freedesktop
        );

        // Bundled sets return themselves
        assert_eq!(
            IconSetChoice::Material.effective_icon_set(IconSet::Freedesktop),
            IconSet::Material
        );
        assert_eq!(
            IconSetChoice::Lucide.effective_icon_set(IconSet::Freedesktop),
            IconSet::Lucide
        );
    }

    #[test]
    fn test_icon_set_choice_freedesktop_theme() {
        assert_eq!(
            IconSetChoice::Default("Adwaita".to_string()).freedesktop_theme(),
            Some("Adwaita")
        );
        assert_eq!(
            IconSetChoice::Freedesktop("breeze".to_string()).freedesktop_theme(),
            Some("breeze")
        );
        assert_eq!(IconSetChoice::System.freedesktop_theme(), None);
        assert_eq!(IconSetChoice::Material.freedesktop_theme(), None);
        assert_eq!(IconSetChoice::Lucide.freedesktop_theme(), None);
    }

    #[test]
    fn test_default_icon_choice_none() {
        // When icon_theme is None, always returns System regardless of icon_set
        assert_eq!(
            default_icon_choice(IconSet::Freedesktop, None),
            IconSetChoice::System
        );
        assert_eq!(
            default_icon_choice(IconSet::Material, None),
            IconSetChoice::System
        );
    }

    #[test]
    fn test_default_icon_choice_bundled() {
        // Material and Lucide are always available
        assert_eq!(
            default_icon_choice(IconSet::Material, Some("any-theme")),
            IconSetChoice::Default("any-theme".to_string())
        );
        assert_eq!(
            default_icon_choice(IconSet::Lucide, Some("any-theme")),
            IconSetChoice::Default("any-theme".to_string())
        );
    }

    #[test]
    fn test_list_freedesktop_themes_no_panic() {
        // Just verify it doesn't panic -- result varies by platform
        let themes = list_freedesktop_themes();
        // On Linux, should return a non-empty list on most desktop systems.
        // On other platforms, returns empty vec.
        #[cfg(not(target_os = "linux"))]
        assert!(themes.is_empty());
        // Suppress unused variable warning
        let _ = themes;
    }
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::indexing_slicing,
    reason = "a test fails by panicking"
)]
mod colorize_tests {
    use super::colorize_monochrome_svg;
    use crate::color::Rgba;

    const BLUE: Rgba = Rgba::new(51, 102, 204, 255);
    const RED: Rgba = Rgba::new(255, 0, 0, 255);
    const GREEN: Rgba = Rgba::new(20, 184, 82, 255);

    #[test]
    fn colorize_svg_replaces_fill_black() {
        let svg = b"<svg><path fill=\"black\" d=\"M0 0h24v24H0z\"/></svg>";
        let result_str = String::from_utf8(colorize_monochrome_svg(svg, BLUE)).unwrap();
        assert!(
            !result_str.contains("fill=\"black\""),
            "fill=\"black\" should be replaced, got: {result_str}"
        );
        assert!(
            result_str.contains("fill=\"#3366cc\""),
            "should contain the hex fill, got: {result_str}"
        );
    }

    #[test]
    fn colorize_svg_replaces_fill_hex_black() {
        let svg = b"<svg><rect fill=\"#000000\" width=\"24\" height=\"24\"/></svg>";
        let result_str = String::from_utf8(colorize_monochrome_svg(svg, RED)).unwrap();
        assert!(
            !result_str.contains("#000000"),
            "fill=\"#000000\" should be replaced, got: {result_str}"
        );
    }

    #[test]
    fn colorize_svg_replaces_fill_short_hex_black() {
        let svg = b"<svg><rect fill=\"#000\" width=\"24\" height=\"24\"/></svg>";
        let result_str = String::from_utf8(colorize_monochrome_svg(svg, GREEN)).unwrap();
        assert!(
            !result_str.contains("fill=\"#000\""),
            "fill=\"#000\" should be replaced, got: {result_str}"
        );
    }

    #[test]
    fn colorize_svg_current_color_still_works() {
        let svg = b"<svg><path stroke=\"currentColor\" d=\"M0 0\"/></svg>";
        let result_str = String::from_utf8(colorize_monochrome_svg(svg, RED)).unwrap();
        assert!(
            !result_str.contains("currentColor"),
            "currentColor should be replaced"
        );
        assert!(
            result_str.contains("#ff0000"),
            "should contain the hex colour"
        );
    }

    #[test]
    fn colorize_svg_implicit_black_still_works() {
        // SVG with no fill attribute at all (Material-style)
        let svg = b"<svg xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M0 0\"/></svg>";
        let result_str = String::from_utf8(colorize_monochrome_svg(svg, RED)).unwrap();
        assert!(
            result_str.contains("fill=\"#ff0000\""),
            "should inject fill into root svg tag, got: {result_str}"
        );
    }

    #[test]
    fn colorize_svg_non_utf8_returns_original() {
        // Non-UTF-8 bytes: valid SVG prefix followed by an invalid byte sequence
        let mut svg = b"<svg><path fill=\"black\" d=\"M0 0\"/>".to_vec();
        svg.push(0xFF); // invalid UTF-8 byte
        svg.extend_from_slice(b"</svg>");
        let result = colorize_monochrome_svg(&svg, RED);
        assert_eq!(result, svg, "non-UTF-8 input should be returned unchanged");
    }

    #[test]
    fn colorize_svg_replaces_stroke_black() {
        let svg = b"<svg><path stroke=\"black\" d=\"M0 0h24\"/></svg>";
        let result_str = String::from_utf8(colorize_monochrome_svg(svg, BLUE)).unwrap();
        assert!(
            !result_str.contains("stroke=\"black\""),
            "stroke=\"black\" should be replaced, got: {result_str}"
        );
        assert!(
            result_str.contains("stroke=\"#3366cc\""),
            "should contain the hex stroke, got: {result_str}"
        );
    }

    #[test]
    fn colorize_svg_replaces_stroke_hex_black() {
        let svg = b"<svg><line stroke=\"#000000\" x1=\"0\" y1=\"0\" x2=\"24\" y2=\"24\"/></svg>";
        let result_str = String::from_utf8(colorize_monochrome_svg(svg, RED)).unwrap();
        assert!(
            !result_str.contains("#000000"),
            "stroke=\"#000000\" should be replaced"
        );
    }

    #[test]
    fn colorize_self_closing_svg_produces_valid_xml() {
        // Self-closing <svg .../> tag: the fill must be injected before '/'
        let svg = b"<svg xmlns=\"http://www.w3.org/2000/svg\" />";
        let result_str = String::from_utf8(colorize_monochrome_svg(svg, RED)).unwrap();
        assert!(
            result_str.contains("fill=\"#ff0000\""),
            "should inject fill, got: {result_str}"
        );
        assert!(
            !result_str.contains("/ fill="),
            "fill must be before '/', got: {result_str}"
        );
        assert!(
            result_str.trim().ends_with("/>"),
            "should remain self-closing, got: {result_str}"
        );
    }

    #[test]
    fn colorize_svg_with_fill_white_root() {
        // A root fill that is not black is kept, not replaced
        let svg = b"<svg fill=\"white\"><path/></svg>";
        let result_str = String::from_utf8(colorize_monochrome_svg(svg, RED)).unwrap();
        assert!(
            result_str.contains("fill=\"white\""),
            "fill=\"white\" should be preserved, got: {result_str}"
        );
    }

    #[test]
    fn colorize_svg_with_fill_none_root() {
        // stroke="black" is replaced even when the root has fill="none"
        let svg = b"<svg fill=\"none\"><path stroke=\"black\"/></svg>";
        let result_str = String::from_utf8(colorize_monochrome_svg(svg, RED)).unwrap();
        assert!(
            !result_str.contains("stroke=\"black\""),
            "stroke=\"black\" should be replaced, got: {result_str}"
        );
        assert!(
            result_str.contains("stroke=\"#ff0000\""),
            "should contain the hex stroke, got: {result_str}"
        );
    }

    /// The colour's alpha is discarded: an SVG `fill` takes opaque hex (spec ยง9.2).
    #[test]
    fn colorize_svg_discards_alpha() {
        let svg = b"<svg><path fill=\"black\"/></svg>";
        let translucent = Rgba::new(255, 0, 0, 40);
        assert_eq!(
            colorize_monochrome_svg(svg, translucent),
            colorize_monochrome_svg(svg, RED)
        );
    }
}