From 014ead170fee7b45b92fe883e7f21567b11122cc Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 16 Nov 2026 12:40:51 +0000 Subject: [PATCH] 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 --- crates/craft/Cargo.toml | 2 ++ crates/svg/Cargo.toml | 16 ++++++---- crates/svg/src/lib.rs | 2 +- crates/svg/src/preflight.rs | 12 +++++++- crates/svg/src/tree.rs | 22 ++++++++++++-- crates/svg/src/tree/draw.rs | 8 ++--- crates/ui-contract/Cargo.toml | 4 +-- .../src/primitives/pointer_art/art.rs | 2 +- crates/ui-contract/src/primitives/svg_set.rs | 9 +++--- crates/ui-contract/src/primitives/svg_tree.rs | 30 ++++++++++++++----- crates/ui-shell/Cargo.toml | 2 +- crates/ui-shell/src/shell/caption_icons.rs | 9 ++++-- .../ui-shell/tests/it/shell/caption_button.rs | 9 ++++++ 13 files changed, 95 insertions(+), 32 deletions(-) diff --git a/crates/craft/Cargo.toml b/crates/craft/Cargo.toml index d72241234..e454b6873 100644 --- a/crates/craft/Cargo.toml +++ b/crates/craft/Cargo.toml @@ -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"] diff --git a/crates/svg/Cargo.toml b/crates/svg/Cargo.toml index 7516ddab2..a1d1e3437 100644 --- a/crates/svg/Cargo.toml +++ b/crates/svg/Cargo.toml @@ -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 `` 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"] diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index 5c70e8c60..1acdb7a9a 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -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; diff --git a/crates/svg/src/preflight.rs b/crates/svg/src/preflight.rs index 0c2d3a7b1..8f5ed6dcf 100644 --- a/crates/svg/src/preflight.rs +++ b/crates/svg/src/preflight.rs @@ -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 `(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("", &normal), Err(Error::Xml(_)))); } + + #[test] + fn a_document_type_is_refused_only_when_the_limits_say_so() { + let svg = r#"]>&a;"#; + assert!(parse_text(svg, &Limits::default()).is_ok()); + assert!(matches!(parse_text(svg, &Limits { allow_dtd: false, ..Default::default() }), Err(Error::Xml(_)))); + } } diff --git a/crates/svg/src/tree.rs b/crates/svg/src/tree.rs index 9cf85c3bd..613e298ff 100644 --- a/crates/svg/src/tree.rs +++ b/crates/svg/src/tree.rs @@ -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 `` 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, 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, } +#[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 { match craft_image_codecs::detect(data)? { format @ (craft_image_codecs::Format::Png @@ -514,6 +528,7 @@ fn raster_format(data: &[u8]) -> Option { } } +#[cfg(feature = "tree")] fn raster_image(used: &Used, limits: &Limits, data: Arc>, format: craft_image_codecs::Format) -> Option { 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>, 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 { 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 `` 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) -> 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) -> usvg::ImageHrefResolve } } -#[cfg(test)] +#[cfg(all(test, feature = "tree"))] mod tests; diff --git a/crates/svg/src/tree/draw.rs b/crates/svg/src/tree/draw.rs index f83653284..cf9d42e14 100644 --- a/crates/svg/src/tree/draw.rs +++ b/crates/svg/src/tree/draw.rs @@ -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 { 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 { 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()) diff --git a/crates/ui-contract/Cargo.toml b/crates/ui-contract/Cargo.toml index 7dab97453..112697346 100644 --- a/crates/ui-contract/Cargo.toml +++ b/crates/ui-contract/Cargo.toml @@ -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" diff --git a/crates/ui-contract/src/primitives/pointer_art/art.rs b/crates/ui-contract/src/primitives/pointer_art/art.rs index b6768b4db..8d887aeed 100644 --- a/crates/ui-contract/src/primitives/pointer_art/art.rs +++ b/crates/ui-contract/src/primitives/pointer_art/art.rs @@ -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. diff --git a/crates/ui-contract/src/primitives/svg_set.rs b/crates/ui-contract/src/primitives/svg_set.rs index 58422549e..f6e30379b 100644 --- a/crates/ui-contract/src/primitives/svg_set.rs +++ b/crates/ui-contract/src/primitives/svg_set.rs @@ -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, 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=\""; diff --git a/crates/ui-contract/src/primitives/svg_tree.rs b/crates/ui-contract/src/primitives/svg_tree.rs index 52671fb2d..aaafe6da8 100644 --- a/crates/ui-contract/src/primitives/svg_tree.rs +++ b/crates/ui-contract/src/primitives/svg_tree.rs @@ -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 `` 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 +//! `` 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 { @@ -19,8 +36,5 @@ pub fn parse(svg: &[u8]) -> Result { 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()) } diff --git a/crates/ui-shell/Cargo.toml b/crates/ui-shell/Cargo.toml index e4d8fdb79..d55e80fcb 100644 --- a/crates/ui-shell/Cargo.toml +++ b/crates/ui-shell/Cargo.toml @@ -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" diff --git a/crates/ui-shell/src/shell/caption_icons.rs b/crates/ui-shell/src/shell/caption_icons.rs index 5a6f9d20d..e77ed4b57 100644 --- a/crates/ui-shell/src/shell/caption_icons.rs +++ b/crates/ui-shell/src/shell/caption_icons.rs @@ -137,10 +137,13 @@ fn theme_files(_theme: &str) -> [Option>; 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 { - 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 { } 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() diff --git a/crates/ui-shell/tests/it/shell/caption_button.rs b/crates/ui-shell/tests/it/shell/caption_button.rs index 793569629..c12c9d388 100644 --- a/crates/ui-shell/tests/it/shell/caption_button.rs +++ b/crates/ui-shell/tests/it/shell/caption_button.rs @@ -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#"{}{}"#, "".repeat(200), "".repeat(200)); + assert!(mask_of(deep.as_bytes(), GLYPH_PX).is_none()); + let shallow = format!(r#"{}{}"#, "".repeat(8), "".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() {