1use std::path::{Path, PathBuf};
22
23use resvg::tiny_skia::{FilterQuality, Pixmap, PixmapPaint, Transform};
24use resvg::usvg::{Options, 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
31pub const SOURCE_PNG_SIZE: u32 = 512;
37
38pub struct DerivedIcon {
40 pub file_name: &'static str,
41 pub size: u32,
42 format: IconFormat,
43}
44
45enum IconFormat {
46 Png,
47 Ico,
50}
51
52pub 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
76pub 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
92pub enum IconSource {
94 Svg(PathBuf),
97 Png(PathBuf),
99}
100
101impl IconSource {
102 #[must_use]
104 pub const fn is_vector(&self) -> bool {
105 matches!(self, Self::Svg(_))
106 }
107}
108
109pub 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
139pub 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
179enum 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 = 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 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
251fn 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
266pub fn dimensions(path: &Path) -> Result<(u32, u32), CacheBusterError> {
272 let size = imagesize::size(path).map_err(|error| CacheBusterError::ReadImage {
273 path: path.to_path_buf(),
274 reason: error.to_string(),
275 })?;
276 Ok((
277 u32::try_from(size.width).unwrap_or(0),
278 u32::try_from(size.height).unwrap_or(0),
279 ))
280}
281
282fn wrap_png_in_ico(png: &[u8], size: u32) -> Vec<u8> {
287 let dimension: u8 = u8::try_from(size).unwrap_or(0);
289 let length: u32 = u32::try_from(png.len()).unwrap_or(u32::MAX);
290
291 let mut ico: Vec<u8> = Vec::with_capacity(22 + png.len());
292 ico.extend_from_slice(&0u16.to_le_bytes()); ico.extend_from_slice(&1u16.to_le_bytes()); ico.extend_from_slice(&1u16.to_le_bytes()); ico.push(dimension); ico.push(dimension); ico.push(0); ico.push(0); ico.extend_from_slice(&1u16.to_le_bytes()); ico.extend_from_slice(&32u16.to_le_bytes()); ico.extend_from_slice(&length.to_le_bytes()); ico.extend_from_slice(&22u32.to_le_bytes()); ico.extend_from_slice(png);
304 ico
305}
306
307#[cfg(test)]
308mod tests {
309 use super::{DERIVED, SOURCE_PNG_SIZE, wrap_png_in_ico};
310
311 #[test]
312 fn an_ico_carries_the_png_verbatim_after_a_22_byte_header() {
313 let png: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];
314
315 let ico: Vec<u8> = wrap_png_in_ico(&png, 32);
316
317 let expected_len: usize = 22 + png.len();
318 let actual_len: usize = ico.len();
319 assert_eq!(expected_len, actual_len);
320
321 assert_eq!(&png[..], &ico[22..]);
322 assert_eq!(1u16, u16::from_le_bytes([ico[2], ico[3]]));
323 assert_eq!(1u16, u16::from_le_bytes([ico[4], ico[5]]));
324 assert_eq!(32u8, ico[6]);
325 assert_eq!(32u8, ico[7]);
326 }
327
328 #[test]
329 fn a_256_pixel_icon_records_its_dimension_as_zero_per_the_format() {
330 let ico: Vec<u8> = wrap_png_in_ico(&[0u8; 4], 256);
331
332 let expected: u8 = 0;
333 let actual: u8 = ico[6];
334 assert_eq!(expected, actual);
335 }
336
337 #[test]
338 fn every_derived_size_is_a_downscale_from_the_source() {
339 for icon in &DERIVED {
342 assert!(
343 icon.size <= SOURCE_PNG_SIZE,
344 "`{}` is {}px, larger than the {SOURCE_PNG_SIZE}px source",
345 icon.file_name,
346 icon.size
347 );
348 }
349 }
350}