merge-fwd: item 4: FW9: ui-contract and ui-shell parse and draw icons through craft-svg (features tree-core, tree, draw, tree-render; Limits.allow_dtd); resvg 0.45 goes; trials

This commit is contained in:
aiongg
2026-11-16 12:40:51 +00:00
parent a809ccadc6
commit 014ead170f
13 changed files with 95 additions and 32 deletions
+2
View File
@@ -611,7 +611,9 @@ stencilcraft-format = ["dep:craft-stencilcraft-format"]
stream-codecs = ["dep:craft-stream-codecs"]
svg = ["dep:craft-svg"]
svg-draw = ["svg", "craft-svg/draw"]
svg-tree = ["svg", "craft-svg/tree"]
svg-tree-core = ["svg", "craft-svg/tree-core"]
svg-tree-render = ["svg", "craft-svg/tree-render"]
svg-tree-render-system-fonts = ["svg", "craft-svg/tree-render-system-fonts"]
svg-tree-system-fonts = ["svg", "craft-svg/tree-system-fonts"]
+11 -5
View File
@@ -26,17 +26,23 @@ vectorcraft-pathops = { workspace = true }
usvg = { version = "=0.48.1", default-features = false, optional = true }
# Rendering the parsed tree uses the matching renderer version. Keep it behind an opt-in feature
# so callers that only need bounded SVG text/tree parsing do not pull in raster backends.
resvg = { version = "=0.48.1", default-features = false, features = ["text", "raster-images"], optional = true }
resvg = { version = "=0.48.1", default-features = false, optional = true }
data-url = { version = "0.3.2", optional = true }
[features]
# `craft_svg::tree`: usvg behind the bounded entry point.
tree = ["dep:usvg", "dep:data-url", "dep:craft-image-codecs"]
# `craft_svg::tree` without images: usvg behind the bounded entry point, the preflight, the
# limits and the draw check. For a caller that parses SVG it trusts no `<image>` in (UI icons).
tree-core = ["dep:usvg"]
# `craft_svg::tree`: usvg behind the bounded entry point, with the data-URL image resolver.
tree = ["tree-core", "dep:data-url", "dep:craft-image-codecs"]
# Text converted to paths (needs a font database in the options).
tree-text = ["tree", "usvg/text"]
# The system's fonts in `usvg::fontdb`.
tree-system-fonts = ["tree-text", "usvg/system-fonts"]
# Bounded rendering of a parsed tree through the matching resvg/tiny-skia versions.
tree-render = ["tree", "dep:resvg"]
# Bounded drawing of a parsed tree through the matching resvg/tiny-skia versions, without text or
# raster images (`tree::draw::render`, `render_node`, the `resvg` and `tiny_skia` re-exports).
draw = ["tree-core", "dep:resvg"]
# Bounded rendering of a parsed tree with its text and raster images.
tree-render = ["tree", "draw", "resvg/text", "resvg/raster-images"]
tree-render-system-fonts = ["tree-render", "resvg/system-fonts"]
+1 -1
View File
@@ -26,6 +26,6 @@ pub mod paths;
pub mod preflight;
pub mod sniff;
pub mod svgz;
#[cfg(feature = "tree")]
#[cfg(feature = "tree-core")]
pub mod tree;
pub mod write;
+11 -1
View File
@@ -23,6 +23,8 @@ pub struct Limits {
pub attribute_work: usize,
/// Maximum XML nodes after entity expansion.
pub xml_nodes: u32,
/// Accept a document type declaration; `false` refuses any `<!DOCTYPE`.
pub allow_dtd: bool,
}
impl Default for Limits {
@@ -35,6 +37,7 @@ impl Default for Limits {
attributes: crate::guard::MAX_ATTRIBUTES,
attribute_work: crate::guard::MAX_ATTRIBUTE_WORK,
xml_nodes: 4_000_000,
allow_dtd: true,
}
}
}
@@ -93,7 +96,7 @@ pub fn parse_text_with_depth<'a>(svg: &'a str, limits: &Limits) -> Result<(roxml
if prescan.too_deep {
return Err(Error::TooDeep(limits.depth));
}
let options = roxmltree::ParsingOptions { allow_dtd: true, nodes_limit: limits.xml_nodes, ..Default::default() };
let options = roxmltree::ParsingOptions { allow_dtd: limits.allow_dtd, nodes_limit: limits.xml_nodes, ..Default::default() };
let xml = roxmltree::Document::parse_with_options(svg, options).map_err(|e| Error::Xml(e.to_string()))?;
Ok((xml, prescan.depth, prescan.open_depth))
}
@@ -123,4 +126,11 @@ mod tests {
let normal = Limits::default();
assert!(matches!(parse_text_with_depth("<svg><g></svg>", &normal), Err(Error::Xml(_))));
}
#[test]
fn a_document_type_is_refused_only_when_the_limits_say_so() {
let svg = r#"<!DOCTYPE svg [<!ENTITY a "x">]><svg>&a;</svg>"#;
assert!(parse_text(svg, &Limits::default()).is_ok());
assert!(matches!(parse_text(svg, &Limits { allow_dtd: false, ..Default::default() }), Err(Error::Xml(_))));
}
}
+20 -2
View File
@@ -22,9 +22,13 @@
//! 16 MB or so, and a 1 MB stack takes a depth of about 34.
use std::borrow::Cow;
use std::collections::HashMap;
#[cfg(feature = "tree")]
use std::collections::HashSet;
use std::collections::hash_map::Entry;
use std::collections::{HashMap, HashSet};
#[cfg(feature = "tree")]
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
#[cfg(feature = "tree")]
use std::sync::{Arc, Mutex, PoisonError};
pub use usvg;
@@ -58,6 +62,8 @@ pub struct Limits {
pub attribute_work: usize,
/// Nodes the XML may hold once entities are expanded.
pub xml_nodes: u32,
/// Accept a document type declaration; `false` refuses any `<!DOCTYPE`.
pub allow_dtd: bool,
/// Bytes of all SVG documents embedded in `<image>` data URLs, unpacked, for
/// [`image_resolver`].
pub embedded_bytes: usize,
@@ -80,6 +86,7 @@ impl Default for Limits {
attributes: guard::MAX_ATTRIBUTES,
attribute_work: guard::MAX_ATTRIBUTE_WORK,
xml_nodes: 4_000_000,
allow_dtd: true,
embedded_bytes: 32 << 20,
embedded_depth: 4,
embedded_raster_pixels: 24_000_000,
@@ -189,6 +196,7 @@ pub fn preflight<'s>(svg: &'s str, limits: &Limits) -> Result<Preflight<'s>, Err
attributes: limits.attributes,
attribute_work: limits.attribute_work,
xml_nodes: limits.xml_nodes,
allow_dtd: limits.allow_dtd,
};
let (xml, _, depth) = crate::preflight::parse_text_with_depth(svg, &preflight_limits).map_err(|e| match e {
crate::preflight::Error::Text(e) => Error::Text(e),
@@ -375,6 +383,7 @@ pub fn height(xml: &roxmltree::Document<'_>, most: usize) -> Result<Option<usize
Ok(Some(heights.get(&xml.root_element().id()).copied().unwrap_or(0)))
}
#[cfg(feature = "tree")]
/// What the embedded SVGs of one import have used so far.
struct Used {
bytes: AtomicUsize,
@@ -391,6 +400,7 @@ struct Used {
svg_resource_limit: AtomicUsize,
}
#[cfg(feature = "tree")]
/// What resolving one drawing's embedded images used or refused.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ImageUsage {
@@ -416,6 +426,7 @@ pub struct ImageUsage {
pub svg_resource_limit_images: usize,
}
#[cfg(feature = "tree")]
/// A data-URL resolver and the accounting for the one drawing it serves.
///
/// Keep this value while parsing, then read [`usage`](Self::usage). Linked files are never read.
@@ -424,6 +435,7 @@ pub struct ImageResolver {
used: Arc<Used>,
}
#[cfg(feature = "tree")]
impl ImageResolver {
/// Create one resolver budget for one drawing import.
pub fn new(limits: Limits) -> Self {
@@ -483,6 +495,7 @@ impl ImageResolver {
}
}
#[cfg(feature = "tree")]
// usvg's data-URL decoder returns before resolve_data for invalid base64. Count
// these omissions separately, including feImage, without reading linked resources.
fn account_invalid_data_urls(xml: &roxmltree::Document<'_>, used: &Used) {
@@ -504,6 +517,7 @@ fn account_invalid_data_urls(xml: &roxmltree::Document<'_>, used: &Used) {
}
}
#[cfg(feature = "tree")]
fn raster_format(data: &[u8]) -> Option<craft_image_codecs::Format> {
match craft_image_codecs::detect(data)? {
format @ (craft_image_codecs::Format::Png
@@ -514,6 +528,7 @@ fn raster_format(data: &[u8]) -> Option<craft_image_codecs::Format> {
}
}
#[cfg(feature = "tree")]
fn raster_image(used: &Used, limits: &Limits, data: Arc<Vec<u8>>, format: craft_image_codecs::Format) -> Option<usvg::ImageKind> {
let Ok((width, height)) = craft_image_codecs::probe_allocation_size(&data) else {
used.invalid_raster.fetch_add(1, Ordering::Relaxed);
@@ -576,6 +591,7 @@ fn raster_image(used: &Used, limits: &Limits, data: Arc<Vec<u8>>, format: craft_
})
}
#[cfg(feature = "tree")]
/// An embedded SVG document, if the budgets allow it.
fn embedded(used: &Used, limits: &Limits, data: &[u8], options: &usvg::Options<'_>) -> Option<usvg::ImageKind> {
if used.depth.load(Ordering::Relaxed) >= limits.embedded_depth {
@@ -650,6 +666,7 @@ fn embedded(used: &Used, limits: &Limits, data: &[u8], options: &usvg::Options<'
}
}
#[cfg(feature = "tree")]
/// An image resolver for `usvg::Options::image_href_resolver` that reads `<image>` data URLs
/// only: raster images as they are (PNG, JPEG, GIF, WebP), SVG documents (SVGZ too) through the
/// same checks as [`parse`] and within [`Limits::embedded_bytes`] in all and
@@ -659,6 +676,7 @@ pub fn image_resolver(limits: Limits) -> usvg::ImageHrefResolver<'static> {
ImageResolver::new(limits).resolver()
}
#[cfg(feature = "tree")]
fn image_resolver_for(limits: Limits, used: Arc<Used>) -> usvg::ImageHrefResolver<'static> {
usvg::ImageHrefResolver {
resolve_data: Box::new(move |mime, data, options| {
@@ -690,5 +708,5 @@ fn image_resolver_for(limits: Limits, used: Arc<Used>) -> usvg::ImageHrefResolve
}
}
#[cfg(test)]
#[cfg(all(test, feature = "tree"))]
mod tests;
+4 -4
View File
@@ -24,9 +24,9 @@ use std::collections::HashMap;
use usvg::Transform;
#[cfg(feature = "tree-render")]
#[cfg(feature = "draw")]
pub use resvg;
#[cfg(feature = "tree-render")]
#[cfg(feature = "draw")]
pub use resvg::tiny_skia;
/// Filter primitives per filter. A result of every primitive is kept; real filters have 1 to 12
@@ -165,7 +165,7 @@ pub fn check(nodes: &[usvg::Node], ts: Transform, width: u32, height: u32, held:
/// Draws a complete tree onto a transparent pixmap after checking the peak RGBA allocation.
/// `held` is caller-owned RGBA storage that remains live during the draw; the target itself is
/// charged by this function.
#[cfg(feature = "tree-render")]
#[cfg(feature = "draw")]
pub fn render(tree: &usvg::Tree, ts: Transform, width: u32, height: u32, held: u64, budget: u64) -> Result<tiny_skia::Pixmap, Refusal> {
check_filter_cost(tree, ts, 2_000_000_000, 10_000_000, 200)?;
// Even an empty tree allocates the target. `check` only walks buffers added by nodes, so
@@ -186,7 +186,7 @@ pub fn render(tree: &usvg::Tree, ts: Transform, width: u32, height: u32, held: u
/// Draws one node onto `target` after checking the peak RGBA allocation. The node remains in its
/// parent's coordinate space, matching `resvg::render_node`.
#[cfg(feature = "tree-render")]
#[cfg(feature = "draw")]
pub fn render_node(node: &usvg::Node, ts: Transform, target: &mut tiny_skia::Pixmap, held: u64, budget: u64) -> Result<bool, Refusal> {
check(std::slice::from_ref(node), ts, target.width(), target.height(), held, budget)?;
Ok(resvg::render_node(node, ts, &mut target.as_mut()).is_some())
+2 -2
View File
@@ -62,8 +62,8 @@ craft-fonts-build = { workspace = true }
# Only `color_fonts` reads it: the feature turns on epaint's colour glyphs.
epaint = { version = "0.37", default-features = false, optional = true }
# Icon rasterising; the version egui_extras's `svg` feature uses, so apps build one copy.
resvg = { version = "0.45.1", default-features = false }
# Icon parsing and rasterising: the bounded usvg/resvg stack every Craft app shares, without text or raster images.
craft-svg = { workspace = true, features = ["draw"] }
# `std::time::Instant` on native; the browser clock on wasm, where `Instant::now` panics.
web-time = "1.1"
@@ -4,7 +4,7 @@
use crate::primitives::SvgIcon;
use crate::runtime::cursor::{CursorArt, CursorBitmap};
use egui::{Color32, Painter, Pos2, Rect, Shape, Stroke, Vec2};
use resvg::tiny_skia;
use craft_svg::tree::draw::tiny_skia;
use std::sync::Arc;
/// How far past a mark's geometry its antialiasing reaches, in device pixels.
+5 -4
View File
@@ -1,7 +1,7 @@
//! The SVG icon catalog the build embeds, the app icon sets registered beside it, and their rasteriser.
use egui::{Color32, ColorImage};
use resvg::tiny_skia;
use craft_svg::tree::draw::{self as svg_draw, tiny_skia};
use std::sync::{PoisonError, RwLock};
use super::svg_tree;
@@ -151,14 +151,15 @@ fn draw(svg: &[u8], own: Option<f32>, px: u32, stroke_px: f32, mirrored: bool) -
let text = std::str::from_utf8(svg).map_err(|e| e.to_string())?;
tree = svg_tree::parse(scale_stroke_widths(text, units / own).as_bytes())?;
}
let mut pixmap = tiny_skia::Pixmap::new(px, px).ok_or("zero size")?;
let (sx, sy) = (px as f32 / view.width(), px as f32 / view.height());
let transform =
if mirrored { tiny_skia::Transform::from_row(-sx, 0.0, 0.0, sy, px as f32, 0.0) } else { tiny_skia::Transform::from_scale(sx, sy) };
resvg::render(&tree, transform, &mut pixmap.as_mut());
Ok(pixmap)
svg_draw::render(&tree, transform, px, px, 0, ICON_DRAW_BUDGET).map_err(|refusal| refusal.message)
}
/// Bytes drawing one icon may allocate, its target included.
const ICON_DRAW_BUDGET: u64 = 64 << 20;
/// `svg` with each `stroke-width="..."` attribute multiplied by `factor`.
fn scale_stroke_widths(svg: &str, factor: f32) -> String {
const ATTR: &str = "stroke-width=\"";
+22 -8
View File
@@ -1,14 +1,31 @@
//! The one SVG parser. Icon files come from the build and from icon themes on the user's disk, so parsing is bounded:
//! no gzip (its size is unlimited), no DTD (entity expansion), a node limit, and no `<image>` loaded, which keeps a
//! document from making the renderer read another file or nest an SVG.
//! The one SVG parser, craft-svg's bounded entry point. Icon files come from the build and from icon themes on the
//! user's disk, so parsing is bounded: no gzip, no DTD (entity expansion), a node limit, a nesting limit, and no
//! `<image>` loaded, which keeps a document from making the renderer read another file or nest an SVG.
use resvg::usvg;
use craft_svg::tree::{self, Limits, usvg};
/// Elements and text nodes an icon SVG may have; a glyph has a handful.
const MAX_NODES: u32 = 10_000;
/// The first bytes of a gzip stream.
const GZIP_MAGIC: [u8; 2] = [0x1f, 0x8b];
/// What an icon may use. Icons parse on the UI thread, whose stack may be 1 MB (Windows' main thread): craft-svg
/// gives about 34 levels for that, so nesting stops at 32.
fn icon_limits() -> Limits {
Limits {
bytes: 1 << 20,
depth: 32,
tree_depth: 32,
xml_nodes: MAX_NODES,
allow_dtd: false,
refuse_entity_markup: true,
embedded_bytes: 0,
embedded_depth: 0,
embedded_raster_pixels: 0,
..Limits::default()
}
}
/// The render tree of `svg`, or why it was refused.
#[doc(hidden)]
pub fn parse(svg: &[u8]) -> Result<usvg::Tree, String> {
@@ -19,8 +36,5 @@ pub fn parse(svg: &[u8]) -> Result<usvg::Tree, String> {
image_href_resolver: usvg::ImageHrefResolver { resolve_data: Box::new(|_, _, _| None), resolve_string: Box::new(|_, _| None) },
..usvg::Options::default()
};
let text = std::str::from_utf8(svg).map_err(|e| e.to_string())?;
let xml = usvg::roxmltree::ParsingOptions { allow_dtd: false, nodes_limit: MAX_NODES };
let doc = usvg::roxmltree::Document::parse_with_options(text, xml).map_err(|e| e.to_string())?;
usvg::Tree::from_xmltree(&doc, &options).map_err(|e| e.to_string())
tree::parse(svg, &icon_limits(), &options).map_err(|e| e.to_string())
}
+1 -1
View File
@@ -36,7 +36,7 @@ craft-i18n = { workspace = true, features = ["collate"] }
# The saved forms of `ScreenMode`, `RecentView` and `RecentSort`.
serde = { workspace = true }
# The caption button icons.
resvg = { version = "0.45.1", default-features = false }
craft-svg = { workspace = true, features = ["draw"] }
# `std::time::Instant` on native; the browser clock on wasm, where `Instant::now` panics.
web-time = "1.1"
+6 -3
View File
@@ -137,10 +137,13 @@ fn theme_files(_theme: &str) -> [Option<Arc<[u8]>>; 4] {
Default::default()
}
/// Bytes drawing one caption icon may allocate, its target included.
const MASK_DRAW_BUDGET: u64 = 64 << 20;
/// An SVG's coverage (alpha) as a `px` x `px` mask, the drawing fitted and centred. `None` for an unreadable SVG or
/// an absurd size.
fn rasterize_mask(svg: &[u8], px: u32) -> Option<CaptionMask> {
use resvg::tiny_skia;
use craft_svg::tree::draw::{self, tiny_skia};
if !(1..=MAX_MASK_SIDE).contains(&px) {
return None;
}
@@ -155,8 +158,8 @@ fn rasterize_mask(svg: &[u8], px: u32) -> Option<CaptionMask> {
}
let scale = px as f32 / side;
let (dx, dy) = ((px as f32 - size.width() * scale) / 2.0, (px as f32 - size.height() * scale) / 2.0);
let mut pixmap = tiny_skia::Pixmap::new(px, px)?;
resvg::render(&tree, tiny_skia::Transform::from_scale(scale, scale).post_translate(dx, dy), &mut pixmap.as_mut());
let transform = tiny_skia::Transform::from_scale(scale, scale).post_translate(dx, dy);
let pixmap = draw::render(&tree, transform, px, px, 0, MASK_DRAW_BUDGET).ok()?;
Some(pixmap.data().as_chunks::<4>().0.iter().map(|[_, _, _, a]| *a).collect())
}))
.ok()
@@ -29,6 +29,15 @@ fn hostile_svgs_render_nothing() {
assert!(mask_of(image.as_bytes(), GLYPH_PX).is_some_and(|mask| mask.iter().all(|coverage| *coverage == 0)), "nothing drawn");
}
/// Icons parse on the UI thread: a document nested deeper than its stack takes is refused, not a stack overflow.
#[trial]
fn an_icon_nested_past_its_depth_is_refused_not_a_crash() {
let deep = format!(r#"<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16">{}<path d="M4 4h8v8H4z"/>{}</svg>"#, "<g>".repeat(200), "</g>".repeat(200));
assert!(mask_of(deep.as_bytes(), GLYPH_PX).is_none());
let shallow = format!(r#"<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16">{}<path d="M4 4h8v8H4z"/>{}</svg>"#, "<g>".repeat(8), "</g>".repeat(8));
assert!(mask_of(shallow.as_bytes(), GLYPH_PX).is_some_and(|mask| mask.iter().any(|coverage| *coverage > 0)), "a shallow icon draws");
}
/// A glyph is a square coverage mask of the drawing, fitted to the asked side; the glyphs a theme lacks have none.
#[trial]
fn masks_are_square_coverage() {