1use crate::{AssetSource, DevicePixels, IsZero, Result, SharedString, Size};
2use anyhow::anyhow;
3use resvg::tiny_skia::Pixmap;
4use std::{hash::Hash, sync::Arc};
5
6#[derive(Clone, PartialEq, Hash, Eq)]
7pub(crate) struct RenderSvgParams {
8 pub(crate) path: SharedString,
9 pub(crate) size: Size<DevicePixels>,
10}
11
12#[derive(Clone)]
13pub struct SvgRenderer {
14 asset_source: Arc<dyn AssetSource>,
15}
16
17pub enum SvgSize {
18 Size(Size<DevicePixels>),
19 ScaleFactor(f32),
20}
21
22impl SvgRenderer {
23 pub fn new(asset_source: Arc<dyn AssetSource>) -> Self {
24 Self { asset_source }
25 }
26
27 pub(crate) fn render(&self, params: &RenderSvgParams) -> Result<Option<Vec<u8>>> {
28 if params.size.is_zero() {
29 return Err(anyhow!("can't render at a zero size"));
30 }
31
32 // Load the tree.
33 let Some(bytes) = self.asset_source.load(¶ms.path)? else {
34 return Ok(None);
35 };
36
37 let pixmap = self.render_pixmap(&bytes, SvgSize::Size(params.size))?;
38
39 // Convert the pixmap's pixels into an alpha mask.
40 let alpha_mask = pixmap
41 .pixels()
42 .iter()
43 .map(|p| p.alpha())
44 .collect::<Vec<_>>();
45 Ok(Some(alpha_mask))
46 }
47
48 pub fn render_pixmap(&self, bytes: &[u8], size: SvgSize) -> Result<Pixmap, usvg::Error> {
49 let tree = usvg::Tree::from_data(bytes, &usvg::Options::default())?;
50
51 let size = match size {
52 SvgSize::Size(size) => size,
53 SvgSize::ScaleFactor(scale) => crate::size(
54 DevicePixels((tree.size().width() * scale) as i32),
55 DevicePixels((tree.size().height() * scale) as i32),
56 ),
57 };
58
59 // Render the SVG to a pixmap with the specified width and height.
60 let mut pixmap = resvg::tiny_skia::Pixmap::new(size.width.into(), size.height.into())
61 .ok_or(usvg::Error::InvalidSize)?;
62
63 let scale = size.width.0 as f32 / tree.size().width();
64 let transform = resvg::tiny_skia::Transform::from_scale(scale, scale);
65
66 resvg::render(&tree, transform, &mut pixmap.as_mut());
67
68 Ok(pixmap)
69 }
70}