Merge pull request #7934 from dotCooCoo/fix/svg-import-absolute-ltr-character

SVG import: absolutely placed characters one text object cannot place import as a group
This commit is contained in:
BFlat
2026-11-16 04:27:23 +07:00
committed by GitHub
5 changed files with 329 additions and 88 deletions
+44 -32
View File
@@ -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<Paint> = (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<Paint> = (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<Node> {
@@ -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 {
+192 -48
View File
@@ -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<usize>, Option<usize>)>,
/// 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<Key>)>,
/// 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<String>)| {
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 `<text>`: 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<Break> = vec![];
let mut para_styles: Vec<ParaStyle> = 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<f64>],
y: &[Option<f64>],
dx: &[f64],
dy: &[f64],
anchor_of: &dyn Fn(usize) -> f64,
pin: &dyn Fn(&mut TextObject),
obj: &mut TextObject,
ys: &mut Vec<(f64, f64)>,
) -> (Vec<Break>, Vec<ParaStyle>, Vec<usize>) {
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<ParaStyle>, pin: &dyn Fn(&mut TextObject)) -> Vec<Key> {
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<Cell>,
breaks: Vec<Break>,
paras: Vec<ParaStyle>,
}
/// 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<f64>],
y: &[Option<f64>],
dx: &[f64],
dy: &[f64],
ys: &[(f64, f64)],
anchor_of: &dyn Fn(usize) -> f64,
pin: &dyn Fn(&mut TextObject),
unplaced: Vec<usize>,
) -> Vec<Piece> {
let piece = |r: Range<usize>| {
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<Option<f64>> = 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::<Vec<_>>())
};
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<usize> = 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<Break>,
) -> (Justify, f64, Vec<(usize, f64, f64)>, usize) {
ys: &mut Vec<(f64, f64)>,
) -> (Justify, f64, Vec<LineStart>, Vec<usize>) {
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<Option<Pen>> {
.collect()
}
type Key = (Option<usize>, Option<usize>);
/// The indices of a run's fill and stroke `url(#…)` paints.
pub(super) type Key = (Option<usize>, Option<usize>);
type Runs = (Vec<TextRun>, Vec<Key>);
/// Runs (and their paint indices) from the characters, with `breaks` inserted; also the byte offset
+14
View File
@@ -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##"<clipPath id="c"><text x="100 160 220" y="80" direction="rtl" font-size="20">אbג</text></clipPath>
<rect width="400" height="300" clip-path="url(#c)"/>"##,
);
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(
+77 -7
View File
@@ -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#"<text x="100 160 220" y="80" direction="rtl" font-size="20">אbג</text>"#)).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<Case> = vec![
(
r#"<text id="t" x="100 160 220" y="80" direction="rtl" font-size="20">אbג</text>"#,
"אbג",
vec![('א', 100.0, 80.0), ('b', 160.0, 80.0), ('ג', 220.0, 80.0)],
),
(
r#"<text id="t" x="100 160 220 280" y="80" direction="rtl" font-size="20">אbגd</text>"#,
"א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#"<text id="t" x="220 160 100" y="80" direction="rtl" font-size="20">אbג</text>"#,
"א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#"<text id="t" direction="rtl" font-size="20"><tspan x="40" y="40">אב</tspan><tspan x="100 160 220" y="80 80 90">גbד</tspan></text>"#,
"אבג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#"<text x="100 160 220" y="80" direction="rtl" font-size="20">אbc</text>"#, [('א', 100.0), ('b', 160.0), ('c', 220.0)]),
(r#"<text x="220 160 100" y="80" direction="rtl" font-size="20">אבג</text>"#, [('א', 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]
+2 -1
View File
@@ -1793,7 +1793,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 `<style>` rules for its id, its classes and its element name, and the rules whose selector ends in none of these (`*`, `[x]`).
SVG import places right-to-left point type and type on a path as [SVG 2's `text-anchor`](https://www.w3.org/TR/SVG2/text.html#TextAnchoringProperties) says: with `direction: rtl`, `start` puts the right edge of the text at its position (on a path, the text ends at `startOffset`) and `end` puts the left edge there. Each line and each absolutely placed chunk is anchored by the `text-anchor` and `direction` of the element holding its first character, a `<tspan>`'s own included, and each line starts at its own `x`. An absolutely placed chunk is anchored by the left and right edges of its glyphs as they are drawn, so a chunk of several right-to-left characters, whose first character is drawn at its right, sits on its anchor too. A letter-spaced right-to-left line keeps the tracking of all its letters inside the advance it anchors (`rtl_point_text_start_and_end_use_directional_edges`, `rtl_type_on_a_path_starts_at_its_directional_edge`, `rtl_letter_spaced_lines_stay_on_their_anchor`, `rtl_lines_use_each_chunk_first_character_direction_and_anchor`, `each_line_starts_at_its_own_x`, `absolutely_placed_chunks_use_their_own_rtl_anchor` and `absolutely_placed_rtl_chunks_of_several_characters_anchor_by_their_visual_edges` in `crates/svg/tests/it/import_text.rs`).
SVG import puts each absolutely placed character of right-to-left text on its own `x`, as [SVG 1.1's text chunks](https://www.w3.org/TR/SVG11/text.html#TextLayoutIntroduction) require, also when the characters run right to left on a later line: in `<text direction="rtl" font-size="20">`, `<tspan x="100 160" y="80 80">אב</tspan>` after a first line puts the right edges of `א` and `ב` at 100 and 160, where import put the right edge of `א` at 393.48 before. Chunks that overlap keep their own anchors, and characters stretched by `lengthAdjust="spacingAndGlyphs"` land on their `x` too. A left-to-right character drawn between two absolutely placed right-to-left characters leaves the one after it where the line puts it, and the import warns about it (`absolutely_placed_right_to_left_characters_sit_on_their_own_x` in `crates/svg/tests/it/import_text.rs`).
SVG import puts each absolutely placed character of right-to-left text on its own `x`, as [SVG 1.1's text chunks](https://www.w3.org/TR/SVG11/text.html#TextLayoutIntroduction) require, also when the characters run right to left on a later line: in `<text direction="rtl" font-size="20">`, `<tspan x="100 160" y="80 80">אב</tspan>` after a first line puts the right edges of `א` and `ב` at 100 and 160, where import put the right edge of `א` at 393.48 before. Chunks that overlap keep their own anchors, and characters stretched by `lengthAdjust="spacingAndGlyphs"` land on their `x` too (`absolutely_placed_right_to_left_characters_sit_on_their_own_x` in `crates/svg/tests/it/import_text.rs`).
SVG import puts an absolutely placed character on its `x` also when one text object cannot place it. [SVG 1.1 reorders right-to-left characters only within a text chunk](https://www.w3.org/TR/SVG11/text.html#RelationshipWithBi-directionality), while one object reorders the whole line: in `<text x="100 160 220" y="80" direction="rtl" font-size="20">אbג</text>`, the left-to-right `b` is drawn right before `ג` with no kerning between them, and import left `ג` where the line put it, with a warning, before. Such a text imports as a group of point type objects named after the element, cut before each character one object cannot place, with the right edges of `א`, `b` and `ג` at 100, 160 and 220, and the import warns that the text became several objects. A text that one object can place stays one object, and a split text in a clip path clips by the outlines of all its objects (`absolutely_placed_characters_one_object_cannot_place_import_as_a_group` in `crates/svg/tests/it/import_text.rs`, `a_text_imported_as_several_objects_clips_by_all_their_outlines` in `crates/svg/tests/it/clip_text.rs`).
SVG import places type on a path of one closed subpath as [SVG 2's `startOffset` attribute](https://www.w3.org/TR/SVG2/text.html#TextPathElementStartOffsetAttribute) describes: text anchored to start before the path's start point, or offset past its end, wraps around the path, so text with `text-anchor="end"` at `startOffset` 0 ends at the start point, and a negative `startOffset` counts back from the end. Text longer than the loop draws its first characters whatever its anchor. A path of several closed subpaths still starts the text at the path's start or end (`text_on_a_closed_path_wraps_past_the_path_start` in `crates/svg/tests/it/import_text.rs`).
Type on an open path can start before the path's start (`type.pathOptions` `start` below 0), and the characters whose middle falls before the path's start are not drawn, as [SVG 2's text on a path layout](https://www.w3.org/TR/SVG2/text.html#TextLayoutPath) describes for the path's start; past the path's end, text that does not fit is overflow, as for other type on a path. The text keeps every character, and the start bracket stays at the path's start. SVG import reads text anchored or offset before an open path's start this way instead of starting it at the path's start, and SVG export writes it with a negative `startOffset`. PDF export writes only the characters drawn on the path, the legacy `.ai` and `.ai` editing data writers write the type from the path's start with a warning, and Release Type on a Path keeps the first drawn character where it was drawn (`type_on_an_open_path_starts_before_the_path` in `crates/doc/src/text/tests.rs`, `on_path_open_start_before_the_path_hides_the_glyphs_before_it` in `crates/text/src/tests.rs`, `text_on_an_open_path_starts_before_the_path` in `crates/svg/tests/it/import_text.rs`, `text_on_an_open_path_starting_before_it_round_trips` in `crates/svg/tests/it/roundtrip.rs`, `options_start_type_before_an_open_path` in `crates/engine/src/tests/pathtype.rs`).
SVG import reads the bidi embedding of a `<tspan>`, `<textPath>` or `<a>` inside a `<text>` as [SVG 1.1's bidi section](https://www.w3.org/TR/SVG11/text.html#RelationshipWithBi-directionality) describes: with `unicode-bidi: embed` its characters take its `direction` as their Character Direction, an element with `normal` stays in its parent's embedding, and the `<text>` keeps its own paragraph direction, so a run that SVG export writes with `direction` and `unicode-bidi="embed"` opens with its Character Direction again. Character Direction holds one level of embedding, so `bidi-override`, `isolate` and `isolate-override` are imported as embeddings in their `direction`, `plaintext` as an embedding in the direction of its first strong character, and an embedding inside another as an embedding of its own, each with an import warning. With `unicode-bidi: plaintext` on the `<text>`, each of its paragraphs runs, and each chunk is anchored, in the direction of its first strong character (`a_tspan_bidi_embedding_becomes_its_character_direction`, `unicode_bidi_is_not_inherited_and_reads_from_the_cascade` and `unicode_bidi_values_the_text_model_cannot_hold_are_reported` in `crates/svg/tests/it/import_text.rs`; `character_direction_reads_back` in `crates/svg/tests/it/text_layout.rs`).