Skip to main content

aer/proc/
favicon.rs

1use std::io::Cursor;
2
3use image::ImageFormat;
4
5use super::{Asset, Environment, LayeredContext, MediaType, ProcessesAssets, ProcessingError};
6
7/// Converts `favicon.png` files to `32x32` pixel `favicon.ico` files.
8pub struct FaviconProcessor;
9
10impl ProcessesAssets for FaviconProcessor {
11    fn process(
12        &self,
13        _env: &Environment,
14        _context: &LayeredContext,
15        asset: &mut Asset,
16    ) -> Result<bool, ProcessingError> {
17        if asset.media_type() != &MediaType::Png {
18            return Ok(false);
19        }
20
21        // Only process files named "favicon.png".
22        let path = asset.path();
23        let file_name = path.as_str().rsplit('/').next().unwrap_or(path.as_str());
24        if file_name != "favicon.png" {
25            return Ok(false);
26        }
27
28        tracing::trace!("favicon: {}", asset.path());
29
30        // Load the PNG image.
31        let image_bytes = asset.as_bytes();
32        let png =
33            image::load_from_memory_with_format(image_bytes, ImageFormat::Png).map_err(|e| {
34                ProcessingError::Malformed {
35                    message: e.to_string().into(),
36                }
37            })?;
38
39        // Resize the PNG to fit within 32x32 (standard favicon size).
40        let png = png.thumbnail(32, 32);
41
42        // Encode as ICO.
43        let ico_frame = image::codecs::ico::IcoFrame::as_png(
44            png.as_bytes(),
45            png.width(),
46            png.height(),
47            png.color().into(),
48        )
49        .map_err(|e| ProcessingError::Malformed {
50            message: e.to_string().into(),
51        })?;
52
53        let mut ico_bytes = Vec::new();
54        let ico_encoder = image::codecs::ico::IcoEncoder::new(Cursor::new(&mut ico_bytes));
55        ico_encoder
56            .encode_images(&[ico_frame])
57            .map_err(|e| ProcessingError::Malformed {
58                message: e.to_string().into(),
59            })?;
60
61        // Replace asset content with ICO and update media type.
62        asset.replace_with_bytes(ico_bytes, MediaType::Ico);
63
64        Ok(true)
65    }
66}
67
68#[cfg(test)]
69mod tests {
70    use super::*;
71    use crate::proc::LayeredContext;
72
73    #[test]
74    fn converts_favicon_png_to_ico() {
75        // Create a simple PNG image for testing.
76        let source_bytes = std::fs::read("test/example.png").unwrap();
77
78        // Wrap in an asset named "favicon.png".
79        let mut asset = Asset::new("favicon.png".into(), source_bytes);
80        assert_eq!(asset.media_type(), &MediaType::Png);
81
82        // Process the favicon.
83        FaviconProcessor
84            .process(
85                &Environment::test(),
86                &LayeredContext::from_flat(Default::default()),
87                &mut asset,
88            )
89            .unwrap();
90
91        // Verify the media type changed to ICO.
92        assert_eq!(asset.media_type(), &MediaType::Ico);
93
94        // Verify the content is valid ICO data (starts with ICO magic bytes).
95        let ico_bytes = asset.as_bytes();
96        assert!(ico_bytes.len() > 6);
97        // ICO files start with 00 00 01 00 (reserved, type=1 for ICO).
98        assert_eq!(&ico_bytes[0..4], &[0x00, 0x00, 0x01, 0x00]);
99    }
100
101    #[test]
102    fn skips_non_favicon_png() {
103        let source_bytes = std::fs::read("test/example.png").unwrap();
104
105        // Wrap in an asset with a different name.
106        let mut asset = Asset::new("other-image.png".into(), source_bytes.clone());
107        let original_len = asset.as_bytes().len();
108
109        // Process should skip this file.
110        let modified = FaviconProcessor
111            .process(
112                &Environment::test(),
113                &LayeredContext::from_flat(Default::default()),
114                &mut asset,
115            )
116            .unwrap();
117
118        // Verify the processor reported no modification.
119        assert!(!modified);
120        assert_eq!(asset.media_type(), &MediaType::Png);
121        assert_eq!(asset.as_bytes().len(), original_len);
122    }
123}