use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::ffi::OsStr;
use std::num::NonZeroU32;
use std::sync::{Arc, Mutex, OnceLock};
use crate::IconData;
use crate::icons::{has_theme_index, icon_base_dirs};
use crate::model::animated::{AnimatedIcon, TransformAnimation};
use std::path::{Component, Path, PathBuf};
const FREEDESKTOP_FRAME_DURATION_MS: u32 = 80;
const FREEDESKTOP_SPIN_DURATION_MS: u32 = 1000;
fn inherits(index: &str) -> Vec<&str> {
let mut in_icon_theme = false;
for line in index.lines().map(str::trim) {
if let Some(group) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
in_icon_theme = group == "Icon Theme";
continue;
}
if in_icon_theme
&& let Some((key, value)) = line.split_once('=')
&& key.trim() == "Inherits"
{
return value
.split(',')
.map(str::trim)
.filter(|parent| !parent.is_empty())
.collect();
}
}
Vec::new()
}
fn declared_parents(theme: &str, bases: &[PathBuf]) -> Vec<String> {
let mut parents: Vec<String> = Vec::new();
for base in bases {
let Ok(index) = std::fs::read_to_string(base.join(theme).join("index.theme")) else {
continue;
};
for parent in inherits(&index) {
if !parents.iter().any(|known| known == parent) {
parents.push(parent.to_string());
}
}
}
parents
}
fn theme_chain(theme: &str, bases: &[PathBuf]) -> Option<Vec<String>> {
if !has_theme_index(theme, bases) {
return None;
}
let mut chain: Vec<String> = Vec::new();
let mut pending = vec![theme.to_string()];
while let Some(name) = pending.pop() {
if chain.contains(&name) {
continue;
}
let parents = declared_parents(&name, bases);
chain.push(name);
pending.extend(
parents
.into_iter()
.rev()
.filter(|parent| parent != "hicolor" && has_theme_index(parent, bases)),
);
}
Some(chain)
}
fn cached_theme_chain(theme: &str) -> Option<Vec<String>> {
type Chains = Mutex<HashMap<String, Option<Vec<String>>>>;
static CHAINS: OnceLock<Chains> = OnceLock::new();
let chains = CHAINS.get_or_init(Chains::default);
if let Ok(known) = chains.lock()
&& let Some(chain) = known.get(theme)
{
return chain.clone();
}
let chain = theme_chain(theme, icon_base_dirs());
if let Ok(mut known) = chains.lock() {
known.insert(theme.to_string(), chain.clone());
}
chain
}
fn is_in_theme_dir(path: &Path, theme: &str, bases: &[PathBuf]) -> bool {
if path
.components()
.any(|component| component == Component::ParentDir)
{
return false;
}
bases.iter().any(|base| {
let Ok(rest) = path.strip_prefix(base) else {
return false;
};
let mut rest = rest.components();
let in_theme = matches!(
rest.next(),
Some(Component::Normal(dir)) if dir == OsStr::new(theme)
);
in_theme && rest.next().is_some()
})
}
fn first_in_chain(
chain: &[String],
bases: &[PathBuf],
mut lookup: impl FnMut(&str) -> Option<PathBuf>,
) -> Option<PathBuf> {
chain
.iter()
.find_map(|theme| lookup(theme).filter(|path| is_in_theme_dir(path, theme, bases)))
}
const ICON_FILE_ENDINGS: [&str; 4] = [".svg", ".png", ".xmp", ".xpm"];
fn theme_icon_stems(theme: &str, bases: &[PathBuf]) -> HashSet<String> {
let mut stems = HashSet::new();
let mut visited: HashSet<PathBuf> = HashSet::new();
let mut pending: Vec<PathBuf> = bases.iter().map(|base| base.join(theme)).collect();
while let Some(dir) = pending.pop() {
let Ok(canonical) = std::fs::canonicalize(&dir) else {
continue;
};
if !visited.insert(canonical) {
continue;
}
let Ok(entries) = std::fs::read_dir(&dir) else {
continue;
};
for entry in entries.flatten() {
let path = entry.path();
let is_dir = match entry.file_type() {
Ok(kind) if kind.is_symlink() => path.is_dir(),
Ok(kind) => kind.is_dir(),
Err(_) => path.is_dir(),
};
if is_dir {
pending.push(path);
} else if let Some(stem) = entry.file_name().to_str().and_then(|file| {
ICON_FILE_ENDINGS
.iter()
.find_map(|ending| file.strip_suffix(ending))
}) {
stems.insert(stem.to_string());
}
}
}
stems
}
fn cached_theme_icon_stems(theme: &str) -> Arc<HashSet<String>> {
type Stems = Mutex<HashMap<String, Arc<HashSet<String>>>>;
static STEMS: OnceLock<Stems> = OnceLock::new();
let known_stems = STEMS.get_or_init(Stems::default);
if let Ok(known) = known_stems.lock()
&& let Some(stems) = known.get(theme)
{
return Arc::clone(stems);
}
let stems = Arc::new(theme_icon_stems(theme, icon_base_dirs()));
if let Ok(mut known) = known_stems.lock() {
known.insert(theme.to_string(), Arc::clone(&stems));
}
stems
}
fn themes_that_may_have(
name: &str,
chain: &[String],
mut stems: impl FnMut(&str) -> Arc<HashSet<String>>,
) -> Vec<String> {
if name.contains('/') {
return chain.to_vec();
}
chain
.iter()
.filter(|theme| stems(theme).contains(name))
.cloned()
.collect()
}
fn lookup_in_chain(name: &str, size: u16, chain: &[String]) -> Option<PathBuf> {
let themes = themes_that_may_have(name, chain, cached_theme_icon_stems);
first_in_chain(&themes, icon_base_dirs(), |theme| {
freedesktop_icons::lookup(name)
.with_theme(theme)
.with_size(size)
.force_svg()
.find()
})
}
fn find_icon(name: &str, theme: &str, size: u16) -> Option<(PathBuf, bool)> {
find_icon_with(name, theme, size, lookup_in_chain)
}
fn find_icon_with(
name: &str,
theme: &str,
size: u16,
lookup_in_chain: impl Fn(&str, u16, &[String]) -> Option<PathBuf>,
) -> Option<(PathBuf, bool)> {
let chain = cached_theme_chain(theme)?;
let symbolic = format!("{name}-symbolic");
if let Some(path) = lookup_in_chain(&symbolic, size, &chain) {
return Some((path, true));
}
lookup_in_chain(name, size, &chain).map(|path| (path, name.ends_with("-symbolic")))
}
#[must_use]
pub(crate) fn load_freedesktop_icon_by_name(
name: &str,
theme: &str,
size: u16,
fg_color: Option<[u8; 3]>,
) -> Option<IconData> {
let (path, is_symbolic) = find_icon(name, theme, size)?;
load_icon_file(&path, is_symbolic, fg_color)
}
fn load_icon_file(path: &Path, is_symbolic: bool, fg_color: Option<[u8; 3]>) -> Option<IconData> {
let ext = path
.extension()
.and_then(|e| e.to_str())
.map(str::to_ascii_lowercase);
match ext.as_deref() {
Some("svg") => {
let bytes = std::fs::read(path).ok()?;
let bytes = if is_symbolic {
let replacement = fg_to_replacement(fg_color);
normalize_gtk_symbolic(bytes, &replacement)
} else {
bytes
};
Some(IconData::Svg(Cow::Owned(bytes)))
}
Some("png") => {
let bytes = std::fs::read(path).ok()?;
decode_png_to_rgba(&bytes)
}
_ => None,
}
}
fn decode_png_to_rgba(bytes: &[u8]) -> Option<IconData> {
let mut decoder = png::Decoder::new(std::io::Cursor::new(bytes));
decoder.set_transformations(
png::Transformations::EXPAND | png::Transformations::STRIP_16 | png::Transformations::ALPHA,
);
let mut reader = decoder.read_info().ok()?;
let mut buf = vec![0u8; reader.output_buffer_size()?];
let info = reader.next_frame(&mut buf).ok()?;
buf.truncate(info.buffer_size());
let (width, height) = (info.width, info.height);
let pixel_count = (width as usize).checked_mul(height as usize)?;
let rgba_len = pixel_count.checked_mul(4)?;
let rgba = match info.color_type {
png::ColorType::Rgba => buf,
png::ColorType::Rgb => expand_to_rgba(&buf, 3, |p, out| {
if let [r, g, b] = p {
out.extend_from_slice(&[*r, *g, *b, 0xff]);
}
})?,
png::ColorType::GrayscaleAlpha => expand_to_rgba(&buf, 2, |p, out| {
if let [gray, alpha] = p {
out.extend_from_slice(&[*gray, *gray, *gray, *alpha]);
}
})?,
png::ColorType::Grayscale => expand_to_rgba(&buf, 1, |p, out| {
if let [gray] = p {
out.extend_from_slice(&[*gray, *gray, *gray, 0xff]);
}
})?,
png::ColorType::Indexed => return None,
};
if rgba.len() != rgba_len {
return None;
}
Some(IconData::Rgba {
width,
height,
data: rgba,
})
}
fn expand_to_rgba<F>(buf: &[u8], sample_stride: usize, mut write: F) -> Option<Vec<u8>>
where
F: FnMut(&[u8], &mut Vec<u8>),
{
if sample_stride == 0 || !buf.len().is_multiple_of(sample_stride) {
return None;
}
let pixel_count = buf.len().checked_div(sample_stride)?;
let mut out = Vec::with_capacity(pixel_count.saturating_mul(4));
for chunk in buf.chunks_exact(sample_stride) {
write(chunk, &mut out);
}
Some(out)
}
fn fg_to_replacement(fg_color: Option<[u8; 3]>) -> String {
match fg_color {
Some([r, g, b]) => format!("#{r:02x}{g:02x}{b:02x}"),
None => "currentColor".to_string(),
}
}
fn parse_sprite_sheet(svg_bytes: &[u8]) -> Option<Vec<Vec<u8>>> {
let svg_str = std::str::from_utf8(svg_bytes).ok()?;
let (vb_attr_start, vb_val_start, quote) = svg_str
.find("viewBox=\"")
.map(|i| (i, i.saturating_add(9), '"'))
.or_else(|| {
svg_str
.find("viewBox='")
.map(|i| (i, i.saturating_add(9), '\''))
})?;
let tail = svg_str.get(vb_val_start..)?;
let vb_val_end = tail.find(quote)?.saturating_add(vb_val_start);
let vb_value = svg_str.get(vb_val_start..vb_val_end)?;
let parts: Vec<f64> = vb_value
.split(|c: char| c.is_whitespace() || c == ',')
.filter(|s| !s.is_empty())
.filter_map(|s| s.parse().ok())
.collect();
let [_, _, width, height] = parts.as_slice() else {
return None;
};
let (width, height) = (*width, *height);
if height <= width {
return None; }
let frame_count = (height / width).round() as usize;
if frame_count < 2 {
return None;
}
if (height - width * frame_count as f64).abs() > 0.01 {
return None;
}
let original_vb_attr = svg_str.get(vb_attr_start..vb_val_end.saturating_add(1))?;
let frames = (0..frame_count)
.map(|i| {
let y_offset = width * i as f64;
let new_vb = format!("viewBox={quote}0 {y_offset} {width} {width}{quote}");
svg_str.replacen(original_vb_attr, &new_vb, 1).into_bytes()
})
.collect();
Some(frames)
}
pub(crate) fn load_freedesktop_spinner(theme: Option<&str>) -> Option<AnimatedIcon> {
load_freedesktop_spinner_with(theme, crate::system_icon_theme)
}
fn load_freedesktop_spinner_with(
theme: Option<&str>,
detect: impl FnOnce() -> crate::Result<String>,
) -> Option<AnimatedIcon> {
let detected;
let theme: &str = match theme {
Some(t) => t,
None => {
detected = detect().ok()?;
&detected
}
};
let chain = cached_theme_chain(theme)?;
if let Some(path) = lookup_in_chain("process-working", 22, &chain) {
let bytes = std::fs::read(&path).ok()?;
let frame_dur = NonZeroU32::new(FREEDESKTOP_FRAME_DURATION_MS)?;
let spin_dur = NonZeroU32::new(FREEDESKTOP_SPIN_DURATION_MS)?;
if let Some(frames) = parse_sprite_sheet(&bytes) {
let frame_icons: Vec<IconData> = frames
.into_iter()
.map(|b| IconData::Svg(Cow::Owned(b)))
.collect();
return AnimatedIcon::frames(frame_icons, frame_dur).ok();
}
return Some(AnimatedIcon::transform(
IconData::Svg(Cow::Owned(bytes)),
TransformAnimation::Spin {
duration_ms: spin_dur,
},
));
}
if let Some(path) = lookup_in_chain("process-working-symbolic", 22, &chain) {
let bytes = std::fs::read(&path).ok()?;
let spin_dur = NonZeroU32::new(FREEDESKTOP_SPIN_DURATION_MS)?;
return Some(AnimatedIcon::transform(
IconData::Svg(Cow::Owned(bytes)),
TransformAnimation::Spin {
duration_ms: spin_dur,
},
));
}
None
}
const GTK_FG_COLORS: &[&str] = &["#2e3436", "#2e3434", "#222222", "#474747"];
fn normalize_gtk_symbolic(svg_bytes: Vec<u8>, replacement: &str) -> Vec<u8> {
let Ok(svg_str) = std::str::from_utf8(&svg_bytes) else {
return svg_bytes;
};
if svg_str.contains("currentColor") {
return svg_bytes;
}
if !GTK_FG_COLORS.iter().any(|c| svg_str.contains(c)) {
return svg_bytes;
}
let mut result = svg_str.to_string();
for color in GTK_FG_COLORS {
result = result.replace(
&format!("fill=\"{color}\""),
&format!("fill=\"{replacement}\""),
);
result = result.replace(
&format!("stroke=\"{color}\""),
&format!("stroke=\"{replacement}\""),
);
result = result.replace(&format!("fill:{color}"), &format!("fill:{replacement}"));
result = result.replace(&format!("stroke:{color}"), &format!("stroke:{replacement}"));
}
result.into_bytes()
}
#[cfg(test)]
#[cfg(feature = "system-icons")]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
use super::*;
use crate::{IconRole, IconSet, icon_name};
#[test]
#[ignore = "requires a freedesktop icon theme installed (not available on CI)"]
fn load_icon_returns_some_for_dialog_error() {
let theme = crate::system_icon_theme().expect("requires a detected icon theme");
let name = icon_name(IconRole::DialogError, IconSet::Freedesktop).unwrap();
let result = load_freedesktop_icon_by_name(name, &theme, 24, None);
assert!(result.is_some(), "DialogError should resolve to an icon");
match result.unwrap() {
IconData::Svg(ref cow) => {
let s = String::from_utf8_lossy(cow);
assert!(s.contains("<svg"), "Icon data should contain <svg tag");
}
other => panic!("Expected SVG data, got {other:?}"),
}
}
#[test]
fn load_icon_notification_attempts_native_lookup() {
if let Ok(theme) = crate::system_icon_theme()
&& let Some(name) = icon_name(IconRole::Notification, IconSet::Freedesktop)
{
let _result = load_freedesktop_icon_by_name(name, &theme, 24, None);
}
}
#[test]
#[ignore = "requires a freedesktop icon theme installed (not available on CI)"]
fn load_icon_returns_svg_variant() {
let theme = crate::system_icon_theme().expect("requires a detected icon theme");
let name = icon_name(IconRole::ActionCopy, IconSet::Freedesktop).unwrap();
let result = load_freedesktop_icon_by_name(name, &theme, 24, None);
assert!(result.is_some(), "ActionCopy should resolve to an icon");
assert!(
matches!(result.unwrap(), IconData::Svg(_)),
"Expected Svg variant"
);
}
#[test]
fn spinner_without_a_detected_theme_is_none() {
let spinner = load_freedesktop_spinner_with(None, || {
Err(crate::Error::PlatformUnsupported {
platform: "the test's failing detection",
})
});
assert!(
spinner.is_none(),
"a spinner loaded though no icon theme was detected"
);
}
#[test]
fn find_icon_nonexistent_returns_none() {
let result = find_icon("totally-nonexistent-icon-xyz", "hicolor", 24);
assert!(result.is_none(), "Nonexistent icon should return None");
}
#[test]
#[ignore = "requires a freedesktop icon theme installed (not available on CI)"]
fn load_icon_by_name_finds_edit_copy() {
let theme = crate::system_icon_theme().expect("requires a detected icon theme");
let result = load_freedesktop_icon_by_name("edit-copy", &theme, 24, None);
assert!(
result.is_some(),
"edit-copy should be found in system theme"
);
assert!(matches!(result.unwrap(), IconData::Svg(_)));
}
struct Fixture {
root: PathBuf,
bases: Vec<PathBuf>,
}
impl Fixture {
fn new(tag: &str) -> Self {
let root = std::env::temp_dir().join(format!(
"native-theme-icon-dirs-{}-{tag}",
std::process::id()
));
let _ = std::fs::remove_dir_all(&root);
let icons = root.join("share/icons");
let home_icons = root.join("home/.icons");
let theme = |base: &Path, name: &str, inherits: Option<&str>| {
let dir = base.join(name);
std::fs::create_dir_all(dir.join("actions")).unwrap();
let inherits = inherits.map_or(String::new(), |i| format!("Inherits={i}\n"));
std::fs::write(
dir.join("index.theme"),
format!("[Icon Theme]\nName={name}\n{inherits}Directories=actions\n"),
)
.unwrap();
};
theme(&icons, "child", Some("parent,hicolor"));
theme(&icons, "parent", Some("grand"));
theme(&icons, "grand", None);
theme(&icons, "fork", Some("left,right"));
theme(&icons, "left", Some("deep"));
theme(&icons, "right", None);
theme(&icons, "deep", None);
theme(&icons, "hicolor", None);
theme(&icons, "breeze", None);
theme(&icons, "breeze-dark", None);
theme(&icons, "cycle-a", Some("cycle-b"));
theme(&icons, "cycle-b", Some("cycle-a"));
std::fs::create_dir_all(home_icons.join("child/actions")).unwrap();
std::fs::write(icons.join("loose.svg"), "<svg/>").unwrap();
std::fs::create_dir_all(root.join("share/pixmaps")).unwrap();
std::fs::write(root.join("share/pixmaps/pixmap.svg"), "<svg/>").unwrap();
Self {
bases: vec![icons, home_icons],
root,
}
}
fn icons(&self, rest: &str) -> PathBuf {
self.root.join("share/icons").join(rest)
}
fn accepts(&self, theme: &str, path: &Path) -> bool {
theme_chain(theme, &self.bases).is_some_and(|names| {
names
.iter()
.any(|name| is_in_theme_dir(path, name, &self.bases))
})
}
fn add_icon(&self, theme: &str, name: &str) -> PathBuf {
let path = self.icons(&format!("{theme}/actions/{name}.svg"));
std::fs::write(&path, "<svg/>").unwrap();
path
}
fn freedesktop_icons_lookup(&self, name: &str, theme: &str) -> Option<PathBuf> {
let mut searched = vec![theme.to_string()];
searched.extend(declared_parents(theme, &self.bases));
searched.push("hicolor".to_string());
searched
.iter()
.flat_map(|t| {
self.bases
.iter()
.map(move |base| base.join(t).join("actions").join(format!("{name}.svg")))
})
.find(|path| path.exists())
}
fn find(&self, name: &str, theme: &str) -> Option<PathBuf> {
let chain = theme_chain(theme, &self.bases)?;
first_in_chain(&chain, &self.bases, |t| {
self.freedesktop_icons_lookup(name, t)
})
}
}
impl Drop for Fixture {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.root);
}
}
#[test]
fn theme_dirs_accept_the_theme_itself() {
let fx = Fixture::new("own");
assert!(fx.accepts("child", &fx.icons("child/actions/edit-copy.svg")));
assert!(fx.accepts(
"child",
&fx.root.join("home/.icons/child/actions/edit-copy.svg")
));
}
#[test]
fn theme_dirs_accept_a_declared_parent() {
let fx = Fixture::new("parent");
assert!(fx.accepts("child", &fx.icons("parent/actions/edit-copy.svg")));
}
#[test]
fn theme_dirs_reject_hicolor_even_when_declared() {
let fx = Fixture::new("hicolor");
assert!(!fx.accepts("child", &fx.icons("hicolor/actions/edit-copy.svg")));
assert!(!fx.accepts("parent", &fx.icons("hicolor/actions/edit-copy.svg")));
}
#[test]
fn theme_dirs_accept_hicolor_when_it_is_the_theme() {
let fx = Fixture::new("hicolor-chosen");
assert!(fx.accepts("hicolor", &fx.icons("hicolor/actions/edit-copy.svg")));
}
#[test]
fn theme_dirs_reject_loose_and_pixmaps_files() {
let fx = Fixture::new("loose");
assert!(!fx.accepts("child", &fx.icons("loose.svg")));
assert!(!fx.accepts("child", &fx.root.join("home/.icons/loose.svg")));
assert!(!fx.accepts("child", &fx.root.join("share/pixmaps/pixmap.svg")));
assert!(!fx.accepts(
"child",
&fx.root.join("share/pixmaps/child/actions/edit-copy.svg")
));
}
#[test]
fn theme_dirs_match_whole_components() {
let fx = Fixture::new("components");
assert!(!fx.accepts("breeze", &fx.icons("breeze-dark/actions/edit-copy.svg")));
assert!(!fx.accepts("breeze-dark", &fx.icons("breeze/actions/edit-copy.svg")));
assert!(fx.accepts("breeze", &fx.icons("breeze/actions/edit-copy.svg")));
}
#[test]
fn theme_dirs_reject_a_path_climbing_out_of_the_theme() {
let fx = Fixture::new("climb");
assert!(!fx.accepts("child", &fx.icons("child/../hicolor/actions/edit-copy.svg")));
}
#[test]
fn theme_chain_is_depth_first_in_declared_order() {
let fx = Fixture::new("order");
assert_eq!(
theme_chain("child", &fx.bases).unwrap(),
["child", "parent", "grand"]
);
assert_eq!(
theme_chain("fork", &fx.bases).unwrap(),
["fork", "left", "deep", "right"]
);
}
#[test]
fn chain_lookup_reaches_a_grandparent() {
let fx = Fixture::new("grand");
let grand = fx.add_icon("grand", "grand-only");
fx.add_icon("hicolor", "grand-only");
assert_eq!(fx.find("grand-only", "child"), Some(grand));
}
#[test]
fn chain_lookup_takes_a_theme_s_own_file_only() {
let fx = Fixture::new("own-file");
fx.add_icon("parent", "parent-only");
fx.add_icon("hicolor", "hicolor-only");
let child_only = ["child".to_string()];
let lookup = |t: &str| fx.freedesktop_icons_lookup("parent-only", t);
assert_eq!(first_in_chain(&child_only, &fx.bases, lookup), None);
let lookup = |t: &str| fx.freedesktop_icons_lookup("hicolor-only", t);
assert_eq!(first_in_chain(&child_only, &fx.bases, lookup), None);
assert_eq!(fx.find("hicolor-only", "child"), None);
}
#[test]
fn chain_lookup_takes_the_nearer_theme() {
let fx = Fixture::new("nearer");
let parent = fx.add_icon("parent", "both");
fx.add_icon("grand", "both");
assert_eq!(fx.find("both", "child"), Some(parent));
let deep = fx.add_icon("deep", "split");
fx.add_icon("right", "split");
assert_eq!(fx.find("split", "fork"), Some(deep));
}
fn find_indexed(
fx: &Fixture,
name: &str,
theme: &str,
asked: &mut Vec<String>,
) -> Option<PathBuf> {
let chain = theme_chain(theme, &fx.bases)?;
let candidates =
themes_that_may_have(name, &chain, |t| Arc::new(theme_icon_stems(t, &fx.bases)));
first_in_chain(&candidates, &fx.bases, |t| {
asked.push(t.to_string());
fx.freedesktop_icons_lookup(name, t)
})
}
#[test]
fn chain_lookup_never_asks_a_theme_without_the_name() {
let fx = Fixture::new("indexed-miss");
let mut asked = Vec::new();
assert_eq!(find_indexed(&fx, "nowhere", "child", &mut asked), None);
assert!(asked.is_empty(), "asked {asked:?}");
fx.add_icon("hicolor", "hicolor-only");
assert_eq!(find_indexed(&fx, "hicolor-only", "child", &mut asked), None);
assert!(asked.is_empty(), "asked {asked:?}");
}
#[test]
fn chain_lookup_asks_only_the_themes_with_the_name() {
let fx = Fixture::new("indexed-hit");
let grand = fx.add_icon("grand", "grand-only");
let mut asked = Vec::new();
assert_eq!(
find_indexed(&fx, "grand-only", "child", &mut asked),
Some(grand)
);
assert_eq!(asked, ["grand"]);
let parent = fx.add_icon("parent", "both");
fx.add_icon("grand", "both");
let mut asked = Vec::new();
let found = find_indexed(&fx, "both", "child", &mut asked);
assert_eq!(found, Some(parent));
assert_eq!(found, fx.find("both", "child"));
assert_eq!(asked, ["parent"]);
}
#[test]
fn chain_lookup_asks_every_theme_for_a_name_with_a_separator() {
let fx = Fixture::new("indexed-separator");
let mut asked = Vec::new();
assert_eq!(find_indexed(&fx, "actions/x", "child", &mut asked), None);
assert_eq!(asked, ["child", "parent", "grand"]);
}
#[cfg(unix)]
#[test]
fn theme_icon_stems_walk_nested_and_linked_dirs() {
use std::os::unix::fs::symlink;
let fx = Fixture::new("stems");
let child = fx.icons("child");
fx.add_icon("child", "flat");
std::fs::create_dir_all(child.join("16x16/apps/deeper")).unwrap();
std::fs::write(child.join("16x16/apps/deeper/nested.png"), "").unwrap();
std::fs::write(child.join("actions/pixmap.xpm"), "").unwrap();
std::fs::write(child.join("actions/upstream.xmp"), "").unwrap();
std::fs::write(child.join("actions/notes.txt"), "").unwrap();
std::fs::write(child.join("actions/backup.svg.bak"), "").unwrap();
std::fs::write(child.join("icon-theme.cache"), "").unwrap();
let elsewhere = fx.root.join("elsewhere");
std::fs::create_dir_all(elsewhere.join("linked")).unwrap();
std::fs::write(elsewhere.join("linked/via-dir.svg"), "").unwrap();
std::fs::write(elsewhere.join("target.svg"), "").unwrap();
symlink(elsewhere.join("linked"), child.join("linked")).unwrap();
symlink(
elsewhere.join("target.svg"),
child.join("actions/via-file.svg"),
)
.unwrap();
symlink(&child, child.join("actions/loop")).unwrap();
symlink("..", child.join("16x16/up")).unwrap();
symlink(child.join("missing"), child.join("dangling")).unwrap();
std::fs::write(fx.root.join("home/.icons/child/actions/home.svg"), "").unwrap();
let mut stems: Vec<String> = theme_icon_stems("child", &fx.bases).into_iter().collect();
stems.sort();
assert_eq!(
stems,
[
"flat", "home", "nested", "pixmap", "upstream", "via-dir", "via-file"
]
);
assert!(theme_icon_stems("no-such-theme", &fx.bases).is_empty());
}
#[test]
fn theme_chain_terminates_on_a_cycle() {
let fx = Fixture::new("cycle");
let mut names = theme_chain("cycle-a", &fx.bases).unwrap();
names.sort();
assert_eq!(names, ["cycle-a", "cycle-b"]);
}
#[test]
fn theme_chain_of_a_missing_theme_is_none() {
let fx = Fixture::new("missing");
assert_eq!(theme_chain("no-such-theme", &fx.bases), None);
assert_eq!(theme_chain("../share/icons/child", &fx.bases), None);
}
#[test]
fn find_icon_rejects_a_loose_base_dir_file() {
let loose = Path::new("/usr/share/icons/cachyos.svg");
if !loose.exists() || !Path::new("/usr/share/icons/breeze/index.theme").exists() {
eprintln!("skipped: needs {} and the breeze theme", loose.display());
return;
}
assert_eq!(find_icon("cachyos", "breeze", 24), None);
}
#[test]
fn find_icon_never_returns_hicolor_for_another_theme() {
let apps = Path::new("/usr/share/icons/hicolor/scalable/apps");
let (Ok(entries), true) = (
std::fs::read_dir(apps),
Path::new("/usr/share/icons/breeze/index.theme").exists(),
) else {
eprintln!("skipped: needs {} and the breeze theme", apps.display());
return;
};
let hicolor = Path::new("/usr/share/icons/hicolor");
let names: Vec<String> = entries
.filter_map(Result::ok)
.filter_map(|e| {
let path = e.path();
(path.extension()? == "svg").then_some(())?;
Some(path.file_stem()?.to_str()?.to_string())
})
.take(20)
.collect();
for name in &names {
if let Some((path, _)) = find_icon(name, "breeze", 24) {
assert!(
!path.starts_with(hicolor),
"{name} for breeze came from hicolor: {}",
path.display()
);
}
}
}
#[test]
fn find_icon_reaches_a_grandparent_theme() {
let icons = Path::new("/usr/share/icons");
let default_index = std::fs::read_to_string(icons.join("default/index.theme"));
let inherits_adwaita = default_index
.as_deref()
.is_ok_and(|index| inherits(index).contains(&"Adwaita"));
let legacy = icons.join("AdwaitaLegacy");
if !inherits_adwaita || !legacy.join("index.theme").exists() {
eprintln!("skipped: needs `default` inheriting Adwaita, and AdwaitaLegacy");
return;
}
fn stems(dir: &Path, out: &mut std::collections::BTreeSet<String>) {
for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() {
let path = entry.path();
if path.is_dir() {
stems(&path, out);
} else if let (Some(stem), Some("png" | "svg")) = (
path.file_stem().and_then(|s| s.to_str()),
path.extension().and_then(|e| e.to_str()),
) {
out.insert(stem.to_string());
}
}
}
let mut legacy_names = std::collections::BTreeSet::new();
stems(&legacy, &mut legacy_names);
let mut adwaita_names = std::collections::BTreeSet::new();
stems(&icons.join("Adwaita"), &mut adwaita_names);
stems(&icons.join("default"), &mut adwaita_names);
let legacy_only: Vec<&String> = legacy_names
.iter()
.filter(|name| {
!name.ends_with("-symbolic")
&& !adwaita_names.contains(name.as_str())
&& !adwaita_names.contains(&format!("{name}-symbolic"))
})
.take(20)
.collect();
assert!(!legacy_only.is_empty(), "no AdwaitaLegacy-only icon found");
for name in legacy_only {
let found = find_icon(name, "default", 24);
assert!(
found
.as_ref()
.is_some_and(|(path, _)| path.starts_with(&legacy)),
"{name} for default: {found:?}"
);
}
}
#[test]
fn find_icon_still_finds_breeze_edit_copy() {
if !Path::new("/usr/share/icons/breeze/index.theme").exists() {
eprintln!("skipped: the breeze theme is not installed");
return;
}
let (path, _) = find_icon("edit-copy", "breeze", 24).expect("breeze has edit-copy");
assert!(
path.starts_with("/usr/share/icons/breeze"),
"{}",
path.display()
);
}
fn lookup_in_chain_unfiltered(name: &str, size: u16, chain: &[String]) -> Option<PathBuf> {
first_in_chain(chain, icon_base_dirs(), |theme| {
freedesktop_icons::lookup(name)
.with_theme(theme)
.with_size(size)
.force_svg()
.find()
})
}
#[cfg(target_os = "linux")]
#[test]
#[ignore = "slow (~30-50 s): compares the indexed lookup with freedesktop-icons' unfiltered one on the installed icon themes; run with --ignored"]
fn indexed_lookup_matches_the_unfiltered_lookup_on_installed_themes() {
const SIZES: [u16; 4] = [16, 22, 24, 32];
let mut checked = 0;
for theme in ["breeze", "breeze-dark", "Adwaita"] {
if !has_theme_index(theme, icon_base_dirs()) {
eprintln!("skipped {theme}: not installed");
continue;
}
let mut names: std::collections::BTreeSet<String> = IconRole::ALL
.iter()
.filter_map(|role| icon_name(*role, IconSet::Freedesktop))
.chain(["process-working", "process-working-symbolic"])
.map(str::to_string)
.collect();
let mut own: Vec<String> = theme_icon_stems(theme, icon_base_dirs())
.into_iter()
.collect();
own.sort();
let step = own.len().div_ceil(300).max(1);
names.extend(own.into_iter().step_by(step));
names.extend((0..20).map(|i| format!("nt-test-missing-{i}")));
let symbolic: Vec<String> = names.iter().map(|n| format!("{n}-symbolic")).collect();
names.extend(symbolic);
let names: Vec<String> = names.into_iter().collect();
let mismatches: Vec<String> = std::thread::scope(|scope| {
let workers: Vec<_> = SIZES
.iter()
.map(|&size| {
let names = &names;
scope.spawn(move || {
names
.iter()
.filter_map(|name| {
let new = find_icon(name, theme, size);
let old = find_icon_with(
name,
theme,
size,
lookup_in_chain_unfiltered,
);
(new != old).then(|| {
format!("{theme} {name}@{size}: {new:?} != {old:?}")
})
})
.collect::<Vec<_>>()
})
})
.collect();
workers
.into_iter()
.flat_map(|worker| worker.join().unwrap())
.collect()
});
assert!(mismatches.is_empty(), "{mismatches:#?}");
eprintln!(
"{theme}: {} names x {} sizes compared",
names.len(),
SIZES.len()
);
checked += 1;
}
if checked == 0 {
eprintln!("skipped: none of breeze, breeze-dark, Adwaita is installed");
}
}
#[test]
fn load_icon_by_name_returns_none_for_nonexistent() {
let result = load_freedesktop_icon_by_name("zzz-nonexistent-icon", "hicolor", 24, None);
assert!(result.is_none());
}
#[test]
fn test_parse_sprite_sheet_two_frames() {
let svg = br#"<svg viewBox="0 0 10 20" xmlns="http://www.w3.org/2000/svg">
<rect x="0" y="0" width="10" height="10" fill="red"/>
<rect x="0" y="10" width="10" height="10" fill="blue"/>
</svg>"#;
let frames = parse_sprite_sheet(svg).expect("should parse 2-frame sprite sheet");
assert_eq!(frames.len(), 2);
let frame0 = std::str::from_utf8(&frames[0]).unwrap();
assert!(
frame0.contains(r#"viewBox="0 0 10 10""#),
"frame 0 viewBox: {frame0}"
);
let frame1 = std::str::from_utf8(&frames[1]).unwrap();
assert!(
frame1.contains(r#"viewBox="0 10 10 10""#),
"frame 1 viewBox: {frame1}"
);
}
#[test]
fn test_parse_sprite_sheet_fifteen_frames() {
let svg = br#"<svg viewBox="0 0 22 330" xmlns="http://www.w3.org/2000/svg">
<path d="M0 0"/>
</svg>"#;
let frames = parse_sprite_sheet(svg).expect("should parse 15-frame sprite sheet");
assert_eq!(frames.len(), 15);
let first = std::str::from_utf8(&frames[0]).unwrap();
assert!(first.contains(r#"viewBox="0 0 22 22""#));
let last = std::str::from_utf8(&frames[14]).unwrap();
assert!(last.contains(r#"viewBox="0 308 22 22""#));
}
#[test]
fn test_parse_sprite_sheet_single_frame_returns_none() {
let svg = br#"<svg viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg">
<circle cx="11" cy="11" r="10"/>
</svg>"#;
assert!(parse_sprite_sheet(svg).is_none());
}
#[test]
fn test_parse_sprite_sheet_non_multiple_returns_none() {
let svg = br#"<svg viewBox="0 0 22 33" xmlns="http://www.w3.org/2000/svg">
<path d="M0 0"/>
</svg>"#;
assert!(parse_sprite_sheet(svg).is_none());
}
#[test]
fn test_parse_sprite_sheet_invalid_svg_returns_none() {
assert!(parse_sprite_sheet(b"not svg at all").is_none());
}
#[test]
fn test_parse_sprite_sheet_comma_separated_viewbox() {
let svg = br#"<svg viewBox="0,0,10,20" xmlns="http://www.w3.org/2000/svg">
<rect x="0" y="0" width="10" height="10" fill="red"/>
</svg>"#;
let frames = parse_sprite_sheet(svg).expect("should parse comma-separated viewBox");
assert_eq!(frames.len(), 2);
let frame0 = std::str::from_utf8(&frames[0]).unwrap();
assert!(frame0.contains(r#"viewBox="0 0 10 10""#));
}
#[test]
fn test_parse_sprite_sheet_preserves_svg_content() {
let svg = br#"<svg viewBox="0 0 10 20" xmlns="http://www.w3.org/2000/svg">
<rect x="0" y="0" width="10" height="10" fill="red" id="unique-marker"/>
<rect x="0" y="10" width="10" height="10" fill="blue"/>
</svg>"#;
let frames = parse_sprite_sheet(svg).unwrap();
for frame in &frames {
let s = std::str::from_utf8(frame).unwrap();
assert!(
s.contains("unique-marker"),
"SVG content should be preserved in all frames"
);
assert!(s.contains("<rect"), "rect elements should be preserved");
assert!(s.contains("xmlns="), "namespace should be preserved");
}
}
#[test]
fn test_load_freedesktop_spinner_no_panic() {
let _result = load_freedesktop_spinner(None);
}
#[test]
fn normalize_gtk_symbolic_replaces_2e3436() {
let svg = br##"<svg><path fill="#2e3436" d="M0 0"/></svg>"##.to_vec();
let result = normalize_gtk_symbolic(svg, "#ffffff");
let s = std::str::from_utf8(&result).unwrap();
assert!(s.contains(r##"fill="#ffffff""##));
assert!(!s.contains("#2e3436"));
}
#[test]
fn normalize_gtk_symbolic_replaces_2e3434_preserves_opacity() {
let svg = br##"<svg><path fill="#2e3434" fill-opacity="0.35" d="M0 0"/></svg>"##.to_vec();
let result = normalize_gtk_symbolic(svg, "#ffffff");
let s = std::str::from_utf8(&result).unwrap();
assert!(s.contains(r##"fill="#ffffff""##));
assert!(s.contains(r#"fill-opacity="0.35""#));
}
#[test]
fn normalize_gtk_symbolic_replaces_222222() {
let svg = br##"<svg><path fill="#222222" d="M0 0"/></svg>"##.to_vec();
let result = normalize_gtk_symbolic(svg, "#ffffff");
let s = std::str::from_utf8(&result).unwrap();
assert!(s.contains(r##"fill="#ffffff""##));
assert!(!s.contains("#222222"));
}
#[test]
fn normalize_gtk_symbolic_replaces_474747() {
let svg = br##"<svg><path fill="#474747" d="M0 0"/></svg>"##.to_vec();
let result = normalize_gtk_symbolic(svg, "#ffffff");
let s = std::str::from_utf8(&result).unwrap();
assert!(s.contains(r##"fill="#ffffff""##));
assert!(!s.contains("#474747"));
}
#[test]
fn normalize_gtk_symbolic_replaces_stroke() {
let svg = br##"<svg><path stroke="#2e3436" fill="none" d="M1 1l14 14"/></svg>"##.to_vec();
let result = normalize_gtk_symbolic(svg, "#ffffff");
let s = std::str::from_utf8(&result).unwrap();
assert!(s.contains(r##"stroke="#ffffff""##));
assert!(!s.contains("#2e3436"));
}
#[test]
fn normalize_gtk_symbolic_replaces_css_style_fill() {
let svg = br##"<svg><path style="fill:#2e3436;fill-opacity:1" d="M0 0"/></svg>"##.to_vec();
let result = normalize_gtk_symbolic(svg, "#ffffff");
let s = std::str::from_utf8(&result).unwrap();
assert!(s.contains("fill:#ffffff"));
assert!(!s.contains("#2e3436"));
}
#[test]
fn normalize_gtk_symbolic_preserves_semantic_colors() {
let svg = br##"<svg><path fill="#2e3436"/><path fill="#ff7800"/><path fill="#33d17a"/><path fill="#e01b24"/></svg>"##.to_vec();
let result = normalize_gtk_symbolic(svg, "#ffffff");
let s = std::str::from_utf8(&result).unwrap();
assert!(s.contains("#ffffff"));
assert!(s.contains("#ff7800"), "warning color must be preserved");
assert!(s.contains("#33d17a"), "success color must be preserved");
assert!(s.contains("#e01b24"), "error color must be preserved");
}
#[test]
fn normalize_gtk_symbolic_skips_currentcolor_svgs() {
let svg = br##"<svg><defs><style>.ColorScheme-Text{color:#232629}</style></defs><path fill="currentColor"/></svg>"##.to_vec();
let original = svg.clone();
let result = normalize_gtk_symbolic(svg, "#ffffff");
assert_eq!(
result, original,
"Breeze-style SVGs should pass through unchanged"
);
}
#[test]
fn normalize_gtk_symbolic_skips_non_gtk_svgs() {
let svg = br#"<svg><path fill="red"/></svg>"#.to_vec();
let original = svg.clone();
let result = normalize_gtk_symbolic(svg, "#ffffff");
assert_eq!(
result, original,
"non-GTK SVGs should pass through unchanged"
);
}
fn encode_test_png(
width: u32,
height: u32,
color: png::ColorType,
pixels: &[u8],
) -> Option<Vec<u8>> {
let mut out = Vec::new();
let mut encoder = png::Encoder::new(&mut out, width, height);
encoder.set_color(color);
encoder.set_depth(png::BitDepth::Eight);
let mut writer = encoder.write_header().ok()?;
writer.write_image_data(pixels).ok()?;
drop(writer);
Some(out)
}
#[test]
fn decode_png_to_rgba_roundtrips_2x2_rgba() {
let pixels: [u8; 16] = [
0xff, 0x00, 0x00, 0xff, 0x00, 0xff, 0x00, 0x80, 0x00, 0x00, 0xff, 0xff, 0x11, 0x22, 0x33, 0x44, ];
let bytes = encode_test_png(2, 2, png::ColorType::Rgba, &pixels).expect("test PNG encode");
let result = decode_png_to_rgba(&bytes);
match result {
Some(IconData::Rgba {
width,
height,
data,
}) => {
assert_eq!(width, 2);
assert_eq!(height, 2);
assert_eq!(data, pixels.to_vec());
}
other => panic!("expected Rgba, got {other:?}"),
}
}
#[test]
fn decode_png_to_rgba_expands_rgb_to_rgba() {
let pixels: [u8; 6] = [
0xab, 0xcd, 0xef, 0x11, 0x22, 0x33, ];
let bytes = encode_test_png(2, 1, png::ColorType::Rgb, &pixels).expect("test PNG encode");
match decode_png_to_rgba(&bytes) {
Some(IconData::Rgba {
width,
height,
data,
}) => {
assert_eq!((width, height), (2, 1));
assert_eq!(data, vec![0xab, 0xcd, 0xef, 0xff, 0x11, 0x22, 0x33, 0xff]);
}
other => panic!("expected Rgba, got {other:?}"),
}
}
#[test]
fn decode_png_to_rgba_expands_grayscale_to_rgba() {
let pixels: [u8; 2] = [0x40, 0xc0];
let bytes =
encode_test_png(2, 1, png::ColorType::Grayscale, &pixels).expect("test PNG encode");
match decode_png_to_rgba(&bytes) {
Some(IconData::Rgba { data, .. }) => {
assert_eq!(data, vec![0x40, 0x40, 0x40, 0xff, 0xc0, 0xc0, 0xc0, 0xff]);
}
other => panic!("expected Rgba, got {other:?}"),
}
}
#[test]
fn decode_png_to_rgba_rejects_non_png_bytes() {
assert!(decode_png_to_rgba(b"not a png at all").is_none());
assert!(decode_png_to_rgba(&[]).is_none());
}
#[test]
#[ignore = "requires AdwaitaLegacy icon theme installed (GNOME legacy raster theme)"]
fn load_icon_from_png_only_theme_returns_rgba() {
let result = load_freedesktop_icon_by_name("edit-copy", "AdwaitaLegacy", 24, None);
let data = result.expect("edit-copy exists in AdwaitaLegacy 24x24/legacy");
match data {
IconData::Rgba {
width,
height,
data,
} => {
assert!(width > 0 && height > 0);
assert_eq!(
data.len(),
(width as usize) * (height as usize) * 4,
"RGBA byte count must match width*height*4"
);
}
IconData::Svg(bytes) => {
let head: Vec<u8> = bytes.iter().take(8).copied().collect();
panic!(
"expected Rgba, got Svg with {} bytes starting {:x?} \
(PNG magic is 89 50 4e 47)",
bytes.len(),
head
);
}
}
}
}