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