use crate::formats::{ani::AniFile, xcursor::Xcursor};
use super::{cursor_image::CursorImage, cursor_role::CursorRole};
use std::{
collections::BTreeMap,
fs::{self, File},
io::{BufWriter, Cursor, Write},
path::Path,
};
use anyhow::{Context, Result, bail};
use binrw::BinWrite;
use fast_image_resize::ResizeAlg;
use ico::IconDir;
#[derive(Debug)]
pub struct GenericCursor {
images: Vec<(f64, Vec<CursorImage>)>,
pub role: Option<CursorRole>,
info: Option<String>,
}
impl GenericCursor {
fn from_source(
base: Vec<CursorImage>,
variants: impl IntoIterator<Item = Vec<CursorImage>>,
info: Option<String>,
) -> Result<Self> {
let base_frame = base.first().context("no base frames found")?;
let base_size = base_frame.nominal_size;
let base_len = base.len();
let mut images: Vec<(f64, Vec<CursorImage>)> = Vec::new();
for mut frames in std::iter::once(base).chain(variants) {
if frames.len() != base_len {
bail!("expected {base_len} frames per size, got {}", frames.len());
}
CursorImage::validate_frames(&mut frames)?;
let source_size = frames[0].nominal_size;
if images
.iter()
.any(|(_, stored)| stored[0].nominal_size == source_size)
{
bail!("multiple source cursor variants have nominal size {source_size}");
}
let scale_factor = f64::from(source_size) / f64::from(base_size);
images.push((scale_factor, frames));
}
Ok(Self {
images,
role: None,
info,
})
}
pub fn set_base_nominal_size(&mut self, size: u32) -> Result<()> {
if size == 0 {
bail!("nominal size can't be zero");
}
let nominal_sizes = self
.images
.iter()
.map(|(scale, _)| {
let nominal_size = (f64::from(size) * scale).floor().max(1.0);
#[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
Ok(nominal_size as u32)
})
.collect::<Result<Vec<_>>>()?;
for ((_, frames), nominal_size) in self.images.iter_mut().zip(nominal_sizes) {
for frame in frames {
frame.nominal_size = nominal_size;
}
}
Ok(())
}
pub fn add_scale(&mut self, scale_factor: f64, algorithm: ResizeAlg) -> Result<()> {
let base = &self.images[0].1;
#[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
let nominal_size = ((f64::from(base[0].nominal_size) * scale_factor).floor() as u32).max(1);
#[expect(
clippy::float_cmp,
reason = "skip scales already present at the requested factor"
)]
if self
.images
.iter()
.any(|(scale, frames)| *scale == scale_factor || frames[0].nominal_size == nominal_size)
{
eprintln!("scale_factor={scale_factor} already exists, skipping");
return Ok(());
}
let scaled_frames = base
.iter()
.map(|c| c.scaled_to(scale_factor, nominal_size, algorithm))
.collect::<Result<_>>()?;
self.images.push((scale_factor, scaled_frames));
Ok(())
}
pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Self> {
let path = path.as_ref();
let Some(ext) = path.extension() else {
bail!("path has no extension; expected 'cur' or 'ani'")
};
let ext = ext.to_ascii_lowercase();
if ext == "cur" {
Self::from_cur_path(path)
} else if ext == "ani" {
Self::from_ani_path(path)
} else {
bail!(
"expected extension 'cur' or 'ani' for path, got ext={}",
ext.display()
)
}
}
pub fn from_cur_path<P: AsRef<Path>>(cur_path: P) -> Result<Self> {
let cur_path = cur_path.as_ref();
let handle = fs::read(cur_path).context("(filesystem) failed to read")?;
let icon_dir = IconDir::read(Cursor::new(handle)).context("failed to read `IconDir`")?;
let entries = icon_dir.entries();
if entries.is_empty() {
bail!("no stored images found");
}
let mut base = Vec::new();
let mut variants = Vec::new();
let base_dims = Self::get_base_dimensions(&[&icon_dir]);
for entry in entries {
let image = CursorImage::from_entry(entry, 0)?;
if image.dimensions() == base_dims {
base.push(image);
} else {
variants.push(vec![image]);
}
}
Self::from_source(base, variants, None)
}
pub fn from_ani_path<P: AsRef<Path>>(ani_path: P) -> Result<Self> {
let ani_blob = fs::read(&ani_path)?;
let ani_file = AniFile::from_blob(&ani_blob)?;
let header = &ani_file.header;
let info = match (ani_file.title, ani_file.author) {
(Some(t), Some(a)) => Some(format!("'{t}' by '{a}'")),
(Some(t), None) => Some(format!("'{t}' by [unknown]")),
(None, Some(a)) => Some(format!("[unknown] by '{a}'")),
(None, None) => None,
};
let icos: Vec<IconDir> = ani_file
.ico_frames
.into_iter()
.map(|chunk| {
let ico = IconDir::read(&mut Cursor::new(&chunk))?;
if ico.entries().is_empty() {
bail!("ANI frame contains no images");
}
Ok(ico)
})
.collect::<Result<_>>()?;
let sequence: Option<Vec<usize>> = ani_file
.sequence
.map(|chunk| chunk.into_iter().map(usize::try_from).collect())
.transpose()?;
let sequenced_icos: Vec<&IconDir> = sequence.map_or_else(
|| icos.iter().collect(),
|v| v.into_iter().map(|idx| &icos[idx]).collect(),
);
let num_steps = usize::try_from(header.num_steps)?;
let delays_jiffies = ani_file
.rate
.unwrap_or_else(|| vec![header.jiffy_rate; num_steps]);
let delays_ms: Vec<u32> = delays_jiffies
.into_iter()
.map(|j| (j * 1000 + 30) / 60) .collect();
let base_dims = Self::get_base_dimensions(&sequenced_icos);
let mut by_dimensions = BTreeMap::<_, Vec<_>>::new();
for (ico, delay) in sequenced_icos.iter().zip(delays_ms) {
for entry in ico.entries() {
let image = CursorImage::from_entry(entry, delay)?;
by_dimensions
.entry(image.dimensions())
.or_default()
.push(image);
}
}
let base = by_dimensions
.remove(&base_dims)
.context("no base frames found")?;
Self::from_source(base, by_dimensions.into_values(), info)
}
pub fn save_as_xcursor<P: AsRef<Path>>(&self, path: P) -> Result<()> {
let path = path.as_ref();
let file = File::create(path)?;
let mut writer = BufWriter::new(file);
let xcursor = Xcursor::new(self)?;
xcursor.write(&mut writer)?;
writer.flush().context("failed to flush Xcursor output")?;
Ok(())
}
fn get_base_dimensions(icons: &[&IconDir]) -> (u32, u32) {
if icons
.iter()
.flat_map(|ico| ico.entries())
.any(|e| (e.width(), e.height()) == (32, 32))
{
(32, 32)
} else {
let first_entry = &icons[0].entries()[0];
(first_entry.width(), first_entry.height())
}
}
pub fn frames(&self) -> impl Iterator<Item = &CursorImage> {
self.images.iter().flat_map(|(_, frames)| frames)
}
#[must_use]
pub fn info(&self) -> Option<String> {
self.info.clone()
}
#[must_use]
pub fn num_images(&self) -> usize {
self.images.iter().map(|(_, frames)| frames.len()).sum()
}
}
#[cfg(test)]
pub mod tests {
use super::*;
use crate::cursors::cursor_image::tests::{BLACK, WHITE};
#[expect(clippy::missing_panics_doc)]
pub fn black_and_white() -> GenericCursor {
let frames = [
BLACK.clone(),
WHITE.clone(),
BLACK.clone(),
WHITE.clone(),
BLACK.clone(),
WHITE.clone(),
BLACK.clone(),
WHITE.clone(),
BLACK.clone(),
WHITE.clone(),
];
GenericCursor::from_source(frames.to_vec(), [], None).unwrap()
}
}