From cdcaab93016e9d749101c803e5afc8be317ba83b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 07:53:05 -0800 Subject: [PATCH] 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). --- crates/doc/src/text.rs | 2 +- crates/doc/src/text/wrap.rs | 44 ++- crates/engine/src/cmd/retype.rs | 370 ++++++++++++++++++++++++-- crates/engine/src/cmd/retype_tests.rs | 305 +++++++++++++++++++++ crates/engine/src/cmd/typemenu.rs | 50 ++-- docs/mcp.md | 20 ++ docs/roadmap.md | 2 +- docs/target-app-parity.md | 4 + docs/type-parity.md | 2 +- 9 files changed, 749 insertions(+), 50 deletions(-) diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index c6a9860189..107ac1dab9 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -38,7 +38,7 @@ pub use tabs_lists::{ Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, MAX_LIST_START, NumberStyle, ParaList, TabAlign, TabStop, }; -pub use wrap::{resolve_wrap, wrap_outline, wrap_sources, wrap_work}; +pub use wrap::{resolve_wrap, wrap_copy_units, wrap_outline, wrap_sources, wrap_work}; /// A text object. `runs` split into paragraphs at `\n`. /// diff --git a/crates/doc/src/text/wrap.rs b/crates/doc/src/text/wrap.rs index 15a0fbbd40..c55a973be0 100644 --- a/crates/doc/src/text/wrap.rs +++ b/crates/doc/src/text/wrap.rs @@ -66,10 +66,45 @@ fn collect<'a>(n: &'a Node, out: &mut Vec>) { } } +/// The anchors and subpaths [`outline`] would collect for wrap object `n`, counted without copying +/// them. +fn outline_size(n: &Node) -> (usize, usize) { + match &n.kind { + NodeKind::Path { path, guide: false, .. } => path + .subpaths + .iter() + .filter(|sp| sp.closed || sp.anchors.len() > 2) + .fold((0usize, 0usize), |(a, s), sp| (a.saturating_add(sp.anchors.len()), s.saturating_add(1))), + NodeKind::Compound { children, .. } | NodeKind::Group { children, clip: false } => children + .iter() + .filter(|c| c.visible) + .map(|c| outline_size(c)) + .fold((0, 0), |(a, s), (ca, cs)| (a.saturating_add(ca), s.saturating_add(cs))), + NodeKind::Group { children, clip: true } => children.first().map_or((0, 0), |c| outline_size(c)), + // A rectangle of the object's bounds. + _ => { + if n.geometric_bounds().is_some() { + (4, 1) + } else { + (0, 0) + } + } + } +} + /// How much [`resolve_wrap`] would copy into the wrap shapes of every area text object in `doc`: /// each wrap object's outline (its anchors, plus one for the shape) once for each area text object /// below it in its layer. pub fn wrap_work(doc: &Document) -> usize { + work(doc, false) +} + +/// [`wrap_work`], with one more for each subpath of each outline, empty ones included. +pub fn wrap_copy_units(doc: &Document) -> usize { + work(doc, true) +} + +fn work(doc: &Document, count_subpaths: bool) -> usize { let mut total = 0usize; for layer in &doc.layers { let mut items = vec![]; @@ -78,11 +113,10 @@ pub fn wrap_work(doc: &Document) -> usize { for it in items.iter().rev() { match it { Item::Wrap(n) => { - let mut pd = PathData::default(); - outline(n, &mut pd); - if !pd.is_empty() { - let anchors: usize = pd.subpaths.iter().map(|sp| sp.anchors.len()).sum(); - above = above.saturating_add(anchors.saturating_add(1)); + let (anchors, subpaths) = outline_size(n); + if anchors > 0 { + let subpaths = if count_subpaths { subpaths } else { 0 }; + above = above.saturating_add(anchors).saturating_add(subpaths).saturating_add(1); } } Item::Text(_) => total = total.saturating_add(above), diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index 6066e47f33..45ae073129 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -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 { "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 { - 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 { + 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, system_layout: bool, unmatched: &mut Vec) 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 = 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, + /// The glyphs the type must draw, in order. + matches: Vec, + pieces: Vec, + text: String, + face: Arc, + size: f64, + tracking: f64, + /// The leading set on the type: None for Auto or a single line. + leading: Option, + 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, + /// 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, +} + +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 { + 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 { + let single = |lines: &[Line]| lines.iter().map(|l| Made::line(l, system_layout)).collect::>(); + 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::>().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 = 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, follows: impl Fn(NodeId, NodeId) -> bool, system_layout: bool, budget: &mut usize) -> Vec { + let mut out = vec![]; + let mut block: Option = 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(&mut self, l: &Line, ranges: [(usize, usize); N]); @@ -855,20 +1128,29 @@ fn retype(s: &mut Session, p: &Value) -> Result { !lone }); } - (lines, unmatched, truncated) + let at: std::collections::HashMap = 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 { } } } + // 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 = 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::>(), "texts": lines.iter().map(|l| l.text.clone()).collect::>(), "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::>(), "unmatched": unmatched.iter().map(|i| i.0).collect::>(), "truncated": truncated, diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index b89d8e0d78..ec98c914c0 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -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 = 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 = 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); +} diff --git a/crates/engine/src/cmd/typemenu.rs b/crates/engine/src/cmd/typemenu.rs index e9c316157f..b66a50bc19 100644 --- a/crates/engine/src/cmd/typemenu.rs +++ b/crates/engine/src/cmd/typemenu.rs @@ -634,34 +634,40 @@ fn to_area(s: &mut Session, p: &Value) -> Result { 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) { diff --git a/docs/mcp.md b/docs/mcp.md index f0f035a261..b6295de9d9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -12177,6 +12177,26 @@ tracking their own gaps give. These rules are VectorCraft's own. Each entry of t {"name":"run_command","arguments":{"command":"type.retype","params":{}}} ``` +## Retype several lines + +`type.retype` joins 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 tracking of the others), into one type object when each +line's baseline is the same distance below the one before (between 0.25 and 3 times the size) and the lines line up at their starts, ends or centers. The object is area type with Convert To Area +Type's frame, its lines separated by line breaks, with left, right or center alignment, checked in that order. Its +leading is Auto when Auto puts the last baseline in place, else the mean distance between the baselines, to a +thousandth of a point when that still puts the last baseline in place. Lines with an opacity below 100%, a blend mode +other than Normal, a gradient or pattern fill, or a stroke stay one object per line. These rules are VectorCraft's own. + +Every joined object is laid out and compared with the outlines. When area type would not draw each glyph where its +outline was, including after Text Wrap objects above it reflow it, or when its frame would reach past the canvas's +coordinate limit, the lines become one multi-line point type object (one object per line when its bounds would reach +past that limit). When that also moves a glyph, the lines before that glyph's line stay one object, and the lines +from that line on are joined again from it. When the Text Wrap objects on the layers Retype changes would copy more +than 2,000,000 units into the wrap shapes of their area type (one for each anchor, subpath and shape, for each area +type object below them), Retype does not check the wrap and the lines become multi-line point type. Each entry of +the result's `texts` list holds an object's lines joined by `\n`, and each entry of its `fonts` list also has +`leading` (points; null for Auto leading or a single line) and `area`. + ## Retype panel `type.retypeFonts {count?}` lists the fonts whose glyphs match the selected outlined text. It compares each selected path diff --git a/docs/roadmap.md b/docs/roadmap.md index 488755ffef..8b9e0cfa0d 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -181,7 +181,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths (#8128; estimates unchanged); Production Preflight checks fonts, overflow, links and image resolution with clickable findings and automatic rechecking (VectorCraft addition; estimates unchanged); PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one, as the file composites them; estimates unchanged); PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543; estimates unchanged); PDF import: type filled and stroked after a page of type filled only (more than 64 lines) comes in as one filled and stroked type object again, with or without a path between, and a `TJ` over more lines than are kept with a glyph kept as an outline still stays a filled object and a stroked one for each part (#8549 follow-up; estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; estimates unchanged); Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); | 3–6 (existing scope; Affinity export unestimated) | | M5 | Performance | 🟡 background render + caches + MT done; text thread overlays index repeated selection lookups, keeping the first lookup and singleton selections direct (#6543); `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; dirty-region rendering, GPU backend spike pending | 15–25 | | M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (live compound shapes: Make, Alt-click a Shape Mode, member modes, Release, Expand (#4522); single-result Pathfinder names and SVG IDs retained (#1293); Divide open-cutting-path geometry, appearance and history verified (#1307; existing segment cap remains); Simplify preview/counts and rewritten-path component selection verified (#1272; the slider opens at the Auto-Simplify level; a Direct Selection part of a path simplifies on its own); Compound appearance and member fill-rule edits verified (#1197); Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open); Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog | 3–6 | -| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, the custom dictionary and Ignore All commands, Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, Spelling › Auto Spell Check in the context menu of type, the Edit Custom Dictionary dialog, and the modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `Cmd+I`, `ui.checkSpelling`, #4936); 🟡 Retype phase 1: `type.retype` turns outlined text that exactly matches an available font back into point text (#4934), keeping even spacing as tracking; Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs (feature-valued alternates and unencoded glyphs applied in one Undo step while keeping Arabic joining, #5514), OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, vertical type pending | 45–60 | +| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, the custom dictionary and Ignore All commands, Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, Spelling › Auto Spell Check in the context menu of type, the Edit Custom Dictionary dialog, and the modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `Cmd+I`, `ui.checkSpelling`, #4936); 🟡 Retype phase 1: `type.retype` turns outlined text that exactly matches an available font back into point text (#4934), keeping even spacing as tracking and making stacked, aligned lines one area type object; Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs (feature-valued alternates and unencoded glyphs applied in one Undo step while keeping Arabic joining, #5514), OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, vertical type pending | 45–60 | | M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Anchor Point spine conversion/handle editing and selection priority (#2544), with #2425 Shift reshape preserved; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box | 2–4 | | M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, the custom dictionary and Ignore All commands, Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, Spelling › Auto Spell Check in the context menu of type, the Edit Custom Dictionary dialog, and the modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `Cmd+I`, `ui.checkSpelling`, #4936); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs (feature-valued alternates and unencoded glyphs applied in one Undo step while keeping Arabic joining, #5514), OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, vertical type pending | 45–60 | | M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Anchor Point spine conversion/handle editing and selection priority (#2544), with #2425 Shift reshape preserved; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box; #5179 curved-spine redraw bounds include rotated keys and steps (two focused CPU regressions) | 2–4 | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f94e56c853..f1e15798ca 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3021,6 +3021,10 @@ The identify-fonts page has the Retype panel list ten matching fonts ordered by #4934 asks Retype to match the tracking of outlined text. `type.retype` now sets a line whose glyphs most gaps space evenly apart with that spacing as tracking, keeps gaps one space wide as word spaces when untracked type draws them, and sets negative tracking only on opaque, Normal lines with a solid fill or none and no stroke. These rules are VectorCraft's own. Each line is laid out and compared with the outlines before it is kept; a line its tracked type would move a glyph of is checked again untracked, and the glyphs after a split take the tracking their own gaps give. Tested by round trips through Create Outlines (a tracked line with a word space; uneven, tight and fractional tracking; kerned pairs in tight tracking; spaced letters that need no tracking; translucent overlapping glyphs) and by the measure's layout budget, in `crates/engine/src/cmd/retype_tests.rs`. +## Retype several lines (2026-11-19) + +#4934 asks for area text when outlined text has several lines, with its line spacing. `type.retype` now turns lines that follow each other, stack at one leading and line up at their starts, ends or centers into one area type object with that leading and left, right or center alignment. These rules are VectorCraft's own. Each object is laid out and compared with the outlines before it is kept; when area type would move a glyph, the lines become multi-line point type, and when that also would, the block ends at the line of that glyph and the lines after it join again. Tested by round trips through Create Outlines (three lines with Auto leading; set leading with left, center and right alignment; long blocks at leadings finer than a thousandth of a point; a line tracked apart from the others; tracked lines with word spaces; lines far apart or askew; a shape painted between two lines; translucent, blended, gradient and stroked lines; lines under a Text Wrap object) in `crates/engine/src/cmd/retype_tests.rs`. + ## Control bar: Paragraph section while type is selected (2026-11-06) With type selected, the Control bar shows a Paragraph: link and the Align left, Align center and Align right buttons after its Character controls, as the public documentation has the Control panel format paragraphs while the Type tool is in use, with a way to the Paragraph panel ([Paragraph panel overview](https://helpx.adobe.com/illustrator/using/formatting-paragraphs.html)), and its alignment buttons align text as the Paragraph panel's do ([Align text](https://helpx.adobe.com/illustrator/using/align-text.html)). A button aligns the selected type (`text.setStyle {justify}`, one undo step) and the shared alignment shows selected; the link opens the Paragraph panel in a popover under it, as Character: opens the Character panel. Keeping to the three alignments that don't justify is our choice, for the bar's room; the popover has all seven. Short of room the bar leaves controls out from its right end: the inline X/Y/W/H fields, the Distribute and Align buttons, area type's vertical alignment, then these buttons and last the link, keeping room for the Transform link; on a 1536 pt bar with one point type object, the buttons show (pinned by a headless test, #5372). diff --git a/docs/type-parity.md b/docs/type-parity.md index 5e3a648745..111ee5d838 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -56,7 +56,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Alt + numeric-keypad codes while typing (Windows: `Alt+0176` → °) | partial | #5108: on Windows the character Windows posts when Alt comes up after keypad digits is typed at the caret like any other, in the typing's undo step, and the keypad digits typed with Alt run no shortcut. With NumLock off the keypad keys (Insert, End, arrows, Clear, Home, Page Up/Down without the extended-key flag) count as digits too and don't move the caret (`windows_alt_codes` unit tests; neither NumLock on nor off has been tried on a Windows machine yet). `type.insert {code}` (Windows Alt+0 code, Windows-1252 for 128–159) and `{unicode}` (hex code point) insert a character by its code (`menucmds::insert_a_character_by_its_code`). macOS and Linux have no such system convention and egui reports a keypad digit as the top-row digit, so there it does nothing; a floating panel window doesn't receive the character | | Caret: the arrows and Delete step over whole clusters (Thai consonant with its marks, combining accents, emoji); Backspace removes one character | done | in text with right-to-left characters the arrows move in visual order and stop on both sides of a character drawn with no width, such as a zero width non-joiner | | Touch Type tool | done | moves, scales and rotates one character through its kerning, baseline shift, scales and rotation (`text.touchType`); a character with a preceding logical character on the same line can move along the line in either reading direction; the first logical character moves only up and down. Positive `dx` follows reading order. These direction rules are VectorCraft's choices. | -| Retype (identify fonts in outlines/images) | partial | Phase 1 (#4934): Type › Retype (`type.retype`) turns outlined glyphs back into point text when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. Evenly spaced glyphs keep their spacing as tracking (gaps one space wide stay word spaces when type draws them; VectorCraft's own rules, checked against the layout). Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Missing (phase 2): near or fuzzy matches (another version of the font, simplified outlines, glyphs merged into one path), opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, installed fonts not yet loaded, area text for several lines, text in images. Public behaviour: [identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html) | +| Retype (identify fonts in outlines/images) | partial | Phase 1 (#4934): Type › Retype (`type.retype`) turns outlined glyphs back into type when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line unless lines stack into one object as described below, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. Evenly spaced glyphs keep their spacing as tracking (gaps one space wide stay word spaces when type draws them), and lines stacked at one leading and lined up at their starts, ends or centers become one area type object with that leading and alignment (VectorCraft's own rules, checked against the layout). Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Missing (phase 2): near or fuzzy matches (another version of the font, simplified outlines, glyphs merged into one path), opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, installed fonts not yet loaded, text in images. Public behaviour: [identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html) | | Snap to Glyph | done | View › Snap to Glyph (`view.snapToGlyph`): with Smart Guides on, new point type and drawing tools snap to live-text baselines and glyph bounds, the corners of each glyph's box included, turning with rotated type (#5112; `guides::tests::a_drawn_point_lands_on_a_corner_of_a_glyphs_bounds`, `Targets::for_drawing`, `tools::text_tests::snap_to_glyph_lines_up_new_point_type_with_a_baseline`). With Alignment Guides on as well, and Snap to Grid and Snap to Pixel off, both ends of a Measure or Measure & Inspect drag snap to those guides and show them during the drag (`Targets::for_measure`, `xform::measure::tests::its_ends_land_on_glyph_guides_with_snap_to_glyph`). That the Measure tools take the guides is VectorCraft's choice; they leave out Anchor Point, which [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/snap-to-glyph.html) limits to the Pen tool and objects moved with the Selection tool. Character panel menu › Show Snap to Glyph Options: Baseline, x-height, Glyph Bounds, Proximity Guides, Angular Guides and Anchor Point each turn their guides on or off (`view.snapToGlyph.options`, all on by default; #4232), after a Snap to Glyph checkbox for View › Snap to Glyph; showing them scrolls the panel to them (#5273) | | Thai, Lao, Khmer, Myanmar: shaping (marks, reordering), lines broken between words, word-by-word caret and double-click | done | words found by ICU4X's line segmenter: dictionaries on the desktop, LSTM models on the web | | Middle Eastern: bidirectional layout, Paragraph Direction | done | PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import still needs ActualText support (#6165); separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. |