Retype: stacked lines become one area type object

Part of #4934. type.retype set each line of outlined text as its own
point type object, even when the lines stack as one paragraph.

- Opaque, Normal lines with a solid fill or none and no stroke that
  follow each other in paint order, with the same group, paint, font,
  size, turn and tracking, each the same leading (0.25 to 3 times the
  size) below the one before and lined up at their starts, ends or
  centers, become one area type object. Its leading is Auto when Auto
  puts the last baseline in place, else the mean distance between the
  baselines, and its alignment is left, right or center. Its frame is
  Convert To Area Type's, now shared through typemenu::point_to_area.
  An untracked line of one or two glyphs takes the others' tracking.
- Every object is laid out and compared with the outlines first: when
  area type would move a glyph the lines stay multi-line point type.
  When that also moves a glyph, the block ends at that glyph's line and
  the lines after it join again. Type whose bounds would reach past the
  coordinate limit stays apart.
- Text Wrap objects above new area type are taken into account; when
  checking them on the changed layers would copy more than 2,000,000
  anchors, subpaths and shapes, the lines stay multi-line point type.
  text::wrap_copy_units counts that work without copying the outlines,
  and wrap_work no longer copies them to count.
- The result's fonts entries add leading and area, and texts join an
  object's lines with line breaks.

These rules are VectorCraft's own. Docs: docs/mcp.md (Retype several
lines), docs/type-parity.md (Retype row), docs/target-app-parity.md,
docs/roadmap.md (M7 row).
This commit is contained in:
dotCooCoo
2026-11-19 10:22:49 -08:00
parent 45c6fb40cb
commit cdcaab9301
9 changed files with 749 additions and 50 deletions
+350 -20
View File
@@ -11,9 +11,10 @@
//! ([`vectorcraft_text::retype`]), the same up to uniform scale, rotation and translation. Matched
//! glyphs map back to characters through the font's cmap and are rebuilt as point text, one object
//! per line of glyphs, with the first glyph's fill and stroke. A line whose glyphs are evenly spaced
//! apart takes that spacing as its tracking ([`Line::tracked`]). Shapes that match no font stay as
//! they are and are reported. Near matches (another version of the font, simplified outlines,
//! merged glyphs) and images are phase 2.
//! apart takes that spacing as its tracking ([`Line::tracked`]), and lines stacked at one leading
//! and lined up at their starts, ends or centers become one area type object ([`blocks`]). Shapes
//! that match no font stay as they are and are reported. Near matches (another version of the
//! font, simplified outlines, merged glyphs) and images are phase 2.
use std::f64::consts::{PI, TAU};
use std::sync::Arc;
@@ -40,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Retype",
["Type"],
None,
"{fonts?: [family…]} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live point text: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation (exact matches only); matched glyphs become point text in that font and size at the same baseline, one object per line, with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts, fonts: [{family, style, size, tracking (1/1000 em)}], unmatched: [id…], truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error when no shape matches",
"{fonts?: [family…]} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation (exact matches only); matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool)}], unmatched: [id…], truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error when no shape matches",
has_selected_path,
retype
)]
@@ -347,18 +348,15 @@ impl Line {
/// (a substitution the font makes) or the same glyph elsewhere (tracking, manual spacing,
/// more space than whole spaces make); `None` when the type draws every glyph in its place.
fn first_mismatch(&self, t: &TextObject) -> Option<usize> {
let lay = vectorcraft_text::layout(FontDb::global(), t);
let mut drawn = lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty());
let tol = (self.scale * self.face.units_per_em() * 0.01).max(0.01);
for (k, m) in self.matches.iter().enumerate() {
let Some(g) = drawn.next() else { return Some(k) };
let at = t.xf * (g.xf * Point::ORIGIN);
if g.font_id != m.face.id() || g.gid != m.gid || at.distance(m.origin) > tol {
return Some(k);
}
}
// Ink the outlines did not have: the last glyph is where it went wrong.
drawn.next().map(|_| self.matches.len().saturating_sub(1))
first_mismatch(t, &self.matches, self.size())
}
/// Along the line, where its first glyph starts and its last glyph's advance ends, from
/// `from` (the tracking after the last glyph left out).
fn span_from(&self, from: Point) -> (f64, f64) {
let dir = self.dir();
let last = self.matches.last().map_or(self.end, |m| m.origin + dir * (m.face.advance(m.gid) * m.scale));
((self.origin - from).dot(dir), (last - from).dot(dir))
}
/// This line with the tracking its glyphs are spaced by, when it has at least three glyphs.
@@ -564,6 +562,24 @@ fn round_tracking(t: f64) -> f64 {
if (t - t.round()).abs() < 0.05 { t.round() } else { t }
}
/// The first of `matches` that type `t` (at `size`) does not draw as the outlines did: another
/// glyph (a substitution the font makes) or the same glyph elsewhere (tracking, manual spacing,
/// more space than whole spaces make); `None` when the type draws every glyph in its place.
fn first_mismatch(t: &TextObject, matches: &[GlyphMatch], size: f64) -> Option<usize> {
let lay = vectorcraft_text::layout(FontDb::global(), t);
let mut drawn = lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty());
let tol = (size * 0.01).max(0.01);
for (k, m) in matches.iter().enumerate() {
let Some(g) = drawn.next() else { return Some(k) };
let at = t.xf * (g.xf * Point::ORIGIN);
if g.font_id != m.face.id() || g.gid != m.gid || at.distance(m.origin) > tol {
return Some(k);
}
}
// Ink the outlines did not have: the last glyph is where it went wrong.
drawn.next().map(|_| matches.len().saturating_sub(1))
}
/// `lines` checked against their own layout: a line splits where its type stops drawing the
/// outlines, and a glyph its type cannot draw even on its own stays an outline (`unmatched`).
/// The glyphs laid out are bounded by a multiple of the number of glyphs.
@@ -656,6 +672,263 @@ fn verified(lines: Vec<Line>, system_layout: bool, unmatched: &mut Vec<NodeId>)
out
}
/// Most units (anchors, subpaths and shapes) that Text Wrap objects may copy into the wrap shapes
/// of the area type on the layers Retype changes
/// ([`vectorcraft_doc::text::wrap_copy_units`]) when Retype checks how they flow new area type.
const MAX_WRAP_WORK: usize = 2_000_000;
#[cfg(not(test))]
fn max_wrap_work() -> usize {
MAX_WRAP_WORK
}
#[cfg(test)]
thread_local! {
/// [`MAX_WRAP_WORK`], lowered by tests on their own thread.
static WRAP_LIMIT: std::cell::Cell<usize> = const { std::cell::Cell::new(MAX_WRAP_WORK) };
}
#[cfg(test)]
fn max_wrap_work() -> usize {
WRAP_LIMIT.with(|c| c.get())
}
/// Lines farther apart than this many times their size do not join into one object.
const MAX_LEADING: f64 = 3.0;
/// What Retype makes: one type object and the shapes it replaces.
struct Made {
t: TextObject,
/// For area type, the point type that also draws the glyphs in place: the type kept when
/// Text Wrap objects above it change the area type's layout.
point: Option<TextObject>,
/// The glyphs the type must draw, in order.
matches: Vec<GlyphMatch>,
pieces: Vec<NodeId>,
text: String,
face: Arc<vectorcraft_text::FontFace>,
size: f64,
tracking: f64,
/// The leading set on the type: None for Auto or a single line.
leading: Option<f64>,
opacity: f32,
blend: vectorcraft_color::BlendMode,
}
impl Made {
fn line(l: &Line, system_layout: bool) -> Made {
Made {
t: l.text_object(system_layout),
point: None,
matches: l.matches.clone(),
pieces: l.pieces.clone(),
text: l.text.clone(),
face: l.face.clone(),
size: l.size(),
tracking: l.tracking,
leading: None,
opacity: l.opacity,
blend: l.blend,
}
}
}
/// The alignments lines can share, in the order one is chosen: their starts, their ends, their
/// centers.
const ALIGNS: [vectorcraft_doc::Justify; 3] = [vectorcraft_doc::Justify::Left, vectorcraft_doc::Justify::Right, vectorcraft_doc::Justify::Center];
/// A run of lines that may become one object: lines after the first, each one leading further
/// across, in the same group, paint, transparency, font, size, turn and tracking, lined up alike.
struct Block {
lines: Vec<Line>,
/// The mean distance between baselines, from the first line's to the last line's.
leading: f64,
/// Which of [`ALIGNS`] every line so far shares.
aligns: [bool; 3],
/// The tracking of the first line that has one ([`Block::spaced`]).
tracking: Option<f64>,
}
impl Block {
fn new(l: Line) -> Block {
let tracking = Block::spaced(&l).then_some(l.tracking);
Block { lines: vec![l], leading: 0.0, aligns: [true; 3], tracking }
}
/// Does line `l` have a tracking of its own? A line of fewer than three glyphs that kept no
/// tracking has no gaps to measure it by ([`Line::tracked`]): it takes the block's.
fn spaced(l: &Line) -> bool {
l.pieces.len() >= 3 || l.tracking != 0.0
}
/// Add `l` when it continues the block; `l` back when it does not. `follows` tells whether the
/// shape `l` starts with comes right after the block's last shape, with nothing between them
/// in paint order.
fn take(&mut self, l: Line, follows: impl Fn(NodeId, NodeId) -> bool) -> Option<Line> {
let (Some(first), Some(prev)) = (self.lines.first(), self.lines.last()) else { return Some(l) };
let (Some(a), Some(b)) = (prev.pieces.last(), l.pieces.first()) else { return Some(l) };
let size = first.size();
let tol = (size * 0.01).max(0.01);
let same = follows(*a, *b)
&& l.parent == first.parent
&& l.appearance == first.appearance
&& l.opacity == first.opacity
&& l.blend == first.blend
&& l.face.id() == first.face.id()
&& (l.scale - first.scale).abs() <= first.scale * 1e-4
&& ((l.angle - first.angle + PI).rem_euclid(TAU) - PI).abs() < 1e-5
// The lines' estimates may differ a little; the layout check decides.
&& (!Block::spaced(&l) || self.tracking.is_none_or(|t| (l.tracking - t).abs() < 1.0))
// Lines whose ink overlaps, or a gradient spanning them, would paint otherwise as one.
&& paints_as_one(first);
if !same {
return Some(l);
}
// Across the lines, down from the first line's baseline.
let across = Vec2::new(-first.angle.sin(), first.angle.cos());
let down = (l.origin - first.origin).dot(across);
let n = self.lines.len() as f64;
// The mean distance between the baselines so far, which this line's must continue.
let leading = if self.lines.len() == 1 { down } else { self.leading };
if !(leading > size * 0.25 && leading <= size * MAX_LEADING) || (down - n * leading).abs() > tol {
return Some(l);
}
let leading = down / n;
let (s0, e0) = first.span_from(first.origin);
let (s, e) = l.span_from(first.origin);
let fits = [(s - s0).abs() <= tol, (e - e0).abs() <= tol, ((s + e) - (s0 + e0)).abs() * 0.5 <= tol];
let aligns = [self.aligns[0] && fits[0], self.aligns[1] && fits[1], self.aligns[2] && fits[2]];
if !aligns.contains(&true) {
return Some(l);
}
self.leading = leading;
self.aligns = aligns;
if self.tracking.is_none() && Block::spaced(&l) {
self.tracking = Some(l.tracking);
}
self.lines.push(l);
None
}
/// The block as one area type object when type draws every glyph in its place as area type,
/// else as one point type object when that does. When neither does, the lines before the line
/// of the first glyph the type moves are made again as a block, and the lines from that one on
/// are joined again ([`blocks`]); the first line on its own stays one object. Area type whose
/// frame would reach past [`crate::MAX_COORD`] stays point type, and point type whose bounds
/// would stays one object per line. Each try takes six times the
/// block's glyphs from `budget` (point and area type are each laid out, measured and checked);
/// without enough left, each line is one object.
fn made(self, system_layout: bool, budget: &mut usize) -> Vec<Made> {
let single = |lines: &[Line]| lines.iter().map(|l| Made::line(l, system_layout)).collect::<Vec<_>>();
let (Some(first), true) = (self.lines.first(), self.lines.len() > 1) else { return single(&self.lines) };
let Some(justify) = ALIGNS.iter().zip(self.aligns).find(|(_, ok)| *ok).map(|(j, _)| *j) else { return single(&self.lines) };
let glyphs = self.lines.iter().map(|l| l.pieces.len()).fold(0usize, usize::saturating_add);
let Some(left) = budget.checked_sub(glyphs.saturating_mul(6)) else { return single(&self.lines) };
*budget = left;
let mut all = first.clone();
all.tracking = self.tracking.unwrap_or(first.tracking);
all.text = self.lines.iter().map(|l| l.text.as_str()).collect::<Vec<_>>().join("\n");
let mut t = all.probe(system_layout);
t.para.justify = justify;
let size = first.size();
let mut set_leading = None;
if let Some(r) = t.runs.first_mut() {
// The leading that puts the last baseline where the last line's is: Auto when Auto
// does, else the mean distance between baselines, to a thousandth of a point (as
// typed leading is) when that still puts the last baseline in place.
let gaps = self.lines.len().saturating_sub(1) as f64;
let across = Vec2::new(-first.angle.sin(), first.angle.cos());
let span = self.lines.last().map_or(0.0, |l| (l.origin - first.origin).dot(across));
if (t.para.effective_leading(&r.style) * gaps - span).abs() > size * 1e-4 {
let exact = span / gaps;
let rounded = (exact * 1000.0).round() / 1000.0;
let leading = if ((rounded - exact) * gaps).abs() <= size * 1e-4 { rounded } else { exact };
r.style.leading = Some(leading);
set_leading = Some(leading);
}
}
let matches: Vec<GlyphMatch> = self.lines.iter().flat_map(|l| l.matches.iter().cloned()).collect();
// Aligned at its end or center, point type starts its first line elsewhere: the type moves
// so its first glyph is where the first outline is.
let lay = vectorcraft_text::layout(FontDb::global(), &t);
if let (Some(g), Some(m)) = (lay.glyphs.iter().find(|g| !g.outline.elements().is_empty()), matches.first()) {
let at = t.xf * (g.xf * Point::ORIGIN);
t.xf = kurbo::Affine::translate(m.origin - at) * t.xf;
}
super::typecmd::refresh_bounds(&mut t);
if let Some(k) = first_mismatch(&t, &matches, size) {
// The line that holds glyph `k`.
let mut seen = 0usize;
let at = self.lines.iter().position(|l| {
seen = seen.saturating_add(l.pieces.len());
k < seen
});
let Block { mut lines, leading, aligns, .. } = self;
let rest = lines.split_off(at.unwrap_or(0).clamp(1, lines.len()));
let mut out = if lines.len() > 1 {
let tracking = lines.iter().find(|l| Block::spaced(l)).map(|l| l.tracking);
Block { lines, leading, aligns, tracking }.made(system_layout, budget)
} else {
single(&lines)
};
// The lines of the rest followed each other in the block.
out.extend(blocks(rest, |_, _| true, system_layout, budget));
return out;
}
// The edit is refused when an object's bounds reach past the coordinate limit. A turned
// block's box can reach a corner that none of its lines does: the lines then stay apart.
let in_range =
|t: &TextObject| Node::new(NodeId(0), NodeKind::Text(Box::new(t.clone()))).geometric_bounds().is_none_or(crate::sanity::rect_in_range);
if !in_range(&t) {
return single(&self.lines);
}
let mut area = t.clone();
super::typemenu::point_to_area(&mut area);
let mut point = None;
if in_range(&area) && first_mismatch(&area, &matches, size).is_none() {
point = Some(std::mem::replace(&mut t, area));
}
vec![Made {
t,
point,
matches,
pieces: self.lines.iter().flat_map(|l| l.pieces.iter().copied()).collect(),
text: all.text,
face: first.face.clone(),
size,
tracking: all.tracking,
leading: set_leading,
opacity: first.opacity,
blend: first.blend,
}]
}
}
/// `lines`, in paint order, as the objects Retype makes: runs of lines that stack as the lines of
/// one paragraph do become one object ([`Block`]). `follows(a, b)`: shape `b` comes right after
/// shape `a`, with nothing between them in paint order. `budget`: see [`Block::made`].
fn blocks(lines: Vec<Line>, follows: impl Fn(NodeId, NodeId) -> bool, system_layout: bool, budget: &mut usize) -> Vec<Made> {
let mut out = vec![];
let mut block: Option<Block> = None;
for l in lines {
let l = match block.as_mut() {
Some(b) => match b.take(l, &follows) {
None => continue,
Some(l) => l,
},
None => l,
};
if let Some(b) = block.take() {
out.extend(b.made(system_layout, budget));
}
block = Some(Block::new(l));
}
if let Some(b) = block {
out.extend(b.made(system_layout, budget));
}
out
}
/// Puts parts of a line at the front of the work list, in order.
trait FrontParts {
fn extend_front_parts<const N: usize>(&mut self, l: &Line, ranges: [(usize, usize); N]);
@@ -855,20 +1128,29 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
!lone
});
}
(lines, unmatched, truncated)
let at: std::collections::HashMap<NodeId, usize> = pieces.iter().enumerate().map(|(i, pc)| (pc.id, i)).collect();
let follows = |a: NodeId, b: NodeId| match (at.get(&a), at.get(&b)) {
(Some(i), Some(j)) => *j == i + 1 && pieces.get(*j).is_some_and(|pc| !pc.after_barrier),
_ => false,
};
// Joining lines takes at most four tries' work per glyph (see [`Block::made`]), with room
// for small blocks.
let mut budget = lines.iter().map(|l| l.pieces.len()).fold(0usize, usize::saturating_add).saturating_mul(24).saturating_add(256);
(blocks(lines, follows, system_layout, &mut budget), unmatched, truncated)
};
if lines.is_empty() {
return Err(EngineError::Other(format!("Retype: no selected shape matches a glyph of an available font ({} checked)", unmatched.len())));
}
let made = s.edit("Retype", |d, sel| {
// The layers as they were, for the Text Wrap check below.
let before = lines.iter().any(|l| l.point.is_some()).then(|| d.clone());
let mut ids = vec![];
let mut emptied = vec![];
for l in &lines {
let Some(first) = l.pieces.first() else { continue };
let (par, idx, _) = d.position(*first).ok_or(EngineError::NoNode(*first))?;
let t = l.text_object(system_layout);
let id = d.alloc_id();
let mut node = Node::new(id, NodeKind::Text(Box::new(t)));
let mut node = Node::new(id, NodeKind::Text(Box::new(l.t.clone())));
// The glyphs' own transparency (the group's, kept, still applies over it).
node.opacity = l.opacity;
node.blend = l.blend;
@@ -915,17 +1197,65 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
}
}
}
// Text Wrap objects above new area type flow it once the edit is done: area type they
// would move a glyph of becomes the point type that draws it in place.
if let Some(before) = &before {
// Worked out on a copy, so the edit's own Text Wrap refresh still sees every other
// area type whose wrap changes, and only on the layers this edit changed, as that
// refresh is. The copy holds only the changed layers while the work is counted; past
// the limit, the new area type is not flowed and all of it becomes its point type.
let mut probe = d.clone();
let all = std::mem::take(&mut probe.layers);
probe.layers = all
.iter()
.enumerate()
.filter(|(i, layer)| {
// As resolve_wrap tells an unchanged layer: the same layer at its index first.
!(before.layers.get(*i).is_some_and(|b| Arc::ptr_eq(b, layer))
|| before.layers.iter().any(|b| b.id == layer.id && Arc::ptr_eq(b, layer)))
})
.map(|(_, layer)| layer.clone())
.collect();
let units = vectorcraft_doc::text::wrap_copy_units(&probe);
let flowed = units <= max_wrap_work();
probe.layers = all;
if flowed && units > 0 {
vectorcraft_doc::text::resolve_wrap(Some(before), &mut probe);
}
// With nothing to copy, no area type on those layers has a wrap shape.
for (l, id) in lines.iter().zip(&ids).filter(|_| units > 0) {
let Some(point) = &l.point else { continue };
let Some(NodeKind::Text(t)) = probe.node(*id).map(|n| &n.kind) else { continue };
if flowed && (t.wrap.is_empty() || first_mismatch(t, &l.matches, l.size).is_none()) {
continue;
}
if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) {
**t = point.clone();
}
}
}
let mut keep: Vec<NodeId> = roots.iter().copied().filter(|r| d.node(*r).is_some()).collect();
keep.extend(&ids);
sel.set(keep);
Ok(ids)
})?;
let d = &s.doc()?.doc;
let area =
|id: &NodeId| matches!(d.node(*id).map(|n| &n.kind), Some(NodeKind::Text(t)) if matches!(t.kind, vectorcraft_doc::TextKind::Area { .. }));
Ok(json!({
"ids": made.iter().map(|i| i.0).collect::<Vec<_>>(),
"texts": lines.iter().map(|l| l.text.clone()).collect::<Vec<_>>(),
"fonts": lines
.iter()
.map(|l| json!({"family": l.face.family, "style": l.face.style, "size": l.size(), "tracking": l.tracking}))
.zip(&made)
.map(|(l, id)| json!({
"family": l.face.family,
"style": l.face.style,
"size": l.size,
"tracking": l.tracking,
"leading": l.leading,
"area": area(id),
}))
.collect::<Vec<_>>(),
"unmatched": unmatched.iter().map(|i| i.0).collect::<Vec<_>>(),
"truncated": truncated,
+305
View File
@@ -568,6 +568,202 @@ fn assert_same_places(a: &TextObject, b: &TextObject) {
}
}
#[test]
fn several_lines_become_one_area_type_object() {
let mut s = session();
let text = "First line\nSecond one\nThird";
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 24}), &[]);
assert_eq!(r["texts"], json!([text]), "{r}");
assert_eq!(r["fonts"][0]["area"], json!(true), "{r}");
assert_eq!(r["fonts"][0]["leading"], json!(null), "Auto leading gives the lines' spacing: {r}");
let t = text_of(&s, r["ids"][0].as_u64().unwrap());
assert!(matches!(t.kind, vectorcraft_doc::TextKind::Area { .. }));
assert_eq!(t.plain_text(), text);
assert_same_places(&before, &t);
}
#[test]
fn lines_keep_their_leading_and_alignment() {
for justify in ["left", "center", "right"] {
let mut s = session();
let text = "Wide first line\nmid\nlast one";
let (before, r) = retyped(&mut s, json!({"x": 300, "y": 100, "text": text, "size": 20, "justify": justify}), &[json!({"leading": 31})]);
assert_eq!(r["texts"], json!([text]), "{justify}: {r}");
assert!(near(r["fonts"][0]["leading"].as_f64().unwrap(), 31.0, 1e-3), "{justify}: {r}");
assert_eq!(r["fonts"][0]["area"], json!(true), "{justify}: {r}");
let t = text_of(&s, r["ids"][0].as_u64().unwrap());
assert!(matches!(t.kind, vectorcraft_doc::TextKind::Area { .. }), "{justify}");
assert_eq!(t.para.justify, before.para.justify, "{justify}");
assert_same_places(&before, &t);
}
}
#[test]
fn a_long_block_near_auto_leading_keeps_its_own_leading() {
// 24.001 pt is Auto's 24 pt within a ten-thousandth of the size per line, but 250 lines
// move the last one a quarter of a point.
let mut s = session();
let text = vec!["ab"; 250].join("\n");
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 40, "text": text, "size": 20}), &[json!({"leading": 24.001})]);
assert_eq!(r["texts"], json!([text]), "{}", r["fonts"].as_array().map_or(0, |f| f.len()));
assert!(near(r["fonts"][0]["leading"].as_f64().unwrap(), 24.001, 1e-4), "{}", r["fonts"][0]);
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
}
#[test]
fn a_long_block_at_auto_leading_of_a_fractional_size_keeps_auto() {
// Auto leading of 20.002 pt is 24.0024 pt, finer than the thousandth of a point the leading
// between two lines is read to.
let mut s = session();
// Six hundred lines: read to a thousandth, each gap would be 0.0004 pt short, and the last
// line 0.24 pt off.
let text = vec!["ab"; 600].join("\n");
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 40, "text": text, "size": 20.002}), &[]);
assert_eq!(r["texts"], json!([text]), "{}", r["fonts"].as_array().map_or(0, |f| f.len()));
assert_eq!(r["fonts"][0]["leading"], json!(null), "{}", r["fonts"][0]);
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
}
#[test]
fn a_long_block_at_a_leading_finer_than_a_thousandth_keeps_it() {
// 23.9996 pt read to a thousandth is 24 pt, Auto for 20 pt type: over 600 lines the last one
// would be 0.24 pt off.
let mut s = session();
let text = vec!["ab"; 600].join("\n");
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 40, "text": text, "size": 20}), &[json!({"leading": 23.9996})]);
assert_eq!(r["texts"], json!([text]), "{}", r["fonts"].as_array().map_or(0, |f| f.len()));
assert!(near(r["fonts"][0]["leading"].as_f64().unwrap(), 23.9996, 1e-6), "{}", r["fonts"][0]);
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
}
#[test]
fn a_block_whose_first_gap_is_a_little_off_stays_one_object() {
// The second line moved up 0.004 pt: its gap read alone, carried over 100 lines, would put
// the last one 0.4 pt off.
let mut s = session();
let text = ["ab"; 100].join("\n");
let id = s.execute("text.create", &json!({"x": 40, "y": 40, "text": text, "size": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("text.setRangeStyle", &json!({"id": id, "leading": 24.004})).unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
let kids = children_of(&s, g);
s.execute("select.set", &json!({"ids": kids[2..4]})).unwrap();
s.execute("object.move", &json!({"dx": 0, "dy": -0.004})).unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!([text]), "{}", r["fonts"].as_array().map_or(0, |f| f.len()));
assert!(near(r["fonts"][0]["leading"].as_f64().unwrap(), 24.004, 1e-3), "{}", r["fonts"][0]);
}
#[test]
fn lines_whose_frame_would_pass_the_coordinate_limit_stay_point_type() {
let mut s = session();
let text = "Wide line\nWide";
let id = s.execute("text.create", &json!({"x": 3_999_000, "y": 100, "text": text, "size": 20})).unwrap()["id"].as_u64().unwrap();
let right = s.doc().unwrap().doc.node(NodeId(id)).unwrap().geometric_bounds().unwrap().x1;
s.execute("select.set", &json!({"ids": [id]})).unwrap();
// The ink ends 2 pt short of the limit; Convert To Area Type's slack would reach past it.
s.execute("object.move", &json!({"dx": vectorcraft_doc::MAX_COORD - 2.0 - right, "dy": 0})).unwrap();
let before = text_of(&s, id);
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!([text]), "{r}");
assert_eq!(r["fonts"][0]["area"], json!(false), "{r}");
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
}
#[test]
fn a_line_type_cannot_join_ends_the_block_there() {
// The fourth line keeps a fraction of a unit of tracking that the others do not: joined, it
// moves, so the lines before it stay one object and the lines after it join again.
let mut s = session();
let line = "M".repeat(40);
let text = [line.as_str(); 6].join("\n");
let start = 3 * 41;
let (before, r) =
retyped(&mut s, json!({"x": 20, "y": 40, "text": text, "size": 20}), &[json!({"start": start, "end": start + 40, "tracking": 0.6})]);
let texts: Vec<String> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect();
assert_eq!(texts.len(), 3, "{texts:?} {}", r["fonts"]);
assert_eq!(texts.join("\n"), text);
let places: Vec<kurbo::Point> = r["ids"].as_array().unwrap().iter().flat_map(|id| glyph_places(&text_of(&s, id.as_u64().unwrap()))).collect();
let want = glyph_places(&before);
assert_eq!(places.len(), want.len());
for (x, y) in places.iter().zip(&want) {
assert!(x.distance(*y) < 0.05, "{x:?} vs {y:?}");
}
}
/// The glyphs of the outline groups `others` moved to the end of group `g`, in order, and the
/// emptied groups removed.
fn into_one_group(s: &mut Session, g: u64, others: &[u64]) {
s.edit("test", |d, _| {
for o in others {
let kids: Vec<_> = d.node(NodeId(*o)).unwrap().children().unwrap().to_vec();
d.remove(NodeId(*o))?;
for k in kids {
let at = d.node(NodeId(g)).unwrap().children().unwrap().len();
d.insert(Some(NodeId(g)), at, (*k).clone())?;
}
}
Ok(())
})
.unwrap();
}
#[test]
fn lines_that_do_not_stack_as_a_paragraph_stay_apart() {
let mut s = session();
// Far apart, then lined up at nothing.
let a = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Top", "size": 20}));
let b = outlined(&mut s, json!({"x": 40, "y": 300, "text": "Far", "size": 20}));
let c = outlined(&mut s, json!({"x": 75, "y": 324, "text": "Askew", "size": 20}));
into_one_group(&mut s, a, &[b, c]);
s.execute("select.set", &json!({"ids": [a]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["Top", "Far", "Askew"]), "{r}");
assert!(r["fonts"].as_array().unwrap().iter().all(|f| f["area"] == json!(false)), "{r}");
}
#[test]
fn a_shape_between_lines_keeps_them_apart() {
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB\nCD", "size": 30}));
let rect = s.execute("shape.rectangle", &json!({"x": 30, "y": 60, "width": 80, "height": 80})).unwrap()["id"].as_u64().unwrap();
s.edit("test", |d, _| {
let n = d.node(NodeId(rect)).unwrap().clone();
d.remove(NodeId(rect))?;
d.insert(Some(NodeId(g)), 2, n)?;
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["AB", "CD"]), "the rectangle is painted between the lines: {r}");
}
#[test]
fn tracked_lines_keep_their_tracking_and_spaces() {
let mut s = session();
let text = "SPACED OUT\nTITLE";
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 24}), &[json!({"tracking": 400})]);
assert_eq!(r["texts"], json!([text]), "{r}");
assert_eq!(r["fonts"][0]["tracking"], json!(400.0), "{r}");
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
}
#[test]
fn a_short_line_takes_the_tracking_of_its_block() {
// One glyph has no gap to measure tracking by: it joins the tracked lines.
for text in ["TITLE\nB", "B\nTITLE", "TITLE\nB\nTITLE"] {
let mut s = session();
let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 24}), &[json!({"tracking": 400})]);
assert_eq!(r["texts"], json!([text]), "{r}");
assert_eq!(r["fonts"][0]["tracking"], json!(400.0), "{r}");
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
}
}
#[test]
fn unevenly_tracked_type_still_becomes_type() {
let mut s = session();
@@ -882,3 +1078,112 @@ fn overlapping_translucent_glyphs_are_not_tracked_into_one_object() {
assert_eq!(r["texts"], json!(["M", "M", "M", "M"]), "{r}");
assert!(r["fonts"].as_array().unwrap().iter().all(|f| f["tracking"] == json!(0.0)), "{r}");
}
#[test]
fn translucent_gradient_or_stroked_lines_stay_apart() {
for case in ["opacity", "blend", "gradient", "stroke"] {
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "One\nTwo", "size": 30}));
let kids = children_of(&s, g);
match case {
"gradient" => {
let gradient = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]});
s.execute("paint.setFill", &json!({"gradient": gradient, "ids": kids})).unwrap();
}
"stroke" => {
s.execute("paint.setStroke", &json!({"color": "#ff0000", "ids": kids})).unwrap();
}
_ => {
s.edit("test", |d, _| {
for k in &kids {
let n = d.node_mut(NodeId(*k)).unwrap();
if case == "opacity" {
n.opacity = 0.5;
} else {
n.blend = vectorcraft_color::BlendMode::Multiply;
}
}
Ok(())
})
.unwrap();
}
}
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["One", "Two"]), "{case}: one object would composite or fill the lines as one: {r}");
}
}
#[test]
fn lines_stay_point_type_past_the_text_wrap_limit_of_their_layer() {
// A Text Wrap object above the lines that moves no glyph, on their layer or on another one,
// with the limit lowered to nothing: only on their layer does it count.
for same_layer in [true, false] {
let mut s = session();
let text = "First line\nSecond one";
let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": text, "size": 24})).unwrap()["id"].as_u64().unwrap();
let before = text_of(&s, id);
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
if !same_layer {
// Area type below the Text Wrap object on the other layer: work there, none on this one.
s.execute("layer.new", &json!({})).unwrap();
let other = s.execute("text.create", &json!({"x": 450, "y": 300, "text": "Other", "size": 12})).unwrap()["id"].as_u64().unwrap();
s.execute("type.convertToAreaType", &json!({"ids": [other]})).unwrap();
}
let rect = s.execute("shape.rectangle", &json!({"x": 500, "y": 330, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("object.textWrap.make", &json!({"ids": [rect]})).unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
super::WRAP_LIMIT.with(|c| c.set(0));
let r = s.execute("type.retype", &json!({}));
super::WRAP_LIMIT.with(|c| c.set(super::MAX_WRAP_WORK));
let r = r.unwrap();
assert_eq!(r["texts"], json!([text]), "{r}");
assert_eq!(r["fonts"][0]["area"], json!(!same_layer), "{same_layer}: {r}");
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
}
}
#[test]
fn empty_subpaths_of_a_text_wrap_object_count_as_wrap_work() {
// Each one is copied into the wrap shapes of the area type below it.
let mut s = session();
let t = s.execute("text.create", &json!({"x": 40, "y": 100, "text": "Area", "size": 12})).unwrap()["id"].as_u64().unwrap();
s.execute("type.convertToAreaType", &json!({"ids": [t]})).unwrap();
let rect = s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("object.textWrap.make", &json!({"ids": [rect]})).unwrap();
let base = vectorcraft_doc::text::wrap_copy_units(&s.doc().unwrap().doc);
let file_work = vectorcraft_doc::text::wrap_work(&s.doc().unwrap().doc);
s.edit("test", |d, _| {
if let NodeKind::Path { path, .. } = &mut d.node_mut(NodeId(rect)).unwrap().kind {
for _ in 0..100 {
path.subpaths.push(vectorcraft_geom::SubPath::new(vec![], true));
}
}
Ok(())
})
.unwrap();
assert!(vectorcraft_doc::text::wrap_copy_units(&s.doc().unwrap().doc) >= base + 100);
// The count file import and the `.ai` editing copy use stays anchors and shapes only.
assert_eq!(vectorcraft_doc::text::wrap_work(&s.doc().unwrap().doc), file_work);
}
#[test]
fn lines_under_a_text_wrap_object_stay_point_type() {
let mut s = session();
let text = "First line\nSecond one";
let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": text, "size": 24})).unwrap()["id"].as_u64().unwrap();
let before = text_of(&s, id);
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
// Above the outlines, over the end of both lines: area type would wrap round it.
let rect = s.execute("shape.rectangle", &json!({"x": 90, "y": 70, "width": 60, "height": 50})).unwrap()["id"].as_u64().unwrap();
s.execute("object.textWrap.make", &json!({"ids": [rect]})).unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!([text]), "{r}");
assert_eq!(r["fonts"][0]["area"], json!(false), "{r}");
let t = text_of(&s, r["ids"][0].as_u64().unwrap());
assert!(matches!(t.kind, vectorcraft_doc::TextKind::Point));
assert_same_places(&before, &t);
}
+28 -22
View File
@@ -634,34 +634,40 @@ fn to_area(s: &mut Session, p: &Value) -> Result<Value> {
if !matches!(t.kind, TextKind::Point) {
continue;
}
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
// The frame is worked out in line space, where the lines are; vertical type turns it
// into text space with the lines.
let text_bounds = if lay.bounds.area() > 0.0 { lay.bounds } else { t.estimate_bounds() };
let mut b = lay.line_xf.inverse().transform_rect_bbox(text_bounds);
// Across, the frame spans the lines as they are aligned: from their starts to their ends
// without the tracking after their last characters (`LineInfo::trailing`), not to the
// ink, which tracking can pull past an advance. Area type aligns them alike.
let (x0, x1) = lay.lines.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, z), l| (a.min(l.x0), z.max(l.x1 - l.trailing)));
if x0.is_finite() && x1.is_finite() && x0 <= x1 {
(b.x0, b.x1) = (x0, x1);
}
// Line breaking counts that tracking: the slack holds the most of it.
let trailing = lay.lines.iter().map(|l| l.trailing).filter(|t| t.is_finite()).fold(0.0, f64::max);
let size = t.first_style().size;
// A little slack on the right so the text doesn't rewrap.
let top = lay.lines.first().map(|l| l.baseline - l.ascent).unwrap_or(b.y0).min(b.y0);
let slack = size * 0.5 + trailing;
let (sl, sr) = slack_sides(t.para_at(0).justify, lay.lines.first().is_some_and(|l| l.rtl), slack);
let frame = lay.line_xf.transform_rect_bbox(Rect::new(b.x0 - sl, top, b.x1 + sr, b.y1.max(top + 1.0)));
t.kind = TextKind::Area { frame: shapes::rectangle(frame) };
refresh_bounds(t);
point_to_area(t);
}
Ok(())
})?;
Ok(ids_json(&ids))
}
/// Point type `t` turned into area type in a frame around its lines, with a little slack where its
/// alignment leaves room, so the text stays where it is and does not rewrap.
pub(super) fn point_to_area(t: &mut TextObject) {
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
// The frame is worked out in line space, where the lines are; vertical type turns it
// into text space with the lines.
let text_bounds = if lay.bounds.area() > 0.0 { lay.bounds } else { t.estimate_bounds() };
let mut b = lay.line_xf.inverse().transform_rect_bbox(text_bounds);
// Across, the frame spans the lines as they are aligned: from their starts to their ends
// without the tracking after their last characters (`LineInfo::trailing`), not to the
// ink, which tracking can pull past an advance. Area type aligns them alike.
let (x0, x1) = lay.lines.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, z), l| (a.min(l.x0), z.max(l.x1 - l.trailing)));
if x0.is_finite() && x1.is_finite() && x0 <= x1 {
(b.x0, b.x1) = (x0, x1);
}
// Line breaking counts that tracking: the slack holds the most of it.
let trailing = lay.lines.iter().map(|l| l.trailing).filter(|t| t.is_finite()).fold(0.0, f64::max);
let size = t.first_style().size;
// A little slack on the right so the text doesn't rewrap.
let top = lay.lines.first().map(|l| l.baseline - l.ascent).unwrap_or(b.y0).min(b.y0);
let slack = size * 0.5 + trailing;
let (sl, sr) = slack_sides(t.para_at(0).justify, lay.lines.first().is_some_and(|l| l.rtl), slack);
let frame = lay.line_xf.transform_rect_bbox(Rect::new(b.x0 - sl, top, b.x1 + sr, b.y1.max(top + 1.0)));
t.kind = TextKind::Area { frame: shapes::rectangle(frame) };
refresh_bounds(t);
}
/// How `slack` added to point type's lines in a frame is shared before and after them: where the
/// alignment leaves room, so the text doesn't move or rewrap.
fn slack_sides(justify: Justify, rtl: bool, slack: f64) -> (f64, f64) {