From d154d7289021462d83ecbb6029eced32f07837f0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:48:26 -0800 Subject: [PATCH] SVG import: absolutely placed characters one text object cannot place import as a group MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SVG reorders right-to-left characters only within a text chunk, while one text object reorders the whole line. In אbג the left-to-right b is drawn right before ג with no kerning between them, so ג stayed where the line put it and the import warned. When kerning cannot put every absolutely placed character on its x, the text is now cut before each such character and each piece is placed again, and the text imports as a group of point type objects named after the element. A text one object can place stays one object. A split text in a clip path clips by the outlines of all its objects. --- crates/svg/src/import/importer.rs | 76 +++++---- crates/svg/src/import/text.rs | 240 +++++++++++++++++++++++------ crates/svg/tests/it/clip_text.rs | 14 ++ crates/svg/tests/it/import_text.rs | 84 +++++++++- docs/target-app-parity.md | 3 +- 5 files changed, 329 insertions(+), 88 deletions(-) diff --git a/crates/svg/src/import/importer.rs b/crates/svg/src/import/importer.rs index 2eede1f7be..6e3ecb955e 100644 --- a/crates/svg/src/import/importer.rs +++ b/crates/svg/src/import/importer.rs @@ -243,48 +243,59 @@ impl Importer { if !matches!(kids.get(main), Some(usvg::Node::Path(p)) if p.is_visible()) { return Some(vec![]); } - let text::PendingText { name, mut obj, servers, paints, non_scaling, under, .. } = self.slots.texts.get(i)?.clone(); - // The scale the type draws at becomes its size (last, below): text space grows by `grow`. - let xf = ts * obj.xf; - let grow = text::size_scale(&obj, xf); - // usvg resolved the `url(#…)` paints (the paths after the main one) in the element's user - // space; runs paint in text space. - let to_text = Affine::scale(grow) * obj.xf.inverse(); + let text::PendingText { name, obj, servers, rest, paints, non_scaling, under, .. } = self.slots.texts.get(i)?.clone(); let slot_paint = |im: &mut Self, k: usize, m: Affine| match kids.get(main + 1 + k) { Some(usvg::Node::Path(p)) => p.fill().map_or(Paint::None, |f| im.paint(f.paint(), m)), _ => Paint::None, }; - let resolved: Vec = (0..paints).map(|k| slot_paint(self, k, to_text)).collect(); - let server = |k: usize| resolved.get(k).cloned().unwrap_or(Paint::None); - for (run, (fill, stroke)) in obj.runs.iter_mut().zip(servers) { - if let Some(k) = fill { - run.style.fill = server(k); + // A text split into several objects becomes a group of them, named after the element. + let whole = rest.is_empty(); + let mut skewed = false; + let mut nodes = Vec::with_capacity(rest.len() + 1); + for (mut obj, servers) in std::iter::once((obj, servers)).chain(rest) { + // The scale the type draws at becomes its size (last, below): text space grows by `grow`. + let xf = ts * obj.xf; + let grow = text::size_scale(&obj, xf); + // usvg resolved the `url(#…)` paints (the paths after the main one) in the element's user + // space; runs paint in text space. + let to_text = Affine::scale(grow) * obj.xf.inverse(); + let resolved: Vec = (0..paints).map(|k| slot_paint(self, k, to_text)).collect(); + let server = |k: usize| resolved.get(k).cloned().unwrap_or(Paint::None); + for (run, (fill, stroke)) in obj.runs.iter_mut().zip(servers) { + if let Some(k) = fill { + run.style.fill = server(k); + } + if let Some(k) = stroke { + run.style.stroke = server(k); + } } - if let Some(k) = stroke { - run.style.stroke = server(k); + obj.xf = xf; + skewed |= non_scaling && !vector_effect::unscale_text(&mut obj, self.screen); + // A stroke under the characters is the object's own: it paints in the document. + let under = under.clone().map(|(mut sl, k)| { + if let Some(k) = k { + sl.paint = slot_paint(self, k, ts); + } + let mut ap = Appearance { items: vec![AppearanceItem::Stroke(sl)], ..Default::default() }; + ap.scale_strokes(if non_scaling { self.screen } else { obj.xf.determinant().abs().sqrt() }); + ap.set_contents_at(1); + ap + }); + text::fold_scale(&mut obj, grow); + let mut n = self.named(if whole { &name } else { "" }, NodeKind::Text(Box::new(obj)))?; + if let Some(ap) = under { + n.appearance = ap.into(); } + nodes.push(Arc::new(n)); } - obj.xf = xf; - if non_scaling && !vector_effect::unscale_text(&mut obj, self.screen) { + if skewed { let label = if name.is_empty() || made_up(&name) { "a text".to_string() } else { format!("text '{name}'") }; self.warn(format!("non-scaling stroke on {label} approximated: the text is stretched or skewed")); } - // A stroke under the characters is the object's own: it paints in the document. - let under = under.map(|(mut sl, k)| { - if let Some(k) = k { - sl.paint = slot_paint(self, k, ts); - } - let mut ap = Appearance { items: vec![AppearanceItem::Stroke(sl)], ..Default::default() }; - ap.scale_strokes(if non_scaling { self.screen } else { obj.xf.determinant().abs().sqrt() }); - ap.set_contents_at(1); - ap - }); - text::fold_scale(&mut obj, grow); - let mut n = self.named(&name, NodeKind::Text(Box::new(obj)))?; - if let Some(ap) = under { - n.appearance = ap.into(); + if whole { + return Some(nodes); } - Some(vec![Arc::new(n)]) + Some(vec![Arc::new(self.named(&name, NodeKind::Group { children: nodes, clip: false })?)]) } fn group_node(&mut self, g: &usvg::Group, acc: Affine) -> Option { @@ -584,7 +595,8 @@ impl Importer { if p.id().is_empty() || !p.is_visible() || p.fill().is_some_and(|f| f.rule() == usvg::FillRule::EvenOdd) { return None; } - let mut obj = self.slots.texts.get(self.slots.find(p)?)?.obj.clone(); + // A text split into several objects clips by its outlines. + let mut obj = self.slots.texts.get(self.slots.find(p)?).filter(|t| t.rest.is_empty())?.obj.clone(); obj.xf = m * self.slots.inner(p) * obj.xf; let grow = text::size_scale(&obj, obj.xf); for run in &mut obj.runs { diff --git a/crates/svg/src/import/text.rs b/crates/svg/src/import/text.rs index ef3934c2d6..d783c04319 100644 --- a/crates/svg/src/import/text.rs +++ b/crates/svg/src/import/text.rs @@ -130,6 +130,7 @@ const BIDI_NESTED: &str = "a unicode-bidi embedding inside another imported one const BIDI_TEXT_OVERRIDE: &str = "unicode-bidi override on the text imported as its paragraph direction; directional override is not supported"; /// One character of a text and the adjustments its position needs. +#[derive(Clone)] struct Cell { ch: char, style: CharStyle, @@ -178,6 +179,9 @@ pub(super) struct PendingText { pub obj: TextObject, /// For each run, the index of its fill's and stroke's `url(#…)` paint, if any. pub servers: Vec<(Option, Option)>, + /// The other point type objects of a text whose absolutely placed characters one object cannot + /// put on their x ([`split`]), after `obj` in text order, each with its runs' paint indices. + pub rest: Vec<(TextObject, Vec)>, /// Number of `url(#…)` paints (the placeholder paths after the main one, in order). pub paints: usize, /// `vector-effect="non-scaling-stroke"`: the character strokes keep their width on screen. @@ -233,7 +237,14 @@ impl TextSlots { return Some(bp.clone()); } let t = self.texts.get(i)?; - let bp = Rc::new(vectorcraft_text::layout(FontDb::global(), &t.obj).to_bezpath()); + let mut bp = vectorcraft_text::layout(FontDb::global(), &t.obj).to_bezpath(); + // The other objects of a split text, in the first one's text space. + for (o, _) in &t.rest { + let mut more = vectorcraft_text::layout(FontDb::global(), o).to_bezpath(); + more.apply_affine(t.obj.xf.inverse() * o.xf); + bp.extend(more.elements().iter().copied()); + } + let bp = Rc::new(bp); self.outlines.borrow_mut().insert(i, bp.clone()); Some(bp) } @@ -534,7 +545,10 @@ fn use_slot( shown.build(style_xml, style_t, &label, &mut found) }; let differs = |(text, paints): &(PendingText, Vec)| { - slots.texts.get(shared).is_none_or(|old| old.obj != text.obj || old.servers != text.servers || old.under != text.under) + slots + .texts + .get(shared) + .is_none_or(|old| old.obj != text.obj || old.servers != text.servers || old.rest != text.rest || old.under != text.under) || inst.paints.get(shared) != Some(paints) }; let slot = built.filter(differs).map(|(text, paints)| { @@ -1337,7 +1351,7 @@ impl Ctx { } let marker = Rect::new(b.x0, b.y0, b.x1.max(b.x0 + 1.0), b.y1.max(b.y0 + 1.0)); let name = t.attribute("id").unwrap_or("").to_string(); - Some((PendingText { name, obj, servers, paints: 0, non_scaling: false, under: None, marker }, Vec::new())) + Some((PendingText { name, obj, servers, rest: vec![], paints: 0, non_scaling: false, under: None, marker }, Vec::new())) } /// Read one ``: the pending text and its `url(#…)` paints. @@ -1469,6 +1483,7 @@ impl Ctx { let mut obj = TextObject::point(Point::ZERO, "", CharStyle::default()); let mut breaks: Vec = vec![]; let mut para_styles: Vec = vec![]; + let mut rest = vec![]; if let Some((tp, followed)) = path { let bp = &followed.path; // Along the path: dx is extra advance, dy shifts off the path. @@ -1549,46 +1564,37 @@ impl Ctx { obj.kind = TextKind::OnPath { path: PathData::from_bezpath(&bp), start: 0.0, end: None }; obj.xf = Affine::IDENTITY; } else { - let origin = Point::new(x[0].unwrap_or(0.0) + dx[0], y[0].unwrap_or(0.0) + dy[0]); - let (justify, left, starts, unplaced) = lines(&mut cells, &x, &y, &dx, &dy, &anchor_of, &pin, origin.x, &mut breaks); - if unplaced > 0 { + let whole = cells.clone(); + let mut ys = vec![]; + let (b, p, unplaced) = place(&mut cells, &x, &y, &dx, &dy, &anchor_of, &pin, &mut obj, &mut ys); + (breaks, para_styles) = (b, p); + if !unplaced.is_empty() { + // One object cannot put every absolutely placed character on its x: the text becomes + // several, the first of them `obj`. + let mut pieces = split(&whole, &x, &y, &dx, &dy, &ys, &anchor_of, &pin, unplaced).into_iter(); + if let Some(first) = pieces.next() { + (obj, cells, breaks, para_styles) = (first.obj, first.cells, first.breaks, first.paras); + } + rest = pieces + .map(|mut p| { + let servers = finish(&mut p.obj, &p.cells, &p.breaks, p.paras, &pin); + (p.obj, servers) + }) + .collect(); warnings.push(format!( - "{label}: {unplaced} absolutely placed character(s) between characters of the other direction keep their place in the line" + "{label}: imported as {} point type objects in a group, since one object cannot put every character on its own x", + rest.len() + 1 )); } - obj.para.justify = justify; - obj.xf = Affine::translate((finite(left), finite(origin.y))); - // Lines anchored differently or at different x (paragraphs aligned or indented - // differently): each line's paragraph takes its alignment, and indents that put it - // where it was. - if starts.iter().any(|&(_, a, ax)| a != starts[0].1 || ax != starts[0].2) { - for (k, &(_, a, ax)) in starts.iter().enumerate() { - let d = finite(ax - left); - let mut pa = ParaStyle { justify: justify_of(a), ..ParaStyle::default() }; - match pa.justify { - Justify::Center if d >= 0.0 => pa.left_indent = 2.0 * d, - Justify::Center => pa.right_indent = -2.0 * d, - Justify::Right => pa.right_indent = -d, - _ => pa.left_indent = d, - } - let count = if k == 0 { 1 } else { breaks.get(k - 1).map_or(1, |b| b.count) }; - para_styles.extend(std::iter::repeat_n(pa, count)); - } - } } - let (runs, servers) = assemble(&cells, &breaks).0; - obj.runs = runs; - if !para_styles.is_empty() { - obj.set_paragraph_styles(para_styles); - } - pin(&mut obj); - keep_reader_anchors(&mut obj); + let servers = finish(&mut obj, &cells, &breaks, para_styles, &pin); // The placeholder covers the text (laid out when a paint server needs its bounding box). - let b = if paints.is_empty() { obj.bounds() } else { Some(obj.xf.transform_rect_bbox(measure(&obj).bounds)) }.unwrap_or_default(); + let bounds = |o: &TextObject| if paints.is_empty() { o.bounds() } else { Some(o.xf.transform_rect_bbox(measure(o).bounds)) }; + let b = rest.iter().filter_map(|(o, _)| bounds(o)).fold(bounds(&obj), |all, b| Some(all.map_or(b, |a| a.union(b)))).unwrap_or_default(); let marker = Rect::new(b.x0, b.y0, b.x1.max(b.x0 + 1.0), b.y1.max(b.y0 + 1.0)); let name = t.attribute("id").unwrap_or("").to_string(); let non_scaling = vector_effect::is_non_scaling(&self.css, t); - Some((PendingText { name, obj, servers, paints: paints.len(), non_scaling, under, marker }, paints)) + Some((PendingText { name, obj, servers, rest, paints: paints.len(), non_scaling, under, marker }, paints)) } } @@ -1683,13 +1689,145 @@ fn leading_tolerance(spacing: f64) -> f64 { 0.01_f64.min(spacing.abs() * 1e-3) } +/// Point type `obj` of `cells` placed by the positioning lists ([`lines`]): sets its justification +/// and transform, and returns its line breaks, its paragraph styles and the absolutely placed +/// characters kerning cannot put on their x. `ys` takes each character's line baseline and y. +#[allow(clippy::too_many_arguments)] +fn place( + cells: &mut [Cell], + x: &[Option], + y: &[Option], + dx: &[f64], + dy: &[f64], + anchor_of: &dyn Fn(usize) -> f64, + pin: &dyn Fn(&mut TextObject), + obj: &mut TextObject, + ys: &mut Vec<(f64, f64)>, +) -> (Vec, Vec, Vec) { + let mut breaks = vec![]; + let mut para_styles = vec![]; + let origin = Point::new(x[0].unwrap_or(0.0) + dx[0], y[0].unwrap_or(0.0) + dy[0]); + let (justify, left, starts, unplaced) = lines(cells, x, y, dx, dy, anchor_of, pin, origin.x, &mut breaks, ys); + obj.para.justify = justify; + obj.xf = Affine::translate((finite(left), finite(origin.y))); + // Lines anchored differently or at different x (paragraphs aligned or indented + // differently): each line's paragraph takes its alignment, and indents that put it + // where it was. + if starts.iter().any(|&(_, a, ax)| a != starts[0].1 || ax != starts[0].2) { + for (k, &(_, a, ax)) in starts.iter().enumerate() { + let d = finite(ax - left); + let mut pa = ParaStyle { justify: justify_of(a), ..ParaStyle::default() }; + match pa.justify { + Justify::Center if d >= 0.0 => pa.left_indent = 2.0 * d, + Justify::Center => pa.right_indent = -2.0 * d, + Justify::Right => pa.right_indent = -d, + _ => pa.left_indent = d, + } + let count = if k == 0 { 1 } else { breaks.get(k - 1).map_or(1, |b| b.count) }; + para_styles.extend(std::iter::repeat_n(pa, count)); + } + } + (breaks, para_styles, unplaced) +} + +/// Gives `obj` the runs of `cells` with `breaks`, its paragraph styles and its paragraph +/// directions; returns the paint indices of its runs. +fn finish(obj: &mut TextObject, cells: &[Cell], breaks: &[Break], para_styles: Vec, pin: &dyn Fn(&mut TextObject)) -> Vec { + let (runs, servers) = assemble(cells, breaks).0; + obj.runs = runs; + if !para_styles.is_empty() { + obj.set_paragraph_styles(para_styles); + } + pin(obj); + keep_reader_anchors(obj); + servers +} + +/// One point type object of a text [`split`] into several, before [`finish`]. +struct Piece { + obj: TextObject, + cells: Vec, + breaks: Vec, + paras: Vec, +} + +/// How many times [`split`] cuts a piece before the characters kerning cannot place; a piece that +/// still has such characters is then cut before each of its chunks. +const MAX_SPLITS: usize = 3; + +/// Point type objects, in text order, that together put every absolutely placed character of +/// `cells` (before [`place`] kerned them) on its x. SVG anchors each chunk on its own and reorders +/// right-to-left characters only within a chunk (SVG 2 › Text, https://www.w3.org/TR/SVG2/text.html), +/// while one object reorders the whole +/// line: a left-to-right character drawn right before a right-to-left one has no kerning between +/// them. The text is cut before each character `unplaced` lists, and each piece placed again. `ys` +/// holds each character's line baseline and y, so that a piece keeps its characters' baselines. +#[allow(clippy::too_many_arguments)] +fn split( + cells: &[Cell], + x: &[Option], + y: &[Option], + dx: &[f64], + dy: &[f64], + ys: &[(f64, f64)], + anchor_of: &dyn Fn(usize) -> f64, + pin: &dyn Fn(&mut TextObject), + unplaced: Vec, +) -> Vec { + let piece = |r: Range| { + let s = r.start; + let mut cells = cells[r.clone()].to_vec(); + let (base, cur) = ys.get(s).copied().unwrap_or((0.0, 0.0)); + // The piece starts on its line's baseline, and its first character keeps its own y. + cells[0].style.baseline_shift += base - cur; + let py: Vec> = r + .clone() + .map(|i| match i - s { + 0 => Some(base), + 1 => y[i].or(Some(cur)), + _ => y[i], + }) + .collect(); + let mut pdy = dy[r.clone()].to_vec(); + pdy[0] = 0.0; + let mut obj = TextObject::point(Point::ZERO, "", CharStyle::default()); + let (breaks, paras, unplaced) = place(&mut cells, &x[r.clone()], &py, &dx[r], &pdy, &|j| anchor_of(s + j), pin, &mut obj, &mut vec![]); + (Piece { obj, cells, breaks, paras }, unplaced.into_iter().map(|j| s + j).collect::>()) + }; + let mut done = vec![]; + let mut todo = vec![(0..cells.len(), unplaced, 0)]; + while let Some((range, failed, round)) = todo.pop() { + // Past the last round every chunk of the piece is a piece of its own, and so has no + // characters to place. + let mut cuts: Vec = if round < MAX_SPLITS { failed } else { (range.start + 1..range.end).filter(|&i| x[i].is_some()).collect() }; + cuts.sort_unstable(); + cuts.dedup(); + let mut from = range.start; + for to in cuts.into_iter().chain([range.end]) { + if to <= from || to > range.end { + continue; + } + match piece(from..to) { + (p, failed) if failed.is_empty() => done.push((from, p)), + (_, failed) => todo.push((from..to, failed, round + 1)), + } + from = to; + } + } + done.sort_by_key(|p| p.0); + done.into_iter().map(|p| p.1).collect() +} + +/// A line's first character, alignment (as for [`justify_of`]) and anchor x. +type LineStart = (usize, f64, f64); + /// Point type: line breaks, baseline shifts and kerning from the positioning lists. Returns the /// justification, the x of the first line's left (or anchor) edge and each line's first /// character, alignment (as for [`justify_of`]) and anchor x. `anchor_of` gives where the chunk /// starting at a character sits on its anchor, and `pin` sets the paragraph directions of the /// text ([`pin_direction`]). When characters are placed on their own, every line is left-aligned -/// and its anchor x is its left edge. Also returns how many absolutely placed characters kerning -/// cannot put on their x. +/// and its anchor x is its left edge. Also returns the absolutely placed characters kerning cannot +/// put on their x. `ys` takes each character's line baseline and y. #[allow(clippy::too_many_arguments)] fn lines( cells: &mut [Cell], @@ -1701,10 +1839,13 @@ fn lines( pin: &dyn Fn(&mut TextObject), x0: f64, breaks: &mut Vec, -) -> (Justify, f64, Vec<(usize, f64, f64)>, usize) { + ys: &mut Vec<(f64, f64)>, +) -> (Justify, f64, Vec, Vec) { let n = cells.len(); let y0 = y[0].unwrap_or(0.0) + dy[0]; let (mut base, mut cur) = (y0, y0); + ys.clear(); + ys.push((y0, y0)); // Line starts (first character, anchor x) and absolutely placed characters (index, x). let mut lines = vec![(0, x0)]; let mut targets: Vec<(usize, f64)> = vec![]; @@ -1723,9 +1864,11 @@ fn lines( breaks.push(Break { at: i, count: count as usize, leading: gap / count }); lines.push((i, ax + dx[i])); (base, cur) = (ny, ny); + ys.push((base, cur)); continue; } cur = ny; + ys.push((base, cur)); match x[i] { Some(ax) => targets.push((i, ax + dx[i])), None => cells[i - 1].kern += dx[i], @@ -1744,7 +1887,7 @@ fn lines( } if targets.is_empty() { let starts = lines.iter().map(|&(s, lx)| (s, anchor_of(s), lx)).collect(); - return (justify_of(anchor_of(0)), x0, starts, 0); + return (justify_of(anchor_of(0)), x0, starts, vec![]); } // Absolutely placed characters: lay the text out left-aligned and kern each one onto its x. // SVG anchors every absolutely placed chunk on its own, so a chunk not anchored at its left @@ -1774,7 +1917,7 @@ fn lines( let mut wants: Vec<(usize, f64)> = vec![]; // Absolutely placed characters drawn right next to a placed neighbor with no kerning between // them (a left-to-right character between right-to-left ones): they stay where the layout puts them. - let mut unplaced = 0; + let mut unplaced = vec![]; // Kerning changes shaping (pair kerning is off for manually kerned characters): repeat until // every character sits on its x. for round in 0..4 { @@ -1811,7 +1954,7 @@ fn lines( // character's horizontal scale, so each correction is divided by it. let mut worst = 0.0f64; let mut from = 0; - unplaced = 0; + unplaced.clear(); while from < wants.len() { let l = line_of(wants[from].0); let to = from + wants[from..].partition_point(|&(i, _)| line_of(i) == l); @@ -1831,35 +1974,35 @@ fn lines( .filter_map(|&(i, _)| (lines[l].0..i).rev().find_map(|j| pens[j]).map(|k| (2 * k.rank + if k.rtl { 1 } else { 3 }, i - 1))) .collect(); cuts.sort_unstable(); - let mut points: Vec<(usize, f64, f64)> = - on_line.iter().filter_map(|&(i, want)| pens[i].map(|p| (2 * p.rank + 2, p.start, want))).collect(); + let mut points: Vec<(usize, f64, f64, usize)> = + on_line.iter().filter_map(|&(i, want)| pens[i].map(|p| (2 * p.rank + 2, p.start, want, i))).collect(); points.sort_by_key(|p| p.0); // The character kerned at the first cut between places `a` and `b`. let cut = |a: usize, b: usize| cuts.get(cuts.partition_point(|c| c.0 <= a)).filter(|c| c.0 < b).map(|c| c.1); let split = points.partition_point(|p| p.0 < home); // Drawn right of the line's first chunk: kerning moves the character away from it. let (mut prev, mut moved) = (home, 0.0); - for &(place, start, want) in &points[split..] { + for &(place, start, want, i) in &points[split..] { if let Some(k) = cut(prev, place) { let d = want - (start - p0 + moved); cells[k].kern += d / spacing_scale(&cells[k].style, false); moved += d; worst = worst.max(d.abs()); } else { - unplaced += 1; + unplaced.push(i); } prev = place; } // Drawn left of it: kerning moves the chunk (and what lies between) away from the character. (prev, moved) = (home, 0.0); - for &(place, start, want) in points[..split].iter().rev() { + for &(place, start, want, i) in points[..split].iter().rev() { if let Some(k) = cut(place, prev) { let d = start - p0 - moved - want; cells[k].kern += d / spacing_scale(&cells[k].style, false); moved += d; worst = worst.max(d.abs()); } else { - unplaced += 1; + unplaced.push(i); } prev = place; } @@ -2064,7 +2207,8 @@ fn pens(lay: &TextLayout, bytes: &[usize], cells: &[Cell]) -> Vec> { .collect() } -type Key = (Option, Option); +/// The indices of a run's fill and stroke `url(#…)` paints. +pub(super) type Key = (Option, Option); type Runs = (Vec, Vec); /// Runs (and their paint indices) from the characters, with `breaks` inserted; also the byte offset diff --git a/crates/svg/tests/it/clip_text.rs b/crates/svg/tests/it/clip_text.rs index bb92802e60..4cbcc9a812 100644 --- a/crates/svg/tests/it/clip_text.rs +++ b/crates/svg/tests/it/clip_text.rs @@ -125,6 +125,20 @@ fn a_text_clip_path_with_a_clip_rule_or_a_clip_of_its_own_clips_by_its_outlines( assert_eq!(shapes[0].1, vectorcraft_geom::FillRule::EvenOdd); } +#[test] +fn a_text_imported_as_several_objects_clips_by_all_their_outlines() { + // One object cannot put ג on its x, so the text is several objects; the clip outlines all of them. + let d = open( + r##"אbג + "##, + ); + let (clip, _) = clip_group(&top(&d)[0]); + assert!(!matches!(clip.kind, NodeKind::Text(_)), "{:?}", clip.kind); + let b = clip_bounds(clip); + // ג ends at 220, the first object at 160. + assert!(b.x1 > 200.0 && b.x1 <= 220.0 + 1e-6 && b.x0 < 100.0, "{b:?}"); +} + #[test] fn tspans_and_type_on_a_path_clip_too() { let d = open( diff --git a/crates/svg/tests/it/import_text.rs b/crates/svg/tests/it/import_text.rs index fa91f8d162..c8a1cfd4ed 100644 --- a/crates/svg/tests/it/import_text.rs +++ b/crates/svg/tests/it/import_text.rs @@ -974,7 +974,7 @@ fn absolutely_placed_right_to_left_characters_sit_on_their_own_x() { vec![(0..2, 20.0), (3..4, 100.0), (4..5, 160.0)], ), ]; - let unplaced = |w: &[String]| w.iter().any(|w| w.contains("absolutely placed")); + let unplaced = |w: &[String]| w.iter().any(|w| w.contains("point type objects")); for (body, share, chunks) in cases { let (d, w) = import_with_report(&svg(&body)).unwrap(); assert!(!unplaced(&w), "{body}: {w:?}"); @@ -988,12 +988,82 @@ fn absolutely_placed_right_to_left_characters_sit_on_their_own_x() { assert!(close(left, want, 0.05), "{body}: the chunk {bytes:?} spans {left}..{right}, so it does not start at {want}"); } } - // A left-to-right character between right-to-left ones is drawn right next to the one after - // it, with no kerning between them: that one keeps its place in the line, and a warning says so. - let (d, w) = import_with_report(&svg(r#"אbג"#)).unwrap(); - assert!(unplaced(&w), "{w:?}"); - let (left, right) = chunk_edges(only_text(&d), 2..3); - assert!(close(right, 160.0, 0.05), "b spans {left}..{right}"); +} + +/// The document-space edges of character `ch`, in whichever text of `d` holds it (as +/// [`chunk_edges`] measures them), and the y it is drawn at (its baseline moved by its baseline +/// shift). +fn char_edges(d: &Document, ch: char) -> (f64, f64, f64) { + let t = texts(d).into_iter().find(|t| t.plain_text().contains(ch)).unwrap_or_else(|| panic!("no text holds {ch}")); + let at = t.plain_text().find(ch).unwrap(); + let (left, right) = chunk_edges(t, at..at + ch.len_utf8()); + let shift = t.runs.iter().find(|r| r.text.contains(ch)).unwrap().style.baseline_shift; + let y = layout(FontDb::global(), t).glyphs.iter().find(|g| g.byte == at).map(|g| (t.xf * g.origin).y).unwrap() - shift; + (left, right, y) +} + +/// SVG 2 › Text (https://www.w3.org/TR/SVG2/text.html): each absolute position starts a chunk, +/// and bidi reordering happens only within a chunk. A left-to-right character drawn right before a +/// right-to-left one has no kerning between them in one text object, so such a text imports as a +/// group of point type objects, each character on its own x. +#[test] +fn absolutely_placed_characters_one_object_cannot_place_import_as_a_group() { + // (markup, the characters of its objects in order, each character with the x its right edge + // sits on and its baseline) + type Case = (&'static str, &'static str, Vec<(char, f64, f64)>); + let cases: Vec = vec![ + ( + r#"אbג"#, + "אbג", + vec![('א', 100.0, 80.0), ('b', 160.0, 80.0), ('ג', 220.0, 80.0)], + ), + ( + r#"אbגd"#, + "אbגd", + vec![('א', 100.0, 80.0), ('b', 160.0, 80.0), ('ג', 220.0, 80.0), ('d', 280.0, 80.0)], + ), + // x values that decrease. + ( + r#"אbג"#, + "אbג", + vec![('א', 220.0, 80.0), ('b', 160.0, 80.0), ('ג', 100.0, 80.0)], + ), + // On a second line, and with a baseline of its own. + ( + r#"אבגbד"#, + "אבגbד", + vec![('א', 40.0, 40.0), ('ג', 100.0, 80.0), ('b', 160.0, 80.0), ('ד', 220.0, 90.0)], + ), + ]; + for (body, text, chars) in cases { + let (d, w) = import_with_report(&svg(body)).unwrap(); + assert!(w.iter().any(|w| w.contains("point type objects in a group")), "{body}: {w:?}"); + let top = d.layers[0].children().unwrap(); + assert_eq!(top.len(), 1, "{body}: {top:?}"); + assert_eq!(top[0].name.as_deref(), Some("t"), "{body}: the group takes the element's id"); + let NodeKind::Group { children, clip: false } = &top[0].kind else { panic!("{body}: {:?}", top[0].kind) }; + assert!(children.len() > 1 && children.iter().all(|c| matches!(c.kind, NodeKind::Text(_))), "{body}: {children:?}"); + let all: String = texts(&d).iter().map(|t| t.plain_text().replace('\n', "")).collect(); + assert_eq!(all, text, "{body}: every character once, in order"); + for (ch, x, y) in chars { + let (left, right, base) = char_edges(&d, ch); + assert!(close(right, x, 0.05), "{body}: {ch} spans {left}..{right}, not ending at {x}"); + assert!(close(base, y, 1e-6), "{body}: {ch} sits on {base}, not {y}"); + } + } + // Placed characters one object can place stay one object, also when their x values decrease. + for (body, chars) in [ + (r#"אbc"#, [('א', 100.0), ('b', 160.0), ('c', 220.0)]), + (r#"אבג"#, [('א', 220.0), ('ב', 160.0), ('ג', 100.0)]), + ] { + let (d, w) = import_with_report(&svg(body)).unwrap(); + assert!(!w.iter().any(|w| w.contains("point type objects")), "{body}: {w:?}"); + only_text(&d); + for (ch, x) in chars { + let (left, right, _) = char_edges(&d, ch); + assert!(close(right, x, 0.05), "{body}: {ch} spans {left}..{right}, not ending at {x}"); + } + } } #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index eed107bf24..520ec4fc09 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1783,7 +1783,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A gap between glyphs of two sizes is measured against the smaller one, so a word set beside a much larger one with no space glyph between them (a browser's margin between two sizes, as in `≤ 4` and a small `hours`) keeps its word space (#3623). SVG import's style cascade, used for hidden objects, non-scaling strokes and type, tests each element only against the `