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::icons::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!(IconRole::ALL.iter().any(|role| role.name() == "action-save"));
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::icons::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 every variant, one for each role, in declaration order.
221    pub const ALL: &'static [IconRole] = &[
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::icons::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(16, 16, vec![0; 16 * 16 * 4]).unwrap();
289/// assert_eq!(rgba.bytes().len(), 16 * 16 * 4);
290///
291/// // A buffer that is not `width × height × 4` bytes is refused.
292/// assert_eq!(IconData::rgba(16, 16, vec![]), None);
293/// ```
294#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
295#[non_exhaustive]
296#[must_use]
297pub enum IconData {
298    /// SVG content as raw bytes (from freedesktop themes, bundled icon sets).
299    ///
300    /// Bundled icons use `Cow::Borrowed` for zero-copy access to compile-time
301    /// embedded data. Runtime-loaded icons (freedesktop, custom providers)
302    /// use `Cow::Owned`.
303    Svg(Cow<'static, [u8]>),
304
305    /// Rasterized RGBA pixels (from macOS/Windows system APIs).
306    ///
307    /// Built with [`IconData::rgba`], which checks the buffer's length.
308    Rgba(RgbaData),
309}
310
311impl IconData {
312    /// Build an [`IconData::Rgba`] from `width × height` RGBA pixels.
313    ///
314    /// Returns `None` unless `data` holds exactly `width × height × 4` bytes
315    /// (4 bytes per pixel, row-major), or when that product overflows `usize`.
316    #[must_use]
317    pub fn rgba(width: u32, height: u32, data: Vec<u8>) -> Option<Self> {
318        RgbaData::new(width, height, data).map(IconData::Rgba)
319    }
320
321    /// Borrow the underlying bytes regardless of variant or ownership.
322    ///
323    /// For `Svg`, returns the SVG content bytes.
324    /// For `Rgba`, returns the raw pixel data.
325    #[must_use]
326    pub fn bytes(&self) -> &[u8] {
327        match self {
328            IconData::Svg(cow) => cow,
329            IconData::Rgba(rgba) => rgba.data(),
330        }
331    }
332}
333
334/// Rasterized RGBA pixels whose buffer holds exactly `width × height × 4` bytes.
335///
336/// The payload of [`IconData::Rgba`]. The fields are private, so every value
337/// went through [`IconData::rgba`]'s length check; deserializing checks it too.
338///
339/// # Examples
340///
341/// ```
342/// use native_theme::icons::IconData;
343///
344/// let icon = IconData::rgba(2, 1, vec![255, 0, 0, 255, 0, 0, 255, 255]).unwrap();
345/// if let IconData::Rgba(rgba) = &icon {
346///     assert_eq!((rgba.width(), rgba.height()), (2, 1));
347///     assert_eq!(rgba.data().len(), 2 * 4);
348/// }
349/// ```
350#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
351#[serde(try_from = "RawRgbaData")]
352pub struct RgbaData {
353    width: u32,
354    height: u32,
355    data: Vec<u8>,
356}
357
358impl RgbaData {
359    fn new(width: u32, height: u32, data: Vec<u8>) -> Option<Self> {
360        let len = usize::try_from(width)
361            .ok()?
362            .checked_mul(usize::try_from(height).ok()?)?
363            .checked_mul(4)?;
364        (data.len() == len).then_some(Self {
365            width,
366            height,
367            data,
368        })
369    }
370
371    /// Image width in pixels.
372    #[must_use]
373    pub fn width(&self) -> u32 {
374        self.width
375    }
376
377    /// Image height in pixels.
378    #[must_use]
379    pub fn height(&self) -> u32 {
380        self.height
381    }
382
383    /// Raw RGBA pixel data (4 bytes per pixel, row-major), `width × height × 4` bytes.
384    #[must_use]
385    pub fn data(&self) -> &[u8] {
386        &self.data
387    }
388
389    /// Take the raw RGBA pixel data.
390    #[must_use]
391    pub fn into_data(self) -> Vec<u8> {
392        self.data
393    }
394}
395
396/// [`RgbaData`]'s serialized shape, checked by [`RgbaData::try_from`].
397#[derive(Deserialize)]
398struct RawRgbaData {
399    width: u32,
400    height: u32,
401    data: Vec<u8>,
402}
403
404impl TryFrom<RawRgbaData> for RgbaData {
405    type Error = String;
406
407    fn try_from(raw: RawRgbaData) -> Result<Self, Self::Error> {
408        let (width, height, len) = (raw.width, raw.height, raw.data.len());
409        Self::new(width, height, raw.data).ok_or_else(|| {
410            format!("RGBA data of {len} bytes does not match {width} x {height} x 4 bytes")
411        })
412    }
413}
414
415/// Known icon sets that provide platform-specific icon identifiers.
416///
417/// Each variant corresponds to a well-known icon naming system.
418/// Use [`from_name`](IconSet::from_name) to parse from TOML strings
419/// and [`name`](IconSet::name) to serialize back to kebab-case.
420///
421/// # Examples
422///
423/// ```
424/// use native_theme::theme::IconSet;
425///
426/// let set = IconSet::from_name("sf-symbols").unwrap();
427/// assert_eq!(set, IconSet::SfSymbols);
428/// assert_eq!(set.name(), "sf-symbols");
429///
430/// // Round-trip
431/// let name = IconSet::Material.name();
432/// assert_eq!(IconSet::from_name(name), Some(IconSet::Material));
433///
434/// // Unknown names return None
435/// assert_eq!(IconSet::from_name("unknown"), None);
436/// ```
437#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
438#[serde(rename_all = "kebab-case")]
439#[non_exhaustive]
440pub enum IconSet {
441    /// Apple SF Symbols (macOS, iOS).
442    SfSymbols,
443    /// Microsoft Segoe Fluent Icons (Windows): the font's glyphs (Segoe MDL2
444    /// Assets on Windows 10, same code points) and the shell's stock icons
445    /// (`SHGetStockIconInfo`, `LoadIconW`).
446    SegoeFluent,
447    /// freedesktop Icon Naming Specification (Linux).
448    Freedesktop,
449    /// Google Material Symbols.
450    Material,
451    /// Lucide Icons (fork of Feather).
452    Lucide,
453}
454
455impl std::fmt::Display for IconSet {
456    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
457        f.write_str(self.name())
458    }
459}
460
461impl IconSet {
462    /// Parse an icon set from its kebab-case string identifier.
463    ///
464    /// Accepts the names used in TOML configuration:
465    /// `"sf-symbols"`, `"segoe-fluent"`, `"freedesktop"`, `"material"`, `"lucide"`.
466    ///
467    /// Returns `None` for unrecognized names.
468    #[must_use]
469    pub fn from_name(name: &str) -> Option<Self> {
470        match name {
471            "sf-symbols" => Some(Self::SfSymbols),
472            "segoe-fluent" => Some(Self::SegoeFluent),
473            "freedesktop" => Some(Self::Freedesktop),
474            "material" => Some(Self::Material),
475            "lucide" => Some(Self::Lucide),
476            _ => None,
477        }
478    }
479
480    /// The kebab-case string identifier for this icon set, as used in TOML.
481    #[must_use]
482    pub fn name(&self) -> &'static str {
483        match self {
484            Self::SfSymbols => "sf-symbols",
485            Self::SegoeFluent => "segoe-fluent",
486            Self::Freedesktop => "freedesktop",
487            Self::Material => "material",
488            Self::Lucide => "lucide",
489        }
490    }
491}
492
493/// Trait for types that map icon identifiers to platform-specific names and SVG data.
494///
495/// Implement this trait on an enum to make its variants loadable via
496/// the typed per-set loaders in [`crate::icons`]. The typical pattern is
497/// for each enum variant to represent an icon role, with `icon_name()` returning
498/// the platform-specific identifier and `icon_svg()` returning embedded SVG bytes.
499///
500/// The `native-theme-build` crate can auto-generate implementations from TOML
501/// definitions at build time, so manual implementation is only needed for
502/// special cases.
503///
504/// [`IconRole`] implements this trait, delegating to the built-in icon mappings.
505///
506/// # Object Safety
507///
508/// This trait is object-safe (only requires [`Debug`] as a supertrait).
509/// `Box<dyn IconProvider>` works for dynamic dispatch.
510///
511/// # Examples
512///
513/// ```
514/// use native_theme::icons::IconProvider;
515/// use native_theme::theme::IconSet;
516/// use std::borrow::Cow;
517///
518/// #[derive(Debug)]
519/// enum MyIcon { Play, Pause }
520///
521/// impl IconProvider for MyIcon {
522///     fn icon_name(&self, set: IconSet) -> Option<&str> {
523///         match (self, set) {
524///             (MyIcon::Play, IconSet::SfSymbols) => Some("play.fill"),
525///             (MyIcon::Play, IconSet::Material) => Some("play_arrow"),
526///             (MyIcon::Pause, IconSet::SfSymbols) => Some("pause.fill"),
527///             (MyIcon::Pause, IconSet::Material) => Some("pause"),
528///             _ => None,
529///         }
530///     }
531///     fn icon_svg(&self, _set: IconSet) -> Option<Cow<'static, [u8]>> {
532///         None // No bundled SVGs in this example
533///     }
534/// }
535/// ```
536pub trait IconProvider: std::fmt::Debug {
537    /// Return the platform/theme-specific icon name for this icon in the given set.
538    fn icon_name(&self, set: IconSet) -> Option<&str>;
539
540    /// Return bundled SVG bytes for this icon in the given set.
541    ///
542    /// Bundled providers should return `Cow::Borrowed` for zero-copy access.
543    /// Runtime providers (e.g. loading from disk) should return `Cow::Owned`.
544    fn icon_svg(&self, set: IconSet) -> Option<Cow<'static, [u8]>>;
545}
546
547impl IconProvider for IconRole {
548    fn icon_name(&self, set: IconSet) -> Option<&str> {
549        icon_name(*self, set)
550    }
551
552    fn icon_svg(&self, set: IconSet) -> Option<Cow<'static, [u8]>> {
553        crate::model::bundled::bundled_icon_svg(*self, set).map(Cow::Borrowed)
554    }
555}
556
557/// Look up the platform-specific icon identifier for a given icon set and role.
558///
559/// Returns `Some(name)` if the icon set has a standard icon for the role,
560/// or `None` if no standard icon exists (e.g., SF Symbols has no open-folder
561/// variant).
562///
563/// # Examples
564///
565/// ```
566/// use native_theme::icons::{IconRole, icon_name};
567/// use native_theme::theme::IconSet;
568///
569/// assert_eq!(icon_name(IconRole::ActionCopy, IconSet::SfSymbols), Some("doc.on.doc"));
570/// assert_eq!(icon_name(IconRole::ActionCopy, IconSet::Freedesktop), Some("edit-copy"));
571/// assert_eq!(icon_name(IconRole::FolderOpen, IconSet::SfSymbols), None);
572/// ```
573#[must_use]
574#[allow(unreachable_patterns)] // wildcard arm kept for #[non_exhaustive] forward compat
575pub fn icon_name(role: IconRole, set: IconSet) -> Option<&'static str> {
576    match set {
577        IconSet::SfSymbols => sf_symbols_name(role),
578        IconSet::SegoeFluent => segoe_name(role),
579        IconSet::Freedesktop => freedesktop_name(role),
580        IconSet::Material => material_name(role),
581        IconSet::Lucide => lucide_name(role),
582        _ => None,
583    }
584}
585
586// --- Private mapping functions ---
587
588#[allow(unreachable_patterns)]
589fn sf_symbols_name(role: IconRole) -> Option<&'static str> {
590    Some(match role {
591        // Dialog / Alert
592        IconRole::DialogWarning => "exclamationmark.triangle.fill",
593        IconRole::DialogError => "xmark.circle.fill",
594        IconRole::DialogInfo => "info.circle.fill",
595        IconRole::DialogQuestion => "questionmark.circle.fill",
596        IconRole::DialogSuccess => "checkmark.circle.fill",
597        IconRole::Shield => "shield.fill",
598
599        // Window Controls
600        IconRole::WindowClose => "xmark",
601        IconRole::WindowMinimize => "minus",
602        IconRole::WindowMaximize => "arrow.up.left.and.arrow.down.right",
603        IconRole::WindowRestore => "arrow.down.right.and.arrow.up.left",
604
605        // Common Actions
606        IconRole::ActionSave => "square.and.arrow.down",
607        IconRole::ActionDelete => "trash",
608        IconRole::ActionCopy => "doc.on.doc",
609        IconRole::ActionPaste => "doc.on.clipboard",
610        IconRole::ActionCut => "scissors",
611        IconRole::ActionUndo => "arrow.uturn.backward",
612        IconRole::ActionRedo => "arrow.uturn.forward",
613        IconRole::ActionSearch => "magnifyingglass",
614        IconRole::ActionSettings => "gearshape",
615        IconRole::ActionEdit => "pencil",
616        IconRole::ActionAdd => "plus",
617        IconRole::ActionRemove => "minus",
618        IconRole::ActionRefresh => "arrow.clockwise",
619        IconRole::ActionPrint => "printer",
620
621        // Navigation
622        IconRole::NavBack => "chevron.backward",
623        IconRole::NavForward => "chevron.forward",
624        IconRole::NavUp => "chevron.up",
625        IconRole::NavDown => "chevron.down",
626        IconRole::NavHome => "house",
627        IconRole::NavMenu => "line.horizontal.3",
628
629        // Files / Places
630        IconRole::FileGeneric => "doc",
631        IconRole::FolderClosed => "folder",
632        // FolderOpen: no SF Symbol equivalent
633        IconRole::FolderOpen => return None,
634        IconRole::TrashEmpty => "trash",
635        IconRole::TrashFull => "trash.fill",
636
637        // Status
638        // StatusBusy: no static SF Symbol (no static busy equivalent)
639        IconRole::StatusBusy => return None,
640        IconRole::StatusCheck => "checkmark",
641        IconRole::StatusError => "xmark.circle.fill",
642
643        // System
644        IconRole::UserAccount => "person.fill",
645        IconRole::Notification => "bell.fill",
646        IconRole::Help => "questionmark.circle",
647        IconRole::Lock => "lock.fill",
648
649        _ => return None,
650    })
651}
652
653#[allow(unreachable_patterns)]
654fn segoe_name(role: IconRole) -> Option<&'static str> {
655    Some(match role {
656        // Dialog / Alert (SHSTOCKICONID constants)
657        IconRole::DialogWarning => "SIID_WARNING",
658        IconRole::DialogError => "SIID_ERROR",
659        IconRole::DialogInfo => "SIID_INFO",
660        IconRole::DialogQuestion => "IDI_QUESTION",
661        IconRole::DialogSuccess => "CheckMark",
662        IconRole::Shield => "SIID_SHIELD",
663
664        // Window Controls (Segoe Fluent Icons glyphs)
665        IconRole::WindowClose => "ChromeClose",
666        IconRole::WindowMinimize => "ChromeMinimize",
667        IconRole::WindowMaximize => "ChromeMaximize",
668        IconRole::WindowRestore => "ChromeRestore",
669
670        // Common Actions (Segoe Fluent Icons glyphs)
671        IconRole::ActionSave => "Save",
672        IconRole::ActionDelete => "Delete",
673        IconRole::ActionCopy => "Copy",
674        IconRole::ActionPaste => "Paste",
675        IconRole::ActionCut => "Cut",
676        IconRole::ActionUndo => "Undo",
677        IconRole::ActionRedo => "Redo",
678        IconRole::ActionSearch => "Search",
679        IconRole::ActionSettings => "Settings",
680        IconRole::ActionEdit => "Edit",
681        IconRole::ActionAdd => "Add",
682        IconRole::ActionRemove => "Remove",
683        IconRole::ActionRefresh => "Refresh",
684        IconRole::ActionPrint => "Print",
685
686        // Navigation (Segoe Fluent Icons)
687        IconRole::NavBack => "Back",
688        IconRole::NavForward => "Forward",
689        IconRole::NavUp => "Up",
690        IconRole::NavDown => "Down",
691        IconRole::NavHome => "Home",
692        IconRole::NavMenu => "GlobalNavigationButton",
693
694        // Files / Places (SHSTOCKICONID)
695        IconRole::FileGeneric => "SIID_DOCNOASSOC",
696        IconRole::FolderClosed => "SIID_FOLDER",
697        IconRole::FolderOpen => "SIID_FOLDEROPEN",
698        IconRole::TrashEmpty => "SIID_RECYCLER",
699        IconRole::TrashFull => "SIID_RECYCLERFULL",
700
701        // Status
702        // StatusBusy: no static Windows icon (no static busy equivalent)
703        IconRole::StatusBusy => return None,
704        IconRole::StatusCheck => "CheckMark",
705        IconRole::StatusError => "SIID_ERROR",
706
707        // System
708        IconRole::UserAccount => "SIID_USERS",
709        IconRole::Notification => "Ringer",
710        IconRole::Help => "SIID_HELP",
711        IconRole::Lock => "SIID_LOCK",
712
713        _ => return None,
714    })
715}
716
717#[allow(unreachable_patterns)]
718fn freedesktop_name(role: IconRole) -> Option<&'static str> {
719    Some(match role {
720        // Dialog / Alert
721        IconRole::DialogWarning => "dialog-warning",
722        IconRole::DialogError => "dialog-error",
723        IconRole::DialogInfo => "dialog-information",
724        IconRole::DialogQuestion => "dialog-question",
725        // Icon Naming Spec 0.8.90 standard name; Adwaita + Breeze both ship
726        // `object-select-symbolic`. "emblem-ok" (a legacy GNOME-only emblem,
727        // not in the spec) was tried first but is absent from Adwaita.
728        IconRole::DialogSuccess => "object-select-symbolic",
729        IconRole::Shield => "security-high",
730
731        // Window Controls
732        IconRole::WindowClose => "window-close",
733        IconRole::WindowMinimize => "window-minimize",
734        IconRole::WindowMaximize => "window-maximize",
735        IconRole::WindowRestore => "window-restore",
736
737        // Common Actions
738        IconRole::ActionSave => "document-save",
739        IconRole::ActionDelete => "edit-delete",
740        IconRole::ActionCopy => "edit-copy",
741        IconRole::ActionPaste => "edit-paste",
742        IconRole::ActionCut => "edit-cut",
743        IconRole::ActionUndo => "edit-undo",
744        IconRole::ActionRedo => "edit-redo",
745        IconRole::ActionSearch => "edit-find",
746        IconRole::ActionSettings => "preferences-system",
747        IconRole::ActionEdit => "document-edit",
748        IconRole::ActionAdd => "list-add",
749        IconRole::ActionRemove => "list-remove",
750        IconRole::ActionRefresh => "view-refresh",
751        IconRole::ActionPrint => "document-print",
752
753        // Navigation
754        IconRole::NavBack => "go-previous",
755        IconRole::NavForward => "go-next",
756        IconRole::NavUp => "go-up",
757        IconRole::NavDown => "go-down",
758        IconRole::NavHome => "go-home",
759        IconRole::NavMenu => "open-menu",
760
761        // Files / Places
762        IconRole::FileGeneric => "text-x-generic",
763        IconRole::FolderClosed => "folder",
764        IconRole::FolderOpen => "folder-open",
765        IconRole::TrashEmpty => "user-trash",
766        IconRole::TrashFull => "user-trash-full",
767
768        // Status
769        // Three-dot ellipsis loading indicator. Adwaita + Breeze both ship
770        // `content-loading-symbolic`; it's a strict superset of the older
771        // `process-working` name (every theme shipping that ships this too,
772        // plus Adwaita). The animated `process-working` spinner is a
773        // separate code path (see `load_freedesktop_spinner`).
774        IconRole::StatusBusy => "content-loading-symbolic",
775        IconRole::StatusCheck => "emblem-default",
776        IconRole::StatusError => "dialog-error",
777
778        // System
779        IconRole::UserAccount => "system-users",
780        // KDE convention (Breeze, Oxygen); GNOME themes return None from lookup
781        IconRole::Notification => "notification-active",
782        IconRole::Help => "help-browser",
783        IconRole::Lock => "system-lock-screen",
784
785        _ => return None,
786    })
787}
788
789#[allow(unreachable_patterns)]
790fn material_name(role: IconRole) -> Option<&'static str> {
791    Some(match role {
792        // Dialog / Alert
793        IconRole::DialogWarning => "warning",
794        IconRole::DialogError => "error",
795        IconRole::DialogInfo => "info",
796        IconRole::DialogQuestion => "help",
797        IconRole::DialogSuccess => "check_circle",
798        IconRole::Shield => "shield",
799
800        // Window Controls
801        IconRole::WindowClose => "close",
802        IconRole::WindowMinimize => "minimize",
803        IconRole::WindowMaximize => "open_in_full",
804        IconRole::WindowRestore => "close_fullscreen",
805
806        // Common Actions
807        IconRole::ActionSave => "save",
808        IconRole::ActionDelete => "delete",
809        IconRole::ActionCopy => "content_copy",
810        IconRole::ActionPaste => "content_paste",
811        IconRole::ActionCut => "content_cut",
812        IconRole::ActionUndo => "undo",
813        IconRole::ActionRedo => "redo",
814        IconRole::ActionSearch => "search",
815        IconRole::ActionSettings => "settings",
816        IconRole::ActionEdit => "edit",
817        IconRole::ActionAdd => "add",
818        IconRole::ActionRemove => "remove",
819        IconRole::ActionRefresh => "refresh",
820        IconRole::ActionPrint => "print",
821
822        // Navigation
823        IconRole::NavBack => "arrow_back",
824        IconRole::NavForward => "arrow_forward",
825        IconRole::NavUp => "arrow_upward",
826        IconRole::NavDown => "arrow_downward",
827        IconRole::NavHome => "home",
828        IconRole::NavMenu => "menu",
829
830        // Files / Places
831        IconRole::FileGeneric => "description",
832        IconRole::FolderClosed => "folder",
833        IconRole::FolderOpen => "folder_open",
834        IconRole::TrashEmpty => "delete",
835        // same as TrashEmpty -- Material has no full-trash variant
836        IconRole::TrashFull => "delete",
837
838        // Status
839        IconRole::StatusBusy => "progress_activity",
840        IconRole::StatusCheck => "check",
841        IconRole::StatusError => "error",
842
843        // System
844        IconRole::UserAccount => "person",
845        IconRole::Notification => "notifications",
846        IconRole::Help => "help",
847        IconRole::Lock => "lock",
848
849        _ => return None,
850    })
851}
852
853#[allow(unreachable_patterns)]
854fn lucide_name(role: IconRole) -> Option<&'static str> {
855    Some(match role {
856        // Dialog / Alert
857        IconRole::DialogWarning => "triangle-alert",
858        IconRole::DialogError => "circle-x",
859        IconRole::DialogInfo => "info",
860        IconRole::DialogQuestion => "circle-question-mark",
861        IconRole::DialogSuccess => "circle-check",
862        IconRole::Shield => "shield",
863
864        // Window Controls
865        IconRole::WindowClose => "x",
866        IconRole::WindowMinimize => "minimize",
867        IconRole::WindowMaximize => "maximize",
868        IconRole::WindowRestore => "minimize-2",
869
870        // Common Actions
871        IconRole::ActionSave => "save",
872        IconRole::ActionDelete => "trash",
873        IconRole::ActionCopy => "copy",
874        IconRole::ActionPaste => "clipboard-paste",
875        IconRole::ActionCut => "scissors",
876        IconRole::ActionUndo => "undo-2",
877        IconRole::ActionRedo => "redo-2",
878        IconRole::ActionSearch => "search",
879        IconRole::ActionSettings => "settings",
880        IconRole::ActionEdit => "pencil",
881        IconRole::ActionAdd => "plus",
882        IconRole::ActionRemove => "minus",
883        IconRole::ActionRefresh => "refresh-cw",
884        IconRole::ActionPrint => "printer",
885
886        // Navigation
887        IconRole::NavBack => "chevron-left",
888        IconRole::NavForward => "chevron-right",
889        IconRole::NavUp => "chevron-up",
890        IconRole::NavDown => "chevron-down",
891        IconRole::NavHome => "house",
892        IconRole::NavMenu => "menu",
893
894        // Files / Places
895        IconRole::FileGeneric => "file",
896        IconRole::FolderClosed => "folder-closed",
897        IconRole::FolderOpen => "folder-open",
898        IconRole::TrashEmpty => "trash",
899        // same as TrashEmpty -- Lucide has no full-trash variant
900        IconRole::TrashFull => "trash",
901
902        // Status
903        IconRole::StatusBusy => "loader",
904        IconRole::StatusCheck => "check",
905        IconRole::StatusError => "circle-x",
906
907        // System
908        IconRole::UserAccount => "user",
909        IconRole::Notification => "bell",
910        IconRole::Help => "circle-question-mark",
911        IconRole::Lock => "lock",
912
913        _ => return None,
914    })
915}
916
917#[cfg(test)]
918#[allow(clippy::unwrap_used, clippy::expect_used)]
919mod tests {
920    use super::*;
921
922    // === IconRole tests ===
923
924    #[test]
925    fn icon_role_all_has_42_variants() {
926        assert_eq!(IconRole::ALL.len(), 42);
927    }
928
929    #[test]
930    fn icon_role_all_contains_every_variant() {
931        // Exhaustive match — adding a new IconRole variant without adding it
932        // here will cause a compile error (missing match arm). This is valid
933        // within the defining crate despite #[non_exhaustive].
934        use std::collections::HashSet;
935        let all_set: HashSet<IconRole> = IconRole::ALL.iter().copied().collect();
936        let check = |role: IconRole| {
937            assert!(
938                all_set.contains(&role),
939                "IconRole::{role:?} missing from ALL array"
940            );
941        };
942
943        // Exhaustive match forces compiler to catch new variants:
944        #[deny(unreachable_patterns)]
945        match IconRole::DialogWarning {
946            IconRole::DialogWarning
947            | IconRole::DialogError
948            | IconRole::DialogInfo
949            | IconRole::DialogQuestion
950            | IconRole::DialogSuccess
951            | IconRole::Shield
952            | IconRole::WindowClose
953            | IconRole::WindowMinimize
954            | IconRole::WindowMaximize
955            | IconRole::WindowRestore
956            | IconRole::ActionSave
957            | IconRole::ActionDelete
958            | IconRole::ActionCopy
959            | IconRole::ActionPaste
960            | IconRole::ActionCut
961            | IconRole::ActionUndo
962            | IconRole::ActionRedo
963            | IconRole::ActionSearch
964            | IconRole::ActionSettings
965            | IconRole::ActionEdit
966            | IconRole::ActionAdd
967            | IconRole::ActionRemove
968            | IconRole::ActionRefresh
969            | IconRole::ActionPrint
970            | IconRole::NavBack
971            | IconRole::NavForward
972            | IconRole::NavUp
973            | IconRole::NavDown
974            | IconRole::NavHome
975            | IconRole::NavMenu
976            | IconRole::FileGeneric
977            | IconRole::FolderClosed
978            | IconRole::FolderOpen
979            | IconRole::TrashEmpty
980            | IconRole::TrashFull
981            | IconRole::StatusBusy
982            | IconRole::StatusCheck
983            | IconRole::StatusError
984            | IconRole::UserAccount
985            | IconRole::Notification
986            | IconRole::Help
987            | IconRole::Lock => {}
988        }
989
990        // Verify each variant is in ALL:
991        check(IconRole::DialogWarning);
992        check(IconRole::DialogError);
993        check(IconRole::DialogInfo);
994        check(IconRole::DialogQuestion);
995        check(IconRole::DialogSuccess);
996        check(IconRole::Shield);
997        check(IconRole::WindowClose);
998        check(IconRole::WindowMinimize);
999        check(IconRole::WindowMaximize);
1000        check(IconRole::WindowRestore);
1001        check(IconRole::ActionSave);
1002        check(IconRole::ActionDelete);
1003        check(IconRole::ActionCopy);
1004        check(IconRole::ActionPaste);
1005        check(IconRole::ActionCut);
1006        check(IconRole::ActionUndo);
1007        check(IconRole::ActionRedo);
1008        check(IconRole::ActionSearch);
1009        check(IconRole::ActionSettings);
1010        check(IconRole::ActionEdit);
1011        check(IconRole::ActionAdd);
1012        check(IconRole::ActionRemove);
1013        check(IconRole::ActionRefresh);
1014        check(IconRole::ActionPrint);
1015        check(IconRole::NavBack);
1016        check(IconRole::NavForward);
1017        check(IconRole::NavUp);
1018        check(IconRole::NavDown);
1019        check(IconRole::NavHome);
1020        check(IconRole::NavMenu);
1021        check(IconRole::FileGeneric);
1022        check(IconRole::FolderClosed);
1023        check(IconRole::FolderOpen);
1024        check(IconRole::TrashEmpty);
1025        check(IconRole::TrashFull);
1026        check(IconRole::StatusBusy);
1027        check(IconRole::StatusCheck);
1028        check(IconRole::StatusError);
1029        check(IconRole::UserAccount);
1030        check(IconRole::Notification);
1031        check(IconRole::Help);
1032        check(IconRole::Lock);
1033    }
1034
1035    #[test]
1036    fn icon_role_all_no_duplicates() {
1037        let all = IconRole::ALL;
1038        for (i, role) in all.iter().enumerate() {
1039            for (j, other) in all.iter().enumerate() {
1040                if i != j {
1041                    assert_ne!(role, other, "Duplicate at index {i} and {j}");
1042                }
1043            }
1044        }
1045    }
1046
1047    #[test]
1048    fn icon_role_derives_copy_clone() {
1049        let role = IconRole::ActionCopy;
1050        let copied1 = role;
1051        let copied2 = role;
1052        assert_eq!(role, copied1);
1053        assert_eq!(role, copied2);
1054    }
1055
1056    #[test]
1057    fn icon_role_derives_debug() {
1058        let s = format!("{:?}", IconRole::DialogWarning);
1059        assert!(s.contains("DialogWarning"));
1060    }
1061
1062    #[test]
1063    fn icon_role_derives_hash() {
1064        use std::collections::HashSet;
1065        let mut set = HashSet::new();
1066        set.insert(IconRole::ActionSave);
1067        set.insert(IconRole::ActionDelete);
1068        assert_eq!(set.len(), 2);
1069        assert!(set.contains(&IconRole::ActionSave));
1070    }
1071
1072    // === IconData tests ===
1073
1074    #[test]
1075    fn icon_data_svg_construct_and_match() {
1076        let data = IconData::Svg(Cow::Borrowed(b"<svg></svg>"));
1077        assert_eq!(data.bytes(), b"<svg></svg>");
1078        match data {
1079            IconData::Svg(ref cow) => assert_eq!(cow.as_ref(), b"<svg></svg>"),
1080            _ => panic!("Expected Svg variant"),
1081        }
1082    }
1083
1084    #[test]
1085    fn icon_data_rgba_construct_and_match() {
1086        let pixels = vec![255, 0, 0, 255]; // 1 red pixel
1087        let data = IconData::rgba(1, 1, pixels.clone()).unwrap();
1088        match data {
1089            IconData::Rgba(rgba) => {
1090                assert_eq!(rgba.width(), 1);
1091                assert_eq!(rgba.height(), 1);
1092                assert_eq!(rgba.data(), pixels.as_slice());
1093                assert_eq!(rgba.into_data(), pixels);
1094            }
1095            _ => panic!("Expected Rgba variant"),
1096        }
1097    }
1098
1099    #[test]
1100    fn icon_data_rgba_rejects_a_buffer_of_the_wrong_length() {
1101        assert_eq!(IconData::rgba(16, 16, vec![]), None);
1102        assert_eq!(IconData::rgba(1, 1, vec![0; 3]), None);
1103        assert_eq!(IconData::rgba(1, 1, vec![0; 5]), None);
1104        assert_eq!(IconData::rgba(2, 3, vec![0; 2 * 3 * 4 - 1]), None);
1105        assert!(IconData::rgba(2, 3, vec![0; 2 * 3 * 4]).is_some());
1106        assert!(IconData::rgba(0, 0, vec![]).is_some());
1107    }
1108
1109    #[test]
1110    fn icon_data_rgba_rejects_an_overflowing_size() {
1111        assert_eq!(IconData::rgba(u32::MAX, u32::MAX, vec![]), None);
1112    }
1113
1114    #[test]
1115    fn icon_data_rgba_serializes_as_before() {
1116        let icon = IconData::rgba(1, 1, vec![255, 0, 0, 255]).unwrap();
1117        let json = serde_json::to_string(&icon).unwrap();
1118        assert_eq!(
1119            json,
1120            r#"{"Rgba":{"width":1,"height":1,"data":[255,0,0,255]}}"#
1121        );
1122        let back: IconData = serde_json::from_str(&json).unwrap();
1123        assert_eq!(back, icon);
1124
1125        let toml_text = toml::to_string(&icon).unwrap();
1126        let back: IconData = toml::from_str(&toml_text).unwrap();
1127        assert_eq!(back, icon);
1128    }
1129
1130    #[test]
1131    fn icon_data_rgba_deserialize_rejects_a_short_buffer() {
1132        let json = r#"{"Rgba":{"width":16,"height":16,"data":[0,0,0,0]}}"#;
1133        let err = serde_json::from_str::<IconData>(json).unwrap_err();
1134        assert!(
1135            err.to_string().contains("16 x 16 x 4"),
1136            "unexpected error: {err}"
1137        );
1138
1139        let toml_text = "[Rgba]\nwidth = 16\nheight = 16\ndata = [0, 0, 0, 0]\n";
1140        let err = toml::from_str::<IconData>(toml_text).unwrap_err();
1141        assert!(
1142            err.to_string().contains("16 x 16 x 4"),
1143            "unexpected error: {err}"
1144        );
1145    }
1146
1147    #[test]
1148    fn icon_data_derives_debug() {
1149        let data = IconData::Svg(Cow::Borrowed(b""));
1150        let s = format!("{:?}", data);
1151        assert!(s.contains("Svg"));
1152    }
1153
1154    #[test]
1155    fn icon_data_derives_clone() {
1156        let data = IconData::rgba(16, 16, vec![0; 16 * 16 * 4]).unwrap();
1157        let cloned = data.clone();
1158        assert_eq!(data, cloned);
1159    }
1160
1161    #[test]
1162    fn icon_data_derives_eq() {
1163        let a = IconData::Svg(Cow::Borrowed(b"<svg/>"));
1164        let b = IconData::Svg(Cow::Owned(b"<svg/>".to_vec()));
1165        assert_eq!(a, b);
1166
1167        let c = IconData::Svg(Cow::Borrowed(b"<other/>"));
1168        assert_ne!(a, c);
1169    }
1170
1171    // === IconSet tests ===
1172
1173    #[test]
1174    fn icon_set_from_name_sf_symbols() {
1175        assert_eq!(IconSet::from_name("sf-symbols"), Some(IconSet::SfSymbols));
1176    }
1177
1178    #[test]
1179    fn icon_set_from_name_segoe_fluent() {
1180        assert_eq!(
1181            IconSet::from_name("segoe-fluent"),
1182            Some(IconSet::SegoeFluent)
1183        );
1184    }
1185
1186    #[test]
1187    fn icon_set_from_name_freedesktop() {
1188        assert_eq!(
1189            IconSet::from_name("freedesktop"),
1190            Some(IconSet::Freedesktop)
1191        );
1192    }
1193
1194    #[test]
1195    fn icon_set_from_name_material() {
1196        assert_eq!(IconSet::from_name("material"), Some(IconSet::Material));
1197    }
1198
1199    #[test]
1200    fn icon_set_from_name_lucide() {
1201        assert_eq!(IconSet::from_name("lucide"), Some(IconSet::Lucide));
1202    }
1203
1204    #[test]
1205    fn icon_set_from_name_unknown() {
1206        assert_eq!(IconSet::from_name("unknown"), None);
1207    }
1208
1209    #[test]
1210    fn icon_set_name_sf_symbols() {
1211        assert_eq!(IconSet::SfSymbols.name(), "sf-symbols");
1212    }
1213
1214    #[test]
1215    fn icon_set_name_segoe_fluent() {
1216        assert_eq!(IconSet::SegoeFluent.name(), "segoe-fluent");
1217    }
1218
1219    #[test]
1220    fn icon_set_name_freedesktop() {
1221        assert_eq!(IconSet::Freedesktop.name(), "freedesktop");
1222    }
1223
1224    #[test]
1225    fn icon_set_name_material() {
1226        assert_eq!(IconSet::Material.name(), "material");
1227    }
1228
1229    #[test]
1230    fn icon_set_name_lucide() {
1231        assert_eq!(IconSet::Lucide.name(), "lucide");
1232    }
1233
1234    #[test]
1235    fn icon_set_from_name_name_round_trip() {
1236        let sets = [
1237            IconSet::SfSymbols,
1238            IconSet::SegoeFluent,
1239            IconSet::Freedesktop,
1240            IconSet::Material,
1241            IconSet::Lucide,
1242        ];
1243        for set in &sets {
1244            let name = set.name();
1245            let parsed = IconSet::from_name(name);
1246            assert_eq!(parsed, Some(*set), "Round-trip failed for {:?}", set);
1247        }
1248    }
1249
1250    #[test]
1251    fn icon_set_derives_copy_clone() {
1252        let set = IconSet::Material;
1253        let copied1 = set;
1254        let copied2 = set;
1255        assert_eq!(set, copied1);
1256        assert_eq!(set, copied2);
1257    }
1258
1259    #[test]
1260    fn icon_set_derives_hash() {
1261        use std::collections::HashSet;
1262        let mut map = HashSet::new();
1263        map.insert(IconSet::SfSymbols);
1264        map.insert(IconSet::Lucide);
1265        assert_eq!(map.len(), 2);
1266    }
1267
1268    #[test]
1269    fn icon_set_derives_debug() {
1270        let s = format!("{:?}", IconSet::Freedesktop);
1271        assert!(s.contains("Freedesktop"));
1272    }
1273
1274    #[test]
1275    fn icon_set_serde_round_trip() {
1276        let set = IconSet::SfSymbols;
1277        let json = serde_json::to_string(&set).unwrap();
1278        let deserialized: IconSet = serde_json::from_str(&json).unwrap();
1279        assert_eq!(set, deserialized);
1280    }
1281
1282    // === icon_name() tests ===
1283
1284    #[test]
1285    fn icon_name_sf_symbols_action_copy() {
1286        assert_eq!(
1287            icon_name(IconRole::ActionCopy, IconSet::SfSymbols),
1288            Some("doc.on.doc")
1289        );
1290    }
1291
1292    #[test]
1293    fn icon_name_segoe_action_copy() {
1294        assert_eq!(
1295            icon_name(IconRole::ActionCopy, IconSet::SegoeFluent),
1296            Some("Copy")
1297        );
1298    }
1299
1300    #[test]
1301    fn icon_name_freedesktop_action_copy() {
1302        assert_eq!(
1303            icon_name(IconRole::ActionCopy, IconSet::Freedesktop),
1304            Some("edit-copy")
1305        );
1306    }
1307
1308    #[test]
1309    fn icon_name_material_action_copy() {
1310        assert_eq!(
1311            icon_name(IconRole::ActionCopy, IconSet::Material),
1312            Some("content_copy")
1313        );
1314    }
1315
1316    #[test]
1317    fn icon_name_lucide_action_copy() {
1318        assert_eq!(
1319            icon_name(IconRole::ActionCopy, IconSet::Lucide),
1320            Some("copy")
1321        );
1322    }
1323
1324    #[test]
1325    fn icon_name_sf_symbols_dialog_warning() {
1326        assert_eq!(
1327            icon_name(IconRole::DialogWarning, IconSet::SfSymbols),
1328            Some("exclamationmark.triangle.fill")
1329        );
1330    }
1331
1332    // None cases for known gaps
1333    #[test]
1334    fn icon_name_sf_symbols_folder_open_is_none() {
1335        assert_eq!(icon_name(IconRole::FolderOpen, IconSet::SfSymbols), None);
1336    }
1337
1338    #[test]
1339    fn icon_name_sf_symbols_trash_full() {
1340        assert_eq!(
1341            icon_name(IconRole::TrashFull, IconSet::SfSymbols),
1342            Some("trash.fill")
1343        );
1344    }
1345
1346    #[test]
1347    fn icon_name_sf_symbols_status_busy_is_none() {
1348        assert_eq!(icon_name(IconRole::StatusBusy, IconSet::SfSymbols), None);
1349    }
1350
1351    #[test]
1352    fn icon_name_sf_symbols_window_restore() {
1353        assert_eq!(
1354            icon_name(IconRole::WindowRestore, IconSet::SfSymbols),
1355            Some("arrow.down.right.and.arrow.up.left")
1356        );
1357    }
1358
1359    #[test]
1360    fn icon_name_segoe_dialog_success() {
1361        assert_eq!(
1362            icon_name(IconRole::DialogSuccess, IconSet::SegoeFluent),
1363            Some("CheckMark")
1364        );
1365    }
1366
1367    #[test]
1368    fn icon_name_segoe_status_busy_is_none() {
1369        assert_eq!(icon_name(IconRole::StatusBusy, IconSet::SegoeFluent), None);
1370    }
1371
1372    #[test]
1373    fn icon_name_freedesktop_notification() {
1374        assert_eq!(
1375            icon_name(IconRole::Notification, IconSet::Freedesktop),
1376            Some("notification-active")
1377        );
1378    }
1379
1380    #[test]
1381    fn icon_name_freedesktop_dialog_success() {
1382        // Must be the Icon Naming Spec 0.8.90 standard name "object-select"
1383        // (Adwaita ships it; "emblem-ok" is a legacy GNOME emblem that
1384        // Adwaita does not ship and is not in the spec).
1385        assert_eq!(
1386            icon_name(IconRole::DialogSuccess, IconSet::Freedesktop),
1387            Some("object-select-symbolic")
1388        );
1389    }
1390
1391    #[test]
1392    fn icon_name_freedesktop_status_busy() {
1393        // Must resolve to "content-loading-symbolic" (three-dot ellipsis),
1394        // which Adwaita and Breeze both ship. `process-working` was tried
1395        // first but is absent from Adwaita.
1396        assert_eq!(
1397            icon_name(IconRole::StatusBusy, IconSet::Freedesktop),
1398            Some("content-loading-symbolic")
1399        );
1400    }
1401
1402    #[test]
1403    fn icon_name_material_trash_full() {
1404        assert_eq!(
1405            icon_name(IconRole::TrashFull, IconSet::Material),
1406            Some("delete")
1407        );
1408    }
1409
1410    #[test]
1411    fn icon_name_lucide_trash_full() {
1412        assert_eq!(
1413            icon_name(IconRole::TrashFull, IconSet::Lucide),
1414            Some("trash")
1415        );
1416    }
1417
1418    // Spot-check across all 5 icon sets for multiple roles
1419    #[test]
1420    fn icon_name_spot_check_dialog_error() {
1421        assert_eq!(
1422            icon_name(IconRole::DialogError, IconSet::SfSymbols),
1423            Some("xmark.circle.fill")
1424        );
1425        assert_eq!(
1426            icon_name(IconRole::DialogError, IconSet::SegoeFluent),
1427            Some("SIID_ERROR")
1428        );
1429        assert_eq!(
1430            icon_name(IconRole::DialogError, IconSet::Freedesktop),
1431            Some("dialog-error")
1432        );
1433        assert_eq!(
1434            icon_name(IconRole::DialogError, IconSet::Material),
1435            Some("error")
1436        );
1437        assert_eq!(
1438            icon_name(IconRole::DialogError, IconSet::Lucide),
1439            Some("circle-x")
1440        );
1441    }
1442
1443    #[test]
1444    fn icon_name_spot_check_nav_home() {
1445        assert_eq!(
1446            icon_name(IconRole::NavHome, IconSet::SfSymbols),
1447            Some("house")
1448        );
1449        assert_eq!(
1450            icon_name(IconRole::NavHome, IconSet::SegoeFluent),
1451            Some("Home")
1452        );
1453        assert_eq!(
1454            icon_name(IconRole::NavHome, IconSet::Freedesktop),
1455            Some("go-home")
1456        );
1457        assert_eq!(
1458            icon_name(IconRole::NavHome, IconSet::Material),
1459            Some("home")
1460        );
1461        assert_eq!(icon_name(IconRole::NavHome, IconSet::Lucide), Some("house"));
1462    }
1463
1464    // Count test: verify expected Some/None count for each icon set
1465    #[test]
1466    fn icon_name_sf_symbols_expected_count() {
1467        // SF Symbols: 42 - 2 None (FolderOpen, StatusBusy) = 40 Some
1468        let some_count = IconRole::ALL
1469            .iter()
1470            .filter(|r| icon_name(**r, IconSet::SfSymbols).is_some())
1471            .count();
1472        assert_eq!(some_count, 40, "SF Symbols should have 40 mappings");
1473    }
1474
1475    #[test]
1476    fn icon_name_segoe_expected_count() {
1477        // Segoe: 42 - 1 None (StatusBusy) = 41 Some
1478        let some_count = IconRole::ALL
1479            .iter()
1480            .filter(|r| icon_name(**r, IconSet::SegoeFluent).is_some())
1481            .count();
1482        assert_eq!(some_count, 41, "Segoe Fluent should have 41 mappings");
1483    }
1484
1485    #[test]
1486    fn icon_name_freedesktop_expected_count() {
1487        // Freedesktop: all 42 roles mapped
1488        let some_count = IconRole::ALL
1489            .iter()
1490            .filter(|r| icon_name(**r, IconSet::Freedesktop).is_some())
1491            .count();
1492        assert_eq!(some_count, 42, "Freedesktop should have 42 mappings");
1493    }
1494
1495    #[test]
1496    fn icon_name_material_expected_count() {
1497        // Material: all 42 roles mapped
1498        let some_count = IconRole::ALL
1499            .iter()
1500            .filter(|r| icon_name(**r, IconSet::Material).is_some())
1501            .count();
1502        assert_eq!(some_count, 42, "Material should have 42 mappings");
1503    }
1504
1505    #[test]
1506    fn icon_name_lucide_expected_count() {
1507        // Lucide: all 42 roles mapped
1508        let some_count = IconRole::ALL
1509            .iter()
1510            .filter(|r| icon_name(**r, IconSet::Lucide).is_some())
1511            .count();
1512        assert_eq!(some_count, 42, "Lucide should have 42 mappings");
1513    }
1514
1515    // === IconProvider trait tests ===
1516
1517    #[test]
1518    fn icon_provider_is_object_safe() {
1519        // Box<dyn IconProvider> must compile and be usable
1520        let provider: Box<dyn IconProvider> = Box::new(IconRole::ActionCopy);
1521        let debug_str = format!("{:?}", provider);
1522        assert!(
1523            debug_str.contains("ActionCopy"),
1524            "Debug should print variant name"
1525        );
1526    }
1527
1528    #[test]
1529    fn icon_role_provider_icon_name() {
1530        // IconRole::ActionCopy should return "content_copy" for Material via IconProvider
1531        let role = IconRole::ActionCopy;
1532        let name = IconProvider::icon_name(&role, IconSet::Material);
1533        assert_eq!(name, Some("content_copy"));
1534    }
1535
1536    #[test]
1537    fn icon_role_provider_icon_name_sf_symbols() {
1538        let role = IconRole::ActionCopy;
1539        let name = IconProvider::icon_name(&role, IconSet::SfSymbols);
1540        assert_eq!(name, Some("doc.on.doc"));
1541    }
1542
1543    #[test]
1544    #[cfg(feature = "material-icons")]
1545    fn icon_role_provider_icon_svg_material() {
1546        let role = IconRole::ActionCopy;
1547        let svg = IconProvider::icon_svg(&role, IconSet::Material);
1548        assert!(svg.is_some(), "Material SVG should be Some");
1549        let cow = svg.unwrap();
1550        let content = std::str::from_utf8(&cow).expect("valid UTF-8");
1551        assert!(content.contains("<svg"), "should contain <svg tag");
1552    }
1553
1554    #[test]
1555    fn icon_role_provider_icon_svg_non_bundled() {
1556        // SfSymbols is not a bundled set, so icon_svg should return None
1557        let role = IconRole::ActionCopy;
1558        let svg = IconProvider::icon_svg(&role, IconSet::SfSymbols);
1559        assert!(svg.is_none(), "SfSymbols should not have bundled SVGs");
1560    }
1561
1562    #[test]
1563    fn icon_role_provider_all_roles() {
1564        // All 42 IconRole variants implement IconProvider -- iterate and call icon_name
1565        for role in IconRole::ALL {
1566            // All 42 roles are mapped for Material
1567            let _name = IconProvider::icon_name(role, IconSet::Material);
1568            // Just verifying it doesn't panic
1569        }
1570    }
1571
1572    #[test]
1573    fn icon_provider_dyn_dispatch() {
1574        // Call icon_name and icon_svg through &dyn IconProvider
1575        let role = IconRole::ActionCopy;
1576        let provider: &dyn IconProvider = &role;
1577        let name = provider.icon_name(IconSet::Material);
1578        assert_eq!(name, Some("content_copy"));
1579        let svg = provider.icon_svg(IconSet::SfSymbols);
1580        assert!(svg.is_none(), "SfSymbols should not have bundled SVGs");
1581    }
1582
1583    // === Coverage tests ===
1584
1585    fn known_gaps() -> &'static [(IconSet, IconRole)] {
1586        &[
1587            (IconSet::SfSymbols, IconRole::FolderOpen),
1588            (IconSet::SfSymbols, IconRole::StatusBusy),
1589            (IconSet::SegoeFluent, IconRole::StatusBusy),
1590        ]
1591    }
1592
1593    #[test]
1594    fn no_unexpected_icon_gaps() {
1595        let gaps = known_gaps();
1596        let system_sets = [
1597            IconSet::SfSymbols,
1598            IconSet::SegoeFluent,
1599            IconSet::Freedesktop,
1600        ];
1601        for &set in &system_sets {
1602            for role in IconRole::ALL.iter().copied() {
1603                let is_known_gap = gaps.contains(&(set, role));
1604                let is_mapped = icon_name(role, set).is_some();
1605                if !is_known_gap {
1606                    assert!(
1607                        is_mapped,
1608                        "{role:?} has no mapping for {set:?} and is not in known_gaps()"
1609                    );
1610                }
1611            }
1612        }
1613    }
1614
1615    #[test]
1616    #[cfg(all(feature = "material-icons", feature = "lucide-icons"))]
1617    fn all_roles_have_bundled_svg() {
1618        use crate::bundled_icon_svg;
1619        for set in [IconSet::Material, IconSet::Lucide] {
1620            for role in IconRole::ALL.iter().copied() {
1621                assert!(
1622                    bundled_icon_svg(role, set).is_some(),
1623                    "{role:?} has no bundled SVG for {set:?}"
1624                );
1625            }
1626        }
1627    }
1628
1629    /// Exhaustive icon_name() coverage: Material, Lucide, and Freedesktop map ALL 42,
1630    /// Segoe maps at least 41, SF Symbols maps at least 40.
1631    #[test]
1632    fn icon_name_exhaustive_all_sets() {
1633        // Material: all 42
1634        for role in IconRole::ALL.iter().copied() {
1635            assert!(
1636                icon_name(role, IconSet::Material).is_some(),
1637                "Material must map {role:?} to Some"
1638            );
1639        }
1640        // Lucide: all 42
1641        for role in IconRole::ALL.iter().copied() {
1642            assert!(
1643                icon_name(role, IconSet::Lucide).is_some(),
1644                "Lucide must map {role:?} to Some"
1645            );
1646        }
1647        // Freedesktop: all 42
1648        for role in IconRole::ALL.iter().copied() {
1649            assert!(
1650                icon_name(role, IconSet::Freedesktop).is_some(),
1651                "Freedesktop must map {role:?} to Some"
1652            );
1653        }
1654        // Segoe: at least 41 (StatusBusy is None)
1655        let segoe_count = IconRole::ALL
1656            .iter()
1657            .filter(|r| icon_name(**r, IconSet::SegoeFluent).is_some())
1658            .count();
1659        assert!(
1660            segoe_count >= 41,
1661            "Segoe should map at least 41 roles, got {segoe_count}"
1662        );
1663        // SF Symbols: at least 40 (FolderOpen and StatusBusy are None)
1664        let sf_count = IconRole::ALL
1665            .iter()
1666            .filter(|r| icon_name(**r, IconSet::SfSymbols).is_some())
1667            .count();
1668        assert!(
1669            sf_count >= 40,
1670            "SfSymbols should map at least 40 roles, got {sf_count}"
1671        );
1672    }
1673
1674    /// Verify icon_name returns non-empty strings for all mapped roles.
1675    #[test]
1676    fn icon_name_returns_nonempty_strings() {
1677        let all_sets = [
1678            IconSet::SfSymbols,
1679            IconSet::SegoeFluent,
1680            IconSet::Freedesktop,
1681            IconSet::Material,
1682            IconSet::Lucide,
1683        ];
1684        for set in all_sets {
1685            for role in IconRole::ALL.iter().copied() {
1686                if let Some(name) = icon_name(role, set) {
1687                    assert!(
1688                        !name.is_empty(),
1689                        "icon_name({role:?}, {set:?}) returned empty string"
1690                    );
1691                }
1692            }
1693        }
1694    }
1695
1696    // === IconSet drift-guard test (ICON-06) ===
1697
1698    #[test]
1699    fn icon_set_name_round_trip() {
1700        // Drift-guard: if a new IconSet variant is added without updating
1701        // from_name(), this test fails.
1702        let all_sets = [
1703            IconSet::SfSymbols,
1704            IconSet::SegoeFluent,
1705            IconSet::Freedesktop,
1706            IconSet::Material,
1707            IconSet::Lucide,
1708        ];
1709        for set in all_sets {
1710            assert_eq!(
1711                IconSet::from_name(set.name()),
1712                Some(set),
1713                "IconSet::{:?}.name() = {:?} did not round-trip through from_name()",
1714                set,
1715                set.name()
1716            );
1717        }
1718    }
1719
1720    // === IconRole::name() tests (ICON-07) ===
1721
1722    #[test]
1723    fn icon_role_name_returns_kebab_case() {
1724        assert_eq!(IconRole::ActionSave.name(), "action-save");
1725        assert_eq!(IconRole::DialogWarning.name(), "dialog-warning");
1726        assert_eq!(IconRole::WindowClose.name(), "window-close");
1727        assert_eq!(IconRole::NavBack.name(), "nav-back");
1728        assert_eq!(IconRole::FileGeneric.name(), "file-generic");
1729        assert_eq!(IconRole::StatusBusy.name(), "status-busy");
1730        assert_eq!(IconRole::UserAccount.name(), "user-account");
1731        assert_eq!(IconRole::Shield.name(), "shield");
1732        assert_eq!(IconRole::Notification.name(), "notification");
1733        assert_eq!(IconRole::Help.name(), "help");
1734        assert_eq!(IconRole::Lock.name(), "lock");
1735    }
1736
1737    #[test]
1738    fn icon_role_display_delegates_to_name() {
1739        for role in IconRole::ALL {
1740            assert_eq!(
1741                format!("{role}"),
1742                role.name(),
1743                "Display for IconRole::{:?} should delegate to name()",
1744                role
1745            );
1746        }
1747    }
1748
1749    // === IconSet serde-vs-name cross-check (GAP-5) ===
1750
1751    #[test]
1752    fn icon_set_serde_matches_name() {
1753        let all_sets = [
1754            IconSet::SfSymbols,
1755            IconSet::SegoeFluent,
1756            IconSet::Freedesktop,
1757            IconSet::Material,
1758            IconSet::Lucide,
1759        ];
1760        for set in all_sets {
1761            let serialized = serde_json::to_string(&set)
1762                .unwrap_or_else(|e| panic!("failed to serialize {set:?}: {e}"));
1763            let trimmed = serialized.trim_matches('"');
1764            assert_eq!(
1765                trimmed,
1766                set.name(),
1767                "serde serialization of {set:?} ({trimmed:?}) does not match name() ({:?})",
1768                set.name()
1769            );
1770        }
1771    }
1772
1773    // === IconData::bytes() accessor test ===
1774
1775    #[test]
1776    fn icon_data_bytes_accessor() {
1777        let svg = IconData::Svg(Cow::Borrowed(b"<svg/>"));
1778        assert_eq!(svg.bytes(), b"<svg/>");
1779
1780        let rgba = IconData::rgba(1, 1, vec![1, 2, 3, 4]).unwrap();
1781        assert_eq!(rgba.bytes(), &[1, 2, 3, 4]);
1782    }
1783}