Skip to main content

native_theme/
icons.rs

1//! Icon loading and dispatch.
2
3use std::fmt;
4
5#[allow(unused_imports)]
6use std::borrow::Cow;
7
8#[allow(unused_imports)]
9use crate::model::icons::{icon_name, system_icon_set, system_icon_theme};
10use crate::model::{AnimatedIcon, IconData, IconProvider, IconRole, IconSet};
11#[allow(unused_imports)]
12use crate::model::{bundled_icon_by_name, bundled_icon_svg};
13
14/// Identifies what icon to load: a semantic role, a platform-specific name,
15/// or a custom provider.
16///
17/// Constructed via [`From`] impls -- users rarely reference this type directly.
18/// Pass an [`IconRole`], `&str`, or `&dyn IconProvider` to a per-set loader's
19/// `new()` constructor (e.g. [`FreedesktopLoader::new`] or [`MaterialLoader::new`]).
20///
21/// # Examples
22///
23/// ```
24/// use native_theme::icons::IconId;
25/// use native_theme::theme::IconRole;
26///
27/// // All of these work via Into<IconId>:
28/// let _: IconId = IconRole::ActionSave.into();
29/// let _: IconId = "edit-copy".into();
30/// ```
31#[derive(Debug)]
32#[non_exhaustive]
33pub enum IconId<'a> {
34    /// Load by semantic role (most common).
35    Role(IconRole),
36    /// Load by platform-specific name string.
37    Name(&'a str),
38    /// Load via a custom [`IconProvider`] implementation.
39    Custom(&'a dyn IconProvider),
40}
41
42impl From<IconRole> for IconId<'_> {
43    fn from(role: IconRole) -> Self {
44        IconId::Role(role)
45    }
46}
47
48impl<'a> From<&'a str> for IconId<'a> {
49    fn from(name: &'a str) -> Self {
50        IconId::Name(name)
51    }
52}
53
54impl<'a> From<&'a dyn IconProvider> for IconId<'a> {
55    fn from(provider: &'a dyn IconProvider) -> Self {
56        IconId::Custom(provider)
57    }
58}
59
60// =============================================================================
61// Typed per-set icon loaders
62// =============================================================================
63//
64// Each set has its own loader struct exposing only the methods meaningful
65// for that set. This eliminates the silent-ignore bug class where a method
66// like `.theme()` could be called on a non-freedesktop loader and have no
67// effect. Calling a set-specific method on the wrong loader is now a
68// compile error.
69//
70// For runtime-set dispatch (common in connector code), use the free
71// functions `load_icon(id, set)` and `load_icon_indicator(set)` at the
72// bottom of this section.
73
74/// Loader for freedesktop.org icon themes (GTK / Linux).
75///
76/// Honors `.theme()` for BOTH role-based and name-based lookups — unlike
77/// the previous single-struct design, no dispatch layer can silently
78/// drop the theme override.
79///
80/// ```
81/// # #[cfg(all(target_os = "linux", feature = "system-icons"))]
82/// # {
83/// use native_theme::icons::FreedesktopLoader;
84/// use native_theme::theme::IconRole;
85///
86/// // By role, system theme:
87/// let _icon = FreedesktopLoader::new(IconRole::ActionCopy).load();
88///
89/// // By name, explicit theme + size + symbolic fg color:
90/// let _icon = FreedesktopLoader::new("edit-copy")
91///     .theme("Adwaita")
92///     .size(48)
93///     .color([0, 0, 0])
94///     .load();
95/// # }
96/// ```
97#[derive(Debug)]
98#[must_use]
99pub struct FreedesktopLoader<'a> {
100    // Fields read only in the Linux + system-icons cfg branch of `load`.
101    #[allow(dead_code)]
102    id: IconId<'a>,
103    #[allow(dead_code)]
104    size: u16,
105    #[allow(dead_code)]
106    fg_color: Option<[u8; 3]>,
107    #[allow(dead_code)]
108    theme: Option<&'a str>,
109}
110
111impl<'a> FreedesktopLoader<'a> {
112    /// Create a freedesktop loader. Defaults: size 24, no fg_color, system theme.
113    pub fn new(id: impl Into<IconId<'a>>) -> Self {
114        Self {
115            id: id.into(),
116            size: 24,
117            fg_color: None,
118            theme: None,
119        }
120    }
121
122    /// Set the requested icon size in pixels (default 24).
123    pub fn size(mut self, size: u16) -> Self {
124        self.size = size;
125        self
126    }
127
128    /// Set the foreground color for GTK symbolic icon colorization.
129    pub fn color(mut self, rgb: [u8; 3]) -> Self {
130        self.fg_color = Some(rgb);
131        self
132    }
133
134    /// Set the foreground color if `Some`, leave default if `None`.
135    pub fn color_opt(mut self, rgb: Option<[u8; 3]>) -> Self {
136        self.fg_color = rgb;
137        self
138    }
139
140    /// Override the freedesktop icon theme (e.g. "Adwaita", "breeze").
141    /// When unset, uses the system-detected theme.
142    pub fn theme(mut self, theme: &'a str) -> Self {
143        self.theme = Some(theme);
144        self
145    }
146
147    /// Load the icon, returning its data.
148    #[must_use]
149    #[allow(unused_variables)]
150    pub fn load(self) -> Option<IconData> {
151        #[cfg(all(target_os = "linux", feature = "system-icons"))]
152        {
153            let detected;
154            let theme: &str = match self.theme {
155                Some(t) => t,
156                None => {
157                    detected = system_icon_theme();
158                    &detected
159                }
160            };
161            match self.id {
162                IconId::Role(role) => {
163                    let name = icon_name(role, IconSet::Freedesktop)?;
164                    crate::freedesktop::load_freedesktop_icon_by_name(
165                        name,
166                        theme,
167                        self.size,
168                        self.fg_color,
169                    )
170                }
171                IconId::Name(name) => crate::freedesktop::load_freedesktop_icon_by_name(
172                    name,
173                    theme,
174                    self.size,
175                    self.fg_color,
176                ),
177                IconId::Custom(provider) => {
178                    if let Some(name) = provider.icon_name(IconSet::Freedesktop)
179                        && let Some(data) = crate::freedesktop::load_freedesktop_icon_by_name(
180                            name,
181                            theme,
182                            self.size,
183                            self.fg_color,
184                        )
185                    {
186                        return Some(data);
187                    }
188                    provider.icon_svg(IconSet::Freedesktop).map(IconData::Svg)
189                }
190            }
191        }
192        #[cfg(not(all(target_os = "linux", feature = "system-icons")))]
193        {
194            None
195        }
196    }
197
198    /// Load the theme's animated process-working spinner.
199    ///
200    /// `theme` of `None` uses the system-detected theme; `Some(t)` overrides.
201    /// Associated function (no `self`) — the spinner is a property of the
202    /// theme, not of any particular icon id.
203    #[must_use]
204    #[allow(unused_variables)]
205    pub fn load_indicator(theme: Option<&str>) -> Option<AnimatedIcon> {
206        #[cfg(all(target_os = "linux", feature = "system-icons"))]
207        {
208            crate::freedesktop::load_freedesktop_spinner(theme)
209        }
210        #[cfg(not(all(target_os = "linux", feature = "system-icons")))]
211        {
212            None
213        }
214    }
215}
216
217/// Loader for Apple SF Symbols (macOS only).
218///
219/// SF Symbols has no concept of themes or foreground-color baking, so the
220/// loader exposes only [`Self::new`] and [`Self::load`].
221#[derive(Debug)]
222#[must_use]
223pub struct SfSymbolsLoader<'a> {
224    #[allow(dead_code)] // read only in the macOS cfg branch of `load`
225    id: IconId<'a>,
226}
227
228impl<'a> SfSymbolsLoader<'a> {
229    /// Construct a new SF Symbols loader for the given icon id.
230    pub fn new(id: impl Into<IconId<'a>>) -> Self {
231        Self { id: id.into() }
232    }
233
234    /// Load the icon, returning its data. Returns `None` on non-macOS targets.
235    #[must_use]
236    #[allow(unused_variables)]
237    pub fn load(self) -> Option<IconData> {
238        #[cfg(all(target_os = "macos", feature = "system-icons"))]
239        {
240            match self.id {
241                IconId::Role(role) => {
242                    let name = icon_name(role, IconSet::SfSymbols)?;
243                    crate::sficons::load_sf_icon_by_name(name)
244                }
245                IconId::Name(n) => crate::sficons::load_sf_icon_by_name(n),
246                IconId::Custom(p) => {
247                    if let Some(n) = p.icon_name(IconSet::SfSymbols)
248                        && let Some(data) = crate::sficons::load_sf_icon_by_name(n)
249                    {
250                        return Some(data);
251                    }
252                    p.icon_svg(IconSet::SfSymbols).map(IconData::Svg)
253                }
254            }
255        }
256        #[cfg(not(all(target_os = "macos", feature = "system-icons")))]
257        {
258            None
259        }
260    }
261    // No load_indicator: SF Symbols has no animated spinner primitive.
262}
263
264/// Loader for Windows Segoe Fluent Icons (Windows only).
265///
266/// Segoe icons have no themes or fg_color baking in this API.
267#[derive(Debug)]
268#[must_use]
269pub struct SegoeIconsLoader<'a> {
270    #[allow(dead_code)] // read only in the Windows cfg branch of `load`
271    id: IconId<'a>,
272}
273
274impl<'a> SegoeIconsLoader<'a> {
275    /// Construct a new Segoe Fluent loader for the given icon id.
276    pub fn new(id: impl Into<IconId<'a>>) -> Self {
277        Self { id: id.into() }
278    }
279
280    /// Load the icon, returning its data. Returns `None` on non-Windows targets.
281    #[must_use]
282    #[allow(unused_variables)]
283    pub fn load(self) -> Option<IconData> {
284        #[cfg(all(target_os = "windows", feature = "system-icons"))]
285        {
286            match self.id {
287                IconId::Role(role) => {
288                    let name = icon_name(role, IconSet::SegoeIcons)?;
289                    crate::winicons::load_windows_icon_by_name(name)
290                }
291                IconId::Name(n) => crate::winicons::load_windows_icon_by_name(n),
292                IconId::Custom(p) => {
293                    if let Some(n) = p.icon_name(IconSet::SegoeIcons)
294                        && let Some(data) = crate::winicons::load_windows_icon_by_name(n)
295                    {
296                        return Some(data);
297                    }
298                    p.icon_svg(IconSet::SegoeIcons).map(IconData::Svg)
299                }
300            }
301        }
302        #[cfg(not(all(target_os = "windows", feature = "system-icons")))]
303        {
304            None
305        }
306    }
307    // No load_indicator: Segoe has no animated spinner primitive.
308}
309
310/// Loader for Google Material Symbols (bundled SVG).
311///
312/// Material SVGs are scalable at render time, so no `size` method.
313#[derive(Debug)]
314#[must_use]
315pub struct MaterialLoader<'a> {
316    #[allow(dead_code)] // read only in the material-icons feature cfg branch of `load`
317    id: IconId<'a>,
318}
319
320impl<'a> MaterialLoader<'a> {
321    /// Construct a new Material Symbols loader for the given icon id.
322    pub fn new(id: impl Into<IconId<'a>>) -> Self {
323        Self { id: id.into() }
324    }
325
326    /// Load the icon, returning its data. Requires `feature = "material-icons"`.
327    #[must_use]
328    #[allow(unused_variables)]
329    pub fn load(self) -> Option<IconData> {
330        #[cfg(feature = "material-icons")]
331        {
332            match self.id {
333                IconId::Role(role) => bundled_icon_svg(role, IconSet::Material)
334                    .map(|b| IconData::Svg(Cow::Borrowed(b))),
335                IconId::Name(n) => bundled_icon_by_name(n, IconSet::Material)
336                    .map(|b| IconData::Svg(Cow::Borrowed(b))),
337                IconId::Custom(p) => {
338                    if let Some(n) = p.icon_name(IconSet::Material)
339                        && let Some(b) = bundled_icon_by_name(n, IconSet::Material)
340                    {
341                        return Some(IconData::Svg(Cow::Borrowed(b)));
342                    }
343                    p.icon_svg(IconSet::Material).map(IconData::Svg)
344                }
345            }
346        }
347        #[cfg(not(feature = "material-icons"))]
348        {
349            None
350        }
351    }
352
353    /// Load the Material animated spinner. Associated function; no `self`.
354    #[must_use]
355    pub fn load_indicator() -> Option<AnimatedIcon> {
356        #[cfg(feature = "material-icons")]
357        {
358            Some(crate::spinners::material_spinner())
359        }
360        #[cfg(not(feature = "material-icons"))]
361        {
362            None
363        }
364    }
365}
366
367/// Loader for Lucide Icons (bundled SVG).
368#[derive(Debug)]
369#[must_use]
370pub struct LucideLoader<'a> {
371    #[allow(dead_code)] // read only in the lucide-icons feature cfg branch of `load`
372    id: IconId<'a>,
373}
374
375impl<'a> LucideLoader<'a> {
376    /// Construct a new Lucide Icons loader for the given icon id.
377    pub fn new(id: impl Into<IconId<'a>>) -> Self {
378        Self { id: id.into() }
379    }
380
381    /// Load the icon, returning its data. Requires `feature = "lucide-icons"`.
382    #[must_use]
383    #[allow(unused_variables)]
384    pub fn load(self) -> Option<IconData> {
385        #[cfg(feature = "lucide-icons")]
386        {
387            match self.id {
388                IconId::Role(role) => {
389                    bundled_icon_svg(role, IconSet::Lucide).map(|b| IconData::Svg(Cow::Borrowed(b)))
390                }
391                IconId::Name(n) => bundled_icon_by_name(n, IconSet::Lucide)
392                    .map(|b| IconData::Svg(Cow::Borrowed(b))),
393                IconId::Custom(p) => {
394                    if let Some(n) = p.icon_name(IconSet::Lucide)
395                        && let Some(b) = bundled_icon_by_name(n, IconSet::Lucide)
396                    {
397                        return Some(IconData::Svg(Cow::Borrowed(b)));
398                    }
399                    p.icon_svg(IconSet::Lucide).map(IconData::Svg)
400                }
401            }
402        }
403        #[cfg(not(feature = "lucide-icons"))]
404        {
405            None
406        }
407    }
408
409    /// Load the Lucide animated spinner. Associated function; no `self`.
410    #[must_use]
411    pub fn load_indicator() -> Option<AnimatedIcon> {
412        #[cfg(feature = "lucide-icons")]
413        {
414            Some(crate::spinners::lucide_spinner())
415        }
416        #[cfg(not(feature = "lucide-icons"))]
417        {
418            None
419        }
420    }
421}
422
423// =============================================================================
424// Runtime-set dispatch helpers
425// =============================================================================
426
427/// Load an icon using the given set with default per-set options.
428///
429/// For set-specific options (freedesktop theme, fg_color), construct the
430/// specific loader directly and chain the relevant methods.
431#[must_use]
432pub fn load_icon<'a>(id: impl Into<IconId<'a>>, set: IconSet) -> Option<IconData> {
433    let id = id.into();
434    match set {
435        IconSet::Freedesktop => FreedesktopLoader::new(id).load(),
436        IconSet::SfSymbols => SfSymbolsLoader::new(id).load(),
437        IconSet::SegoeIcons => SegoeIconsLoader::new(id).load(),
438        IconSet::Material => MaterialLoader::new(id).load(),
439        IconSet::Lucide => LucideLoader::new(id).load(),
440    }
441}
442
443/// Load the animated loading indicator for the given set.
444///
445/// Returns `None` for sets without an animated spinner (SfSymbols, SegoeIcons).
446/// For a freedesktop spinner from a specific theme, use
447/// [`FreedesktopLoader::load_indicator`] directly.
448#[must_use]
449pub fn load_icon_indicator(set: IconSet) -> Option<AnimatedIcon> {
450    match set {
451        IconSet::Freedesktop => FreedesktopLoader::load_indicator(None),
452        IconSet::Material => MaterialLoader::load_indicator(),
453        IconSet::Lucide => LucideLoader::load_indicator(),
454        IconSet::SfSymbols | IconSet::SegoeIcons => None,
455    }
456}
457
458/// Check whether a freedesktop icon theme is installed on this system.
459///
460/// Looks for the theme's `index.theme` file in the standard XDG icon
461/// directories (`$XDG_DATA_DIRS/icons/<theme>/` and
462/// `$XDG_DATA_HOME/icons/<theme>/`).
463///
464/// Always returns `false` on non-Linux platforms.
465#[must_use]
466pub fn is_freedesktop_theme_available(theme: &str) -> bool {
467    #[cfg(target_os = "linux")]
468    {
469        let data_dirs = std::env::var("XDG_DATA_DIRS")
470            .unwrap_or_else(|_| "/usr/share:/usr/local/share".to_string());
471        for dir in data_dirs.split(':') {
472            if std::path::Path::new(dir)
473                .join("icons")
474                .join(theme)
475                .join("index.theme")
476                .exists()
477            {
478                return true;
479            }
480        }
481        let data_home = std::env::var("XDG_DATA_HOME").unwrap_or_else(|_| {
482            std::env::var("HOME")
483                .map(|h| format!("{h}/.local/share"))
484                .unwrap_or_default()
485        });
486        if !data_home.is_empty() {
487            return std::path::Path::new(&data_home)
488                .join("icons")
489                .join(theme)
490                .join("index.theme")
491                .exists();
492        }
493        false
494    }
495    #[cfg(not(target_os = "linux"))]
496    {
497        false
498    }
499}
500
501// =============================================================================
502// IconSetChoice: user's icon set selection intent
503// =============================================================================
504
505/// The user's icon set selection mode.
506///
507/// Represents the user's intent for which icons to display.  The key
508/// invariant: only [`Default`](Self::Default) is re-derived on theme changes.
509/// All other variants represent an explicit user choice that is preserved
510/// across theme re-applications.
511#[derive(Debug, Clone, PartialEq, Eq)]
512pub enum IconSetChoice {
513    /// Follow the theme preset's recommendation.
514    ///
515    /// The `String` is the preset's `icon_theme` name (e.g. "Adwaita"),
516    /// used for display ("default (Adwaita)") and for loading when the
517    /// icon set is `Freedesktop`.
518    ///
519    /// This is the ONLY variant that gets overwritten on theme change.
520    /// It is only constructed via [`default_icon_choice()`], which
521    /// guarantees the theme is available (bundled sets are always
522    /// available; freedesktop themes are checked via
523    /// [`is_freedesktop_theme_available`] before returning this variant).
524    Default(String),
525
526    /// Use the OS-configured icon theme.
527    ///
528    /// Resolved at load time via [`system_icon_set()`](crate::model::icons::system_icon_set).
529    /// The display label ("system (breeze-dark)") is computed dynamically
530    /// from [`system_icon_theme()`](crate::model::icons::system_icon_theme),
531    /// so it tracks runtime OS theme changes.
532    System,
533
534    /// User explicitly picked a specific installed freedesktop icon theme.
535    ///
536    /// The `String` is the theme directory name (e.g. "char-white",
537    /// "breeze", "Papirus").  Loaded via `IconSet::Freedesktop` with
538    /// `.theme(name)`.
539    Freedesktop(String),
540
541    /// Google Material Symbols (bundled).
542    Material,
543
544    /// Lucide Icons (bundled).
545    Lucide,
546}
547
548impl fmt::Display for IconSetChoice {
549    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
550        match self {
551            Self::Default(name) => write!(f, "default ({name})"),
552            Self::System => {
553                let name = system_icon_theme();
554                write!(f, "system ({name})")
555            }
556            Self::Freedesktop(name) => write!(f, "{name}"),
557            Self::Material => write!(f, "Material (bundled)"),
558            Self::Lucide => write!(f, "Lucide (bundled)"),
559        }
560    }
561}
562
563impl IconSetChoice {
564    /// The effective [`IconSet`] loading mechanism for this choice.
565    ///
566    /// For [`Default`](Self::Default), returns the theme's icon set
567    /// (caller passes it in).
568    /// For [`Freedesktop`](Self::Freedesktop), always returns
569    /// [`IconSet::Freedesktop`].
570    /// For others, returns the corresponding bundled or system set.
571    #[must_use]
572    pub fn effective_icon_set(&self, theme_icon_set: IconSet) -> IconSet {
573        match self {
574            Self::Default(_) => theme_icon_set,
575            Self::System => system_icon_set(),
576            Self::Freedesktop(_) => IconSet::Freedesktop,
577            Self::Material => IconSet::Material,
578            Self::Lucide => IconSet::Lucide,
579        }
580    }
581
582    /// The freedesktop theme name to pass to [`FreedesktopLoader::theme`], if any.
583    ///
584    /// Returns `Some(name)` for [`Default`](Self::Default) and
585    /// [`Freedesktop`](Self::Freedesktop) variants.
586    /// Returns `None` for [`System`](Self::System), [`Material`](Self::Material),
587    /// [`Lucide`](Self::Lucide).
588    ///
589    /// The caller is responsible for only passing the result to
590    /// [`FreedesktopLoader::theme`] when the effective icon set is
591    /// [`IconSet::Freedesktop`].  For bundled sets (Material, Lucide),
592    /// the theme name is not used by the loader.
593    #[must_use]
594    pub fn freedesktop_theme(&self) -> Option<&str> {
595        match self {
596            Self::Default(name) | Self::Freedesktop(name) => Some(name),
597            Self::System | Self::Material | Self::Lucide => None,
598        }
599    }
600
601    /// Whether this choice should be re-derived when the theme changes.
602    ///
603    /// Only [`Default`](Self::Default) follows the preset.  All others
604    /// are explicit user choices that must be preserved.
605    #[must_use]
606    pub fn follows_preset(&self) -> bool {
607        matches!(self, Self::Default(_))
608    }
609}
610
611/// Determine the default icon set choice for a theme.
612///
613/// When the TOML specifies `icon_theme` (`Some`) and the theme is
614/// available (bundled sets are always available; freedesktop themes are
615/// checked via [`is_freedesktop_theme_available`]), returns
616/// [`IconSetChoice::Default(icon_theme)`](IconSetChoice::Default).
617///
618/// When the TOML does not specify `icon_theme` (`None`), or the
619/// specified freedesktop theme is not installed, returns
620/// [`IconSetChoice::System`].
621#[must_use]
622pub fn default_icon_choice(icon_set: IconSet, icon_theme: Option<&str>) -> IconSetChoice {
623    let Some(theme) = icon_theme else {
624        return IconSetChoice::System;
625    };
626    // All five IconSet variants listed explicitly -- no wildcard.
627    // Adding a new variant produces a compiler error, forcing the author
628    // to decide whether the new set's theme is "always available" or
629    // needs a runtime check.
630    let available = match icon_set {
631        IconSet::Material | IconSet::Lucide => true,
632        IconSet::Freedesktop => is_freedesktop_theme_available(theme),
633        IconSet::SfSymbols | IconSet::SegoeIcons => true,
634    };
635    if available {
636        IconSetChoice::Default(theme.to_string())
637    } else {
638        IconSetChoice::System
639    }
640}
641
642/// List installed freedesktop icon themes.
643///
644/// Scans `$XDG_DATA_DIRS/icons/` and `$XDG_DATA_HOME/icons/` for
645/// subdirectories containing an `index.theme` file with a `Directories=`
646/// line (per the freedesktop Icon Theme Specification).  This filters
647/// out cursor-only themes that lack application icons.
648///
649/// Excludes `hicolor` (mandatory fallback) and `default` (typically a
650/// symlink).  Returns a sorted, deduplicated list of theme directory
651/// names.
652///
653/// Silently skips entries on IO errors (e.g. permission denied).
654/// Returns an empty `Vec` on non-Linux platforms.
655///
656/// Note: themes installed via Flatpak or Snap may reside outside
657/// standard XDG paths and will not be discovered.
658#[must_use]
659pub fn list_freedesktop_themes() -> Vec<String> {
660    #[cfg(target_os = "linux")]
661    {
662        use std::collections::BTreeSet;
663        use std::io::BufRead;
664
665        let mut themes = BTreeSet::new();
666
667        // Collect icon base directories from XDG paths.
668        let mut icon_dirs = Vec::new();
669
670        let data_dirs = std::env::var("XDG_DATA_DIRS")
671            .unwrap_or_else(|_| "/usr/share:/usr/local/share".to_string());
672        for dir in data_dirs.split(':') {
673            if !dir.is_empty() {
674                icon_dirs.push(std::path::PathBuf::from(dir).join("icons"));
675            }
676        }
677
678        let data_home = std::env::var("XDG_DATA_HOME").unwrap_or_else(|_| {
679            std::env::var("HOME")
680                .map(|h| format!("{h}/.local/share"))
681                .unwrap_or_default()
682        });
683        if !data_home.is_empty() {
684            icon_dirs.push(std::path::PathBuf::from(&data_home).join("icons"));
685        }
686
687        for icon_dir in &icon_dirs {
688            let entries = match std::fs::read_dir(icon_dir) {
689                Ok(e) => e,
690                Err(_) => continue,
691            };
692            for entry in entries.filter_map(|e| e.ok()) {
693                let path = entry.path();
694                if !path.is_dir() {
695                    continue;
696                }
697                let name = match entry.file_name().into_string() {
698                    Ok(n) => n,
699                    Err(_) => continue,
700                };
701
702                // Exclude hicolor (mandatory fallback) and default (symlink).
703                if name == "hicolor" || name == "default" {
704                    continue;
705                }
706
707                let index_path = path.join("index.theme");
708                let file = match std::fs::File::open(&index_path) {
709                    Ok(f) => f,
710                    Err(_) => continue,
711                };
712
713                // Check if index.theme contains a Directories= line.
714                // Cursor-only themes omit this line.
715                let reader = std::io::BufReader::new(file);
716                let has_directories = reader
717                    .lines()
718                    .map_while(Result::ok)
719                    .any(|line| line.starts_with("Directories="));
720
721                if has_directories {
722                    themes.insert(name);
723                }
724            }
725        }
726
727        themes.into_iter().collect()
728    }
729    #[cfg(not(target_os = "linux"))]
730    {
731        Vec::new()
732    }
733}
734
735// =============================================================================
736// Tests
737// =============================================================================
738
739#[cfg(test)]
740#[allow(clippy::unwrap_used, clippy::expect_used)]
741mod load_icon_tests {
742    use super::*;
743
744    #[test]
745    #[cfg(all(target_os = "linux", feature = "system-icons"))]
746    fn freedesktop_loader_theme_override_honored_for_name_lookup() {
747        // Regression pin for Phase 93-03 silent-ignore bug (Plan 93-09 fix).
748        // The old IconLoader dispatched IconId::Name to a path that silently
749        // dropped `.theme()`. FreedesktopLoader has a single `load()` method
750        // that honors `.theme()` uniformly across Role/Name/Custom.
751        //
752        // Requires the Adwaita icon theme installed on the test host.
753        let result = FreedesktopLoader::new("format-text-rich")
754            .theme("Adwaita")
755            .size(24)
756            .load();
757        assert!(
758            result.is_some(),
759            "theme('Adwaita') must resolve 'format-text-rich' in Adwaita, regardless of system theme"
760        );
761    }
762
763    #[test]
764    #[cfg(feature = "material-icons")]
765    fn load_icon_material_returns_svg() {
766        let result = MaterialLoader::new(IconRole::ActionCopy).load();
767        assert!(result.is_some(), "material ActionCopy should return Some");
768        match result.unwrap() {
769            IconData::Svg(ref cow) => {
770                let s = String::from_utf8_lossy(cow);
771                assert!(s.contains("<svg"), "should contain SVG data");
772            }
773            _ => panic!("expected IconData::Svg for bundled material icon"),
774        }
775    }
776
777    #[test]
778    #[cfg(feature = "lucide-icons")]
779    fn load_icon_lucide_returns_svg() {
780        let result = LucideLoader::new(IconRole::ActionCopy).load();
781        assert!(result.is_some(), "lucide ActionCopy should return Some");
782        match result.unwrap() {
783            IconData::Svg(ref cow) => {
784                let s = String::from_utf8_lossy(cow);
785                assert!(s.contains("<svg"), "should contain SVG data");
786            }
787            _ => panic!("expected IconData::Svg for bundled lucide icon"),
788        }
789    }
790
791    #[test]
792    #[cfg(feature = "material-icons")]
793    fn load_icon_unknown_theme_no_cross_set_fallback() {
794        // On Linux (test platform), unknown theme resolves to system_icon_set() = Freedesktop.
795        // Without system-icons feature, Freedesktop falls through to wildcard -> None.
796        // No cross-set Material fallback.
797        let result = FreedesktopLoader::new(IconRole::ActionCopy).load();
798        // Without system-icons, this falls to wildcard which returns None
799        // With system-icons, this dispatches to load_freedesktop_icon which may return Some
800        // Either way, no panic
801        let _ = result;
802    }
803
804    #[test]
805    #[cfg(feature = "material-icons")]
806    fn load_icon_all_roles_material() {
807        // Material has 42 of 42 roles mapped, all return Some
808        let mut some_count = 0;
809        for role in IconRole::ALL {
810            if MaterialLoader::new(role).load().is_some() {
811                some_count += 1;
812            }
813        }
814        // bundled_icon_svg covers all 42 roles for Material
815        assert_eq!(
816            some_count, 42,
817            "Material should cover all 42 roles via bundled SVGs"
818        );
819    }
820
821    #[test]
822    #[cfg(feature = "lucide-icons")]
823    fn load_icon_all_roles_lucide() {
824        let mut some_count = 0;
825        for role in IconRole::ALL {
826            if LucideLoader::new(role).load().is_some() {
827                some_count += 1;
828            }
829        }
830        // bundled_icon_svg covers all 42 roles for Lucide
831        assert_eq!(
832            some_count, 42,
833            "Lucide should cover all 42 roles via bundled SVGs"
834        );
835    }
836
837    #[test]
838    fn load_icon_unrecognized_set_no_features() {
839        // SfSymbols on Linux without system-icons: falls through to wildcard -> None
840        let _result = SfSymbolsLoader::new(IconRole::ActionCopy).load();
841        // Just verifying it doesn't panic
842    }
843
844    #[test]
845    #[cfg(feature = "material-icons")]
846    fn bundled_icon_load_produces_cow_borrowed() {
847        let result = MaterialLoader::new(IconRole::ActionCopy).load();
848        assert!(
849            matches!(result, Some(IconData::Svg(Cow::Borrowed(_)))),
850            "bundled icon should produce Some(IconData::Svg(Cow::Borrowed(_)))"
851        );
852    }
853}
854
855#[cfg(test)]
856#[allow(clippy::unwrap_used, clippy::expect_used)]
857mod load_system_icon_by_name_tests {
858    use super::*;
859
860    #[test]
861    #[cfg(feature = "material-icons")]
862    fn system_icon_by_name_material() {
863        let result = MaterialLoader::new("content_copy").load();
864        assert!(
865            result.is_some(),
866            "content_copy should be found in Material set"
867        );
868        assert!(matches!(result.unwrap(), IconData::Svg(_)));
869    }
870
871    #[test]
872    #[cfg(feature = "lucide-icons")]
873    fn system_icon_by_name_lucide() {
874        let result = LucideLoader::new("copy").load();
875        assert!(result.is_some(), "copy should be found in Lucide set");
876        assert!(matches!(result.unwrap(), IconData::Svg(_)));
877    }
878
879    #[test]
880    #[cfg(feature = "material-icons")]
881    fn system_icon_by_name_unknown_returns_none() {
882        let result = MaterialLoader::new("nonexistent_xyz").load();
883        assert!(result.is_none(), "nonexistent name should return None");
884    }
885
886    #[test]
887    fn system_icon_by_name_sf_on_linux_returns_none() {
888        // On Linux, SfSymbols set is not available (cfg-gated to macOS)
889        #[cfg(not(target_os = "macos"))]
890        {
891            let result = SfSymbolsLoader::new("doc.on.doc").load();
892            assert!(
893                result.is_none(),
894                "SF Symbols should return None on non-macOS"
895            );
896        }
897    }
898}
899
900#[cfg(test)]
901#[allow(clippy::unwrap_used, clippy::expect_used)]
902mod load_custom_icon_tests {
903    use super::*;
904
905    #[test]
906    #[cfg(feature = "material-icons")]
907    fn custom_icon_with_icon_role_material() {
908        let provider: &dyn IconProvider = &IconRole::ActionCopy;
909        let result = MaterialLoader::new(provider).load();
910        assert!(
911            result.is_some(),
912            "IconRole::ActionCopy should load via material"
913        );
914    }
915
916    #[test]
917    #[cfg(feature = "lucide-icons")]
918    fn custom_icon_with_icon_role_lucide() {
919        let provider: &dyn IconProvider = &IconRole::ActionCopy;
920        let result = LucideLoader::new(provider).load();
921        assert!(
922            result.is_some(),
923            "IconRole::ActionCopy should load via lucide"
924        );
925    }
926
927    #[test]
928    fn custom_icon_no_cross_set_fallback() {
929        // Provider that returns None for all sets -- should NOT fall back
930        #[derive(Debug)]
931        struct NullProvider;
932        impl IconProvider for NullProvider {
933            fn icon_name(&self, _set: IconSet) -> Option<&str> {
934                None
935            }
936            fn icon_svg(&self, _set: IconSet) -> Option<Cow<'static, [u8]>> {
937                None
938            }
939        }
940
941        let provider: &dyn IconProvider = &NullProvider;
942        let result = MaterialLoader::new(provider).load();
943        assert!(
944            result.is_none(),
945            "NullProvider should return None (no cross-set fallback)"
946        );
947    }
948
949    #[test]
950    fn custom_icon_unknown_set_uses_system() {
951        // "unknown-set" is not a known IconSet name, falls through to system_icon_set()
952        #[derive(Debug)]
953        struct NullProvider;
954        impl IconProvider for NullProvider {
955            fn icon_name(&self, _set: IconSet) -> Option<&str> {
956                None
957            }
958            fn icon_svg(&self, _set: IconSet) -> Option<Cow<'static, [u8]>> {
959                None
960            }
961        }
962
963        // Just verify it doesn't panic -- the actual set chosen depends on platform
964        let provider: &dyn IconProvider = &NullProvider;
965        let _result = FreedesktopLoader::new(provider).load();
966    }
967
968    #[test]
969    #[cfg(feature = "material-icons")]
970    fn custom_icon_via_dyn_dispatch() {
971        let boxed: Box<dyn IconProvider> = Box::new(IconRole::ActionCopy);
972        let provider: &dyn IconProvider = &*boxed;
973        let result = MaterialLoader::new(provider).load();
974        assert!(
975            result.is_some(),
976            "dyn dispatch through Box<dyn IconProvider> should work"
977        );
978    }
979
980    #[test]
981    #[cfg(feature = "material-icons")]
982    fn custom_icon_bundled_svg_fallback() {
983        // Provider that returns None from icon_name but Some from icon_svg
984        #[derive(Debug)]
985        struct SvgOnlyProvider;
986        impl IconProvider for SvgOnlyProvider {
987            fn icon_name(&self, _set: IconSet) -> Option<&str> {
988                None
989            }
990            fn icon_svg(&self, _set: IconSet) -> Option<Cow<'static, [u8]>> {
991                Some(Cow::Borrowed(b"<svg>test</svg>"))
992            }
993        }
994
995        let provider: &dyn IconProvider = &SvgOnlyProvider;
996        let result = MaterialLoader::new(provider).load();
997        assert!(
998            result.is_some(),
999            "provider with icon_svg should return Some"
1000        );
1001        match result.unwrap() {
1002            IconData::Svg(ref cow) => {
1003                assert_eq!(cow.as_ref(), b"<svg>test</svg>");
1004            }
1005            _ => panic!("expected IconData::Svg"),
1006        }
1007    }
1008}
1009
1010#[cfg(test)]
1011#[allow(clippy::unwrap_used, clippy::expect_used)]
1012mod loading_indicator_tests {
1013    use super::*;
1014
1015    // === Dispatch tests (through per-set loader API) ===
1016
1017    #[test]
1018    #[cfg(feature = "lucide-icons")]
1019    fn loading_indicator_lucide_returns_frames() {
1020        let anim = LucideLoader::load_indicator();
1021        assert!(anim.is_some(), "lucide should return Some");
1022        let anim = anim.unwrap();
1023        assert!(
1024            matches!(anim, AnimatedIcon::Frames(_)),
1025            "lucide should be pre-rotated Frames"
1026        );
1027        if let AnimatedIcon::Frames(data) = &anim {
1028            assert_eq!(data.frames().len(), 24);
1029            assert_eq!(data.frame_duration_ms().get(), 42);
1030        }
1031    }
1032
1033    /// Freedesktop loading_indicator returns Some if the active icon theme
1034    /// has a `process-working` sprite sheet (e.g. Breeze), None otherwise.
1035    #[test]
1036    #[cfg(all(target_os = "linux", feature = "system-icons"))]
1037    fn loading_indicator_freedesktop_depends_on_theme() {
1038        let anim = FreedesktopLoader::load_indicator(None);
1039        // Result depends on installed icon theme -- Some if process-working exists
1040        if let Some(anim) = anim {
1041            match anim {
1042                AnimatedIcon::Frames(data) => {
1043                    assert!(
1044                        !data.frames().is_empty(),
1045                        "Frames variant should have at least one frame"
1046                    );
1047                }
1048                AnimatedIcon::Transform(_) => {
1049                    // Single-frame theme icon with Spin -- valid result
1050                }
1051                _ => {}
1052            }
1053        }
1054    }
1055
1056    /// Freedesktop spinner depends on platform and icon theme.
1057    #[test]
1058    fn loading_indicator_freedesktop_does_not_panic() {
1059        let _result = FreedesktopLoader::load_indicator(None);
1060    }
1061
1062    // === Direct spinner construction tests (any platform) ===
1063
1064    #[test]
1065    #[cfg(feature = "lucide-icons")]
1066    fn lucide_spinner_is_frames() {
1067        let anim = crate::spinners::lucide_spinner();
1068        assert!(
1069            matches!(anim, AnimatedIcon::Frames(_)),
1070            "lucide should be pre-rotated Frames"
1071        );
1072    }
1073}
1074
1075// === New builder API tests ===
1076
1077#[cfg(test)]
1078#[allow(clippy::unwrap_used, clippy::expect_used)]
1079mod icon_loader_tests {
1080    use super::*;
1081
1082    #[test]
1083    #[cfg(feature = "material-icons")]
1084    fn icon_loader_basic_role() {
1085        let icon = MaterialLoader::new(IconRole::ActionCopy).load();
1086        assert!(icon.is_some());
1087    }
1088
1089    #[test]
1090    #[cfg(feature = "material-icons")]
1091    fn icon_loader_by_name() {
1092        let icon = MaterialLoader::new("content_copy").load();
1093        assert!(icon.is_some());
1094    }
1095
1096    #[test]
1097    #[cfg(feature = "material-icons")]
1098    fn icon_loader_custom_provider() {
1099        let provider: &dyn IconProvider = &IconRole::ActionCopy;
1100        let icon = MaterialLoader::new(provider).load();
1101        assert!(icon.is_some());
1102    }
1103
1104    #[test]
1105    #[cfg(all(target_os = "linux", feature = "system-icons"))]
1106    fn freedesktop_loader_builder_chain_compiles() {
1107        // Smoke test: the builder chain constructs without runtime errors.
1108        // Size propagates through; the actual load result depends on the
1109        // system theme having 'document-save' at size 48.
1110        let _ = FreedesktopLoader::new(IconRole::ActionSave)
1111            .size(48)
1112            .color([0, 0, 0])
1113            .theme("Adwaita")
1114            .load();
1115    }
1116
1117    #[test]
1118    #[cfg(feature = "material-icons")]
1119    fn icon_loader_load_indicator() {
1120        let anim = MaterialLoader::load_indicator();
1121        assert!(anim.is_some());
1122    }
1123
1124    #[test]
1125    fn load_icon_free_fn_dispatches() {
1126        // load_icon() free function routes to the right per-set loader.
1127        // SfSymbols on Linux is cfg-gated to macOS => None, no panic.
1128        let _ = load_icon(IconRole::ActionCopy, IconSet::SfSymbols);
1129    }
1130
1131    #[test]
1132    fn load_icon_indicator_free_fn_dispatches() {
1133        // SfSymbols and SegoeIcons have no spinner primitive.
1134        assert!(load_icon_indicator(IconSet::SfSymbols).is_none());
1135        assert!(load_icon_indicator(IconSet::SegoeIcons).is_none());
1136    }
1137}
1138
1139#[cfg(all(test, feature = "svg-rasterize"))]
1140#[allow(clippy::unwrap_used, clippy::expect_used)]
1141mod spinner_rasterize_tests {
1142    use super::*;
1143
1144    #[test]
1145    #[cfg(feature = "lucide-icons")]
1146    fn lucide_spinner_icon_rasterizes() {
1147        let anim = crate::spinners::lucide_spinner();
1148        if let AnimatedIcon::Frames(data) = &anim {
1149            let first = data.frames().first();
1150            if let IconData::Svg(cow) = first {
1151                let result = crate::rasterize::rasterize_svg(cow, 24);
1152                assert!(result.is_ok(), "lucide loader should rasterize");
1153                if let Ok(IconData::Rgba { data, .. }) = &result {
1154                    assert!(
1155                        data.iter().any(|&b| b != 0),
1156                        "lucide loader rasterized to empty image"
1157                    );
1158                }
1159            } else {
1160                panic!("lucide spinner frame should be Svg");
1161            }
1162        } else {
1163            panic!("lucide spinner should be Frames");
1164        }
1165    }
1166}
1167
1168// =============================================================================
1169// IconSetChoice tests
1170// =============================================================================
1171
1172#[cfg(test)]
1173mod icon_set_choice_tests {
1174    use super::*;
1175
1176    #[test]
1177    fn test_icon_set_choice_display_default() {
1178        let choice = IconSetChoice::Default("Adwaita".to_string());
1179        assert_eq!(choice.to_string(), "default (Adwaita)");
1180    }
1181
1182    #[test]
1183    fn test_icon_set_choice_display_material() {
1184        assert_eq!(IconSetChoice::Material.to_string(), "Material (bundled)");
1185    }
1186
1187    #[test]
1188    fn test_icon_set_choice_display_lucide() {
1189        assert_eq!(IconSetChoice::Lucide.to_string(), "Lucide (bundled)");
1190    }
1191
1192    #[test]
1193    fn test_icon_set_choice_display_freedesktop() {
1194        let choice = IconSetChoice::Freedesktop("breeze".to_string());
1195        assert_eq!(choice.to_string(), "breeze");
1196    }
1197
1198    #[test]
1199    fn test_icon_set_choice_follows_preset() {
1200        assert!(IconSetChoice::Default("Adwaita".to_string()).follows_preset());
1201        assert!(!IconSetChoice::System.follows_preset());
1202        assert!(!IconSetChoice::Freedesktop("breeze".to_string()).follows_preset());
1203        assert!(!IconSetChoice::Material.follows_preset());
1204        assert!(!IconSetChoice::Lucide.follows_preset());
1205    }
1206
1207    #[test]
1208    fn test_icon_set_choice_effective_icon_set() {
1209        // Default returns whatever the theme specifies
1210        let choice = IconSetChoice::Default("Adwaita".to_string());
1211        assert_eq!(
1212            choice.effective_icon_set(IconSet::Freedesktop),
1213            IconSet::Freedesktop
1214        );
1215        assert_eq!(
1216            choice.effective_icon_set(IconSet::Material),
1217            IconSet::Material
1218        );
1219
1220        // System returns the platform's icon set
1221        let sys = IconSetChoice::System.effective_icon_set(IconSet::Material);
1222        assert_eq!(sys, system_icon_set());
1223
1224        // Freedesktop always returns Freedesktop
1225        let choice = IconSetChoice::Freedesktop("breeze".to_string());
1226        assert_eq!(
1227            choice.effective_icon_set(IconSet::Material),
1228            IconSet::Freedesktop
1229        );
1230
1231        // Bundled sets return themselves
1232        assert_eq!(
1233            IconSetChoice::Material.effective_icon_set(IconSet::Freedesktop),
1234            IconSet::Material
1235        );
1236        assert_eq!(
1237            IconSetChoice::Lucide.effective_icon_set(IconSet::Freedesktop),
1238            IconSet::Lucide
1239        );
1240    }
1241
1242    #[test]
1243    fn test_icon_set_choice_freedesktop_theme() {
1244        assert_eq!(
1245            IconSetChoice::Default("Adwaita".to_string()).freedesktop_theme(),
1246            Some("Adwaita")
1247        );
1248        assert_eq!(
1249            IconSetChoice::Freedesktop("breeze".to_string()).freedesktop_theme(),
1250            Some("breeze")
1251        );
1252        assert_eq!(IconSetChoice::System.freedesktop_theme(), None);
1253        assert_eq!(IconSetChoice::Material.freedesktop_theme(), None);
1254        assert_eq!(IconSetChoice::Lucide.freedesktop_theme(), None);
1255    }
1256
1257    #[test]
1258    fn test_default_icon_choice_none() {
1259        // When icon_theme is None, always returns System regardless of icon_set
1260        assert_eq!(
1261            default_icon_choice(IconSet::Freedesktop, None),
1262            IconSetChoice::System
1263        );
1264        assert_eq!(
1265            default_icon_choice(IconSet::Material, None),
1266            IconSetChoice::System
1267        );
1268    }
1269
1270    #[test]
1271    fn test_default_icon_choice_bundled() {
1272        // Material and Lucide are always available
1273        assert_eq!(
1274            default_icon_choice(IconSet::Material, Some("any-theme")),
1275            IconSetChoice::Default("any-theme".to_string())
1276        );
1277        assert_eq!(
1278            default_icon_choice(IconSet::Lucide, Some("any-theme")),
1279            IconSetChoice::Default("any-theme".to_string())
1280        );
1281    }
1282
1283    #[test]
1284    fn test_list_freedesktop_themes_no_panic() {
1285        // Just verify it doesn't panic -- result varies by platform
1286        let themes = list_freedesktop_themes();
1287        // On Linux, should return a non-empty list on most desktop systems.
1288        // On other platforms, returns empty vec.
1289        #[cfg(not(target_os = "linux"))]
1290        assert!(themes.is_empty());
1291        // Suppress unused variable warning
1292        let _ = themes;
1293    }
1294}