use crate::common::geom::Rect;
use base64::Engine;
use hayro::vello_cpu::color::palette::css::{TRANSPARENT, WHITE};
use hayro::vello_cpu::{Pixmap, RasterizerSettings, RenderContext, Resources, TargetInit};
use hayro::{RenderCache, RenderSettings, render_into};
use hayro_interpret::InterpreterSettings;
use hayro_interpret::util::TransformExt;
use hayro_syntax::Pdf;
use kurbo::Affine;
use std::collections::{HashMap, HashSet};
pub const MAX_RASTER_PIXELS: u64 = 40_000_000;
pub(crate) const MAX_FILTERED_PIXELS: u64 = 10_000_000;
pub(crate) const MAX_SVG_TEXT_CHARS: u64 = 20_000;
pub(crate) const MAX_SVG_ELEMENTS: u64 = 1_000_000;
pub(crate) const MAX_SVG_PATH_BYTES: u64 = 64 * 1024 * 1024;
pub(crate) const MAX_SVG_NODES: u64 = 100_000;
pub(crate) const MAX_SVG_POINTS: u64 = 1_000_000;
pub(crate) const MAX_RASTER_SVG_POINTS: u64 = 10_000_000;
pub(crate) const MAX_SVG_FILTERS: usize = 16;
pub(crate) const MAX_SVG_BYTES: usize = 32 * 1024 * 1024;
const MAX_BITMAP_SIDE_PX: f32 = 6000.0;
const SVG_BACKGROUND: [u8; 4] = [255, 255, 255, 255];
const PNG_DATA_URI: &str = "data:image/png;base64,";
const JPEG_DATA_URI: &str = "data:image/jpeg;base64,";
const MIN_RECOMPRESS_LEN: usize = 200_000;
const MAX_IMAGE_SIDE_PX: u32 = 2600;
const JPEG_QUALITY: u8 = 88;
const PHOTO_MIN_PNG_BYTES: usize = 64_000;
const PHOTO_MIN_COLOURS: usize = 4096;
const GLYPH_USE_PREFIX: &str = "<use xlink:href=\"#";
const TRANSFORM_ATTR: &str = "transform=\"";
const GLYPH_DEF_PREFIX: &str = "<path id=\"";
const BLANK_GLYPH_SUFFIX: &str = " d=\"\"/>";
const PIXELATED_STYLE: &str = " style=\"image-rendering: pixelated\"";
const PIXELATED_MIN_PIXEL_PT: f64 = 1.0;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum PngCompression {
Fast,
#[default]
Balanced,
High,
}
impl PngCompression {
fn level(self) -> png::Compression {
match self {
Self::Fast => png::Compression::Fast,
Self::Balanced => png::Compression::Balanced,
Self::High => png::Compression::High,
}
}
}
fn encode_png(pixmap: Pixmap, compression: PngCompression) -> Option<Vec<u8>> {
if compression == PngCompression::Balanced {
return pixmap.into_png().ok();
}
let (width, height) = (u32::from(pixmap.width()), u32::from(pixmap.height()));
let (color, pixels) = match pixmap.try_take_rgb8(hayro::vello_cpu::peniko::ImageAlphaType::Alpha) {
hayro::vello_cpu::Pixels::Rgb8(pixels) => (png::ColorType::Rgb, pixels),
hayro::vello_cpu::Pixels::Rgba8(pixels) => (png::ColorType::Rgba, pixels),
};
let mut data = Vec::new();
let mut encoder = png::Encoder::new(&mut data, width, height);
encoder.set_color(color);
encoder.set_depth(png::BitDepth::Eight);
encoder.set_compression(compression.level());
let mut writer = encoder.write_header().ok()?;
writer.write_image_data(&pixels).ok()?;
writer.finish().ok()?;
Some(data)
}
pub struct PageRenderer<'a> {
pdf: &'a Pdf,
cache: RenderCache<'a>,
svg_cache: hayro_svg::RenderCache<'a>,
settings: InterpreterSettings,
png: PngCompression,
}
impl<'a> PageRenderer<'a> {
pub fn new(pdf: &'a Pdf) -> Self {
Self {
pdf,
cache: RenderCache::new(),
svg_cache: hayro_svg::RenderCache::new(),
settings: InterpreterSettings::default(),
png: PngCompression::default(),
}
}
#[must_use]
pub fn with_png_compression(mut self, compression: PngCompression) -> Self {
self.png = compression;
self
}
pub fn region_png(&self, page: usize, rect: Rect, scale: f32, transparent: bool) -> Option<(Vec<u8>, u32, u32)> {
let pixmap = self.region_pixmap(page, rect, scale, transparent)?;
let (width, height) = (u32::from(pixmap.width()), u32::from(pixmap.height()));
let png = encode_png(pixmap, self.png)?;
Some((png, width, height))
}
pub fn region_picture(&self, page: usize, rect: Rect, scale: f32, transparent: bool) -> Option<(Vec<u8>, bool)> {
let pixmap = self.region_pixmap(page, rect, scale, transparent)?;
let (width, height) = (u32::from(pixmap.width()), u32::from(pixmap.height()));
let rgba = (!transparent).then(|| pixmap.data_as_u8_slice().to_vec());
let png = encode_png(pixmap, self.png)?;
crate::common::cancel::check();
if let Some(rgba) = rgba
&& png.len() >= PHOTO_MIN_PNG_BYTES
&& many_colours(&rgba, PHOTO_MIN_COLOURS)
&& let Some(jpeg) = encode_jpeg(&rgba, width, height)
&& jpeg.len() * 2 < png.len()
{
return Some((jpeg, true));
}
Some((png, false))
}
fn region_pixmap(&self, page: usize, rect: Rect, scale: f32, transparent: bool) -> Option<Pixmap> {
let page = self.pdf.pages().get(page)?;
let (scale, width, height) = region_bitmap(rect, scale);
let (width_px, height_px) = (width as u16, height as u16);
let mut ctx = RenderContext::new(width_px, height_px);
let transform = Affine::scale(scale as f64)
* Affine::translate((-rect.x0 as f64, -rect.y0 as f64))
* page.initial_transform(true).to_kurbo();
render_into(
page,
&self.cache,
&self.settings,
&RenderSettings::default(),
&mut ctx,
transform,
);
crate::common::cancel::check();
ctx.flush();
crate::common::cancel::check();
let mut pixmap = Pixmap::new(width_px, height_px);
ctx.render_with(
&mut pixmap,
&mut Resources::default(),
RasterizerSettings {
target_init: TargetInit::Clear(if transparent { TRANSPARENT } else { WHITE }),
..Default::default()
},
);
crate::common::cancel::check();
Some(pixmap)
}
pub fn page_png(&self, page: usize, scale: f32) -> Option<(Vec<u8>, u32, u32)> {
let pdf_page = self.pdf.pages().get(page)?;
let (width, height) = pdf_page.render_dimensions();
self.region_png(page, Rect::new(0.0, 0.0, width, height), scale, false)
}
pub fn page_svg_without_text(&self, page: usize, remove: &dyn Fn(f32, f32) -> bool) -> Option<String> {
self.page_svg_without_glyphs(page, remove, false)
}
pub fn page_svg_without_all_text(&self, page: usize, remove: &dyn Fn(f32, f32) -> bool) -> Option<String> {
self.page_svg_without_glyphs(page, remove, true)
}
fn page_svg_without_glyphs(&self, page: usize, remove: &dyn Fn(f32, f32) -> bool, type3: bool) -> Option<String> {
let svg = self.page_svg(page)?;
let group_origins = if type3 {
group_glyph_origins(&svg)
} else {
HashMap::new()
};
let blank: HashSet<&str> = svg
.lines()
.filter(|line| line.trim_end().ends_with(BLANK_GLYPH_SUFFIX))
.filter_map(glyph_def)
.collect();
let mut dropped_lines = Vec::new();
let mut referenced: HashSet<&str> = HashSet::new();
for line in svg.lines() {
if let Some(&(x, y)) = group_use(line).and_then(|id| group_origins.get(id))
&& remove(x, y)
{
dropped_lines.push(true);
continue;
}
match glyph_use(line) {
Some((id, x, y)) if blank.contains(id) || remove(x, y) => dropped_lines.push(true),
Some((id, _, _)) => {
referenced.insert(id);
dropped_lines.push(false);
}
None => dropped_lines.push(false),
}
}
let mut out = String::with_capacity(svg.len() / 2);
for (line, dropped) in svg.lines().zip(dropped_lines) {
if dropped || glyph_def(line).is_some_and(|id| !referenced.contains(id)) {
continue;
}
out.push_str(line.trim_start());
out.push('\n');
}
Some(out)
}
pub fn page_svg(&self, page: usize) -> Option<String> {
let pdf_page = self.pdf.pages().get(page)?;
let svg = hayro_svg::convert(
pdf_page,
&self.svg_cache,
&self.settings,
&hayro_svg::SvgRenderSettings {
bg_color: SVG_BACKGROUND,
},
);
Some(smooth_fine_images(compact_images(svg)))
}
}
pub(crate) fn svg_fonts() -> std::sync::Arc<resvg::usvg::fontdb::Database> {
static FONTS: std::sync::OnceLock<std::sync::Arc<resvg::usvg::fontdb::Database>> = std::sync::OnceLock::new();
FONTS
.get_or_init(|| {
let mut fonts = resvg::usvg::fontdb::Database::new();
fonts.load_system_fonts();
if let Some(dirs) = std::env::var_os("KAKEMONO_FONT_DIRS") {
for dir in std::env::split_paths(&dirs) {
fonts.load_fonts_dir(dir);
}
}
let ids: Vec<_> = fonts.faces().map(|face| face.id).collect();
for id in ids {
unsafe {
fonts.make_shared_face_data(id);
}
}
fonts.set_serif_family("Liberation Serif");
fonts.set_sans_serif_family("Liberation Sans");
fonts.set_monospace_family("Liberation Mono");
std::sync::Arc::new(fonts)
})
.clone()
}
pub(crate) fn svg_options() -> resvg::usvg::Options<'static> {
use resvg::usvg;
usvg::Options {
fontdb: svg_fonts(),
image_href_resolver: usvg::ImageHrefResolver {
resolve_data: Box::new(|mime, data, options| {
let allowed = match declared_size(&data) {
Some(_) => within_pixel_cap(&data),
None => mime == "image/svg+xml" && super::svg::within_read_caps(&data),
};
allowed
.then(|| (usvg::ImageHrefResolver::default_data_resolver())(mime, data, options))
.flatten()
}),
resolve_string: Box::new(|_, _| None),
},
..Default::default()
}
}
pub(crate) fn plan_raster(tree: &resvg::usvg::Tree, scale: f32) -> Option<(f32, resvg::tiny_skia::IntSize)> {
let filters = tree.filters().len() as u64;
let budget = (MAX_RASTER_PIXELS / (1 + isolated_depth(tree.root()))).min(MAX_FILTERED_PIXELS / filters.max(1));
let base = tree.size().to_int_size();
let pixels = f64::from(base.width()) * f64::from(base.height()) * f64::from(scale).powi(2);
let scale = if pixels > budget as f64 {
(f64::from(scale) * (budget as f64 / pixels).sqrt() * 0.999) as f32
} else {
scale
};
let size = base.scale_by(scale)?;
if u64::from(size.width()) * u64::from(size.height()) > budget {
return None;
}
Some((scale, size))
}
pub fn svg_to_png(svg: &str, scale: f32) -> Option<Vec<u8>> {
let tree = resvg::usvg::Tree::from_str(svg, &svg_options()).ok()?;
png_of_tree(&tree, scale)
}
pub fn svg_to_png_in(svg: &str, scale: f32, resources: Option<&std::path::Path>) -> Result<Vec<u8>, String> {
let mut options = resvg::usvg::Options {
resources_dir: resources.map(std::path::Path::to_path_buf),
..svg_options()
};
if resources.is_some() {
options.image_href_resolver.resolve_string = resvg::usvg::ImageHrefResolver::default_string_resolver();
}
let tree = resvg::usvg::Tree::from_str(svg, &options).map_err(|err| err.to_string())?;
png_of_tree(&tree, scale).ok_or_else(|| "the picture is empty or too large to draw".to_string())
}
pub(crate) fn png_of_tree(tree: &resvg::usvg::Tree, scale: f32) -> Option<Vec<u8>> {
use resvg::tiny_skia;
let (scale, size) = plan_raster(tree, scale)?;
let mut pixmap = tiny_skia::Pixmap::new(size.width(), size.height())?;
pixmap.fill(tiny_skia::Color::WHITE);
resvg::render(
tree,
tiny_skia::Transform::from_scale(scale, scale),
&mut pixmap.as_mut(),
);
pixmap.encode_png().ok()
}
fn isolated_depth(group: &resvg::usvg::Group) -> u64 {
let inner = group
.children()
.iter()
.filter_map(|node| match node {
resvg::usvg::Node::Group(child) => Some(isolated_depth(child)),
_ => None,
})
.max()
.unwrap_or(0);
inner + u64::from(group.should_isolate())
}
pub fn within_pixel_cap(data: &[u8]) -> bool {
declared_size(data).is_none_or(|(width, height)| u64::from(width) * u64::from(height) <= MAX_RASTER_PIXELS)
}
pub fn declared_size(data: &[u8]) -> Option<(u32, u32)> {
if data.starts_with(b"\x89PNG\r\n\x1a\n") && data.get(12..16) == Some(b"IHDR") {
let side = |at: usize| {
data.get(at..at + 4)
.map(|bytes| u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
};
return Some((side(16)?, side(20)?));
}
if data.starts_with(b"RIFF") && data.get(8..12) == Some(b"WEBP") {
return webp_size(data);
}
let mut reader = image::ImageReader::new(std::io::Cursor::new(data))
.with_guessed_format()
.ok()?;
reader.no_limits();
reader.into_dimensions().ok()
}
fn webp_size(data: &[u8]) -> Option<(u32, u32)> {
let body = data.get(20..)?;
let le = |bytes: &[u8]| {
bytes
.iter()
.rev()
.fold(0u32, |value, &byte| (value << 8) | u32::from(byte))
};
match data.get(12..16)? {
b"VP8X" => Some((le(body.get(4..7)?) + 1, le(body.get(7..10)?) + 1)),
b"VP8L" => {
if *body.first()? != 0x2f {
return None;
}
let bits = le(body.get(1..5)?);
Some(((bits & 0x3fff) + 1, ((bits >> 14) & 0x3fff) + 1))
}
b"VP8 " => {
if body.get(3..6)? != [0x9d, 0x01, 0x2a] {
return None;
}
Some((le(body.get(6..8)?) & 0x3fff, le(body.get(8..10)?) & 0x3fff))
}
_ => None,
}
}
fn smooth_fine_images(svg: String) -> String {
if !svg.contains(PIXELATED_STYLE) {
return svg;
}
let mut out = String::with_capacity(svg.len());
for line in svg.split_inclusive('\n') {
let pixel_pt = line.contains(PIXELATED_STYLE).then(|| image_pixel_pt(line)).flatten();
match pixel_pt {
Some(size) if size < PIXELATED_MIN_PIXEL_PT => out.push_str(&line.replacen(PIXELATED_STYLE, "", 1)),
_ => out.push_str(line),
}
}
out
}
fn image_pixel_pt(line: &str) -> Option<f64> {
let rest = &line[line.find("<image ")?..];
let matrix = &rest[rest.find("matrix(")? + "matrix(".len()..];
let values: Vec<f64> = matrix[..matrix.find(')')?]
.split([' ', ','])
.filter(|value| !value.is_empty())
.map(str::parse)
.collect::<Result<_, _>>()
.ok()?;
let [x_scale, y_skew, x_skew, y_scale, ..] = values.as_slice() else {
return None;
};
Some((x_scale * y_scale - y_skew * x_skew).abs().sqrt())
}
fn glyph_use(line: &str) -> Option<(&str, f32, f32)> {
let trimmed = line.trim_start();
let rest = trimmed.strip_prefix(GLYPH_USE_PREFIX)?;
let id = &rest[..rest.find('"')?];
let transform = &rest[rest.find(TRANSFORM_ATTR)? + TRANSFORM_ATTR.len()..];
let transform = &transform[..transform.find('"')?];
let inner = transform
.strip_prefix("matrix(")
.or_else(|| transform.strip_prefix("translate("))?
.strip_suffix(')')?;
let nums: Vec<f32> = inner
.split([' ', ','])
.filter(|part| !part.is_empty())
.filter_map(|part| part.parse().ok())
.collect();
let n = nums.len();
(n >= 2).then(|| (id, nums[n - 2], nums[n - 1]))
}
fn group_glyph_origins(svg: &str) -> HashMap<&str, (f32, f32)> {
let mut origins = HashMap::new();
let mut lines = svg.lines().peekable();
while let Some(line) = lines.next() {
let Some(id) = line
.trim_start()
.strip_prefix("<g id=\"")
.and_then(|rest| rest.strip_suffix("\">"))
else {
continue;
};
let Some(child) = lines.peek().map(|child| child.trim_start()) else {
continue;
};
if !child.starts_with("<path ") {
continue;
}
if let Some(start) = child.find("transform=\"matrix(") {
let inner = &child[start + "transform=\"matrix(".len()..];
let nums: Vec<f32> = inner[..inner.find(')').unwrap_or(0)]
.split([' ', ','])
.filter_map(|part| part.parse().ok())
.collect();
if nums.len() == 6 {
origins.insert(id, (nums[4], nums[5]));
}
}
}
origins
}
fn group_use(line: &str) -> Option<&str> {
line.trim().strip_prefix("<use xlink:href=\"#")?.strip_suffix("\"/>")
}
fn glyph_def(line: &str) -> Option<&str> {
let rest = line.trim_start().strip_prefix(GLYPH_DEF_PREFIX)?;
let id = &rest[..rest.find('"')?];
(id.starts_with('g') && id[1..].chars().all(|ch| ch.is_ascii_digit()) && id.len() > 1).then_some(id)
}
fn compact_images(svg: String) -> String {
if !svg.contains(PNG_DATA_URI) {
return svg;
}
let engine = base64::engine::general_purpose::STANDARD;
let mut out = String::with_capacity(svg.len());
let mut rest = svg.as_str();
while let Some(pos) = rest.find(PNG_DATA_URI) {
let start = pos + PNG_DATA_URI.len();
let len = rest[start..].find('"').unwrap_or(rest.len() - start);
let payload = &rest[start..start + len];
let replacement = recompress_png(&engine, payload);
out.push_str(&rest[..pos]);
match replacement {
Some(jpeg) => {
out.push_str(JPEG_DATA_URI);
out.push_str(&engine.encode(jpeg));
}
None => {
out.push_str(PNG_DATA_URI);
out.push_str(payload);
}
}
rest = &rest[start + len..];
}
out.push_str(rest);
out
}
fn recompress_png(engine: &base64::engine::GeneralPurpose, payload: &str) -> Option<Vec<u8>> {
let len = payload.len();
(len >= MIN_RECOMPRESS_LEN)
.then(|| engine.decode(payload).ok())
.flatten()
.and_then(|png| image::load_from_memory_with_format(&png, image::ImageFormat::Png).ok())
.and_then(|img| {
if img.color().has_alpha() && img.to_rgba8().pixels().any(|pixel| pixel.0[3] != 255) {
return None;
}
let img = if img.width().max(img.height()) > MAX_IMAGE_SIDE_PX {
img.resize(
MAX_IMAGE_SIDE_PX,
MAX_IMAGE_SIDE_PX,
image::imageops::FilterType::Triangle,
)
} else {
img
};
let mut jpeg = Vec::new();
let encoder = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, JPEG_QUALITY);
img.to_rgb8().write_with_encoder(encoder).ok()?;
Some(jpeg)
})
.filter(|jpeg| jpeg.len() * 4 / 3 < len)
}
fn many_colours(rgba: &[u8], min: usize) -> bool {
let mut seen = vec![0u64; (1 << 24) / 64];
let mut count = 0usize;
for pixel in rgba.as_chunks::<4>().0 {
let colour = (usize::from(pixel[0]) << 16) | (usize::from(pixel[1]) << 8) | usize::from(pixel[2]);
let (word, bit) = (colour / 64, 1u64 << (colour % 64));
if seen[word] & bit == 0 {
seen[word] |= bit;
count += 1;
if count >= min {
return true;
}
}
}
false
}
fn encode_jpeg(rgba: &[u8], width: u32, height: u32) -> Option<Vec<u8>> {
let rgb: Vec<u8> = rgba
.as_chunks::<4>()
.0
.iter()
.flat_map(|pixel| [pixel[0], pixel[1], pixel[2]])
.collect();
let mut jpeg = Vec::new();
image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, JPEG_QUALITY)
.encode(&rgb, width, height, image::ExtendedColorType::Rgb8)
.ok()?;
Some(jpeg)
}
pub fn region_bitmap(rect: Rect, scale: f32) -> (f32, u32, u32) {
let scale = scale
.min(MAX_BITMAP_SIDE_PX / rect.width().max(1.0))
.min(MAX_BITMAP_SIDE_PX / rect.height().max(1.0));
let width = (rect.width() * scale).ceil().max(1.0) as u32;
let height = (rect.height() * scale).ceil().max(1.0) as u32;
(scale, width, height)
}
#[cfg(test)]
mod smoothing_tests {
use super::smooth_fine_images;
#[test]
fn fine_pictures_are_smoothed_and_coarse_ones_stay_sharp() {
let line = |scale: f64| {
format!(
"<image transform=\"matrix({scale} 0 0 {scale} 10 20)\" xlink:href=\"data:image/png;base64,AAAA\" \
width=\"484\" height=\"209\" preserveAspectRatio=\"none\" style=\"image-rendering: pixelated\"/>\n"
)
};
assert!(!smooth_fine_images(line(0.588843)).contains("pixelated"));
assert!(smooth_fine_images(line(1.8)).contains("pixelated"));
}
}
#[cfg(test)]
mod svg_tests {
use super::{MAX_RASTER_PIXELS, declared_size, svg_to_png, within_pixel_cap};
fn pixels(png: &[u8]) -> u64 {
let (width, height) = declared_size(png).unwrap();
u64::from(width) * u64::from(height)
}
#[test]
fn nested_groups_drawn_apart_share_the_cap() {
let open = r#"<g opacity="0.9">"#.repeat(30);
let close = "</g>".repeat(30);
let svg = format!(
r#"<svg xmlns="http://www.w3.org/2000/svg" width="30000" height="30000">{open}<rect width="30000" height="30000" fill="red"/>{close}</svg>"#
);
let png = svg_to_png(&svg, 2.0).expect("drawn smaller");
assert!(pixels(&png) * 31 <= MAX_RASTER_PIXELS, "{} pixels", pixels(&png));
}
#[test]
fn a_thin_svg_counts_its_rounded_pixels() {
let svg = r#"<svg xmlns="http://www.w3.org/2000/svg" width="200000000" height="0.01"><rect width="10" height="10"/></svg>"#;
assert!(svg_to_png(svg, 2.0).is_none_or(|png| pixels(&png) <= MAX_RASTER_PIXELS));
}
fn webp_headers(width: u32, height: u32) -> [Vec<u8>; 3] {
let riff = |chunk: &[u8], body: &[u8]| {
let mut data = b"RIFF\0\0\0\0WEBP".to_vec();
data.extend(chunk);
data.extend((body.len() as u32).to_le_bytes());
data.extend(body);
data
};
let (wide, high) = (width - 1, height - 1);
let mut extended = vec![0u8; 4];
extended.extend(&wide.to_le_bytes()[..3]);
extended.extend(&high.to_le_bytes()[..3]);
let mut lossless = vec![0x2f];
lossless.extend((wide | (high << 14)).to_le_bytes());
let mut lossy = vec![0x10, 0x02, 0x00, 0x9d, 0x01, 0x2a];
lossy.extend((width as u16).to_le_bytes());
lossy.extend((height as u16).to_le_bytes());
[
riff(b"VP8X", &extended),
riff(b"VP8L", &lossless),
riff(b"VP8 ", &lossy),
]
}
#[test]
fn the_size_of_a_webp_picture_is_read() {
for header in webp_headers(16_383, 9_000) {
assert_eq!(declared_size(&header), Some((16_383, 9_000)));
}
}
#[test]
fn an_svg_draws_only_pictures_it_can_size_within_the_cap() {
let [_, lossless, _] = webp_headers(16_383, 16_383);
assert!(!within_pixel_cap(&lossless));
let [_, small, _] = webp_headers(100, 100);
assert!(within_pixel_cap(&small));
}
#[test]
fn a_huge_svg_is_drawn_within_the_pixel_cap() {
let svg = r#"<svg xmlns="http://www.w3.org/2000/svg" width="30000" height="30000"><rect width="10" height="10"/></svg>"#;
let png = svg_to_png(svg, 2.0).expect("drawn smaller");
let (width, height) = image::ImageReader::new(std::io::Cursor::new(&png))
.with_guessed_format()
.unwrap()
.into_dimensions()
.unwrap();
assert!(
u64::from(width) * u64::from(height) <= MAX_RASTER_PIXELS,
"{width}x{height}"
);
assert!(width > 1000 && width == height, "{width}x{height}");
}
}