From aef2b90738fd2cceaa8050eb69ea392c915cb3cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Mon, 23 Nov 2026 14:22:57 -0500 Subject: [PATCH] fix(render): say each SVG marker image refusal's own cause (#2713) --- crates/engine/src/project.rs | 32 ++++++++- crates/engine/src/tests.rs | 17 ++++- crates/render/src/lib.rs | 2 +- crates/render/src/picture.rs | 115 +++++++++++++++++++++++------ crates/render/src/picture/svg.rs | 119 ++++++++++++++++++++----------- crates/ui-egui/src/markerpick.rs | 14 ++++ docs/user-guide/cartography.md | 34 ++++----- docs/user-guide/workspace.md | 4 +- 8 files changed, 253 insertions(+), 84 deletions(-) diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 31c929fc81..91026dcac2 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -2179,10 +2179,15 @@ pub(crate) fn picture_notices_by<'a>( *seen.borrow_mut().entry(p).or_insert_with(|| check(p)) }; // The names with an image refused so, by each refusal in `WHY`, in the order their notices go. - const WHY: [MarkerRefusal; 5] = [ + const WHY: [MarkerRefusal; 10] = [ MarkerRefusal::NotAnImage, + MarkerRefusal::TooManyBytes, MarkerRefusal::TooManyPixels, MarkerRefusal::TooMuchToDraw, + MarkerRefusal::SvgTooNested, + MarkerRefusal::SvgFontRadius, + MarkerRefusal::SvgTooSmall, + MarkerRefusal::SvgNotUtf8, MarkerRefusal::SvgUndrawn, MarkerRefusal::PastRunPixels, ]; @@ -2227,13 +2232,19 @@ pub(crate) fn picture_notices_by<'a>( ], )); } - let [not_images, too_large, too_much, filtered, past_run] = &bad; + let [not_images, too_long, too_large, too_much, too_nested, font_radius, too_small, not_utf8, filtered, past_run] = &bad; if !not_images.is_empty() { notices.push(NoticeText::format( "Image markers in {names} aren't PNG, JPEG or SVG images and are drawn as circles", [("names", picture_names(not_images))], )); } + if !too_long.is_empty() { + notices.push(NoticeText::format( + "Image markers in {names} are longer than {mib} MiB as base64 and are drawn as circles", + [("names", picture_names(too_long)), ("mib", (MAX_PICTURE_BYTES >> 20).to_string().into())], + )); + } if !too_large.is_empty() { notices.push(NoticeText::format( "Image markers in {names} have more pixels than {side} × {side} and are drawn as circles", @@ -2246,6 +2257,23 @@ pub(crate) fn picture_notices_by<'a>( [("names", picture_names(too_much)), ("side", rustgis_render::MARKER_PIXELS_SIDE.to_string().into())], )); } + // Each SVG's own cause (#2713), its figures as the renderer's phrase gives them. + for (names, what) in [ + ( + too_nested, + "Image markers in {names} are SVGs with more than 40,000 XML nodes or nested deeper than 64 levels and are drawn as circles", + ), + ( + font_radius, + "Image markers in {names} are SVGs with a radius in em or ex, whose size RustGIS can't know, and are drawn as circles", + ), + (too_small, "Image markers in {names} are SVGs too small to draw and are drawn as circles"), + (not_utf8, "Image markers in {names} are SVGs that aren't UTF-8 text and are drawn as circles"), + ] { + if !names.is_empty() { + notices.push(NoticeText::format(what, [("names", picture_names(names))])); + } + } if !filtered.is_empty() { notices.push(NoticeText::format( "Image markers in {names} are SVGs with filters, text, images, animation or links to other files, which RustGIS doesn't draw in marker images, and are drawn as circles", diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index fd34aa84a1..82089893d6 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2662,7 +2662,7 @@ fn layer_marker_takes_an_svg_and_refuses_one_it_cant_draw() { } /// An SVG image marker that has too much to draw, or filters, is said with why on reading, apart -/// from the others (the renderer's check stood in for). +/// from the others, each cause its own (#2713) (the renderer's check stood in for). #[test] fn svg_image_markers_that_dont_draw_are_said_with_why() { use rustgis_render::MarkerRefusal; @@ -2682,10 +2682,25 @@ fn svg_image_markers_that_dont_draw_are_said_with_why() { MarkerRefusal::SvgUndrawn, "Image markers in \"Cities\", \"Rivers\" are SVGs with filters, text, images, animation or links to other files, which RustGIS doesn't draw in marker images, and are drawn as circles", ), + (MarkerRefusal::TooManyBytes, "Image markers in \"Cities\", \"Rivers\" are longer than 2 MiB as base64 and are drawn as circles"), + ( + MarkerRefusal::SvgTooNested, + "Image markers in \"Cities\", \"Rivers\" are SVGs with more than 40,000 XML nodes or nested deeper than 64 levels and are drawn as circles", + ), + ( + MarkerRefusal::SvgFontRadius, + "Image markers in \"Cities\", \"Rivers\" are SVGs with a radius in em or ex, whose size RustGIS can't know, and are drawn as circles", + ), + (MarkerRefusal::SvgTooSmall, "Image markers in \"Cities\", \"Rivers\" are SVGs too small to draw and are drawn as circles"), + (MarkerRefusal::SvgNotUtf8, "Image markers in \"Cities\", \"Rivers\" are SVGs that aren't UTF-8 text and are drawn as circles"), ] { let said: Vec = crate::project::picture_notices_by(layers, [], &|_| Some(why)).iter().map(|n| n.english()).collect(); assert_eq!(said, [notice]); } + // The caps the notices write out are the renderer's. + let (nodes, depth) = (rustgis_render::SVG_XML_NODES, rustgis_render::SVG_DEPTH); + assert_eq!((nodes, depth), (40_000, 64), "the SVG notices and the picker's say 40,000 and 64"); + assert_eq!(rustgis_map::symbology::MAX_PICTURE_BYTES >> 20, 2, "the notice says 2 MiB"); } /// Saved image markers that are SVGs open drawn, and one with a filter, which RustGIS doesn't draw, diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 760c7351da..27f85c379b 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -607,7 +607,7 @@ pub fn picture_size(b64: &str) -> Option<(u32, u32)> { picture::size(b64) } -pub use picture::{MARKER_PIXELS, MARKER_PIXELS_SIDE, MarkerRefusal, RUN_MARKER_BYTES, RUN_MARKER_PIXELS}; +pub use picture::{MARKER_PIXELS, MARKER_PIXELS_SIDE, MarkerRefusal, RUN_MARKER_BYTES, RUN_MARKER_PIXELS, SVG_DEPTH, SVG_XML_NODES}; /// Base64 `b64` as a picture marker's image (one kept already, or one before it is set): its /// height for its width when it draws (a PNG or JPEG within [`MARKER_PIXELS`], an SVG with as much diff --git a/crates/render/src/picture.rs b/crates/render/src/picture.rs index 2a5f65258b..9d1cf2fc18 100644 --- a/crates/render/src/picture.rs +++ b/crates/render/src/picture.rs @@ -32,10 +32,15 @@ const MARKER_SIDE: u32 = 700; /// passes): past it, it isn't decoded and is drawn as a circle. What a marker costs to check and /// draw is its pixels (decoding and scaling one takes some 19 ns a pixel), not its bytes: a PNG of /// a few kilobytes can declare hundreds of megapixels. So the cap is set by that cost, one at it -/// taking some 80 ms; a marker is drawn from at most [`MARKER_SIDE`] pixels a side whatever its -/// image's size. An SVG may have as much to draw, in [`svg::work`]'s units (some 13 ns each at -/// most, so about as long). +/// taking some 80 ms; a marker is drawn from at most `MARKER_SIDE` (700) pixels a side whatever +/// its image's size. An SVG may have as much to draw, in the units of the renderer's SVG count +/// (some 13 ns each at most, so about as long). pub const MARKER_PIXELS: u64 = MARKER_PIXELS_SIDE as u64 * MARKER_PIXELS_SIDE as u64; +/// The most XML nodes and the deepest nesting of an SVG marker image, for messages (theirs, written +/// out, a test pins). +pub const SVG_XML_NODES: u32 = svg::XML_NODES; +/// See [`SVG_XML_NODES`]. +pub const SVG_DEPTH: u32 = svg::DEPTH; /// The side of the square [`MARKER_PIXELS`] is, for messages (theirs, written out, a test pins). pub const MARKER_PIXELS_SIDE: u32 = 2048; /// The most pixels of different picture markers' images a run decodes, about 5 s of decoding; @@ -68,13 +73,25 @@ const SVG_READ: u64 = 3; pub enum MarkerRefusal { /// It isn't a PNG, JPEG or SVG image that decodes. NotAnImage, + /// Its base64 is longer than a kept picture may be + /// ([`rustgis_map::symbology::MAX_PICTURE_BYTES`]). + TooManyBytes, /// It declares more than [`MARKER_PIXELS`]. TooManyPixels, - /// It is an SVG with more to draw than [`MARKER_PIXELS`] (in [`svg::work`]'s units), or more - /// elements than [`svg::ELEMENTS`]. + /// It is an SVG with more to draw than [`MARKER_PIXELS`] (in the units of the renderer's SVG + /// count, `svg::work`), or more elements than `svg::ELEMENTS` (10,000). TooMuchToDraw, + /// It is an SVG with more XML nodes than `svg::XML_NODES` (40,000) or nested deeper than + /// `svg::DEPTH` (64). + SvgTooNested, + /// It is an SVG with a radius in em or ex, a font's size, which may be any. + SvgFontRadius, + /// It is an SVG too small to scale up to a pixmap (its size near 0). + SvgTooSmall, + /// It is an SVG that isn't UTF-8 text. + SvgNotUtf8, /// It is an SVG with filters, text, images, animation or links to other files, which marker - /// images don't draw ([`svg`] says why). + /// images don't draw (the renderer's `svg` module says why). SvgUndrawn, /// It would take the run past [`RUN_MARKER_PIXELS`] or [`RUN_MARKER_BYTES`]. PastRunPixels, @@ -114,8 +131,13 @@ macro_rules! refusal_phrases { refusal_phrases! { NotAnImage => "isn't a PNG, JPEG or SVG RustGIS reads", + TooManyBytes => "is longer than 2 MiB as base64", TooManyPixels => "has more pixels than 2048 × 2048", TooMuchToDraw => "is an SVG with more to draw than a 2048 × 2048 image", + SvgTooNested => "is an SVG with more than 40,000 XML nodes or nested deeper than 64 levels", + SvgFontRadius => "is an SVG with a radius in em or ex, whose size RustGIS can't know", + SvgTooSmall => "is an SVG too small to draw", + SvgNotUtf8 => "is an SVG that isn't UTF-8 text", SvgUndrawn => "is an SVG with filters, text, images, animation or links to other files, which RustGIS doesn't draw in marker images", PastRunPixels => "is past what RustGIS decodes of marker images until it restarts (256 megapixels, 128 MiB)", } @@ -207,7 +229,9 @@ struct Store { } /// The [`Store`]. Its lock is held while an image is decoded, so two threads meeting the same new -/// image decode it once; another waits at most one image's decoding (80 ms at [`MARKER_PIXELS`]). +/// image decode it once; another waits at most one image's decoding: 80 ms for a PNG or JPEG at +/// [`MARKER_PIXELS`]; for an SVG, its reading (some 50 ms at the length a kept picture may be) and +/// its drawing (as long as a PNG's at most). fn store() -> std::sync::MutexGuard<'static, Store> { static STORE: OnceLock> = OnceLock::new(); STORE.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner()) @@ -243,6 +267,10 @@ fn marker_in(store: &mut Store, b64: &str) -> Marker { use MarkerRefusal::*; let b64 = b64.trim(); let Some(format) = format(b64) else { return Err(NotAnImage) }; + // What a kept picture may be, whoever checks it: reading an SVG is then bounded too (~50 ms). + if b64.len() > rustgis_map::symbology::MAX_PICTURE_BYTES { + return Err(TooManyBytes); + } let id = content_id(b64); if let Some(found) = store.images.get(&id) { return found.clone(); @@ -279,15 +307,11 @@ fn marker_in(store: &mut Store, b64: &str) -> Marker { /// refusal, which a later image giving back bytes may lift, as for a PNG. fn svg_in(store: &mut Store, id: u128, bytes: &[u8]) -> Marker { use MarkerRefusal::*; - // What a kept picture may be, whoever checks it: reading it is then bounded too (~50 ms). - if bytes.len() > rustgis_map::symbology::MAX_PICTURE_BYTES / 4 * 3 { - return Err(TooMuchToDraw); - } let limits = (RUN_MARKER_PIXELS, RUN_MARKER_BYTES); store.budget.take((bytes.len() as u64).saturating_mul(SVG_READ), 0, limits)?; // Read from its first `<`, as `format` told it: XML takes nothing before its declaration. let text = std::str::from_utf8(bytes).map(|t| t.trim_start_matches('\u{feff}').trim_start()); - let tree = text.map_err(|_| NotAnImage).and_then(|text| svg::read(text).map_err(MarkerRefusal::from)); + let tree = text.map_err(|_| SvgNotUtf8).and_then(|text| svg::read(text).map_err(MarkerRefusal::from)); let found = tree.and_then(|tree| { let size = tree.size(); let (w, h) = (size.width(), size.height()); @@ -298,7 +322,7 @@ fn svg_in(store: &mut Store, id: u128, bytes: &[u8]) -> Marker { let (sx, sy) = (pw as f32 / w, ph as f32 / h); // One too small to scale up to a pixmap (its size near 0) can't be drawn. if !(k.is_finite() && sx.is_finite() && sy.is_finite()) { - return Err(NotAnImage); + return Err(SvgTooSmall); } let at = Transform::from_scale(sx, sy); let work = svg::work(&tree, (pw, ph), at, MARKER_PIXELS)?; @@ -322,6 +346,8 @@ impl From for MarkerRefusal { match why { svg::Refusal::NotSvg => MarkerRefusal::NotAnImage, svg::Refusal::TooMuch => MarkerRefusal::TooMuchToDraw, + svg::Refusal::TooNested => MarkerRefusal::SvgTooNested, + svg::Refusal::FontRadius => MarkerRefusal::SvgFontRadius, svg::Refusal::Undrawn => MarkerRefusal::SvgUndrawn, } } @@ -563,10 +589,11 @@ fn format(b64: &str) -> Option { mod tests { use super::*; - /// Picture markers take PNG and JPEG alone, read from the first bytes: not a GIF (which the - /// desktop's decoder reads and the web's doesn't), nor what isn't base64 or an image. + /// Picture markers take PNG and JPEG images read from their first bytes (SVG too, tested + /// below): not a GIF (which the desktop's decoder reads and the web's doesn't), nor what isn't + /// base64 or an image. #[test] - fn a_marker_is_a_png_or_a_jpeg() { + fn a_marker_is_a_png_a_jpeg_or_an_svg() { let encoded = |format: image::ImageFormat| { let mut bytes = Vec::new(); image::RgbImage::from_pixel(4, 2, image::Rgb([10, 20, 30])).write_to(&mut std::io::Cursor::new(&mut bytes), format).unwrap(); @@ -714,8 +741,20 @@ mod tests { fn only_the_runs_refusal_passes() { use MarkerRefusal::*; assert_eq!( - [NotAnImage, TooManyPixels, TooMuchToDraw, SvgUndrawn, PastRunPixels].map(MarkerRefusal::lasts), - [true, true, true, true, false] + [ + NotAnImage, + TooManyBytes, + TooManyPixels, + TooMuchToDraw, + SvgTooNested, + SvgFontRadius, + SvgTooSmall, + SvgNotUtf8, + SvgUndrawn, + PastRunPixels + ] + .map(MarkerRefusal::lasts), + [true, true, true, true, true, true, true, true, true, false] ); // A kept image the run's spent budget refuses is kept as it is; one refused for itself // isn't; one that draws is. @@ -767,6 +806,42 @@ mod tests { assert!(MarkerRefusal::PastRunPixels.what().contains(&run)); assert_eq!(MarkerRefusal::NotAnImage.whose(), "whose image isn't a PNG, JPEG or SVG RustGIS reads"); assert!(MarkerRefusal::TooMuchToDraw.what().contains(&format!("a {side} × {side} image"))); + let mib = format!("longer than {} MiB as base64", rustgis_map::symbology::MAX_PICTURE_BYTES >> 20); + assert!(MarkerRefusal::TooManyBytes.what().contains(&mib)); + let (nodes, depth) = (SVG_XML_NODES, SVG_DEPTH); + let nested = format!("more than {},{:03} XML nodes or nested deeper than {depth} levels", nodes / 1000, nodes % 1000); + assert!(MarkerRefusal::SvgTooNested.what().contains(&nested)); + } + + /// Each refusal says its own cause (#2713): a long image, an SVG nested deep or with many + /// nodes, a radius in em or ex, one too small to draw, one that isn't UTF-8. + #[test] + fn an_image_is_refused_for_its_own_cause() { + use MarkerRefusal::*; + let svg = |body: &str| b64(&format!(r#"{body}"#)); + let deep = format!("{}{}", "".repeat(70), "".repeat(70)); + let nodes = "".repeat(svg::XML_NODES as usize); + let long_png = { + let mut bytes = b"\x89PNG\r\n\x1a\n".to_vec(); + bytes.resize(rustgis_map::symbology::MAX_PICTURE_BYTES, 0); + base64::engine::general_purpose::STANDARD.encode(bytes) + }; + let not_utf8 = base64::engine::general_purpose::STANDARD.encode(b"\xff"); + for (image, why) in [ + (long_png, TooManyBytes), + (svg(&deep), SvgTooNested), + (svg(&nodes), SvgTooNested), + (svg(r#""#), SvgFontRadius), + (svg(r#""#), SvgFontRadius), + (b64(r#""#), SvgTooSmall), + (not_utf8, SvgNotUtf8), + ] { + assert_eq!(marker_in(&mut Store::default(), &image).err(), Some(why), "{why:?}"); + } + // A radius of 0 em is 0, drawn; so is one in em where the shape takes no such radius. + for drawn in [r#""#, r#""#, r#""#] { + assert!(marker_in(&mut Store::default(), &svg(drawn)).is_ok(), "{drawn}"); + } } fn b64(text: &str) -> String { @@ -804,7 +879,7 @@ mod tests { // One too small to scale up isn't drawn; one thinner than a pixel is drawn a pixel thick, // its proportions those it is drawn at. let sized = |w: &str, h: &str| b64(&format!(r#""#)); - assert_eq!(marker_in(&mut store, &sized("1e-40", "1e-40")).err(), Some(MarkerRefusal::NotAnImage)); + assert_eq!(marker_in(&mut store, &sized("1e-40", "1e-40")).err(), Some(MarkerRefusal::SvgTooSmall)); for ((w, h), drawn) in [(("1e30", "1e-30"), (700, 1, 1.0 / 700.0)), (("1e-30", "1"), (1, 256, 256.0))] { let found = marker_in(&mut store, &sized(w, h)).unwrap(); assert_eq!((found.image.width(), found.image.height(), found.aspect), drawn, "{w} × {h}"); @@ -869,7 +944,7 @@ mod tests { // One past what a kept picture may be is refused before it is read, charging nothing. let mut store = Store::default(); let long = svg(format!("", " ".repeat(rustgis_map::symbology::MAX_PICTURE_BYTES))); - assert_eq!(marker_in(&mut store, &long).err(), Some(MarkerRefusal::TooMuchToDraw)); + assert_eq!(marker_in(&mut store, &long).err(), Some(MarkerRefusal::TooManyBytes)); assert_eq!((store.budget.pixels, store.budget.bytes), (0, 0)); } diff --git a/crates/render/src/picture/svg.rs b/crates/render/src/picture/svg.rs index 1bce8c5ddf..8a2da57b04 100644 --- a/crates/render/src/picture/svg.rs +++ b/crates/render/src/picture/svg.rs @@ -8,18 +8,19 @@ //! each arc into cubic curves, more the larger its radius ([`cubics`]): a 24-byte circle of radius //! 10³⁸ came to 9.6 million points, and a path's arc whose radius its ends stretch never finished. //! So what an SVG comes to is counted before it is read ([`elements`]), and it is taken only when -//! what it draws is worked out first ([`work`]), -//! from what the rasterizer does: the pixels each shape covers and the rows its edges cross, each -//! dash and each segment of a stroke, each layer a group with opacity, a clip or a mask draws -//! into. A unit is a pixel blended, about 13 ns, the dearest the rasterizer spends on one. The -//! measured cases all came within ~13 ns a unit; an icon is a few hundred thousand units. +//! what it draws is worked out first ([`work`]), from what the rasterizer does: the pixels each +//! shape covers and the rows its edges cross, each dash and each segment of a stroke, each layer a +//! group with opacity, a clip or a mask draws into. A unit is a pixel blended, about 13 ns, the +//! dearest the rasterizer spends on one. The measured cases all came within ~13 ns a unit; an icon +//! is a few hundred thousand units. //! //! Filters are refused outright: they cost per pixel by kind and parameter (a blur's radius, a //! turbulence's octaves, a morphology's, a convolution's), which a marker's icon rarely needs and //! a count can't bound without modelling each one. So is text (no fonts are loaded for it) and an //! image inside the SVG or one it links to (it would pass the image caps, or read a file): drawn -//! without them, an icon would lose them unsaid. So is animation (the still image is drawn) and -//! anything it takes from another file (a ``, a paint or a style sheet): no file is read. +//! without them, an icon would lose them unsaid. So is animation, which only its first frame would +//! show, and anything it takes from another file (a ``, a paint or a style sheet): no file +//! is read. use resvg::usvg; use usvg::roxmltree; @@ -31,6 +32,11 @@ pub(super) enum Refusal { NotSvg, /// It has more to draw than the cap given, or more elements than [`ELEMENTS`]. TooMuch, + /// It has more XML nodes than [`XML_NODES`], or nests deeper than [`DEPTH`]. + TooNested, + /// A shape's radius is in em or ex: font sizes, which no font is loaded to give, so it may be + /// any size. + FontRadius, /// It has filters, text, images, animation or links to other files, which aren't drawn (the /// module says why). Undrawn, @@ -59,23 +65,23 @@ const ARC_CUBICS: f64 = 200.0; const CSS_STEPS: u64 = 1_000_000; /// The most XML nodes (elements, text, comments) read before giving up, a bound on reading the /// text itself: [`ELEMENTS`] and the text and spaces between them. -const XML_NODES: u32 = 4 * ELEMENTS as u32; +pub(super) const XML_NODES: u32 = 4 * ELEMENTS as u32; /// The deepest nesting read (usvg's own bound is 1,024): icons nest a few levels, and the walks /// here recurse as deep. -const DEPTH: u32 = 64; +pub(super) const DEPTH: u32 = 64; /// What each element and each segment costs whatever its size, in units. const NODE: u64 = 100; -/// Each `STOPS` of a gradient's stops cost a unit a pixel, past two: tiny-skia then goes through -/// them all at each pixel (its `gradient` stage), some 0.7 ns a stop (measured: 1,000 stops 695 ns a pixel, -/// 100 stops 93 ns, 2 stops 21 ns). -const STOPS: u64 = 16; +/// What a gradient's stops are divided by to cost units a pixel: past two, tiny-skia goes through +/// them all at each pixel (its `gradient` stage), some 0.7 ns a stop (measured: 1,000 stops +/// 695 ns a pixel, 100 stops 93 ns, 2 stops 21 ns), so each stop costs 1/16 of a unit a pixel. +const STOPS_PER_UNIT: u64 = 16; /// SVG text `text` read into a tree: within [`XML_NODES`], [`ELEMENTS`], [`POINTS`] and /// [`CSS_STEPS`], its root an ``, with no images resolved and no files read. pub(super) fn read(text: &str) -> Result { let xml = roxmltree::ParsingOptions { allow_dtd: true, nodes_limit: XML_NODES, ..Default::default() }; let doc = roxmltree::Document::parse_with_options(text, xml).map_err(|e| match e { - roxmltree::Error::NodesLimitReached => Refusal::TooMuch, + roxmltree::Error::NodesLimitReached => Refusal::TooNested, _ => Refusal::NotSvg, })?; if doc.root_element().tag_name().name() != "svg" { @@ -84,9 +90,13 @@ pub(super) fn read(text: &str) -> Result { if doc.descendants().any(undrawn) { return Err(Refusal::Undrawn); } - if with_sheet(&doc, |sheet| elements(&doc, sheet).is_none() || nested_markers(&doc, sheet)) { - return Err(Refusal::TooMuch); + if doc.descendants().any(font_radius) { + return Err(Refusal::FontRadius); } + with_sheet(&doc, |sheet| { + elements(&doc, sheet)?; + if nested_markers(&doc, sheet) { Err(Refusal::TooMuch) } else { Ok(()) } + })?; let opt = usvg::Options { resources_dir: None, max_depth: DEPTH, @@ -99,6 +109,21 @@ pub(super) fn read(text: &str) -> Result { }) } +/// Whether shape `n` has a radius in em or ex other than 0 ([`Refusal::FontRadius`]), of those +/// usvg reads for it: a circle's `r`, an ellipse's or a rectangle's `rx` and `ry`. +fn font_radius(n: roxmltree::Node) -> bool { + use svgtypes::LengthUnit::{Em, Ex}; + let radii: &[&str] = match n.tag_name().name() { + "circle" => &["r"], + "ellipse" | "rect" => &["rx", "ry"], + _ => return false, + }; + radii + .iter() + .filter_map(|a| n.attribute(*a)) + .any(|v| v.trim().parse::().is_ok_and(|l| matches!(l.unit, Em | Ex) && l.number != 0.0)) +} + /// Whether `n` is something that isn't drawn: text, an image, animation, or what an SVG takes from /// another file (a ``, a gradient or pattern it inherits, a paint, a clip path or a style /// sheet's `@import` or `` from elsewhere, which usvg never reads); an HTML @@ -161,8 +186,8 @@ fn names_marker(n: roxmltree::Node) -> bool { }) } -/// Whether property `name` of `value` sets a marker: a marker property naming one (`url(#id)`), read -/// as usvg reads it; `none` sets none. +/// Whether property `name` of `value` sets a marker: a marker property naming one (`url(#id)`), +/// read as usvg reads it; `none` sets none. fn sets_marker(name: &str, value: &str) -> bool { is_marker(name) && svgtypes::FuncIRI::from_str(value).is_ok() } @@ -302,11 +327,11 @@ fn elsewhere(v: &str) -> bool { } /// The elements `doc` comes to once each `` is counted as what it repeats and each marker as -/// often as the vertices it can sit on; `None` past [`ELEMENTS`], its shapes' points ([`points_of`]) -/// counted so past [`POINTS`], nested past [`DEPTH`], matched to its style sheets past -/// [`CSS_STEPS`] ([`css_steps`]) or where a `` repeats itself (usvg drops those, but counting -/// it is no use). -fn elements(doc: &roxmltree::Document, sheet: &simplecss::StyleSheet) -> Option { +/// often as the vertices it can sit on. Refused nested past [`DEPTH`] ([`Refusal::TooNested`]); +/// past [`ELEMENTS`], its shapes' points ([`points_of`]) counted so past [`POINTS`], matched to its +/// style sheets past [`CSS_STEPS`] ([`css_steps`]) or where a `` repeats itself (usvg drops +/// those, but counting it is no use) as too much ([`Refusal::TooMuch`]). +fn elements(doc: &roxmltree::Document, sheet: &simplecss::StyleSheet) -> Result { // The first element of an id, as usvg takes it: counting another would count what isn't drawn. let mut ids = std::collections::HashMap::new(); for n in doc.descendants() { @@ -314,8 +339,9 @@ fn elements(doc: &roxmltree::Document, sheet: &simplecss::StyleSheet) -> Option< ids.entry(id).or_insert(n); } } - let mut counter = Counter { ids, seen: std::collections::HashMap::new(), viewport: viewport(doc), sheet, matched: 0 }; - let all = counter.count(doc.root_element(), 0)?; + let mut counter = Counter { ids, seen: std::collections::HashMap::new(), viewport: viewport(doc), sheet, matched: 0, deep: false }; + let refused = |c: &Counter| if c.deep { Refusal::TooNested } else { Refusal::TooMuch }; + let all = counter.count(doc.root_element(), 0).ok_or_else(|| refused(&counter))?; // A marker sits on the vertices (`marker-mid`) and both ends of the shapes that set it, by // attribute or style, or that inherit it from what holds them or from the `` that copies // them; a style sheet may set it on any shape. So each marker, its elements and their points, @@ -323,13 +349,14 @@ fn elements(doc: &roxmltree::Document, sheet: &simplecss::StyleSheet) -> Option< let vertices = if sheet_sets_marker(sheet) { all.points } else { all.marked }; let named = named_markers(doc, sheet); let used = |m: &roxmltree::Node| m.has_tag_name("marker") && m.attribute("id").is_some_and(|id| named.contains(id)); - let (markers, marked) = doc.descendants().filter(used).try_fold((0u64, 0u64), |sum, m| { - let c = counter.count(m, 0)?; - Some((sum.0.saturating_add(c.elements), sum.1.saturating_add(c.points))) - })?; + let (mut markers, mut marked) = (0u64, 0u64); + for m in doc.descendants().filter(used) { + let c = counter.count(m, 0).ok_or_else(|| refused(&counter))?; + (markers, marked) = (markers.saturating_add(c.elements), marked.saturating_add(c.points)); + } let total = all.elements.saturating_add(markers.saturating_mul(vertices)); let points = all.points.saturating_add(marked.saturating_mul(vertices)); - (total <= ELEMENTS && points <= POINTS).then_some(total) + (total <= ELEMENTS && points <= POINTS).then_some(total).ok_or(Refusal::TooMuch) } /// What an element and what's under it come to ([`elements`]). @@ -358,6 +385,8 @@ struct Counter<'a, 's> { sheet: &'s simplecss::StyleSheet<'s>, /// The steps the matching here has taken so far, each element once ([`css_steps`]). matched: u64, + /// Whether a count stopped for nesting past [`DEPTH`] ([`Refusal::TooNested`]). + deep: bool, } impl<'a> Counter<'a, '_> { @@ -367,10 +396,14 @@ impl<'a> Counter<'a, '_> { /// deeper. fn count(&mut self, n: roxmltree::Node<'a, 'a>, depth: u32) -> Option { if depth > DEPTH { + self.deep = true; return None; } match self.seen.get(&n.id()) { - Some(Some(done)) => return (depth + done.height <= DEPTH).then_some(*done), + Some(Some(done)) => { + self.deep |= depth + done.height > DEPTH; + return (depth + done.height <= DEPTH).then_some(*done); + } Some(None) => return None, None => {} } @@ -579,7 +612,7 @@ impl Cost { /// that is drawn nowhere). The only place nesting is bounded: every walk down comes here. fn group(&mut self, g: &usvg::Group, t: tiny_skia::Transform, onto: Option, depth: u32) -> Result<(), Refusal> { if depth > DEPTH { - return Err(Refusal::TooMuch); + return Err(Refusal::TooNested); } if !g.filters().is_empty() { return Err(Refusal::Undrawn); @@ -678,7 +711,7 @@ impl Cost { fn paint(&mut self, paint: &usvg::Paint, t: tiny_skia::Transform, covered: u64, depth: u32) -> Result<(), Refusal> { match paint { usvg::Paint::Color(_) => Ok(()), - // Past two stops, each of them at each pixel too ([`STOPS`]). + // Past two stops, each of them at each pixel too ([`STOPS_PER_UNIT`]). usvg::Paint::LinearGradient(g) => self.add(gradient(covered, g.stops().len())), usvg::Paint::RadialGradient(g) => self.add(gradient(covered, g.stops().len())), usvg::Paint::Pattern(pattern) => { @@ -694,9 +727,9 @@ impl Cost { } } -/// What a gradient of `stops` costs computed across `covered` pixels ([`STOPS`]). +/// What a gradient of `stops` costs computed across `covered` pixels ([`STOPS_PER_UNIT`]). fn gradient(covered: u64, stops: usize) -> u64 { - let through = if stops > 2 { covered.saturating_mul(stops as u64) / STOPS } else { 0 }; + let through = if stops > 2 { covered.saturating_mul(stops as u64) / STOPS_PER_UNIT } else { 0 }; covered.saturating_add(through) } @@ -770,7 +803,7 @@ mod tests { /// [`elements`] of `body`. fn element_count(body: &str) -> Option { - roxmltree::Document::parse(&svg(body)).map(|d| with_sheet(&d, |sheet| elements(&d, sheet))).unwrap() + roxmltree::Document::parse(&svg(body)).map(|d| with_sheet(&d, |sheet| elements(&d, sheet).ok())).unwrap() } /// What `body` costs drawn 100 × 100 pixels, a pixel a unit of its view. @@ -925,7 +958,6 @@ mod tests { r#""#, r#""#, r#""#, - r#""#, // Past [`ARC_CUBICS`]: some 220 curves to an arc nearly round (#2713). r#""#, ] { @@ -933,6 +965,9 @@ mod tests { assert_eq!((counted(body).0, read(&svg(body)).err()), (u64::MAX, Some(Refusal::TooMuch)), "{body}"); assert!(started.elapsed() < std::time::Duration::from_secs(1), "{body}"); } + // A radius in em or ex, a font's size, is refused as such (#2713). + let em = r#""#; + assert_eq!((counted(em).0, read(&svg(em)).err()), (u64::MAX, Some(Refusal::FontRadius))); } /// What isn't an SVG, or reads past its bounds, is refused while it is read: an entity loop, @@ -948,9 +983,9 @@ mod tests { let started = std::time::Instant::now(); assert_eq!(read(&laughs.replace("&g;", r#""#)).err(), Some(Refusal::NotSvg)); assert!(started.elapsed() < std::time::Duration::from_secs(1)); - assert_eq!(read(&svg(&"".repeat(XML_NODES as usize))).err(), Some(Refusal::TooMuch)); + assert_eq!(read(&svg(&"".repeat(XML_NODES as usize))).err(), Some(Refusal::TooNested)); let deep = format!("{}{}", "".repeat(2000), "".repeat(2000)); - assert_eq!(read(&svg(&deep)).err(), Some(Refusal::TooMuch)); + assert_eq!(read(&svg(&deep)).err(), Some(Refusal::TooNested)); // A marker on a shape inside another marker is drawn on each of that marker's vertices // too, which isn't counted: refused, by attribute, inherited or from a style sheet. let zigzag = "M0 0L1 1L2 0L3 1"; @@ -1171,7 +1206,7 @@ mod tests { let doc = roxmltree::Document::parse(&text).unwrap(); with_sheet(&doc, |sheet| { let (ids, seen) = (std::collections::HashMap::new(), std::collections::HashMap::new()); - let mut counter = Counter { ids, seen, viewport: 100.0, sheet, matched: 0 }; + let mut counter = Counter { ids, seen, viewport: 100.0, sheet, matched: 0, deep: false }; assert!(counter.count(doc.root_element(), 0).is_none()); assert!(counter.matched <= CSS_STEPS + 1, "{} steps", counter.matched); }); @@ -1203,7 +1238,7 @@ mod tests { let stops = (0..stops).map(|i| format!(r#""#, i as f32 / stops as f32)).collect::(); cost(&format!(r#"{stops}"#)).unwrap() }; - assert!(painted(1000) - painted(2) >= 10_000 * 1000 / STOPS, "{} {}", painted(1000), painted(2)); + assert!(painted(1000) - painted(2) >= 10_000 * 1000 / STOPS_PER_UNIT, "{} {}", painted(1000), painted(2)); } /// A subtree counted once where it is shallow is counted again where a `` reaches it @@ -1215,7 +1250,7 @@ mod tests { let doc = element_count; assert!(doc(&tree).is_some()); assert_eq!(doc(&format!("{tree}{deep}")), None); - assert_eq!(read(&svg(&format!("{tree}{deep}"))).err(), Some(Refusal::TooMuch)); + assert_eq!(read(&svg(&format!("{tree}{deep}"))).err(), Some(Refusal::TooNested)); } /// Geometry at the ends of what a float holds is drawn without panicking, when what it costs diff --git a/crates/ui-egui/src/markerpick.rs b/crates/ui-egui/src/markerpick.rs index 45295e42e9..788cc900ff 100644 --- a/crates/ui-egui/src/markerpick.rs +++ b/crates/ui-egui/src/markerpick.rs @@ -91,6 +91,20 @@ impl MarkerImage { "This image can't be a marker: it is an SVG with more to draw than a {side} × {side} image", &[("side", &rustgis_engine::render::MARKER_PIXELS_SIDE.to_string())], ), + // Past the file's own cap above, for completeness. + MarkerRefusal::TooManyBytes => crate::i18n::fmt( + "This image can't be a marker: it is longer than {mib} MiB as base64; make it smaller", + &[("mib", &(rustgis_engine::map::symbology::MAX_PICTURE_BYTES >> 20).to_string())], + ), + MarkerRefusal::SvgTooNested => tl!( + "This image can't be a marker: it is an SVG with more than 40,000 XML nodes or nested deeper than 64 levels" + ) + .to_string(), + MarkerRefusal::SvgFontRadius => { + tl!("This image can't be a marker: it is an SVG with a radius in em or ex, whose size RustGIS can't know").to_string() + } + MarkerRefusal::SvgTooSmall => tl!("This image can't be a marker: it is an SVG too small to draw").to_string(), + MarkerRefusal::SvgNotUtf8 => tl!("This image can't be a marker: it is an SVG that isn't UTF-8 text").to_string(), MarkerRefusal::SvgUndrawn => { tl!("This image can't be a marker: it is an SVG with filters, text, images, animation or links to other files, which RustGIS doesn't draw in marker images").to_string() } diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index 43602efca9..319a970f55 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -96,14 +96,14 @@ layer.marker={"layer":"Peaks","char":"▲","font":"DejaVu Sans","size":12} A marker can also be an **image**: a PNG or JPEG picked with **Image…** at the end of **Shape** (choose it again for another image), or a PNG, JPEG or SVG given by command as base64 (at most -2 MiB of base64 text, an image of about 1.5 MiB) and of at most 2048 × 2048 pixels (by area: a -4096 × 1024 strip is taken). Other formats, such as GIF, aren't taken: a file in another format, -one too large, or one that doesn't decode is said in a notice and leaves the marker as it was. -An SVG is drawn once into an image of its proportions, 256 to 700 pixels on its longer side (more -where it says it is larger), and kept as a PNG is. Its shapes, gradients, patterns, clip paths -and masks are drawn. One with filters (a blur, a shadow), text, images or links to other files (a -``, a paint or a style sheet from elsewhere) isn't taken, as they aren't drawn; nor is a file -read. What an SVG costs to draw is what it +2 MiB of base64 text, an image of about 1.5 MiB). A PNG or JPEG may have at most 2048 × 2048 +pixels (by area: a 4096 × 1024 strip is taken). Other formats, such as GIF, aren't taken: a file +in another format, one too large, or one that doesn't decode is said in a notice, with why, and +leaves the marker as it was. An SVG is drawn once into an image of its proportions, 256 pixels on +its longer side, or as many as it says up to 700, and kept as a PNG is. Its shapes, gradients, +patterns, clip paths and masks are drawn. One with filters (a blur, a shadow), text, images or +links to other files (a ``, a paint or a style sheet from elsewhere) isn't taken, as they +aren't drawn; nor is a file read. What an SVG costs to draw is what it paints, not its size: a few kilobytes of dashes finer than a pixel, or of see-through shapes piled up, can take minutes. So one with more to draw than a 2048 × 2048 image isn't taken either, nor one past 10,000 elements or 200,000 points of its shapes once each `` is counted where it @@ -111,8 +111,9 @@ repeats, nor one with a marker on a shape inside another marker (drawn on each o wherever it is). An arc is counted as the curves it is drawn with, more the larger its radius: one of more than 200 curves isn't taken, nor is a circle, an ellipse or a rounded corner whose radius is in em or ex, which may come to any size. A radius in % is counted as that share of the -largest size the SVG gives itself, unless a size inside it is in %, em or ex. Each image is -decoded once until RustGIS restarts, and kept decoded, at most 700 pixels a side: in all at most +largest size the SVG gives itself, unless its own width or height is in em or ex, or a size +inside it is in %, em or ex. Each image is decoded once until RustGIS restarts, and kept +decoded, at most 700 pixels a side: in all at most 256 megapixels of different marker images and 128 MiB once decoded (as many images as it keeps, at 177 × 177 each), so that a crafted file can't hold it for minutes; past it a new image is refused, or drawn as a circle, with a notice saying so, until RustGIS is restarted. A vector @@ -370,12 +371,13 @@ line** turns each mark with the line's direction; the **Angle** turns it further take the stroke's colour, its width as a hash mark's line (or a marker's outline, by command), and its offset to either side. Stack them with line strokes: a casing, a core and ticks across it. A marker can also be an image, with **Image…** under **Shape** or by command (`"image"`, a PNG, JPEG -or SVG as base64 of at most 2 MiB and 2048 × 2048 pixels, or as much to draw): as wide as its **Size** and as tall as -its proportions make it, turned with the line, the stroke's colour and outline left out; selected, -each is framed. An image a file gave that can't be drawn (too large to keep, one that doesn't -decode or that has too many pixels) shows as a circle; changing the strokes in the pane makes it -the circle, and says so. One past what RustGIS decodes until it restarts shows as a circle and is -kept as it is. By command, `"markers"` on a stroke: +or SVG as base64 of at most 2 MiB; a PNG or JPEG of at most 2048 × 2048 pixels, an SVG with no +more to draw than such an image): as wide as its **Size** and as tall as its proportions make it, +turned with the line, the stroke's colour and outline left out; selected, each is framed. An image +a file gave that can't be drawn (too large to keep, one that doesn't decode, that has too many +pixels or that is an SVG RustGIS can't draw) shows as a circle; changing the strokes in the pane +makes it the circle, and says so. One past what RustGIS decodes until it restarts shows as a +circle and is kept as it is. By command, `"markers"` on a stroke: ```text layer.lineStrokes={"layer":"Railways","strokes":[{"color":"#333333","width":1.5},{"color":"#333333","width":1,"markers":{"mark":"hash","size":6,"interval":10}}]} diff --git a/docs/user-guide/workspace.md b/docs/user-guide/workspace.md index 92e1e57b36..48810192e8 100644 --- a/docs/user-guide/workspace.md +++ b/docs/user-guide/workspace.md @@ -337,8 +337,8 @@ Each layer keeps its look: lines as strokes of markers or hash marks, at their places (intervals, vertices, the ends, the middle), turned with the line, their markers' offsets and angles kept; font markers as characters of their font, on points and along lines; raster image markers as - [image markers](cartography.md#symbology) of their PNG, JPEG or SVG (embedded in the file, or a file - of their own, relative to the project's folder or, in a style, to the style's), on points + [image markers](cartography.md#symbology) of their PNG, JPEG or SVG (embedded in the file, or a + file of their own, relative to the project's folder or, in a style, to the style's), on points (anchored where QGIS anchors them) and along lines; a marker symbol of several layers, or one shifted, turned or anchored off its centre, as a point's marks; a marker angle taken from a field (`"field"` or `- "field"`) as the layer's rotation field; a fill symbol of several layers