From 7bed9165952efb01a6a59c09592ed1fcf5fa065d Mon Sep 17 00:00:00 2001 From: Vikram Bhaskaran Date: Mon, 12 Oct 2026 23:41:01 +1100 Subject: [PATCH 1/5] Write simple rectangles, circles, and ellipses back to SVG as those elements. Import turns those elements into paths, so export now recognizes the upright geometry and writes the original element. --- crates/svg/src/export.rs | 103 ++++++++++++++++++++++++++++++++++ crates/svg/tests/roundtrip.rs | 13 +++-- 2 files changed, 112 insertions(+), 4 deletions(-) diff --git a/crates/svg/src/export.rs b/crates/svg/src/export.rs index bfd0100316..b642446c83 100644 --- a/crates/svg/src/export.rs +++ b/crates/svg/src/export.rs @@ -955,7 +955,102 @@ impl Writer<'_> { } } } +} +/// An upright rectangle or a full axis-aligned ellipse, in the same user space `path_d` writes. +fn primitive_tag(path: &PathData, xf: Affine, mut num: impl FnMut(f64) -> String) -> Option { + let [_, b, c, _, _, _] = xf.as_coeffs(); + if b.abs() > 1e-6 || c.abs() > 1e-6 { + return None; + } + let map = |p: Point| xf * p; + if let Some(bounds) = upright_rect(path) { + let (p0, p1) = (map(Point::new(bounds.x0, bounds.y0)), map(Point::new(bounds.x1, bounds.y1))); + let (x, y) = (p0.x.min(p1.x), p0.y.min(p1.y)); + return Some(format!( + "rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\"", + num(x), + num(y), + num((p1.x - p0.x).abs()), + num((p1.y - p0.y).abs()) + )); + } + let (cx, cy, rx, ry) = axis_ellipse(path)?; + let c = map(Point::new(cx, cy)); + let [a, b, c0, d, _, _] = xf.as_coeffs(); + let rx = (a * rx).hypot(b * rx); + let ry = (c0 * ry).hypot(d * ry); + if (rx - ry).abs() <= 1e-3 * rx.max(ry).max(1.0) { + Some(format!("circle cx=\"{}\" cy=\"{}\" r=\"{}\"", num(c.x), num(c.y), num((rx + ry) / 2.0))) + } else { + Some(format!("ellipse cx=\"{}\" cy=\"{}\" rx=\"{}\" ry=\"{}\"", num(c.x), num(c.y), num(rx), num(ry))) + } +} + +fn upright_rect(path: &PathData) -> Option { + let ([sp], Some(b)) = (path.subpaths.as_slice(), path.bounds()) else { return None }; + let corner = |p: Point| ((p.x - b.x0).abs() < 1e-3 || (p.x - b.x1).abs() < 1e-3) && ((p.y - b.y0).abs() < 1e-3 || (p.y - b.y1).abs() < 1e-3); + (sp.closed + && sp.anchors.len() == 4 + && (0..sp.segment_count()).all(|i| sp.segment_is_line(i)) + && sp.anchors.iter().all(|a| corner(a.p)) + && b.width() > 0.0 + && b.height() > 0.0) + .then_some(b) +} + +/// A closed four-cubic ellipse whose anchors sit on the cardinal points. +fn axis_ellipse(path: &PathData) -> Option<(f64, f64, f64, f64)> { + let [sp] = path.subpaths.as_slice() else { return None }; + if !sp.closed || sp.anchors.len() != 4 || (0..4).any(|i| sp.segment_is_line(i)) { + return None; + } + let b = path.bounds()?; + let (cx, cy, rx, ry) = (b.center().x, b.center().y, b.width() / 2.0, b.height() / 2.0); + if rx < 1e-6 || ry < 1e-6 { + return None; + } + let card = [Point::new(cx + rx, cy), Point::new(cx, cy + ry), Point::new(cx - rx, cy), Point::new(cx, cy - ry)]; + let tol = 0.02 * rx.max(ry); + let mut used = [false; 4]; + let mut order = [0usize; 4]; + for (i, a) in sp.anchors.iter().enumerate() { + let j = card.iter().position(|c| c.distance(a.p) <= tol.max(0.05))?; + if used[j] { + return None; + } + used[j] = true; + order[i] = j; + } + let k = vectorcraft_geom::shapes::KAPPA; + for i in 0..4 { + let step = (order[(i + 1) % 4] as i32 - order[i] as i32).rem_euclid(4); + if step != 1 && step != 3 { + return None; + } + let a = &sp.anchors[i]; + let toward = |to: usize| { + let (ox, oy) = match (order[i], to) { + (0, 1) => (0.0, k * ry), + (0, 3) => (0.0, -k * ry), + (2, 3) => (0.0, -k * ry), + (2, 1) => (0.0, k * ry), + (1, 2) => (-k * rx, 0.0), + (1, 0) => (k * rx, 0.0), + (3, 0) => (k * rx, 0.0), + (3, 2) => (-k * rx, 0.0), + _ => (f64::NAN, f64::NAN), + }; + Point::new(card[order[i]].x + ox, card[order[i]].y + oy) + }; + if a.h_out.distance(toward(order[(i + 1) % 4])) > tol.max(0.75) || a.h_in.distance(toward(order[(i + 3) % 4])) > tol.max(0.75) { + return None; + } + } + Some((cx, cy, rx, ry)) +} + +impl Writer<'_> { /// Paint a shape (`d`) with a node's appearance stack. `paths` is the same shape in document /// space, for strokes that aren't plain (it may be empty when all are). fn shape(&mut self, n: &Node, d: &str, paths: &[&PathData], rule: FillRule, bounds: Option) { @@ -1006,6 +1101,14 @@ impl Writer<'_> { } p.extend(css::transparency(n)); let a = self.attrs(&p); + let dashed = items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.dash.is_some())); + if !dashed + && paths.len() == 1 + && let Some(tag) = primitive_tag(paths[0], self.xf, |n| self.num(n)) + { + self.line(&format!("<{tag}{id}{a}/>")); + return; + } self.line(&format!("")); return; } diff --git a/crates/svg/tests/roundtrip.rs b/crates/svg/tests/roundtrip.rs index 8439e720f3..8d45a689c8 100644 --- a/crates/svg/tests/roundtrip.rs +++ b/crates/svg/tests/roundtrip.rs @@ -69,7 +69,7 @@ fn curves_roundtrip() { let n = Node::path(id, shapes::ellipse(Rect::new(20.0, 30.0, 120.0, 90.0)), Appearance::default_art()); let d = doc_with(vec![n]); let s = export(&d, &ExportOptions::default()); - assert!(s.contains(" C"), "{s}"); + assert!(s.contains(" Date: Tue, 13 Oct 2026 13:30:16 +1100 Subject: [PATCH 2/5] Export a rectangle or ellipse only when the path is that shape. A bowtie or a repeated corner stays a path, and ellipse handles must sit within a fraction of the radius, so a small bad curve is not rewritten as a circle. resvg renders of a real rectangle, circle, and ellipse match the canvas. --- crates/svg/src/export.rs | 48 ++++++++++++++++----- crates/svg/tests/primitives.rs | 79 ++++++++++++++++++++++++++++++++++ 2 files changed, 116 insertions(+), 11 deletions(-) create mode 100644 crates/svg/tests/primitives.rs diff --git a/crates/svg/src/export.rs b/crates/svg/src/export.rs index b642446c83..eba5c2f0a4 100644 --- a/crates/svg/src/export.rs +++ b/crates/svg/src/export.rs @@ -989,14 +989,39 @@ fn primitive_tag(path: &PathData, xf: Affine, mut num: impl FnMut(f64) -> String fn upright_rect(path: &PathData) -> Option { let ([sp], Some(b)) = (path.subpaths.as_slice(), path.bounds()) else { return None }; - let corner = |p: Point| ((p.x - b.x0).abs() < 1e-3 || (p.x - b.x1).abs() < 1e-3) && ((p.y - b.y0).abs() < 1e-3 || (p.y - b.y1).abs() < 1e-3); - (sp.closed - && sp.anchors.len() == 4 - && (0..sp.segment_count()).all(|i| sp.segment_is_line(i)) - && sp.anchors.iter().all(|a| corner(a.p)) - && b.width() > 0.0 - && b.height() > 0.0) - .then_some(b) + if !sp.closed || sp.anchors.len() != 4 || b.width() <= 0.0 || b.height() <= 0.0 { + return None; + } + if (0..4).any(|i| !sp.segment_is_line(i)) { + return None; + } + let pts: [Point; 4] = std::array::from_fn(|i| sp.anchors[i].p); + // Four distinct corners. A repeated corner (a triangle stored as four anchors) is not a rect. + for i in 0..4 { + for j in (i + 1)..4 { + if pts[i].distance(pts[j]) <= 1e-3 { + return None; + } + } + } + let on = |a: f64, b: f64| (a - b).abs() <= 1e-3; + let mut horizontal = [false; 4]; + for i in 0..4 { + let (a, c) = (pts[i], pts[(i + 1) % 4]); + let h = on(a.y, c.y) && !on(a.x, c.x); + let v = on(a.x, c.x) && !on(a.y, c.y); + if h == v { + // Diagonal, or a zero-length edge. A bowtie's crossing edges fail here. + return None; + } + horizontal[i] = h; + } + // Edges alternate horizontal and vertical, so the outline is the bounds, not a zigzag. + if (0..4).any(|i| horizontal[i] == horizontal[(i + 1) % 4]) { + return None; + } + let corner = |p: Point| (on(p.x, b.x0) || on(p.x, b.x1)) && (on(p.y, b.y0) || on(p.y, b.y1)); + pts.iter().all(|p| corner(*p)).then_some(b) } /// A closed four-cubic ellipse whose anchors sit on the cardinal points. @@ -1011,11 +1036,12 @@ fn axis_ellipse(path: &PathData) -> Option<(f64, f64, f64, f64)> { return None; } let card = [Point::new(cx + rx, cy), Point::new(cx, cy + ry), Point::new(cx - rx, cy), Point::new(cx, cy - ry)]; - let tol = 0.02 * rx.max(ry); + // Tight against the radii. A fixed 0.75 pt floor turned a 1 pt circle with bad handles into a circle. + let tol = 1e-3 * rx.max(ry); let mut used = [false; 4]; let mut order = [0usize; 4]; for (i, a) in sp.anchors.iter().enumerate() { - let j = card.iter().position(|c| c.distance(a.p) <= tol.max(0.05))?; + let j = card.iter().position(|c| c.distance(a.p) <= tol)?; if used[j] { return None; } @@ -1043,7 +1069,7 @@ fn axis_ellipse(path: &PathData) -> Option<(f64, f64, f64, f64)> { }; Point::new(card[order[i]].x + ox, card[order[i]].y + oy) }; - if a.h_out.distance(toward(order[(i + 1) % 4])) > tol.max(0.75) || a.h_in.distance(toward(order[(i + 3) % 4])) > tol.max(0.75) { + if a.h_out.distance(toward(order[(i + 1) % 4])) > tol || a.h_in.distance(toward(order[(i + 3) % 4])) > tol { return None; } } diff --git a/crates/svg/tests/primitives.rs b/crates/svg/tests/primitives.rs new file mode 100644 index 0000000000..4b2fb71708 --- /dev/null +++ b/crates/svg/tests/primitives.rs @@ -0,0 +1,79 @@ +//! A rectangle, circle, or ellipse exports as that element only when the path is that shape. +//! A bowtie, a repeated corner, and a near-ellipse stay paths. resvg must paint the real shapes +//! the way the canvas does. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use kurbo::Vec2; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node}; +use vectorcraft_geom::{PathData, Point, Rect, SubPath, shapes}; +use vectorcraft_svg::{ExportOptions, export}; +use vectorcraft_testkit::raster::{Image, assert_similar, render_artboard}; + +fn filled(path: PathData) -> Document { + let mut d = Document::new(120.0, 90.0); + let n = Node::path( + d.alloc_id(), + path, + Appearance { items: vec![AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::BLACK)))], ..Default::default() }, + ); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, n).unwrap(); + d +} + +fn resvg_render(svg: &str) -> Image { + let tree = resvg::usvg::Tree::from_str(svg, &resvg::usvg::Options::default()).expect("parse"); + let mut pm = resvg::tiny_skia::Pixmap::new(120, 90).unwrap(); + pm.fill(resvg::tiny_skia::Color::WHITE); + resvg::render(&tree, resvg::tiny_skia::Transform::identity(), &mut pm.as_mut()); + Image { width: 120, height: 90, rgba: pm.data().to_vec() } +} + +fn paints_like_the_canvas(doc: &Document, svg: &str) { + assert_similar(&render_artboard(doc), &resvg_render(svg), 24.0, 0.002); +} + +#[test] +fn a_rectangle_circle_and_ellipse_export_as_those_elements() { + let rect = filled(shapes::rectangle(Rect::new(10.0, 10.0, 60.0, 40.0))); + let rect_svg = export(&rect, &ExportOptions::default()); + assert!(rect_svg.contains(" Date: Wed, 4 Nov 2026 19:00:38 +1100 Subject: [PATCH 3/5] Count exported crop marks as lines. --- crates/engine/src/tests/registration.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/tests/registration.rs b/crates/engine/src/tests/registration.rs index b24f7f31e1..e4d73d7d6b 100644 --- a/crates/engine/src/tests/registration.rs +++ b/crates/engine/src/tests/registration.rs @@ -160,7 +160,7 @@ fn crop_marks_effect_follows_the_object() { // SVG export and Expand Appearance draw the marks as shapes. let svg = vectorcraft_svg::export(&s.doc().unwrap().doc, &Default::default()); assert_eq!(vectorcraft_testkit::svg_shapes(&svg), 9, "{svg}"); - assert_eq!(svg.matches(" Date: Wed, 4 Nov 2026 19:34:23 +1100 Subject: [PATCH 4/5] Expect a straight triangle to round-trip as a polygon. Simple shapes export as rect, circle, ellipse, line, polyline, and polygon, so the imported triangle is no longer a path. --- crates/svg/tests/it/roundtrip.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/svg/tests/it/roundtrip.rs b/crates/svg/tests/it/roundtrip.rs index 06cd95d7ef..513746d115 100644 --- a/crates/svg/tests/it/roundtrip.rs +++ b/crates/svg/tests/it/roundtrip.rs @@ -600,7 +600,9 @@ fn import_basic_shapes() { assert!(s.contains(" Date: Wed, 4 Nov 2026 19:57:21 +1100 Subject: [PATCH 5/5] Expect a bowtie and a repeated corner to export as polygons. Straight segments already write polygon, including a self-crossing quad and a corner that repeats. Those shapes stay out of rect, and a near-ellipse stays a path. --- crates/svg/tests/primitives.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/svg/tests/primitives.rs b/crates/svg/tests/primitives.rs index 4b2fb71708..a1f1ea3840 100644 --- a/crates/svg/tests/primitives.rs +++ b/crates/svg/tests/primitives.rs @@ -1,6 +1,6 @@ //! A rectangle, circle, or ellipse exports as that element only when the path is that shape. -//! A bowtie, a repeated corner, and a near-ellipse stay paths. resvg must paint the real shapes -//! the way the canvas does. +//! A bowtie and a repeated corner are straight segments, so they are polygons, not rectangles. +//! A near-ellipse stays a path. resvg must paint the real shapes the way the canvas does. #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use kurbo::Vec2; @@ -53,21 +53,21 @@ fn a_rectangle_circle_and_ellipse_export_as_those_elements() { } #[test] -fn a_bowtie_a_repeated_corner_and_a_near_ellipse_stay_paths() { +fn a_bowtie_and_a_repeated_corner_are_polygons_and_a_near_ellipse_stays_a_path() { let bowtie = filled(PathData::single(SubPath::polyline( &[Point::new(10.0, 10.0), Point::new(60.0, 40.0), Point::new(60.0, 10.0), Point::new(10.0, 40.0)], true, ))); let bowtie_svg = export(&bowtie, &ExportOptions::default()); - assert!(bowtie_svg.contains("