From 21a386a6d4a3cb2f1c043d0399bd06b19c40a7ad Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 12 Oct 2026 14:16:40 -0700 Subject: [PATCH] SVG import: the style cascade looks up each element's rules by id, class and type The SVG import's style cascade tested every + + + + + + + tu + + "#; + assert_same_as_every_rule(svg); + with_doc(svg, |doc, st| { + let own = |id: &str, name: &str| st.own(by_id(doc, id), name); + assert_eq!(own("a", "fill").as_deref(), Some("f2"), "#a beats rect.a"); + assert_eq!(own("r2", "fill").as_deref(), Some("f4"), "rect.a beats g rect"); + assert_eq!(own("r2", "stroke").as_deref(), Some("s5"), "classes apart by a tab and a line feed, one repeated"); + assert_eq!(own("r3", "fill").as_deref(), Some("f8"), "!important"); + assert_eq!(own("r3", "display").as_deref(), Some("none")); + assert_eq!(own("r4", "fill").as_deref(), Some("f1"), "g rect beats rect"); + assert_eq!(own("r4", "font-size").as_deref(), Some("9px")); + assert_eq!(own("c5", "fill").as_deref(), Some("f11"), "of rules alike, the last one"); + assert_eq!(own("c5", "stroke").as_deref(), Some("s")); + assert_eq!(own("t7", "font-size").as_deref(), Some("8px")); + assert_eq!(own("r8", "fill").as_deref(), Some("f9")); + }); + } + + /// An element's candidates hold each rule once, however often the element repeats a class. + #[test] + fn repeated_classes_give_each_rule_once() { + with_doc( + r#""#, + |doc, st| assert_eq!(st.index.candidates(by_id(doc, "r")), [0, 1, 2, 3]), + ); + } + + /// A compound selector over a few tags, ids, classes and attributes. + fn arb_compound() -> impl Strategy { + let tag = prop::sample::select(vec!["", "*", "g", "rect", "text", "tspan"]); + let id = prop::sample::select(vec!["", "#a", "#b"]); + let classes = prop::collection::vec(prop::sample::select(vec![".a", ".b", ".c"]), 0..3); + let attr = prop::sample::select(vec!["", "[data-k]", "[data-k=v]"]); + (tag, id, classes, attr).prop_map(|(t, i, c, a)| match format!("{t}{i}{}{a}", c.concat()) { + s if s.is_empty() => "*".to_string(), + s => s, + }) + } + + /// One to three compounds joined by descendant and child combinators. + fn arb_selector() -> impl Strategy { + (arb_compound(), prop::collection::vec((prop::sample::select(vec![" ", " > ", ">"]), arb_compound()), 0..3)) + .prop_map(|(first, rest)| rest.into_iter().fold(first, |s, (comb, c)| format!("{s}{comb}{c}"))) + } + + /// A rule of one or two selectors that sets one to three properties, some of them `!important`. + fn arb_rule() -> impl Strategy { + let decl = (prop::sample::select(vec!["fill", "stroke", "display"]), 0..1000u16, any::()) + .prop_map(|(name, v, important)| format!("{name}: v{v}{}", if important { " !important" } else { "" })); + (prop::collection::vec(arb_selector(), 1..3), prop::collection::vec(decl, 1..4)) + .prop_map(|(selectors, decls)| format!("{} {{ {} }}", selectors.join(", "), decls.join("; "))) + } + + /// An element that may have an id, classes (some repeated, apart by spaces, tabs and line feeds) + /// and a `data-k` or `style` attribute, with up to four children on each of the `depth` levels + /// below it. + fn arb_element(depth: u32) -> BoxedStrategy { + let tag = prop::sample::select(vec!["g", "rect", "text", "tspan"]); + let id = prop::sample::select(vec!["", r#" id="a""#, r#" id="b""#, r#" id="c""#]); + let classes = prop::collection::vec((prop::sample::select(vec![" ", " ", " "]), prop::sample::select(vec!["a", "b", "c", "x"])), 0..4) + .prop_map(|v| match v.iter().map(|(gap, c)| format!("{gap}{c}")).collect::() { + s if s.is_empty() => s, + s => format!(r#" class="{s}""#), + }); + let more = prop::sample::select(vec!["", r#" data-k="v""#, r#" data-k="w""#, r#" style="fill: s""#, r#" style="stroke: s !important""#]); + let children = if depth == 0 { Just(vec![]).boxed() } else { prop::collection::vec(arb_element(depth - 1), 0..5).boxed() }; + (tag, id, classes, more, children).prop_map(|(t, i, c, m, ch)| format!("<{t}{i}{c}{m}>{}", ch.concat())).boxed() + } + + proptest! { + #![proptest_config(ProptestConfig { failure_persistence: None, ..ProptestConfig::default() })] + + /// Random style sheets give each element of a random document what testing every rule + /// gives it. + #[test] + fn random_sheets_give_what_testing_every_rule_gives(rules in prop::collection::vec(arb_rule(), 0..24), body in prop::collection::vec(arb_element(3), 1..6)) { + assert_same_as_every_rule(&format!(r#"{}"#, rules.join("\n"), body.concat())); + } + } + + /// 50,000 class rules give 50,000 elements, each with one of the classes, their fill within + /// 20 s. + #[test] + fn styling_50000_elements_with_50000_rules_finishes_within_20_s() { + const N: usize = 50_000; + let rules: String = (0..N).map(|i| format!(".c{i} {{ fill: #{i:06x} }}\n")).collect(); + let rects: String = (0..N).map(|i| format!(r#""#)).collect(); + let svg = format!(r#"{rects}"#); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let doc = roxmltree::Document::parse(&svg).unwrap(); + let st = Styles::new(&doc); + let fills: Vec> = doc.descendants().filter(|n| n.tag_name().name() == "rect").map(|n| st.own(n, "fill")).collect(); + tx.send(fills).ok(); + }); + let fills = rx.recv_timeout(std::time::Duration::from_secs(20)).unwrap_or_else(|_| panic!("styling {N} elements did not finish within 20 s")); + assert_eq!(fills.len(), N); + for (i, fill) in fills.iter().enumerate() { + assert_eq!(fill.as_deref(), Some(format!("#{i:06x}").as_str())); + } + } + #[test] fn the_font_shorthand_sets_its_longhands() { let d = parse_decls("fill: red; font: italic bold 30px 'DejaVu Sans' ; font-weight: 300 !important; font: nonsense"); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d8a680d2..d49ef6f7 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -497,6 +497,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Files (M4):** - `.vectorcraft` (lossless JSON, compressed, atomic saves, save down to v1), Save As with a format chooser, Save a Copy, Revert, templates, Data Recovery after a crash (browser tabs hold their copies with Web Locks too, so a background tab's copies are never taken for a crash's, and a tab repairs copies another removed when it resumes: #367), background save and export. The desktop app writes its warnings and errors (graphics adapter, a lost graphics device, panics the guard recovered from) to standard error and to `logs/vectorcraft.log` next to the preferences, the two previous runs kept and each file capped at 16 MiB, so a launch without a terminal still leaves something to attach to a bug report (#465). Native documents with a lot of path data (traced or generated art, in layers, symbols or patterns) are saved as compact JSON, about a fifth of the size; small documents stay pretty-printed (#1492). - SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420; hidden objects written hidden on Save and `convert`, and `data-*` attributes kept as the objects' own data: #522; top-level groups open as layers named from `data-name`, else the id, also when one more group (a transform on all the art, a ``) wraps them, hidden ones hidden, and a file whose art sits loose under a root `` with an id (or `data-name`), as one-layer exports write it, opens with its one layer named from it; nested groups stay groups, except the sublayers VectorCraft writes, marked `data-vc-layer`, and Inkscape sublayers, which open as sublayers in their layer's colour: #372); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; art reaching past a plain PDF's page clipped to its crop box, as PDF viewers show it, each such object in a clip group of its own (a PDF-compatible `.ai` opens whole: #675); a `.ai` on its trim boxes with the bleed boxes round them as the document's bleed, as Crop To › Trim opens a PDF (#1266); masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs) to PDF export: a CMYK JPEG passes through unchanged, others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320). Overprint is kept from PDF import (opened, the PDF part of an `.ai`, placed) to PDF export: the graphics state's `/OP` and `/op` become the overprint of fills, strokes and type, so a spot colour over a process colour still overprints; a page whose overprint can't be read for certain knocks out with a note, as does `/OPM 0` being read as nonzero overprint (#1388; hand-written fixtures, `pdf/src/tests_import_overprint.rs`). A masked CMYK image (`/SMask`, `/Mask` or a colour key) keeps its inks too, its alpha coming in as a greyscale opacity mask. + SVG import's style cascade, used for hidden objects, non-scaling strokes and type, tests each element only against the `