Skip to main content

native_theme/
icons.rs

1// Icon loading and dispatch; the module docs are on its declaration in lib.rs.
2
3use std::fmt;
4
5use std::borrow::Cow;
6
7use crate::color::Rgba;
8#[allow(unused_imports)]
9use crate::detect::{system_icon_set, system_icon_theme};
10use crate::model::IconSet;
11pub use crate::model::{
12    AnimatedIcon, EmptyFrameListError, FrameList, FramesData, IconData, IconProvider, IconRole,
13    RgbaData, TransformAnimation, TransformData, icon_name,
14};
15#[allow(unused_imports)]
16use crate::model::{bundled_icon_by_name, bundled_icon_svg};
17
18/// The largest buffer, in bytes, built while decoding an icon from outside
19/// data: a PNG's output buffer, a sprite sheet's frames (`frame_count ×
20/// svg_len`) and a raster the OS draws (an SF Symbol's or a stock shell
21/// icon's bitmap). A raster drawn at a requested size (`size² × 4`: an SVG,
22/// a Segoe glyph) is checked against it too, but only as a backstop: the
23/// size is clamped to [`MAX_ICON_SIZE`] first, and 512² × 4 bytes is 1 MiB,
24/// so that check cannot fail.
25///
26/// 64 MiB, the png crate's own default memory limit (`Limits::default()`,
27/// png-0.18.1 `src/decoder/mod.rs:81-87`): a 4096 × 4096 RGBA image, beyond
28/// any icon directory's size.
29#[cfg_attr(
30    not(any(
31        all(target_os = "linux", feature = "system-icons"),
32        feature = "svg-rasterize"
33    )),
34    allow(dead_code)
35)]
36pub(crate) const MAX_ICON_DECODE_BYTES: usize = 64 * 1024 * 1024;
37
38/// The largest size, in pixels (points for an SF Symbol), that the system
39/// loaders ([`FreedesktopLoader::size`], [`SfSymbolsLoader::size`],
40/// [`SegoeFluentLoader::size`]), and through them [`load_custom_icon`] and
41/// [`load_custom_icon_in`], and `rasterize::rasterize_svg` (feature
42/// `svg-rasterize`) load or draw an icon at: a larger size is taken as this
43/// one, and 0 as 1.
44///
45/// 512, so the largest raster one call builds is 512² × 4 bytes, 1 MiB, where
46/// a size of 10 000 would allocate 400 MB for one icon. A connector that loads
47/// and rasterizes its icons through these shares the bound.
48pub const MAX_ICON_SIZE: u32 = 512;
49
50/// Whether a `size × size` RGBA raster (`size² × 4` bytes) is inside
51/// [`MAX_ICON_DECODE_BYTES`]; a size of 0 is not.
52#[cfg_attr(
53    not(all(
54        any(target_os = "macos", target_os = "windows"),
55        feature = "system-icons"
56    )),
57    allow(dead_code)
58)]
59pub(crate) fn raster_size_in_bound(size: u32) -> bool {
60    raster_bytes_in_bound(size, size).is_some()
61}
62
63/// The bytes of a `width × height` RGBA raster (`width × height × 4`) where
64/// they are inside [`MAX_ICON_DECODE_BYTES`]; `None` for a side of 0 or a
65/// raster over the bound.
66#[cfg_attr(
67    not(any(
68        all(
69            any(target_os = "macos", target_os = "windows"),
70            feature = "system-icons"
71        ),
72        feature = "svg-rasterize"
73    )),
74    allow(dead_code)
75)]
76pub(crate) fn raster_bytes_in_bound(width: u32, height: u32) -> Option<usize> {
77    if width == 0 || height == 0 {
78        return None;
79    }
80    u64::from(width)
81        .checked_mul(u64::from(height))?
82        .checked_mul(4)
83        .filter(|&bytes| bytes <= MAX_ICON_DECODE_BYTES as u64)
84        .and_then(|bytes| usize::try_from(bytes).ok())
85}
86
87/// The red, green and blue of a loader's foreground colour; the alpha is
88/// dropped, as the loaders draw the glyph's own coverage.
89fn rgb(color: Rgba) -> [u8; 3] {
90    [color.r, color.g, color.b]
91}
92
93/// Identifies what icon to load: a semantic role, a platform-specific name,
94/// or a custom provider.
95///
96/// Constructed via [`From`] impls -- users rarely reference this type directly.
97/// Pass an [`IconRole`], `&str`, or `&dyn IconProvider` to a per-set loader's
98/// `new()` constructor (e.g. [`FreedesktopLoader::new`] or [`MaterialLoader::new`]).
99///
100/// # Examples
101///
102/// ```
103/// use native_theme::icons::IconId;
104/// use native_theme::icons::IconRole;
105///
106/// // All of these work via Into<IconId>:
107/// let _: IconId = IconRole::ActionSave.into();
108/// let _: IconId = "edit-copy".into();
109/// ```
110#[derive(Debug)]
111#[non_exhaustive]
112pub enum IconId<'a> {
113    /// Load by semantic role (most common).
114    Role(IconRole),
115    /// Load by platform-specific name string.
116    Name(&'a str),
117    /// Load via a custom [`IconProvider`] implementation.
118    Custom(&'a dyn IconProvider),
119}
120
121impl From<IconRole> for IconId<'_> {
122    fn from(role: IconRole) -> Self {
123        IconId::Role(role)
124    }
125}
126
127impl<'a> From<&'a str> for IconId<'a> {
128    fn from(name: &'a str) -> Self {
129        IconId::Name(name)
130    }
131}
132
133impl<'a> From<&'a dyn IconProvider> for IconId<'a> {
134    fn from(provider: &'a dyn IconProvider) -> Self {
135        IconId::Custom(provider)
136    }
137}
138
139/// A provider by reference, such as a variant of the icon enum
140/// `native-theme-build` generates: `MaterialLoader::new(&AppIcon::PlayPause)`.
141impl<'a, T: IconProvider> From<&'a T> for IconId<'a> {
142    fn from(provider: &'a T) -> Self {
143        IconId::Custom(provider)
144    }
145}
146
147// =============================================================================
148// Typed per-set icon loaders
149// =============================================================================
150//
151// Each set has its own loader struct exposing only the methods meaningful
152// for that set. This eliminates the silent-ignore bug class where a method
153// like `.theme()` could be called on a non-freedesktop loader and have no
154// effect. Calling a set-specific method on the wrong loader is now a
155// compile error.
156//
157// For runtime-set dispatch (common in connector code), use the free
158// functions `load_icon(id, set)`, `load_custom_icon(provider, set, color, size)`,
159// `load_custom_icon_in(provider, set, icon_theme, color, size)` and
160// `load_icon_indicator(set, theme)` at the bottom of this section.
161
162/// Loader for freedesktop.org icon themes (GTK / Linux).
163///
164/// Honors `.theme()` for BOTH role-based and name-based lookups — unlike
165/// the previous single-struct design, no dispatch layer can silently
166/// drop the theme override.
167///
168/// An icon comes only from the theme or from a theme in the `Inherits=`
169/// chain its `index.theme` declares, searched depth-first in declared
170/// order as the Icon Theme Specification's lookup does, never from
171/// `hicolor` unless `hicolor` is the theme asked for, nor from a loose
172/// file in an icon directory or `/usr/share/pixmaps`. An icon the theme
173/// and its parents lack is `None`, and so is every icon of a theme that
174/// is not installed.
175///
176/// The installed themes are read once, at the process's first freedesktop
177/// lookup (freedesktop-icons caches them the same way), and a theme's
178/// `Inherits=` chain at its own first lookup, so a theme installed after
179/// that is not searched, and a changed `Inherits=` is not seen, until the
180/// process restarts.
181///
182/// ```
183/// # #[cfg(all(target_os = "linux", feature = "system-icons"))]
184/// # {
185/// use native_theme::icons::FreedesktopLoader;
186/// use native_theme::icons::IconRole;
187///
188/// // By role, system theme:
189/// let _icon = FreedesktopLoader::new(IconRole::ActionCopy).load();
190///
191/// // By name, explicit theme + size + symbolic fg color:
192/// let _icon = FreedesktopLoader::new("edit-copy")
193///     .theme("Adwaita")
194///     .size(48)
195///     .color(native_theme::Rgba::rgb(0, 0, 0))
196///     .load();
197/// # }
198/// ```
199#[derive(Debug)]
200#[must_use]
201pub struct FreedesktopLoader<'a> {
202    // Fields read only in the Linux + system-icons cfg branch of `load`.
203    #[allow(dead_code)]
204    wanted: Wanted<'a>,
205    #[allow(dead_code)]
206    size: u32,
207    #[allow(dead_code)]
208    fg_color: Option<[u8; 3]>,
209    #[allow(dead_code)]
210    theme: Option<&'a str>,
211}
212
213/// What a [`FreedesktopLoader`] looks up.
214#[derive(Debug)]
215enum Wanted<'a> {
216    /// One icon: a role, a name or a provider ([`FreedesktopLoader::new`]).
217    // Read only in the Linux + system-icons cfg branch of `load`.
218    #[allow(dead_code)]
219    Id(IconId<'a>),
220    /// The first of several names the theme has ([`FreedesktopLoader::any`]).
221    #[allow(dead_code)]
222    AnyOf(&'a [&'a str]),
223}
224
225impl<'a> FreedesktopLoader<'a> {
226    /// Create a freedesktop loader. Defaults: size 24, no fg_color, system theme.
227    pub fn new(id: impl Into<IconId<'a>>) -> Self {
228        Self::wanting(Wanted::Id(id.into()))
229    }
230
231    /// Create a loader for the first of `names` the theme has, for a
232    /// concept icon themes name differently (Breeze's `view-visible`,
233    /// Adwaita's `view-reveal`). Each theme of the chain (see
234    /// [`FreedesktopLoader`]) is searched for every name, in order, before
235    /// the theme it inherits from, so the theme's own icon under a later
236    /// name wins over its parent's under an earlier one: Adwaita's
237    /// `starred-symbolic` over AdwaitaLegacy's raster `emblem-favorite`,
238    /// which [`Self::new`] tried name by name would load. Within a theme a
239    /// name is tried as `<name>-symbolic`, then as itself. Every name is
240    /// looked up in the one theme and its chain, so no icon comes from
241    /// another set. Defaults as [`Self::new`]; no names load `None`.
242    ///
243    /// With one name, `any(&[name])` differs from `new(name)` in one case: a
244    /// theme that has the plain `name` while a theme it inherits from has
245    /// `<name>-symbolic`. `any` takes the theme's own plain icon, as it
246    /// searches a theme before its parent; `new` searches the whole chain for
247    /// the symbolic form first and takes the parent's.
248    ///
249    /// ```
250    /// # #[cfg(all(target_os = "linux", feature = "system-icons"))]
251    /// # {
252    /// use native_theme::icons::FreedesktopLoader;
253    ///
254    /// let _eye = FreedesktopLoader::any(&["view-visible", "view-reveal"])
255    ///     .theme("Adwaita")
256    ///     .load();
257    /// # }
258    /// ```
259    pub fn any(names: &'a [&'a str]) -> Self {
260        Self::wanting(Wanted::AnyOf(names))
261    }
262
263    /// A loader for `wanted`, with [`Self::new`]'s defaults.
264    fn wanting(wanted: Wanted<'a>) -> Self {
265        Self {
266            wanted,
267            size: 24,
268            fg_color: None,
269            theme: None,
270        }
271    }
272
273    /// Set the requested icon size in pixels (default 24), clamped to
274    /// `1..=`[`MAX_ICON_SIZE`]: a larger size is looked up as 512, in the
275    /// theme's directory nearest it.
276    pub fn size(mut self, size: u32) -> Self {
277        self.size = size.clamp(1, MAX_ICON_SIZE);
278        self
279    }
280
281    /// Set the foreground color for GTK symbolic icon colorization; its
282    /// alpha is ignored: the icon keeps its own coverage.
283    pub fn color(mut self, color: Rgba) -> Self {
284        self.fg_color = Some(rgb(color));
285        self
286    }
287
288    /// Set the foreground color if `Some`, leave default if `None`; its
289    /// alpha is ignored, as in [`Self::color`].
290    pub fn color_opt(mut self, color: Option<Rgba>) -> Self {
291        self.fg_color = color.map(rgb);
292        self
293    }
294
295    /// Override the freedesktop icon theme (e.g. "Adwaita", "breeze").
296    /// When unset, uses the system-detected theme, and searches no theme
297    /// where detection fails (see [`Self::load`]).
298    pub fn theme(mut self, theme: &'a str) -> Self {
299        self.theme = Some(theme);
300        self
301    }
302
303    /// Load the icon, returning its data.
304    ///
305    /// `None` when neither the theme nor a theme it inherits from has the
306    /// icon (see [`FreedesktopLoader`]).
307    ///
308    /// With no [`theme`](Self::theme) set, the icon comes from the system's
309    /// icon theme, and where that cannot be detected no theme is searched,
310    /// as none stands in for the undetected one: a role or a name gives
311    /// `None`, and a custom [`IconProvider`] gives only its own freedesktop
312    /// SVG ([`IconProvider::icon_svg`]), which depends on no theme, where it
313    /// has one. [`system_icon_theme()`](crate::detect::system_icon_theme)
314    /// gives the reason.
315    ///
316    /// Requires the `system-icons` feature, and Linux; `None` otherwise.
317    #[must_use]
318    pub fn load(self) -> Option<IconData> {
319        self.load_with(system_icon_theme)
320    }
321
322    /// [`Self::load`], with `detect` giving the system's icon theme where no
323    /// theme is set.
324    #[allow(unused_variables)]
325    fn load_with(self, detect: impl FnOnce() -> crate::Result<String>) -> Option<IconData> {
326        #[cfg(all(target_os = "linux", feature = "system-icons"))]
327        {
328            let detected;
329            let theme: Option<&str> = match self.theme {
330                Some(t) => Some(t),
331                None => {
332                    detected = detect().ok();
333                    detected.as_deref()
334                }
335            };
336            match self.wanted {
337                Wanted::AnyOf(names) => crate::freedesktop::load_freedesktop_icon_by_names(
338                    names,
339                    theme?,
340                    self.size,
341                    self.fg_color,
342                ),
343                Wanted::Id(IconId::Role(role)) => {
344                    let name = icon_name(role, IconSet::Freedesktop)?;
345                    crate::freedesktop::load_freedesktop_icon_by_name(
346                        name,
347                        theme?,
348                        self.size,
349                        self.fg_color,
350                    )
351                }
352                Wanted::Id(IconId::Name(name)) => {
353                    crate::freedesktop::load_freedesktop_icon_by_name(
354                        name,
355                        theme?,
356                        self.size,
357                        self.fg_color,
358                    )
359                }
360                Wanted::Id(IconId::Custom(provider)) => {
361                    if let Some(theme) = theme
362                        && let Some(name) = provider.icon_name(IconSet::Freedesktop)
363                        && let Some(data) = crate::freedesktop::load_freedesktop_icon_by_name(
364                            name,
365                            theme,
366                            self.size,
367                            self.fg_color,
368                        )
369                    {
370                        return Some(data);
371                    }
372                    provider.icon_svg(IconSet::Freedesktop).map(IconData::Svg)
373                }
374            }
375        }
376        #[cfg(not(all(target_os = "linux", feature = "system-icons")))]
377        {
378            None
379        }
380    }
381
382    /// Load the theme's animated process-working spinner.
383    ///
384    /// `theme` of `None` uses the system-detected theme, and gives `None`
385    /// where detection fails — no theme stands in for the undetected one;
386    /// `Some(t)` overrides.
387    /// Associated function (no `self`) — the spinner is a property of the
388    /// theme, not of any particular icon id. Found only where
389    /// [`Self::load`] would find an icon: in the theme or a theme it
390    /// inherits from, never in `hicolor` unless that is the theme.
391    ///
392    /// Requires the `system-icons` feature, and Linux; `None` otherwise.
393    #[must_use]
394    #[allow(unused_variables)]
395    pub fn load_indicator(theme: Option<&str>) -> Option<AnimatedIcon> {
396        #[cfg(all(target_os = "linux", feature = "system-icons"))]
397        {
398            crate::freedesktop::load_freedesktop_spinner(theme)
399        }
400        #[cfg(not(all(target_os = "linux", feature = "system-icons")))]
401        {
402            None
403        }
404    }
405}
406
407/// Loader for Apple SF Symbols (macOS only).
408///
409/// SF Symbols has no concept of themes. A symbol is a monochrome template,
410/// drawn black unless [`Self::color`] gives it a foreground colour.
411#[derive(Debug)]
412#[must_use]
413pub struct SfSymbolsLoader<'a> {
414    #[allow(dead_code)] // read only in the macOS cfg branch of `load`
415    id: IconId<'a>,
416    #[allow(dead_code)] // read only in the macOS cfg branch of `load`
417    size: Option<u32>,
418    #[allow(dead_code)] // read only in the macOS cfg branch of `load`
419    fg_color: Option<[u8; 3]>,
420}
421
422impl<'a> SfSymbolsLoader<'a> {
423    /// Construct a new SF Symbols loader for the given icon id. Defaults:
424    /// size 24 points, no fg_color.
425    pub fn new(id: impl Into<IconId<'a>>) -> Self {
426        Self {
427            id: id.into(),
428            size: None,
429            fg_color: None,
430        }
431    }
432
433    /// Set the symbol's point size (default 24), the size its symbol
434    /// configuration is made with, clamped to `1..=`[`MAX_ICON_SIZE`]. A
435    /// symbol whose raster the OS draws over the 64 MiB decode bound loads
436    /// `None`.
437    pub fn size(mut self, size: u32) -> Self {
438        self.size = Some(size.clamp(1, MAX_ICON_SIZE));
439        self
440    }
441
442    /// Set the foreground color the monochrome symbol is drawn in; its
443    /// alpha is ignored: the symbol keeps its own coverage.
444    pub fn color(mut self, color: Rgba) -> Self {
445        self.fg_color = Some(rgb(color));
446        self
447    }
448
449    /// Set the foreground color if `Some`, leave default if `None`; its
450    /// alpha is ignored, as in [`Self::color`].
451    pub fn color_opt(mut self, color: Option<Rgba>) -> Self {
452        self.fg_color = color.map(rgb);
453        self
454    }
455
456    /// Load the icon, returning its data.
457    ///
458    /// Requires the `system-icons` feature, and macOS; `None` otherwise.
459    #[must_use]
460    #[allow(unused_variables)]
461    pub fn load(self) -> Option<IconData> {
462        #[cfg(all(target_os = "macos", feature = "system-icons"))]
463        {
464            match self.id {
465                IconId::Role(role) => {
466                    let name = icon_name(role, IconSet::SfSymbols)?;
467                    crate::sficons::load_sf_icon_by_name(name, self.size, self.fg_color)
468                }
469                IconId::Name(n) => {
470                    crate::sficons::load_sf_icon_by_name(n, self.size, self.fg_color)
471                }
472                IconId::Custom(p) => {
473                    if let Some(n) = p.icon_name(IconSet::SfSymbols)
474                        && let Some(data) =
475                            crate::sficons::load_sf_icon_by_name(n, self.size, self.fg_color)
476                    {
477                        return Some(data);
478                    }
479                    p.icon_svg(IconSet::SfSymbols).map(IconData::Svg)
480                }
481            }
482        }
483        #[cfg(not(all(target_os = "macos", feature = "system-icons")))]
484        {
485            None
486        }
487    }
488    // No load_indicator: SF Symbols has no animated spinner primitive.
489}
490
491/// Loader for Windows Segoe Fluent Icons (Windows only).
492///
493/// Segoe icons have no themes. A Segoe Fluent glyph is monochrome, drawn
494/// white unless [`Self::color`] gives it a foreground colour; a stock shell
495/// icon (the `SIID_*` and `IDI_QUESTION` names) is full-colour and keeps its
496/// own colours.
497#[derive(Debug)]
498#[must_use]
499pub struct SegoeFluentLoader<'a> {
500    #[allow(dead_code)] // read only in the Windows cfg branch of `load`
501    id: IconId<'a>,
502    #[allow(dead_code)] // read only in the Windows cfg branch of `load`
503    size: Option<u32>,
504    #[allow(dead_code)] // read only in the Windows cfg branch of `load`
505    fg_color: Option<[u8; 3]>,
506}
507
508impl<'a> SegoeFluentLoader<'a> {
509    /// Construct a new Segoe Fluent loader for the given icon id. Defaults:
510    /// size 32 pixels, no fg_color.
511    pub fn new(id: impl Into<IconId<'a>>) -> Self {
512        Self {
513            id: id.into(),
514            size: None,
515            fg_color: None,
516        }
517    }
518
519    /// Set a glyph's size in pixels (default 32), the em height its font
520    /// is created with, clamped to `1..=`[`MAX_ICON_SIZE`]. A stock shell
521    /// icon keeps the system's large icon size.
522    pub fn size(mut self, size: u32) -> Self {
523        self.size = Some(size.clamp(1, MAX_ICON_SIZE));
524        self
525    }
526
527    /// Set the foreground color a monochrome glyph is drawn in; its alpha
528    /// is ignored: the glyph keeps its own coverage. A full-colour stock
529    /// icon is unchanged.
530    pub fn color(mut self, color: Rgba) -> Self {
531        self.fg_color = Some(rgb(color));
532        self
533    }
534
535    /// Set the foreground color if `Some`, leave default if `None`; its
536    /// alpha is ignored, as in [`Self::color`].
537    pub fn color_opt(mut self, color: Option<Rgba>) -> Self {
538        self.fg_color = color.map(rgb);
539        self
540    }
541
542    /// Load the icon, returning its data.
543    ///
544    /// Requires the `system-icons` feature, and Windows; `None` otherwise.
545    #[must_use]
546    #[allow(unused_variables)]
547    pub fn load(self) -> Option<IconData> {
548        #[cfg(all(target_os = "windows", feature = "system-icons"))]
549        {
550            match self.id {
551                IconId::Role(role) => {
552                    let name = icon_name(role, IconSet::SegoeFluent)?;
553                    crate::winicons::load_windows_icon_by_name(name, self.size, self.fg_color)
554                }
555                IconId::Name(n) => {
556                    crate::winicons::load_windows_icon_by_name(n, self.size, self.fg_color)
557                }
558                IconId::Custom(p) => {
559                    if let Some(n) = p.icon_name(IconSet::SegoeFluent)
560                        && let Some(data) =
561                            crate::winicons::load_windows_icon_by_name(n, self.size, self.fg_color)
562                    {
563                        return Some(data);
564                    }
565                    p.icon_svg(IconSet::SegoeFluent).map(IconData::Svg)
566                }
567            }
568        }
569        #[cfg(not(all(target_os = "windows", feature = "system-icons")))]
570        {
571            None
572        }
573    }
574    // No load_indicator: Segoe has no animated spinner primitive.
575}
576
577/// Loader for Google Material Symbols (bundled SVG).
578///
579/// Material SVGs are scalable at render time, so no `size` method.
580#[derive(Debug)]
581#[must_use]
582pub struct MaterialLoader<'a> {
583    #[allow(dead_code)] // read only in the material-icons feature cfg branch of `load`
584    id: IconId<'a>,
585}
586
587impl<'a> MaterialLoader<'a> {
588    /// Construct a new Material Symbols loader for the given icon id.
589    pub fn new(id: impl Into<IconId<'a>>) -> Self {
590        Self { id: id.into() }
591    }
592
593    /// Load the icon, returning its data.
594    ///
595    /// Requires the `material-icons` feature; `None` otherwise.
596    #[must_use]
597    #[allow(unused_variables)]
598    pub fn load(self) -> Option<IconData> {
599        #[cfg(feature = "material-icons")]
600        {
601            match self.id {
602                IconId::Role(role) => bundled_icon_svg(role, IconSet::Material)
603                    .map(|b| IconData::Svg(Cow::Borrowed(b))),
604                IconId::Name(n) => bundled_icon_by_name(n, IconSet::Material)
605                    .map(|b| IconData::Svg(Cow::Borrowed(b))),
606                IconId::Custom(p) => {
607                    if let Some(n) = p.icon_name(IconSet::Material)
608                        && let Some(b) = bundled_icon_by_name(n, IconSet::Material)
609                    {
610                        return Some(IconData::Svg(Cow::Borrowed(b)));
611                    }
612                    p.icon_svg(IconSet::Material).map(IconData::Svg)
613                }
614            }
615        }
616        #[cfg(not(feature = "material-icons"))]
617        {
618            None
619        }
620    }
621
622    /// Load the Material animated spinner. Associated function; no `self`.
623    ///
624    /// Requires the `material-icons` feature; `None` otherwise.
625    #[must_use]
626    pub fn load_indicator() -> Option<AnimatedIcon> {
627        #[cfg(feature = "material-icons")]
628        {
629            Some(crate::spinners::material_spinner())
630        }
631        #[cfg(not(feature = "material-icons"))]
632        {
633            None
634        }
635    }
636}
637
638/// Loader for Lucide Icons (bundled SVG).
639#[derive(Debug)]
640#[must_use]
641pub struct LucideLoader<'a> {
642    #[allow(dead_code)] // read only in the lucide-icons feature cfg branch of `load`
643    id: IconId<'a>,
644}
645
646impl<'a> LucideLoader<'a> {
647    /// Construct a new Lucide Icons loader for the given icon id.
648    pub fn new(id: impl Into<IconId<'a>>) -> Self {
649        Self { id: id.into() }
650    }
651
652    /// Load the icon, returning its data.
653    ///
654    /// Requires the `lucide-icons` feature; `None` otherwise.
655    #[must_use]
656    #[allow(unused_variables)]
657    pub fn load(self) -> Option<IconData> {
658        #[cfg(feature = "lucide-icons")]
659        {
660            match self.id {
661                IconId::Role(role) => {
662                    bundled_icon_svg(role, IconSet::Lucide).map(|b| IconData::Svg(Cow::Borrowed(b)))
663                }
664                IconId::Name(n) => bundled_icon_by_name(n, IconSet::Lucide)
665                    .map(|b| IconData::Svg(Cow::Borrowed(b))),
666                IconId::Custom(p) => {
667                    if let Some(n) = p.icon_name(IconSet::Lucide)
668                        && let Some(b) = bundled_icon_by_name(n, IconSet::Lucide)
669                    {
670                        return Some(IconData::Svg(Cow::Borrowed(b)));
671                    }
672                    p.icon_svg(IconSet::Lucide).map(IconData::Svg)
673                }
674            }
675        }
676        #[cfg(not(feature = "lucide-icons"))]
677        {
678            None
679        }
680    }
681
682    /// Load the Lucide animated spinner. Associated function; no `self`.
683    ///
684    /// Requires the `lucide-icons` feature; `None` otherwise.
685    #[must_use]
686    pub fn load_indicator() -> Option<AnimatedIcon> {
687        #[cfg(feature = "lucide-icons")]
688        {
689            Some(crate::spinners::lucide_spinner())
690        }
691        #[cfg(not(feature = "lucide-icons"))]
692        {
693            None
694        }
695    }
696}
697
698// =============================================================================
699// Runtime-set dispatch helpers
700// =============================================================================
701
702/// Load an icon using the given set with default per-set options.
703///
704/// For set-specific options (freedesktop theme, fg_color), construct the
705/// specific loader directly and chain the relevant methods.
706///
707/// Each set needs its loader's feature (see the loaders); `None` without it.
708#[must_use]
709pub fn load_icon<'a>(id: impl Into<IconId<'a>>, set: IconSet) -> Option<IconData> {
710    let id = id.into();
711    match set {
712        IconSet::Freedesktop => FreedesktopLoader::new(id).load(),
713        IconSet::SfSymbols => SfSymbolsLoader::new(id).load(),
714        IconSet::SegoeFluent => SegoeFluentLoader::new(id).load(),
715        IconSet::Material => MaterialLoader::new(id).load(),
716        IconSet::Lucide => LucideLoader::new(id).load(),
717    }
718}
719
720/// Load the animated loading indicator for the given set.
721///
722/// `theme` is the freedesktop theme to take the spinner from, as
723/// [`FreedesktopLoader::load_indicator`] takes it: `None` uses the
724/// system-detected theme. It is used only for [`IconSet::Freedesktop`];
725/// for the sets that have no themes (Material, Lucide, SfSymbols,
726/// SegoeFluent), the theme name is not used by the loader.
727///
728/// Returns `None` for sets without an animated spinner (SfSymbols, SegoeFluent).
729///
730/// Each set needs its loader's feature (see the loaders); `None` without it.
731#[must_use]
732pub fn load_icon_indicator(set: IconSet, theme: Option<&str>) -> Option<AnimatedIcon> {
733    match set {
734        IconSet::Freedesktop => FreedesktopLoader::load_indicator(theme),
735        IconSet::Material => MaterialLoader::load_indicator(),
736        IconSet::Lucide => LucideLoader::load_indicator(),
737        IconSet::SfSymbols | IconSet::SegoeFluent => None,
738    }
739}
740
741/// Load a custom icon from an [`IconProvider`] for a set known only at
742/// runtime, in `color`, at `size`.
743///
744/// The provider's [`icon_name`](IconProvider::icon_name) for `set` is loaded
745/// first; where it has none, or the set has no such icon, its own
746/// [`icon_svg`](IconProvider::icon_svg) for `set` is used. No other set is
747/// tried.
748///
749/// Each set takes `color` its own way: an SF Symbol or a Segoe glyph loads
750/// in it ([`SfSymbolsLoader::color`], [`SegoeFluentLoader::color`]), and a
751/// Material or Lucide icon, or the provider's own SVG, is coloured through
752/// [`colorize_monochrome_svg`]. A freedesktop icon takes it where it has a
753/// foreground left to the caller: a symbolic icon's placeholders
754/// ([`FreedesktopLoader::color`]) and a `currentColor` the document sets no
755/// `color` for ([`fill_current_color`]) are drawn in it. An icon whose own
756/// stylesheet sets the `color` its `currentColor` takes (Breeze's
757/// `current-color-scheme`) keeps that colour, as it is not yet rewritten from
758/// the theme as KDE's own icon loader does, and a full-colour icon keeps its
759/// palette. `None` leaves each icon in the colour it loads in. A freedesktop
760/// icon comes from the system's icon theme; [`load_custom_icon_in`] takes
761/// another, and [`SystemTheme::icon`](crate::SystemTheme::icon) the theme's
762/// own. A provider's own SVG is coloured as a monochrome icon, so give a
763/// colour only for monochrome icons; with `None` a full-colour SVG is
764/// returned unchanged.
765///
766/// `size` is clamped to `1..=`[`MAX_ICON_SIZE`] and reaches each system
767/// set's loader as that loader takes it: the pixel size a freedesktop icon
768/// is looked up at ([`FreedesktopLoader::size`], which picks the theme's
769/// directory nearest it, so a PNG icon comes back at that directory's
770/// size), an SF Symbol's point size ([`SfSymbolsLoader::size`]) and a Segoe
771/// glyph's pixel size ([`SegoeFluentLoader::size`]); a loader that cannot
772/// draw the icon at that size returns `None`, as for an icon it does not
773/// find. `None` keeps each loader's default (24 pixels, 24 points and 32
774/// pixels). A Material or Lucide icon, or the provider's own SVG, is
775/// scalable and loads the same at every size.
776///
777/// Each set needs its loader's feature (see the loaders); `None` without it.
778#[must_use]
779pub fn load_custom_icon(
780    provider: &(impl IconProvider + ?Sized),
781    set: IconSet,
782    color: Option<Rgba>,
783    size: Option<u32>,
784) -> Option<IconData> {
785    load_custom_icon_in(provider, set, None, color, size)
786}
787
788/// [`load_custom_icon`], with a freedesktop icon looked up in `icon_theme`
789/// ([`FreedesktopLoader::theme`]) where it is `Some`, the system's icon
790/// theme where it is `None`. `size` is clamped to `1..=`[`MAX_ICON_SIZE`]
791/// as there.
792///
793/// For the icon theme the application's theme names
794/// ([`SystemTheme::icon_theme_for`](crate::SystemTheme::icon_theme_for),
795/// [`Resolved::icon_theme`](crate::Resolved::icon_theme)), so a provider's
796/// icon comes from the same icon theme as the role icons beside it. An
797/// icon the theme and the themes it inherits from lack is the provider's
798/// own SVG, or `None`; no other theme is searched. The other sets have no
799/// themes and do not use it.
800#[must_use]
801pub fn load_custom_icon_in(
802    provider: &(impl IconProvider + ?Sized),
803    set: IconSet,
804    icon_theme: Option<&str>,
805    color: Option<Rgba>,
806    size: Option<u32>,
807) -> Option<IconData> {
808    load_provider_icon(provider, set, icon_theme, color, size)
809}
810
811/// The runtime-set load behind
812/// [`SystemTheme::icon`](crate::SystemTheme::icon): `id` from `set` in
813/// `color` at `size`, a freedesktop icon from `theme` (the system's where
814/// `None`).
815pub(crate) fn load_icon_in<'a>(
816    id: IconId<'a>,
817    set: IconSet,
818    theme: Option<&'a str>,
819    color: Option<Rgba>,
820    size: Option<u32>,
821) -> Option<IconData> {
822    match id {
823        IconId::Custom(provider) => load_provider_icon(provider, set, theme, color, size),
824        id => load_set_icon(id, set, theme, color, size),
825    }
826}
827
828/// A provider's icon: its name for `set` through the set's loader, else its
829/// own SVG, coloured.
830fn load_provider_icon(
831    provider: &(impl IconProvider + ?Sized),
832    set: IconSet,
833    theme: Option<&str>,
834    color: Option<Rgba>,
835    size: Option<u32>,
836) -> Option<IconData> {
837    if let Some(name) = provider.icon_name(set)
838        && let Some(data) = load_set_icon(IconId::Name(name), set, theme, color, size)
839    {
840        return Some(data);
841    }
842    provider
843        .icon_svg(set)
844        .map(|svg| colorize_svg_data(IconData::Svg(svg), color))
845}
846
847/// A role or a name from `set`'s loader, in `color`, at `size` where the
848/// loader takes one; each system loader's `size` clamps it to
849/// `1..=MAX_ICON_SIZE`.
850fn load_set_icon<'a>(
851    id: IconId<'a>,
852    set: IconSet,
853    theme: Option<&'a str>,
854    color: Option<Rgba>,
855    size: Option<u32>,
856) -> Option<IconData> {
857    match set {
858        IconSet::Freedesktop => {
859            let loader = FreedesktopLoader::new(id).color_opt(color);
860            let loader = match size {
861                Some(size) => loader.size(size),
862                None => loader,
863            };
864            match theme {
865                Some(theme) => loader.theme(theme),
866                None => loader,
867            }
868            .load()
869            .map(|data| fill_freedesktop_svg_data(data, color))
870        }
871        IconSet::SfSymbols => {
872            let loader = SfSymbolsLoader::new(id).color_opt(color);
873            match size {
874                Some(size) => loader.size(size),
875                None => loader,
876            }
877            .load()
878        }
879        IconSet::SegoeFluent => {
880            let loader = SegoeFluentLoader::new(id).color_opt(color);
881            match size {
882                Some(size) => loader.size(size),
883                None => loader,
884            }
885            .load()
886        }
887        IconSet::Material => MaterialLoader::new(id)
888            .load()
889            .map(|data| colorize_svg_data(data, color)),
890        IconSet::Lucide => LucideLoader::new(id)
891            .load()
892            .map(|data| colorize_svg_data(data, color)),
893    }
894}
895
896/// An SVG coloured through [`colorize_monochrome_svg`] where `color` is
897/// given; anything else unchanged.
898fn colorize_svg_data(data: IconData, color: Option<Rgba>) -> IconData {
899    match (data, color) {
900        (IconData::Svg(svg), Some(color)) => {
901            IconData::Svg(Cow::Owned(colorize_monochrome_svg(&svg, color)))
902        }
903        (data, _) => data,
904    }
905}
906
907/// A freedesktop SVG's `currentColor` filled in with `color` through
908/// [`fill_current_color`] where the document sets no `color` of its own, as
909/// a rasteriser would otherwise draw it black; an SVG that sets its own (a
910/// Breeze `current-color-scheme` stylesheet), one without `currentColor`, a
911/// raster, or no `color`, unchanged.
912fn fill_freedesktop_svg_data(data: IconData, color: Option<Rgba>) -> IconData {
913    match (data, color) {
914        (IconData::Svg(svg), Some(color)) => {
915            let filled = match fill_current_color(&svg, color) {
916                Cow::Owned(filled) => Some(filled),
917                Cow::Borrowed(_) => None,
918            };
919            IconData::Svg(filled.map_or(svg, Cow::Owned))
920        }
921        (data, _) => data,
922    }
923}
924
925/// Colour a monochrome SVG icon in its bytes.
926///
927/// A rasteriser given no `color` draws an implicit fill and an unresolved
928/// `currentColor` black, and a draw-time tint multiplies, which leaves black
929/// black — so a Material or Lucide icon would draw black on a dark scheme.
930/// This writes `color` into the bytes instead, with gpui's algorithm:
931///
932/// 1. `currentColor` becomes the colour's `#rrggbb` (Lucide-style SVGs);
933/// 2. explicit black fills — `fill="black"`, `fill="#000000"`, `fill="#000"` —
934///    and explicit black strokes — `stroke="black"`, `stroke="#000000"`,
935///    `stroke="#000"` — become the hex (third-party SVGs with hardcoded black);
936/// 3. where none of those occurs, `fill="#rrggbb"` is injected into a root
937///    `<svg>` tag that has no `fill=` attribute (Material-style SVGs), before
938///    the `/` of a self-closing tag.
939///
940/// Bytes that are not UTF-8 come back unchanged (a lossy replacement would
941/// corrupt them). The colour's alpha is discarded: an SVG `fill` or `stroke`
942/// attribute takes opaque hex. Not handled, as in gpui: CSS inline styles
943/// (`style="fill:black"`), `fill="rgb(0,0,0)"`, and explicit black on a child
944/// element when the root tag has another fill. For monochrome icon sets; a
945/// full-colour SVG should not be passed through it.
946#[must_use]
947pub fn colorize_monochrome_svg(svg: &[u8], color: Rgba) -> Vec<u8> {
948    let hex = format!("#{:02x}{:02x}{:02x}", color.r, color.g, color.b);
949
950    let Ok(svg_str) = std::str::from_utf8(svg) else {
951        return svg.to_vec();
952    };
953
954    // 1. currentColor
955    let replaced = if svg_str.contains("currentColor") {
956        svg_str.replace("currentColor", &hex)
957    } else {
958        svg_str.to_owned()
959    };
960
961    // 2. explicit black fills and strokes
962    let fill_hex = format!("fill=\"{hex}\"");
963    let replaced = replaced
964        .replace("fill=\"black\"", &fill_hex)
965        .replace("fill=\"#000000\"", &fill_hex)
966        .replace("fill=\"#000\"", &fill_hex);
967    let stroke_hex = format!("stroke=\"{hex}\"");
968    let replaced = replaced
969        .replace("stroke=\"black\"", &stroke_hex)
970        .replace("stroke=\"#000000\"", &stroke_hex)
971        .replace("stroke=\"#000\"", &stroke_hex);
972
973    if replaced != svg_str {
974        return replaced.into_bytes();
975    }
976
977    // 3. No currentColor and no explicit black: inject a fill into a root
978    // <svg> tag that has none (implicit black fill).
979    if let Some(pos) = svg_str.find("<svg")
980        && let Some(tail) = svg_str.get(pos..)
981        && let Some(close) = tail.find('>')
982    {
983        let tag_end = pos.saturating_add(close);
984        if let Some(tag) = svg_str.get(pos..tag_end)
985            && !tag.contains("fill=")
986        {
987            // A self-closing tag: inject before the '/' of '<svg .../>'.
988            let is_self_closing = tag_end > 0
989                && svg_str
990                    .as_bytes()
991                    .get(tag_end.saturating_sub(1))
992                    .is_some_and(|&b| b == b'/');
993            let inject_pos = if is_self_closing {
994                tag_end.saturating_sub(1)
995            } else {
996                tag_end
997            };
998            if let Some(before) = svg_str.get(..inject_pos)
999                && let Some(after) = svg_str.get(inject_pos..)
1000            {
1001                let mut result = String::with_capacity(svg_str.len().saturating_add(20));
1002                result.push_str(before);
1003                result.push_str(&format!(" fill=\"{hex}\""));
1004                result.push_str(after);
1005                return result.into_bytes();
1006            }
1007        }
1008    }
1009
1010    // A non-black fill and no currentColor: unchanged.
1011    svg.to_vec()
1012}
1013
1014/// Fill a symbolic icon's `currentColor` in with `color`, in its bytes.
1015///
1016/// A symbolic freedesktop icon, the `process-working-symbolic` spinner among
1017/// them, comes back from [`FreedesktopLoader`] without a colour of its own
1018/// with its foreground as `currentColor`, and a rasteriser resolves
1019/// `currentColor` from the nearest `color` property, black where the
1020/// document sets none (usvg 0.45.1 `src/parser/style.rs:170-173`). This
1021/// replaces every `currentColor` with the colour's `#rrggbb` where the
1022/// document sets no `color` property or attribute of its own; one that does,
1023/// as Breeze's stylesheet does per colour scheme, keeps the colour it states.
1024/// `color` is what `currentColor` stands for: a theme's
1025/// `defaults.text_color`.
1026///
1027/// The bytes come back borrowed and unchanged where they hold no
1028/// `currentColor`, set a `color` of their own, or are not UTF-8. The
1029/// colour's alpha is discarded, as in [`colorize_monochrome_svg`]. Unlike
1030/// that function it touches nothing else, so it suits a full-colour icon
1031/// too.
1032///
1033/// # Examples
1034///
1035/// ```
1036/// use native_theme::Rgba;
1037/// use native_theme::icons::fill_current_color;
1038///
1039/// let text = Rgba::rgb(0x22, 0x22, 0x26);
1040/// let symbolic = br#"<svg><path fill="currentColor"/></svg>"#;
1041/// assert_eq!(
1042///     &*fill_current_color(symbolic, text),
1043///     br##"<svg><path fill="#222226"/></svg>"##
1044/// );
1045///
1046/// let styled = br#"<svg><style>.a { color: #fcfcfc }</style><path class="a" fill="currentColor"/></svg>"#;
1047/// assert_eq!(&*fill_current_color(styled, text), &styled[..]);
1048/// ```
1049#[must_use]
1050pub fn fill_current_color(svg: &[u8], color: Rgba) -> Cow<'_, [u8]> {
1051    match std::str::from_utf8(svg) {
1052        Ok(text) if text.contains("currentColor") && !sets_color(text) => Cow::Owned(
1053            text.replace(
1054                "currentColor",
1055                &format!("#{:02x}{:02x}{:02x}", color.r, color.g, color.b),
1056            )
1057            .into_bytes(),
1058        ),
1059        _ => Cow::Borrowed(svg),
1060    }
1061}
1062
1063/// Whether an SVG sets a `color` property of its own: the name `color` not
1064/// preceded by a letter, digit, `-` or `_`, then optional whitespace and `:`
1065/// (a stylesheet or `style` declaration) or `=` (an attribute), anywhere in
1066/// it. usvg takes `color` from the nearest ancestor that sets it, so the
1067/// test is over the whole document. `stop-color`, `flood-color` and the like
1068/// are other properties, and an `id` or `class` named `color` is no
1069/// property.
1070fn sets_color(svg: &str) -> bool {
1071    let bytes = svg.as_bytes();
1072    svg.match_indices("color").any(|(at, _)| {
1073        let preceded = at
1074            .checked_sub(1)
1075            .and_then(|i| bytes.get(i))
1076            .is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'-' || *b == b'_');
1077        if preceded {
1078            return false;
1079        }
1080        at.checked_add("color".len())
1081            .and_then(|i| bytes.get(i..))
1082            .and_then(|rest| rest.iter().find(|b| !b.is_ascii_whitespace()))
1083            .is_some_and(|b| *b == b':' || *b == b'=')
1084    })
1085}
1086
1087/// The icon base directories, in the Icon Theme Specification's order
1088/// (version 0.13, *Directory Layout*: "$HOME/.icons (for backwards
1089/// compatibility), in $XDG_DATA_DIRS/icons and in /usr/share/pixmaps (in
1090/// that order)"), with `$XDG_DATA_HOME`, which the XDG Base Directory
1091/// Specification ranks above every `$XDG_DATA_DIRS` entry, first among the
1092/// data dirs: `~/.icons`, `$XDG_DATA_HOME/icons`, then each `$XDG_DATA_DIRS`
1093/// entry's `icons`, keeping those that exist. These are the directories
1094/// freedesktop-icons 0.4.0 searches, without the `pixmaps` directory beside
1095/// each `icons` one, which no UI icon may come from.
1096///
1097/// This order decides what native-theme reads itself: the `index.theme`
1098/// that says whether a theme is installed and what it inherits is a
1099/// theme's first one here ([`theme_index`]), so a copy the user installed
1100/// wins over the system's. freedesktop-icons searches the same directories
1101/// data dirs first and `~/.icons` last
1102/// (`freedesktop-icons-0.4.0/src/theme/paths.rs:14-33`), reads every copy
1103/// of a theme through the first `index.theme` in that order
1104/// (`src/theme/mod.rs:169-177`, `:197-215`) and takes an icon from the
1105/// first copy that has it (`src/lib.rs:297-305`): for the icons of a theme
1106/// installed both ways, the system copy comes first, an order this crate
1107/// does not control.
1108///
1109/// Read once per process, as freedesktop-icons reads its own list once.
1110#[cfg(target_os = "linux")]
1111pub(crate) fn icon_base_dirs() -> &'static [std::path::PathBuf] {
1112    static DIRS: std::sync::OnceLock<Vec<std::path::PathBuf>> = std::sync::OnceLock::new();
1113    DIRS.get_or_init(|| {
1114        icon_base_dirs_in(
1115            std::env::home_dir().as_deref(),
1116            std::env::var_os("XDG_DATA_HOME").as_deref(),
1117            std::env::var_os("XDG_DATA_DIRS").as_deref(),
1118        )
1119    })
1120}
1121
1122/// [`icon_base_dirs`] for the home directory `home` and the
1123/// `$XDG_DATA_HOME` (`data_home`) and `$XDG_DATA_DIRS` (`data_dirs`)
1124/// values, read the way freedesktop-icons' `xdg` 2.5.2 reads them
1125/// (`xdg-2.5.2/src/base_directories.rs:268-309`): a relative or unset
1126/// `$XDG_DATA_HOME` is `~/.local/share`, relative `$XDG_DATA_DIRS` entries
1127/// are dropped, and none left is `/usr/local/share:/usr/share`. Without a
1128/// home directory `xdg` gives no data dirs at all, and there is no
1129/// `~/.icons` either.
1130#[cfg(target_os = "linux")]
1131pub(crate) fn icon_base_dirs_in(
1132    home: Option<&std::path::Path>,
1133    data_home: Option<&std::ffi::OsStr>,
1134    data_dirs: Option<&std::ffi::OsStr>,
1135) -> Vec<std::path::PathBuf> {
1136    use std::path::PathBuf;
1137
1138    let Some(home) = home else {
1139        return Vec::new();
1140    };
1141    let mut dirs: Vec<PathBuf> = std::iter::once(home.join(".icons"))
1142        .chain(
1143            xdg_data_home(data_home, Some(home))
1144                .into_iter()
1145                .chain(xdg_data_dirs(data_dirs))
1146                .map(|dir| dir.join("icons")),
1147        )
1148        .collect();
1149    dirs.retain(|dir| dir.exists());
1150    dirs
1151}
1152
1153/// The data dirs `$XDG_DATA_DIRS` (`var`) names: its absolute entries, or
1154/// `/usr/local/share` and `/usr/share` when none is left, as `xdg` 2.5.2
1155/// and Qt (`qstandardpaths_unix.cpp:370-399` at v6.11.2) read it.
1156#[cfg(target_os = "linux")]
1157pub(crate) fn xdg_data_dirs(var: Option<&std::ffi::OsStr>) -> Vec<std::path::PathBuf> {
1158    use std::path::PathBuf;
1159
1160    var.map(|dirs| {
1161        std::env::split_paths(dirs)
1162            .filter(|dir| dir.is_absolute())
1163            .collect::<Vec<_>>()
1164    })
1165    .filter(|dirs| !dirs.is_empty())
1166    .unwrap_or_else(|| {
1167        vec![
1168            PathBuf::from("/usr/local/share"),
1169            PathBuf::from("/usr/share"),
1170        ]
1171    })
1172}
1173
1174/// The data home `$XDG_DATA_HOME` (`var`) names: itself when absolute, else
1175/// `<home>/.local/share`, as `xdg` 2.5.2 and Qt
1176/// (`qstandardpaths_unix.cpp:227-232` at v6.11.2) read it; `None` without
1177/// either.
1178#[cfg(target_os = "linux")]
1179pub(crate) fn xdg_data_home(
1180    var: Option<&std::ffi::OsStr>,
1181    home: Option<&std::path::Path>,
1182) -> Option<std::path::PathBuf> {
1183    var.map(std::path::PathBuf::from)
1184        .filter(|dir| dir.is_absolute())
1185        .or_else(|| home.map(|home| home.join(".local/share")))
1186}
1187
1188/// Whether `name` can name a theme directory: one plain path component,
1189/// so joining it to a base dir stays inside that base dir.
1190#[cfg(target_os = "linux")]
1191pub(crate) fn is_theme_name(name: &str) -> bool {
1192    use std::path::{Component, Path};
1193
1194    let mut components = Path::new(name).components();
1195    matches!(
1196        (components.next(), components.next()),
1197        (Some(Component::Normal(_)), None)
1198    )
1199}
1200
1201/// The `index.theme` of `theme` in `bases`: its first readable one in
1202/// their order, the one the Icon Theme Specification reads ("The first
1203/// index.theme found while searching the base directories in order is
1204/// used", *Directory Layout*). `None` for a name that is no theme directory.
1205#[cfg(target_os = "linux")]
1206pub(crate) fn theme_index(theme: &str, bases: &[std::path::PathBuf]) -> Option<String> {
1207    if !is_theme_name(theme) {
1208        return None;
1209    }
1210    bases
1211        .iter()
1212        .find_map(|base| std::fs::read_to_string(base.join(theme).join("index.theme")).ok())
1213}
1214
1215/// Whether `theme` is an icon theme installed in `bases`: its
1216/// [`theme_index`] lists `Directories`, a key the specification requires,
1217/// in its `[Icon Theme]` group. A cursor theme (`breeze_cursors`) or one
1218/// that only inherits (`default`) lists none.
1219#[cfg(target_os = "linux")]
1220pub(crate) fn has_theme_index(theme: &str, bases: &[std::path::PathBuf]) -> bool {
1221    theme_index(theme, bases)
1222        .is_some_and(|index| ini_value(&index, "Icon Theme", "Directories").is_some())
1223}
1224
1225/// The installed icon themes in `bases`: each directory name there that
1226/// [`has_theme_index`] accepts.
1227#[cfg(target_os = "linux")]
1228fn installed_themes_in(bases: &[std::path::PathBuf]) -> std::collections::BTreeSet<String> {
1229    bases
1230        .iter()
1231        .filter_map(|base| std::fs::read_dir(base).ok())
1232        .flatten()
1233        .filter_map(Result::ok)
1234        .filter_map(|entry| entry.file_name().into_string().ok())
1235        .filter(|name| has_theme_index(name, bases))
1236        .collect()
1237}
1238
1239/// The installed icon themes in [`icon_base_dirs`] ([`installed_themes_in`]),
1240/// read once, at the process's first call of
1241/// [`is_freedesktop_theme_available`], [`list_freedesktop_themes`] or a
1242/// freedesktop icon lookup, which all read it: a theme listed or available
1243/// is one the lookup searches, and a theme installed after this snapshot is
1244/// none of them until the process restarts.
1245/// [`invalidate_caches`](crate::detect::invalidate_caches) leaves it, as
1246/// freedesktop-icons' own list of themes, taken at its first lookup (after
1247/// this one, `freedesktop-icons-0.4.0/src/theme/mod.rs:15`), cannot be read
1248/// again.
1249#[cfg(target_os = "linux")]
1250pub(crate) fn installed_themes() -> &'static std::collections::BTreeSet<String> {
1251    static THEMES: std::sync::OnceLock<std::collections::BTreeSet<String>> =
1252        std::sync::OnceLock::new();
1253    THEMES.get_or_init(|| installed_themes_in(icon_base_dirs()))
1254}
1255
1256/// The value of `key` in the `[section]` group of the INI `content`,
1257/// trimmed: `None` if the group or key is missing or the value empty.
1258#[cfg(target_os = "linux")]
1259pub(crate) fn ini_value<'a>(content: &'a str, section: &str, key: &str) -> Option<&'a str> {
1260    let mut in_section = false;
1261    for line in content.lines().map(str::trim) {
1262        if let Some(group) = line.strip_prefix('[') {
1263            in_section = group.strip_suffix(']') == Some(section);
1264            continue;
1265        }
1266        if in_section
1267            && let Some((name, value)) = line.split_once('=')
1268            && name.trim() == key
1269            && !value.trim().is_empty()
1270        {
1271            return Some(value.trim());
1272        }
1273    }
1274    None
1275}
1276
1277/// Check whether a freedesktop icon theme is installed on this system.
1278///
1279/// A theme is installed when its first `index.theme` in the icon base
1280/// directories the freedesktop icon lookup searches (`~/.icons/<theme>/`,
1281/// `$XDG_DATA_HOME/icons/<theme>/`, then `$XDG_DATA_DIRS/icons/<theme>/`)
1282/// lists `Directories` in its `[Icon Theme]` group, so a cursor-only theme
1283/// is not one. The installed themes are read once per process, at the
1284/// first call of this function, [`list_freedesktop_themes`] or a
1285/// freedesktop icon lookup: a theme installed later is not available until
1286/// the process restarts, as the lookup does not search it.
1287///
1288/// Always returns `false` on non-Linux platforms.
1289#[must_use]
1290pub fn is_freedesktop_theme_available(theme: &str) -> bool {
1291    #[cfg(target_os = "linux")]
1292    {
1293        installed_themes().contains(theme)
1294    }
1295    #[cfg(not(target_os = "linux"))]
1296    {
1297        let _ = theme;
1298        false
1299    }
1300}
1301
1302// =============================================================================
1303// IconSetChoice: user's icon set selection intent
1304// =============================================================================
1305
1306/// The user's icon set selection mode.
1307///
1308/// Represents the user's intent for which icons to display.  The key
1309/// invariant: only [`Default`](Self::Default) is re-derived on theme changes.
1310/// All other variants represent an explicit user choice that is preserved
1311/// across theme re-applications.
1312#[derive(Debug, Clone, PartialEq, Eq)]
1313#[non_exhaustive]
1314pub enum IconSetChoice {
1315    /// Follow the theme preset's recommendation.
1316    ///
1317    /// The `String` is the preset's `icon_theme` name (e.g. "Adwaita"),
1318    /// used for display ("default (Adwaita)") and for loading when the
1319    /// icon set is `Freedesktop`.
1320    ///
1321    /// This is the ONLY variant that gets overwritten on theme change.
1322    /// [`default_icon_choice()`] is the constructor that checks the theme
1323    /// is available (bundled sets are always available, SF Symbols and
1324    /// Segoe Fluent where their loader is compiled, freedesktop themes are
1325    /// checked via [`is_freedesktop_theme_available`]) before it returns
1326    /// this variant. A value built directly carries no such check.
1327    Default(String),
1328
1329    /// Use the OS-configured icon theme.
1330    ///
1331    /// Resolved at load time via [`system_icon_set()`](crate::detect::system_icon_set).
1332    /// The display label ("system (breeze-dark)") is computed dynamically
1333    /// from [`system_icon_theme()`](crate::detect::system_icon_theme),
1334    /// so it tracks runtime OS theme changes. Where detection fails the
1335    /// label is short, `system (unavailable)`, as a control's label is:
1336    /// [`system_icon_theme()`](crate::detect::system_icon_theme) gives the
1337    /// reason, for a tooltip or a note where there is room for it. The
1338    /// freedesktop loaders then search no theme for this choice.
1339    System,
1340
1341    /// User explicitly picked a specific installed freedesktop icon theme.
1342    ///
1343    /// The `String` is the theme directory name (e.g. "char-white",
1344    /// "breeze", "Papirus").  Loaded via `IconSet::Freedesktop` with
1345    /// `.theme(name)`.
1346    Freedesktop(String),
1347
1348    /// Google Material Symbols (bundled).
1349    Material,
1350
1351    /// Lucide Icons (bundled).
1352    Lucide,
1353}
1354
1355impl fmt::Display for IconSetChoice {
1356    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1357        match self {
1358            Self::Default(name) => write!(f, "default ({name})"),
1359            Self::System => f.write_str(&system_choice_label(&system_icon_theme())),
1360            Self::Freedesktop(name) => write!(f, "{name}"),
1361            Self::Material => write!(f, "Material (bundled)"),
1362            Self::Lucide => write!(f, "Lucide (bundled)"),
1363        }
1364    }
1365}
1366
1367/// [`IconSetChoice::System`]'s label for the `detected` system icon theme:
1368/// its name, or `unavailable` where there is none, without the reason, which
1369/// can run to a reader's whole error.
1370fn system_choice_label(detected: &crate::Result<String>) -> String {
1371    match detected {
1372        Ok(name) => format!("system ({name})"),
1373        Err(_) => "system (unavailable)".to_string(),
1374    }
1375}
1376
1377impl IconSetChoice {
1378    /// The effective [`IconSet`] loading mechanism for this choice.
1379    ///
1380    /// For [`Default`](Self::Default), returns the theme's icon set
1381    /// (caller passes it in).
1382    /// For [`Freedesktop`](Self::Freedesktop), always returns
1383    /// [`IconSet::Freedesktop`].
1384    /// For others, returns the corresponding bundled or system set.
1385    #[must_use]
1386    pub fn effective_icon_set(&self, theme_icon_set: IconSet) -> IconSet {
1387        match self {
1388            Self::Default(_) => theme_icon_set,
1389            Self::System => system_icon_set(),
1390            Self::Freedesktop(_) => IconSet::Freedesktop,
1391            Self::Material => IconSet::Material,
1392            Self::Lucide => IconSet::Lucide,
1393        }
1394    }
1395
1396    /// The freedesktop theme name to pass to [`FreedesktopLoader::theme`], if any.
1397    ///
1398    /// Returns `Some(name)` for [`Default`](Self::Default) and
1399    /// [`Freedesktop`](Self::Freedesktop) variants.
1400    /// Returns `None` for [`System`](Self::System), [`Material`](Self::Material),
1401    /// [`Lucide`](Self::Lucide).
1402    ///
1403    /// The caller is responsible for only passing the result to
1404    /// [`FreedesktopLoader::theme`] when the effective icon set is
1405    /// [`IconSet::Freedesktop`].  For bundled sets (Material, Lucide),
1406    /// the theme name is not used by the loader.
1407    #[must_use]
1408    pub fn freedesktop_theme(&self) -> Option<&str> {
1409        match self {
1410            Self::Default(name) | Self::Freedesktop(name) => Some(name),
1411            Self::System | Self::Material | Self::Lucide => None,
1412        }
1413    }
1414
1415    /// Whether this choice should be re-derived when the theme changes.
1416    ///
1417    /// Only [`Default`](Self::Default) follows the preset.  All others
1418    /// are explicit user choices that must be preserved.
1419    #[must_use]
1420    pub fn follows_preset(&self) -> bool {
1421        matches!(self, Self::Default(_))
1422    }
1423}
1424
1425/// Determine the default icon set choice for a theme.
1426///
1427/// When the TOML specifies `icon_theme` (`Some`) and the theme is
1428/// available, returns
1429/// [`IconSetChoice::Default(icon_theme)`](IconSetChoice::Default). Material
1430/// and Lucide are always available; SF Symbols only on macOS and Segoe
1431/// Fluent only on Windows, each with the `system-icons` feature, where its
1432/// loader is compiled; a freedesktop theme when
1433/// [`is_freedesktop_theme_available`] says so.
1434///
1435/// When the TOML does not specify `icon_theme` (`None`), or the
1436/// specified set or theme is not available, returns
1437/// [`IconSetChoice::System`].
1438#[must_use]
1439pub fn default_icon_choice(icon_set: IconSet, icon_theme: Option<&str>) -> IconSetChoice {
1440    let Some(theme) = icon_theme else {
1441        return IconSetChoice::System;
1442    };
1443    // All five IconSet variants listed explicitly -- no wildcard.
1444    // Adding a new variant produces a compiler error, forcing the author
1445    // to decide whether the new set's theme is "always available" or
1446    // needs a runtime check.
1447    let available = match icon_set {
1448        IconSet::Material | IconSet::Lucide => true,
1449        IconSet::Freedesktop => is_freedesktop_theme_available(theme),
1450        IconSet::SfSymbols => cfg!(all(target_os = "macos", feature = "system-icons")),
1451        IconSet::SegoeFluent => cfg!(all(target_os = "windows", feature = "system-icons")),
1452    };
1453    if available {
1454        IconSetChoice::Default(theme.to_string())
1455    } else {
1456        IconSetChoice::System
1457    }
1458}
1459
1460/// List installed freedesktop icon themes.
1461///
1462/// The themes [`is_freedesktop_theme_available`] reports installed, from
1463/// the same snapshot: each theme whose first `index.theme` in the icon base
1464/// directories the freedesktop icon lookup searches (`~/.icons/`,
1465/// `$XDG_DATA_HOME/icons/`, then `$XDG_DATA_DIRS/icons/`) lists
1466/// `Directories` in its `[Icon Theme]` group (the Icon Theme
1467/// Specification requires the key), which leaves out cursor-only themes and
1468/// themes that only inherit, such as `default`. The snapshot is taken once
1469/// per process, so a theme installed after it is not listed until the
1470/// process restarts.
1471///
1472/// Excludes `hicolor` (the specification's shared theme for application
1473/// icons, which native-theme's icon lookup never falls back to). Returns a
1474/// sorted list of theme directory names; a directory that cannot be read is
1475/// skipped. Returns an empty `Vec` on non-Linux platforms.
1476///
1477/// Note: themes installed via Flatpak or Snap may reside outside
1478/// standard XDG paths and will not be discovered.
1479#[must_use]
1480pub fn list_freedesktop_themes() -> Vec<String> {
1481    #[cfg(target_os = "linux")]
1482    {
1483        installed_themes()
1484            .iter()
1485            .filter(|theme| *theme != "hicolor")
1486            .cloned()
1487            .collect()
1488    }
1489    #[cfg(not(target_os = "linux"))]
1490    {
1491        Vec::new()
1492    }
1493}
1494
1495// =============================================================================
1496// Tests
1497// =============================================================================
1498
1499#[cfg(test)]
1500#[allow(clippy::unwrap_used, clippy::expect_used)]
1501mod load_icon_tests {
1502    use super::*;
1503
1504    #[cfg(all(target_os = "linux", feature = "system-icons"))]
1505    fn undetected() -> crate::Result<String> {
1506        Err(crate::Error::PlatformUnsupported {
1507            platform: "the test's failing detection",
1508        })
1509    }
1510
1511    /// With no theme set and no icon theme detected, nothing loads: no
1512    /// theme stands in for the one that could not be detected.
1513    #[test]
1514    #[cfg(all(target_os = "linux", feature = "system-icons"))]
1515    fn freedesktop_loader_without_a_detected_theme_loads_nothing() {
1516        let custom: &dyn IconProvider = &IconRole::ActionCopy;
1517        for id in [
1518            IconId::Role(IconRole::ActionCopy),
1519            IconId::Name("edit-copy"),
1520            IconId::Custom(custom),
1521        ] {
1522            assert!(
1523                FreedesktopLoader::new(id).load_with(undetected).is_none(),
1524                "an icon loaded though no icon theme was detected"
1525            );
1526        }
1527    }
1528
1529    /// A custom provider's own freedesktop SVG depends on no theme, so it
1530    /// still loads where no icon theme was detected; only the lookup of its
1531    /// freedesktop name in a theme is skipped.
1532    #[test]
1533    #[cfg(all(target_os = "linux", feature = "system-icons"))]
1534    fn freedesktop_loader_without_a_detected_theme_gives_a_providers_own_svg() {
1535        #[derive(Debug)]
1536        struct AppIcon;
1537        impl IconProvider for AppIcon {
1538            fn icon_name(&self, _set: IconSet) -> Option<&str> {
1539                Some("edit-copy")
1540            }
1541            fn icon_svg(&self, set: IconSet) -> Option<Cow<'static, [u8]>> {
1542                (set == IconSet::Freedesktop).then_some(Cow::Borrowed(b"<svg>app</svg>"))
1543            }
1544        }
1545
1546        let provider: &dyn IconProvider = &AppIcon;
1547        assert_eq!(
1548            FreedesktopLoader::new(provider).load_with(undetected),
1549            Some(IconData::Svg(Cow::Borrowed(b"<svg>app</svg>"))),
1550            "the provider's own SVG did not load without a detected icon theme"
1551        );
1552    }
1553
1554    /// A generated icon enum (native-theme-build) is handed to a loader by
1555    /// reference, as its README shows: `MaterialLoader::new(&AppIcon::X)`.
1556    #[test]
1557    #[cfg(feature = "material-icons")]
1558    fn a_provider_is_passed_to_a_loader_by_reference() {
1559        #[derive(Debug)]
1560        struct AppIcon;
1561        impl IconProvider for AppIcon {
1562            fn icon_name(&self, _set: IconSet) -> Option<&str> {
1563                None
1564            }
1565            fn icon_svg(&self, set: IconSet) -> Option<Cow<'static, [u8]>> {
1566                (set == IconSet::Material).then_some(Cow::Borrowed(b"<svg>app</svg>"))
1567            }
1568        }
1569
1570        assert_eq!(
1571            MaterialLoader::new(&AppIcon).load(),
1572            Some(IconData::Svg(Cow::Borrowed(b"<svg>app</svg>"))),
1573            "a provider passed by reference did not load its own SVG"
1574        );
1575    }
1576
1577    /// An explicit theme needs no detection: the detector never runs.
1578    #[test]
1579    #[cfg(all(target_os = "linux", feature = "system-icons"))]
1580    fn freedesktop_loader_with_a_theme_does_not_detect() {
1581        let runs = std::cell::Cell::new(0);
1582        let _ = FreedesktopLoader::new("edit-copy")
1583            .theme("Adwaita")
1584            .load_with(|| {
1585                runs.set(runs.get() + 1);
1586                undetected()
1587            });
1588        assert_eq!(runs.get(), 0, "an explicit theme ran the detection");
1589    }
1590
1591    #[test]
1592    #[cfg(all(target_os = "linux", feature = "system-icons"))]
1593    fn freedesktop_loader_theme_override_honored_for_name_lookup() {
1594        // Regression pin for Phase 93-03 silent-ignore bug (Plan 93-09 fix).
1595        // The old IconLoader dispatched IconId::Name to a path that silently
1596        // dropped `.theme()`. FreedesktopLoader has a single `load()` method
1597        // that honors `.theme()` uniformly across Role/Name/Custom.
1598        //
1599        // Requires the Adwaita icon theme installed on the test host.
1600        let result = FreedesktopLoader::new("format-text-rich")
1601            .theme("Adwaita")
1602            .size(24)
1603            .load();
1604        assert!(
1605            result.is_some(),
1606            "theme('Adwaita') must resolve 'format-text-rich' in Adwaita, regardless of system theme"
1607        );
1608    }
1609
1610    #[test]
1611    #[cfg(feature = "material-icons")]
1612    fn load_icon_material_returns_svg() {
1613        let result = MaterialLoader::new(IconRole::ActionCopy).load();
1614        assert!(result.is_some(), "material ActionCopy should return Some");
1615        match result.unwrap() {
1616            IconData::Svg(ref cow) => {
1617                let s = String::from_utf8_lossy(cow);
1618                assert!(s.contains("<svg"), "should contain SVG data");
1619            }
1620            _ => panic!("expected IconData::Svg for bundled material icon"),
1621        }
1622    }
1623
1624    #[test]
1625    #[cfg(feature = "lucide-icons")]
1626    fn load_icon_lucide_returns_svg() {
1627        let result = LucideLoader::new(IconRole::ActionCopy).load();
1628        assert!(result.is_some(), "lucide ActionCopy should return Some");
1629        match result.unwrap() {
1630            IconData::Svg(ref cow) => {
1631                let s = String::from_utf8_lossy(cow);
1632                assert!(s.contains("<svg"), "should contain SVG data");
1633            }
1634            _ => panic!("expected IconData::Svg for bundled lucide icon"),
1635        }
1636    }
1637
1638    /// A freedesktop icon the system's theme lacks, or asked of a theme that
1639    /// is not installed, is `None`: Material's icon does not stand in. The
1640    /// system's theme `lacking` is a fixture in a child process
1641    /// ([`native_theme_test_fixtures`]) whose one icon, `dialog-error`, loads,
1642    /// so the `None` is a lookup's: it has no `edit-copy`.
1643    #[test]
1644    #[cfg(all(
1645        target_os = "linux",
1646        feature = "system-icons",
1647        feature = "material-icons"
1648    ))]
1649    fn load_icon_unknown_theme_no_cross_set_fallback() -> std::io::Result<()> {
1650        const NAME: &str = "icons::load_icon_tests::load_icon_unknown_theme_no_cross_set_fallback";
1651        const 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>"##;
1652        if native_theme_test_fixtures::in_child() {
1653            assert_eq!(
1654                FreedesktopLoader::new(IconRole::DialogError).load(),
1655                Some(IconData::Svg(Cow::Borrowed(DIALOG_ERROR.as_bytes()))),
1656                "the system's theme is looked up"
1657            );
1658            assert!(MaterialLoader::new(IconRole::ActionCopy).load().is_some());
1659            assert_eq!(
1660                FreedesktopLoader::new(IconRole::ActionCopy).load(),
1661                None,
1662                "the system's theme lacks edit-copy"
1663            );
1664            assert_eq!(
1665                FreedesktopLoader::new(IconRole::ActionCopy)
1666                    .theme("native-theme-no-such-theme")
1667                    .load(),
1668                None,
1669                "the theme given is not installed"
1670            );
1671            return Ok(());
1672        }
1673        let child = native_theme_test_fixtures::Child::kde("lacking");
1674        native_theme_test_fixtures::run(NAME, child, |icons| {
1675            native_theme_test_fixtures::write_scalable_theme(
1676                icons,
1677                "lacking",
1678                &[("dialog-error", DIALOG_ERROR)],
1679            )
1680        })
1681    }
1682
1683    #[test]
1684    #[cfg(feature = "material-icons")]
1685    fn load_icon_all_roles_material() {
1686        // Material has 42 of 42 roles mapped, all return Some
1687        let mut some_count = 0;
1688        for role in IconRole::ALL.iter().copied() {
1689            if MaterialLoader::new(role).load().is_some() {
1690                some_count += 1;
1691            }
1692        }
1693        // bundled_icon_svg covers all 42 roles for Material
1694        assert_eq!(
1695            some_count, 42,
1696            "Material should cover all 42 roles via bundled SVGs"
1697        );
1698    }
1699
1700    #[test]
1701    #[cfg(feature = "lucide-icons")]
1702    fn load_icon_all_roles_lucide() {
1703        let mut some_count = 0;
1704        for role in IconRole::ALL.iter().copied() {
1705            if LucideLoader::new(role).load().is_some() {
1706                some_count += 1;
1707            }
1708        }
1709        // bundled_icon_svg covers all 42 roles for Lucide
1710        assert_eq!(
1711            some_count, 42,
1712            "Lucide should cover all 42 roles via bundled SVGs"
1713        );
1714    }
1715
1716    #[test]
1717    fn freedesktop_loader_stores_the_size_and_colour() {
1718        let loader = FreedesktopLoader::new("edit-copy");
1719        assert_eq!((loader.size, loader.fg_color), (24, None));
1720        let loader = loader.size(48).color(Rgba::new(10, 20, 30, 40));
1721        assert_eq!(loader.size, 48);
1722        assert_eq!(loader.fg_color, Some([10, 20, 30]), "the alpha is ignored");
1723        assert_eq!(loader.color_opt(None).fg_color, None);
1724    }
1725
1726    /// Each system loader's size is clamped to `1..=MAX_ICON_SIZE`.
1727    #[test]
1728    fn the_system_loaders_clamp_the_size() {
1729        for (size, clamped) in [
1730            (0, 1),
1731            (48, 48),
1732            (MAX_ICON_SIZE, MAX_ICON_SIZE),
1733            (MAX_ICON_SIZE + 1, MAX_ICON_SIZE),
1734            (70_000, MAX_ICON_SIZE),
1735            (u32::MAX, MAX_ICON_SIZE),
1736        ] {
1737            assert_eq!(
1738                FreedesktopLoader::new("edit-copy").size(size).size,
1739                clamped,
1740                "freedesktop {size}"
1741            );
1742            assert_eq!(
1743                SfSymbolsLoader::new(IconRole::ActionCopy).size(size).size,
1744                Some(clamped),
1745                "SF Symbols {size}"
1746            );
1747            assert_eq!(
1748                SegoeFluentLoader::new(IconRole::ActionCopy).size(size).size,
1749                Some(clamped),
1750                "Segoe {size}"
1751            );
1752        }
1753    }
1754
1755    #[test]
1756    fn raster_size_in_bound_is_the_decode_bound() {
1757        assert!(!raster_size_in_bound(0));
1758        assert!(raster_size_in_bound(1));
1759        assert!(raster_size_in_bound(4096));
1760        assert!(!raster_size_in_bound(4097));
1761        assert!(!raster_size_in_bound(u32::MAX));
1762    }
1763
1764    #[test]
1765    fn raster_bytes_in_bound_is_the_decode_bound() {
1766        assert_eq!(raster_bytes_in_bound(0, 16), None);
1767        assert_eq!(raster_bytes_in_bound(16, 0), None);
1768        assert_eq!(raster_bytes_in_bound(3, 2), Some(24));
1769        assert_eq!(
1770            raster_bytes_in_bound(8192, 2048),
1771            Some(MAX_ICON_DECODE_BYTES)
1772        );
1773        assert_eq!(raster_bytes_in_bound(8192, 2049), None);
1774        assert_eq!(raster_bytes_in_bound(u32::MAX, u32::MAX), None);
1775    }
1776
1777    #[test]
1778    fn sf_symbols_loader_stores_the_colour() {
1779        let loader = SfSymbolsLoader::new(IconRole::ActionCopy).color(Rgba::new(10, 20, 30, 40));
1780        assert_eq!(loader.fg_color, Some([10, 20, 30]), "the alpha is ignored");
1781        let loader = loader.color_opt(None);
1782        assert_eq!(loader.fg_color, None);
1783        let loader = loader.color_opt(Some(Rgba::rgb(40, 50, 60)));
1784        assert_eq!(loader.fg_color, Some([40, 50, 60]));
1785        assert_eq!(SfSymbolsLoader::new(IconRole::ActionCopy).fg_color, None);
1786    }
1787
1788    #[test]
1789    fn sf_symbols_loader_stores_the_size() {
1790        assert_eq!(SfSymbolsLoader::new(IconRole::ActionCopy).size, None);
1791        assert_eq!(
1792            SfSymbolsLoader::new(IconRole::ActionCopy).size(48).size,
1793            Some(48)
1794        );
1795    }
1796
1797    #[test]
1798    fn segoe_fluent_loader_stores_the_colour() {
1799        let loader = SegoeFluentLoader::new(IconRole::ActionCopy).color(Rgba::new(10, 20, 30, 40));
1800        assert_eq!(loader.fg_color, Some([10, 20, 30]), "the alpha is ignored");
1801        let loader = loader.color_opt(None);
1802        assert_eq!(loader.fg_color, None);
1803        let loader = loader.color_opt(Some(Rgba::rgb(40, 50, 60)));
1804        assert_eq!(loader.fg_color, Some([40, 50, 60]));
1805        assert_eq!(SegoeFluentLoader::new(IconRole::ActionCopy).fg_color, None);
1806    }
1807
1808    #[test]
1809    fn segoe_fluent_loader_stores_the_size() {
1810        assert_eq!(SegoeFluentLoader::new(IconRole::ActionCopy).size, None);
1811        assert_eq!(
1812            SegoeFluentLoader::new(IconRole::ActionCopy).size(48).size,
1813            Some(48)
1814        );
1815    }
1816
1817    /// An SF Symbol loads only on macOS with `system-icons`; elsewhere it is
1818    /// `None`, and no other set's icon stands in.
1819    #[test]
1820    fn an_sf_symbol_loads_only_on_macos_with_system_icons() {
1821        let result = SfSymbolsLoader::new(IconRole::ActionCopy).load();
1822        assert_eq!(
1823            result.is_some(),
1824            cfg!(all(target_os = "macos", feature = "system-icons"))
1825        );
1826    }
1827
1828    #[test]
1829    #[cfg(feature = "material-icons")]
1830    fn bundled_icon_load_produces_cow_borrowed() {
1831        let result = MaterialLoader::new(IconRole::ActionCopy).load();
1832        assert!(
1833            matches!(result, Some(IconData::Svg(Cow::Borrowed(_)))),
1834            "bundled icon should produce Some(IconData::Svg(Cow::Borrowed(_)))"
1835        );
1836    }
1837}
1838
1839#[cfg(test)]
1840#[allow(clippy::unwrap_used, clippy::expect_used)]
1841mod load_system_icon_by_name_tests {
1842    #[test]
1843    #[cfg(feature = "material-icons")]
1844    fn system_icon_by_name_material() {
1845        let result = super::MaterialLoader::new("content_copy").load();
1846        assert!(
1847            result.is_some(),
1848            "content_copy should be found in Material set"
1849        );
1850        assert!(matches!(result.unwrap(), super::IconData::Svg(_)));
1851    }
1852
1853    #[test]
1854    #[cfg(feature = "lucide-icons")]
1855    fn system_icon_by_name_lucide() {
1856        let result = super::LucideLoader::new("copy").load();
1857        assert!(result.is_some(), "copy should be found in Lucide set");
1858        assert!(matches!(result.unwrap(), super::IconData::Svg(_)));
1859    }
1860
1861    #[test]
1862    #[cfg(feature = "material-icons")]
1863    fn system_icon_by_name_unknown_returns_none() {
1864        let result = super::MaterialLoader::new("nonexistent_xyz").load();
1865        assert!(result.is_none(), "nonexistent name should return None");
1866    }
1867
1868    #[test]
1869    fn system_icon_by_name_sf_on_linux_returns_none() {
1870        // On Linux, SfSymbols set is not available (cfg-gated to macOS)
1871        #[cfg(not(target_os = "macos"))]
1872        {
1873            let result = super::SfSymbolsLoader::new("doc.on.doc").load();
1874            assert!(
1875                result.is_none(),
1876                "SF Symbols should return None on non-macOS"
1877            );
1878        }
1879    }
1880}
1881
1882#[cfg(test)]
1883#[allow(clippy::unwrap_used, clippy::expect_used)]
1884mod load_custom_icon_tests {
1885    use super::*;
1886
1887    #[test]
1888    #[cfg(feature = "material-icons")]
1889    fn custom_icon_with_icon_role_material() {
1890        let provider: &dyn IconProvider = &IconRole::ActionCopy;
1891        let result = MaterialLoader::new(provider).load();
1892        assert!(
1893            result.is_some(),
1894            "IconRole::ActionCopy should load via material"
1895        );
1896    }
1897
1898    #[test]
1899    #[cfg(feature = "lucide-icons")]
1900    fn custom_icon_with_icon_role_lucide() {
1901        let provider: &dyn IconProvider = &IconRole::ActionCopy;
1902        let result = LucideLoader::new(provider).load();
1903        assert!(
1904            result.is_some(),
1905            "IconRole::ActionCopy should load via lucide"
1906        );
1907    }
1908
1909    #[test]
1910    fn custom_icon_no_cross_set_fallback() {
1911        // Provider that returns None for all sets -- should NOT fall back
1912        #[derive(Debug)]
1913        struct NullProvider;
1914        impl IconProvider for NullProvider {
1915            fn icon_name(&self, _set: IconSet) -> Option<&str> {
1916                None
1917            }
1918            fn icon_svg(&self, _set: IconSet) -> Option<Cow<'static, [u8]>> {
1919                None
1920            }
1921        }
1922
1923        let provider: &dyn IconProvider = &NullProvider;
1924        let result = MaterialLoader::new(provider).load();
1925        assert!(
1926            result.is_none(),
1927            "NullProvider should return None (no cross-set fallback)"
1928        );
1929    }
1930
1931    /// A provider that names and draws its icon for Material only has no
1932    /// freedesktop icon: its Material name and SVG do not stand in.
1933    #[test]
1934    fn a_custom_freedesktop_icon_does_not_take_the_providers_material_icon() {
1935        #[derive(Debug)]
1936        struct MaterialOnly;
1937        impl IconProvider for MaterialOnly {
1938            fn icon_name(&self, set: IconSet) -> Option<&str> {
1939                (set == IconSet::Material).then_some("content_copy")
1940            }
1941            fn icon_svg(&self, set: IconSet) -> Option<Cow<'static, [u8]>> {
1942                (set == IconSet::Material).then_some(Cow::Borrowed(
1943                    br#"<svg xmlns="http://www.w3.org/2000/svg"/>"#,
1944                ))
1945            }
1946        }
1947
1948        let provider: &dyn IconProvider = &MaterialOnly;
1949        #[cfg(feature = "material-icons")]
1950        assert!(MaterialLoader::new(provider).load().is_some());
1951        assert_eq!(FreedesktopLoader::new(provider).load(), None);
1952    }
1953
1954    #[test]
1955    #[cfg(feature = "material-icons")]
1956    fn custom_icon_via_dyn_dispatch() {
1957        let boxed: Box<dyn IconProvider> = Box::new(IconRole::ActionCopy);
1958        let provider: &dyn IconProvider = &*boxed;
1959        let result = MaterialLoader::new(provider).load();
1960        assert!(
1961            result.is_some(),
1962            "dyn dispatch through Box<dyn IconProvider> should work"
1963        );
1964    }
1965
1966    #[test]
1967    #[cfg(feature = "material-icons")]
1968    fn custom_icon_bundled_svg_fallback() {
1969        // Provider that returns None from icon_name but Some from icon_svg
1970        #[derive(Debug)]
1971        struct SvgOnlyProvider;
1972        impl IconProvider for SvgOnlyProvider {
1973            fn icon_name(&self, _set: IconSet) -> Option<&str> {
1974                None
1975            }
1976            fn icon_svg(&self, _set: IconSet) -> Option<Cow<'static, [u8]>> {
1977                Some(Cow::Borrowed(b"<svg>test</svg>"))
1978            }
1979        }
1980
1981        let provider: &dyn IconProvider = &SvgOnlyProvider;
1982        let result = MaterialLoader::new(provider).load();
1983        assert!(
1984            result.is_some(),
1985            "provider with icon_svg should return Some"
1986        );
1987        match result.unwrap() {
1988            IconData::Svg(ref cow) => {
1989                assert_eq!(cow.as_ref(), b"<svg>test</svg>");
1990            }
1991            _ => panic!("expected IconData::Svg"),
1992        }
1993    }
1994}
1995
1996#[cfg(test)]
1997#[allow(clippy::unwrap_used, clippy::expect_used)]
1998mod runtime_set_icon_tests {
1999    use super::*;
2000
2001    // Test fixture colour, not a theme value.
2002    const COLOR: Rgba = Rgba::rgb(0x12, 0x34, 0x56);
2003
2004    fn svg_text(data: IconData) -> String {
2005        match data {
2006            IconData::Svg(svg) => String::from_utf8(svg.into_owned()).unwrap(),
2007            other => panic!("expected IconData::Svg, got {other:?}"),
2008        }
2009    }
2010
2011    #[derive(Debug)]
2012    struct SvgOnlyProvider;
2013    impl IconProvider for SvgOnlyProvider {
2014        fn icon_name(&self, _set: IconSet) -> Option<&str> {
2015            None
2016        }
2017        fn icon_svg(&self, _set: IconSet) -> Option<Cow<'static, [u8]>> {
2018            Some(Cow::Borrowed(
2019                b"<svg viewBox=\"0 0 24 24\"><path d=\"M0 0\"/></svg>",
2020            ))
2021        }
2022    }
2023
2024    #[test]
2025    #[cfg(feature = "material-icons")]
2026    fn material_role_comes_back_in_the_colour() {
2027        let svg = svg_text(
2028            load_custom_icon(&IconRole::ActionCopy, IconSet::Material, Some(COLOR), None).unwrap(),
2029        );
2030        assert!(
2031            svg.contains("#123456"),
2032            "colour written into the bytes: {svg}"
2033        );
2034    }
2035
2036    #[test]
2037    #[cfg(feature = "lucide-icons")]
2038    fn lucide_role_comes_back_in_the_colour() {
2039        let svg = svg_text(
2040            load_custom_icon(&IconRole::ActionCopy, IconSet::Lucide, Some(COLOR), None).unwrap(),
2041        );
2042        assert!(
2043            svg.contains("#123456"),
2044            "colour written into the bytes: {svg}"
2045        );
2046        assert!(!svg.contains("currentColor"), "{svg}");
2047    }
2048
2049    #[test]
2050    #[cfg(feature = "material-icons")]
2051    fn no_colour_leaves_the_bundled_bytes() {
2052        let loaded =
2053            load_custom_icon(&IconRole::ActionCopy, IconSet::Material, None, None).unwrap();
2054        assert_eq!(
2055            loaded,
2056            MaterialLoader::new(IconRole::ActionCopy).load().unwrap()
2057        );
2058    }
2059
2060    #[test]
2061    fn provider_svg_comes_back_in_the_colour() {
2062        for set in [
2063            IconSet::Freedesktop,
2064            IconSet::SfSymbols,
2065            IconSet::SegoeFluent,
2066            IconSet::Material,
2067            IconSet::Lucide,
2068        ] {
2069            let svg = svg_text(load_custom_icon(&SvgOnlyProvider, set, Some(COLOR), None).unwrap());
2070            assert!(svg.contains("fill=\"#123456\""), "{set:?}: {svg}");
2071        }
2072    }
2073
2074    /// A provider whose freedesktop name is `edit-copy`, with `self.0` as its
2075    /// own SVG.
2076    #[derive(Debug)]
2077    struct EditCopy(Option<&'static [u8]>);
2078    impl IconProvider for EditCopy {
2079        fn icon_name(&self, _set: IconSet) -> Option<&str> {
2080            Some("edit-copy")
2081        }
2082        fn icon_svg(&self, _set: IconSet) -> Option<Cow<'static, [u8]>> {
2083            self.0.map(Cow::Borrowed)
2084        }
2085    }
2086
2087    /// In an icon theme that is not installed the provider's name finds
2088    /// nothing, and its own SVG, where it has one, is the icon. On every
2089    /// host: the theme given is the only one searched.
2090    #[test]
2091    fn a_custom_icon_missing_from_the_icon_theme_given_is_the_providers_own() {
2092        let missing = Some("native-theme-no-such-theme");
2093        assert!(
2094            load_custom_icon_in(&EditCopy(None), IconSet::Freedesktop, missing, None, None)
2095                .is_none()
2096        );
2097        let own = b"<svg viewBox=\"0 0 24 24\"><path d=\"M0 0\"/></svg>";
2098        assert_eq!(
2099            load_custom_icon_in(
2100                &EditCopy(Some(own)),
2101                IconSet::Freedesktop,
2102                missing,
2103                None,
2104                None
2105            ),
2106            Some(IconData::Svg(Cow::Borrowed(own)))
2107        );
2108    }
2109
2110    /// A custom icon is loaded at a size clamped to `1..=MAX_ICON_SIZE`: a
2111    /// freedesktop lookup at 99 999 is made at 512, so it takes the theme's
2112    /// 512 directory, not its 1024 one, and one at 0 is made at 1, taking the
2113    /// 1 directory, not the 0 one. The theme is a fixture in a child process
2114    /// ([`native_theme_test_fixtures`]).
2115    #[cfg(all(target_os = "linux", feature = "system-icons"))]
2116    #[test]
2117    fn a_custom_icon_is_loaded_at_a_clamped_size() -> std::io::Result<()> {
2118        const NAME: &str =
2119            "icons::runtime_set_icon_tests::a_custom_icon_is_loaded_at_a_clamped_size";
2120        const ZERO: &str = r##"<svg xmlns="http://www.w3.org/2000/svg"/>"##;
2121        const SMALL: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 1"/>"##;
2122        const AT_512: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"/>"##;
2123        const AT_1024: &str =
2124            r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024"/>"##;
2125        if native_theme_test_fixtures::in_child() {
2126            let svg = |svg: &'static str| Some(IconData::Svg(Cow::Borrowed(svg.as_bytes())));
2127            let load = |size| {
2128                load_custom_icon_in(
2129                    &EditCopy(None),
2130                    IconSet::Freedesktop,
2131                    None,
2132                    None,
2133                    Some(size),
2134                )
2135            };
2136            assert_eq!(load(99_999), svg(AT_512), "asked for 99999");
2137            assert_eq!(load(MAX_ICON_SIZE + 1), svg(AT_512), "asked for 513");
2138            assert_eq!(load(1024), svg(AT_512), "asked for 1024");
2139            assert_eq!(load(0), svg(SMALL), "asked for 0");
2140            return Ok(());
2141        }
2142        let child = native_theme_test_fixtures::Child::kde("sized");
2143        native_theme_test_fixtures::run(NAME, child, |icons| {
2144            native_theme_test_fixtures::write_fixed_theme(
2145                icons,
2146                "sized",
2147                &[
2148                    (0, "edit-copy.svg", ZERO.as_bytes()),
2149                    (1, "edit-copy.svg", SMALL.as_bytes()),
2150                    (512, "edit-copy.svg", AT_512.as_bytes()),
2151                    (1024, "edit-copy.svg", AT_1024.as_bytes()),
2152                ],
2153            )
2154        })
2155    }
2156
2157    /// A freedesktop icon is looked up in the icon theme given and no
2158    /// other: the given theme's own icon is the one loaded, and in one that
2159    /// is not installed the provider's name finds nothing though the
2160    /// system's theme has it. The themes are fixtures in a child process
2161    /// ([`native_theme_test_fixtures`]), the system's `system`.
2162    #[cfg(all(target_os = "linux", feature = "system-icons"))]
2163    #[test]
2164    fn a_custom_icon_is_looked_up_in_the_icon_theme_given() -> std::io::Result<()> {
2165        const NAME: &str =
2166            "icons::runtime_set_icon_tests::a_custom_icon_is_looked_up_in_the_icon_theme_given";
2167        const SYSTEM: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill="#3daee9" d="M2 2h12v12H2z"/></svg>"##;
2168        const CHOSEN: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill="#e01b24" d="M2 2h12v12H2z"/></svg>"##;
2169        if native_theme_test_fixtures::in_child() {
2170            let svg = |svg: &'static str| Some(IconData::Svg(Cow::Borrowed(svg.as_bytes())));
2171            let load = |theme| {
2172                load_custom_icon_in(&EditCopy(None), IconSet::Freedesktop, theme, None, None)
2173            };
2174            assert_eq!(load(None), svg(SYSTEM), "the system's theme");
2175            assert_eq!(load(Some("chosen")), svg(CHOSEN));
2176            assert_eq!(
2177                load(Some("native-theme-no-such-theme")),
2178                None,
2179                "an icon the theme given lacks is not taken from the system's"
2180            );
2181            return Ok(());
2182        }
2183        let child = native_theme_test_fixtures::Child::kde("system");
2184        native_theme_test_fixtures::run(NAME, child, |icons| {
2185            native_theme_test_fixtures::write_scalable_theme(
2186                icons,
2187                "system",
2188                &[("edit-copy", SYSTEM)],
2189            )?;
2190            native_theme_test_fixtures::write_scalable_theme(
2191                icons,
2192                "chosen",
2193                &[("edit-copy", CHOSEN)],
2194            )
2195        })
2196    }
2197
2198    #[test]
2199    #[cfg(feature = "material-icons")]
2200    fn a_themeless_set_ignores_the_icon_theme() {
2201        assert_eq!(
2202            load_custom_icon_in(
2203                &IconRole::ActionCopy,
2204                IconSet::Material,
2205                Some("breeze"),
2206                Some(COLOR),
2207                None
2208            ),
2209            load_custom_icon(&IconRole::ActionCopy, IconSet::Material, Some(COLOR), None)
2210        );
2211    }
2212
2213    #[test]
2214    fn unsized_provider_is_accepted() {
2215        let provider: &dyn IconProvider = &SvgOnlyProvider;
2216        assert!(load_custom_icon(provider, IconSet::Material, None, None).is_some());
2217    }
2218
2219    #[test]
2220    #[cfg(feature = "material-icons")]
2221    fn custom_id_in_the_dispatcher_is_coloured() {
2222        let provider: &dyn IconProvider = &IconRole::ActionCopy;
2223        let svg = svg_text(
2224            load_icon_in(
2225                IconId::Custom(provider),
2226                IconSet::Material,
2227                None,
2228                Some(COLOR),
2229                None,
2230            )
2231            .unwrap(),
2232        );
2233        assert!(svg.contains("#123456"), "{svg}");
2234    }
2235
2236    #[test]
2237    fn provider_with_nothing_is_none() {
2238        #[derive(Debug)]
2239        struct NullProvider;
2240        impl IconProvider for NullProvider {
2241            fn icon_name(&self, _set: IconSet) -> Option<&str> {
2242                None
2243            }
2244            fn icon_svg(&self, _set: IconSet) -> Option<Cow<'static, [u8]>> {
2245                None
2246            }
2247        }
2248        assert!(load_custom_icon(&NullProvider, IconSet::Material, Some(COLOR), None).is_none());
2249    }
2250
2251    /// The SVG's text; empty for an icon that is not an SVG, which then
2252    /// fails the comparison.
2253    fn svg_of(data: IconData) -> String {
2254        match data {
2255            IconData::Svg(svg) => String::from_utf8_lossy(&svg).into_owned(),
2256            _ => String::new(),
2257        }
2258    }
2259
2260    /// A freedesktop SVG whose `currentColor` nothing in the document
2261    /// resolves is filled in with the colour asked for (M5-04): a rasteriser
2262    /// draws an unset `currentColor` black.
2263    #[test]
2264    fn a_freedesktop_svg_s_bare_current_color_is_filled_in_the_colour() {
2265        let bare = br#"<svg xmlns="http://www.w3.org/2000/svg"><path fill="currentColor" d="M0 0h16v16H0z"/></svg>"#;
2266        let filled = fill_freedesktop_svg_data(IconData::Svg(Cow::Borrowed(bare)), Some(COLOR));
2267        assert_eq!(
2268            svg_of(filled),
2269            r##"<svg xmlns="http://www.w3.org/2000/svg"><path fill="#123456" d="M0 0h16v16H0z"/></svg>"##
2270        );
2271    }
2272
2273    /// A freedesktop SVG whose own stylesheet sets the `color` its
2274    /// `currentColor` takes (Breeze's `current-color-scheme`), and a
2275    /// full-colour one, come back as they loaded, colour or not; so does
2276    /// any icon loaded with no colour.
2277    #[test]
2278    fn a_freedesktop_svg_with_its_own_colour_is_left_as_it_is() {
2279        let styled = br#"<svg xmlns="http://www.w3.org/2000/svg"><style id="current-color-scheme">.ColorScheme-Text { color:#232629; }</style><path class="ColorScheme-Text" style="fill:currentColor" d="M0 0h16v16H0z"/></svg>"#;
2280        let full_colour = br##"<svg xmlns="http://www.w3.org/2000/svg"><path fill="#3daee9" d="M0 0h16v16H0z"/><path fill="#ffffff" d="M2 2h4v4H2z"/></svg>"##;
2281        let bare = br#"<svg xmlns="http://www.w3.org/2000/svg"><path fill="currentColor" d="M0 0h16v16H0z"/></svg>"#;
2282        for (svg, color) in [
2283            (&styled[..], Some(COLOR)),
2284            (&full_colour[..], Some(COLOR)),
2285            (&bare[..], None),
2286        ] {
2287            let data = fill_freedesktop_svg_data(IconData::Svg(Cow::Borrowed(svg)), color);
2288            assert_eq!(svg_of(data), String::from_utf8_lossy(svg));
2289        }
2290    }
2291
2292    #[test]
2293    #[cfg(feature = "material-icons")]
2294    fn indicator_of_a_themeless_set_ignores_the_theme() {
2295        assert_eq!(
2296            load_icon_indicator(IconSet::Material, Some("breeze")),
2297            load_icon_indicator(IconSet::Material, None)
2298        );
2299    }
2300}
2301
2302#[cfg(test)]
2303#[allow(clippy::unwrap_used, clippy::expect_used)]
2304mod loading_indicator_tests {
2305    use super::*;
2306
2307    // === Dispatch tests (through per-set loader API) ===
2308
2309    #[test]
2310    #[cfg(feature = "lucide-icons")]
2311    fn loading_indicator_lucide_returns_frames() {
2312        let anim = LucideLoader::load_indicator();
2313        assert!(anim.is_some(), "lucide should return Some");
2314        let anim = anim.unwrap();
2315        assert!(
2316            matches!(anim, AnimatedIcon::Frames(_)),
2317            "lucide should be pre-rotated Frames"
2318        );
2319        if let AnimatedIcon::Frames(data) = &anim {
2320            assert_eq!(data.frames().len(), 24);
2321            assert_eq!(data.frame_duration_ms().get(), 42);
2322        }
2323    }
2324
2325    /// Freedesktop loading_indicator returns Some if the active icon theme
2326    /// has a `process-working` sprite sheet (e.g. Breeze), None otherwise.
2327    #[test]
2328    #[cfg(all(target_os = "linux", feature = "system-icons"))]
2329    fn loading_indicator_freedesktop_depends_on_theme() {
2330        let anim = FreedesktopLoader::load_indicator(None);
2331        // Result depends on installed icon theme -- Some if process-working exists
2332        if let Some(anim) = anim {
2333            match anim {
2334                AnimatedIcon::Frames(data) => {
2335                    assert!(
2336                        !data.frames().is_empty(),
2337                        "Frames variant should have at least one frame"
2338                    );
2339                }
2340                AnimatedIcon::Transform(_) => {
2341                    // Single-frame theme icon with Spin -- valid result
2342                }
2343            }
2344        }
2345    }
2346
2347    /// Freedesktop spinner depends on platform and icon theme.
2348    #[test]
2349    fn loading_indicator_freedesktop_does_not_panic() {
2350        let _result = FreedesktopLoader::load_indicator(None);
2351    }
2352
2353    // === Direct spinner construction tests (any platform) ===
2354
2355    #[test]
2356    #[cfg(feature = "lucide-icons")]
2357    fn lucide_spinner_is_frames() {
2358        let anim = crate::spinners::lucide_spinner();
2359        assert!(
2360            matches!(anim, AnimatedIcon::Frames(_)),
2361            "lucide should be pre-rotated Frames"
2362        );
2363    }
2364}
2365
2366// === New builder API tests ===
2367
2368#[cfg(test)]
2369#[allow(clippy::unwrap_used, clippy::expect_used)]
2370mod icon_loader_tests {
2371    use super::*;
2372
2373    #[test]
2374    #[cfg(feature = "material-icons")]
2375    fn icon_loader_basic_role() {
2376        let icon = MaterialLoader::new(IconRole::ActionCopy).load();
2377        assert!(icon.is_some());
2378    }
2379
2380    #[test]
2381    #[cfg(feature = "material-icons")]
2382    fn icon_loader_by_name() {
2383        let icon = MaterialLoader::new("content_copy").load();
2384        assert!(icon.is_some());
2385    }
2386
2387    #[test]
2388    #[cfg(feature = "material-icons")]
2389    fn icon_loader_custom_provider() {
2390        let provider: &dyn IconProvider = &IconRole::ActionCopy;
2391        let icon = MaterialLoader::new(provider).load();
2392        assert!(icon.is_some());
2393    }
2394
2395    #[test]
2396    #[cfg(all(target_os = "linux", feature = "system-icons"))]
2397    fn freedesktop_loader_builder_chain_compiles() {
2398        // Smoke test: the builder chain constructs without runtime errors.
2399        // Size propagates through; the actual load result depends on the
2400        // system theme having 'document-save' at size 48.
2401        let _ = FreedesktopLoader::new(IconRole::ActionSave)
2402            .size(48)
2403            .color(Rgba::rgb(0, 0, 0))
2404            .theme("Adwaita")
2405            .load();
2406    }
2407
2408    #[test]
2409    #[cfg(feature = "material-icons")]
2410    fn icon_loader_load_indicator() {
2411        let anim = MaterialLoader::load_indicator();
2412        assert!(anim.is_some());
2413    }
2414
2415    #[test]
2416    fn load_icon_free_fn_dispatches() {
2417        let role = IconRole::ActionCopy;
2418        for (set, loaded) in [
2419            (IconSet::Freedesktop, FreedesktopLoader::new(role).load()),
2420            (IconSet::SfSymbols, SfSymbolsLoader::new(role).load()),
2421            (IconSet::SegoeFluent, SegoeFluentLoader::new(role).load()),
2422            (IconSet::Material, MaterialLoader::new(role).load()),
2423            (IconSet::Lucide, LucideLoader::new(role).load()),
2424        ] {
2425            assert_eq!(load_icon(role, set), loaded, "{set}");
2426        }
2427        #[cfg(all(feature = "material-icons", feature = "lucide-icons"))]
2428        assert_ne!(
2429            load_icon(role, IconSet::Material),
2430            load_icon(role, IconSet::Lucide)
2431        );
2432    }
2433
2434    #[test]
2435    fn load_icon_indicator_free_fn_dispatches() {
2436        // SfSymbols and SegoeFluent have no spinner primitive.
2437        assert!(load_icon_indicator(IconSet::SfSymbols, None).is_none());
2438        assert!(load_icon_indicator(IconSet::SegoeFluent, None).is_none());
2439    }
2440}
2441
2442#[cfg(all(test, feature = "svg-rasterize", feature = "lucide-icons"))]
2443#[allow(clippy::unwrap_used, clippy::expect_used)]
2444mod spinner_rasterize_tests {
2445    use super::*;
2446
2447    #[test]
2448    fn lucide_spinner_icon_rasterizes() {
2449        let anim = crate::spinners::lucide_spinner();
2450        if let AnimatedIcon::Frames(data) = &anim {
2451            let first = data.frames().first();
2452            if let IconData::Svg(cow) = first {
2453                let result = crate::rasterize::rasterize_svg(cow, 24);
2454                assert!(result.is_ok(), "lucide loader should rasterize");
2455                if let Ok(IconData::Rgba(rgba)) = &result {
2456                    assert!(
2457                        rgba.data().iter().any(|&b| b != 0),
2458                        "lucide loader rasterized to empty image"
2459                    );
2460                }
2461            } else {
2462                panic!("lucide spinner frame should be Svg");
2463            }
2464        } else {
2465            panic!("lucide spinner should be Frames");
2466        }
2467    }
2468}
2469
2470// =============================================================================
2471// IconSetChoice tests
2472// =============================================================================
2473
2474#[cfg(test)]
2475mod icon_set_choice_tests {
2476    use super::*;
2477
2478    #[test]
2479    fn system_choice_names_the_detected_theme() {
2480        assert_eq!(
2481            system_choice_label(&Ok("breeze-dark".to_string())),
2482            "system (breeze-dark)"
2483        );
2484    }
2485
2486    #[test]
2487    fn system_choice_shows_a_failed_detection_as_unavailable() {
2488        let label = system_choice_label(&Err(crate::Error::PlatformUnsupported {
2489            platform: "the test's failing detection",
2490        }));
2491        assert_eq!(label, "system (unavailable)");
2492    }
2493
2494    /// The label is short whatever the failure: no reader's error, which
2495    /// can run to several paths and a command line, reaches it.
2496    /// `system_icon_theme()` gives the reason.
2497    #[test]
2498    fn a_failed_detections_label_leaves_the_reason_out() {
2499        let failures = [
2500            crate::Error::PlatformUnsupported {
2501                platform: "the test's failing detection",
2502            },
2503            crate::Error::WatchUnavailable {
2504                reason: "a reason long enough to fill a drop-down twice over",
2505            },
2506        ];
2507        for failure in failures {
2508            let reason = failure.to_string();
2509            let label = system_choice_label(&Err(failure));
2510            assert_eq!(label, "system (unavailable)", "for {reason:?}");
2511            assert!(!label.contains(&reason), "{label:?} quotes {reason:?}");
2512        }
2513    }
2514
2515    #[test]
2516    fn test_icon_set_choice_display_default() {
2517        let choice = IconSetChoice::Default("Adwaita".to_string());
2518        assert_eq!(choice.to_string(), "default (Adwaita)");
2519    }
2520
2521    #[test]
2522    fn test_icon_set_choice_display_material() {
2523        assert_eq!(IconSetChoice::Material.to_string(), "Material (bundled)");
2524    }
2525
2526    #[test]
2527    fn test_icon_set_choice_display_lucide() {
2528        assert_eq!(IconSetChoice::Lucide.to_string(), "Lucide (bundled)");
2529    }
2530
2531    #[test]
2532    fn test_icon_set_choice_display_freedesktop() {
2533        let choice = IconSetChoice::Freedesktop("breeze".to_string());
2534        assert_eq!(choice.to_string(), "breeze");
2535    }
2536
2537    #[test]
2538    fn test_icon_set_choice_follows_preset() {
2539        assert!(IconSetChoice::Default("Adwaita".to_string()).follows_preset());
2540        assert!(!IconSetChoice::System.follows_preset());
2541        assert!(!IconSetChoice::Freedesktop("breeze".to_string()).follows_preset());
2542        assert!(!IconSetChoice::Material.follows_preset());
2543        assert!(!IconSetChoice::Lucide.follows_preset());
2544    }
2545
2546    #[test]
2547    fn test_icon_set_choice_effective_icon_set() {
2548        // Default returns whatever the theme specifies
2549        let choice = IconSetChoice::Default("Adwaita".to_string());
2550        assert_eq!(
2551            choice.effective_icon_set(IconSet::Freedesktop),
2552            IconSet::Freedesktop
2553        );
2554        assert_eq!(
2555            choice.effective_icon_set(IconSet::Material),
2556            IconSet::Material
2557        );
2558
2559        // System returns the platform's icon set
2560        let sys = IconSetChoice::System.effective_icon_set(IconSet::Material);
2561        assert_eq!(sys, system_icon_set());
2562
2563        // Freedesktop always returns Freedesktop
2564        let choice = IconSetChoice::Freedesktop("breeze".to_string());
2565        assert_eq!(
2566            choice.effective_icon_set(IconSet::Material),
2567            IconSet::Freedesktop
2568        );
2569
2570        // Bundled sets return themselves
2571        assert_eq!(
2572            IconSetChoice::Material.effective_icon_set(IconSet::Freedesktop),
2573            IconSet::Material
2574        );
2575        assert_eq!(
2576            IconSetChoice::Lucide.effective_icon_set(IconSet::Freedesktop),
2577            IconSet::Lucide
2578        );
2579    }
2580
2581    #[test]
2582    fn test_icon_set_choice_freedesktop_theme() {
2583        assert_eq!(
2584            IconSetChoice::Default("Adwaita".to_string()).freedesktop_theme(),
2585            Some("Adwaita")
2586        );
2587        assert_eq!(
2588            IconSetChoice::Freedesktop("breeze".to_string()).freedesktop_theme(),
2589            Some("breeze")
2590        );
2591        assert_eq!(IconSetChoice::System.freedesktop_theme(), None);
2592        assert_eq!(IconSetChoice::Material.freedesktop_theme(), None);
2593        assert_eq!(IconSetChoice::Lucide.freedesktop_theme(), None);
2594    }
2595
2596    #[test]
2597    fn test_default_icon_choice_none() {
2598        // When icon_theme is None, always returns System regardless of icon_set
2599        assert_eq!(
2600            default_icon_choice(IconSet::Freedesktop, None),
2601            IconSetChoice::System
2602        );
2603        assert_eq!(
2604            default_icon_choice(IconSet::Material, None),
2605            IconSetChoice::System
2606        );
2607    }
2608
2609    #[test]
2610    fn test_default_icon_choice_bundled() {
2611        // Material and Lucide are always available
2612        assert_eq!(
2613            default_icon_choice(IconSet::Material, Some("any-theme")),
2614            IconSetChoice::Default("any-theme".to_string())
2615        );
2616        assert_eq!(
2617            default_icon_choice(IconSet::Lucide, Some("any-theme")),
2618            IconSetChoice::Default("any-theme".to_string())
2619        );
2620    }
2621
2622    /// SF Symbols and Segoe Fluent are available only where their loader is
2623    /// compiled; anywhere else their theme is not taken as the default.
2624    #[test]
2625    fn system_sets_are_available_only_where_their_loader_is_compiled() {
2626        let default =
2627            |set| default_icon_choice(set, Some("x")) == IconSetChoice::Default("x".into());
2628        assert_eq!(
2629            default(IconSet::SfSymbols),
2630            cfg!(all(target_os = "macos", feature = "system-icons"))
2631        );
2632        assert_eq!(
2633            default(IconSet::SegoeFluent),
2634            cfg!(all(target_os = "windows", feature = "system-icons"))
2635        );
2636    }
2637
2638    #[test]
2639    fn test_list_freedesktop_themes_no_panic() {
2640        // Just verify it doesn't panic -- result varies by platform
2641        let themes = list_freedesktop_themes();
2642        // On Linux, should return a non-empty list on most desktop systems.
2643        // On other platforms, returns empty vec.
2644        #[cfg(not(target_os = "linux"))]
2645        assert!(themes.is_empty());
2646        // Suppress unused variable warning
2647        let _ = themes;
2648    }
2649}
2650
2651#[cfg(all(test, target_os = "linux"))]
2652#[allow(clippy::unwrap_used, reason = "a test fails by panicking")]
2653mod installed_theme_tests {
2654    use super::*;
2655    use std::path::{Path, PathBuf};
2656
2657    /// A throwaway icon base dir under `share/icons`, removed on drop, and
2658    /// the home directory `home` beside it.
2659    struct Bases {
2660        root: PathBuf,
2661    }
2662
2663    impl Bases {
2664        fn new(tag: &str) -> Self {
2665            let root = std::env::temp_dir().join(format!(
2666                "native-theme-installed-{}-{tag}",
2667                std::process::id()
2668            ));
2669            let _ = std::fs::remove_dir_all(&root);
2670            std::fs::create_dir_all(root.join("share/icons")).unwrap();
2671            Self { root }
2672        }
2673
2674        fn icons(&self) -> PathBuf {
2675            self.root.join("share/icons")
2676        }
2677
2678        fn add(&self, base: &Path, theme: &str, index: &str) {
2679            std::fs::create_dir_all(base.join(theme)).unwrap();
2680            std::fs::write(base.join(theme).join("index.theme"), index).unwrap();
2681        }
2682    }
2683
2684    impl Drop for Bases {
2685        fn drop(&mut self) {
2686            let _ = std::fs::remove_dir_all(&self.root);
2687        }
2688    }
2689
2690    /// An icon theme is an `index.theme` whose `[Icon Theme]` group lists
2691    /// `Directories`: a cursor theme and a theme that only inherits are none,
2692    /// and the key may have spaces around `=`.
2693    #[test]
2694    fn an_installed_theme_lists_directories_in_its_icon_theme_group() {
2695        let bases = Bases::new("predicate");
2696        let icons = bases.icons();
2697        bases.add(
2698            &icons,
2699            "icons",
2700            "[Icon Theme]\nName=icons\nDirectories=actions\n",
2701        );
2702        bases.add(
2703            &icons,
2704            "spaced",
2705            "[Icon Theme]\nName=spaced\nDirectories = actions\n",
2706        );
2707        bases.add(
2708            &icons,
2709            "breeze_cursors",
2710            "[Icon Theme]\nName=Breeze Cursors\nInherits=breeze\n",
2711        );
2712        bases.add(&icons, "default", "[Icon Theme]\nInherits=Adwaita\n");
2713        bases.add(
2714            &icons,
2715            "elsewhere",
2716            "[Icon Theme]\nName=elsewhere\n\n[Other]\nDirectories=actions\n",
2717        );
2718        let dirs = [icons];
2719        assert!(has_theme_index("icons", &dirs));
2720        assert!(has_theme_index("spaced", &dirs));
2721        assert!(!has_theme_index("breeze_cursors", &dirs));
2722        assert!(!has_theme_index("default", &dirs));
2723        assert!(!has_theme_index("elsewhere", &dirs));
2724        assert!(!has_theme_index("missing", &dirs));
2725        assert_eq!(
2726            installed_themes_in(&dirs).into_iter().collect::<Vec<_>>(),
2727            ["icons", "spaced"]
2728        );
2729    }
2730
2731    /// The installed `breeze_cursors` is a cursor theme, not available.
2732    #[test]
2733    fn breeze_cursors_is_not_available() {
2734        if !Path::new("/usr/share/icons/breeze_cursors/index.theme").exists() {
2735            eprintln!("skipped: breeze_cursors is not installed");
2736            return;
2737        }
2738        assert!(!is_freedesktop_theme_available("breeze_cursors"));
2739        assert!(!list_freedesktop_themes().contains(&"breeze_cursors".to_string()));
2740    }
2741
2742    /// Every listed theme is available, read from the one snapshot.
2743    #[test]
2744    fn listed_themes_are_available() {
2745        for theme in list_freedesktop_themes() {
2746            assert!(is_freedesktop_theme_available(&theme), "{theme}");
2747        }
2748    }
2749
2750    /// The base dirs in the Icon Theme Specification's order, `~/.icons`
2751    /// first, then the data home, then each data dir.
2752    #[test]
2753    fn icon_base_dirs_put_the_user_s_first() {
2754        let bases = Bases::new("order");
2755        let home = bases.root.join("home");
2756        for dir in [".icons", ".local/share/icons"] {
2757            std::fs::create_dir_all(home.join(dir)).unwrap();
2758        }
2759        let system = bases.root.join("share");
2760        assert_eq!(
2761            icon_base_dirs_in(Some(&home), None, Some(system.as_os_str())),
2762            [
2763                home.join(".icons"),
2764                home.join(".local/share/icons"),
2765                system.join("icons")
2766            ]
2767        );
2768    }
2769
2770    /// The first `index.theme` in base-dir order is the theme's, as the
2771    /// specification reads it: a user copy without `Directories` hides a
2772    /// system copy with them.
2773    #[test]
2774    fn the_first_index_theme_decides_whether_a_theme_is_installed() {
2775        let bases = Bases::new("first-index");
2776        let user = bases.root.join("home/.icons");
2777        bases.add(&user, "shadowed", "[Icon Theme]\nName=shadowed\n");
2778        bases.add(
2779            &bases.icons(),
2780            "shadowed",
2781            "[Icon Theme]\nName=shadowed\nDirectories=actions\n",
2782        );
2783        assert!(!has_theme_index("shadowed", &[user.clone(), bases.icons()]));
2784        assert!(has_theme_index("shadowed", &[bases.icons(), user]));
2785    }
2786}
2787
2788#[cfg(test)]
2789#[allow(
2790    clippy::unwrap_used,
2791    clippy::expect_used,
2792    clippy::panic,
2793    clippy::indexing_slicing,
2794    reason = "a test fails by panicking"
2795)]
2796mod colorize_tests {
2797    use super::{colorize_monochrome_svg, fill_current_color, sets_color};
2798    use crate::color::Rgba;
2799    use std::borrow::Cow;
2800
2801    const BLUE: Rgba = Rgba::new(51, 102, 204, 255);
2802    const RED: Rgba = Rgba::new(255, 0, 0, 255);
2803    const GREEN: Rgba = Rgba::new(20, 184, 82, 255);
2804
2805    #[test]
2806    fn colorize_svg_replaces_fill_black() {
2807        let svg = b"<svg><path fill=\"black\" d=\"M0 0h24v24H0z\"/></svg>";
2808        let result_str = String::from_utf8(colorize_monochrome_svg(svg, BLUE)).unwrap();
2809        assert!(
2810            !result_str.contains("fill=\"black\""),
2811            "fill=\"black\" should be replaced, got: {result_str}"
2812        );
2813        assert!(
2814            result_str.contains("fill=\"#3366cc\""),
2815            "should contain the hex fill, got: {result_str}"
2816        );
2817    }
2818
2819    #[test]
2820    fn colorize_svg_replaces_fill_hex_black() {
2821        let svg = b"<svg><rect fill=\"#000000\" width=\"24\" height=\"24\"/></svg>";
2822        let result_str = String::from_utf8(colorize_monochrome_svg(svg, RED)).unwrap();
2823        assert!(
2824            !result_str.contains("#000000"),
2825            "fill=\"#000000\" should be replaced, got: {result_str}"
2826        );
2827        assert!(
2828            result_str.contains("fill=\"#ff0000\""),
2829            "should contain the hex fill, got: {result_str}"
2830        );
2831    }
2832
2833    #[test]
2834    fn colorize_svg_replaces_fill_short_hex_black() {
2835        let svg = b"<svg><rect fill=\"#000\" width=\"24\" height=\"24\"/></svg>";
2836        let result_str = String::from_utf8(colorize_monochrome_svg(svg, GREEN)).unwrap();
2837        assert!(
2838            !result_str.contains("fill=\"#000\""),
2839            "fill=\"#000\" should be replaced, got: {result_str}"
2840        );
2841        assert!(
2842            result_str.contains("fill=\"#14b852\""),
2843            "should contain the hex fill, got: {result_str}"
2844        );
2845    }
2846
2847    #[test]
2848    fn colorize_svg_current_color_still_works() {
2849        let svg = b"<svg><path stroke=\"currentColor\" d=\"M0 0\"/></svg>";
2850        let result_str = String::from_utf8(colorize_monochrome_svg(svg, RED)).unwrap();
2851        assert!(
2852            !result_str.contains("currentColor"),
2853            "currentColor should be replaced"
2854        );
2855        assert!(
2856            result_str.contains("#ff0000"),
2857            "should contain the hex colour"
2858        );
2859    }
2860
2861    #[test]
2862    fn colorize_svg_implicit_black_still_works() {
2863        // SVG with no fill attribute at all (Material-style)
2864        let svg = b"<svg xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M0 0\"/></svg>";
2865        let result_str = String::from_utf8(colorize_monochrome_svg(svg, RED)).unwrap();
2866        assert!(
2867            result_str.contains("fill=\"#ff0000\""),
2868            "should inject fill into root svg tag, got: {result_str}"
2869        );
2870    }
2871
2872    #[test]
2873    fn colorize_svg_non_utf8_returns_original() {
2874        // Non-UTF-8 bytes: valid SVG prefix followed by an invalid byte sequence
2875        let mut svg = b"<svg><path fill=\"black\" d=\"M0 0\"/>".to_vec();
2876        svg.push(0xFF); // invalid UTF-8 byte
2877        svg.extend_from_slice(b"</svg>");
2878        let result = colorize_monochrome_svg(&svg, RED);
2879        assert_eq!(result, svg, "non-UTF-8 input should be returned unchanged");
2880    }
2881
2882    #[test]
2883    fn colorize_svg_replaces_stroke_black() {
2884        let svg = b"<svg><path stroke=\"black\" d=\"M0 0h24\"/></svg>";
2885        let result_str = String::from_utf8(colorize_monochrome_svg(svg, BLUE)).unwrap();
2886        assert!(
2887            !result_str.contains("stroke=\"black\""),
2888            "stroke=\"black\" should be replaced, got: {result_str}"
2889        );
2890        assert!(
2891            result_str.contains("stroke=\"#3366cc\""),
2892            "should contain the hex stroke, got: {result_str}"
2893        );
2894    }
2895
2896    #[test]
2897    fn colorize_svg_replaces_stroke_hex_black() {
2898        let svg = b"<svg><line stroke=\"#000000\" x1=\"0\" y1=\"0\" x2=\"24\" y2=\"24\"/></svg>";
2899        let result_str = String::from_utf8(colorize_monochrome_svg(svg, RED)).unwrap();
2900        assert!(
2901            !result_str.contains("#000000"),
2902            "stroke=\"#000000\" should be replaced"
2903        );
2904        assert!(
2905            result_str.contains("stroke=\"#ff0000\""),
2906            "should contain the hex stroke, got: {result_str}"
2907        );
2908    }
2909
2910    #[test]
2911    fn colorize_self_closing_svg_produces_valid_xml() {
2912        // Self-closing <svg .../> tag: the fill must be injected before '/'
2913        let svg = b"<svg xmlns=\"http://www.w3.org/2000/svg\" />";
2914        let result_str = String::from_utf8(colorize_monochrome_svg(svg, RED)).unwrap();
2915        assert!(
2916            result_str.contains("fill=\"#ff0000\""),
2917            "should inject fill, got: {result_str}"
2918        );
2919        assert!(
2920            !result_str.contains("/ fill="),
2921            "fill must be before '/', got: {result_str}"
2922        );
2923        assert!(
2924            result_str.trim().ends_with("/>"),
2925            "should remain self-closing, got: {result_str}"
2926        );
2927    }
2928
2929    #[test]
2930    fn colorize_svg_with_fill_white_root() {
2931        // A root fill that is not black is kept, not replaced
2932        let svg = b"<svg fill=\"white\"><path/></svg>";
2933        let result_str = String::from_utf8(colorize_monochrome_svg(svg, RED)).unwrap();
2934        assert!(
2935            result_str.contains("fill=\"white\""),
2936            "fill=\"white\" should be preserved, got: {result_str}"
2937        );
2938    }
2939
2940    #[test]
2941    fn colorize_svg_with_fill_none_root() {
2942        // stroke="black" is replaced even when the root has fill="none"
2943        let svg = b"<svg fill=\"none\"><path stroke=\"black\"/></svg>";
2944        let result_str = String::from_utf8(colorize_monochrome_svg(svg, RED)).unwrap();
2945        assert!(
2946            !result_str.contains("stroke=\"black\""),
2947            "stroke=\"black\" should be replaced, got: {result_str}"
2948        );
2949        assert!(
2950            result_str.contains("stroke=\"#ff0000\""),
2951            "should contain the hex stroke, got: {result_str}"
2952        );
2953    }
2954
2955    /// The colour's alpha is discarded: an SVG `fill` takes opaque hex (spec §9.2).
2956    #[test]
2957    fn colorize_svg_discards_alpha() {
2958        let svg = b"<svg><path fill=\"black\"/></svg>";
2959        let translucent = Rgba::new(255, 0, 0, 40);
2960        assert_eq!(
2961            colorize_monochrome_svg(svg, translucent),
2962            colorize_monochrome_svg(svg, RED)
2963        );
2964    }
2965
2966    #[test]
2967    fn colorize_svg_replaces_stroke_short_hex_black() {
2968        let svg = b"<svg><path stroke=\"#000\" d=\"M0 0\"/></svg>";
2969        let result_str = String::from_utf8(colorize_monochrome_svg(svg, BLUE)).unwrap();
2970        assert!(
2971            result_str.contains("stroke=\"#3366cc\""),
2972            "stroke=\"#000\" should be replaced, got: {result_str}"
2973        );
2974    }
2975
2976    #[test]
2977    fn colorize_svg_keeps_a_root_fill_and_injects_none() {
2978        let svg = b"<svg fill=\"red\"><path d=\"M0 0\"/></svg>";
2979        let result_str = String::from_utf8(colorize_monochrome_svg(svg, GREEN)).unwrap();
2980        // No second fill is injected, since the root has one
2981        assert!(result_str.contains("fill=\"red\""), "got: {result_str}");
2982        assert!(!result_str.contains("#14b852"), "got: {result_str}");
2983    }
2984
2985    #[test]
2986    fn colorize_svg_mixed_fill_attributes() {
2987        // fill="black" is replaced, fill="red" is kept
2988        let svg = b"<svg><rect fill=\"black\" width=\"10\" height=\"10\"/><rect fill=\"red\" width=\"10\" height=\"10\"/></svg>";
2989        let result_str = String::from_utf8(colorize_monochrome_svg(svg, GREEN)).unwrap();
2990        assert!(
2991            !result_str.contains("fill=\"black\""),
2992            "fill=\"black\" should be replaced, got: {result_str}"
2993        );
2994        assert!(
2995            result_str.contains("fill=\"red\""),
2996            "fill=\"red\" should be preserved, got: {result_str}"
2997        );
2998    }
2999
3000    #[test]
3001    fn colorize_self_closing_svg_without_a_space_produces_valid_xml() {
3002        // `<svg .../>` with no space before '/': the fill still goes before it
3003        let svg = b"<svg xmlns='http://www.w3.org/2000/svg'/>";
3004        let result_str = String::from_utf8(colorize_monochrome_svg(svg, RED)).unwrap();
3005        assert!(
3006            result_str.contains("fill=\"#ff0000\"") && result_str.ends_with("/>"),
3007            "self-closing SVG should remain valid XML, got: {result_str}"
3008        );
3009        assert!(
3010            !result_str.contains("/ fill="),
3011            "fill should not be between / and >, got: {result_str}"
3012        );
3013    }
3014
3015    #[test]
3016    fn fill_current_color_fills_an_unset_current_color() {
3017        let svg = br#"<svg><path fill="currentColor" stroke="currentColor"/></svg>"#;
3018        let filled = fill_current_color(svg, Rgba::new(51, 102, 204, 7));
3019        assert_eq!(
3020            &*filled,
3021            br##"<svg><path fill="#3366cc" stroke="#3366cc"/></svg>"##
3022        );
3023    }
3024
3025    #[test]
3026    fn fill_current_color_borrows_what_it_leaves_alone() {
3027        let plain = br##"<svg><path fill="#2e3436"/></svg>"##;
3028        let styled = br#"<svg><style>.ColorScheme-Text { color:#232629; }</style><path class="ColorScheme-Text" fill="currentColor"/></svg>"#;
3029        let attribute = br##"<svg color="#fff"><path fill="currentColor"/></svg>"##;
3030        let not_utf8 = b"<svg>\xff currentColor</svg>";
3031        for svg in [&plain[..], &styled[..], &attribute[..], &not_utf8[..]] {
3032            assert!(
3033                matches!(fill_current_color(svg, BLUE), Cow::Borrowed(b) if b == svg),
3034                "{}",
3035                String::from_utf8_lossy(svg)
3036            );
3037        }
3038    }
3039
3040    #[test]
3041    fn sets_color_reads_only_the_color_property() {
3042        assert!(!sets_color(r#"<svg><path fill="currentColor"/></svg>"#));
3043        assert!(sets_color(
3044            r##"<svg color="#fff"><path fill="currentColor"/></svg>"##
3045        ));
3046        assert!(sets_color("<svg><style>.a { color : #fff }</style></svg>"));
3047        assert!(sets_color(r#"<svg><path style="color:#fff"/></svg>"#));
3048        assert!(!sets_color(
3049            r##"<svg><stop stop-color="#fff"/><path fill="currentColor"/></svg>"##
3050        ));
3051        assert!(!sets_color(
3052            r##"<svg flood-color="#fff" lighting-color="#fff" solid-color="#fff"/>"##
3053        ));
3054        assert!(!sets_color(
3055            r##"<svg text-decoration-color="#fff" pagecolor="#fff" bordercolor="#fff"/>"##
3056        ));
3057        assert!(!sets_color(
3058            r#"<svg id="color" class="color"><path fill="currentColor"/></svg>"#
3059        ));
3060        assert!(!sets_color(r#"<svg color-interpolation="sRGB"/>"#));
3061    }
3062}