Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

fix(io): SVG text placed by a transform keeps it on import (#4806) (#5334)

Ahmed Magdy4e5c6a018ac5
diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs
index 04fc4bee3..72b231867 100644
--- a/crates/io/src/svg.rs
+++ b/crates/io/src/svg.rs
@@ -337,6 +337,11 @@ impl Conv {
/// `nodes` in paint order (first = bottom), as layers in the same order. `parent` is the
/// absolute transform of the group holding them (what resvg needs to render one of them
/// alone, since a node's own data is in its parent's space).
+ ///
+ /// Transforms are composed from `parent` down rather than read from `abs_transform()`: the
+ /// glyph outlines usvg builds for a text element (`Text::flattened`) keep identity absolute
+ /// transforms, so text placed by its own or an ancestor's `transform` (Illustrator writes
+ /// `matrix(1 0 0 1 x y)` on every text element) would lose it (#4806). Elsewhere the two agree.
fn convert_children(&mut self, nodes: &[usvg::Node], depth: usize, rec: usize, parent: tiny_skia::Transform) -> Vec<Layer> {
let mut out = Vec::new();
for node in nodes {
@@ -350,7 +355,7 @@ impl Conv {
usvg::Node::Group(g) => {
// A clip-path of one plain path becomes the group's vector mask (#4266); others
// are rasterised with the group.
- let clip = g.clip_path().and_then(|cp| self.clip_mask(g, cp));
+ let clip = g.clip_path().and_then(|cp| self.clip_mask(parent.pre_concat(g.transform()), cp));
let dropped: [(bool, &'static str); 3] =
[(!g.filters().is_empty(), "filter"), (g.clip_path().is_some() && clip.is_none(), "clip-path"), (g.mask().is_some(), "mask")];
let too_deep = self.max_group_depth.is_some_and(|limit| depth >= limit) || depth >= MAX_GROUP_DEPTH || rec >= MAX_RECURSION;
@@ -370,7 +375,8 @@ impl Conv {
// A group that only carries a transform (baked into its paths by usvg) or that
// usvg inserted for its own bookkeeping adds nothing to the layer tree.
let plain = clip.is_none() && g.id().is_empty() && g.opacity().get() >= 1.0 && g.blend_mode() == usvg::BlendMode::Normal;
- let children = self.convert_children(g.children(), if plain { depth } else { depth + 1 }, rec + 1, g.abs_transform());
+ let abs = parent.pre_concat(g.transform());
+ let children = self.convert_children(g.children(), if plain { depth } else { depth + 1 }, rec + 1, abs);
if children.is_empty() {
return;
}
@@ -404,7 +410,9 @@ impl Conv {
out.extend(self.raster_layer(node, name, parent));
}
usvg::Node::Text(t) => {
- let children = self.convert_children(t.flattened().children(), depth + 1, rec + 1, t.flattened().abs_transform());
+ // The outlines are in the text element's own space.
+ let abs = t.abs_transform().pre_concat(t.flattened().transform());
+ let children = self.convert_children(t.flattened().children(), depth + 1, rec + 1, abs);
if children.is_empty() {
self.note("text", "SVG: text needs a font the drawing can use; none matched, so it was dropped".to_string());
return;
@@ -421,10 +429,10 @@ impl Conv {
}
}
- /// The vector mask for group `g` clipped by `cp`, when the clip is one visible path with no
- /// clip of its own: what resvg draws for the clip (the group's transform, then the clip's,
- /// then the path), in canvas pixels, with the clip rule as its fill rule.
- fn clip_mask(&self, g: &usvg::Group, cp: &usvg::ClipPath) -> Option<VectorMask> {
+ /// The vector mask for a group clipped by `cp`, when the clip is one visible path with no
+ /// clip of its own: what resvg draws for the clip (the group's absolute transform `abs`, then
+ /// the clip's, then the path), in canvas pixels, with the clip rule as its fill rule.
+ fn clip_mask(&self, abs: tiny_skia::Transform, cp: &usvg::ClipPath) -> Option<VectorMask> {
if cp.clip_path().is_some() {
return None;
}
@@ -432,7 +440,7 @@ impl Conv {
if !p.is_visible() {
return None;
}
- let ts = g.abs_transform().pre_concat(cp.transform()).post_concat(self.global);
+ let ts = abs.pre_concat(cp.transform()).post_concat(self.global);
let subpaths = knots(&(*p.data()).clone().transform(ts)?);
if subpaths.is_empty() {
return None;
@@ -455,7 +463,8 @@ impl Conv {
let name = self.name(p.id(), 0);
return self.raster_layer(node, name, parent);
}
- let ts = p.abs_transform().post_concat(self.global);
+ // A path has no transform of its own: its data is in its parent's space.
+ let ts = parent.post_concat(self.global);
let data = (*p.data()).clone().transform(ts)?;
let subpaths = knots(&data);
if subpaths.is_empty() {
@@ -542,7 +551,14 @@ impl Conv {
/// The node rendered by resvg into a pixel layer over its bounding box, clipped to the canvas.
/// `parent` is the absolute transform of the node's parent group.
fn raster_layer(&mut self, node: &usvg::Node, name: String, parent: tiny_skia::Transform) -> Option<Layer> {
- let bb = node.abs_layer_bounding_box()?;
+ // Where the node lands, from its box in its parent's space (as usvg computes its absolute
+ // box, but through `parent`, which is right inside text too).
+ let bb = match node {
+ usvg::Node::Group(g) => g.layer_bounding_box().transform(parent.pre_concat(g.transform()))?,
+ _ => node.bounding_box().to_non_zero_rect()?.transform(parent)?,
+ };
+ // What resvg shifts the node by before drawing it.
+ let shift = node.abs_layer_bounding_box()?;
let k = self.global.sx;
let x0 = ((bb.x() * k).floor() as i32).max(self.canvas.x0);
let y0 = ((bb.y() * k).floor() as i32).max(self.canvas.y0);
@@ -559,7 +575,7 @@ impl Conv {
// to the origin: undo that shift, apply the parent's transform, then scale to the canvas
// and shift so the pixmap starts at (x0, y0).
let canvas = tiny_skia::Transform::from_row(k, 0.0, 0.0, k, -(x0 as f32), -(y0 as f32));
- let ts = canvas.pre_concat(parent).pre_translate(bb.x(), bb.y());
+ let ts = canvas.pre_concat(parent).pre_translate(shift.x(), shift.y());
resvg::render_node(node, ts, &mut pixmap.as_mut())?;
Some(Layer::new(name, LayerContent::Raster(surface(&pixmap, Rect::new(x0, y0, x1, y1), self.fmt))))
}
diff --git a/crates/io/tests/svg.rs b/crates/io/tests/svg.rs
index d1baf418f..4f21bd5dc 100644
--- a/crates/io/tests/svg.rs
+++ b/crates/io/tests/svg.rs
@@ -221,6 +221,57 @@ fn text_becomes_outline_shapes_or_warns_without_a_font() {
assert!(dark > 4, "glyph strokes cross the middle row: {dark}");
}
+/// #4806: text placed by a `transform` (Illustrator writes `matrix(1 0 0 1 x y)` on every text
+/// element), on the text or on a group around it, lands where resvg draws it. usvg leaves the
+/// glyph outlines' absolute transforms at identity, so reading them dropped the transform: the
+/// text went off the canvas or kept its untransformed place and size.
+#[test]
+fn transformed_text_lands_where_resvg_draws_it() {
+ let font = "font-size=\"24\" font-family=\"DejaVu Sans, Arial, Helvetica, sans-serif\" fill=\"black\"";
+ let cases = [
+ format!("<text transform=\"translate(10 40)\" {font}>IHI</text>"),
+ format!("<text transform=\"matrix(1 0 0 1 10 40)\" {font}>IHI</text>"),
+ format!("<text transform=\"translate(10 0)\" x=\"20\" y=\"40\" {font}>IHI</text>"),
+ format!("<text transform=\"scale(2)\" x=\"5\" y=\"25\" {font}>IHI</text>"),
+ format!("<g transform=\"translate(10 40)\"><text {font}>IHI</text></g>"),
+ format!("<g transform=\"translate(60 0)\"><g transform=\"rotate(90)\"><text x=\"5\" y=\"20\" {font}>IHI</text></g></g>"),
+ ];
+ for c in cases {
+ let svg = format!("<svg {NS} width=\"120\" height=\"60\">{c}</svg>");
+ let r = open(&svg);
+ let d = &r.document;
+ if d.layers.is_empty() {
+ // No font at all on this machine: the import says so instead.
+ assert!(r.warnings.iter().any(|w| w.contains("font")), "{:?}", r.warnings);
+ return;
+ }
+ assert!(matches!(d.layers[0].content, LayerContent::Group(_)), "text stays outline shapes: {c}");
+ let imported = photocraft_compose::flatten(d);
+ let reference = svg::rasterize(svg.as_bytes(), 1.0).unwrap();
+ let (mut both, mut either) = (0usize, 0usize);
+ let (mut a_box, mut b_box) = ([i32::MAX, i32::MAX, i32::MIN, i32::MIN], [i32::MAX, i32::MAX, i32::MIN, i32::MIN]);
+ let grow = |bx: &mut [i32; 4], x: i32, y: i32| *bx = [bx[0].min(x), bx[1].min(y), bx[2].max(x), bx[3].max(y)];
+ for y in 0..60 {
+ for x in 0..120 {
+ let (a, b) = (imported.get(x, y)[3] > 0.5, reference.get(x, y)[3] > 0.5);
+ if a {
+ grow(&mut a_box, x, y);
+ }
+ if b {
+ grow(&mut b_box, x, y);
+ }
+ both += usize::from(a && b);
+ either += usize::from(a || b);
+ }
+ }
+ assert!(either > 50, "resvg draws the text on the canvas: {c}");
+ // Same place and size to the pixel; the outlines are filled by a different rasteriser, so
+ // the edges of thin stems may differ by half a pixel.
+ assert!(a_box.iter().zip(b_box).all(|(a, b)| (a - b).abs() <= 1), "imported {a_box:?}, resvg {b_box:?}: {c}");
+ assert!(both * 10 >= either * 7, "imported glyphs cover what resvg draws ({both} of {either} px): {c}");
+ }
+}
+
#[test]
fn size_comes_from_the_viewbox_and_huge_drawings_shrink_to_fit() {
let r = open(&format!("<svg {NS} viewBox=\"0 0 300 150\"><rect width=\"300\" height=\"150\"/></svg>"));