use std::borrow::Cow;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum IconRole {
DialogWarning,
DialogError,
DialogInfo,
DialogQuestion,
DialogSuccess,
Shield,
WindowClose,
WindowMinimize,
WindowMaximize,
WindowRestore,
ActionSave,
ActionDelete,
ActionCopy,
ActionPaste,
ActionCut,
ActionUndo,
ActionRedo,
ActionSearch,
ActionSettings,
ActionEdit,
ActionAdd,
ActionRemove,
ActionRefresh,
ActionPrint,
NavBack,
NavForward,
NavUp,
NavDown,
NavHome,
NavMenu,
FileGeneric,
FolderClosed,
FolderOpen,
TrashEmpty,
TrashFull,
StatusBusy,
StatusCheck,
StatusError,
UserAccount,
Notification,
Help,
Lock,
}
impl std::fmt::Display for IconRole {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.name())
}
}
impl IconRole {
#[must_use]
pub fn name(&self) -> &'static str {
match self {
Self::DialogWarning => "dialog-warning",
Self::DialogError => "dialog-error",
Self::DialogInfo => "dialog-info",
Self::DialogQuestion => "dialog-question",
Self::DialogSuccess => "dialog-success",
Self::Shield => "shield",
Self::WindowClose => "window-close",
Self::WindowMinimize => "window-minimize",
Self::WindowMaximize => "window-maximize",
Self::WindowRestore => "window-restore",
Self::ActionSave => "action-save",
Self::ActionDelete => "action-delete",
Self::ActionCopy => "action-copy",
Self::ActionPaste => "action-paste",
Self::ActionCut => "action-cut",
Self::ActionUndo => "action-undo",
Self::ActionRedo => "action-redo",
Self::ActionSearch => "action-search",
Self::ActionSettings => "action-settings",
Self::ActionEdit => "action-edit",
Self::ActionAdd => "action-add",
Self::ActionRemove => "action-remove",
Self::ActionRefresh => "action-refresh",
Self::ActionPrint => "action-print",
Self::NavBack => "nav-back",
Self::NavForward => "nav-forward",
Self::NavUp => "nav-up",
Self::NavDown => "nav-down",
Self::NavHome => "nav-home",
Self::NavMenu => "nav-menu",
Self::FileGeneric => "file-generic",
Self::FolderClosed => "folder-closed",
Self::FolderOpen => "folder-open",
Self::TrashEmpty => "trash-empty",
Self::TrashFull => "trash-full",
Self::StatusBusy => "status-busy",
Self::StatusCheck => "status-check",
Self::StatusError => "status-error",
Self::UserAccount => "user-account",
Self::Notification => "notification",
Self::Help => "help",
Self::Lock => "lock",
}
}
pub const ALL: &'static [IconRole] = &[
Self::DialogWarning,
Self::DialogError,
Self::DialogInfo,
Self::DialogQuestion,
Self::DialogSuccess,
Self::Shield,
Self::WindowClose,
Self::WindowMinimize,
Self::WindowMaximize,
Self::WindowRestore,
Self::ActionSave,
Self::ActionDelete,
Self::ActionCopy,
Self::ActionPaste,
Self::ActionCut,
Self::ActionUndo,
Self::ActionRedo,
Self::ActionSearch,
Self::ActionSettings,
Self::ActionEdit,
Self::ActionAdd,
Self::ActionRemove,
Self::ActionRefresh,
Self::ActionPrint,
Self::NavBack,
Self::NavForward,
Self::NavUp,
Self::NavDown,
Self::NavHome,
Self::NavMenu,
Self::FileGeneric,
Self::FolderClosed,
Self::FolderOpen,
Self::TrashEmpty,
Self::TrashFull,
Self::StatusBusy,
Self::StatusCheck,
Self::StatusError,
Self::UserAccount,
Self::Notification,
Self::Help,
Self::Lock,
];
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
#[must_use]
pub enum IconData {
Svg(Cow<'static, [u8]>),
Rgba(RgbaData),
}
impl IconData {
#[must_use]
pub fn rgba(width: u32, height: u32, data: Vec<u8>) -> Option<Self> {
RgbaData::new(width, height, data).map(IconData::Rgba)
}
#[must_use]
pub fn bytes(&self) -> &[u8] {
match self {
IconData::Svg(cow) => cow,
IconData::Rgba(rgba) => rgba.data(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "RawRgbaData")]
pub struct RgbaData {
width: u32,
height: u32,
data: Vec<u8>,
}
impl RgbaData {
fn new(width: u32, height: u32, data: Vec<u8>) -> Option<Self> {
let len = usize::try_from(width)
.ok()?
.checked_mul(usize::try_from(height).ok()?)?
.checked_mul(4)?;
(data.len() == len).then_some(Self {
width,
height,
data,
})
}
#[must_use]
pub fn width(&self) -> u32 {
self.width
}
#[must_use]
pub fn height(&self) -> u32 {
self.height
}
#[must_use]
pub fn data(&self) -> &[u8] {
&self.data
}
#[must_use]
pub fn into_data(self) -> Vec<u8> {
self.data
}
}
#[derive(Deserialize)]
struct RawRgbaData {
width: u32,
height: u32,
data: Vec<u8>,
}
impl TryFrom<RawRgbaData> for RgbaData {
type Error = String;
fn try_from(raw: RawRgbaData) -> Result<Self, Self::Error> {
let (width, height, len) = (raw.width, raw.height, raw.data.len());
Self::new(width, height, raw.data).ok_or_else(|| {
format!("RGBA data of {len} bytes does not match {width} x {height} x 4 bytes")
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub enum IconSet {
SfSymbols,
SegoeFluent,
Freedesktop,
Material,
Lucide,
}
impl std::fmt::Display for IconSet {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.name())
}
}
impl IconSet {
#[must_use]
pub fn from_name(name: &str) -> Option<Self> {
match name {
"sf-symbols" => Some(Self::SfSymbols),
"segoe-fluent" => Some(Self::SegoeFluent),
"freedesktop" => Some(Self::Freedesktop),
"material" => Some(Self::Material),
"lucide" => Some(Self::Lucide),
_ => None,
}
}
#[must_use]
pub fn name(&self) -> &'static str {
match self {
Self::SfSymbols => "sf-symbols",
Self::SegoeFluent => "segoe-fluent",
Self::Freedesktop => "freedesktop",
Self::Material => "material",
Self::Lucide => "lucide",
}
}
}
pub trait IconProvider: std::fmt::Debug {
fn icon_name(&self, set: IconSet) -> Option<&str>;
fn icon_svg(&self, set: IconSet) -> Option<Cow<'static, [u8]>>;
}
impl IconProvider for IconRole {
fn icon_name(&self, set: IconSet) -> Option<&str> {
icon_name(*self, set)
}
fn icon_svg(&self, set: IconSet) -> Option<Cow<'static, [u8]>> {
crate::model::bundled::bundled_icon_svg(*self, set).map(Cow::Borrowed)
}
}
#[must_use]
#[allow(unreachable_patterns)] pub fn icon_name(role: IconRole, set: IconSet) -> Option<&'static str> {
match set {
IconSet::SfSymbols => sf_symbols_name(role),
IconSet::SegoeFluent => segoe_name(role),
IconSet::Freedesktop => freedesktop_name(role),
IconSet::Material => material_name(role),
IconSet::Lucide => lucide_name(role),
_ => None,
}
}
#[allow(unreachable_patterns)]
fn sf_symbols_name(role: IconRole) -> Option<&'static str> {
Some(match role {
IconRole::DialogWarning => "exclamationmark.triangle.fill",
IconRole::DialogError => "xmark.circle.fill",
IconRole::DialogInfo => "info.circle.fill",
IconRole::DialogQuestion => "questionmark.circle.fill",
IconRole::DialogSuccess => "checkmark.circle.fill",
IconRole::Shield => "shield.fill",
IconRole::WindowClose => "xmark",
IconRole::WindowMinimize => "minus",
IconRole::WindowMaximize => "arrow.up.left.and.arrow.down.right",
IconRole::WindowRestore => "arrow.down.right.and.arrow.up.left",
IconRole::ActionSave => "square.and.arrow.down",
IconRole::ActionDelete => "trash",
IconRole::ActionCopy => "doc.on.doc",
IconRole::ActionPaste => "doc.on.clipboard",
IconRole::ActionCut => "scissors",
IconRole::ActionUndo => "arrow.uturn.backward",
IconRole::ActionRedo => "arrow.uturn.forward",
IconRole::ActionSearch => "magnifyingglass",
IconRole::ActionSettings => "gearshape",
IconRole::ActionEdit => "pencil",
IconRole::ActionAdd => "plus",
IconRole::ActionRemove => "minus",
IconRole::ActionRefresh => "arrow.clockwise",
IconRole::ActionPrint => "printer",
IconRole::NavBack => "chevron.backward",
IconRole::NavForward => "chevron.forward",
IconRole::NavUp => "chevron.up",
IconRole::NavDown => "chevron.down",
IconRole::NavHome => "house",
IconRole::NavMenu => "line.horizontal.3",
IconRole::FileGeneric => "doc",
IconRole::FolderClosed => "folder",
IconRole::FolderOpen => return None,
IconRole::TrashEmpty => "trash",
IconRole::TrashFull => "trash.fill",
IconRole::StatusBusy => return None,
IconRole::StatusCheck => "checkmark",
IconRole::StatusError => "xmark.circle.fill",
IconRole::UserAccount => "person.fill",
IconRole::Notification => "bell.fill",
IconRole::Help => "questionmark.circle",
IconRole::Lock => "lock.fill",
_ => return None,
})
}
#[allow(unreachable_patterns)]
fn segoe_name(role: IconRole) -> Option<&'static str> {
Some(match role {
IconRole::DialogWarning => "SIID_WARNING",
IconRole::DialogError => "SIID_ERROR",
IconRole::DialogInfo => "SIID_INFO",
IconRole::DialogQuestion => "IDI_QUESTION",
IconRole::DialogSuccess => "CheckMark",
IconRole::Shield => "SIID_SHIELD",
IconRole::WindowClose => "ChromeClose",
IconRole::WindowMinimize => "ChromeMinimize",
IconRole::WindowMaximize => "ChromeMaximize",
IconRole::WindowRestore => "ChromeRestore",
IconRole::ActionSave => "Save",
IconRole::ActionDelete => "Delete",
IconRole::ActionCopy => "Copy",
IconRole::ActionPaste => "Paste",
IconRole::ActionCut => "Cut",
IconRole::ActionUndo => "Undo",
IconRole::ActionRedo => "Redo",
IconRole::ActionSearch => "Search",
IconRole::ActionSettings => "Settings",
IconRole::ActionEdit => "Edit",
IconRole::ActionAdd => "Add",
IconRole::ActionRemove => "Remove",
IconRole::ActionRefresh => "Refresh",
IconRole::ActionPrint => "Print",
IconRole::NavBack => "Back",
IconRole::NavForward => "Forward",
IconRole::NavUp => "Up",
IconRole::NavDown => "Down",
IconRole::NavHome => "Home",
IconRole::NavMenu => "GlobalNavigationButton",
IconRole::FileGeneric => "SIID_DOCNOASSOC",
IconRole::FolderClosed => "SIID_FOLDER",
IconRole::FolderOpen => "SIID_FOLDEROPEN",
IconRole::TrashEmpty => "SIID_RECYCLER",
IconRole::TrashFull => "SIID_RECYCLERFULL",
IconRole::StatusBusy => return None,
IconRole::StatusCheck => "CheckMark",
IconRole::StatusError => "SIID_ERROR",
IconRole::UserAccount => "SIID_USERS",
IconRole::Notification => "Ringer",
IconRole::Help => "SIID_HELP",
IconRole::Lock => "SIID_LOCK",
_ => return None,
})
}
#[allow(unreachable_patterns)]
fn freedesktop_name(role: IconRole) -> Option<&'static str> {
Some(match role {
IconRole::DialogWarning => "dialog-warning",
IconRole::DialogError => "dialog-error",
IconRole::DialogInfo => "dialog-information",
IconRole::DialogQuestion => "dialog-question",
IconRole::DialogSuccess => "object-select-symbolic",
IconRole::Shield => "security-high",
IconRole::WindowClose => "window-close",
IconRole::WindowMinimize => "window-minimize",
IconRole::WindowMaximize => "window-maximize",
IconRole::WindowRestore => "window-restore",
IconRole::ActionSave => "document-save",
IconRole::ActionDelete => "edit-delete",
IconRole::ActionCopy => "edit-copy",
IconRole::ActionPaste => "edit-paste",
IconRole::ActionCut => "edit-cut",
IconRole::ActionUndo => "edit-undo",
IconRole::ActionRedo => "edit-redo",
IconRole::ActionSearch => "edit-find",
IconRole::ActionSettings => "preferences-system",
IconRole::ActionEdit => "document-edit",
IconRole::ActionAdd => "list-add",
IconRole::ActionRemove => "list-remove",
IconRole::ActionRefresh => "view-refresh",
IconRole::ActionPrint => "document-print",
IconRole::NavBack => "go-previous",
IconRole::NavForward => "go-next",
IconRole::NavUp => "go-up",
IconRole::NavDown => "go-down",
IconRole::NavHome => "go-home",
IconRole::NavMenu => "open-menu",
IconRole::FileGeneric => "text-x-generic",
IconRole::FolderClosed => "folder",
IconRole::FolderOpen => "folder-open",
IconRole::TrashEmpty => "user-trash",
IconRole::TrashFull => "user-trash-full",
IconRole::StatusBusy => "content-loading-symbolic",
IconRole::StatusCheck => "emblem-default",
IconRole::StatusError => "dialog-error",
IconRole::UserAccount => "system-users",
IconRole::Notification => "notification-active",
IconRole::Help => "help-browser",
IconRole::Lock => "system-lock-screen",
_ => return None,
})
}
#[allow(unreachable_patterns)]
fn material_name(role: IconRole) -> Option<&'static str> {
Some(match role {
IconRole::DialogWarning => "warning",
IconRole::DialogError => "error",
IconRole::DialogInfo => "info",
IconRole::DialogQuestion => "help",
IconRole::DialogSuccess => "check_circle",
IconRole::Shield => "shield",
IconRole::WindowClose => "close",
IconRole::WindowMinimize => "minimize",
IconRole::WindowMaximize => "open_in_full",
IconRole::WindowRestore => "close_fullscreen",
IconRole::ActionSave => "save",
IconRole::ActionDelete => "delete",
IconRole::ActionCopy => "content_copy",
IconRole::ActionPaste => "content_paste",
IconRole::ActionCut => "content_cut",
IconRole::ActionUndo => "undo",
IconRole::ActionRedo => "redo",
IconRole::ActionSearch => "search",
IconRole::ActionSettings => "settings",
IconRole::ActionEdit => "edit",
IconRole::ActionAdd => "add",
IconRole::ActionRemove => "remove",
IconRole::ActionRefresh => "refresh",
IconRole::ActionPrint => "print",
IconRole::NavBack => "arrow_back",
IconRole::NavForward => "arrow_forward",
IconRole::NavUp => "arrow_upward",
IconRole::NavDown => "arrow_downward",
IconRole::NavHome => "home",
IconRole::NavMenu => "menu",
IconRole::FileGeneric => "description",
IconRole::FolderClosed => "folder",
IconRole::FolderOpen => "folder_open",
IconRole::TrashEmpty => "delete",
IconRole::TrashFull => "delete",
IconRole::StatusBusy => "progress_activity",
IconRole::StatusCheck => "check",
IconRole::StatusError => "error",
IconRole::UserAccount => "person",
IconRole::Notification => "notifications",
IconRole::Help => "help",
IconRole::Lock => "lock",
_ => return None,
})
}
#[allow(unreachable_patterns)]
fn lucide_name(role: IconRole) -> Option<&'static str> {
Some(match role {
IconRole::DialogWarning => "triangle-alert",
IconRole::DialogError => "circle-x",
IconRole::DialogInfo => "info",
IconRole::DialogQuestion => "circle-question-mark",
IconRole::DialogSuccess => "circle-check",
IconRole::Shield => "shield",
IconRole::WindowClose => "x",
IconRole::WindowMinimize => "minimize",
IconRole::WindowMaximize => "maximize",
IconRole::WindowRestore => "minimize-2",
IconRole::ActionSave => "save",
IconRole::ActionDelete => "trash",
IconRole::ActionCopy => "copy",
IconRole::ActionPaste => "clipboard-paste",
IconRole::ActionCut => "scissors",
IconRole::ActionUndo => "undo-2",
IconRole::ActionRedo => "redo-2",
IconRole::ActionSearch => "search",
IconRole::ActionSettings => "settings",
IconRole::ActionEdit => "pencil",
IconRole::ActionAdd => "plus",
IconRole::ActionRemove => "minus",
IconRole::ActionRefresh => "refresh-cw",
IconRole::ActionPrint => "printer",
IconRole::NavBack => "chevron-left",
IconRole::NavForward => "chevron-right",
IconRole::NavUp => "chevron-up",
IconRole::NavDown => "chevron-down",
IconRole::NavHome => "house",
IconRole::NavMenu => "menu",
IconRole::FileGeneric => "file",
IconRole::FolderClosed => "folder-closed",
IconRole::FolderOpen => "folder-open",
IconRole::TrashEmpty => "trash",
IconRole::TrashFull => "trash",
IconRole::StatusBusy => "loader",
IconRole::StatusCheck => "check",
IconRole::StatusError => "circle-x",
IconRole::UserAccount => "user",
IconRole::Notification => "bell",
IconRole::Help => "circle-question-mark",
IconRole::Lock => "lock",
_ => return None,
})
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
use super::*;
#[test]
fn icon_role_all_has_42_variants() {
assert_eq!(IconRole::ALL.len(), 42);
}
#[test]
fn icon_role_all_contains_every_variant() {
use std::collections::HashSet;
let all_set: HashSet<IconRole> = IconRole::ALL.iter().copied().collect();
let check = |role: IconRole| {
assert!(
all_set.contains(&role),
"IconRole::{role:?} missing from ALL array"
);
};
#[deny(unreachable_patterns)]
match IconRole::DialogWarning {
IconRole::DialogWarning
| IconRole::DialogError
| IconRole::DialogInfo
| IconRole::DialogQuestion
| IconRole::DialogSuccess
| IconRole::Shield
| IconRole::WindowClose
| IconRole::WindowMinimize
| IconRole::WindowMaximize
| IconRole::WindowRestore
| IconRole::ActionSave
| IconRole::ActionDelete
| IconRole::ActionCopy
| IconRole::ActionPaste
| IconRole::ActionCut
| IconRole::ActionUndo
| IconRole::ActionRedo
| IconRole::ActionSearch
| IconRole::ActionSettings
| IconRole::ActionEdit
| IconRole::ActionAdd
| IconRole::ActionRemove
| IconRole::ActionRefresh
| IconRole::ActionPrint
| IconRole::NavBack
| IconRole::NavForward
| IconRole::NavUp
| IconRole::NavDown
| IconRole::NavHome
| IconRole::NavMenu
| IconRole::FileGeneric
| IconRole::FolderClosed
| IconRole::FolderOpen
| IconRole::TrashEmpty
| IconRole::TrashFull
| IconRole::StatusBusy
| IconRole::StatusCheck
| IconRole::StatusError
| IconRole::UserAccount
| IconRole::Notification
| IconRole::Help
| IconRole::Lock => {}
}
check(IconRole::DialogWarning);
check(IconRole::DialogError);
check(IconRole::DialogInfo);
check(IconRole::DialogQuestion);
check(IconRole::DialogSuccess);
check(IconRole::Shield);
check(IconRole::WindowClose);
check(IconRole::WindowMinimize);
check(IconRole::WindowMaximize);
check(IconRole::WindowRestore);
check(IconRole::ActionSave);
check(IconRole::ActionDelete);
check(IconRole::ActionCopy);
check(IconRole::ActionPaste);
check(IconRole::ActionCut);
check(IconRole::ActionUndo);
check(IconRole::ActionRedo);
check(IconRole::ActionSearch);
check(IconRole::ActionSettings);
check(IconRole::ActionEdit);
check(IconRole::ActionAdd);
check(IconRole::ActionRemove);
check(IconRole::ActionRefresh);
check(IconRole::ActionPrint);
check(IconRole::NavBack);
check(IconRole::NavForward);
check(IconRole::NavUp);
check(IconRole::NavDown);
check(IconRole::NavHome);
check(IconRole::NavMenu);
check(IconRole::FileGeneric);
check(IconRole::FolderClosed);
check(IconRole::FolderOpen);
check(IconRole::TrashEmpty);
check(IconRole::TrashFull);
check(IconRole::StatusBusy);
check(IconRole::StatusCheck);
check(IconRole::StatusError);
check(IconRole::UserAccount);
check(IconRole::Notification);
check(IconRole::Help);
check(IconRole::Lock);
}
#[test]
fn icon_role_all_no_duplicates() {
let all = IconRole::ALL;
for (i, role) in all.iter().enumerate() {
for (j, other) in all.iter().enumerate() {
if i != j {
assert_ne!(role, other, "Duplicate at index {i} and {j}");
}
}
}
}
#[test]
fn icon_role_derives_copy_clone() {
let role = IconRole::ActionCopy;
let copied1 = role;
let copied2 = role;
assert_eq!(role, copied1);
assert_eq!(role, copied2);
}
#[test]
fn icon_role_derives_debug() {
let s = format!("{:?}", IconRole::DialogWarning);
assert!(s.contains("DialogWarning"));
}
#[test]
fn icon_role_derives_hash() {
use std::collections::HashSet;
let mut set = HashSet::new();
set.insert(IconRole::ActionSave);
set.insert(IconRole::ActionDelete);
assert_eq!(set.len(), 2);
assert!(set.contains(&IconRole::ActionSave));
}
#[test]
fn icon_data_svg_construct_and_match() {
let data = IconData::Svg(Cow::Borrowed(b"<svg></svg>"));
assert_eq!(data.bytes(), b"<svg></svg>");
match data {
IconData::Svg(ref cow) => assert_eq!(cow.as_ref(), b"<svg></svg>"),
_ => panic!("Expected Svg variant"),
}
}
#[test]
fn icon_data_rgba_construct_and_match() {
let pixels = vec![255, 0, 0, 255]; let data = IconData::rgba(1, 1, pixels.clone()).unwrap();
match data {
IconData::Rgba(rgba) => {
assert_eq!(rgba.width(), 1);
assert_eq!(rgba.height(), 1);
assert_eq!(rgba.data(), pixels.as_slice());
assert_eq!(rgba.into_data(), pixels);
}
_ => panic!("Expected Rgba variant"),
}
}
#[test]
fn icon_data_rgba_rejects_a_buffer_of_the_wrong_length() {
assert_eq!(IconData::rgba(16, 16, vec![]), None);
assert_eq!(IconData::rgba(1, 1, vec![0; 3]), None);
assert_eq!(IconData::rgba(1, 1, vec![0; 5]), None);
assert_eq!(IconData::rgba(2, 3, vec![0; 2 * 3 * 4 - 1]), None);
assert!(IconData::rgba(2, 3, vec![0; 2 * 3 * 4]).is_some());
assert!(IconData::rgba(0, 0, vec![]).is_some());
}
#[test]
fn icon_data_rgba_rejects_an_overflowing_size() {
assert_eq!(IconData::rgba(u32::MAX, u32::MAX, vec![]), None);
}
#[test]
fn icon_data_rgba_serializes_as_before() {
let icon = IconData::rgba(1, 1, vec![255, 0, 0, 255]).unwrap();
let json = serde_json::to_string(&icon).unwrap();
assert_eq!(
json,
r#"{"Rgba":{"width":1,"height":1,"data":[255,0,0,255]}}"#
);
let back: IconData = serde_json::from_str(&json).unwrap();
assert_eq!(back, icon);
let toml_text = toml::to_string(&icon).unwrap();
let back: IconData = toml::from_str(&toml_text).unwrap();
assert_eq!(back, icon);
}
#[test]
fn icon_data_rgba_deserialize_rejects_a_short_buffer() {
let json = r#"{"Rgba":{"width":16,"height":16,"data":[0,0,0,0]}}"#;
let err = serde_json::from_str::<IconData>(json).unwrap_err();
assert!(
err.to_string().contains("16 x 16 x 4"),
"unexpected error: {err}"
);
let toml_text = "[Rgba]\nwidth = 16\nheight = 16\ndata = [0, 0, 0, 0]\n";
let err = toml::from_str::<IconData>(toml_text).unwrap_err();
assert!(
err.to_string().contains("16 x 16 x 4"),
"unexpected error: {err}"
);
}
#[test]
fn icon_data_derives_debug() {
let data = IconData::Svg(Cow::Borrowed(b""));
let s = format!("{:?}", data);
assert!(s.contains("Svg"));
}
#[test]
fn icon_data_derives_clone() {
let data = IconData::rgba(16, 16, vec![0; 16 * 16 * 4]).unwrap();
let cloned = data.clone();
assert_eq!(data, cloned);
}
#[test]
fn icon_data_derives_eq() {
let a = IconData::Svg(Cow::Borrowed(b"<svg/>"));
let b = IconData::Svg(Cow::Owned(b"<svg/>".to_vec()));
assert_eq!(a, b);
let c = IconData::Svg(Cow::Borrowed(b"<other/>"));
assert_ne!(a, c);
}
#[test]
fn icon_set_from_name_sf_symbols() {
assert_eq!(IconSet::from_name("sf-symbols"), Some(IconSet::SfSymbols));
}
#[test]
fn icon_set_from_name_segoe_fluent() {
assert_eq!(
IconSet::from_name("segoe-fluent"),
Some(IconSet::SegoeFluent)
);
}
#[test]
fn icon_set_from_name_freedesktop() {
assert_eq!(
IconSet::from_name("freedesktop"),
Some(IconSet::Freedesktop)
);
}
#[test]
fn icon_set_from_name_material() {
assert_eq!(IconSet::from_name("material"), Some(IconSet::Material));
}
#[test]
fn icon_set_from_name_lucide() {
assert_eq!(IconSet::from_name("lucide"), Some(IconSet::Lucide));
}
#[test]
fn icon_set_from_name_unknown() {
assert_eq!(IconSet::from_name("unknown"), None);
}
#[test]
fn icon_set_name_sf_symbols() {
assert_eq!(IconSet::SfSymbols.name(), "sf-symbols");
}
#[test]
fn icon_set_name_segoe_fluent() {
assert_eq!(IconSet::SegoeFluent.name(), "segoe-fluent");
}
#[test]
fn icon_set_name_freedesktop() {
assert_eq!(IconSet::Freedesktop.name(), "freedesktop");
}
#[test]
fn icon_set_name_material() {
assert_eq!(IconSet::Material.name(), "material");
}
#[test]
fn icon_set_name_lucide() {
assert_eq!(IconSet::Lucide.name(), "lucide");
}
#[test]
fn icon_set_from_name_name_round_trip() {
let sets = [
IconSet::SfSymbols,
IconSet::SegoeFluent,
IconSet::Freedesktop,
IconSet::Material,
IconSet::Lucide,
];
for set in &sets {
let name = set.name();
let parsed = IconSet::from_name(name);
assert_eq!(parsed, Some(*set), "Round-trip failed for {:?}", set);
}
}
#[test]
fn icon_set_derives_copy_clone() {
let set = IconSet::Material;
let copied1 = set;
let copied2 = set;
assert_eq!(set, copied1);
assert_eq!(set, copied2);
}
#[test]
fn icon_set_derives_hash() {
use std::collections::HashSet;
let mut map = HashSet::new();
map.insert(IconSet::SfSymbols);
map.insert(IconSet::Lucide);
assert_eq!(map.len(), 2);
}
#[test]
fn icon_set_derives_debug() {
let s = format!("{:?}", IconSet::Freedesktop);
assert!(s.contains("Freedesktop"));
}
#[test]
fn icon_set_serde_round_trip() {
let set = IconSet::SfSymbols;
let json = serde_json::to_string(&set).unwrap();
let deserialized: IconSet = serde_json::from_str(&json).unwrap();
assert_eq!(set, deserialized);
}
#[test]
fn icon_name_sf_symbols_action_copy() {
assert_eq!(
icon_name(IconRole::ActionCopy, IconSet::SfSymbols),
Some("doc.on.doc")
);
}
#[test]
fn icon_name_segoe_action_copy() {
assert_eq!(
icon_name(IconRole::ActionCopy, IconSet::SegoeFluent),
Some("Copy")
);
}
#[test]
fn icon_name_freedesktop_action_copy() {
assert_eq!(
icon_name(IconRole::ActionCopy, IconSet::Freedesktop),
Some("edit-copy")
);
}
#[test]
fn icon_name_material_action_copy() {
assert_eq!(
icon_name(IconRole::ActionCopy, IconSet::Material),
Some("content_copy")
);
}
#[test]
fn icon_name_lucide_action_copy() {
assert_eq!(
icon_name(IconRole::ActionCopy, IconSet::Lucide),
Some("copy")
);
}
#[test]
fn icon_name_sf_symbols_dialog_warning() {
assert_eq!(
icon_name(IconRole::DialogWarning, IconSet::SfSymbols),
Some("exclamationmark.triangle.fill")
);
}
#[test]
fn icon_name_sf_symbols_folder_open_is_none() {
assert_eq!(icon_name(IconRole::FolderOpen, IconSet::SfSymbols), None);
}
#[test]
fn icon_name_sf_symbols_trash_full() {
assert_eq!(
icon_name(IconRole::TrashFull, IconSet::SfSymbols),
Some("trash.fill")
);
}
#[test]
fn icon_name_sf_symbols_status_busy_is_none() {
assert_eq!(icon_name(IconRole::StatusBusy, IconSet::SfSymbols), None);
}
#[test]
fn icon_name_sf_symbols_window_restore() {
assert_eq!(
icon_name(IconRole::WindowRestore, IconSet::SfSymbols),
Some("arrow.down.right.and.arrow.up.left")
);
}
#[test]
fn icon_name_segoe_dialog_success() {
assert_eq!(
icon_name(IconRole::DialogSuccess, IconSet::SegoeFluent),
Some("CheckMark")
);
}
#[test]
fn icon_name_segoe_status_busy_is_none() {
assert_eq!(icon_name(IconRole::StatusBusy, IconSet::SegoeFluent), None);
}
#[test]
fn icon_name_freedesktop_notification() {
assert_eq!(
icon_name(IconRole::Notification, IconSet::Freedesktop),
Some("notification-active")
);
}
#[test]
fn icon_name_freedesktop_dialog_success() {
assert_eq!(
icon_name(IconRole::DialogSuccess, IconSet::Freedesktop),
Some("object-select-symbolic")
);
}
#[test]
fn icon_name_freedesktop_status_busy() {
assert_eq!(
icon_name(IconRole::StatusBusy, IconSet::Freedesktop),
Some("content-loading-symbolic")
);
}
#[test]
fn icon_name_material_trash_full() {
assert_eq!(
icon_name(IconRole::TrashFull, IconSet::Material),
Some("delete")
);
}
#[test]
fn icon_name_lucide_trash_full() {
assert_eq!(
icon_name(IconRole::TrashFull, IconSet::Lucide),
Some("trash")
);
}
#[test]
fn icon_name_spot_check_dialog_error() {
assert_eq!(
icon_name(IconRole::DialogError, IconSet::SfSymbols),
Some("xmark.circle.fill")
);
assert_eq!(
icon_name(IconRole::DialogError, IconSet::SegoeFluent),
Some("SIID_ERROR")
);
assert_eq!(
icon_name(IconRole::DialogError, IconSet::Freedesktop),
Some("dialog-error")
);
assert_eq!(
icon_name(IconRole::DialogError, IconSet::Material),
Some("error")
);
assert_eq!(
icon_name(IconRole::DialogError, IconSet::Lucide),
Some("circle-x")
);
}
#[test]
fn icon_name_spot_check_nav_home() {
assert_eq!(
icon_name(IconRole::NavHome, IconSet::SfSymbols),
Some("house")
);
assert_eq!(
icon_name(IconRole::NavHome, IconSet::SegoeFluent),
Some("Home")
);
assert_eq!(
icon_name(IconRole::NavHome, IconSet::Freedesktop),
Some("go-home")
);
assert_eq!(
icon_name(IconRole::NavHome, IconSet::Material),
Some("home")
);
assert_eq!(icon_name(IconRole::NavHome, IconSet::Lucide), Some("house"));
}
#[test]
fn icon_name_sf_symbols_expected_count() {
let some_count = IconRole::ALL
.iter()
.filter(|r| icon_name(**r, IconSet::SfSymbols).is_some())
.count();
assert_eq!(some_count, 40, "SF Symbols should have 40 mappings");
}
#[test]
fn icon_name_segoe_expected_count() {
let some_count = IconRole::ALL
.iter()
.filter(|r| icon_name(**r, IconSet::SegoeFluent).is_some())
.count();
assert_eq!(some_count, 41, "Segoe Fluent should have 41 mappings");
}
#[test]
fn icon_name_freedesktop_expected_count() {
let some_count = IconRole::ALL
.iter()
.filter(|r| icon_name(**r, IconSet::Freedesktop).is_some())
.count();
assert_eq!(some_count, 42, "Freedesktop should have 42 mappings");
}
#[test]
fn icon_name_material_expected_count() {
let some_count = IconRole::ALL
.iter()
.filter(|r| icon_name(**r, IconSet::Material).is_some())
.count();
assert_eq!(some_count, 42, "Material should have 42 mappings");
}
#[test]
fn icon_name_lucide_expected_count() {
let some_count = IconRole::ALL
.iter()
.filter(|r| icon_name(**r, IconSet::Lucide).is_some())
.count();
assert_eq!(some_count, 42, "Lucide should have 42 mappings");
}
#[test]
fn icon_provider_is_object_safe() {
let provider: Box<dyn IconProvider> = Box::new(IconRole::ActionCopy);
let debug_str = format!("{:?}", provider);
assert!(
debug_str.contains("ActionCopy"),
"Debug should print variant name"
);
}
#[test]
fn icon_role_provider_icon_name() {
let role = IconRole::ActionCopy;
let name = IconProvider::icon_name(&role, IconSet::Material);
assert_eq!(name, Some("content_copy"));
}
#[test]
fn icon_role_provider_icon_name_sf_symbols() {
let role = IconRole::ActionCopy;
let name = IconProvider::icon_name(&role, IconSet::SfSymbols);
assert_eq!(name, Some("doc.on.doc"));
}
#[test]
#[cfg(feature = "material-icons")]
fn icon_role_provider_icon_svg_material() {
let role = IconRole::ActionCopy;
let svg = IconProvider::icon_svg(&role, IconSet::Material);
assert!(svg.is_some(), "Material SVG should be Some");
let cow = svg.unwrap();
let content = std::str::from_utf8(&cow).expect("valid UTF-8");
assert!(content.contains("<svg"), "should contain <svg tag");
}
#[test]
fn icon_role_provider_icon_svg_non_bundled() {
let role = IconRole::ActionCopy;
let svg = IconProvider::icon_svg(&role, IconSet::SfSymbols);
assert!(svg.is_none(), "SfSymbols should not have bundled SVGs");
}
#[test]
fn icon_role_provider_all_roles() {
for role in IconRole::ALL {
let _name = IconProvider::icon_name(role, IconSet::Material);
}
}
#[test]
fn icon_provider_dyn_dispatch() {
let role = IconRole::ActionCopy;
let provider: &dyn IconProvider = &role;
let name = provider.icon_name(IconSet::Material);
assert_eq!(name, Some("content_copy"));
let svg = provider.icon_svg(IconSet::SfSymbols);
assert!(svg.is_none(), "SfSymbols should not have bundled SVGs");
}
fn known_gaps() -> &'static [(IconSet, IconRole)] {
&[
(IconSet::SfSymbols, IconRole::FolderOpen),
(IconSet::SfSymbols, IconRole::StatusBusy),
(IconSet::SegoeFluent, IconRole::StatusBusy),
]
}
#[test]
fn no_unexpected_icon_gaps() {
let gaps = known_gaps();
let system_sets = [
IconSet::SfSymbols,
IconSet::SegoeFluent,
IconSet::Freedesktop,
];
for &set in &system_sets {
for role in IconRole::ALL.iter().copied() {
let is_known_gap = gaps.contains(&(set, role));
let is_mapped = icon_name(role, set).is_some();
if !is_known_gap {
assert!(
is_mapped,
"{role:?} has no mapping for {set:?} and is not in known_gaps()"
);
}
}
}
}
#[test]
#[cfg(all(feature = "material-icons", feature = "lucide-icons"))]
fn all_roles_have_bundled_svg() {
use crate::bundled_icon_svg;
for set in [IconSet::Material, IconSet::Lucide] {
for role in IconRole::ALL.iter().copied() {
assert!(
bundled_icon_svg(role, set).is_some(),
"{role:?} has no bundled SVG for {set:?}"
);
}
}
}
#[test]
fn icon_name_exhaustive_all_sets() {
for role in IconRole::ALL.iter().copied() {
assert!(
icon_name(role, IconSet::Material).is_some(),
"Material must map {role:?} to Some"
);
}
for role in IconRole::ALL.iter().copied() {
assert!(
icon_name(role, IconSet::Lucide).is_some(),
"Lucide must map {role:?} to Some"
);
}
for role in IconRole::ALL.iter().copied() {
assert!(
icon_name(role, IconSet::Freedesktop).is_some(),
"Freedesktop must map {role:?} to Some"
);
}
let segoe_count = IconRole::ALL
.iter()
.filter(|r| icon_name(**r, IconSet::SegoeFluent).is_some())
.count();
assert!(
segoe_count >= 41,
"Segoe should map at least 41 roles, got {segoe_count}"
);
let sf_count = IconRole::ALL
.iter()
.filter(|r| icon_name(**r, IconSet::SfSymbols).is_some())
.count();
assert!(
sf_count >= 40,
"SfSymbols should map at least 40 roles, got {sf_count}"
);
}
#[test]
fn icon_name_returns_nonempty_strings() {
let all_sets = [
IconSet::SfSymbols,
IconSet::SegoeFluent,
IconSet::Freedesktop,
IconSet::Material,
IconSet::Lucide,
];
for set in all_sets {
for role in IconRole::ALL.iter().copied() {
if let Some(name) = icon_name(role, set) {
assert!(
!name.is_empty(),
"icon_name({role:?}, {set:?}) returned empty string"
);
}
}
}
}
#[test]
fn icon_set_name_round_trip() {
let all_sets = [
IconSet::SfSymbols,
IconSet::SegoeFluent,
IconSet::Freedesktop,
IconSet::Material,
IconSet::Lucide,
];
for set in all_sets {
assert_eq!(
IconSet::from_name(set.name()),
Some(set),
"IconSet::{:?}.name() = {:?} did not round-trip through from_name()",
set,
set.name()
);
}
}
#[test]
fn icon_role_name_returns_kebab_case() {
assert_eq!(IconRole::ActionSave.name(), "action-save");
assert_eq!(IconRole::DialogWarning.name(), "dialog-warning");
assert_eq!(IconRole::WindowClose.name(), "window-close");
assert_eq!(IconRole::NavBack.name(), "nav-back");
assert_eq!(IconRole::FileGeneric.name(), "file-generic");
assert_eq!(IconRole::StatusBusy.name(), "status-busy");
assert_eq!(IconRole::UserAccount.name(), "user-account");
assert_eq!(IconRole::Shield.name(), "shield");
assert_eq!(IconRole::Notification.name(), "notification");
assert_eq!(IconRole::Help.name(), "help");
assert_eq!(IconRole::Lock.name(), "lock");
}
#[test]
fn icon_role_display_delegates_to_name() {
for role in IconRole::ALL {
assert_eq!(
format!("{role}"),
role.name(),
"Display for IconRole::{:?} should delegate to name()",
role
);
}
}
#[test]
fn icon_set_serde_matches_name() {
let all_sets = [
IconSet::SfSymbols,
IconSet::SegoeFluent,
IconSet::Freedesktop,
IconSet::Material,
IconSet::Lucide,
];
for set in all_sets {
let serialized = serde_json::to_string(&set)
.unwrap_or_else(|e| panic!("failed to serialize {set:?}: {e}"));
let trimmed = serialized.trim_matches('"');
assert_eq!(
trimmed,
set.name(),
"serde serialization of {set:?} ({trimmed:?}) does not match name() ({:?})",
set.name()
);
}
}
#[test]
fn icon_data_bytes_accessor() {
let svg = IconData::Svg(Cow::Borrowed(b"<svg/>"));
assert_eq!(svg.bytes(), b"<svg/>");
let rgba = IconData::rgba(1, 1, vec![1, 2, 3, 4]).unwrap();
assert_eq!(rgba.bytes(), &[1, 2, 3, 4]);
}
}