use std::fmt;
#[allow(unused_imports)]
use std::borrow::Cow;
#[allow(unused_imports)]
use crate::model::icons::{icon_name, system_icon_set, system_icon_theme};
use crate::model::{AnimatedIcon, IconData, IconProvider, IconRole, IconSet};
#[allow(unused_imports)]
use crate::model::{bundled_icon_by_name, bundled_icon_svg};
#[derive(Debug)]
#[non_exhaustive]
pub enum IconId<'a> {
Role(IconRole),
Name(&'a str),
Custom(&'a dyn IconProvider),
}
impl From<IconRole> for IconId<'_> {
fn from(role: IconRole) -> Self {
IconId::Role(role)
}
}
impl<'a> From<&'a str> for IconId<'a> {
fn from(name: &'a str) -> Self {
IconId::Name(name)
}
}
impl<'a> From<&'a dyn IconProvider> for IconId<'a> {
fn from(provider: &'a dyn IconProvider) -> Self {
IconId::Custom(provider)
}
}
impl<'a, T: IconProvider> From<&'a T> for IconId<'a> {
fn from(provider: &'a T) -> Self {
IconId::Custom(provider)
}
}
#[derive(Debug)]
#[must_use]
pub struct FreedesktopLoader<'a> {
#[allow(dead_code)]
id: IconId<'a>,
#[allow(dead_code)]
size: u16,
#[allow(dead_code)]
fg_color: Option<[u8; 3]>,
#[allow(dead_code)]
theme: Option<&'a str>,
}
impl<'a> FreedesktopLoader<'a> {
pub fn new(id: impl Into<IconId<'a>>) -> Self {
Self {
id: id.into(),
size: 24,
fg_color: None,
theme: None,
}
}
pub fn size(mut self, size: u16) -> Self {
self.size = size;
self
}
pub fn color(mut self, rgb: [u8; 3]) -> Self {
self.fg_color = Some(rgb);
self
}
pub fn color_opt(mut self, rgb: Option<[u8; 3]>) -> Self {
self.fg_color = rgb;
self
}
pub fn theme(mut self, theme: &'a str) -> Self {
self.theme = Some(theme);
self
}
#[must_use]
pub fn load(self) -> Option<IconData> {
self.load_with(system_icon_theme)
}
#[allow(unused_variables)]
fn load_with(self, detect: impl FnOnce() -> crate::Result<String>) -> Option<IconData> {
#[cfg(all(target_os = "linux", feature = "system-icons"))]
{
let detected;
let theme: Option<&str> = match self.theme {
Some(t) => Some(t),
None => {
detected = detect().ok();
detected.as_deref()
}
};
match self.id {
IconId::Role(role) => {
let name = icon_name(role, IconSet::Freedesktop)?;
crate::freedesktop::load_freedesktop_icon_by_name(
name,
theme?,
self.size,
self.fg_color,
)
}
IconId::Name(name) => crate::freedesktop::load_freedesktop_icon_by_name(
name,
theme?,
self.size,
self.fg_color,
),
IconId::Custom(provider) => {
if let Some(theme) = theme
&& let Some(name) = provider.icon_name(IconSet::Freedesktop)
&& let Some(data) = crate::freedesktop::load_freedesktop_icon_by_name(
name,
theme,
self.size,
self.fg_color,
)
{
return Some(data);
}
provider.icon_svg(IconSet::Freedesktop).map(IconData::Svg)
}
}
}
#[cfg(not(all(target_os = "linux", feature = "system-icons")))]
{
None
}
}
#[must_use]
#[allow(unused_variables)]
pub fn load_indicator(theme: Option<&str>) -> Option<AnimatedIcon> {
#[cfg(all(target_os = "linux", feature = "system-icons"))]
{
crate::freedesktop::load_freedesktop_spinner(theme)
}
#[cfg(not(all(target_os = "linux", feature = "system-icons")))]
{
None
}
}
}
#[derive(Debug)]
#[must_use]
pub struct SfSymbolsLoader<'a> {
#[allow(dead_code)] id: IconId<'a>,
#[allow(dead_code)] fg_color: Option<[u8; 3]>,
}
impl<'a> SfSymbolsLoader<'a> {
pub fn new(id: impl Into<IconId<'a>>) -> Self {
Self {
id: id.into(),
fg_color: None,
}
}
pub fn color(mut self, rgb: [u8; 3]) -> Self {
self.fg_color = Some(rgb);
self
}
pub fn color_opt(mut self, rgb: Option<[u8; 3]>) -> Self {
self.fg_color = rgb;
self
}
#[must_use]
#[allow(unused_variables)]
pub fn load(self) -> Option<IconData> {
#[cfg(all(target_os = "macos", feature = "system-icons"))]
{
match self.id {
IconId::Role(role) => {
let name = icon_name(role, IconSet::SfSymbols)?;
crate::sficons::load_sf_icon_by_name(name, self.fg_color)
}
IconId::Name(n) => crate::sficons::load_sf_icon_by_name(n, self.fg_color),
IconId::Custom(p) => {
if let Some(n) = p.icon_name(IconSet::SfSymbols)
&& let Some(data) = crate::sficons::load_sf_icon_by_name(n, self.fg_color)
{
return Some(data);
}
p.icon_svg(IconSet::SfSymbols).map(IconData::Svg)
}
}
}
#[cfg(not(all(target_os = "macos", feature = "system-icons")))]
{
None
}
}
}
#[derive(Debug)]
#[must_use]
pub struct SegoeIconsLoader<'a> {
#[allow(dead_code)] id: IconId<'a>,
#[allow(dead_code)] fg_color: Option<[u8; 3]>,
}
impl<'a> SegoeIconsLoader<'a> {
pub fn new(id: impl Into<IconId<'a>>) -> Self {
Self {
id: id.into(),
fg_color: None,
}
}
pub fn color(mut self, rgb: [u8; 3]) -> Self {
self.fg_color = Some(rgb);
self
}
pub fn color_opt(mut self, rgb: Option<[u8; 3]>) -> Self {
self.fg_color = rgb;
self
}
#[must_use]
#[allow(unused_variables)]
pub fn load(self) -> Option<IconData> {
#[cfg(all(target_os = "windows", feature = "system-icons"))]
{
match self.id {
IconId::Role(role) => {
let name = icon_name(role, IconSet::SegoeIcons)?;
crate::winicons::load_windows_icon_by_name(name, self.fg_color)
}
IconId::Name(n) => crate::winicons::load_windows_icon_by_name(n, self.fg_color),
IconId::Custom(p) => {
if let Some(n) = p.icon_name(IconSet::SegoeIcons)
&& let Some(data) =
crate::winicons::load_windows_icon_by_name(n, self.fg_color)
{
return Some(data);
}
p.icon_svg(IconSet::SegoeIcons).map(IconData::Svg)
}
}
}
#[cfg(not(all(target_os = "windows", feature = "system-icons")))]
{
None
}
}
}
#[derive(Debug)]
#[must_use]
pub struct MaterialLoader<'a> {
#[allow(dead_code)] id: IconId<'a>,
}
impl<'a> MaterialLoader<'a> {
pub fn new(id: impl Into<IconId<'a>>) -> Self {
Self { id: id.into() }
}
#[must_use]
#[allow(unused_variables)]
pub fn load(self) -> Option<IconData> {
#[cfg(feature = "material-icons")]
{
match self.id {
IconId::Role(role) => bundled_icon_svg(role, IconSet::Material)
.map(|b| IconData::Svg(Cow::Borrowed(b))),
IconId::Name(n) => bundled_icon_by_name(n, IconSet::Material)
.map(|b| IconData::Svg(Cow::Borrowed(b))),
IconId::Custom(p) => {
if let Some(n) = p.icon_name(IconSet::Material)
&& let Some(b) = bundled_icon_by_name(n, IconSet::Material)
{
return Some(IconData::Svg(Cow::Borrowed(b)));
}
p.icon_svg(IconSet::Material).map(IconData::Svg)
}
}
}
#[cfg(not(feature = "material-icons"))]
{
None
}
}
#[must_use]
pub fn load_indicator() -> Option<AnimatedIcon> {
#[cfg(feature = "material-icons")]
{
Some(crate::spinners::material_spinner())
}
#[cfg(not(feature = "material-icons"))]
{
None
}
}
}
#[derive(Debug)]
#[must_use]
pub struct LucideLoader<'a> {
#[allow(dead_code)] id: IconId<'a>,
}
impl<'a> LucideLoader<'a> {
pub fn new(id: impl Into<IconId<'a>>) -> Self {
Self { id: id.into() }
}
#[must_use]
#[allow(unused_variables)]
pub fn load(self) -> Option<IconData> {
#[cfg(feature = "lucide-icons")]
{
match self.id {
IconId::Role(role) => {
bundled_icon_svg(role, IconSet::Lucide).map(|b| IconData::Svg(Cow::Borrowed(b)))
}
IconId::Name(n) => bundled_icon_by_name(n, IconSet::Lucide)
.map(|b| IconData::Svg(Cow::Borrowed(b))),
IconId::Custom(p) => {
if let Some(n) = p.icon_name(IconSet::Lucide)
&& let Some(b) = bundled_icon_by_name(n, IconSet::Lucide)
{
return Some(IconData::Svg(Cow::Borrowed(b)));
}
p.icon_svg(IconSet::Lucide).map(IconData::Svg)
}
}
}
#[cfg(not(feature = "lucide-icons"))]
{
None
}
}
#[must_use]
pub fn load_indicator() -> Option<AnimatedIcon> {
#[cfg(feature = "lucide-icons")]
{
Some(crate::spinners::lucide_spinner())
}
#[cfg(not(feature = "lucide-icons"))]
{
None
}
}
}
#[must_use]
pub fn load_icon<'a>(id: impl Into<IconId<'a>>, set: IconSet) -> Option<IconData> {
let id = id.into();
match set {
IconSet::Freedesktop => FreedesktopLoader::new(id).load(),
IconSet::SfSymbols => SfSymbolsLoader::new(id).load(),
IconSet::SegoeIcons => SegoeIconsLoader::new(id).load(),
IconSet::Material => MaterialLoader::new(id).load(),
IconSet::Lucide => LucideLoader::new(id).load(),
}
}
#[must_use]
pub fn load_icon_indicator(set: IconSet) -> Option<AnimatedIcon> {
match set {
IconSet::Freedesktop => FreedesktopLoader::load_indicator(None),
IconSet::Material => MaterialLoader::load_indicator(),
IconSet::Lucide => LucideLoader::load_indicator(),
IconSet::SfSymbols | IconSet::SegoeIcons => None,
}
}
#[must_use]
pub fn colorize_monochrome_svg(svg: &[u8], color: crate::color::Rgba) -> Vec<u8> {
let hex = format!("#{:02x}{:02x}{:02x}", color.r, color.g, color.b);
let Ok(svg_str) = std::str::from_utf8(svg) else {
return svg.to_vec();
};
let replaced = if svg_str.contains("currentColor") {
svg_str.replace("currentColor", &hex)
} else {
svg_str.to_owned()
};
let fill_hex = format!("fill=\"{hex}\"");
let replaced = replaced
.replace("fill=\"black\"", &fill_hex)
.replace("fill=\"#000000\"", &fill_hex)
.replace("fill=\"#000\"", &fill_hex);
let stroke_hex = format!("stroke=\"{hex}\"");
let replaced = replaced
.replace("stroke=\"black\"", &stroke_hex)
.replace("stroke=\"#000000\"", &stroke_hex)
.replace("stroke=\"#000\"", &stroke_hex);
if replaced != svg_str {
return replaced.into_bytes();
}
if let Some(pos) = svg_str.find("<svg")
&& let Some(tail) = svg_str.get(pos..)
&& let Some(close) = tail.find('>')
{
let tag_end = pos.saturating_add(close);
if let Some(tag) = svg_str.get(pos..tag_end)
&& !tag.contains("fill=")
{
let is_self_closing = tag_end > 0
&& svg_str
.as_bytes()
.get(tag_end.saturating_sub(1))
.is_some_and(|&b| b == b'/');
let inject_pos = if is_self_closing {
tag_end.saturating_sub(1)
} else {
tag_end
};
if let Some(before) = svg_str.get(..inject_pos)
&& let Some(after) = svg_str.get(inject_pos..)
{
let mut result = String::with_capacity(svg_str.len().saturating_add(20));
result.push_str(before);
result.push_str(&format!(" fill=\"{hex}\""));
result.push_str(after);
return result.into_bytes();
}
}
}
svg.to_vec()
}
#[cfg(target_os = "linux")]
pub(crate) fn icon_base_dirs() -> &'static [std::path::PathBuf] {
static DIRS: std::sync::OnceLock<Vec<std::path::PathBuf>> = std::sync::OnceLock::new();
DIRS.get_or_init(xdg_icon_base_dirs)
}
#[cfg(target_os = "linux")]
fn xdg_icon_base_dirs() -> Vec<std::path::PathBuf> {
use std::path::PathBuf;
let Some(home) = std::env::home_dir() else {
return Vec::new();
};
let data_dirs: Vec<PathBuf> = std::env::var_os("XDG_DATA_DIRS")
.map(|dirs| {
std::env::split_paths(&dirs)
.filter(|dir| dir.is_absolute())
.collect::<Vec<_>>()
})
.filter(|dirs| !dirs.is_empty())
.unwrap_or_else(|| {
vec![
PathBuf::from("/usr/local/share"),
PathBuf::from("/usr/share"),
]
});
let data_home = std::env::var_os("XDG_DATA_HOME")
.map(PathBuf::from)
.filter(|dir| dir.is_absolute())
.unwrap_or_else(|| home.join(".local/share"));
let mut dirs: Vec<PathBuf> = data_dirs.iter().map(|dir| dir.join("icons")).collect();
dirs.push(data_home.join("icons"));
dirs.push(home.join(".icons"));
dirs.retain(|dir| dir.exists());
dirs
}
#[cfg(target_os = "linux")]
fn is_theme_name(name: &str) -> bool {
use std::path::{Component, Path};
let mut components = Path::new(name).components();
matches!(
(components.next(), components.next()),
(Some(Component::Normal(_)), None)
)
}
#[cfg(target_os = "linux")]
pub(crate) fn has_theme_index(theme: &str, bases: &[std::path::PathBuf]) -> bool {
is_theme_name(theme)
&& bases
.iter()
.any(|base| base.join(theme).join("index.theme").exists())
}
#[must_use]
pub fn is_freedesktop_theme_available(theme: &str) -> bool {
#[cfg(target_os = "linux")]
{
has_theme_index(theme, icon_base_dirs())
}
#[cfg(not(target_os = "linux"))]
{
let _ = theme;
false
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum IconSetChoice {
Default(String),
System,
Freedesktop(String),
Material,
Lucide,
}
impl fmt::Display for IconSetChoice {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Default(name) => write!(f, "default ({name})"),
Self::System => f.write_str(&system_choice_label(&system_icon_theme())),
Self::Freedesktop(name) => write!(f, "{name}"),
Self::Material => write!(f, "Material (bundled)"),
Self::Lucide => write!(f, "Lucide (bundled)"),
}
}
}
fn system_choice_label(detected: &crate::Result<String>) -> String {
match detected {
Ok(name) => format!("system ({name})"),
Err(e) => format!("system (unavailable: {e})"),
}
}
impl IconSetChoice {
#[must_use]
pub fn effective_icon_set(&self, theme_icon_set: IconSet) -> IconSet {
match self {
Self::Default(_) => theme_icon_set,
Self::System => system_icon_set(),
Self::Freedesktop(_) => IconSet::Freedesktop,
Self::Material => IconSet::Material,
Self::Lucide => IconSet::Lucide,
}
}
#[must_use]
pub fn freedesktop_theme(&self) -> Option<&str> {
match self {
Self::Default(name) | Self::Freedesktop(name) => Some(name),
Self::System | Self::Material | Self::Lucide => None,
}
}
#[must_use]
pub fn follows_preset(&self) -> bool {
matches!(self, Self::Default(_))
}
}
#[must_use]
pub fn default_icon_choice(icon_set: IconSet, icon_theme: Option<&str>) -> IconSetChoice {
let Some(theme) = icon_theme else {
return IconSetChoice::System;
};
let available = match icon_set {
IconSet::Material | IconSet::Lucide => true,
IconSet::Freedesktop => is_freedesktop_theme_available(theme),
IconSet::SfSymbols | IconSet::SegoeIcons => true,
};
if available {
IconSetChoice::Default(theme.to_string())
} else {
IconSetChoice::System
}
}
#[must_use]
pub fn list_freedesktop_themes() -> Vec<String> {
#[cfg(target_os = "linux")]
{
use std::collections::BTreeSet;
use std::io::BufRead;
let mut themes = BTreeSet::new();
for icon_dir in icon_base_dirs() {
let entries = match std::fs::read_dir(icon_dir) {
Ok(e) => e,
Err(_) => continue,
};
for entry in entries.filter_map(|e| e.ok()) {
let path = entry.path();
if !path.is_dir() {
continue;
}
let name = match entry.file_name().into_string() {
Ok(n) => n,
Err(_) => continue,
};
if name == "hicolor" || name == "default" {
continue;
}
let index_path = path.join("index.theme");
let file = match std::fs::File::open(&index_path) {
Ok(f) => f,
Err(_) => continue,
};
let reader = std::io::BufReader::new(file);
let has_directories = reader
.lines()
.map_while(Result::ok)
.any(|line| line.starts_with("Directories="));
if has_directories {
themes.insert(name);
}
}
}
themes.into_iter().collect()
}
#[cfg(not(target_os = "linux"))]
{
Vec::new()
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod load_icon_tests {
use super::*;
#[cfg(all(target_os = "linux", feature = "system-icons"))]
fn undetected() -> crate::Result<String> {
Err(crate::Error::PlatformUnsupported {
platform: "the test's failing detection",
})
}
#[test]
#[cfg(all(target_os = "linux", feature = "system-icons"))]
fn freedesktop_loader_without_a_detected_theme_loads_nothing() {
let custom: &dyn IconProvider = &IconRole::ActionCopy;
for id in [
IconId::Role(IconRole::ActionCopy),
IconId::Name("edit-copy"),
IconId::Custom(custom),
] {
assert!(
FreedesktopLoader::new(id).load_with(undetected).is_none(),
"an icon loaded though no icon theme was detected"
);
}
}
#[test]
#[cfg(all(target_os = "linux", feature = "system-icons"))]
fn freedesktop_loader_without_a_detected_theme_gives_a_providers_own_svg() {
#[derive(Debug)]
struct AppIcon;
impl IconProvider for AppIcon {
fn icon_name(&self, _set: IconSet) -> Option<&str> {
Some("edit-copy")
}
fn icon_svg(&self, set: IconSet) -> Option<Cow<'static, [u8]>> {
(set == IconSet::Freedesktop).then_some(Cow::Borrowed(b"<svg>app</svg>"))
}
}
let provider: &dyn IconProvider = &AppIcon;
assert_eq!(
FreedesktopLoader::new(provider).load_with(undetected),
Some(IconData::Svg(Cow::Borrowed(b"<svg>app</svg>"))),
"the provider's own SVG did not load without a detected icon theme"
);
}
#[test]
#[cfg(feature = "material-icons")]
fn a_provider_is_passed_to_a_loader_by_reference() {
#[derive(Debug)]
struct AppIcon;
impl IconProvider for AppIcon {
fn icon_name(&self, _set: IconSet) -> Option<&str> {
None
}
fn icon_svg(&self, set: IconSet) -> Option<Cow<'static, [u8]>> {
(set == IconSet::Material).then_some(Cow::Borrowed(b"<svg>app</svg>"))
}
}
assert_eq!(
MaterialLoader::new(&AppIcon).load(),
Some(IconData::Svg(Cow::Borrowed(b"<svg>app</svg>"))),
"a provider passed by reference did not load its own SVG"
);
}
#[test]
#[cfg(all(target_os = "linux", feature = "system-icons"))]
fn freedesktop_loader_with_a_theme_does_not_detect() {
let runs = std::cell::Cell::new(0);
let _ = FreedesktopLoader::new("edit-copy")
.theme("Adwaita")
.load_with(|| {
runs.set(runs.get() + 1);
undetected()
});
assert_eq!(runs.get(), 0, "an explicit theme ran the detection");
}
#[test]
#[cfg(all(target_os = "linux", feature = "system-icons"))]
fn freedesktop_loader_theme_override_honored_for_name_lookup() {
let result = FreedesktopLoader::new("format-text-rich")
.theme("Adwaita")
.size(24)
.load();
assert!(
result.is_some(),
"theme('Adwaita') must resolve 'format-text-rich' in Adwaita, regardless of system theme"
);
}
#[test]
#[cfg(feature = "material-icons")]
fn load_icon_material_returns_svg() {
let result = MaterialLoader::new(IconRole::ActionCopy).load();
assert!(result.is_some(), "material ActionCopy should return Some");
match result.unwrap() {
IconData::Svg(ref cow) => {
let s = String::from_utf8_lossy(cow);
assert!(s.contains("<svg"), "should contain SVG data");
}
_ => panic!("expected IconData::Svg for bundled material icon"),
}
}
#[test]
#[cfg(feature = "lucide-icons")]
fn load_icon_lucide_returns_svg() {
let result = LucideLoader::new(IconRole::ActionCopy).load();
assert!(result.is_some(), "lucide ActionCopy should return Some");
match result.unwrap() {
IconData::Svg(ref cow) => {
let s = String::from_utf8_lossy(cow);
assert!(s.contains("<svg"), "should contain SVG data");
}
_ => panic!("expected IconData::Svg for bundled lucide icon"),
}
}
#[test]
#[cfg(feature = "material-icons")]
fn load_icon_unknown_theme_no_cross_set_fallback() {
let result = FreedesktopLoader::new(IconRole::ActionCopy).load();
let _ = result;
}
#[test]
#[cfg(feature = "material-icons")]
fn load_icon_all_roles_material() {
let mut some_count = 0;
for role in IconRole::ALL {
if MaterialLoader::new(role).load().is_some() {
some_count += 1;
}
}
assert_eq!(
some_count, 42,
"Material should cover all 42 roles via bundled SVGs"
);
}
#[test]
#[cfg(feature = "lucide-icons")]
fn load_icon_all_roles_lucide() {
let mut some_count = 0;
for role in IconRole::ALL {
if LucideLoader::new(role).load().is_some() {
some_count += 1;
}
}
assert_eq!(
some_count, 42,
"Lucide should cover all 42 roles via bundled SVGs"
);
}
#[test]
fn sf_symbols_loader_stores_the_colour() {
let loader = SfSymbolsLoader::new(IconRole::ActionCopy).color([10, 20, 30]);
assert_eq!(loader.fg_color, Some([10, 20, 30]));
let loader = loader.color_opt(None);
assert_eq!(loader.fg_color, None);
let loader = loader.color_opt(Some([40, 50, 60]));
assert_eq!(loader.fg_color, Some([40, 50, 60]));
assert_eq!(SfSymbolsLoader::new(IconRole::ActionCopy).fg_color, None);
}
#[test]
fn segoe_icons_loader_stores_the_colour() {
let loader = SegoeIconsLoader::new(IconRole::ActionCopy).color([10, 20, 30]);
assert_eq!(loader.fg_color, Some([10, 20, 30]));
let loader = loader.color_opt(None);
assert_eq!(loader.fg_color, None);
let loader = loader.color_opt(Some([40, 50, 60]));
assert_eq!(loader.fg_color, Some([40, 50, 60]));
assert_eq!(SegoeIconsLoader::new(IconRole::ActionCopy).fg_color, None);
}
#[test]
fn load_icon_unrecognized_set_no_features() {
let _result = SfSymbolsLoader::new(IconRole::ActionCopy).load();
}
#[test]
#[cfg(feature = "material-icons")]
fn bundled_icon_load_produces_cow_borrowed() {
let result = MaterialLoader::new(IconRole::ActionCopy).load();
assert!(
matches!(result, Some(IconData::Svg(Cow::Borrowed(_)))),
"bundled icon should produce Some(IconData::Svg(Cow::Borrowed(_)))"
);
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod load_system_icon_by_name_tests {
use super::*;
#[test]
#[cfg(feature = "material-icons")]
fn system_icon_by_name_material() {
let result = MaterialLoader::new("content_copy").load();
assert!(
result.is_some(),
"content_copy should be found in Material set"
);
assert!(matches!(result.unwrap(), IconData::Svg(_)));
}
#[test]
#[cfg(feature = "lucide-icons")]
fn system_icon_by_name_lucide() {
let result = LucideLoader::new("copy").load();
assert!(result.is_some(), "copy should be found in Lucide set");
assert!(matches!(result.unwrap(), IconData::Svg(_)));
}
#[test]
#[cfg(feature = "material-icons")]
fn system_icon_by_name_unknown_returns_none() {
let result = MaterialLoader::new("nonexistent_xyz").load();
assert!(result.is_none(), "nonexistent name should return None");
}
#[test]
fn system_icon_by_name_sf_on_linux_returns_none() {
#[cfg(not(target_os = "macos"))]
{
let result = SfSymbolsLoader::new("doc.on.doc").load();
assert!(
result.is_none(),
"SF Symbols should return None on non-macOS"
);
}
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod load_custom_icon_tests {
use super::*;
#[test]
#[cfg(feature = "material-icons")]
fn custom_icon_with_icon_role_material() {
let provider: &dyn IconProvider = &IconRole::ActionCopy;
let result = MaterialLoader::new(provider).load();
assert!(
result.is_some(),
"IconRole::ActionCopy should load via material"
);
}
#[test]
#[cfg(feature = "lucide-icons")]
fn custom_icon_with_icon_role_lucide() {
let provider: &dyn IconProvider = &IconRole::ActionCopy;
let result = LucideLoader::new(provider).load();
assert!(
result.is_some(),
"IconRole::ActionCopy should load via lucide"
);
}
#[test]
fn custom_icon_no_cross_set_fallback() {
#[derive(Debug)]
struct NullProvider;
impl IconProvider for NullProvider {
fn icon_name(&self, _set: IconSet) -> Option<&str> {
None
}
fn icon_svg(&self, _set: IconSet) -> Option<Cow<'static, [u8]>> {
None
}
}
let provider: &dyn IconProvider = &NullProvider;
let result = MaterialLoader::new(provider).load();
assert!(
result.is_none(),
"NullProvider should return None (no cross-set fallback)"
);
}
#[test]
fn custom_icon_unknown_set_uses_system() {
#[derive(Debug)]
struct NullProvider;
impl IconProvider for NullProvider {
fn icon_name(&self, _set: IconSet) -> Option<&str> {
None
}
fn icon_svg(&self, _set: IconSet) -> Option<Cow<'static, [u8]>> {
None
}
}
let provider: &dyn IconProvider = &NullProvider;
let _result = FreedesktopLoader::new(provider).load();
}
#[test]
#[cfg(feature = "material-icons")]
fn custom_icon_via_dyn_dispatch() {
let boxed: Box<dyn IconProvider> = Box::new(IconRole::ActionCopy);
let provider: &dyn IconProvider = &*boxed;
let result = MaterialLoader::new(provider).load();
assert!(
result.is_some(),
"dyn dispatch through Box<dyn IconProvider> should work"
);
}
#[test]
#[cfg(feature = "material-icons")]
fn custom_icon_bundled_svg_fallback() {
#[derive(Debug)]
struct SvgOnlyProvider;
impl IconProvider for SvgOnlyProvider {
fn icon_name(&self, _set: IconSet) -> Option<&str> {
None
}
fn icon_svg(&self, _set: IconSet) -> Option<Cow<'static, [u8]>> {
Some(Cow::Borrowed(b"<svg>test</svg>"))
}
}
let provider: &dyn IconProvider = &SvgOnlyProvider;
let result = MaterialLoader::new(provider).load();
assert!(
result.is_some(),
"provider with icon_svg should return Some"
);
match result.unwrap() {
IconData::Svg(ref cow) => {
assert_eq!(cow.as_ref(), b"<svg>test</svg>");
}
_ => panic!("expected IconData::Svg"),
}
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod loading_indicator_tests {
use super::*;
#[test]
#[cfg(feature = "lucide-icons")]
fn loading_indicator_lucide_returns_frames() {
let anim = LucideLoader::load_indicator();
assert!(anim.is_some(), "lucide should return Some");
let anim = anim.unwrap();
assert!(
matches!(anim, AnimatedIcon::Frames(_)),
"lucide should be pre-rotated Frames"
);
if let AnimatedIcon::Frames(data) = &anim {
assert_eq!(data.frames().len(), 24);
assert_eq!(data.frame_duration_ms().get(), 42);
}
}
#[test]
#[cfg(all(target_os = "linux", feature = "system-icons"))]
fn loading_indicator_freedesktop_depends_on_theme() {
let anim = FreedesktopLoader::load_indicator(None);
if let Some(anim) = anim {
match anim {
AnimatedIcon::Frames(data) => {
assert!(
!data.frames().is_empty(),
"Frames variant should have at least one frame"
);
}
AnimatedIcon::Transform(_) => {
}
}
}
}
#[test]
fn loading_indicator_freedesktop_does_not_panic() {
let _result = FreedesktopLoader::load_indicator(None);
}
#[test]
#[cfg(feature = "lucide-icons")]
fn lucide_spinner_is_frames() {
let anim = crate::spinners::lucide_spinner();
assert!(
matches!(anim, AnimatedIcon::Frames(_)),
"lucide should be pre-rotated Frames"
);
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod icon_loader_tests {
use super::*;
#[test]
#[cfg(feature = "material-icons")]
fn icon_loader_basic_role() {
let icon = MaterialLoader::new(IconRole::ActionCopy).load();
assert!(icon.is_some());
}
#[test]
#[cfg(feature = "material-icons")]
fn icon_loader_by_name() {
let icon = MaterialLoader::new("content_copy").load();
assert!(icon.is_some());
}
#[test]
#[cfg(feature = "material-icons")]
fn icon_loader_custom_provider() {
let provider: &dyn IconProvider = &IconRole::ActionCopy;
let icon = MaterialLoader::new(provider).load();
assert!(icon.is_some());
}
#[test]
#[cfg(all(target_os = "linux", feature = "system-icons"))]
fn freedesktop_loader_builder_chain_compiles() {
let _ = FreedesktopLoader::new(IconRole::ActionSave)
.size(48)
.color([0, 0, 0])
.theme("Adwaita")
.load();
}
#[test]
#[cfg(feature = "material-icons")]
fn icon_loader_load_indicator() {
let anim = MaterialLoader::load_indicator();
assert!(anim.is_some());
}
#[test]
fn load_icon_free_fn_dispatches() {
let _ = load_icon(IconRole::ActionCopy, IconSet::SfSymbols);
}
#[test]
fn load_icon_indicator_free_fn_dispatches() {
assert!(load_icon_indicator(IconSet::SfSymbols).is_none());
assert!(load_icon_indicator(IconSet::SegoeIcons).is_none());
}
}
#[cfg(all(test, feature = "svg-rasterize"))]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod spinner_rasterize_tests {
use super::*;
#[test]
#[cfg(feature = "lucide-icons")]
fn lucide_spinner_icon_rasterizes() {
let anim = crate::spinners::lucide_spinner();
if let AnimatedIcon::Frames(data) = &anim {
let first = data.frames().first();
if let IconData::Svg(cow) = first {
let result = crate::rasterize::rasterize_svg(cow, 24);
assert!(result.is_ok(), "lucide loader should rasterize");
if let Ok(IconData::Rgba { data, .. }) = &result {
assert!(
data.iter().any(|&b| b != 0),
"lucide loader rasterized to empty image"
);
}
} else {
panic!("lucide spinner frame should be Svg");
}
} else {
panic!("lucide spinner should be Frames");
}
}
}
#[cfg(test)]
mod icon_set_choice_tests {
use super::*;
#[test]
fn system_choice_names_the_detected_theme() {
assert_eq!(
system_choice_label(&Ok("breeze-dark".to_string())),
"system (breeze-dark)"
);
}
#[test]
fn system_choice_shows_a_failed_detection_as_unavailable() {
let label = system_choice_label(&Err(crate::Error::PlatformUnsupported {
platform: "the test's failing detection",
}));
assert_eq!(
label,
"system (unavailable: platform not supported: the test's failing detection)"
);
}
#[test]
fn test_icon_set_choice_display_default() {
let choice = IconSetChoice::Default("Adwaita".to_string());
assert_eq!(choice.to_string(), "default (Adwaita)");
}
#[test]
fn test_icon_set_choice_display_material() {
assert_eq!(IconSetChoice::Material.to_string(), "Material (bundled)");
}
#[test]
fn test_icon_set_choice_display_lucide() {
assert_eq!(IconSetChoice::Lucide.to_string(), "Lucide (bundled)");
}
#[test]
fn test_icon_set_choice_display_freedesktop() {
let choice = IconSetChoice::Freedesktop("breeze".to_string());
assert_eq!(choice.to_string(), "breeze");
}
#[test]
fn test_icon_set_choice_follows_preset() {
assert!(IconSetChoice::Default("Adwaita".to_string()).follows_preset());
assert!(!IconSetChoice::System.follows_preset());
assert!(!IconSetChoice::Freedesktop("breeze".to_string()).follows_preset());
assert!(!IconSetChoice::Material.follows_preset());
assert!(!IconSetChoice::Lucide.follows_preset());
}
#[test]
fn test_icon_set_choice_effective_icon_set() {
let choice = IconSetChoice::Default("Adwaita".to_string());
assert_eq!(
choice.effective_icon_set(IconSet::Freedesktop),
IconSet::Freedesktop
);
assert_eq!(
choice.effective_icon_set(IconSet::Material),
IconSet::Material
);
let sys = IconSetChoice::System.effective_icon_set(IconSet::Material);
assert_eq!(sys, system_icon_set());
let choice = IconSetChoice::Freedesktop("breeze".to_string());
assert_eq!(
choice.effective_icon_set(IconSet::Material),
IconSet::Freedesktop
);
assert_eq!(
IconSetChoice::Material.effective_icon_set(IconSet::Freedesktop),
IconSet::Material
);
assert_eq!(
IconSetChoice::Lucide.effective_icon_set(IconSet::Freedesktop),
IconSet::Lucide
);
}
#[test]
fn test_icon_set_choice_freedesktop_theme() {
assert_eq!(
IconSetChoice::Default("Adwaita".to_string()).freedesktop_theme(),
Some("Adwaita")
);
assert_eq!(
IconSetChoice::Freedesktop("breeze".to_string()).freedesktop_theme(),
Some("breeze")
);
assert_eq!(IconSetChoice::System.freedesktop_theme(), None);
assert_eq!(IconSetChoice::Material.freedesktop_theme(), None);
assert_eq!(IconSetChoice::Lucide.freedesktop_theme(), None);
}
#[test]
fn test_default_icon_choice_none() {
assert_eq!(
default_icon_choice(IconSet::Freedesktop, None),
IconSetChoice::System
);
assert_eq!(
default_icon_choice(IconSet::Material, None),
IconSetChoice::System
);
}
#[test]
fn test_default_icon_choice_bundled() {
assert_eq!(
default_icon_choice(IconSet::Material, Some("any-theme")),
IconSetChoice::Default("any-theme".to_string())
);
assert_eq!(
default_icon_choice(IconSet::Lucide, Some("any-theme")),
IconSetChoice::Default("any-theme".to_string())
);
}
#[test]
fn test_list_freedesktop_themes_no_panic() {
let themes = list_freedesktop_themes();
#[cfg(not(target_os = "linux"))]
assert!(themes.is_empty());
let _ = themes;
}
}
#[cfg(test)]
#[allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::indexing_slicing,
reason = "a test fails by panicking"
)]
mod colorize_tests {
use super::colorize_monochrome_svg;
use crate::color::Rgba;
const BLUE: Rgba = Rgba::new(51, 102, 204, 255);
const RED: Rgba = Rgba::new(255, 0, 0, 255);
const GREEN: Rgba = Rgba::new(20, 184, 82, 255);
#[test]
fn colorize_svg_replaces_fill_black() {
let svg = b"<svg><path fill=\"black\" d=\"M0 0h24v24H0z\"/></svg>";
let result_str = String::from_utf8(colorize_monochrome_svg(svg, BLUE)).unwrap();
assert!(
!result_str.contains("fill=\"black\""),
"fill=\"black\" should be replaced, got: {result_str}"
);
assert!(
result_str.contains("fill=\"#3366cc\""),
"should contain the hex fill, got: {result_str}"
);
}
#[test]
fn colorize_svg_replaces_fill_hex_black() {
let svg = b"<svg><rect fill=\"#000000\" width=\"24\" height=\"24\"/></svg>";
let result_str = String::from_utf8(colorize_monochrome_svg(svg, RED)).unwrap();
assert!(
!result_str.contains("#000000"),
"fill=\"#000000\" should be replaced, got: {result_str}"
);
}
#[test]
fn colorize_svg_replaces_fill_short_hex_black() {
let svg = b"<svg><rect fill=\"#000\" width=\"24\" height=\"24\"/></svg>";
let result_str = String::from_utf8(colorize_monochrome_svg(svg, GREEN)).unwrap();
assert!(
!result_str.contains("fill=\"#000\""),
"fill=\"#000\" should be replaced, got: {result_str}"
);
}
#[test]
fn colorize_svg_current_color_still_works() {
let svg = b"<svg><path stroke=\"currentColor\" d=\"M0 0\"/></svg>";
let result_str = String::from_utf8(colorize_monochrome_svg(svg, RED)).unwrap();
assert!(
!result_str.contains("currentColor"),
"currentColor should be replaced"
);
assert!(
result_str.contains("#ff0000"),
"should contain the hex colour"
);
}
#[test]
fn colorize_svg_implicit_black_still_works() {
let svg = b"<svg xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M0 0\"/></svg>";
let result_str = String::from_utf8(colorize_monochrome_svg(svg, RED)).unwrap();
assert!(
result_str.contains("fill=\"#ff0000\""),
"should inject fill into root svg tag, got: {result_str}"
);
}
#[test]
fn colorize_svg_non_utf8_returns_original() {
let mut svg = b"<svg><path fill=\"black\" d=\"M0 0\"/>".to_vec();
svg.push(0xFF); svg.extend_from_slice(b"</svg>");
let result = colorize_monochrome_svg(&svg, RED);
assert_eq!(result, svg, "non-UTF-8 input should be returned unchanged");
}
#[test]
fn colorize_svg_replaces_stroke_black() {
let svg = b"<svg><path stroke=\"black\" d=\"M0 0h24\"/></svg>";
let result_str = String::from_utf8(colorize_monochrome_svg(svg, BLUE)).unwrap();
assert!(
!result_str.contains("stroke=\"black\""),
"stroke=\"black\" should be replaced, got: {result_str}"
);
assert!(
result_str.contains("stroke=\"#3366cc\""),
"should contain the hex stroke, got: {result_str}"
);
}
#[test]
fn colorize_svg_replaces_stroke_hex_black() {
let svg = b"<svg><line stroke=\"#000000\" x1=\"0\" y1=\"0\" x2=\"24\" y2=\"24\"/></svg>";
let result_str = String::from_utf8(colorize_monochrome_svg(svg, RED)).unwrap();
assert!(
!result_str.contains("#000000"),
"stroke=\"#000000\" should be replaced"
);
}
#[test]
fn colorize_self_closing_svg_produces_valid_xml() {
let svg = b"<svg xmlns=\"http://www.w3.org/2000/svg\" />";
let result_str = String::from_utf8(colorize_monochrome_svg(svg, RED)).unwrap();
assert!(
result_str.contains("fill=\"#ff0000\""),
"should inject fill, got: {result_str}"
);
assert!(
!result_str.contains("/ fill="),
"fill must be before '/', got: {result_str}"
);
assert!(
result_str.trim().ends_with("/>"),
"should remain self-closing, got: {result_str}"
);
}
#[test]
fn colorize_svg_with_fill_white_root() {
let svg = b"<svg fill=\"white\"><path/></svg>";
let result_str = String::from_utf8(colorize_monochrome_svg(svg, RED)).unwrap();
assert!(
result_str.contains("fill=\"white\""),
"fill=\"white\" should be preserved, got: {result_str}"
);
}
#[test]
fn colorize_svg_with_fill_none_root() {
let svg = b"<svg fill=\"none\"><path stroke=\"black\"/></svg>";
let result_str = String::from_utf8(colorize_monochrome_svg(svg, RED)).unwrap();
assert!(
!result_str.contains("stroke=\"black\""),
"stroke=\"black\" should be replaced, got: {result_str}"
);
assert!(
result_str.contains("stroke=\"#ff0000\""),
"should contain the hex stroke, got: {result_str}"
);
}
#[test]
fn colorize_svg_discards_alpha() {
let svg = b"<svg><path fill=\"black\"/></svg>";
let translucent = Rgba::new(255, 0, 0, 40);
assert_eq!(
colorize_monochrome_svg(svg, translucent),
colorize_monochrome_svg(svg, RED)
);
}
}