#![cfg_attr(feature = "parse", doc = "```no_run")]
#![cfg_attr(not(feature = "parse"), doc = "```ignore")]
use super::{Measure, PNG, declared_size, parse, texts};
use crate::Error;
use resvg::tiny_skia::{Pixmap, Transform};
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", serde(default, deny_unknown_fields))]
pub struct Options {
pub scale: u32,
pub pixels: Option<u64>,
}
impl Options {
pub const DEFAULT_SCALE: u32 = 2;
pub const DEFAULT_PIXELS: u64 = 1 << 26;
}
impl Default for Options {
fn default() -> Self {
Self {
scale: Self::DEFAULT_SCALE,
pixels: Some(Self::DEFAULT_PIXELS),
}
}
}
impl Options {
#[must_use]
pub fn with_scale(self, scale: u32) -> Self {
Self { scale, ..self }
}
#[must_use]
pub fn with_pixels(self, pixels: Option<u64>) -> Self {
Self { pixels, ..self }
}
}
pub fn from_svg(
svg: &str,
fonts: &[&[u8]],
options: &Options,
limits: &crate::Limits,
) -> Result<Vec<u8>, Error> {
let scale = options.scale.max(1);
let pixels_of = |(width, height): (u64, u64)| {
let side = |n: u64| n.saturating_mul(u64::from(scale));
(
side(width),
side(height),
side(width).saturating_mul(side(height)),
)
};
let too_large = |pixels| {
Error::Refused(crate::limits::Refusal::Pixels {
pixels,
limit: options.pixels.unwrap_or(u64::MAX),
})
};
let measure = Measure::of(svg)?;
let check = |pixels: u64| {
if options.pixels.is_some_and(|limit| pixels > limit) {
return Err(too_large(pixels));
}
let estimate = measure.estimate(&PNG, pixels);
match limits.memory_bytes {
Some(limit) if estimate > limit => {
Err(Error::Refused(crate::limits::Refusal::Memory {
phase: crate::limits::Phase::Render,
limit_bytes: limit,
needed_bytes: Some(estimate),
}))
}
_ => Ok(()),
}
};
let declared = declared_size(svg).map(|(w, h)| pixels_of((w.ceil() as u64, h.ceil() as u64)));
check(declared.map_or(0, |(_, _, pixels)| pixels))?;
let tree = parse(svg, fonts)?;
let size = tree.size().to_int_size();
let (width, height, pixels) = pixels_of((u64::from(size.width()), u64::from(size.height())));
check(pixels)?;
let fits = |n: u64| u32::try_from(n).ok();
let mut pixmap = fits(width)
.zip(fits(height))
.and_then(|(w, h)| Pixmap::new(w, h))
.ok_or_else(|| too_large(pixels))?;
let factor = scale as f32;
resvg::render(
&tree,
Transform::from_scale(factor, factor),
&mut pixmap.as_mut(),
);
let (title, description) = texts(svg);
encode(&pixmap, scale, title, description).map_err(|e| Error::RenderFailed {
message: e.to_string(),
})
}
fn encode(
pixmap: &Pixmap,
scale: u32,
title: Option<String>,
description: Option<String>,
) -> Result<Vec<u8>, png::EncodingError> {
let mut data = Vec::with_capacity(pixmap.data().len());
for pixel in pixmap.pixels() {
let colour = pixel.demultiply();
data.extend([colour.red(), colour.green(), colour.blue(), colour.alpha()]);
}
let mut bytes = Vec::new();
let mut encoder = png::Encoder::new(&mut bytes, pixmap.width(), pixmap.height());
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
encoder.set_source_srgb(png::SrgbRenderingIntent::Perceptual);
let density = u32::try_from((u64::from(scale) * 960_000 + 127) / 254).unwrap_or(u32::MAX);
encoder.set_pixel_dims(Some(png::PixelDimensions {
xppu: density,
yppu: density,
unit: png::Unit::Meter,
}));
for (keyword, text) in [("Title", title), ("Description", description)] {
if let Some(text) = text {
encoder.add_itxt_chunk(keyword.to_owned(), text)?;
}
}
let mut writer = encoder.write_header()?;
writer.write_image_data(&data)?;
writer.finish()?;
Ok(bytes)
}