Use craft-svg for SVG sniffing, SVGZ and the draw-memory check; resvg 0.48

This commit is contained in:
Dylan M. Taylor committed 2026-11-12 02:29:28 +00:00
1 parent 2a4e0f4c99
commit 794532f564
5 files changed
+171 -558

No files matched your search

Generated
+139 -105
View File
@@ -1376,15 +1376,6 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48"
[[package]]
name = "core_maths"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30"
dependencies = [
"libm",
]
[[package]]
name = "cpufeatures"
version = "0.2.17"
@@ -1483,12 +1474,25 @@ dependencies = [
"craft-winprint-gdi",
"log",
"miniz_oxide 0.9.1",
"roxmltree 0.21.1",
"roxmltree 0.21.2",
"tempfile",
"winprint",
"winsafe",
]
[[package]]
name = "craft-svg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=55d120f201771acbb32b2cf122d4a6dc82593a57#55d120f201771acbb32b2cf122d4a6dc82593a57"
dependencies = [
"craft-xml",
"flate2",
"kurbo 0.13.1",
"roxmltree 0.21.2",
"thiserror 2.0.21",
"usvg 0.48.1",
]
[[package]]
name = "craft-ui"
version = "0.1.0"
@@ -1545,6 +1549,15 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=55d120f201771acbb32b2cf122d4a6dc82593a57#55d120f201771acbb32b2cf122d4a6dc82593a57"
dependencies = [
"quick-xml 0.41.0",
"thiserror 2.0.21",
]
[[package]]
name = "crc32fast"
version = "1.5.3"
@@ -2008,7 +2021,7 @@ dependencies = [
"itertools 0.15.0",
"log",
"profiling",
"resvg",
"resvg 0.45.1",
]
[[package]]
@@ -2441,15 +2454,14 @@ dependencies = [
[[package]]
name = "fontdb"
version = "0.23.0"
version = "0.24.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "457e789b3d1202543297a350643cf459f836cade38934e7a4cf6a39e7cde2905"
checksum = "2660c5e9157bf76d2db1294e4a9feba604ef610819a3b591088d0d8392a3290f"
dependencies = [
"fontconfig-parser",
"log",
"slotmap",
"tinyvec",
"ttf-parser",
]
[[package]]
@@ -2467,7 +2479,7 @@ dependencies = [
"objc2-foundation 0.3.2",
"parlance",
"read-fonts 0.41.0",
"roxmltree 0.21.1",
"roxmltree 0.21.2",
"smallvec",
"windows",
"windows-core",
@@ -2720,16 +2732,6 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "gif"
version = "0.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae047235e33e2829703574b54fdec96bfbad892062d97fed2f76022287de61b"
dependencies = [
"color_quant",
"weezl",
]
[[package]]
name = "gif"
version = "0.14.2"
@@ -3057,7 +3059,7 @@ dependencies = [
"rustc-hash 2.1.3",
"smallvec",
"stringprep",
"zune-jpeg 0.5.15",
"zune-jpeg",
]
[[package]]
@@ -3479,7 +3481,7 @@ dependencies = [
"bytemuck",
"byteorder-lite",
"color_quant",
"gif 0.14.2",
"gif",
"moxcms",
"num-traits",
"png 0.18.1",
@@ -3487,8 +3489,8 @@ dependencies = [
"ravif",
"rgb",
"tiff",
"zune-core 0.5.3",
"zune-jpeg 0.5.15",
"zune-core",
"zune-jpeg",
]
[[package]]
@@ -3507,6 +3509,12 @@ version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "edcd27d72f2f071c64249075f42e205ff93c9a4c5f6c6da53e79ed9f9832c285"
[[package]]
name = "imagesize"
version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65b27460c2c92b037f3f94c538ed9a3342f3fdf923606781629ccb35f82d042a"
[[package]]
name = "imgref"
version = "1.12.3"
@@ -5359,10 +5367,10 @@ dependencies = [
"photocraft-tablet",
"photocraft-ui-egui",
"plist",
"resvg",
"resvg 0.45.1",
"rfd",
"ron",
"roxmltree 0.21.1",
"roxmltree 0.21.2",
"rustix 1.1.5",
"serde",
"serde_json",
@@ -5488,8 +5496,8 @@ dependencies = [
"serde_json",
"thiserror 2.0.21",
"tiff",
"zune-core 0.5.3",
"zune-jpeg 0.5.15",
"zune-core",
"zune-jpeg",
"zune-jpegxl",
]
@@ -5559,7 +5567,7 @@ dependencies = [
"photocraft-text",
"photocraft-vector",
"rayon",
"roxmltree 0.21.1",
"roxmltree 0.21.2",
"same-file",
"semver",
"serde",
@@ -5630,9 +5638,10 @@ dependencies = [
"blake3",
"craft-docpath",
"craft-pdf",
"craft-svg",
"crc32fast",
"flate2",
"imagesize",
"imagesize 0.13.0",
"kurbo 0.13.1",
"lopdf",
"miniz_oxide 0.9.1",
@@ -5653,13 +5662,13 @@ dependencies = [
"photocraft-text",
"photocraft-vector",
"proptest",
"resvg",
"roxmltree 0.21.1",
"resvg 0.48.1",
"roxmltree 0.21.2",
"serde_json",
"thiserror 2.0.21",
"tiff",
"ttf-parser",
"zune-core 0.5.3",
"zune-core",
"zune-jpegxl",
]
@@ -5742,8 +5751,8 @@ dependencies = [
"photocraft-raw",
"png 0.18.1",
"rayon",
"zune-core 0.5.3",
"zune-jpeg 0.5.15",
"zune-core",
"zune-jpeg",
"zune-jpegxl",
]
@@ -6683,15 +6692,30 @@ version = "0.45.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a8928798c0a55e03c9ca6c4c6846f76377427d2c1e1f7e6de3c06ae57942df43"
dependencies = [
"gif 0.13.3",
"log",
"pico-args",
"rgb",
"svgtypes 0.15.3",
"tiny-skia 0.11.4",
"usvg 0.45.1",
]
[[package]]
name = "resvg"
version = "0.48.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67e3803f97b999e80cbf7c6ecdd07a8102204d92e1633cf48783720c521196bd"
dependencies = [
"bytemuck",
"gif",
"image-webp",
"log",
"pico-args",
"rgb",
"svgtypes",
"tiny-skia",
"usvg",
"zune-jpeg 0.4.21",
"svgtypes 0.16.2",
"tiny-skia 0.12.0",
"usvg 0.48.1",
"zune-jpeg",
]
[[package]]
@@ -6809,9 +6833,9 @@ checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97"
[[package]]
name = "roxmltree"
version = "0.21.1"
version = "0.21.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1964b10c76125c36f8afe190065a4bf9a87bf324842c05701330bba9f1cacbb"
checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907"
dependencies = [
"memchr",
]
@@ -6982,24 +7006,6 @@ dependencies = [
"wait-timeout",
]
[[package]]
name = "rustybuzz"
version = "0.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd3c7c96f8a08ee34eff8857b11b49b07d71d1c3f4e88f8a88d4c9e9f90b1702"
dependencies = [
"bitflags 2.13.2",
"bytemuck",
"core_maths",
"log",
"smallvec",
"ttf-parser",
"unicode-bidi-mirroring",
"unicode-ccc",
"unicode-properties",
"unicode-script",
]
[[package]]
name = "ruzstd"
version = "0.9.1"
@@ -7085,7 +7091,7 @@ checksum = "b6277f0217056f77f1d8f49f2950ac6c278c0d607c45f5ee99328d792ede24ec"
dependencies = [
"log",
"smithay-client-toolkit 0.19.2",
"tiny-skia",
"tiny-skia 0.11.4",
]
[[package]]
@@ -7741,6 +7747,16 @@ dependencies = [
"siphasher",
]
[[package]]
name = "svgtypes"
version = "0.16.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f12b12995e3638c70618c1facb1ce65302f6a6f706b675f07c58a5d7391120e"
dependencies = [
"kurbo 0.13.1",
"siphasher",
]
[[package]]
name = "syn"
version = "1.0.109"
@@ -7943,7 +7959,7 @@ dependencies = [
"half",
"quick-error 2.0.1",
"weezl",
"zune-jpeg 0.5.15",
"zune-jpeg",
]
[[package]]
@@ -7988,7 +8004,22 @@ dependencies = [
"cfg-if",
"log",
"png 0.17.16",
"tiny-skia-path",
"tiny-skia-path 0.11.4",
]
[[package]]
name = "tiny-skia"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47ffee5eaaf5527f630fb0e356b90ebdec84d5d18d937c5e440350f88c5a91ea"
dependencies = [
"arrayref",
"arrayvec",
"bytemuck",
"cfg-if",
"log",
"png 0.18.1",
"tiny-skia-path 0.12.0",
]
[[package]]
@@ -8002,6 +8033,17 @@ dependencies = [
"strict-num",
]
[[package]]
name = "tiny-skia-path"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "edca365c3faccca67d06593c5980fa6c57687de727a03131735bb85f01fdeeb9"
dependencies = [
"arrayref",
"bytemuck",
"strict-num",
]
[[package]]
name = "tinystr"
version = "0.8.4"
@@ -8271,9 +8313,6 @@ name = "ttf-parser"
version = "0.25.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31"
dependencies = [
"core_maths",
]
[[package]]
name = "twox-hash"
@@ -8331,18 +8370,6 @@ version = "0.3.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5"
[[package]]
name = "unicode-bidi-mirroring"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5dfa6e8c60bb66d49db113e0125ee8711b7647b5579dc7f5f19c42357ed039fe"
[[package]]
name = "unicode-ccc"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce61d488bcdc9bc8b5d1772c404828b17fc481c0a582b5581e95fb233aef503e"
[[package]]
name = "unicode-general-category"
version = "1.1.0"
@@ -8456,18 +8483,40 @@ dependencies = [
"base64 0.22.1",
"data-url",
"flate2",
"fontdb",
"imagesize",
"imagesize 0.13.0",
"kurbo 0.11.3",
"log",
"pico-args",
"roxmltree 0.20.0",
"rustybuzz",
"simplecss",
"siphasher",
"strict-num",
"svgtypes",
"tiny-skia-path",
"svgtypes 0.15.3",
"tiny-skia-path 0.11.4",
"xmlwriter",
]
[[package]]
name = "usvg"
version = "0.48.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "977d0a4abdef933f424a99fe09f95576e089b90aebc6f016a3bc813762493e91"
dependencies = [
"base64 0.23.1",
"data-url",
"fontdb",
"harfrust",
"imagesize 0.15.0",
"kurbo 0.13.1",
"log",
"pico-args",
"roxmltree 0.21.2",
"simplecss",
"siphasher",
"skrifa 0.44.0",
"strict-num",
"svgtypes 0.16.2",
"tiny-skia-path 0.12.0",
"unicode-bidi",
"unicode-script",
"unicode-vo",
@@ -10038,12 +10087,6 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
[[package]]
name = "zune-core"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f423a2c17029964870cfaabb1f13dfab7d092a62a29a89264f4d36990ca414a"
[[package]]
name = "zune-core"
version = "0.5.3"
@@ -10059,22 +10102,13 @@ dependencies = [
"simd-adler32",
]
[[package]]
name = "zune-jpeg"
version = "0.4.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29ce2c8a9384ad323cf564b67da86e21d3cfdff87908bc1223ed5c99bc792713"
dependencies = [
"zune-core 0.4.12",
]
[[package]]
name = "zune-jpeg"
version = "0.5.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"
dependencies = [
"zune-core 0.5.3",
"zune-core",
]
[[package]]
@@ -10083,7 +10117,7 @@ version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cba11ecd07cc23351500e840ae03841b7e4997923ec8e4832ee3ae199ea0b6b4"
dependencies = [
"zune-core 0.5.3",
"zune-core",
]
[[package]]
+2
View File
@@ -39,6 +39,8 @@ photocraft-tablet = { path = "crates/tablet" }
photocraft-ipp = { path = "crates/ipp" }
# external
# SVG: sniffing, SVGZ and the checks around usvg (craft-libs#937).
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "55d120f201771acbb32b2cf122d4a6dc82593a57" }
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" }
# HEIC/HEIF: the shared decoder (replaces crates/heif; craft-libs#784).
craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "081078bb1b44aeedfa5bef3d4f13d978dc77510a" }
+7 -5
View File
@@ -41,17 +41,19 @@ thiserror = { workspace = true }
ttf-parser = "0.25.1"
serde_json = { workspace = true }
blake3 = { version = "1.8", default-features = false, features = ["pure"] }
# svg.rs inflates `.svgz` itself (with a size cap) so the XML can be checked before it is parsed;
# pdn.rs inflates Paint.NET's gzip pixel chunks.
flate2 = { workspace = true }
# ora.rs reads OpenRaster's stack.xml (already in the tree through usvg).
roxmltree = "0.21"
# Reuse usvg's locked header reader to bound embedded SVG raster data before decoding.
imagesize = "0.13"
# SVG import (svg.rs): usvg parses, resvg rasterises what the shape model can't hold. Both are
# already in the tree through the UI's icon loader; text shaping needs the fonts feature set.
# SVG sniffing, SVGZ unpacking and the draw-memory check (craft-libs' craft-svg with its `tree` feature:
# the usvg every Craft app shares).
craft-svg = { workspace = true, features = ["tree"] }
# SVG import (svg.rs): usvg parses, resvg rasterises what the shape model can't hold. resvg 0.48
# is the version craft-svg's usvg (=0.48.1) belongs to; text shaping needs the fonts feature set.
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
resvg = { version = "0.45", default-features = false, features = ["text", "system-fonts", "raster-images"] }
resvg = { version = "0.48", default-features = false, features = ["text", "system-fonts", "raster-images"] }
# The SVG fallback font search keeps each font file's character map (already in the tree through usvg).
ttf-parser = { version = "0.25", default-features = false }
# PDF import (pdf_import.rs): craft-pdf rasterizes pages in pure Rust; no shared library ships.
@@ -61,7 +63,7 @@ craft-pdf = { workspace = true }
kurbo = { version = "0.13", optional = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
resvg = { version = "0.45", default-features = false, features = ["text", "raster-images"] }
resvg = { version = "0.48", default-features = false, features = ["text", "raster-images"] }
[dev-dependencies]
lopdf = { version = "0.38", default-features = false }
+23 -23
View File
@@ -24,7 +24,19 @@ use resvg::usvg;
use crate::{ImportResult, IoError};
mod limits;
/// Hard caps on the memory resvg needs to draw a subtree, checked before it draws: craft-svg's
/// `tree::draw`, within this crate's peak pixel budget.
mod limits {
use resvg::{tiny_skia, usvg};
pub(super) use craft_svg::tree::draw::Refusal;
#[cfg(test)]
pub(super) use craft_svg::tree::draw::px;
pub(super) fn check(nodes: &[usvg::Node], ts: tiny_skia::Transform, w: u32, h: u32, held: u64) -> Result<(), Refusal> {
craft_svg::tree::draw::check(nodes, ts, w, h, held, super::MAX_PEAK_PIXEL_BYTES)
}
}
/// Largest canvas side an SVG opens at; a larger drawing is scaled down to fit.
pub const MAX_SIDE: u32 = 16_384;
@@ -134,14 +146,9 @@ const PARSER_STACK_BYTES: usize = 8 << 20;
pub const MAX_INFLATED_BYTES: u64 = 128 << 20;
/// Does this look like an SVG document (plain XML; `.svgz` is recognised by its extension)?
/// The first element must be `<svg`, after nothing but a prolog (craft-svg's sniff).
pub fn is_svg(bytes: &[u8]) -> bool {
let head = bytes.get(..bytes.len().min(4096)).unwrap_or(bytes);
let text = String::from_utf8_lossy(head);
let t = text.trim_start_matches('\u{feff}').trim_start();
if t.starts_with("<svg") {
return true;
}
(t.starts_with("<?xml") || t.starts_with("<!DOCTYPE") || t.starts_with("<!--")) && t.contains("<svg")
craft_svg::sniff::is_svg(bytes)
}
/// The fonts text runs are shaped with: the bundled craft fonts plus, on the desktop, the
@@ -966,22 +973,15 @@ fn inflate(bytes: &[u8]) -> Result<std::borrow::Cow<'_, [u8]>, IoError> {
inflate_with_limit(bytes, MAX_INFLATED_BYTES)
}
/// [`inflate`] with an explicit `limit`, which also applies to uncompressed input.
/// [`inflate`] with an explicit `limit`, which also applies to uncompressed input. gzip members
/// one after another are one file (craft-svg's `svgz`).
fn inflate_with_limit(bytes: &[u8], limit: u64) -> Result<std::borrow::Cow<'_, [u8]>, IoError> {
use std::io::Read;
if !bytes.starts_with(&[0x1f, 0x8b]) {
if u64::try_from(bytes.len()).unwrap_or(u64::MAX) > limit {
return Err(IoError::Svg(format!("the SVG exceeds the {limit} byte limit")));
}
return Ok(std::borrow::Cow::Borrowed(bytes));
}
let mut out = Vec::new();
let mut reader = flate2::bufread::MultiGzDecoder::new(bytes).take(limit.saturating_add(1));
reader.read_to_end(&mut out).map_err(|e| IoError::Svg(format!("the compressed SVG couldn't be inflated: {e}")))?;
if u64::try_from(out.len()).unwrap_or(u64::MAX) > limit {
return Err(IoError::Svg(format!("the compressed SVG inflates past {} MB", limit >> 20)));
}
Ok(std::borrow::Cow::Owned(out))
let limit = usize::try_from(limit).unwrap_or(usize::MAX);
craft_svg::svgz::inflate(bytes, limit).map_err(|e| match e {
craft_svg::svgz::Error::TooLarge(_) if !bytes.starts_with(&[0x1f, 0x8b]) => IoError::Svg(format!("the SVG exceeds the {limit} byte limit")),
craft_svg::svgz::Error::TooLarge(_) => IoError::Svg(format!("the compressed SVG inflates past {} MB", limit >> 20)),
e => IoError::Svg(format!("the compressed SVG couldn't be inflated: {e}")),
})
}
/// The deepest element nesting in `xml`, stopping as soon as it passes `limit` (the result is
-425
View File
@@ -1,425 +0,0 @@
//! Hard caps on the memory resvg needs to draw a subtree, checked before it draws.
//!
//! [`super::MAX_RASTER_PIXELS`] bounds the target pixmap only. While it draws, resvg also
//! allocates, and a failed allocation aborts the process rather than returning an error:
//! - a layer for every isolated group (opacity, blend mode, clip, mask, filter), clamped to 5 × 5
//! times the target, and one more per link of a clip-path chain, per clip child that has its own
//! clip-path, and per link of a mask-on-mask chain;
//! - for a filter, a result per primitive (all kept until the filter ends) and a clone of the layer.
//! The filter region is NOT clamped: `x`, `y`, `width` and `height` in the file set the size;
//! - a pattern tile of `width × height × scale`;
//! - for an embedded SVG image or an `feImage`, a pixmap of the current layer or filter region with
//! a nested drawing inside.
//!
//! The checks are worst-case products, not a model of resvg's phases. A node is checked against
//! the layers of its ancestors (which are alive while it is drawn) and nothing else, and each
//! shared definition is walked once per size class, so the walk is linear in the file.
use std::collections::HashMap;
use resvg::tiny_skia;
use resvg::usvg;
use super::MAX_PEAK_PIXEL_BYTES;
/// Bytes of RGBA8 buffers alive at once that a drawing may need: the existing 1.5 GiB peak budget.
/// A 24 MP target (96 MB) leaves room for about 14 more full-canvas layers.
const BUDGET: f64 = MAX_PEAK_PIXEL_BYTES as f64;
/// Filter primitives per filter. A result of every primitive is kept; real filters have 1 to 12
/// (Inkscape's drop shadow has 5), and 64 leaves headroom for generated ones.
const MAX_PRIMITIVES: usize = 64;
/// Links of one clip-path chain, mask-on-mask chain or nested clip children with their own
/// clip-path. Each link keeps a layer-sized buffer alive while the next is applied; real files use
/// one or two, and 16 layers of a 24 MP canvas (1.5 GiB) is the whole budget anyway.
const MAX_LINKS: usize = 16;
/// Patterns drawn inside patterns. Each tile is alive while the inner one is drawn.
const MAX_PATTERN_DEPTH: usize = 8;
/// Embedded SVG images inside embedded SVG images: the parser's own limit. Each draws on a pixmap
/// of the enclosing layer, which the live-bytes check charges, so deep chains of small images are
/// harmless and chains of big ones stop at the budget long before this.
const MAX_IMAGE_DEPTH: usize = super::MAX_EMBEDDED_SVG_DEPTH;
/// Nested isolated groups, patterns, embedded images and filter images followed. It keeps this
/// walk, and resvg's own recursion, far from a stack overflow; real drawings stay under a few dozen.
const MAX_DEPTH: usize = 200;
/// Nested groups of any kind. usvg expands `<use>` chains up to its own 1024-level limit, possibly
/// two groups per level; resvg recurses three frames per level too, so a walk that stops here is
/// lighter on the stack than the drawing it guards.
const MAX_NEST: usize = 2_100;
/// Nodes the walk visits before it gives up as too complex to check. A node costs a few
/// nanoseconds, so this bounds the walk to well under a second.
const MAX_NODES: usize = 2_000_000;
/// Why a drawing was not drawn.
#[derive(Debug)]
pub(super) struct Refusal {
/// Too many elements to check, rather than too much memory.
pub(super) complex: bool,
/// Over the memory budget, as opposed to a nesting, chain or element-count cap.
pub(super) memory: bool,
pub(super) message: String,
}
fn mib(bytes: f64) -> String {
if bytes < 1e15 { format!("about {} MiB", (bytes / 1_048_576.0).ceil()) } else { "an enormous amount of memory".to_string() }
}
fn memory(what: &str, bytes: f64) -> Refusal {
let limit = MAX_PEAK_PIXEL_BYTES >> 20;
Refusal { complex: false, memory: true, message: format!("{what} needs {}, over the {limit} MiB limit", mib(bytes)) }
}
fn limit(what: &str, value: usize) -> Refusal {
Refusal { complex: false, memory: false, message: format!("{what} (limit {value})") }
}
/// A pixel count that is never NaN: unknown sizes count as unbounded.
pub(super) fn px(v: f64) -> f64 {
if v.is_nan() { f64::INFINITY } else { v }
}
/// What is alive where a node is drawn.
#[derive(Clone, Copy)]
struct Cx {
/// Bytes held by the target and the layers of the ancestors.
live: f64,
/// Pixels of the pixmap being drawn on.
layer: f64,
/// Pixels of the largest group layer resvg makes in it (5 × 5 times its first target).
cap: f64,
/// Nested layers (isolated groups, patterns, embedded images, filter images).
depth: usize,
patterns: usize,
images: usize,
/// Nested groups of any kind: resvg and this walk recurse once per level.
nest: usize,
}
/// What a subtree needs, relative to what is alive where it starts. A shared definition is walked
/// once per transform and size, and every later reference re-checks its profile against where it
/// is used, so nothing is skipped and the walk stays linear.
#[derive(Clone, Copy, Default)]
struct Profile {
/// Most bytes it holds beyond the incoming live bytes.
extra: f64,
/// Most extra levels of nested layers, patterns, embedded images and groups below it.
depth: usize,
patterns: usize,
images: usize,
nest: usize,
}
impl Profile {
fn max(self, o: Self) -> Self {
Self {
extra: self.extra.max(o.extra),
depth: self.depth.max(o.depth),
patterns: self.patterns.max(o.patterns),
images: self.images.max(o.images),
nest: self.nest.max(o.nest),
}
}
/// This profile seen from a parent that adds `bytes` and one level of each kind in `levels`
/// (layers, patterns, images, groups).
fn under(self, bytes: f64, levels: [usize; 4]) -> Self {
Self {
extra: self.extra + bytes,
depth: self.depth + levels[0],
patterns: self.patterns + levels[1],
images: self.images + levels[2],
nest: self.nest + levels[3],
}
}
}
/// A shared definition at one linear transform, layer size and clamp.
type Key = (usize, [u32; 4], u64, u64);
fn key(ptr: usize, ts: tiny_skia::Transform, cx: Cx) -> Key {
(ptr, [ts.sx.to_bits(), ts.kx.to_bits(), ts.ky.to_bits(), ts.sy.to_bits()], cx.layer.to_bits(), cx.cap.to_bits())
}
struct Walk {
visited: usize,
shared: HashMap<Key, Profile>,
clips: HashMap<usize, usize>,
masks: HashMap<usize, usize>,
}
/// Check that drawing `nodes` at `ts` onto a `w × h` pixmap stays inside the budget, given
/// `held` bytes already in use (the target itself and anything the caller keeps).
pub(super) fn check(nodes: &[usvg::Node], ts: tiny_skia::Transform, w: u32, h: u32, held: u64) -> Result<(), Refusal> {
let target = f64::from(w) * f64::from(h);
let cx = Cx { live: held as f64 + target * 4.0, layer: target, cap: 25.0 * target, depth: 0, patterns: 0, images: 0, nest: 0 };
let mut walk = Walk { visited: 0, shared: HashMap::new(), clips: HashMap::new(), masks: HashMap::new() };
walk.nodes(nodes, ts, cx).map(|_| ())
}
fn need(live: f64, what: impl FnOnce() -> String) -> Result<(), Refusal> {
if live > BUDGET { Err(memory(&what(), live)) } else { Ok(()) }
}
impl Walk {
fn nodes(&mut self, nodes: &[usvg::Node], ts: tiny_skia::Transform, cx: Cx) -> Result<Profile, Refusal> {
let mut profile = Profile::default();
for n in nodes {
profile = profile.max(self.node(n, ts, cx)?);
}
Ok(profile)
}
// The recursion through plain groups is the deep one (usvg allows 1,000+ levels), so only small
// functions sit on it; everything with many locals is kept off it with `inline(never)`.
fn node(&mut self, node: &usvg::Node, ts: tiny_skia::Transform, cx: Cx) -> Result<Profile, Refusal> {
self.visited += 1;
if self.visited > MAX_NODES {
return Err(Refusal { complex: true, memory: false, message: format!("the drawing has more than {MAX_NODES} elements to check") });
}
match node {
usvg::Node::Group(g) if !g.should_isolate() => self.plain(g, ts, cx),
usvg::Node::Group(g) => self.group(g, ts, cx),
usvg::Node::Text(t) => self.group(t.flattened(), ts, cx),
usvg::Node::Path(p) => self.path(p, ts, cx),
usvg::Node::Image(image) => self.image(image, ts, cx),
}
}
/// A plain group is no layer.
fn plain(&mut self, g: &usvg::Group, ts: tiny_skia::Transform, cx: Cx) -> Result<Profile, Refusal> {
if cx.nest >= MAX_NEST {
return Err(limit("groups are nested too deeply", MAX_NEST));
}
let inside = self.nodes(g.children(), ts.pre_concat(g.transform()), Cx { nest: cx.nest + 1, ..cx })?;
Ok(inside.under(0.0, [0, 0, 0, 1]))
}
#[inline(never)]
fn path(&mut self, p: &usvg::Path, ts: tiny_skia::Transform, cx: Cx) -> Result<Profile, Refusal> {
let mut profile = Profile::default();
if !p.is_visible() {
return Ok(profile);
}
for paint in p.fill().map(|f| f.paint()).into_iter().chain(p.stroke().map(|s| s.paint())) {
if let usvg::Paint::Pattern(pattern) = paint {
profile = profile.max(self.pattern(pattern, ts, cx)?);
}
}
Ok(profile)
}
/// resvg draws an embedded SVG on a pixmap the size of the current one, with its own 5 × 5 clamp.
#[inline(never)]
fn image(&mut self, image: &usvg::Image, ts: tiny_skia::Transform, cx: Cx) -> Result<Profile, Refusal> {
let usvg::ImageKind::SVG(tree) = image.kind() else { return Ok(Profile::default()) };
if cx.images >= MAX_IMAGE_DEPTH {
return Err(limit("embedded SVG images are nested too deeply", MAX_IMAGE_DEPTH));
}
let bytes = cx.layer * 4.0;
need(cx.live + bytes, || "an embedded SVG image".to_string())?;
let nested = Cx { live: cx.live + bytes, cap: 25.0 * cx.layer, depth: cx.depth + 1, images: cx.images + 1, nest: cx.nest + 1, ..cx };
deeper(nested)?;
let inside = self.nodes(tree.root().children(), ts, nested)?;
Ok(Profile { extra: bytes, ..Profile::default() }.max(inside.under(bytes, [1, 0, 1, 1])))
}
/// Walk a definition shared by reference (pattern, mask, filter image) once per transform and
/// size; a repeat only re-checks its profile where it is used now.
fn shared(&mut self, key: Key, cx: Cx, walk: impl FnOnce(&mut Self) -> Result<Profile, Refusal>) -> Result<Profile, Refusal> {
let Some(p) = self.shared.get(&key).copied() else {
let p = walk(self)?;
self.shared.insert(key, p);
return Ok(p);
};
need(cx.live + p.extra, || "a shared definition used here".to_string())?;
if cx.depth + p.depth > MAX_DEPTH {
return Err(limit("layers are nested too deeply", MAX_DEPTH));
}
if cx.patterns + p.patterns > MAX_PATTERN_DEPTH {
return Err(limit("patterns are nested too deeply", MAX_PATTERN_DEPTH));
}
if cx.images + p.images > MAX_IMAGE_DEPTH {
return Err(limit("embedded SVG images are nested too deeply", MAX_IMAGE_DEPTH));
}
if cx.nest + p.nest > MAX_NEST {
return Err(limit("groups are nested too deeply", MAX_NEST));
}
Ok(p)
}
#[inline(never)]
fn group(&mut self, g: &usvg::Group, ts: tiny_skia::Transform, cx: Cx) -> Result<Profile, Refusal> {
if !g.should_isolate() {
return self.plain(g, ts, cx);
}
let ts = ts.pre_concat(g.transform());
if cx.nest >= MAX_NEST {
return Err(limit("groups are nested too deeply", MAX_NEST));
}
let Some(bb) = g.layer_bounding_box().transform(ts) else { return Ok(Profile::default()) };
let own = px((f64::from(bb.width()).ceil() + 4.0) * (f64::from(bb.height()).ceil() + 4.0)).min(cx.cap);
let inner = Cx { live: cx.live + own * 4.0, layer: own, depth: cx.depth + 1, nest: cx.nest + 1, ..cx };
deeper(inner)?;
// Filter, clip and mask are applied one after another; each needs its own extra buffers
// beside the group's layer. A clip or mask link is a 4 B/px pixmap and a 1 B/px mask.
let clip = g.clip_path().map_or(Ok(0), |c| self.clip_links(c, 0))?;
let mask = g.mask().map_or(Ok(0), |m| self.mask_links(m, 0))?;
let links = clip.max(mask);
let layers = own * 4.0 + own * 5.0 * links as f64;
need(cx.live + layers, || format!("a group with {links} clip or mask layers of {} px", own as u64))?;
let mut profile = Profile { extra: layers, ..Profile::default() };
for filter in g.filters() {
profile = profile.max(self.filter(filter, ts, cx, own)?);
}
let mut mask_ref = g.mask();
let mut link = 1.0;
while let Some(mask) = mask_ref {
// The mask content is drawn while this and every earlier link's pixmap and mask are alive.
let bytes = own * 4.0 + own * 5.0 * link;
let content = Cx { live: cx.live + bytes, ..inner };
let inside = self.shared(key(std::ptr::from_ref(mask) as usize, ts, content), content, |w| w.nodes(mask.root().children(), ts, content))?;
profile = profile.max(inside.under(bytes, [1, 0, 0, 1]));
mask_ref = mask.mask();
link += 1.0;
}
let inside = self.nodes(g.children(), ts, inner)?;
Ok(profile.max(inside.under(own * 4.0, [1, 0, 0, 1])))
}
/// Layers a clip-path keeps alive: its own, the deepest clip child with a clip-path of its own,
/// or the next link of the chain, whichever is deepest. Nothing is walked twice.
fn clip_links(&mut self, clip: &usvg::ClipPath, depth: usize) -> Result<usize, Refusal> {
let key = std::ptr::from_ref(clip) as usize;
if let Some(n) = self.clips.get(&key) {
return Ok(*n);
}
let too_long = || limit("clip-paths are chained or nested too deeply", MAX_LINKS);
if depth >= MAX_LINKS {
return Err(too_long());
}
let inside = self.clip_children(clip.root(), depth + 1)?;
let next = clip.clip_path().map_or(Ok(0), |c| self.clip_links(c, depth + 1))?;
let n = 1 + inside.max(next);
if n > MAX_LINKS {
return Err(too_long());
}
self.clips.insert(key, n);
Ok(n)
}
/// resvg's `clip_group`: a clip child with its own clip-path is drawn on a layer of its own,
/// kept while its descendants are drawn and its clip is applied.
fn clip_children(&mut self, group: &usvg::Group, depth: usize) -> Result<usize, Refusal> {
let mut deepest = 0;
for child in group.children() {
let inner = match child {
usvg::Node::Group(g) => {
let inside = self.clip_children(g, depth + usize::from(g.clip_path().is_some()))?;
match g.clip_path() {
Some(c) => 1 + inside.max(self.clip_links(c, depth + 1)?),
None => inside,
}
}
usvg::Node::Text(t) => self.clip_children(t.flattened(), depth)?,
_ => 0,
};
if inner + depth > MAX_LINKS {
return Err(limit("clip-paths are chained or nested too deeply", MAX_LINKS));
}
deepest = deepest.max(inner);
}
Ok(deepest)
}
/// Layers a mask chain keeps alive: a mask pixmap per link while the next is applied.
fn mask_links(&mut self, mask: &usvg::Mask, depth: usize) -> Result<usize, Refusal> {
let key = std::ptr::from_ref(mask) as usize;
if let Some(n) = self.masks.get(&key) {
return Ok(*n);
}
if depth >= MAX_LINKS {
return Err(limit("masks are chained too deeply", MAX_LINKS));
}
let n = 1 + mask.mask().map_or(Ok(0), |m| self.mask_links(m, depth + 1))?;
// A cached tail can make the chain longer than `depth` shows; the cap is on the whole chain.
if n > MAX_LINKS {
return Err(limit("masks are chained too deeply", MAX_LINKS));
}
self.masks.insert(key, n);
Ok(n)
}
/// A filter keeps a result per primitive, each as large as the filter region or the layer it
/// filters, whichever is larger (usvg makes the layer the union of all of a group's filter
/// regions, and `SourceGraphic` clones the whole layer). `own` is the size of that layer.
fn filter(&mut self, f: &usvg::filter::Filter, ts: tiny_skia::Transform, cx: Cx, own: f64) -> Result<Profile, Refusal> {
use usvg::filter::Kind;
let prims = f.primitives().len();
if prims > MAX_PRIMITIVES {
return Err(limit("a filter has too many primitives", MAX_PRIMITIVES));
}
let Some(region) = f.rect().transform(ts) else { return Ok(Profile::default()) };
let region = px(f64::from(region.width()).ceil() * f64::from(region.height()).ceil());
let slot = region.max(own) * 4.0;
// Buffers a primitive allocates beside its result (resvg 0.45.1 `filter/`): a blur works
// on one copy, an IIR blur (sigma under 2 after scaling) also on f64 scratch; blend,
// composite and displacement map convert two inputs; a drop shadow holds the input, its
// blur, the shadow and the result.
let (sx, sy) = ts.get_scale();
let transient = |kind: &Kind| match kind {
Kind::GaussianBlur(b) if b.std_dev_x().get() * sx >= 2.0 || b.std_dev_y().get() * sy >= 2.0 => 1.0,
Kind::GaussianBlur(_) => 2.0,
Kind::Blend(_) | Kind::Composite(_) | Kind::DisplacementMap(_) => 2.0,
// A tile of the source graphic converts and tiles two copies.
Kind::Tile(t) if matches!(t.input(), usvg::filter::Input::SourceGraphic) => 2.0,
Kind::DropShadow(_) => 4.0,
_ => 1.0,
};
let most = f.primitives().iter().map(|p| transient(p.kind())).fold(0.0, f64::max);
let extra = own * 4.0 + slot * (prims as f64 + most);
need(cx.live + extra, || format!("a filter with {prims} primitives over a region of {} px", region.min(1e18) as u64))?;
let mut profile = Profile { extra, ..Profile::default() };
for (i, primitive) in f.primitives().iter().enumerate() {
if let Kind::Image(fe) = primitive.kind() {
// What an feImage draws sees the results kept so far.
let bytes = own * 4.0 + slot * (i + 1) as f64;
let (sx, sy) = ts.get_scale();
let scaled = tiny_skia::Transform::from_scale(sx, sy);
let nested = Cx { live: cx.live + bytes, layer: region, cap: region, depth: cx.depth + 1, nest: cx.nest + 1, ..cx };
deeper(nested)?;
let inside = self.shared(key(std::ptr::from_ref(fe) as usize, scaled, nested), nested, |w| w.nodes(fe.root().children(), scaled, nested))?;
profile = profile.max(inside.under(bytes, [1, 0, 0, 1]));
}
}
Ok(profile)
}
/// A pattern tile is `width × height × scale` pixels, whatever the target.
fn pattern(&mut self, pattern: &usvg::Pattern, ts: tiny_skia::Transform, cx: Cx) -> Result<Profile, Refusal> {
let (sx, sy) = ts.pre_concat(pattern.transform()).get_scale();
let rect = pattern.rect();
let (tw, th) = (f64::from(rect.width() * sx).round(), f64::from(rect.height() * sy).round());
// resvg draws no tile smaller than a pixel (or not a number).
if !(tw >= 1.0 && th >= 1.0) {
return Ok(Profile::default());
}
let tile = tw * th;
let bytes = tile * 4.0;
need(cx.live + bytes, || format!("a pattern tile of {tw} × {th} px"))?;
if cx.patterns >= MAX_PATTERN_DEPTH {
return Err(limit("patterns are nested too deeply", MAX_PATTERN_DEPTH));
}
let nested = Cx { live: cx.live + bytes, layer: tile, depth: cx.depth + 1, patterns: cx.patterns + 1, nest: cx.nest + 1, ..cx };
deeper(nested)?;
let inner_ts = tiny_skia::Transform::from_scale(sx, sy);
let inside =
self.shared(key(std::ptr::from_ref(pattern) as usize, inner_ts, nested), nested, |w| w.nodes(pattern.root().children(), inner_ts, nested))?;
Ok(Profile { extra: bytes, ..Profile::default() }.max(inside.under(bytes, [1, 1, 0, 1])))
}
}
fn deeper(cx: Cx) -> Result<(), Refusal> {
if cx.depth > MAX_DEPTH {
return Err(limit("layers are nested too deeply", MAX_DEPTH));
}
Ok(())
}