Krolyxon
Commit 9f6e071

Branches

Tags

Refs →

remagesrcdecodesvg.rs

104 lines · 3.5 KB · Rust

1//! SVG and SVGZ through resvg. The parsed tree is kept so the image can be re-rasterised at
2//! the current zoom and stay sharp.
3
4use std::path::Path;
5use std::sync::{Arc, LazyLock};
6
7use resvg::{tiny_skia, usvg};
8
9use super::{DecodedImage, Options, Refine};
10
11/// Longest side of any raster; zooming further shows this one magnified.
12pub const MAX_RASTER: u32 = 8192;
13
14/// System fonts for `<text>`, loaded once on first use.
15static FONTS: LazyLock<Arc<usvg::fontdb::Database>> = LazyLock::new(|| {
16 let mut db = usvg::fontdb::Database::new();
17 db.load_system_fonts();
18 Arc::new(db)
19});
20
21pub struct Svg {
22 tree: usvg::Tree,
23 /// Intrinsic size, rounded up to whole pixels.
24 size: [u32; 2],
25}
26
27pub fn decode(path: &Path, opts: &Options) -> anyhow::Result<DecodedImage> {
28 let data = std::fs::read(path)?;
29 let options = usvg::Options {
30 resources_dir: path.parent().map(Path::to_path_buf),
31 fontdb: FONTS.clone(),
32 ..Default::default()
33 };
34 let tree = usvg::Tree::from_data(&data, &options)?;
35 let s = tree.size();
36 let size = [
37 (s.width().ceil() as u32).max(1),
38 (s.height().ceil() as u32).max(1),
39 ];
40 let svg = Arc::new(Svg { tree, size });
41 // Never more pixels than the window needs to start with; zooming in re-rasterises.
42 let long = size[0].max(size[1]).min(opts.target.max(16));
43 Ok(svg.rasterize(long))
44}
45
46impl Svg {
47 /// Render with the longer side `long` pixels.
48 pub fn rasterize(self: &Arc<Self>, long: u32) -> DecodedImage {
49 let [w, h] = self.size;
50 let k = long.clamp(1, MAX_RASTER) as f32 / w.max(h) as f32;
51 let pw = ((w as f32 * k).round() as u32).max(1);
52 let ph = ((h as f32 * k).round() as u32).max(1);
53 let pixels = match tiny_skia::Pixmap::new(pw, ph) {
54 Some(mut pixmap) => {
55 let t =
56 tiny_skia::Transform::from_scale(pw as f32 / w as f32, ph as f32 / h as f32);
57 resvg::render(&self.tree, t, &mut pixmap.as_mut());
58 pixmap.take_demultiplied()
59 }
60 None => vec![0; pw as usize * ph as usize * 4],
61 };
62 let mut img = DecodedImage::still([pw, ph], pixels, "SVG");
63 img.source_size = self.size;
64 img.refine = Some(Refine::Svg(self.clone()));
65 img
66 }
67}
68
69#[cfg(test)]
70mod tests {
71 use super::*;
72
73 #[test]
74 fn rasterises_at_any_size() {
75 let dir = std::env::temp_dir().join(format!("remage-svg-{}", std::process::id()));
76 std::fs::create_dir_all(&dir).unwrap();
77 let path = dir.join("a.svg");
78 std::fs::write(
79 &path,
80 r#"<svg xmlns="http://www.w3.org/2000/svg" width="40" height="20">
81 <rect width="20" height="20" fill="red"/></svg>"#,
82 )
83 .unwrap();
84 let img = decode(&path, &Options::default()).unwrap();
85 assert_eq!((img.size, img.source_size), ([40, 20], [40, 20]));
86 assert_eq!(&img.pixels()[..4], [255, 0, 0, 255]);
87 // Transparent right half.
88 assert_eq!(img.pixels()[(30 * 4) + 3], 0);
89 let Some(Refine::Svg(svg)) = &img.refine else {
90 panic!("refinable")
91 };
92 let big = svg.rasterize(400);
93 assert_eq!((big.size, big.source_size), ([400, 200], [40, 20]));
94 let small = decode(
95 &path,
96 &Options {
97 target: 10,
98 ..Options::default()
99 },
100 )
101 .unwrap();
102 assert_eq!(small.size, [16, 8]);
103 }
104}