Skip to main content

native_theme/
rasterize.rs

1// SVG-to-RGBA rasterization using resvg.
2//
3// Converts SVG byte data to IconData::Rgba pixel data at a specified size.
4// Enabled behind the `svg-rasterize` feature gate.
5
6use crate::IconData;
7use resvg::tiny_skia;
8use resvg::usvg;
9
10/// Rasterize SVG bytes to RGBA pixel data at the given size.
11///
12/// Parses the SVG, scales it uniformly to fit within `size x size` pixels
13/// (preserving aspect ratio), and renders to a pixel buffer with straight
14/// (non-premultiplied) alpha. `size` is clamped to
15/// `1..=`[`MAX_ICON_SIZE`](crate::icons::MAX_ICON_SIZE) first: 0 draws one
16/// pixel, and a size above 512 draws at 512.
17///
18/// # Errors
19///
20/// Returns [`crate::Error::ReaderFailed`] with reader `"svg-rasterizer"`,
21/// whose [`kind`](crate::Error::kind) is
22/// [`ErrorKind::Platform`](crate::error::ErrorKind::Platform), if the SVG
23/// cannot be parsed or its `size × size` RGBA buffer cannot be allocated.
24///
25/// An `<image>` is drawn only from an inline `data:` URL; an `href` naming a
26/// file is not read.
27///
28/// # Examples
29///
30/// ```
31/// # #[cfg(feature = "svg-rasterize")]
32/// # {
33/// use native_theme::rasterize::rasterize_svg;
34/// use native_theme::icons::IconData;
35///
36/// let svg = b"<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'><circle cx='12' cy='12' r='10'/></svg>";
37/// let result = rasterize_svg(svg, 24);
38/// assert!(result.is_ok());
39/// if let Ok(IconData::Rgba(rgba)) = result {
40///     assert_eq!(rgba.width(), 24);
41///     assert_eq!(rgba.height(), 24);
42///     assert_eq!(rgba.data().len(), 24 * 24 * 4);
43/// }
44/// # }
45/// ```
46pub fn rasterize_svg(svg_bytes: &[u8], size: u32) -> crate::Result<IconData> {
47    let failed = |source: Box<dyn std::error::Error + Send + Sync>| crate::Error::ReaderFailed {
48        reader: crate::error::reader_names::SVG_RASTERIZER,
49        source,
50    };
51    let size = size.clamp(1, crate::icons::MAX_ICON_SIZE);
52    // A backstop: the clamp keeps the buffer at 1 MiB at most, far inside
53    // the decode bound, so this cannot fail; it also gives the buffer's length.
54    let data_len = crate::icons::raster_bytes_in_bound(size, size).ok_or_else(|| {
55        failed(
56            format!(
57                "rasterization size {size}x{size} is over {} bytes",
58                crate::icons::MAX_ICON_DECODE_BYTES
59            )
60            .into(),
61        )
62    })?;
63
64    // Only inline data: images; a string href would be read from disk
65    // relative to the process's working directory.
66    let options = usvg::Options {
67        image_href_resolver: usvg::ImageHrefResolver {
68            resolve_data: usvg::ImageHrefResolver::default_data_resolver(),
69            resolve_string: Box::new(|_, _| None),
70        },
71        ..usvg::Options::default()
72    };
73    let tree = usvg::Tree::from_data(svg_bytes, &options).map_err(|e| failed(Box::new(e)))?;
74
75    let original_size = tree.size();
76    let scale_x = size as f32 / original_size.width();
77    let scale_y = size as f32 / original_size.height();
78    let scale = scale_x.min(scale_y);
79
80    // Center the icon if aspect ratio doesn't match
81    let scaled_w = original_size.width() * scale;
82    let scaled_h = original_size.height() * scale;
83    let offset_x = (size as f32 - scaled_w) / 2.0;
84    let offset_y = (size as f32 - scaled_h) / 2.0;
85
86    let mut buffer = Vec::new();
87    buffer
88        .try_reserve_exact(data_len)
89        .map_err(|e| failed(Box::new(e)))?;
90    buffer.resize(data_len, 0);
91    let mut pixmap = tiny_skia::IntSize::from_wh(size, size)
92        .and_then(|int_size| tiny_skia::Pixmap::from_vec(buffer, int_size))
93        .ok_or_else(|| failed(format!("invalid rasterization size {size}x{size}").into()))?;
94    let transform =
95        tiny_skia::Transform::from_scale(scale, scale).post_translate(offset_x, offset_y);
96    resvg::render(&tree, transform, &mut pixmap.as_mut());
97
98    // resvg outputs premultiplied RGBA; convert to straight alpha
99    let mut data = pixmap.take();
100    crate::color::unpremultiply_alpha(&mut data);
101
102    IconData::rgba(size, size, data)
103        .ok_or_else(|| failed(format!("rasterized pixels do not fill {size}x{size}").into()))
104}
105
106#[cfg(test)]
107#[allow(clippy::unwrap_used, clippy::expect_used)]
108mod tests {
109    use super::*;
110
111    const VALID_SVG: &[u8] = b"<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'><circle cx='12' cy='12' r='10' fill='red'/></svg>";
112
113    #[test]
114    fn rasterize_valid_svg_returns_rgba() {
115        let result = rasterize_svg(VALID_SVG, 24);
116        assert!(result.is_ok(), "valid SVG should produce Ok");
117        match result.unwrap() {
118            IconData::Rgba(rgba) => {
119                assert_eq!(rgba.width(), 24);
120                assert_eq!(rgba.height(), 24);
121                assert_eq!(rgba.data().len(), 24 * 24 * 4);
122            }
123            _ => panic!("expected IconData::Rgba"),
124        }
125    }
126
127    #[test]
128    fn rasterize_invalid_svg_returns_err() {
129        let result = rasterize_svg(b"not svg", 24);
130        assert!(result.is_err(), "invalid SVG should return Err");
131    }
132
133    #[test]
134    fn rasterize_output_length_matches_size() {
135        for size in [16, 24, 32, 48, 64] {
136            let result = rasterize_svg(VALID_SVG, size);
137            let icon = result.unwrap_or_else(|_| panic!("should produce output for size {size}"));
138            if let IconData::Rgba(rgba) = icon {
139                assert_eq!(
140                    rgba.data().len(),
141                    (size * size * 4) as usize,
142                    "output length mismatch for size {size}"
143                );
144            }
145        }
146    }
147
148    #[test]
149    fn rasterize_produces_non_empty_pixels() {
150        let result = rasterize_svg(VALID_SVG, 24).unwrap();
151        if let IconData::Rgba(rgba) = result {
152            // At least some pixels should be non-zero (red circle on transparent bg)
153            let non_zero = rgba.data().iter().any(|&b| b != 0);
154            assert!(non_zero, "rasterized output should contain non-zero pixels");
155        }
156    }
157
158    #[test]
159    fn rasterize_straight_alpha() {
160        // A semi-transparent SVG element
161        let svg = b"<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 2 2'><rect width='2' height='2' fill='white' fill-opacity='0.5'/></svg>";
162        let result = rasterize_svg(svg, 2).unwrap();
163        if let IconData::Rgba(rgba) = result {
164            // All pixels should be the same semi-transparent white
165            for pixel in rgba.data().as_chunks::<4>().0 {
166                let &[r, _g, _b, a] = pixel;
167                if a > 0 {
168                    // Straight alpha: R should be close to 255, not ~128
169                    // (premultiplied would have R ~= 128 for alpha 128)
170                    assert!(
171                        r > 200,
172                        "expected straight alpha (R near 255), got R={r} A={a}"
173                    );
174                }
175            }
176        }
177    }
178
179    /// A size is clamped to `1..=MAX_ICON_SIZE`: 0 draws one pixel, and a
180    /// size past the bound draws at the bound rather than allocating
181    /// `size² × 4` bytes.
182    #[test]
183    fn rasterize_clamps_the_size_to_max_icon_size() {
184        use crate::icons::MAX_ICON_SIZE;
185        for (size, side) in [
186            (0, 1),
187            (MAX_ICON_SIZE, MAX_ICON_SIZE),
188            (MAX_ICON_SIZE + 1, MAX_ICON_SIZE),
189            (100_000, MAX_ICON_SIZE),
190            (u32::MAX, MAX_ICON_SIZE),
191        ] {
192            let Ok(IconData::Rgba(rgba)) = rasterize_svg(VALID_SVG, size) else {
193                panic!("asked for {size}: no raster");
194            };
195            assert_eq!(
196                (rgba.width(), rgba.height()),
197                (side, side),
198                "asked for {size}"
199            );
200        }
201    }
202
203    fn alpha_at(icon: &IconData, x: usize, y: usize) -> u8 {
204        let IconData::Rgba(rgba) = icon else {
205            panic!("expected IconData::Rgba");
206        };
207        let width = rgba.width() as usize;
208        rgba.data()[(y * width + x) * 4 + 3]
209    }
210
211    #[test]
212    fn rasterize_centres_a_wide_svg() {
213        let svg = b"<svg xmlns='http://www.w3.org/2000/svg' width='10' height='5' viewBox='0 0 10 5'><rect width='10' height='5' fill='red'/></svg>";
214        let icon = rasterize_svg(svg, 100).unwrap();
215        assert_eq!(alpha_at(&icon, 50, 50), 255, "the centre is drawn");
216        assert_eq!(
217            alpha_at(&icon, 50, 26),
218            255,
219            "the drawn band starts at row 25"
220        );
221        assert_eq!(
222            alpha_at(&icon, 50, 73),
223            255,
224            "the drawn band ends at row 75"
225        );
226        assert_eq!(alpha_at(&icon, 50, 23), 0, "above the band is transparent");
227        assert_eq!(alpha_at(&icon, 50, 76), 0, "below the band is transparent");
228    }
229
230    #[test]
231    fn rasterize_draws_nothing_from_a_file_href() {
232        let dir = std::env::temp_dir().join(format!(
233            "native-theme-rasterize-href-{}",
234            std::process::id()
235        ));
236        let _ = std::fs::remove_dir_all(&dir);
237        std::fs::create_dir_all(&dir).unwrap();
238        let referenced = dir.join("red.svg");
239        std::fs::write(&referenced, VALID_SVG).unwrap();
240        let svg = format!(
241            "<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' \
242             viewBox='0 0 24 24'><image width='24' height='24' xlink:href='{}'/></svg>",
243            referenced.display()
244        );
245        let icon = rasterize_svg(svg.as_bytes(), 24);
246        let _ = std::fs::remove_dir_all(&dir);
247        let IconData::Rgba(rgba) = icon.unwrap() else {
248            panic!("expected IconData::Rgba");
249        };
250        assert!(
251            rgba.data().iter().all(|&b| b == 0),
252            "nothing is drawn from a file on disk"
253        );
254    }
255
256    #[test]
257    fn rasterize_draws_a_data_url_image() {
258        let svg = b"<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' viewBox='0 0 24 24'><image width='24' height='24' xlink:href='data:image/svg+xml;utf8,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 24 24%22%3E%3Crect width=%2224%22 height=%2224%22 fill=%22red%22/%3E%3C/svg%3E'/></svg>";
259        let icon = rasterize_svg(svg, 24).unwrap();
260        assert_eq!(
261            alpha_at(&icon, 12, 12),
262            255,
263            "an inline data: image is drawn"
264        );
265    }
266}