Skip to main content

native_theme/model/
icons.rs

1// Icon type definitions: IconRole, IconData, IconSet
2//
3// These are the core icon types for the native-theme icon system.
4
5use std::borrow::Cow;
6
7use serde::{Deserialize, Serialize};
8
9/// Semantic icon roles for cross-platform icon resolution.
10///
11/// Each variant represents a conceptual icon role (not a specific icon image).
12/// Platform-specific icon identifiers are resolved via
13/// [`icon_name()`](crate::icon_name) using an [`IconSet`].
14///
15/// # Categories
16///
17/// Variants are grouped by prefix into 7 categories:
18/// - **Dialog** (6): Alerts and dialog indicators
19/// - **Window** (4): Window control buttons
20/// - **Action** (14): Common user actions
21/// - **Navigation** (6): Directional and structural navigation
22/// - **Files** (5): File and folder representations
23/// - **Status** (3): State indicators
24/// - **System** (4): System-level UI elements
25///
26/// # Examples
27///
28/// ```
29/// use native_theme::theme::IconRole;
30///
31/// let role = IconRole::ActionSave;
32/// match role {
33///     IconRole::ActionSave => println!("save icon"),
34///     _ => println!("other icon"),
35/// }
36///
37/// // Iterate all roles
38/// assert_eq!(IconRole::ALL.len(), 42);
39/// ```
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
41#[non_exhaustive]
42pub enum IconRole {
43    // Dialog / Alert (6)
44    /// Warning indicator for dialogs
45    DialogWarning,
46    /// Error indicator for dialogs
47    DialogError,
48    /// Informational indicator for dialogs
49    DialogInfo,
50    /// Question indicator for dialogs
51    DialogQuestion,
52    /// Success/confirmation indicator for dialogs
53    DialogSuccess,
54    /// Security/shield indicator
55    Shield,
56
57    // Window Controls (4)
58    /// Close window button
59    WindowClose,
60    /// Minimize window button
61    WindowMinimize,
62    /// Maximize window button
63    WindowMaximize,
64    /// Restore window button (from maximized state)
65    WindowRestore,
66
67    // Common Actions (14)
68    /// Save action
69    ActionSave,
70    /// Delete action
71    ActionDelete,
72    /// Copy to clipboard
73    ActionCopy,
74    /// Paste from clipboard
75    ActionPaste,
76    /// Cut to clipboard
77    ActionCut,
78    /// Undo last action
79    ActionUndo,
80    /// Redo last undone action
81    ActionRedo,
82    /// Search / find
83    ActionSearch,
84    /// Settings / preferences
85    ActionSettings,
86    /// Edit / modify
87    ActionEdit,
88    /// Add / create new item
89    ActionAdd,
90    /// Remove item
91    ActionRemove,
92    /// Refresh / reload
93    ActionRefresh,
94    /// Print
95    ActionPrint,
96
97    // Navigation (6)
98    /// Navigate backward
99    NavBack,
100    /// Navigate forward
101    NavForward,
102    /// Navigate up in hierarchy
103    NavUp,
104    /// Navigate down in hierarchy
105    NavDown,
106    /// Navigate to home / root
107    NavHome,
108    /// Open menu / hamburger
109    NavMenu,
110
111    // Files / Places (5)
112    /// Generic file icon
113    FileGeneric,
114    /// Closed folder
115    FolderClosed,
116    /// Open folder
117    FolderOpen,
118    /// Empty trash / recycle bin
119    TrashEmpty,
120    /// Full trash / recycle bin
121    TrashFull,
122
123    // Status (3)
124    /// Busy / working state indicator
125    StatusBusy,
126    /// Check / success indicator
127    StatusCheck,
128    /// Error state indicator
129    StatusError,
130
131    // System (4)
132    /// User account / profile
133    UserAccount,
134    /// Notification / bell
135    Notification,
136    /// Help / question mark
137    Help,
138    /// Lock / security
139    Lock,
140}
141
142impl std::fmt::Display for IconRole {
143    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
144        f.write_str(self.name())
145    }
146}
147
148impl IconRole {
149    /// The kebab-case string identifier for this icon role.
150    ///
151    /// Returns a stable string suitable for logs, serialization, and
152    /// display. Category prefix and variant name are joined with hyphens
153    /// in lowercase (e.g., `DialogWarning` -> `"dialog-warning"`).
154    ///
155    /// # Examples
156    ///
157    /// ```
158    /// use native_theme::theme::IconRole;
159    ///
160    /// assert_eq!(IconRole::ActionSave.name(), "action-save");
161    /// assert_eq!(IconRole::DialogWarning.name(), "dialog-warning");
162    /// ```
163    #[must_use]
164    pub fn name(&self) -> &'static str {
165        match self {
166            // Dialog (6)
167            Self::DialogWarning => "dialog-warning",
168            Self::DialogError => "dialog-error",
169            Self::DialogInfo => "dialog-info",
170            Self::DialogQuestion => "dialog-question",
171            Self::DialogSuccess => "dialog-success",
172            Self::Shield => "shield",
173            // Window (4)
174            Self::WindowClose => "window-close",
175            Self::WindowMinimize => "window-minimize",
176            Self::WindowMaximize => "window-maximize",
177            Self::WindowRestore => "window-restore",
178            // Action (14)
179            Self::ActionSave => "action-save",
180            Self::ActionDelete => "action-delete",
181            Self::ActionCopy => "action-copy",
182            Self::ActionPaste => "action-paste",
183            Self::ActionCut => "action-cut",
184            Self::ActionUndo => "action-undo",
185            Self::ActionRedo => "action-redo",
186            Self::ActionSearch => "action-search",
187            Self::ActionSettings => "action-settings",
188            Self::ActionEdit => "action-edit",
189            Self::ActionAdd => "action-add",
190            Self::ActionRemove => "action-remove",
191            Self::ActionRefresh => "action-refresh",
192            Self::ActionPrint => "action-print",
193            // Navigation (6)
194            Self::NavBack => "nav-back",
195            Self::NavForward => "nav-forward",
196            Self::NavUp => "nav-up",
197            Self::NavDown => "nav-down",
198            Self::NavHome => "nav-home",
199            Self::NavMenu => "nav-menu",
200            // Files (5)
201            Self::FileGeneric => "file-generic",
202            Self::FolderClosed => "folder-closed",
203            Self::FolderOpen => "folder-open",
204            Self::TrashEmpty => "trash-empty",
205            Self::TrashFull => "trash-full",
206            // Status (3)
207            Self::StatusBusy => "status-busy",
208            Self::StatusCheck => "status-check",
209            Self::StatusError => "status-error",
210            // System (4)
211            Self::UserAccount => "user-account",
212            Self::Notification => "notification",
213            Self::Help => "help",
214            Self::Lock => "lock",
215        }
216    }
217
218    /// All icon role variants, useful for iteration and exhaustive testing.
219    ///
220    /// Contains exactly 42 variants, one for each role, in declaration order.
221    pub const ALL: [IconRole; 42] = [
222        // Dialog (6)
223        Self::DialogWarning,
224        Self::DialogError,
225        Self::DialogInfo,
226        Self::DialogQuestion,
227        Self::DialogSuccess,
228        Self::Shield,
229        // Window (4)
230        Self::WindowClose,
231        Self::WindowMinimize,
232        Self::WindowMaximize,
233        Self::WindowRestore,
234        // Action (14)
235        Self::ActionSave,
236        Self::ActionDelete,
237        Self::ActionCopy,
238        Self::ActionPaste,
239        Self::ActionCut,
240        Self::ActionUndo,
241        Self::ActionRedo,
242        Self::ActionSearch,
243        Self::ActionSettings,
244        Self::ActionEdit,
245        Self::ActionAdd,
246        Self::ActionRemove,
247        Self::ActionRefresh,
248        Self::ActionPrint,
249        // Navigation (6)
250        Self::NavBack,
251        Self::NavForward,
252        Self::NavUp,
253        Self::NavDown,
254        Self::NavHome,
255        Self::NavMenu,
256        // Files (5)
257        Self::FileGeneric,
258        Self::FolderClosed,
259        Self::FolderOpen,
260        Self::TrashEmpty,
261        Self::TrashFull,
262        // Status (3)
263        Self::StatusBusy,
264        Self::StatusCheck,
265        Self::StatusError,
266        // System (4)
267        Self::UserAccount,
268        Self::Notification,
269        Self::Help,
270        Self::Lock,
271    ];
272}
273
274/// Icon data returned by loading functions.
275///
276/// Represents the actual pixel or vector data for an icon. This type is
277/// produced by platform icon loaders and bundled icon accessors.
278///
279/// # Examples
280///
281/// ```
282/// use native_theme::theme::IconData;
283/// use std::borrow::Cow;
284///
285/// let svg = IconData::Svg(Cow::Borrowed(b"<svg></svg>"));
286/// assert_eq!(svg.bytes(), b"<svg></svg>");
287///
288/// let rgba = IconData::Rgba { width: 16, height: 16, data: vec![0; 16*16*4] };
289/// assert_eq!(rgba.bytes().len(), 16 * 16 * 4);
290/// ```
291#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
292#[non_exhaustive]
293#[must_use]
294pub enum IconData {
295    /// SVG content as raw bytes (from freedesktop themes, bundled icon sets).
296    ///
297    /// Bundled icons use `Cow::Borrowed` for zero-copy access to compile-time
298    /// embedded data. Runtime-loaded icons (freedesktop, custom providers)
299    /// use `Cow::Owned`.
300    Svg(Cow<'static, [u8]>),
301
302    /// Rasterized RGBA pixels (from macOS/Windows system APIs).
303    Rgba {
304        /// Image width in pixels.
305        width: u32,
306        /// Image height in pixels.
307        height: u32,
308        /// Raw RGBA pixel data (4 bytes per pixel, row-major).
309        data: Vec<u8>,
310    },
311}
312
313impl IconData {
314    /// Borrow the underlying bytes regardless of variant or ownership.
315    ///
316    /// For `Svg`, returns the SVG content bytes.
317    /// For `Rgba`, returns the raw pixel data.
318    #[must_use]
319    pub fn bytes(&self) -> &[u8] {
320        match self {
321            IconData::Svg(cow) => cow,
322            IconData::Rgba { data, .. } => data,
323        }
324    }
325}
326
327/// Known icon sets that provide platform-specific icon identifiers.
328///
329/// Each variant corresponds to a well-known icon naming system.
330/// Use [`from_name`](IconSet::from_name) to parse from TOML strings
331/// and [`name`](IconSet::name) to serialize back to kebab-case.
332///
333/// # Examples
334///
335/// ```
336/// use native_theme::theme::IconSet;
337///
338/// let set = IconSet::from_name("sf-symbols").unwrap();
339/// assert_eq!(set, IconSet::SfSymbols);
340/// assert_eq!(set.name(), "sf-symbols");
341///
342/// // Round-trip
343/// let name = IconSet::Material.name();
344/// assert_eq!(IconSet::from_name(name), Some(IconSet::Material));
345///
346/// // Unknown names return None
347/// assert_eq!(IconSet::from_name("unknown"), None);
348/// ```
349#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
350#[serde(rename_all = "kebab-case")]
351#[non_exhaustive]
352pub enum IconSet {
353    /// Apple SF Symbols (macOS, iOS).
354    SfSymbols,
355    /// Microsoft Segoe Fluent Icons (Windows).
356    #[serde(rename = "segoe-fluent")]
357    SegoeIcons,
358    /// freedesktop Icon Naming Specification (Linux).
359    Freedesktop,
360    /// Google Material Symbols.
361    Material,
362    /// Lucide Icons (fork of Feather).
363    Lucide,
364}
365
366impl std::fmt::Display for IconSet {
367    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
368        f.write_str(self.name())
369    }
370}
371
372impl IconSet {
373    /// Parse an icon set from its kebab-case string identifier.
374    ///
375    /// Accepts the names used in TOML configuration:
376    /// `"sf-symbols"`, `"segoe-fluent"`, `"freedesktop"`, `"material"`, `"lucide"`.
377    ///
378    /// Returns `None` for unrecognized names.
379    #[must_use]
380    pub fn from_name(name: &str) -> Option<Self> {
381        match name {
382            "sf-symbols" => Some(Self::SfSymbols),
383            "segoe-fluent" => Some(Self::SegoeIcons),
384            "freedesktop" => Some(Self::Freedesktop),
385            "material" => Some(Self::Material),
386            "lucide" => Some(Self::Lucide),
387            _ => None,
388        }
389    }
390
391    /// The kebab-case string identifier for this icon set, as used in TOML.
392    #[must_use]
393    pub fn name(&self) -> &'static str {
394        match self {
395            Self::SfSymbols => "sf-symbols",
396            Self::SegoeIcons => "segoe-fluent",
397            Self::Freedesktop => "freedesktop",
398            Self::Material => "material",
399            Self::Lucide => "lucide",
400        }
401    }
402}
403
404/// Trait for types that map icon identifiers to platform-specific names and SVG data.
405///
406/// Implement this trait on an enum to make its variants loadable via
407/// the typed per-set loaders in [`crate::icons`]. The typical pattern is
408/// for each enum variant to represent an icon role, with `icon_name()` returning
409/// the platform-specific identifier and `icon_svg()` returning embedded SVG bytes.
410///
411/// The `native-theme-build` crate can auto-generate implementations from TOML
412/// definitions at build time, so manual implementation is only needed for
413/// special cases.
414///
415/// [`IconRole`] implements this trait, delegating to the built-in icon mappings.
416///
417/// # Object Safety
418///
419/// This trait is object-safe (only requires [`Debug`] as a supertrait).
420/// `Box<dyn IconProvider>` works for dynamic dispatch.
421///
422/// # Examples
423///
424/// ```
425/// use native_theme::theme::{IconProvider, IconSet};
426/// use std::borrow::Cow;
427///
428/// #[derive(Debug)]
429/// enum MyIcon { Play, Pause }
430///
431/// impl IconProvider for MyIcon {
432///     fn icon_name(&self, set: IconSet) -> Option<&str> {
433///         match (self, set) {
434///             (MyIcon::Play, IconSet::SfSymbols) => Some("play.fill"),
435///             (MyIcon::Play, IconSet::Material) => Some("play_arrow"),
436///             (MyIcon::Pause, IconSet::SfSymbols) => Some("pause.fill"),
437///             (MyIcon::Pause, IconSet::Material) => Some("pause"),
438///             _ => None,
439///         }
440///     }
441///     fn icon_svg(&self, _set: IconSet) -> Option<Cow<'static, [u8]>> {
442///         None // No bundled SVGs in this example
443///     }
444/// }
445/// ```
446pub trait IconProvider: std::fmt::Debug {
447    /// Return the platform/theme-specific icon name for this icon in the given set.
448    fn icon_name(&self, set: IconSet) -> Option<&str>;
449
450    /// Return bundled SVG bytes for this icon in the given set.
451    ///
452    /// Bundled providers should return `Cow::Borrowed` for zero-copy access.
453    /// Runtime providers (e.g. loading from disk) should return `Cow::Owned`.
454    fn icon_svg(&self, set: IconSet) -> Option<Cow<'static, [u8]>>;
455}
456
457impl IconProvider for IconRole {
458    fn icon_name(&self, set: IconSet) -> Option<&str> {
459        icon_name(*self, set)
460    }
461
462    fn icon_svg(&self, set: IconSet) -> Option<Cow<'static, [u8]>> {
463        crate::model::bundled::bundled_icon_svg(*self, set).map(Cow::Borrowed)
464    }
465}
466
467/// Look up the platform-specific icon identifier for a given icon set and role.
468///
469/// Returns `Some(name)` if the icon set has a standard icon for the role,
470/// or `None` if no standard icon exists (e.g., SF Symbols has no open-folder
471/// variant).
472///
473/// # Examples
474///
475/// ```
476/// use native_theme::theme::{IconSet, IconRole, icon_name};
477///
478/// assert_eq!(icon_name(IconRole::ActionCopy, IconSet::SfSymbols), Some("doc.on.doc"));
479/// assert_eq!(icon_name(IconRole::ActionCopy, IconSet::Freedesktop), Some("edit-copy"));
480/// assert_eq!(icon_name(IconRole::FolderOpen, IconSet::SfSymbols), None);
481/// ```
482#[must_use]
483#[allow(unreachable_patterns)] // wildcard arm kept for #[non_exhaustive] forward compat
484pub fn icon_name(role: IconRole, set: IconSet) -> Option<&'static str> {
485    match set {
486        IconSet::SfSymbols => sf_symbols_name(role),
487        IconSet::SegoeIcons => segoe_name(role),
488        IconSet::Freedesktop => freedesktop_name(role),
489        IconSet::Material => material_name(role),
490        IconSet::Lucide => lucide_name(role),
491        _ => None,
492    }
493}
494
495/// Detect the native icon set for the current operating system.
496///
497/// Returns the platform-appropriate icon set at runtime using `cfg!()` macros:
498/// - macOS / iOS: [`IconSet::SfSymbols`]
499/// - Windows: [`IconSet::SegoeIcons`]
500/// - Linux: [`IconSet::Freedesktop`]
501/// - Other: [`IconSet::Material`] (safe cross-platform fallback)
502///
503/// # Examples
504///
505/// ```
506/// use native_theme::theme::{IconSet, system_icon_set};
507///
508/// let set = system_icon_set();
509/// // On Linux, this returns Freedesktop
510/// ```
511#[must_use]
512pub fn system_icon_set() -> IconSet {
513    if cfg!(any(target_os = "macos", target_os = "ios")) {
514        IconSet::SfSymbols
515    } else if cfg!(target_os = "windows") {
516        IconSet::SegoeIcons
517    } else if cfg!(target_os = "linux") {
518        IconSet::Freedesktop
519    } else {
520        IconSet::Material
521    }
522}
523
524/// Detect the icon theme name for the current platform (cached).
525///
526/// Returns the name of the icon theme that provides the actual icon files:
527/// - **macOS / iOS:** `"sf-symbols"` (no user-configurable icon theme)
528/// - **Windows:** `"segoe-fluent"` (no user-configurable icon theme)
529/// - **Linux:** DE-specific detection (e.g., `"breeze-dark"`, `"Adwaita"`)
530/// - **Other:** `"material"` (bundled fallback)
531///
532/// On Linux, the detection method depends on the desktop environment:
533/// - KDE: reads `[Icons] Theme` from `kdeglobals`
534/// - GNOME/Budgie: `gsettings get org.gnome.desktop.interface icon-theme`
535/// - Cinnamon: `gsettings get org.cinnamon.desktop.interface icon-theme`
536/// - XFCE: `xfconf-query -c xsettings -p /Net/IconThemeName`
537/// - MATE: `gsettings get org.mate.interface icon-theme`
538/// - LXQt: reads `icon_theme` from `~/.config/lxqt/lxqt.conf`
539/// - Unknown: tries KDE, then GNOME gsettings, then `"hicolor"`
540///
541/// Delegates to [`DetectionContext::icon_theme()`](crate::detect::DetectionContext::icon_theme)
542/// which caches the result and supports per-field invalidation via
543/// [`invalidate_caches()`](crate::detect::invalidate_caches).
544///
545/// # Examples
546///
547/// ```
548/// use native_theme::theme::system_icon_theme;
549///
550/// let theme = system_icon_theme();
551/// // On a KDE system with Breeze Dark: "breeze-dark"
552/// // On macOS: "sf-symbols"
553/// ```
554#[must_use]
555pub fn system_icon_theme() -> String {
556    crate::detect::system().icon_theme().to_string()
557}
558
559/// Detect the icon theme name for the current platform without caching.
560///
561/// Unlike [`system_icon_theme()`], this function queries the OS every time it
562/// is called and never caches the result. Use this when polling for icon theme
563/// changes (e.g., the user switches from Breeze to Breeze Dark in system
564/// settings).
565///
566/// See [`system_icon_theme()`] for platform behavior details.
567#[must_use]
568#[allow(unreachable_code)]
569pub fn detect_icon_theme() -> String {
570    #[cfg(any(target_os = "macos", target_os = "ios"))]
571    {
572        return "sf-symbols".to_string();
573    }
574
575    #[cfg(target_os = "windows")]
576    {
577        return "segoe-fluent".to_string();
578    }
579
580    #[cfg(target_os = "linux")]
581    {
582        detect_linux_icon_theme()
583    }
584
585    #[cfg(not(any(
586        target_os = "linux",
587        target_os = "windows",
588        target_os = "macos",
589        target_os = "ios"
590    )))]
591    {
592        "material".to_string()
593    }
594}
595
596/// Linux icon theme detection, dispatched by desktop environment.
597#[cfg(target_os = "linux")]
598fn detect_linux_icon_theme() -> String {
599    let de = crate::detect::detect_linux_desktop();
600
601    match de {
602        crate::detect::LinuxDesktop::Kde => detect_kde_icon_theme(),
603        crate::detect::LinuxDesktop::Gnome
604        | crate::detect::LinuxDesktop::Budgie
605        | crate::detect::LinuxDesktop::Hyprland
606        | crate::detect::LinuxDesktop::Sway
607        | crate::detect::LinuxDesktop::River
608        | crate::detect::LinuxDesktop::Niri
609        | crate::detect::LinuxDesktop::Wayfire
610        | crate::detect::LinuxDesktop::CosmicDe => {
611            gsettings_icon_theme("org.gnome.desktop.interface")
612        }
613        crate::detect::LinuxDesktop::Cinnamon => {
614            gsettings_icon_theme("org.cinnamon.desktop.interface")
615        }
616        crate::detect::LinuxDesktop::Xfce => detect_xfce_icon_theme(),
617        crate::detect::LinuxDesktop::Mate => gsettings_icon_theme("org.mate.interface"),
618        crate::detect::LinuxDesktop::LxQt => detect_lxqt_icon_theme(),
619        crate::detect::LinuxDesktop::Unknown => {
620            let kde = detect_kde_icon_theme();
621            if kde != "hicolor" {
622                return kde;
623            }
624            let gnome = gsettings_icon_theme("org.gnome.desktop.interface");
625            if gnome != "hicolor" {
626                return gnome;
627            }
628            "hicolor".to_string()
629        }
630    }
631}
632
633/// Read icon theme from KDE's kdeglobals INI file.
634///
635/// Checks `~/.config/kdeglobals` first, then `~/.config/kdedefaults/kdeglobals`
636/// (Plasma 6 stores distro defaults there, including the icon theme).
637///
638/// Uses simple line parsing — no `configparser` dependency required — so this
639/// works without the `kde` feature enabled.
640#[cfg(target_os = "linux")]
641fn detect_kde_icon_theme() -> String {
642    let Some(config_dir) = xdg_config_dir() else {
643        return "hicolor".to_string();
644    };
645    let paths = [
646        config_dir.join("kdeglobals"),
647        config_dir.join("kdedefaults").join("kdeglobals"),
648    ];
649
650    for path in &paths {
651        if let Some(theme) = read_ini_value(path, "Icons", "Theme") {
652            return theme;
653        }
654    }
655    "hicolor".to_string()
656}
657
658/// Query gsettings for icon-theme with the given schema.
659#[cfg(target_os = "linux")]
660fn gsettings_icon_theme(schema: &str) -> String {
661    std::process::Command::new("gsettings")
662        .args(["get", schema, "icon-theme"])
663        .output()
664        .ok()
665        .filter(|o| o.status.success())
666        .and_then(|o| String::from_utf8(o.stdout).ok())
667        .map(|s| s.trim().trim_matches('\'').to_string())
668        .filter(|s| !s.is_empty())
669        .unwrap_or_else(|| "hicolor".to_string())
670}
671
672/// Read icon theme from XFCE's xfconf-query.
673#[cfg(target_os = "linux")]
674fn detect_xfce_icon_theme() -> String {
675    std::process::Command::new("xfconf-query")
676        .args(["-c", "xsettings", "-p", "/Net/IconThemeName"])
677        .output()
678        .ok()
679        .filter(|o| o.status.success())
680        .and_then(|o| String::from_utf8(o.stdout).ok())
681        .map(|s| s.trim().to_string())
682        .filter(|s| !s.is_empty())
683        .unwrap_or_else(|| "hicolor".to_string())
684}
685
686/// Read icon theme from LXQt's config file.
687///
688/// LXQt uses a flat `key=value` format (no section headers for the icon_theme
689/// key), so we scan for the bare `icon_theme=` prefix.
690#[cfg(target_os = "linux")]
691fn detect_lxqt_icon_theme() -> String {
692    let Some(config_dir) = xdg_config_dir() else {
693        return "hicolor".to_string();
694    };
695    let path = config_dir.join("lxqt").join("lxqt.conf");
696
697    if let Ok(content) = std::fs::read_to_string(&path) {
698        for line in content.lines() {
699            let trimmed = line.trim();
700            if let Some(value) = trimmed.strip_prefix("icon_theme=") {
701                let value = value.trim();
702                if !value.is_empty() {
703                    return value.to_string();
704                }
705            }
706        }
707    }
708    "hicolor".to_string()
709}
710
711/// Resolve `$XDG_CONFIG_HOME`, falling back to `$HOME/.config`.
712///
713/// Returns `None` when both `$XDG_CONFIG_HOME` and `$HOME` are unset,
714/// avoiding a bogus `/tmp/.config` fallback.
715#[cfg(target_os = "linux")]
716fn xdg_config_dir() -> Option<std::path::PathBuf> {
717    if let Ok(config_home) = std::env::var("XDG_CONFIG_HOME")
718        && !config_home.is_empty()
719    {
720        return Some(std::path::PathBuf::from(config_home));
721    }
722    std::env::var("HOME")
723        .ok()
724        .filter(|h| !h.is_empty())
725        .map(|h| std::path::PathBuf::from(h).join(".config"))
726}
727
728/// Read a value from an INI file by section and key.
729///
730/// Simple line-based parser — no external crate needed. Handles `[Section]`
731/// headers and `Key=Value` lines. Returns `None` if the file doesn't exist,
732/// the section/key is missing, or the value is empty.
733#[cfg(target_os = "linux")]
734fn read_ini_value(path: &std::path::Path, section: &str, key: &str) -> Option<String> {
735    let content = std::fs::read_to_string(path).ok()?;
736    let target_section = format!("[{}]", section);
737    let mut in_section = false;
738
739    for line in content.lines() {
740        let trimmed = line.trim();
741        if trimmed.starts_with('[') {
742            in_section = trimmed == target_section;
743            continue;
744        }
745        if in_section && let Some(value) = trimmed.strip_prefix(key) {
746            let value = value.trim_start();
747            if let Some(value) = value.strip_prefix('=') {
748                let value = value.trim();
749                if !value.is_empty() {
750                    return Some(value.to_string());
751                }
752            }
753        }
754    }
755    None
756}
757
758// --- Private mapping functions ---
759
760#[allow(unreachable_patterns)]
761fn sf_symbols_name(role: IconRole) -> Option<&'static str> {
762    Some(match role {
763        // Dialog / Alert
764        IconRole::DialogWarning => "exclamationmark.triangle.fill",
765        IconRole::DialogError => "xmark.circle.fill",
766        IconRole::DialogInfo => "info.circle.fill",
767        IconRole::DialogQuestion => "questionmark.circle.fill",
768        IconRole::DialogSuccess => "checkmark.circle.fill",
769        IconRole::Shield => "shield.fill",
770
771        // Window Controls
772        IconRole::WindowClose => "xmark",
773        IconRole::WindowMinimize => "minus",
774        IconRole::WindowMaximize => "arrow.up.left.and.arrow.down.right",
775        IconRole::WindowRestore => "arrow.down.right.and.arrow.up.left",
776
777        // Common Actions
778        IconRole::ActionSave => "square.and.arrow.down",
779        IconRole::ActionDelete => "trash",
780        IconRole::ActionCopy => "doc.on.doc",
781        IconRole::ActionPaste => "doc.on.clipboard",
782        IconRole::ActionCut => "scissors",
783        IconRole::ActionUndo => "arrow.uturn.backward",
784        IconRole::ActionRedo => "arrow.uturn.forward",
785        IconRole::ActionSearch => "magnifyingglass",
786        IconRole::ActionSettings => "gearshape",
787        IconRole::ActionEdit => "pencil",
788        IconRole::ActionAdd => "plus",
789        IconRole::ActionRemove => "minus",
790        IconRole::ActionRefresh => "arrow.clockwise",
791        IconRole::ActionPrint => "printer",
792
793        // Navigation
794        IconRole::NavBack => "chevron.backward",
795        IconRole::NavForward => "chevron.forward",
796        IconRole::NavUp => "chevron.up",
797        IconRole::NavDown => "chevron.down",
798        IconRole::NavHome => "house",
799        IconRole::NavMenu => "line.horizontal.3",
800
801        // Files / Places
802        IconRole::FileGeneric => "doc",
803        IconRole::FolderClosed => "folder",
804        // FolderOpen: no SF Symbol equivalent
805        IconRole::FolderOpen => return None,
806        IconRole::TrashEmpty => "trash",
807        IconRole::TrashFull => "trash.fill",
808
809        // Status
810        // StatusBusy: no static SF Symbol (no static busy equivalent)
811        IconRole::StatusBusy => return None,
812        IconRole::StatusCheck => "checkmark",
813        IconRole::StatusError => "xmark.circle.fill",
814
815        // System
816        IconRole::UserAccount => "person.fill",
817        IconRole::Notification => "bell.fill",
818        IconRole::Help => "questionmark.circle",
819        IconRole::Lock => "lock.fill",
820
821        _ => return None,
822    })
823}
824
825#[allow(unreachable_patterns)]
826fn segoe_name(role: IconRole) -> Option<&'static str> {
827    Some(match role {
828        // Dialog / Alert (SHSTOCKICONID constants)
829        IconRole::DialogWarning => "SIID_WARNING",
830        IconRole::DialogError => "SIID_ERROR",
831        IconRole::DialogInfo => "SIID_INFO",
832        IconRole::DialogQuestion => "IDI_QUESTION",
833        IconRole::DialogSuccess => "CheckMark",
834        IconRole::Shield => "SIID_SHIELD",
835
836        // Window Controls (Segoe Fluent Icons glyphs)
837        IconRole::WindowClose => "ChromeClose",
838        IconRole::WindowMinimize => "ChromeMinimize",
839        IconRole::WindowMaximize => "ChromeMaximize",
840        IconRole::WindowRestore => "ChromeRestore",
841
842        // Common Actions (mix of SHSTOCKICONID and Segoe Fluent)
843        IconRole::ActionSave => "Save",
844        IconRole::ActionDelete => "SIID_DELETE",
845        IconRole::ActionCopy => "Copy",
846        IconRole::ActionPaste => "Paste",
847        IconRole::ActionCut => "Cut",
848        IconRole::ActionUndo => "Undo",
849        IconRole::ActionRedo => "Redo",
850        IconRole::ActionSearch => "SIID_FIND",
851        IconRole::ActionSettings => "SIID_SETTINGS",
852        IconRole::ActionEdit => "Edit",
853        IconRole::ActionAdd => "Add",
854        IconRole::ActionRemove => "Remove",
855        IconRole::ActionRefresh => "Refresh",
856        IconRole::ActionPrint => "SIID_PRINTER",
857
858        // Navigation (Segoe Fluent Icons)
859        IconRole::NavBack => "Back",
860        IconRole::NavForward => "Forward",
861        IconRole::NavUp => "Up",
862        IconRole::NavDown => "Down",
863        IconRole::NavHome => "Home",
864        IconRole::NavMenu => "GlobalNavigationButton",
865
866        // Files / Places (SHSTOCKICONID)
867        IconRole::FileGeneric => "SIID_DOCNOASSOC",
868        IconRole::FolderClosed => "SIID_FOLDER",
869        IconRole::FolderOpen => "SIID_FOLDEROPEN",
870        IconRole::TrashEmpty => "SIID_RECYCLER",
871        IconRole::TrashFull => "SIID_RECYCLERFULL",
872
873        // Status
874        // StatusBusy: no static Windows icon (no static busy equivalent)
875        IconRole::StatusBusy => return None,
876        IconRole::StatusCheck => "CheckMark",
877        IconRole::StatusError => "SIID_ERROR",
878
879        // System
880        IconRole::UserAccount => "SIID_USERS",
881        IconRole::Notification => "Ringer",
882        IconRole::Help => "SIID_HELP",
883        IconRole::Lock => "SIID_LOCK",
884
885        _ => return None,
886    })
887}
888
889#[allow(unreachable_patterns)]
890fn freedesktop_name(role: IconRole) -> Option<&'static str> {
891    Some(match role {
892        // Dialog / Alert
893        IconRole::DialogWarning => "dialog-warning",
894        IconRole::DialogError => "dialog-error",
895        IconRole::DialogInfo => "dialog-information",
896        IconRole::DialogQuestion => "dialog-question",
897        // Icon Naming Spec 0.8.90 standard name; Adwaita + Breeze both ship
898        // `object-select-symbolic`. "emblem-ok" (a legacy GNOME-only emblem,
899        // not in the spec) was tried first but is absent from Adwaita.
900        IconRole::DialogSuccess => "object-select-symbolic",
901        IconRole::Shield => "security-high",
902
903        // Window Controls
904        IconRole::WindowClose => "window-close",
905        IconRole::WindowMinimize => "window-minimize",
906        IconRole::WindowMaximize => "window-maximize",
907        IconRole::WindowRestore => "window-restore",
908
909        // Common Actions
910        IconRole::ActionSave => "document-save",
911        IconRole::ActionDelete => "edit-delete",
912        IconRole::ActionCopy => "edit-copy",
913        IconRole::ActionPaste => "edit-paste",
914        IconRole::ActionCut => "edit-cut",
915        IconRole::ActionUndo => "edit-undo",
916        IconRole::ActionRedo => "edit-redo",
917        IconRole::ActionSearch => "edit-find",
918        IconRole::ActionSettings => "preferences-system",
919        IconRole::ActionEdit => "document-edit",
920        IconRole::ActionAdd => "list-add",
921        IconRole::ActionRemove => "list-remove",
922        IconRole::ActionRefresh => "view-refresh",
923        IconRole::ActionPrint => "document-print",
924
925        // Navigation
926        IconRole::NavBack => "go-previous",
927        IconRole::NavForward => "go-next",
928        IconRole::NavUp => "go-up",
929        IconRole::NavDown => "go-down",
930        IconRole::NavHome => "go-home",
931        IconRole::NavMenu => "open-menu",
932
933        // Files / Places
934        IconRole::FileGeneric => "text-x-generic",
935        IconRole::FolderClosed => "folder",
936        IconRole::FolderOpen => "folder-open",
937        IconRole::TrashEmpty => "user-trash",
938        IconRole::TrashFull => "user-trash-full",
939
940        // Status
941        // Three-dot ellipsis loading indicator. Adwaita + Breeze both ship
942        // `content-loading-symbolic`; it's a strict superset of the older
943        // `process-working` name (every theme shipping that ships this too,
944        // plus Adwaita). The animated `process-working` spinner is a
945        // separate code path (see `load_freedesktop_spinner`).
946        IconRole::StatusBusy => "content-loading-symbolic",
947        IconRole::StatusCheck => "emblem-default",
948        IconRole::StatusError => "dialog-error",
949
950        // System
951        IconRole::UserAccount => "system-users",
952        // KDE convention (Breeze, Oxygen); GNOME themes return None from lookup
953        IconRole::Notification => "notification-active",
954        IconRole::Help => "help-browser",
955        IconRole::Lock => "system-lock-screen",
956
957        _ => return None,
958    })
959}
960
961#[allow(unreachable_patterns)]
962fn material_name(role: IconRole) -> Option<&'static str> {
963    Some(match role {
964        // Dialog / Alert
965        IconRole::DialogWarning => "warning",
966        IconRole::DialogError => "error",
967        IconRole::DialogInfo => "info",
968        IconRole::DialogQuestion => "help",
969        IconRole::DialogSuccess => "check_circle",
970        IconRole::Shield => "shield",
971
972        // Window Controls
973        IconRole::WindowClose => "close",
974        IconRole::WindowMinimize => "minimize",
975        IconRole::WindowMaximize => "open_in_full",
976        IconRole::WindowRestore => "close_fullscreen",
977
978        // Common Actions
979        IconRole::ActionSave => "save",
980        IconRole::ActionDelete => "delete",
981        IconRole::ActionCopy => "content_copy",
982        IconRole::ActionPaste => "content_paste",
983        IconRole::ActionCut => "content_cut",
984        IconRole::ActionUndo => "undo",
985        IconRole::ActionRedo => "redo",
986        IconRole::ActionSearch => "search",
987        IconRole::ActionSettings => "settings",
988        IconRole::ActionEdit => "edit",
989        IconRole::ActionAdd => "add",
990        IconRole::ActionRemove => "remove",
991        IconRole::ActionRefresh => "refresh",
992        IconRole::ActionPrint => "print",
993
994        // Navigation
995        IconRole::NavBack => "arrow_back",
996        IconRole::NavForward => "arrow_forward",
997        IconRole::NavUp => "arrow_upward",
998        IconRole::NavDown => "arrow_downward",
999        IconRole::NavHome => "home",
1000        IconRole::NavMenu => "menu",
1001
1002        // Files / Places
1003        IconRole::FileGeneric => "description",
1004        IconRole::FolderClosed => "folder",
1005        IconRole::FolderOpen => "folder_open",
1006        IconRole::TrashEmpty => "delete",
1007        // same as TrashEmpty -- Material has no full-trash variant
1008        IconRole::TrashFull => "delete",
1009
1010        // Status
1011        IconRole::StatusBusy => "progress_activity",
1012        IconRole::StatusCheck => "check",
1013        IconRole::StatusError => "error",
1014
1015        // System
1016        IconRole::UserAccount => "person",
1017        IconRole::Notification => "notifications",
1018        IconRole::Help => "help",
1019        IconRole::Lock => "lock",
1020
1021        _ => return None,
1022    })
1023}
1024
1025#[allow(unreachable_patterns)]
1026fn lucide_name(role: IconRole) -> Option<&'static str> {
1027    Some(match role {
1028        // Dialog / Alert
1029        IconRole::DialogWarning => "triangle-alert",
1030        IconRole::DialogError => "circle-x",
1031        IconRole::DialogInfo => "info",
1032        IconRole::DialogQuestion => "circle-question-mark",
1033        IconRole::DialogSuccess => "circle-check",
1034        IconRole::Shield => "shield",
1035
1036        // Window Controls
1037        IconRole::WindowClose => "x",
1038        IconRole::WindowMinimize => "minimize",
1039        IconRole::WindowMaximize => "maximize",
1040        IconRole::WindowRestore => "minimize-2",
1041
1042        // Common Actions
1043        IconRole::ActionSave => "save",
1044        IconRole::ActionDelete => "trash-2",
1045        IconRole::ActionCopy => "copy",
1046        IconRole::ActionPaste => "clipboard-paste",
1047        IconRole::ActionCut => "scissors",
1048        IconRole::ActionUndo => "undo-2",
1049        IconRole::ActionRedo => "redo-2",
1050        IconRole::ActionSearch => "search",
1051        IconRole::ActionSettings => "settings",
1052        IconRole::ActionEdit => "pencil",
1053        IconRole::ActionAdd => "plus",
1054        IconRole::ActionRemove => "minus",
1055        IconRole::ActionRefresh => "refresh-cw",
1056        IconRole::ActionPrint => "printer",
1057
1058        // Navigation
1059        IconRole::NavBack => "chevron-left",
1060        IconRole::NavForward => "chevron-right",
1061        IconRole::NavUp => "chevron-up",
1062        IconRole::NavDown => "chevron-down",
1063        IconRole::NavHome => "house",
1064        IconRole::NavMenu => "menu",
1065
1066        // Files / Places
1067        IconRole::FileGeneric => "file",
1068        IconRole::FolderClosed => "folder-closed",
1069        IconRole::FolderOpen => "folder-open",
1070        IconRole::TrashEmpty => "trash-2",
1071        // same as TrashEmpty -- Lucide has no full-trash variant
1072        IconRole::TrashFull => "trash-2",
1073
1074        // Status
1075        IconRole::StatusBusy => "loader",
1076        IconRole::StatusCheck => "check",
1077        IconRole::StatusError => "circle-x",
1078
1079        // System
1080        IconRole::UserAccount => "user",
1081        IconRole::Notification => "bell",
1082        IconRole::Help => "circle-question-mark",
1083        IconRole::Lock => "lock",
1084
1085        _ => return None,
1086    })
1087}
1088
1089#[cfg(test)]
1090#[allow(clippy::unwrap_used, clippy::expect_used)]
1091mod tests {
1092    use super::*;
1093
1094    // === IconRole tests ===
1095
1096    #[test]
1097    fn icon_role_all_has_42_variants() {
1098        assert_eq!(IconRole::ALL.len(), 42);
1099    }
1100
1101    #[test]
1102    fn icon_role_all_contains_every_variant() {
1103        // Exhaustive match — adding a new IconRole variant without adding it
1104        // here will cause a compile error (missing match arm). This is valid
1105        // within the defining crate despite #[non_exhaustive].
1106        use std::collections::HashSet;
1107        let all_set: HashSet<IconRole> = IconRole::ALL.iter().copied().collect();
1108        let check = |role: IconRole| {
1109            assert!(
1110                all_set.contains(&role),
1111                "IconRole::{role:?} missing from ALL array"
1112            );
1113        };
1114
1115        // Exhaustive match forces compiler to catch new variants:
1116        #[deny(unreachable_patterns)]
1117        match IconRole::DialogWarning {
1118            IconRole::DialogWarning
1119            | IconRole::DialogError
1120            | IconRole::DialogInfo
1121            | IconRole::DialogQuestion
1122            | IconRole::DialogSuccess
1123            | IconRole::Shield
1124            | IconRole::WindowClose
1125            | IconRole::WindowMinimize
1126            | IconRole::WindowMaximize
1127            | IconRole::WindowRestore
1128            | IconRole::ActionSave
1129            | IconRole::ActionDelete
1130            | IconRole::ActionCopy
1131            | IconRole::ActionPaste
1132            | IconRole::ActionCut
1133            | IconRole::ActionUndo
1134            | IconRole::ActionRedo
1135            | IconRole::ActionSearch
1136            | IconRole::ActionSettings
1137            | IconRole::ActionEdit
1138            | IconRole::ActionAdd
1139            | IconRole::ActionRemove
1140            | IconRole::ActionRefresh
1141            | IconRole::ActionPrint
1142            | IconRole::NavBack
1143            | IconRole::NavForward
1144            | IconRole::NavUp
1145            | IconRole::NavDown
1146            | IconRole::NavHome
1147            | IconRole::NavMenu
1148            | IconRole::FileGeneric
1149            | IconRole::FolderClosed
1150            | IconRole::FolderOpen
1151            | IconRole::TrashEmpty
1152            | IconRole::TrashFull
1153            | IconRole::StatusBusy
1154            | IconRole::StatusCheck
1155            | IconRole::StatusError
1156            | IconRole::UserAccount
1157            | IconRole::Notification
1158            | IconRole::Help
1159            | IconRole::Lock => {}
1160        }
1161
1162        // Verify each variant is in ALL:
1163        check(IconRole::DialogWarning);
1164        check(IconRole::DialogError);
1165        check(IconRole::DialogInfo);
1166        check(IconRole::DialogQuestion);
1167        check(IconRole::DialogSuccess);
1168        check(IconRole::Shield);
1169        check(IconRole::WindowClose);
1170        check(IconRole::WindowMinimize);
1171        check(IconRole::WindowMaximize);
1172        check(IconRole::WindowRestore);
1173        check(IconRole::ActionSave);
1174        check(IconRole::ActionDelete);
1175        check(IconRole::ActionCopy);
1176        check(IconRole::ActionPaste);
1177        check(IconRole::ActionCut);
1178        check(IconRole::ActionUndo);
1179        check(IconRole::ActionRedo);
1180        check(IconRole::ActionSearch);
1181        check(IconRole::ActionSettings);
1182        check(IconRole::ActionEdit);
1183        check(IconRole::ActionAdd);
1184        check(IconRole::ActionRemove);
1185        check(IconRole::ActionRefresh);
1186        check(IconRole::ActionPrint);
1187        check(IconRole::NavBack);
1188        check(IconRole::NavForward);
1189        check(IconRole::NavUp);
1190        check(IconRole::NavDown);
1191        check(IconRole::NavHome);
1192        check(IconRole::NavMenu);
1193        check(IconRole::FileGeneric);
1194        check(IconRole::FolderClosed);
1195        check(IconRole::FolderOpen);
1196        check(IconRole::TrashEmpty);
1197        check(IconRole::TrashFull);
1198        check(IconRole::StatusBusy);
1199        check(IconRole::StatusCheck);
1200        check(IconRole::StatusError);
1201        check(IconRole::UserAccount);
1202        check(IconRole::Notification);
1203        check(IconRole::Help);
1204        check(IconRole::Lock);
1205    }
1206
1207    #[test]
1208    fn icon_role_all_no_duplicates() {
1209        let all = &IconRole::ALL;
1210        for (i, role) in all.iter().enumerate() {
1211            for (j, other) in all.iter().enumerate() {
1212                if i != j {
1213                    assert_ne!(role, other, "Duplicate at index {i} and {j}");
1214                }
1215            }
1216        }
1217    }
1218
1219    #[test]
1220    fn icon_role_derives_copy_clone() {
1221        let role = IconRole::ActionCopy;
1222        let copied1 = role;
1223        let copied2 = role;
1224        assert_eq!(role, copied1);
1225        assert_eq!(role, copied2);
1226    }
1227
1228    #[test]
1229    fn icon_role_derives_debug() {
1230        let s = format!("{:?}", IconRole::DialogWarning);
1231        assert!(s.contains("DialogWarning"));
1232    }
1233
1234    #[test]
1235    fn icon_role_derives_hash() {
1236        use std::collections::HashSet;
1237        let mut set = HashSet::new();
1238        set.insert(IconRole::ActionSave);
1239        set.insert(IconRole::ActionDelete);
1240        assert_eq!(set.len(), 2);
1241        assert!(set.contains(&IconRole::ActionSave));
1242    }
1243
1244    // === IconData tests ===
1245
1246    #[test]
1247    fn icon_data_svg_construct_and_match() {
1248        let data = IconData::Svg(Cow::Borrowed(b"<svg></svg>"));
1249        assert_eq!(data.bytes(), b"<svg></svg>");
1250        match data {
1251            IconData::Svg(ref cow) => assert_eq!(cow.as_ref(), b"<svg></svg>"),
1252            _ => panic!("Expected Svg variant"),
1253        }
1254    }
1255
1256    #[test]
1257    fn icon_data_rgba_construct_and_match() {
1258        let pixels = vec![255, 0, 0, 255]; // 1 red pixel
1259        let data = IconData::Rgba {
1260            width: 1,
1261            height: 1,
1262            data: pixels.clone(),
1263        };
1264        match data {
1265            IconData::Rgba {
1266                width,
1267                height,
1268                data,
1269            } => {
1270                assert_eq!(width, 1);
1271                assert_eq!(height, 1);
1272                assert_eq!(data, pixels);
1273            }
1274            _ => panic!("Expected Rgba variant"),
1275        }
1276    }
1277
1278    #[test]
1279    fn icon_data_derives_debug() {
1280        let data = IconData::Svg(Cow::Borrowed(b""));
1281        let s = format!("{:?}", data);
1282        assert!(s.contains("Svg"));
1283    }
1284
1285    #[test]
1286    fn icon_data_derives_clone() {
1287        let data = IconData::Rgba {
1288            width: 16,
1289            height: 16,
1290            data: vec![0; 16 * 16 * 4],
1291        };
1292        let cloned = data.clone();
1293        assert_eq!(data, cloned);
1294    }
1295
1296    #[test]
1297    fn icon_data_derives_eq() {
1298        let a = IconData::Svg(Cow::Borrowed(b"<svg/>"));
1299        let b = IconData::Svg(Cow::Owned(b"<svg/>".to_vec()));
1300        assert_eq!(a, b);
1301
1302        let c = IconData::Svg(Cow::Borrowed(b"<other/>"));
1303        assert_ne!(a, c);
1304    }
1305
1306    // === IconSet tests ===
1307
1308    #[test]
1309    fn icon_set_from_name_sf_symbols() {
1310        assert_eq!(IconSet::from_name("sf-symbols"), Some(IconSet::SfSymbols));
1311    }
1312
1313    #[test]
1314    fn icon_set_from_name_segoe_fluent() {
1315        assert_eq!(
1316            IconSet::from_name("segoe-fluent"),
1317            Some(IconSet::SegoeIcons)
1318        );
1319    }
1320
1321    #[test]
1322    fn icon_set_from_name_freedesktop() {
1323        assert_eq!(
1324            IconSet::from_name("freedesktop"),
1325            Some(IconSet::Freedesktop)
1326        );
1327    }
1328
1329    #[test]
1330    fn icon_set_from_name_material() {
1331        assert_eq!(IconSet::from_name("material"), Some(IconSet::Material));
1332    }
1333
1334    #[test]
1335    fn icon_set_from_name_lucide() {
1336        assert_eq!(IconSet::from_name("lucide"), Some(IconSet::Lucide));
1337    }
1338
1339    #[test]
1340    fn icon_set_from_name_unknown() {
1341        assert_eq!(IconSet::from_name("unknown"), None);
1342    }
1343
1344    #[test]
1345    fn icon_set_name_sf_symbols() {
1346        assert_eq!(IconSet::SfSymbols.name(), "sf-symbols");
1347    }
1348
1349    #[test]
1350    fn icon_set_name_segoe_fluent() {
1351        assert_eq!(IconSet::SegoeIcons.name(), "segoe-fluent");
1352    }
1353
1354    #[test]
1355    fn icon_set_name_freedesktop() {
1356        assert_eq!(IconSet::Freedesktop.name(), "freedesktop");
1357    }
1358
1359    #[test]
1360    fn icon_set_name_material() {
1361        assert_eq!(IconSet::Material.name(), "material");
1362    }
1363
1364    #[test]
1365    fn icon_set_name_lucide() {
1366        assert_eq!(IconSet::Lucide.name(), "lucide");
1367    }
1368
1369    #[test]
1370    fn icon_set_from_name_name_round_trip() {
1371        let sets = [
1372            IconSet::SfSymbols,
1373            IconSet::SegoeIcons,
1374            IconSet::Freedesktop,
1375            IconSet::Material,
1376            IconSet::Lucide,
1377        ];
1378        for set in &sets {
1379            let name = set.name();
1380            let parsed = IconSet::from_name(name);
1381            assert_eq!(parsed, Some(*set), "Round-trip failed for {:?}", set);
1382        }
1383    }
1384
1385    #[test]
1386    fn icon_set_derives_copy_clone() {
1387        let set = IconSet::Material;
1388        let copied1 = set;
1389        let copied2 = set;
1390        assert_eq!(set, copied1);
1391        assert_eq!(set, copied2);
1392    }
1393
1394    #[test]
1395    fn icon_set_derives_hash() {
1396        use std::collections::HashSet;
1397        let mut map = HashSet::new();
1398        map.insert(IconSet::SfSymbols);
1399        map.insert(IconSet::Lucide);
1400        assert_eq!(map.len(), 2);
1401    }
1402
1403    #[test]
1404    fn icon_set_derives_debug() {
1405        let s = format!("{:?}", IconSet::Freedesktop);
1406        assert!(s.contains("Freedesktop"));
1407    }
1408
1409    #[test]
1410    fn icon_set_serde_round_trip() {
1411        let set = IconSet::SfSymbols;
1412        let json = serde_json::to_string(&set).unwrap();
1413        let deserialized: IconSet = serde_json::from_str(&json).unwrap();
1414        assert_eq!(set, deserialized);
1415    }
1416
1417    // === icon_name() tests ===
1418
1419    #[test]
1420    fn icon_name_sf_symbols_action_copy() {
1421        assert_eq!(
1422            icon_name(IconRole::ActionCopy, IconSet::SfSymbols),
1423            Some("doc.on.doc")
1424        );
1425    }
1426
1427    #[test]
1428    fn icon_name_segoe_action_copy() {
1429        assert_eq!(
1430            icon_name(IconRole::ActionCopy, IconSet::SegoeIcons),
1431            Some("Copy")
1432        );
1433    }
1434
1435    #[test]
1436    fn icon_name_freedesktop_action_copy() {
1437        assert_eq!(
1438            icon_name(IconRole::ActionCopy, IconSet::Freedesktop),
1439            Some("edit-copy")
1440        );
1441    }
1442
1443    #[test]
1444    fn icon_name_material_action_copy() {
1445        assert_eq!(
1446            icon_name(IconRole::ActionCopy, IconSet::Material),
1447            Some("content_copy")
1448        );
1449    }
1450
1451    #[test]
1452    fn icon_name_lucide_action_copy() {
1453        assert_eq!(
1454            icon_name(IconRole::ActionCopy, IconSet::Lucide),
1455            Some("copy")
1456        );
1457    }
1458
1459    #[test]
1460    fn icon_name_sf_symbols_dialog_warning() {
1461        assert_eq!(
1462            icon_name(IconRole::DialogWarning, IconSet::SfSymbols),
1463            Some("exclamationmark.triangle.fill")
1464        );
1465    }
1466
1467    // None cases for known gaps
1468    #[test]
1469    fn icon_name_sf_symbols_folder_open_is_none() {
1470        assert_eq!(icon_name(IconRole::FolderOpen, IconSet::SfSymbols), None);
1471    }
1472
1473    #[test]
1474    fn icon_name_sf_symbols_trash_full() {
1475        assert_eq!(
1476            icon_name(IconRole::TrashFull, IconSet::SfSymbols),
1477            Some("trash.fill")
1478        );
1479    }
1480
1481    #[test]
1482    fn icon_name_sf_symbols_status_busy_is_none() {
1483        assert_eq!(icon_name(IconRole::StatusBusy, IconSet::SfSymbols), None);
1484    }
1485
1486    #[test]
1487    fn icon_name_sf_symbols_window_restore() {
1488        assert_eq!(
1489            icon_name(IconRole::WindowRestore, IconSet::SfSymbols),
1490            Some("arrow.down.right.and.arrow.up.left")
1491        );
1492    }
1493
1494    #[test]
1495    fn icon_name_segoe_dialog_success() {
1496        assert_eq!(
1497            icon_name(IconRole::DialogSuccess, IconSet::SegoeIcons),
1498            Some("CheckMark")
1499        );
1500    }
1501
1502    #[test]
1503    fn icon_name_segoe_status_busy_is_none() {
1504        assert_eq!(icon_name(IconRole::StatusBusy, IconSet::SegoeIcons), None);
1505    }
1506
1507    #[test]
1508    fn icon_name_freedesktop_notification() {
1509        assert_eq!(
1510            icon_name(IconRole::Notification, IconSet::Freedesktop),
1511            Some("notification-active")
1512        );
1513    }
1514
1515    #[test]
1516    fn icon_name_freedesktop_dialog_success() {
1517        // Must be the Icon Naming Spec 0.8.90 standard name "object-select"
1518        // (Adwaita ships it; "emblem-ok" is a legacy GNOME emblem that
1519        // Adwaita does not ship and is not in the spec).
1520        assert_eq!(
1521            icon_name(IconRole::DialogSuccess, IconSet::Freedesktop),
1522            Some("object-select-symbolic")
1523        );
1524    }
1525
1526    #[test]
1527    fn icon_name_freedesktop_status_busy() {
1528        // Must resolve to "content-loading-symbolic" (three-dot ellipsis),
1529        // which Adwaita and Breeze both ship. `process-working` was tried
1530        // first but is absent from Adwaita.
1531        assert_eq!(
1532            icon_name(IconRole::StatusBusy, IconSet::Freedesktop),
1533            Some("content-loading-symbolic")
1534        );
1535    }
1536
1537    #[test]
1538    fn icon_name_material_trash_full() {
1539        assert_eq!(
1540            icon_name(IconRole::TrashFull, IconSet::Material),
1541            Some("delete")
1542        );
1543    }
1544
1545    #[test]
1546    fn icon_name_lucide_trash_full() {
1547        assert_eq!(
1548            icon_name(IconRole::TrashFull, IconSet::Lucide),
1549            Some("trash-2")
1550        );
1551    }
1552
1553    // Spot-check across all 5 icon sets for multiple roles
1554    #[test]
1555    fn icon_name_spot_check_dialog_error() {
1556        assert_eq!(
1557            icon_name(IconRole::DialogError, IconSet::SfSymbols),
1558            Some("xmark.circle.fill")
1559        );
1560        assert_eq!(
1561            icon_name(IconRole::DialogError, IconSet::SegoeIcons),
1562            Some("SIID_ERROR")
1563        );
1564        assert_eq!(
1565            icon_name(IconRole::DialogError, IconSet::Freedesktop),
1566            Some("dialog-error")
1567        );
1568        assert_eq!(
1569            icon_name(IconRole::DialogError, IconSet::Material),
1570            Some("error")
1571        );
1572        assert_eq!(
1573            icon_name(IconRole::DialogError, IconSet::Lucide),
1574            Some("circle-x")
1575        );
1576    }
1577
1578    #[test]
1579    fn icon_name_spot_check_nav_home() {
1580        assert_eq!(
1581            icon_name(IconRole::NavHome, IconSet::SfSymbols),
1582            Some("house")
1583        );
1584        assert_eq!(
1585            icon_name(IconRole::NavHome, IconSet::SegoeIcons),
1586            Some("Home")
1587        );
1588        assert_eq!(
1589            icon_name(IconRole::NavHome, IconSet::Freedesktop),
1590            Some("go-home")
1591        );
1592        assert_eq!(
1593            icon_name(IconRole::NavHome, IconSet::Material),
1594            Some("home")
1595        );
1596        assert_eq!(icon_name(IconRole::NavHome, IconSet::Lucide), Some("house"));
1597    }
1598
1599    // Count test: verify expected Some/None count for each icon set
1600    #[test]
1601    fn icon_name_sf_symbols_expected_count() {
1602        // SF Symbols: 42 - 2 None (FolderOpen, StatusBusy) = 40 Some
1603        let some_count = IconRole::ALL
1604            .iter()
1605            .filter(|r| icon_name(**r, IconSet::SfSymbols).is_some())
1606            .count();
1607        assert_eq!(some_count, 40, "SF Symbols should have 40 mappings");
1608    }
1609
1610    #[test]
1611    fn icon_name_segoe_expected_count() {
1612        // Segoe: 42 - 1 None (StatusBusy) = 41 Some
1613        let some_count = IconRole::ALL
1614            .iter()
1615            .filter(|r| icon_name(**r, IconSet::SegoeIcons).is_some())
1616            .count();
1617        assert_eq!(some_count, 41, "Segoe Icons should have 41 mappings");
1618    }
1619
1620    #[test]
1621    fn icon_name_freedesktop_expected_count() {
1622        // Freedesktop: all 42 roles mapped
1623        let some_count = IconRole::ALL
1624            .iter()
1625            .filter(|r| icon_name(**r, IconSet::Freedesktop).is_some())
1626            .count();
1627        assert_eq!(some_count, 42, "Freedesktop should have 42 mappings");
1628    }
1629
1630    #[test]
1631    fn icon_name_material_expected_count() {
1632        // Material: all 42 roles mapped
1633        let some_count = IconRole::ALL
1634            .iter()
1635            .filter(|r| icon_name(**r, IconSet::Material).is_some())
1636            .count();
1637        assert_eq!(some_count, 42, "Material should have 42 mappings");
1638    }
1639
1640    #[test]
1641    fn icon_name_lucide_expected_count() {
1642        // Lucide: all 42 roles mapped
1643        let some_count = IconRole::ALL
1644            .iter()
1645            .filter(|r| icon_name(**r, IconSet::Lucide).is_some())
1646            .count();
1647        assert_eq!(some_count, 42, "Lucide should have 42 mappings");
1648    }
1649
1650    // === system_icon_set() tests ===
1651
1652    #[test]
1653    #[cfg(target_os = "linux")]
1654    fn system_icon_set_returns_freedesktop_on_linux() {
1655        assert_eq!(system_icon_set(), IconSet::Freedesktop);
1656    }
1657
1658    #[test]
1659    fn system_icon_theme_returns_non_empty() {
1660        let theme = system_icon_theme();
1661        assert!(
1662            !theme.is_empty(),
1663            "system_icon_theme() should return a non-empty string"
1664        );
1665    }
1666
1667    // === IconProvider trait tests ===
1668
1669    #[test]
1670    fn icon_provider_is_object_safe() {
1671        // Box<dyn IconProvider> must compile and be usable
1672        let provider: Box<dyn IconProvider> = Box::new(IconRole::ActionCopy);
1673        let debug_str = format!("{:?}", provider);
1674        assert!(
1675            debug_str.contains("ActionCopy"),
1676            "Debug should print variant name"
1677        );
1678    }
1679
1680    #[test]
1681    fn icon_role_provider_icon_name() {
1682        // IconRole::ActionCopy should return "content_copy" for Material via IconProvider
1683        let role = IconRole::ActionCopy;
1684        let name = IconProvider::icon_name(&role, IconSet::Material);
1685        assert_eq!(name, Some("content_copy"));
1686    }
1687
1688    #[test]
1689    fn icon_role_provider_icon_name_sf_symbols() {
1690        let role = IconRole::ActionCopy;
1691        let name = IconProvider::icon_name(&role, IconSet::SfSymbols);
1692        assert_eq!(name, Some("doc.on.doc"));
1693    }
1694
1695    #[test]
1696    #[cfg(feature = "material-icons")]
1697    fn icon_role_provider_icon_svg_material() {
1698        let role = IconRole::ActionCopy;
1699        let svg = IconProvider::icon_svg(&role, IconSet::Material);
1700        assert!(svg.is_some(), "Material SVG should be Some");
1701        let cow = svg.unwrap();
1702        let content = std::str::from_utf8(&cow).expect("valid UTF-8");
1703        assert!(content.contains("<svg"), "should contain <svg tag");
1704    }
1705
1706    #[test]
1707    fn icon_role_provider_icon_svg_non_bundled() {
1708        // SfSymbols is not a bundled set, so icon_svg should return None
1709        let role = IconRole::ActionCopy;
1710        let svg = IconProvider::icon_svg(&role, IconSet::SfSymbols);
1711        assert!(svg.is_none(), "SfSymbols should not have bundled SVGs");
1712    }
1713
1714    #[test]
1715    fn icon_role_provider_all_roles() {
1716        // All 42 IconRole variants implement IconProvider -- iterate and call icon_name
1717        for role in IconRole::ALL {
1718            // All 42 roles are mapped for Material
1719            let _name = IconProvider::icon_name(&role, IconSet::Material);
1720            // Just verifying it doesn't panic
1721        }
1722    }
1723
1724    #[test]
1725    fn icon_provider_dyn_dispatch() {
1726        // Call icon_name and icon_svg through &dyn IconProvider
1727        let role = IconRole::ActionCopy;
1728        let provider: &dyn IconProvider = &role;
1729        let name = provider.icon_name(IconSet::Material);
1730        assert_eq!(name, Some("content_copy"));
1731        let svg = provider.icon_svg(IconSet::SfSymbols);
1732        assert!(svg.is_none(), "SfSymbols should not have bundled SVGs");
1733    }
1734
1735    // === Coverage tests ===
1736
1737    fn known_gaps() -> &'static [(IconSet, IconRole)] {
1738        &[
1739            (IconSet::SfSymbols, IconRole::FolderOpen),
1740            (IconSet::SfSymbols, IconRole::StatusBusy),
1741            (IconSet::SegoeIcons, IconRole::StatusBusy),
1742        ]
1743    }
1744
1745    #[test]
1746    fn no_unexpected_icon_gaps() {
1747        let gaps = known_gaps();
1748        let system_sets = [
1749            IconSet::SfSymbols,
1750            IconSet::SegoeIcons,
1751            IconSet::Freedesktop,
1752        ];
1753        for &set in &system_sets {
1754            for role in IconRole::ALL {
1755                let is_known_gap = gaps.contains(&(set, role));
1756                let is_mapped = icon_name(role, set).is_some();
1757                if !is_known_gap {
1758                    assert!(
1759                        is_mapped,
1760                        "{role:?} has no mapping for {set:?} and is not in known_gaps()"
1761                    );
1762                }
1763            }
1764        }
1765    }
1766
1767    #[test]
1768    #[cfg(all(feature = "material-icons", feature = "lucide-icons"))]
1769    fn all_roles_have_bundled_svg() {
1770        use crate::bundled_icon_svg;
1771        for set in [IconSet::Material, IconSet::Lucide] {
1772            for role in IconRole::ALL {
1773                assert!(
1774                    bundled_icon_svg(role, set).is_some(),
1775                    "{role:?} has no bundled SVG for {set:?}"
1776                );
1777            }
1778        }
1779    }
1780
1781    /// Exhaustive icon_name() coverage: Material, Lucide, and Freedesktop map ALL 42,
1782    /// Segoe maps at least 41, SF Symbols maps at least 40.
1783    #[test]
1784    fn icon_name_exhaustive_all_sets() {
1785        // Material: all 42
1786        for role in IconRole::ALL {
1787            assert!(
1788                icon_name(role, IconSet::Material).is_some(),
1789                "Material must map {role:?} to Some"
1790            );
1791        }
1792        // Lucide: all 42
1793        for role in IconRole::ALL {
1794            assert!(
1795                icon_name(role, IconSet::Lucide).is_some(),
1796                "Lucide must map {role:?} to Some"
1797            );
1798        }
1799        // Freedesktop: all 42
1800        for role in IconRole::ALL {
1801            assert!(
1802                icon_name(role, IconSet::Freedesktop).is_some(),
1803                "Freedesktop must map {role:?} to Some"
1804            );
1805        }
1806        // Segoe: at least 41 (StatusBusy is None)
1807        let segoe_count = IconRole::ALL
1808            .iter()
1809            .filter(|r| icon_name(**r, IconSet::SegoeIcons).is_some())
1810            .count();
1811        assert!(
1812            segoe_count >= 41,
1813            "Segoe should map at least 41 roles, got {segoe_count}"
1814        );
1815        // SF Symbols: at least 40 (FolderOpen and StatusBusy are None)
1816        let sf_count = IconRole::ALL
1817            .iter()
1818            .filter(|r| icon_name(**r, IconSet::SfSymbols).is_some())
1819            .count();
1820        assert!(
1821            sf_count >= 40,
1822            "SfSymbols should map at least 40 roles, got {sf_count}"
1823        );
1824    }
1825
1826    /// Verify icon_name returns non-empty strings for all mapped roles.
1827    #[test]
1828    fn icon_name_returns_nonempty_strings() {
1829        let all_sets = [
1830            IconSet::SfSymbols,
1831            IconSet::SegoeIcons,
1832            IconSet::Freedesktop,
1833            IconSet::Material,
1834            IconSet::Lucide,
1835        ];
1836        for set in all_sets {
1837            for role in IconRole::ALL {
1838                if let Some(name) = icon_name(role, set) {
1839                    assert!(
1840                        !name.is_empty(),
1841                        "icon_name({role:?}, {set:?}) returned empty string"
1842                    );
1843                }
1844            }
1845        }
1846    }
1847
1848    // === IconSet drift-guard test (ICON-06) ===
1849
1850    #[test]
1851    fn icon_set_name_round_trip() {
1852        // Drift-guard: if a new IconSet variant is added without updating
1853        // from_name(), this test fails.
1854        let all_sets = [
1855            IconSet::SfSymbols,
1856            IconSet::SegoeIcons,
1857            IconSet::Freedesktop,
1858            IconSet::Material,
1859            IconSet::Lucide,
1860        ];
1861        for set in all_sets {
1862            assert_eq!(
1863                IconSet::from_name(set.name()),
1864                Some(set),
1865                "IconSet::{:?}.name() = {:?} did not round-trip through from_name()",
1866                set,
1867                set.name()
1868            );
1869        }
1870    }
1871
1872    // === IconRole::name() tests (ICON-07) ===
1873
1874    #[test]
1875    fn icon_role_name_returns_kebab_case() {
1876        assert_eq!(IconRole::ActionSave.name(), "action-save");
1877        assert_eq!(IconRole::DialogWarning.name(), "dialog-warning");
1878        assert_eq!(IconRole::WindowClose.name(), "window-close");
1879        assert_eq!(IconRole::NavBack.name(), "nav-back");
1880        assert_eq!(IconRole::FileGeneric.name(), "file-generic");
1881        assert_eq!(IconRole::StatusBusy.name(), "status-busy");
1882        assert_eq!(IconRole::UserAccount.name(), "user-account");
1883        assert_eq!(IconRole::Shield.name(), "shield");
1884        assert_eq!(IconRole::Notification.name(), "notification");
1885        assert_eq!(IconRole::Help.name(), "help");
1886        assert_eq!(IconRole::Lock.name(), "lock");
1887    }
1888
1889    #[test]
1890    fn icon_role_display_delegates_to_name() {
1891        for role in IconRole::ALL {
1892            assert_eq!(
1893                format!("{role}"),
1894                role.name(),
1895                "Display for IconRole::{:?} should delegate to name()",
1896                role
1897            );
1898        }
1899    }
1900
1901    // === IconSet serde-vs-name cross-check (GAP-5) ===
1902
1903    #[test]
1904    fn icon_set_serde_matches_name() {
1905        let all_sets = [
1906            IconSet::SfSymbols,
1907            IconSet::SegoeIcons,
1908            IconSet::Freedesktop,
1909            IconSet::Material,
1910            IconSet::Lucide,
1911        ];
1912        for set in all_sets {
1913            let serialized = serde_json::to_string(&set)
1914                .unwrap_or_else(|e| panic!("failed to serialize {set:?}: {e}"));
1915            let trimmed = serialized.trim_matches('"');
1916            assert_eq!(
1917                trimmed,
1918                set.name(),
1919                "serde serialization of {set:?} ({trimmed:?}) does not match name() ({:?})",
1920                set.name()
1921            );
1922        }
1923    }
1924
1925    // === IconData::bytes() accessor test ===
1926
1927    #[test]
1928    fn icon_data_bytes_accessor() {
1929        let svg = IconData::Svg(Cow::Borrowed(b"<svg/>"));
1930        assert_eq!(svg.bytes(), b"<svg/>");
1931
1932        let rgba = IconData::Rgba {
1933            width: 2,
1934            height: 2,
1935            data: vec![1, 2, 3, 4],
1936        };
1937        assert_eq!(rgba.bytes(), &[1, 2, 3, 4]);
1938    }
1939}