Skip to main content

webserver_base/assets/
icons.rs

1//! The icon set, rendered from the one icon a project authors.
2//!
3//! A project ships exactly one source — `favicon.svg`, or a 512×512
4//! `favicon.png` — and the `.ico`, the apple-touch icon and the two web-manifest
5//! icons are rasterised from it at build time. Five files of setup collapse to
6//! one, and they cannot drift from the source.
7//!
8//! Two formats because vector is not always available. SVG is preferred: it
9//! scales exactly, and it can carry its own `prefers-color-scheme` rules, which
10//! gives a dark-mode-adaptive tab icon for free. But a photographic mark cannot
11//! be vectorised well — autotracing a face yields either a posterised caricature
12//! or a multi-megabyte pile of paths — so a raster source is the honest answer
13//! there. Downscaling 512 → 192 → 180 → 32 is faithful; upscaling never is.
14//!
15//! Exactly one of the two must exist. Both is an error rather than a preference,
16//! because two sources silently drift the moment someone updates one of them.
17//!
18//! **An SVG must not rely on system fonts.** `resvg` is built without them, so
19//! any `<text>` should be converted to paths.
20
21use std::path::{Path, PathBuf};
22
23use resvg::tiny_skia::{FilterQuality, Pixmap, PixmapPaint, Transform};
24use resvg::usvg::{Options, Size, Tree};
25use tracing::info;
26
27use super::error::CacheBusterError;
28use super::generate::{FAVICON_DIRECTORY, FAVICON_PNG_SOURCE, FAVICON_SVG_SOURCE};
29use super::manifest::Manifest;
30
31/// The exact dimensions a raster source must have.
32///
33/// Not a minimum. Every size the set needs is a downscale from 512, so this is
34/// the natural source size, it makes `icon-512.png` a pixel-perfect copy, and
35/// one exact number is a clearer instruction than a range.
36pub const SOURCE_PNG_SIZE: u32 = 512;
37
38/// One icon derived from the source.
39pub struct DerivedIcon {
40    pub file_name: &'static str,
41    pub size: u32,
42    format: IconFormat,
43}
44
45enum IconFormat {
46    Png,
47    /// A single-image ICO wrapping a PNG, which every browser since IE 11
48    /// understands and which avoids hand-rolling a BMP encoder.
49    Ico,
50}
51
52/// The full derived set, in the order they are generated.
53pub const DERIVED: [DerivedIcon; 4] = [
54    DerivedIcon {
55        file_name: "favicon.ico",
56        size: 32,
57        format: IconFormat::Ico,
58    },
59    DerivedIcon {
60        file_name: "apple-touch-icon.png",
61        size: 180,
62        format: IconFormat::Png,
63    },
64    DerivedIcon {
65        file_name: "icon-192.png",
66        size: 192,
67        format: IconFormat::Png,
68    },
69    DerivedIcon {
70        file_name: "icon-512.png",
71        size: 512,
72        format: IconFormat::Png,
73    },
74];
75
76/// Every file the icon directory may contain: one source, and the four derived
77/// from it.
78///
79/// A closed set rather than a minimum. Anything else in there is either a stale
80/// icon from a previous design or a size somebody expected to be picked up and
81/// which never will be — both of which are silent until someone notices the
82/// wrong picture in a browser tab.
83pub const ALLOWED_FAVICON_FILES: [&str; 6] = [
84    "favicon.svg",
85    "favicon-512.png",
86    "favicon.ico",
87    "apple-touch-icon.png",
88    "icon-192.png",
89    "icon-512.png",
90];
91
92/// Which source a project authored.
93pub enum IconSource {
94    /// Vector. Also earns the `<link rel="icon" type="image/svg+xml">` and the
95    /// `/favicon.svg` route.
96    Svg(PathBuf),
97    /// Raster, exactly [`SOURCE_PNG_SIZE`] square.
98    Png(PathBuf),
99}
100
101impl IconSource {
102    /// Whether the layout should link an SVG icon.
103    #[must_use]
104    pub const fn is_vector(&self) -> bool {
105        matches!(self, Self::Svg(_))
106    }
107}
108
109/// Finds the project's single icon source.
110///
111/// # Errors
112///
113/// [`CacheBusterError::MissingFavicon`] if neither exists,
114/// [`CacheBusterError::AmbiguousFavicon`] if both do, or
115/// [`CacheBusterError::FaviconDimensions`] if a PNG source is the wrong size.
116pub fn resolve_source(manifest: &Manifest) -> Result<IconSource, CacheBusterError> {
117    let svg: Option<PathBuf> = existing(manifest, FAVICON_SVG_SOURCE);
118    let png: Option<PathBuf> = existing(manifest, FAVICON_PNG_SOURCE);
119
120    match (svg, png) {
121        (Some(_), Some(_)) => Err(CacheBusterError::AmbiguousFavicon),
122        (Some(svg), None) => Ok(IconSource::Svg(svg)),
123        (None, Some(png)) => {
124            let (width, height) = dimensions(&png)?;
125            if width != SOURCE_PNG_SIZE || height != SOURCE_PNG_SIZE {
126                return Err(CacheBusterError::FaviconDimensions {
127                    path: PathBuf::from(FAVICON_PNG_SOURCE),
128                    expected: SOURCE_PNG_SIZE,
129                    width,
130                    height,
131                });
132            }
133            Ok(IconSource::Png(png))
134        }
135        (None, None) => Err(CacheBusterError::MissingFavicon),
136    }
137}
138
139/// Renders every derived icon that does not already exist.
140///
141/// A file already present is left alone, so a hand-tuned small icon — the one
142/// size where a naive downscale of a detailed mark really does look muddy —
143/// still wins.
144///
145/// # Errors
146///
147/// [`CacheBusterError`] if the source cannot be resolved, parsed, rasterised, or
148/// an output cannot be written.
149pub fn generate_missing_icons(manifest: &Manifest) -> Result<(), CacheBusterError> {
150    let source: IconSource = resolve_source(manifest)?;
151
152    let outstanding: Vec<&DerivedIcon> = DERIVED
153        .iter()
154        .filter(|icon| {
155            existing(manifest, &format!("{FAVICON_DIRECTORY}/{}", icon.file_name)).is_none()
156        })
157        .collect();
158    if outstanding.is_empty() {
159        return Ok(());
160    }
161
162    let renderer: Renderer = Renderer::open(&source)?;
163    for icon in outstanding {
164        let png: Vec<u8> = renderer.rasterize(icon.size)?;
165        let bytes: Vec<u8> = match icon.format {
166            IconFormat::Png => png,
167            IconFormat::Ico => wrap_png_in_ico(&png, icon.size),
168        };
169
170        let path: PathBuf = Path::new(FAVICON_DIRECTORY).join(icon.file_name);
171        std::fs::write(&path, bytes)
172            .map_err(|source| CacheBusterError::WriteIcon { path, source })?;
173        info!("generated `{FAVICON_DIRECTORY}/{}`", icon.file_name);
174    }
175
176    Ok(())
177}
178
179/// Whatever the source is, reduced to "give me a square PNG of size N".
180enum Renderer {
181    Svg(Box<Tree>),
182    Png(Box<Pixmap>),
183}
184
185impl Renderer {
186    fn open(source: &IconSource) -> Result<Self, CacheBusterError> {
187        match source {
188            IconSource::Svg(path) => {
189                let svg: String =
190                    std::fs::read_to_string(path).map_err(|error| CacheBusterError::ReadFile {
191                        path: path.clone(),
192                        source: error,
193                    })?;
194                let tree: Tree = Tree::from_str(&svg, &Options::default())
195                    .map_err(|source| CacheBusterError::RenderIcon { source })?;
196                Ok(Self::Svg(Box::new(tree)))
197            }
198            IconSource::Png(path) => {
199                let bytes: Vec<u8> =
200                    std::fs::read(path).map_err(|error| CacheBusterError::ReadFile {
201                        path: path.clone(),
202                        source: error,
203                    })?;
204                let pixmap: Pixmap =
205                    Pixmap::decode_png(&bytes).map_err(|error| CacheBusterError::EncodeIcon {
206                        reason: error.to_string(),
207                    })?;
208                Ok(Self::Png(Box::new(pixmap)))
209            }
210        }
211    }
212
213    fn rasterize(&self, size: u32) -> Result<Vec<u8>, CacheBusterError> {
214        let mut target: Pixmap =
215            Pixmap::new(size, size).ok_or(CacheBusterError::IconDimensions { size })?;
216        let requested: f32 = f32::from(u16::try_from(size).unwrap_or(u16::MAX));
217
218        match self {
219            Self::Svg(tree) => {
220                let source: Size = tree.size();
221                let transform: Transform =
222                    Transform::from_scale(requested / source.width(), requested / source.height());
223                resvg::render(tree, transform, &mut target.as_mut());
224            }
225            Self::Png(pixmap) => {
226                let source: f32 = f32::from(u16::try_from(pixmap.width()).unwrap_or(1));
227                target.draw_pixmap(
228                    0,
229                    0,
230                    pixmap.as_ref().as_ref(),
231                    &PixmapPaint {
232                        // Every derived size is a downscale from 512, which is
233                        // where a good filter earns its keep.
234                        quality: FilterQuality::Bicubic,
235                        ..PixmapPaint::default()
236                    },
237                    Transform::from_scale(requested / source, requested / source),
238                    None,
239                );
240            }
241        }
242
243        target
244            .encode_png()
245            .map_err(|error| CacheBusterError::EncodeIcon {
246                reason: error.to_string(),
247            })
248    }
249}
250
251/// Finds an asset by its hashed name, falling back to its logical one.
252///
253/// The fallback covers only the pre-hash state: during the build the source is
254/// still `favicon.svg`, and after it the manifest knows it as
255/// `favicon.<hash>.svg`. It is not a fallback for a *missing* asset — that is
256/// caught at boot, loudly.
257fn existing(manifest: &Manifest, logical: &str) -> Option<PathBuf> {
258    let hashed: PathBuf = PathBuf::from(manifest.resolve(logical));
259    if hashed.is_file() {
260        return Some(hashed);
261    }
262    let plain: PathBuf = PathBuf::from(logical);
263    plain.is_file().then_some(plain)
264}
265
266/// Reads an image's real dimensions.
267///
268/// # Errors
269///
270/// [`CacheBusterError::ReadImage`] if the file is absent or not an image.
271pub fn dimensions(path: &Path) -> Result<(u32, u32), CacheBusterError> {
272    let size: imagesize::ImageSize =
273        imagesize::size(path).map_err(|error| CacheBusterError::ReadImage {
274            path: path.to_path_buf(),
275            reason: error.to_string(),
276        })?;
277    Ok((
278        u32::try_from(size.width).unwrap_or(0),
279        u32::try_from(size.height).unwrap_or(0),
280    ))
281}
282
283/// Wraps PNG bytes in a single-image ICO container.
284///
285/// The format is a 6-byte directory header plus one 16-byte entry, and modern
286/// ICOs may carry PNG payloads verbatim — so this is a header, not an encoder.
287fn wrap_png_in_ico(png: &[u8], size: u32) -> Vec<u8> {
288    // 0 means 256 in this field, which is exactly what we want at that size.
289    let dimension: u8 = u8::try_from(size).unwrap_or(0);
290    let length: u32 = u32::try_from(png.len()).unwrap_or(u32::MAX);
291
292    let mut ico: Vec<u8> = Vec::with_capacity(22 + png.len());
293    ico.extend_from_slice(&0u16.to_le_bytes()); // reserved
294    ico.extend_from_slice(&1u16.to_le_bytes()); // type: icon
295    ico.extend_from_slice(&1u16.to_le_bytes()); // image count
296    ico.push(dimension); // width
297    ico.push(dimension); // height
298    ico.push(0); // palette size
299    ico.push(0); // reserved
300    ico.extend_from_slice(&1u16.to_le_bytes()); // colour planes
301    ico.extend_from_slice(&32u16.to_le_bytes()); // bits per pixel
302    ico.extend_from_slice(&length.to_le_bytes()); // payload size
303    ico.extend_from_slice(&22u32.to_le_bytes()); // payload offset
304    ico.extend_from_slice(png);
305    ico
306}
307
308#[cfg(test)]
309mod tests {
310    use super::{DERIVED, SOURCE_PNG_SIZE, wrap_png_in_ico};
311
312    #[test]
313    fn an_ico_carries_the_png_verbatim_after_a_22_byte_header() {
314        let png: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];
315
316        let ico: Vec<u8> = wrap_png_in_ico(&png, 32);
317
318        let expected_len: usize = 22 + png.len();
319        let actual_len: usize = ico.len();
320        assert_eq!(expected_len, actual_len);
321
322        assert_eq!(&png[..], &ico[22..]);
323        assert_eq!(1u16, u16::from_le_bytes([ico[2], ico[3]]));
324        assert_eq!(1u16, u16::from_le_bytes([ico[4], ico[5]]));
325        assert_eq!(32u8, ico[6]);
326        assert_eq!(32u8, ico[7]);
327    }
328
329    #[test]
330    fn a_256_pixel_icon_records_its_dimension_as_zero_per_the_format() {
331        let ico: Vec<u8> = wrap_png_in_ico(&[0u8; 4], 256);
332
333        let expected: u8 = 0;
334        let actual: u8 = ico[6];
335        assert_eq!(expected, actual);
336    }
337
338    #[test]
339    fn every_derived_size_is_a_downscale_from_the_source() {
340        // Upscaling is what makes a generated icon look soft, so the source
341        // must be at least as large as everything derived from it.
342        for icon in &DERIVED {
343            assert!(
344                icon.size <= SOURCE_PNG_SIZE,
345                "`{}` is {}px, larger than the {SOURCE_PNG_SIZE}px source",
346                icon.file_name,
347                icon.size
348            );
349        }
350    }
351}