diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 136a9b3129..60da4336f6 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -2270,7 +2270,7 @@ pub(crate) fn picture_notices_by<'a>( ), ( unknown_radius, - "Image markers in {names} are SVGs with a radius whose size RustGIS can't know (in em or ex, or in % of a size in em, ex or %), and are drawn as circles", + "Image markers in {names} are SVGs with a radius whose size RustGIS can't know (in em or ex, or in % of a size in em or ex, or of a nested size in % over 100%), 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"), diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 42331709e6..27b0bd246f 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2704,7 +2704,7 @@ fn svg_image_markers_that_dont_draw_are_said_with_why() { ), ( MarkerRefusal::SvgUnknownRadius, - "Image markers in \"Cities\", \"Rivers\" are SVGs with a radius whose size RustGIS can't know (in em or ex, or in % of a size in em, ex or %), and are drawn as circles", + "Image markers in \"Cities\", \"Rivers\" are SVGs with a radius whose size RustGIS can't know (in em or ex, or in % of a size in em or ex, or of a nested size in % over 100%), 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"), diff --git a/crates/render/src/picture.rs b/crates/render/src/picture.rs index 7e0ec25321..0e643e1bf2 100644 --- a/crates/render/src/picture.rs +++ b/crates/render/src/picture.rs @@ -85,7 +85,8 @@ pub enum MarkerRefusal { /// `svg::DEPTH` (64). SvgTooNested, /// It is an SVG with a radius that may be any size: in em or ex, a font's size, or in % of a - /// size in em, ex or % (other than the whole SVG's in %). + /// size in em or ex, or of a size in % over 100% (other than the whole SVG's in %). An `` + /// with a view box takes the % from it, whatever its own size. SvgUnknownRadius, /// It is an SVG too small to scale up to a pixmap (its size near 0). SvgTooSmall, @@ -136,7 +137,7 @@ refusal_phrases! { 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", - SvgUnknownRadius => "is an SVG with a radius whose size RustGIS can't know (in em or ex, or in % of a size in em, ex or %)", + SvgUnknownRadius => "is an SVG with a radius whose size RustGIS can't know (in em or ex, or in % of a size in em or ex, or of a nested size in % over 100%)", 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", @@ -178,7 +179,8 @@ struct Decoded { /// A picture marker's decoded image, or why it is drawn as a circle. type Marker = Result, MarkerRefusal>; -/// What the run has decoded of picture markers' images: the pixels they declared and the bytes +/// What the run has decoded of picture markers' images: the pixels they declared (for an SVG, the +/// units its reading, its style sheets' matching and its drawing came to) and the bytes /// they hold, decoded or compressed ([`RUN_MARKER_PIXELS`], [`RUN_MARKER_BYTES`]: compressed /// copies can take the bytes past it). #[derive(Default)] @@ -231,8 +233,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 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). +/// [`MARKER_PIXELS`]; for an SVG, its reading (some 50 ms at the length a kept picture may be, and +/// some 45 ms more matching its style sheets at most, [`svg::CSS_STEPS`]) 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()) @@ -256,8 +259,9 @@ fn content_id(b64: &str) -> u128 { /// first bytes or its header) isn't kept: finding that again costs as little. /// /// Commands and a project's read check images on the UI thread. One image takes at most ~80 ms -/// ([`MARKER_PIXELS`] at ~19 ns a pixel); everything a run decodes, ~5 s ([`RUN_MARKER_PIXELS`]), -/// once: one call or file can spend it all, and after that a new image is refused from its header. +/// ([`MARKER_PIXELS`] at ~19 ns a pixel), and an SVG its reading and matching besides ([`store`]); +/// everything a run decodes, ~5 s ([`RUN_MARKER_PIXELS`]), once: one call or file can spend it +/// all, and after that a new image is refused from its header. /// Kept on the UI thread for that bound: the check answers whether the command is taken. fn marker(b64: &str) -> Marker { marker_in(&mut store(), b64) @@ -268,7 +272,8 @@ 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). + // What a kept picture may be, whoever checks it: reading an SVG is then bounded too (~50 ms); + // matching its style sheets is bounded apart (`svg::CSS_STEPS`). if b64.len() > rustgis_map::symbology::MAX_PICTURE_BYTES { return Err(TooManyBytes); } @@ -302,17 +307,33 @@ fn marker_in(store: &mut Store, b64: &str) -> Marker { found } -/// [`marker_in`] for SVG `bytes` (`id` in the store): its reading charged first, by its length; -/// then what drawing it costs ([`svg::work`]) and the bytes it holds, before it is drawn. Kept -/// whatever comes of it, refused or not (reading it again would cost as much), but for the run's -/// refusal, which a later image giving back bytes may lift, as for a PNG. +/// [`marker_in`] for SVG `bytes` (`id` in the store). Its reading is charged first, by its length. +/// Matching its style sheets is charged once read, by the steps it took ([`svg::CSS_STEPS`]), a +/// pixel each (a step takes some 11 ns, a pixel some 19 ns) and at least [`MARKER_CHARGE`] as every +/// charge, refused or not, as a few hundred bytes of selectors can take them all. Then what drawing +/// it costs ([`svg::work`]) and the bytes it holds are charged, before it is drawn. Kept whatever +/// comes of it, refused or not (reading it again would cost as much), but for the run's refusal, +/// which a later image giving back bytes may lift, as for a PNG. A refusal for the run that its +/// matching meets is kept too: that charges pixels alone, which nothing gives back. fn svg_in(store: &mut Store, id: u128, bytes: &[u8]) -> Marker { use MarkerRefusal::*; 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(|_| SvgNotUtf8).and_then(|text| svg::read(text).map_err(MarkerRefusal::from)); + // Matching takes at most what the run has left, so the run's bound holds for it too. + let room = RUN_MARKER_PIXELS.saturating_sub(store.budget.pixels); + let mut matched = 0; + let tree = text.map_err(|_| SvgNotUtf8).and_then(|text| svg::read(text, room, &mut matched).map_err(MarkerRefusal::from)); + let matching_charge = if matched > 0 { store.budget.take(matched, 0, limits) } else { Ok(()) }; + // Refused for the run by its matching, past the run's pixels, which are never given back, it + // stays refused until RustGIS restarts, and is kept: reading it again would only match it again. + let keep_refusal = matching_charge.is_err() || matches!(tree, Err(PastRunPixels)); + // An SVG refused for itself keeps its cause, even when its matching's charge finds the run + // at its end: only one that would be drawn is then refused for the run (the charge is met + // after its own checks). Matching that reaches what the run has left inside `svg::read` + // refuses it for the run first, before its later checks (nested markers) run: finding its + // own cause would take that matching. let found = tree.and_then(|tree| { let size = tree.size(); let (w, h) = (size.width(), size.height()); @@ -327,6 +348,8 @@ fn svg_in(store: &mut Store, id: u128, bytes: &[u8]) -> Marker { } let at = Transform::from_scale(sx, sy); let work = svg::work(&tree, (pw, ph), at, MARKER_PIXELS)?; + // Charged once its own checks pass: one too small or with too much to draw says so. + matching_charge?; let held = u64::from(pw) * u64::from(ph) * 4; store.budget.take(work, held, limits)?; let Some(image) = svg::draw(&tree, (pw, ph), at) else { @@ -336,7 +359,7 @@ fn svg_in(store: &mut Store, id: u128, bytes: &[u8]) -> Marker { // Its proportions as drawn, as a PNG's: one thinner than a pixel is drawn a pixel thick. Ok(Arc::new(Decoded { image: Arc::new(image), aspect: ph as f32 / pw as f32, packed: OnceLock::new() })) }); - if !matches!(found, Err(PastRunPixels)) { + if keep_refusal || !matches!(found, Err(PastRunPixels)) { store.images.insert(id, found.clone()); } found @@ -347,6 +370,7 @@ impl From for MarkerRefusal { match why { svg::Refusal::NotSvg => MarkerRefusal::NotAnImage, svg::Refusal::TooMuch => MarkerRefusal::TooMuchToDraw, + svg::Refusal::PastRun => MarkerRefusal::PastRunPixels, svg::Refusal::TooNested => MarkerRefusal::SvgTooNested, svg::Refusal::UnknownRadius => MarkerRefusal::SvgUnknownRadius, svg::Refusal::Undrawn => MarkerRefusal::SvgUndrawn, @@ -819,6 +843,48 @@ mod tests { assert!(MarkerRefusal::SvgTooNested.what().contains(&nested)); } + /// Matching an SVG's style sheets is charged to the run once it is read, refused or not: a few + /// hundred bytes of selectors can take every step there is (#2864). + #[test] + fn an_svgs_style_sheet_matching_is_charged_to_the_run() { + let deep = format!("{}{}", "".repeat(40), "".repeat(40)); + let text = format!(r#"{deep}"#); + let mut store = Store::default(); + assert_eq!(marker_in(&mut store, &b64(&text)).err(), Some(MarkerRefusal::TooMuchToDraw)); + assert!(store.budget.pixels >= svg::CSS_STEPS, "{} charged", store.budget.pixels); + // With the run near its end, matching stops where the run does: refused for the run, and + // kept, as the pixels the run charged are never given back. + let mut full = Store::default(); + full.budget.pixels = RUN_MARKER_PIXELS - 100_000; + assert_eq!(marker_in(&mut full, &b64(&text)).err(), Some(MarkerRefusal::PastRunPixels)); + assert_eq!(full.images.len(), 1); + assert!(full.budget.pixels <= RUN_MARKER_PIXELS); + // So is one it would draw, the run at its end. + let drawn = r#""#; + let mut spent = Store::default(); + spent.budget.pixels = RUN_MARKER_PIXELS - MARKER_CHARGE; + assert_eq!(marker_in(&mut spent, &b64(drawn)).err(), Some(MarkerRefusal::PastRunPixels)); + assert_eq!(spent.images.len(), 1); + assert!(marker_in(&mut Store::default(), &b64(drawn)).is_ok(), "drawn with the run's room"); + // One matched within the run's room but refused for itself keeps its cause, and is kept, + // even when its matching's charge finds the run at its end. + let nested = r#""#; + let mut near = Store::default(); + near.budget.pixels = RUN_MARKER_PIXELS - MARKER_CHARGE - 100; + assert_eq!(marker_in(&mut near, &b64(nested)).err(), Some(MarkerRefusal::TooMuchToDraw)); + assert_eq!(near.images.len(), 1); + // So does one too small to draw, refused after it is read (#2864). + let small = r#""#; + let mut low = Store::default(); + low.budget.pixels = RUN_MARKER_PIXELS - MARKER_CHARGE - 100; + assert_eq!(marker_in(&mut low, &b64(small)).err(), Some(MarkerRefusal::SvgTooSmall)); + // An SVG with no style sheet matches nothing, so the run's room left doesn't refuse it. + let plain = r#""#; + let mut room = Store::default(); + room.budget.pixels = RUN_MARKER_PIXELS - 10 * MARKER_CHARGE; + assert!(marker_in(&mut room, &b64(plain)).is_ok()); + } + /// Each refusal says its own cause (#2713): a long image, an SVG nested deep or with many /// nodes, a radius whose size can't be known, one too small to draw, one that isn't UTF-8. #[test] @@ -839,14 +905,12 @@ mod tests { (svg(&nodes), SvgTooNested), (svg(r#""#), SvgUnknownRadius), (svg(r#""#), SvgUnknownRadius), - // A radius in % of a size in em or ex, or of a nested one in %. + // A radius in % of a size in em or ex with no view box, or of a nested one past 100%. ( - b64( - r#""#, - ), + b64(r#""#), SvgUnknownRadius, ), - (svg(r#""#), SvgUnknownRadius), + (svg(r#""#), SvgUnknownRadius), (b64(r#""#), SvgTooSmall), (not_utf8, SvgNotUtf8), ] { diff --git a/crates/render/src/picture/svg.rs b/crates/render/src/picture/svg.rs index 291517a82e..2dc44450bf 100644 --- a/crates/render/src/picture/svg.rs +++ b/crates/render/src/picture/svg.rs @@ -40,6 +40,9 @@ pub(super) enum Refusal { /// It has filters, text, images, animation or links to other files, which aren't drawn (the /// module says why). Undrawn, + /// Matching its style sheets reached the cap given, below [`CSS_STEPS`]: what the run had + /// left, not the SVG, stopped it. + PastRun, } /// The most elements an SVG may have once its ``s and markers are counted where they repeat: @@ -59,10 +62,11 @@ const ARC_CUBICS: f64 = 200.0; /// each element is tried against each rule, and a selector's descendant (`a b`) against every /// element above it, again for each descendant before it, so a few of them deep down come to /// millions (`x g g g g g g rect` 40 levels down took 0.5 s). A step is some 11 ns (measured: a -/// class rule on an element, two steps, 22 ns), so ~11 ms: some 500,000 rules tried on elements, -/// 200 class rules on 2,500 elements. An attribute's value matched costs a step each 64 bytes too, -/// and each node walked back past to a sibling one. Icons take thousands of steps. -const CSS_STEPS: u64 = 1_000_000; +/// class rule on an element, two steps, 22 ns), so ~45 ms: some 2,000,000 rules tried on +/// elements, 200 class rules (an exported icon's one class per style) on [`ELEMENTS`]. An +/// attribute's value matched costs a step each 64 bytes too, and each node walked back past to a +/// sibling one. Icons take thousands of steps. +pub(super) const CSS_STEPS: u64 = 4_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. pub(super) const XML_NODES: u32 = 4 * ELEMENTS as u32; @@ -77,8 +81,11 @@ const NODE: u64 = 100; 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 { +/// [`CSS_STEPS`], its root an ``, with no images resolved and no files read. Matching its +/// style sheets ([`css_steps`]) stops at `cap` too, what the run has left, refused there for the +/// run ([`Refusal::PastRun`]) when below [`CSS_STEPS`]; `matched` is set to the steps it took, +/// refused or not, which its length doesn't bound, for the run to be charged them. +pub(super) fn read(text: &str, cap: u64, matched: &mut u64) -> 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::TooNested, @@ -95,8 +102,8 @@ pub(super) fn read(text: &str) -> Result { return Err(Refusal::UnknownRadius); } with_sheet(&doc, |sheet| { - elements(&doc, sheet)?; - if nested_markers(&doc, sheet) { Err(Refusal::TooMuch) } else { Ok(()) } + let (_, by_sheet) = elements(&doc, sheet, cap, matched)?; + if nested_markers(&doc, &by_sheet) { Err(Refusal::TooMuch) } else { Ok(()) } })?; let opt = usvg::Options { resources_dir: None, @@ -168,19 +175,20 @@ fn undrawn(n: roxmltree::Node) -> bool { /// Whether a marker may be drawn on a shape inside another marker: usvg draws it on each of that /// marker's vertices wherever that marker is (its `convert_children` of a marker), which /// [`elements`] doesn't count. A shape there takes a marker by inheritance: from itself or what -/// holds it inside the marker, from the marker and what holds it, from a style sheet (whose reach -/// isn't read here), or, through a `` in the marker, from anything the copy it makes holds or -/// that holds it. So any of those naming a marker counts. One marker can only nest itself, a cycle -/// usvg drops (it follows a ``'s copy too). -fn nested_markers(doc: &roxmltree::Document, sheet: &simplecss::StyleSheet) -> bool { +/// holds it inside the marker, from the marker and what holds it, or, through a `` in the +/// marker, from anything the copy it makes holds or that holds it; each by attribute, in its +/// `style` or from a style sheet whose selector reaches it (`by_sheet`, from [`elements`]). So any +/// of those setting a marker counts. A `` in a marker is taken broadly: anything that sets a +/// marker, wherever it is, counts. One marker can only nest itself, a cycle usvg drops (it follows +/// a ``'s copy too). +fn nested_markers(doc: &roxmltree::Document, by_sheet: &std::collections::HashSet) -> bool { let markers: Vec<_> = doc.descendants().filter(|n| n.has_tag_name("marker")).collect(); if markers.len() < 2 { return false; } + let sets = |n: roxmltree::Node| names_marker(n) || by_sheet.contains(&n.id()); let uses = markers.iter().any(|m| m.descendants().any(|n| n.has_tag_name("use"))); - sheet_sets_marker(sheet) - || markers.iter().any(|m| m.ancestors().any(names_marker) || m.descendants().any(names_marker)) - || (uses && doc.descendants().any(names_marker)) + markers.iter().any(|m| m.ancestors().any(sets) || m.descendants().any(sets)) || (uses && doc.descendants().any(sets)) } /// Whether element `n` sets a marker on what it draws and holds, by attribute or in its `style`. @@ -197,11 +205,6 @@ fn sets_marker(name: &str, value: &str) -> bool { is_marker(name) && svgtypes::FuncIRI::from_str(value).is_ok() } -/// Whether style sheet `sheet` sets a marker, on whatever its selectors reach. -fn sheet_sets_marker(sheet: &simplecss::StyleSheet) -> bool { - sheet.rules.iter().any(|r| r.declarations.iter().any(|d| sets_marker(d.name, d.value))) -} - /// The ids of the markers a marker property names (`url(#id)`), by attribute, in a `style` or in /// style sheet `sheet`, read as usvg reads them: no other is drawn. fn named_markers(doc: &roxmltree::Document, sheet: &simplecss::StyleSheet) -> std::collections::HashSet { @@ -231,17 +234,26 @@ fn is_marker(name: &str) -> bool { /// The steps matching `sheet`'s rules to element `n` takes, as usvg matches them before reading /// it (each rule tried with simplecss's own matcher, each step counted), on top of the `spent` -/// that matching other elements took; `None` past [`CSS_STEPS`] in all, where it is stopped. -fn css_steps(n: roxmltree::Node, sheet: &simplecss::StyleSheet, spent: u64) -> Option { +/// that matching other elements took, and whether a rule that sets a marker (`marking`, by rule) +/// matches it (one a later rule may take back counts too: more, never less); `None` past +/// [`CSS_STEPS`] in all, where it is stopped (`spent` starts short of it by the cap given, +/// [`elements`]). +fn css_steps(n: roxmltree::Node, sheet: &simplecss::StyleSheet, marking: &[bool], spent: u64) -> Option<(u64, bool)> { let steps = std::cell::Cell::new(spent); - for rule in &sheet.rules { + let mut marks = false; + for (i, rule) in sheet.rules.iter().enumerate() { + // Each rule is tried: one `marking` doesn't name is taken to set a marker. + // `elements` gives a flag for each rule; a rule without one (only the tests leave some + // out) counts as setting a marker, which only ever refuses more. + let sets = marking.get(i).copied().unwrap_or(true); steps.set(steps.get() + 1); - rule.selector.matches(&Stepped(n, &steps)); + let matched = rule.selector.matches(&Stepped(n, &steps)); if steps.get() > CSS_STEPS { return None; } + marks |= matched && sets; } - Some(steps.get() - spent) + Some((steps.get() - spent, marks)) } /// An element as simplecss matches it, each step it takes counted in the cell; past @@ -249,7 +261,8 @@ fn css_steps(n: roxmltree::Node, sheet: &simplecss::StyleSheet, spent: u64) -> O struct Stepped<'a, 'input>(roxmltree::Node<'a, 'input>, &'a std::cell::Cell); impl<'a, 'input> Stepped<'a, 'input> { - /// Counts a step: whether it is still within [`CSS_STEPS`]. + /// Counts a step: whether it is still within [`CSS_STEPS`]. The cell starts at `CSS_STEPS - cap` + /// ([`elements`]), so that is whether the steps taken are still within the cap. fn step(&self) -> bool { self.steps(1) } @@ -335,8 +348,17 @@ fn elsewhere(v: &str) -> bool { /// 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 { +/// those, but counting it is no use) as too much ([`Refusal::TooMuch`]). Returns the count and +/// the set of the elements a style sheet sets a marker on; matching stops at `cap` as at +/// [`CSS_STEPS`] ([`read`]), and `matched` is set to the steps it took, refused or not, each +/// ``'s copy counted again as usvg matches it again. +fn elements( + doc: &roxmltree::Document, + sheet: &simplecss::StyleSheet, + cap: u64, + matched: &mut u64, +) -> Result<(u64, std::collections::HashSet), Refusal> { + let cap = cap.min(CSS_STEPS); // 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() { @@ -349,21 +371,46 @@ fn elements(doc: &roxmltree::Document, sheet: &simplecss::StyleSheet) -> Result< seen: std::collections::HashMap::new(), viewport: viewport(doc).unwrap_or(f64::from(f32::MAX)), sheet, - matched: 0, + // Read once, not on each element a rule matches: a rule may hold thousands of declarations. + marking: sheet.rules.iter().map(|r| r.declarations.iter().any(|d| sets_marker(d.name, d.value))).collect(), + // Started as far along as the cap leaves, so that matching stops at it as at the whole. + matched: CSS_STEPS - cap, + cap, + by_sheet: std::collections::HashSet::new(), deep: false, + run_capped: false, + }; + let counted = match count_all(doc, &mut counter) { + // Past the elements written out it is too much for itself, which is known for nothing. + Err(Refusal::PastRun) if doc.descendants().filter(|n| n.is_element()).count() as u64 > ELEMENTS => Err(Refusal::TooMuch), + counted => counted, + }; + *matched = counter.matched.saturating_sub(CSS_STEPS - cap); + counted.map(|total| (total, counter.by_sheet)) +} + +/// [`elements`]'s count with `counter`, apart from it so that the steps matched are read +/// whatever comes of the count. +fn count_all<'a>(doc: &'a roxmltree::Document<'a>, counter: &mut Counter<'a, '_>) -> Result { + let refused = |c: &Counter| match (c.deep, c.run_capped) { + (true, _) => Refusal::TooNested, + (_, true) => Refusal::PastRun, + _ => Refusal::TooMuch, }; - 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))?; + let all = counter.count(doc.root_element(), 0).ok_or_else(|| refused(counter))?; + // What usvg takes: each ``'s copy matched again, which the steps of each element once + // leave out. + counter.matched = counter.matched.max((CSS_STEPS - counter.cap).saturating_add(all.steps)); // 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, - // is counted as if on all of those vertices: none for a marker nothing names. - let vertices = if sheet_sets_marker(sheet) { all.points } else { all.marked }; - let named = named_markers(doc, sheet); + // attribute, style or a style sheet's rule that reaches them, or that inherit it from what + // holds them or from the `` that copies them. So each marker, its elements and their + // points, is counted as if on all of those vertices: none for a marker nothing names. + let vertices = all.marked; + let named = named_markers(doc, counter.sheet); let used = |m: &roxmltree::Node| m.has_tag_name("marker") && m.attribute("id").is_some_and(|id| named.contains(id)); 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))?; + 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)); @@ -377,7 +424,8 @@ struct Counted { elements: u64, /// Its shapes' points ([`points_of`]). points: u64, - /// The points of those that set a marker or inherit one from what holds them here. + /// The points of those that set a marker (by attribute, style or style sheet) or inherit one + /// from what holds them here. marked: u64, /// The levels under it, ``s counted as levels. height: u32, @@ -395,17 +443,26 @@ struct Counter<'a, 's> { viewport: f64, /// The style sheets. sheet: &'s simplecss::StyleSheet<'s>, - /// The steps the matching here has taken so far, each element once ([`css_steps`]). + /// Whether each of their rules sets a marker ([`sets_marker`]). + marking: Vec, + /// The steps the matching here has taken so far, each element once ([`css_steps`]), from as far + /// along as `cap` leaves of [`CSS_STEPS`]. matched: u64, + /// The most steps matching may take here ([`elements`]). + cap: u64, + /// The elements a style sheet's rule sets a marker on ([`css_steps`]). + by_sheet: std::collections::HashSet, /// Whether a count stopped for nesting past [`DEPTH`] ([`Refusal::TooNested`]). deep: bool, + /// Whether matching stopped at `cap`, below [`CSS_STEPS`] ([`Refusal::PastRun`]). + run_capped: bool, } impl<'a> Counter<'a, '_> { - /// What element `n`, `depth` levels down, comes to; `None` past [`ELEMENTS`], [`DEPTH`] or - /// [`CSS_STEPS`], or for a `` that repeats itself. Each element is counted once and its - /// count kept, but its levels are checked again wherever it is reached: a `` may reach it - /// deeper. + /// What element `n`, `depth` levels down, comes to; `None` past [`ELEMENTS`], [`DEPTH`] or the + /// steps `cap` leaves ([`elements`]), or for a `` that repeats itself. Each element is + /// counted once and its count kept, but its levels are checked again wherever it is reached: a + /// `` may reach it deeper. fn count(&mut self, n: roxmltree::Node<'a, 'a>, depth: u32) -> Option { if depth > DEPTH { self.deep = true; @@ -429,8 +486,16 @@ impl<'a> Counter<'a, '_> { .has_tag_name("use") .then(|| href.and_then(|h| svgtypes::IRI::from_str(h).ok()).and_then(|iri| self.ids.get(iri.0).copied())) .flatten(); - let steps = css_steps(n, self.sheet, self.matched)?; + // Stopped past the cap, all of it spent. + let Some((steps, sets)) = css_steps(n, self.sheet, &self.marking, self.matched) else { + self.matched = CSS_STEPS; + self.run_capped = self.cap < CSS_STEPS; + return None; + }; self.matched = self.matched.saturating_add(steps); + if sets { + self.by_sheet.insert(n.id()); + } let mut total = Counted { elements: 1, points: points_of(n, self.viewport), marked: 0, height: 0, steps }; for under in n.children().filter(|c| c.is_element()).chain(used) { let c = self.count(under, depth + 1)?; @@ -439,12 +504,14 @@ impl<'a> Counter<'a, '_> { total.marked = total.marked.saturating_add(c.marked); total.height = total.height.max(c.height + 1); total.steps = total.steps.saturating_add(c.steps); - if total.elements > ELEMENTS || total.steps > CSS_STEPS { + if total.elements > ELEMENTS || total.steps > self.cap { + // Past the elements it is too much for itself, which is known for nothing. + self.run_capped = total.elements <= ELEMENTS && self.cap < CSS_STEPS; return None; } } // What sets a marker sets it on all it draws and holds. - if names_marker(n) { + if names_marker(n) || sets { total.marked = total.points; } self.seen.insert(n.id(), Some(total)); @@ -454,22 +521,31 @@ impl<'a> Counter<'a, '_> { /// The largest a viewport of `doc` may be, which a length in % is a part of: its view boxes and the /// sizes of its ``s, ``s and ``s, as usvg takes them for one (100 a side -/// without). The root's size in % is of 100 a side. `None` when one may be any size: the root's in -/// em or ex, or another's in %, em or ex. +/// without). An `` with a view box takes its % from it, whatever its own size (usvg's +/// `convert_svg`, and `resolve_svg_size` for the root). The root's size in % is of 100 a side; +/// another's is of the viewport around it, so one of at most 100% is at most as large. `None` when +/// one may be any size: one in em or ex (but an ``'s with a view box), or another than the +/// root's past 100%. fn viewport(doc: &roxmltree::Document) -> Option { use svgtypes::LengthUnit::{Em, Ex, Percent}; let root = doc.root_element(); let mut largest = 100.0f64; for n in doc.descendants().filter(|n| n.is_element()) { - if let Some(b) = n.attribute("viewBox").and_then(|v| v.parse::().ok()) { + let view_box = n.attribute("viewBox").and_then(|v| v.parse::().ok()); + if let Some(b) = view_box { largest = largest.max(b.w.abs()).max(b.h.abs()); } - if matches!(n.tag_name().name(), "svg" | "symbol" | "use") { + let sized = match n.tag_name().name() { + "svg" => view_box.is_none(), + "symbol" | "use" => true, + _ => false, + }; + if sized { for side in ["width", "height"].iter().filter_map(|&a| n.attribute(a)) { - let unknown = side - .trim() - .parse::() - .is_ok_and(|l| l.number != 0.0 && (matches!(l.unit, Em | Ex) || (l.unit == Percent && n != root))); + // One in % of at most 100 comes to at most 100 here, below `largest`. + let unknown = side.trim().parse::().is_ok_and(|l| { + l.number != 0.0 && (matches!(l.unit, Em | Ex) || (l.unit == Percent && n != root && l.number.abs() > 100.0)) + }); if unknown { return None; } @@ -816,13 +892,20 @@ pub(super) fn draw(tree: &usvg::Tree, (w, h): (u32, u32), t: tiny_skia::Transfor mod tests { use super::*; + /// [`super::read`], what its matching took left out. + fn read(text: &str) -> Result { + super::read(text, CSS_STEPS, &mut 0) + } + fn svg(body: &str) -> String { format!(r#"{body}"#) } /// [`elements`] of `body`. fn element_count(body: &str) -> Option { - roxmltree::Document::parse(&svg(body)).map(|d| with_sheet(&d, |sheet| elements(&d, sheet).ok())).unwrap() + roxmltree::Document::parse(&svg(body)) + .map(|d| with_sheet(&d, |sheet| elements(&d, sheet, CSS_STEPS, &mut 0).ok().map(|(n, _)| n))) + .unwrap() } /// What `body` costs drawn 100 × 100 pixels, a pixel a unit of its view. @@ -887,8 +970,13 @@ mod tests { assert_eq!(none(r#"style="marker: none""#), none("")); // On the big path, past the elements. assert_eq!(doc(&format!(r#""#)), None); - // A style sheet that sets a marker may reach any shape: every vertex counts. + // A style sheet sets a marker on the shapes its selectors reach, and what they hold: their + // vertices count, the others' don't (#2864). let sheet = |rule: &str| doc(&format!(r#""#)); + let reached = + |rule: &str, on: &str| doc(&format!(r#"{on}"#)); + assert_eq!(reached(".e { marker-end: url(#m) }", &format!(r#""#)), Some(6 + 2 * 6)); + assert_eq!(reached("g.e { marker-end: url(#m) }", &format!(r#""#)), Some(7 + 2 * 6)); assert_eq!(sheet("path { marker-mid: url(#m) }"), None); assert_eq!(sheet("path { MARKER : url(#m) }"), None); // Read as the reader reads it: past a comment before the colon, after a `*`. @@ -966,6 +1054,9 @@ mod tests { r#""#, r#""#, r#""#, + // Of a nested viewport, at most the one around it, or its own view box (#2864). + r#""#, + r#""#, r#""#, r#""#, ] { @@ -973,15 +1064,36 @@ mod tests { let drawn = drawn.unwrap_or_else(|why| panic!("{body}: {why:?}")); assert!(points >= drawn && points < POINTS, "{body}: {points} counted, {drawn} drawn"); } - // A % radius in a viewport whose size isn't known (a nested one in %, a root in em) is - // refused for it, as one in em or ex is (#2713). - let nested = svg(r#""#); - assert_eq!(read(&nested).err(), Some(Refusal::UnknownRadius)); + // A % radius in a viewport whose size isn't known (a nested one past 100% or in em without + // a view box, a root in em without one) is refused for it, as one in em or ex is (#2713). + // A view box of no size is no view box, as usvg takes it (svgtypes refuses it). + for (open, close) in [ + (r#""#, ""), + (r#""#, ""), + (r#""#, ""), + (r#""#, r##""##), + ] { + let body = svg(&format!(r#"{open}{close}"#)); + assert_eq!(read(&body).err(), Some(Refusal::UnknownRadius), "{body}"); + } + assert_eq!(read(&svg(r#""#)).err(), Some(Refusal::UnknownRadius)); let em_root = r#""#; assert_eq!(read(em_root).err(), Some(Refusal::UnknownRadius)); + // But a nested size of at most 100% is at most the viewport around it, and an `` with + // a view box takes its % from it whatever its own size, the root's too (#2864). + for known in [ + svg(r#""#), + svg(r#""#), + svg(r#""#), + em_root.replace(r#"height="2em""#, r#"height="2em" viewBox="0 0 20 20""#), + ] { + assert!(read(&known).is_ok(), "{known}"); + } // Against a nested viewport of its own size. let large = svg(r#""#); assert_eq!(read(&large).err(), Some(Refusal::TooMuch)); + // A view box makes the % of its own, however large the size it is drawn at (#2864). + assert!(read(&svg(r#""#)).is_ok()); for body in [ r#""#, r#""#, @@ -1055,6 +1167,27 @@ mod tests { // With a style sheet that only names a class like a marker, they are read too (#2713). let classed = format!(r#"{side}"#); assert!(read(&svg(&classed)).is_ok()); + // A style sheet that sets a marker only on shapes outside the markers nests none (#2864). + let edge = format!( + r#""# + ); + assert!(read(&svg(&edge)).is_ok()); + // One that reaches a shape inside a marker, the marker itself or what holds it (it is + // inherited), or any shape when a marker holds a ``, does (#2864). + for nested in [ + format!( + r#""# + ), + format!( + r#""# + ), + format!( + r##""## + ), + ] { + let body = format!(r#"{nested}"#); + assert_eq!(read(&svg(&body)).err(), Some(Refusal::TooMuch), "{body}"); + } let one = format!(r#""#); assert!(read(&svg(&one)).is_ok()); @@ -1209,6 +1342,10 @@ mod tests { let rects = |n: usize| (0..n).map(|i| format!(r#""#)).collect::(); let rules = |n: usize| (0..n).map(|i| format!(".c{i} {{ fill: red }}")).collect::(); assert!(read(&svg(&format!("{}", rules(20), rects(2000)))).is_ok()); + // An exported icon's one class per style: 200 rules on 2,500 elements (#2864). + assert!(read(&svg(&format!("{}", rules(200), rects(2500)))).is_ok()); + // 9,998 rects, the svg and the style come to [`ELEMENTS`], two steps a rule each: the cap. + assert!(read(&svg(&format!("{}", rules(200), rects(9998)))).is_ok()); assert_eq!(read(&svg(&format!("{}", rules(2000), rects(2000)))).err(), Some(Refusal::TooMuch)); // usvg reads what a `` repeats again for each ``, and matches the rules again: a // rect used 1,000 times, under a sheet of 1,000 rules. @@ -1235,17 +1372,90 @@ 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, deep: false }; + let by_sheet = std::collections::HashSet::new(); + let mut counter = Counter { + ids, + seen, + viewport: 100.0, + sheet, + marking: vec![false], + matched: 0, + cap: CSS_STEPS, + by_sheet, + deep: false, + run_capped: false, + }; assert!(counter.count(doc.root_element(), 0).is_none()); assert!(counter.matched <= CSS_STEPS + 1, "{} steps", counter.matched); }); } - /// The siblings walked back past, comments included, are steps too (#2713): 100 rules on an - /// element after 30,000 comments walk 3,000,000 nodes. + /// Whether a rule sets a marker is read once, before matching, not on each element it matches + /// (#2864): one rule of 20,000 declarations on 9,000 elements came to 1.8 × 10⁸ declarations + /// read, some 800 ms. Matching takes it from `marking` alone, and one `marking` doesn't name + /// is taken to set a marker. + #[test] + fn matching_takes_a_rules_marker_flag_from_marking() { + let text = svg(r#""#); + let doc = roxmltree::Document::parse(&text).unwrap(); + let rect = doc.descendants().find(|n| n.has_tag_name("rect")).unwrap(); + with_sheet(&doc, |sheet| { + assert_eq!(css_steps(rect, sheet, &[false], 0).map(|(_, marks)| marks), Some(false)); + assert_eq!(css_steps(rect, sheet, &[true], 0).map(|(_, marks)| marks), Some(true)); + assert_eq!(css_steps(rect, sheet, &[], 0).map(|(_, marks)| marks), Some(true)); + }); + // `elements` reads it from the rule's declarations. + assert_eq!( + element_count( + r#""# + ), + Some(5 + 2 * 6) + ); + } + + /// Past [`ELEMENTS`] an SVG is too much for itself, even where its copies' matching also passes + /// the run's room: that is known for nothing (#2864). + #[test] + fn too_many_elements_is_its_own_cause_at_the_runs_end() { + // A group of 6,000 elements, matched once (some 12,000 steps), and a `` of it: its copy + // passes both the elements and a room of 15,000 steps at once. + let rects = r#""#.repeat(5_999); + let text = svg(&format!(r##"{rects}"##)); + let doc = roxmltree::Document::parse(&text).unwrap(); + with_sheet(&doc, |sheet| { + assert_eq!(elements(&doc, sheet, 15_000, &mut 0).err(), Some(Refusal::TooMuch)); + // With the copy within the elements, the room is what stops it. + let half = text.replacen(&r#""#.repeat(3_000), "", 1); + let doc = roxmltree::Document::parse(&half).unwrap(); + with_sheet(&doc, |sheet| assert_eq!(elements(&doc, sheet, 8_000, &mut 0).err(), Some(Refusal::PastRun))); + }); + // Past the elements written out it is too much for itself too, wherever matching stops. + let many = svg(&format!("{}", r#""#.repeat(10_001))); + let doc = roxmltree::Document::parse(&many).unwrap(); + with_sheet(&doc, |sheet| assert_eq!(elements(&doc, sheet, 1_000, &mut 0).err(), Some(Refusal::TooMuch))); + } + + /// usvg matches the rules again on each ``'s copy: those steps are reported too (#2864). + #[test] + fn the_steps_reported_count_each_copy() { + let steps = |target: &str| { + let text = svg(&format!( + r##"{}"##, + format!(r##""##).repeat(100) + )); + let doc = roxmltree::Document::parse(&text).unwrap(); + let mut matched = 0; + with_sheet(&doc, |sheet| elements(&doc, sheet, CSS_STEPS, &mut matched).map(|_| ())).unwrap_or_else(|why| panic!("{why:?}")); + matched + }; + assert!(steps("r") >= steps("none") + 200, "{} against {}", steps("r"), steps("none")); + } + + /// The siblings walked back past, comments included, are steps too (#2713): 200 rules on an + /// element after 30,000 comments walk 6,000,000 nodes. #[test] fn style_sheet_matching_counts_the_siblings_it_walks() { - let rules = "rect:first-child { fill: red } ".repeat(100); + let rules = "rect:first-child { fill: red } ".repeat(200); let after = |what: &str| element_count(&format!("{}", what.repeat(30_000))); assert_eq!(after(""), Some(4)); assert_eq!(after(""), None); @@ -1257,7 +1467,7 @@ mod tests { let rules = (0..200).map(|i| format!(".c{i} {{ fill: red }}")).collect::(); let class = |bytes: usize| element_count(&format!(r#""#, "a".repeat(bytes))); assert_eq!(class(10), Some(3)); - assert_eq!(class(500_000), None); + assert_eq!(class(2_000_000), None); } /// A gradient of more than two stops goes through them all at each pixel it covers. diff --git a/crates/ui-egui/src/markerpick.rs b/crates/ui-egui/src/markerpick.rs index 558155551b..b943e3b3a6 100644 --- a/crates/ui-egui/src/markerpick.rs +++ b/crates/ui-egui/src/markerpick.rs @@ -99,7 +99,7 @@ impl MarkerImage { ) .to_string(), MarkerRefusal::SvgUnknownRadius => { - tl!("This image can't be a marker: it is an SVG with a radius whose size RustGIS can't know (in em or ex, or in % of a size in em, ex or %)").to_string() + tl!("This image can't be a marker: it is an SVG with a radius whose size RustGIS can't know (in em or ex, or in % of a size in em or ex, or of a nested size in % over 100%)").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(), diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index f614caabcd..1a2560a761 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -112,12 +112,13 @@ wherever it is). An arc is counted as the curves it is drawn with, more the larg 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; such a radius isn't taken either when the SVG's own width or -height is in em or ex, or when the width or height of an ``, `` or `` 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 +height is in em or ex and it has no `viewBox`, or when the width or height of a `` or +`` inside it, or of an `` inside it with no `viewBox`, is in em or ex or past 100%. An +`` with a `viewBox` takes the % from it whatever its own size. 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 export keeps a compressed copy of each image it draws, at most about as much again (some 256 MiB in all), which counts too and leaves less for new images. Its size is its width, and it is as tall as its proportions make it, as QGIS draws a raster image