Skip to main content

effindom_native_packaging/
icon_source.rs

1use crate::{Error, Result};
2use image::imageops::FilterType;
3use image::{ImageFormat, RgbaImage};
4use resvg::{tiny_skia, usvg};
5use serde::Serialize;
6use std::collections::BTreeSet;
7use std::fs;
8use std::path::{Path, PathBuf};
9
10pub const MINIMUM_PNG_ICON_SIZE: u32 = 256;
11pub const RECOMMENDED_PNG_ICON_SIZE: u32 = 1024;
12pub const CANONICAL_ICON_SIZES: &[u32] = &[
13    16, 24, 32, 44, 48, 50, 64, 128, 150, 180, 192, 256, 512, 1024,
14];
15
16#[derive(Clone, Copy, Debug, Serialize, PartialEq, Eq)]
17#[serde(rename_all = "lowercase")]
18pub enum IconSourceFormat {
19    Svg,
20    Png,
21}
22
23#[derive(Clone, Copy, Debug, Serialize, PartialEq, Eq)]
24#[serde(rename_all = "kebab-case")]
25pub enum IconAlpha {
26    Opaque,
27    HasTransparency,
28}
29
30#[derive(Clone, Debug, PartialEq, Eq)]
31pub enum IconQualityWarning {
32    PngWillBeUpscaled {
33        width: u32,
34        height: u32,
35        recommended: u32,
36    },
37}
38
39#[derive(Clone, Debug, PartialEq, Eq)]
40pub struct IconRaster {
41    pub size: u32,
42    pub rgba8: Vec<u8>,
43}
44
45impl IconRaster {
46    pub fn pixel(&self, x: u32, y: u32) -> Option<[u8; 4]> {
47        if x >= self.size || y >= self.size {
48            return None;
49        }
50        let offset = ((y * self.size + x) * 4) as usize;
51        Some(
52            self.rgba8[offset..offset + 4]
53                .try_into()
54                .expect("RGBA pixel"),
55        )
56    }
57}
58
59#[derive(Clone, Debug, PartialEq, Eq)]
60pub struct IconRasterSet {
61    pub source_format: IconSourceFormat,
62    pub source_width: u32,
63    pub source_height: u32,
64    pub alpha: IconAlpha,
65    pub rasters: Vec<IconRaster>,
66}
67
68impl IconRasterSet {
69    pub fn get(&self, size: u32) -> Option<&IconRaster> {
70        self.rasters.iter().find(|raster| raster.size == size)
71    }
72}
73
74#[derive(Clone)]
75enum DecodedSource {
76    Svg(Box<usvg::Tree>),
77    Png(RgbaImage),
78}
79
80#[derive(Clone)]
81pub struct IconSource {
82    path: PathBuf,
83    format: IconSourceFormat,
84    width: u32,
85    height: u32,
86    alpha: IconAlpha,
87    quality_warnings: Vec<IconQualityWarning>,
88    decoded: DecodedSource,
89}
90
91impl IconSource {
92    pub fn path(&self) -> &Path {
93        &self.path
94    }
95
96    pub fn format(&self) -> IconSourceFormat {
97        self.format
98    }
99
100    pub fn width(&self) -> u32 {
101        self.width
102    }
103
104    pub fn height(&self) -> u32 {
105        self.height
106    }
107
108    pub fn alpha(&self) -> IconAlpha {
109        self.alpha
110    }
111
112    pub fn quality_warnings(&self) -> &[IconQualityWarning] {
113        &self.quality_warnings
114    }
115
116    pub fn canonical_rasters(&self) -> Result<IconRasterSet> {
117        self.rasterize(CANONICAL_ICON_SIZES)
118    }
119
120    pub fn rasterize(&self, requested_sizes: &[u32]) -> Result<IconRasterSet> {
121        let sizes = validate_sizes(requested_sizes)?;
122        let rasters = sizes
123            .into_iter()
124            .map(|size| self.render(size))
125            .collect::<Result<Vec<_>>>()?;
126        Ok(IconRasterSet {
127            source_format: self.format,
128            source_width: self.width,
129            source_height: self.height,
130            alpha: self.alpha,
131            rasters,
132        })
133    }
134
135    fn render(&self, size: u32) -> Result<IconRaster> {
136        let rgba8 = match &self.decoded {
137            DecodedSource::Png(image) => {
138                if image.width() == size {
139                    image.as_raw().clone()
140                } else {
141                    image::imageops::resize(image, size, size, FilterType::Lanczos3).into_raw()
142                }
143            }
144            DecodedSource::Svg(tree) => render_svg(tree, size, &self.path)?,
145        };
146        Ok(IconRaster { size, rgba8 })
147    }
148}
149
150pub fn load_icon_source(path: impl AsRef<Path>) -> Result<IconSource> {
151    let path = path.as_ref();
152    let extension = path
153        .extension()
154        .and_then(|extension| extension.to_str())
155        .map(str::to_ascii_lowercase);
156    match extension.as_deref() {
157        Some("png") => load_png(path),
158        Some("svg") => load_svg(path),
159        _ => Err(Error::InvalidIconPath(path.to_path_buf())),
160    }
161}
162
163fn load_png(path: &Path) -> Result<IconSource> {
164    let bytes = read_source(path)?;
165    let image = image::load_from_memory_with_format(&bytes, ImageFormat::Png)
166        .map_err(|error| decode_error(path, error))?
167        .into_rgba8();
168    let width = image.width();
169    let height = image.height();
170    validate_square(path, width, height)?;
171    if width < MINIMUM_PNG_ICON_SIZE {
172        return Err(Error::PngIconTooSmall {
173            path: path.to_path_buf(),
174            width,
175            height,
176            minimum: MINIMUM_PNG_ICON_SIZE,
177        });
178    }
179    let alpha = classify_alpha(path, image.as_raw())?;
180    let quality_warnings = if width < RECOMMENDED_PNG_ICON_SIZE {
181        vec![IconQualityWarning::PngWillBeUpscaled {
182            width,
183            height,
184            recommended: RECOMMENDED_PNG_ICON_SIZE,
185        }]
186    } else {
187        Vec::new()
188    };
189    Ok(IconSource {
190        path: path.to_path_buf(),
191        format: IconSourceFormat::Png,
192        width,
193        height,
194        alpha,
195        quality_warnings,
196        decoded: DecodedSource::Png(image),
197    })
198}
199
200fn load_svg(path: &Path) -> Result<IconSource> {
201    let bytes = read_source(path)?;
202    let options = usvg::Options::default();
203    let tree = usvg::Tree::from_data(&bytes, &options).map_err(|error| Error::DecodeIcon {
204        path: path.to_path_buf(),
205        message: error.to_string(),
206    })?;
207    let size = tree.size();
208    let width = size.width().round() as u32;
209    let height = size.height().round() as u32;
210    if size.width() <= 0.0 || size.height() <= 0.0 || (size.width() - size.height()).abs() > 0.01 {
211        return Err(Error::InvalidIconDimensions {
212            path: path.to_path_buf(),
213            width,
214            height,
215        });
216    }
217    let probe = render_svg(&tree, 256, path)?;
218    let alpha = classify_alpha(path, &probe)?;
219    Ok(IconSource {
220        path: path.to_path_buf(),
221        format: IconSourceFormat::Svg,
222        width,
223        height,
224        alpha,
225        quality_warnings: Vec::new(),
226        decoded: DecodedSource::Svg(Box::new(tree)),
227    })
228}
229
230fn read_source(path: &Path) -> Result<Vec<u8>> {
231    fs::read(path).map_err(|source| Error::ReadFile {
232        path: path.to_path_buf(),
233        source,
234    })
235}
236
237fn render_svg(tree: &usvg::Tree, size: u32, path: &Path) -> Result<Vec<u8>> {
238    let mut pixmap = tiny_skia::Pixmap::new(size, size).ok_or_else(|| Error::DecodeIcon {
239        path: path.to_path_buf(),
240        message: format!("could not allocate {size}x{size} raster"),
241    })?;
242    let source_size = tree.size();
243    let transform = tiny_skia::Transform::from_scale(
244        size as f32 / source_size.width(),
245        size as f32 / source_size.height(),
246    );
247    resvg::render(tree, transform, &mut pixmap.as_mut());
248    Ok(pixmap.take())
249}
250
251fn validate_square(path: &Path, width: u32, height: u32) -> Result<()> {
252    if width == 0 || height == 0 || width != height {
253        Err(Error::InvalidIconDimensions {
254            path: path.to_path_buf(),
255            width,
256            height,
257        })
258    } else {
259        Ok(())
260    }
261}
262
263fn classify_alpha(path: &Path, rgba8: &[u8]) -> Result<IconAlpha> {
264    let mut has_visible_pixel = false;
265    let mut has_transparency = false;
266    for alpha in rgba8.iter().skip(3).step_by(4) {
267        has_visible_pixel |= *alpha != 0;
268        has_transparency |= *alpha != 255;
269    }
270    if !has_visible_pixel {
271        return Err(Error::InvisibleIcon(path.to_path_buf()));
272    }
273    Ok(if has_transparency {
274        IconAlpha::HasTransparency
275    } else {
276        IconAlpha::Opaque
277    })
278}
279
280fn validate_sizes(requested_sizes: &[u32]) -> Result<Vec<u32>> {
281    let mut sizes = BTreeSet::new();
282    for size in requested_sizes {
283        if *size == 0 {
284            return Err(Error::InvalidIconRasterSize(*size));
285        }
286        if !sizes.insert(*size) {
287            return Err(Error::DuplicateIconRasterSize(*size));
288        }
289    }
290    Ok(sizes.into_iter().collect())
291}
292
293fn decode_error(path: &Path, error: image::ImageError) -> Error {
294    Error::DecodeIcon {
295        path: path.to_path_buf(),
296        message: error.to_string(),
297    }
298}