From 24a37f8ba33f1850cc7272eae15561d14cc116f1 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Wed, 18 Nov 2026 02:20:06 +0530 Subject: [PATCH 01/15] =?UTF-8?q?M7/G4:=20Type=20=E2=80=BA=20Retype,=20pha?= =?UTF-8?q?se=201=20(#4934)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit type.retype turns selected outlined text back into live point text when each glyph 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. Matched glyphs map back to characters through the cmap and become point text in that font and size at the same baseline and turn, one object per line, with the first glyph's fill and stroke, in one undo step. Shapes that match no font stay and are reported. Matching (vectorcraft_text::retype) samples each contour at equal steps of arc length and fits a similarity transform; it is bounded (faces, glyphs, path elements, contours) and panic-free. Near matches, the ranked font list, installed fonts not yet loaded and images are phase 2. --- crates/engine/src/cmd.rs | 2 + crates/engine/src/cmd/retype.rs | 293 ++++++++++++++++++++ crates/engine/src/cmd/retype_tests.rs | 120 ++++++++ crates/text/src/fontdb/lookup.rs | 6 + crates/text/src/lib.rs | 1 + crates/text/src/retype.rs | 384 ++++++++++++++++++++++++++ docs/gaps.md | 5 +- docs/roadmap.md | 5 +- docs/target-app-parity.md | 19 +- docs/type-parity.md | 5 +- 10 files changed, 827 insertions(+), 13 deletions(-) create mode 100644 crates/engine/src/cmd/retype.rs create mode 100644 crates/engine/src/cmd/retype_tests.rs create mode 100644 crates/text/src/retype.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index c4a86dd3a5..4fec3f90bd 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -105,6 +105,7 @@ pub mod textstyles; pub(crate) mod textwrap; pub(crate) mod threads; pub(crate) mod typecmd; +mod retype; mod typemenu; mod variablecmds; pub(crate) mod views; @@ -321,6 +322,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(pathops::specs()); v.extend(compoundshape::specs()); v.extend(typecmd::specs()); + v.extend(retype::specs()); v.extend(menucmds::specs()); v.extend(live::specs()); v.extend(colorcmds::specs()); diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs new file mode 100644 index 0000000000..a5f3b98bde --- /dev/null +++ b/crates/engine/src/cmd/retype.rs @@ -0,0 +1,293 @@ +//! Type › Retype (#4934), phase 1: outlined text whose glyph shapes are glyphs of a font the app +//! has becomes live point text again, in that font and size, at the same baseline. +//! +//! Behaviour follows the public description of Illustrator's Retype +//! (, +//! ): +//! select outlined text and Retype finds the fonts that match it, from the fonts on the device among +//! others, for use as live text. Illustrator ranks candidate fonts in a panel; this phase is local +//! and exact instead, and sets the text itself, as #4934 asks. Each selected glyph shape (a path or compound +//! path, inside groups too) is compared with the glyphs of the candidate fonts +//! ([`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. 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::sync::Arc; + +use kurbo::{BezPath, Point, Vec2}; +use serde_json::{Value, json}; +use vectorcraft_doc::{Appearance, CharStyle, Document, Node, NodeId, NodeKind, TextObject}; +use vectorcraft_text::FontDb; +use vectorcraft_text::retype::{GlyphMatch, RetypeIndex}; + +use super::edit::selected_roots; +use super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_selected_path}; + +/// At most this many shapes are compared. +const MAX_PIECES: usize = 2048; +/// Groups deeper than this are not looked into. +const MAX_DEPTH: usize = 16; +/// Extra families named by `fonts`. +const MAX_FONT_PARAMS: usize = 32; + +pub fn specs() -> Vec { + vec![cmd!( + "type.retype", + "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 and stroke, in one undo step; shapes that match no font stay as they are → {ids (the new type), texts, fonts: [{family, style, size}], unmatched: [id…]}; an error when no shape matches", + has_selected_path, + retype + )] +} + +/// A shape to match: a path or compound path, in document space. +struct Piece { + id: NodeId, + path: BezPath, + appearance: Appearance, +} + +fn collect(n: &Node, depth: usize, out: &mut Vec) { + if out.len() >= MAX_PIECES || depth > MAX_DEPTH { + return; + } + match &n.kind { + NodeKind::Group { children, clip: false } => { + for c in children { + collect(c, depth + 1, out); + } + } + NodeKind::Path { path, clipping: false, guide: false, .. } => { + out.push(Piece { id: n.id, path: path.to_bezpath(), appearance: (*n.appearance).clone() }) + } + NodeKind::Compound { children, .. } => { + let mut path = BezPath::new(); + for c in children { + if let NodeKind::Path { path: p, .. } = &c.kind { + path.extend(p.to_bezpath()); + } + } + out.push(Piece { id: n.id, path, appearance: (*n.appearance).clone() }); + } + _ => {} + } +} + +/// The faces to match against: the families in `fonts`, the document's fonts, then every loaded face. +fn candidate_faces(db: &FontDb, d: &Document, fonts: &[String]) -> Vec> { + let mut families: Vec = fonts.iter().take(MAX_FONT_PARAMS).cloned().collect(); + d.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + for r in &t.runs { + if !families.contains(&r.style.font_family) && families.len() < vectorcraft_text::retype::MAX_FACES { + families.push(r.style.font_family.clone()); + } + } + } + }); + let mut faces = vec![]; + for f in &families { + for style in db.styles(f) { + if let Some(face) = db.face(f, &style) { + faces.push(face); + } + } + } + faces.extend(db.loaded_faces()); + faces +} + +/// One line of retyped glyphs. +struct Line { + pieces: Vec, + text: String, + face: Arc, + scale: f64, + angle: f64, + origin: Point, + end: Point, + appearance: Appearance, +} + +impl Line { + fn dir(&self) -> Vec2 { + Vec2::new(self.angle.cos(), self.angle.sin()) + } + + /// Does glyph `m` continue this line (same font, size and turn, on its baseline, after its end)? + fn continues(&self, m: &GlyphMatch) -> bool { + let size = self.scale * self.face.units_per_em(); + let d = m.origin - self.origin; + let dir = self.dir(); + let across = d.cross(dir).abs(); + m.face.id() == self.face.id() + && (m.scale - self.scale).abs() <= self.scale * 0.005 + && (m.angle - self.angle).abs() < 1e-3 + && across < size * 0.05 + && (m.origin - self.end).dot(dir) > -size * 0.25 + } + + fn push(&mut self, id: NodeId, m: &GlyphMatch) { + // A gap wider than half a space before the glyph is spaces the outlines left no shape for. + let dir = self.dir(); + let gap = (m.origin - self.end).dot(dir); + let space = space_advance(&self.face) * self.scale; + if space > 0.0 && gap > space * 0.5 { + let n = ((gap / space).round() as usize).clamp(1, 64); + self.text.extend(std::iter::repeat_n(' ', n)); + } + self.text.push(m.ch); + self.pieces.push(id); + self.end = m.origin + dir * (m.face.advance(m.gid) * m.scale); + } +} + +fn space_advance(face: &vectorcraft_text::FontFace) -> f64 { + face.mapped_chars().iter().find(|(c, _)| *c == ' ').map(|(_, g)| face.advance(*g)).unwrap_or(0.0) +} + +fn new_line(id: NodeId, m: &GlyphMatch, appearance: &Appearance) -> Line { + let dir = Vec2::new(m.angle.cos(), m.angle.sin()); + Line { + pieces: vec![id], + text: m.ch.to_string(), + face: m.face.clone(), + scale: m.scale, + angle: m.angle, + origin: m.origin, + end: m.origin + dir * (m.face.advance(m.gid) * m.scale), + appearance: appearance.clone(), + } +} + +fn retype(s: &mut Session, p: &Value) -> Result { + const C: &str = "type.retype"; + let fonts: Vec = match p.get("fonts") { + None | Some(Value::Null) => vec![], + Some(Value::Array(a)) => { + a.iter().map(|v| v.as_str().map(str::to_owned).ok_or_else(|| bad(C, "fonts must be a list of family names"))).collect::>()? + } + Some(_) => return Err(bad(C, "fonts must be a list of family names")), + }; + let roots = selected_roots(s)?; + let db = FontDb::global(); + let (lines, unmatched) = { + let d = &s.doc()?.doc; + let mut pieces = vec![]; + for r in &roots { + if let Some(n) = d.node(*r) { + collect(n, 0, &mut pieces); + } + } + if pieces.is_empty() { + return Err(EngineError::Other("Retype: select outlined text (paths or compound paths)".into())); + } + let index = RetypeIndex::build(db, candidate_faces(db, d, &fonts)); + let found: Vec> = pieces.iter().map(|pc| index.matches(&pc.path)).collect(); + // The face most shapes match, so a glyph several fonts share is set in the same font as + // the glyphs around it. + let mut votes: Vec<(u32, usize)> = vec![]; + for m in found.iter().flatten() { + match votes.iter_mut().find(|(f, _)| *f == m.face.id()) { + Some(v) => v.1 += 1, + None => votes.push((m.face.id(), 1)), + } + } + let rank = |face: u32| votes.iter().find(|(f, _)| *f == face).map_or(0, |v| v.1); + let mut lines: Vec = vec![]; + let mut unmatched = vec![]; + for (pc, ms) in pieces.iter().zip(&found) { + // Earlier matches win ties: they are the closer fits. + let best = ms.iter().enumerate().max_by_key(|(i, m)| (rank(m.face.id()), std::cmp::Reverse(*i))).map(|(_, m)| m); + let Some(m) = best else { + unmatched.push(pc.id); + continue; + }; + match lines.last_mut() { + Some(l) if l.continues(m) => l.push(pc.id, m), + _ => lines.push(new_line(pc.id, m, &pc.appearance)), + } + } + (lines, unmatched) + }; + if lines.is_empty() { + return Err(EngineError::Other(format!("Retype: no selected shape matches a glyph of an available font ({} checked)", unmatched.len()))); + } + let system_layout = s.doc()?.doc.setup.system_layout; + let made = s.edit("Retype", |d, sel| { + 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 style = CharStyle { + font_family: l.face.family.clone(), + font_style: l.face.style.clone(), + size: l.scale * l.face.units_per_em(), + fill: l.appearance.fill_paint(), + stroke: l.appearance.stroke_paint(), + stroke_width: l.appearance.stroke_width(), + ..Default::default() + }; + let mut t = TextObject::point(l.origin, &l.text, style); + if l.angle != 0.0 { + t.xf *= kurbo::Affine::rotate(l.angle); + } + t.para = super::create::new_type_para(); + t.system_layout = system_layout; + super::typecmd::refresh_bounds(&mut t); + let id = d.alloc_id(); + d.insert(par, idx, Node::new(id, NodeKind::Text(Box::new(t))))?; + for pc in &l.pieces { + if let Some((Some(parent), _, _)) = d.position(*pc) { + emptied.push(parent); + } + d.remove(*pc)?; + } + ids.push(id); + } + // A group left holding only the new type (Create Outlines' group) gives way to it, unless + // the group has transparency, effects, a mask or a name of its own, which then keep + // applying to the type inside it. A group left empty goes. + emptied.sort_unstable(); + emptied.dedup(); + for g in emptied { + let Some(n) = d.node(g) else { continue }; + let NodeKind::Group { children, clip: false } = &n.kind else { continue }; + let plain = n.opacity == 1.0 + && n.blend == vectorcraft_color::BlendMode::Normal + && *n.appearance == Appearance::default() + && n.name.is_none() + && n.extras().mask.is_none(); + let only_type = children.iter().all(|c| ids.contains(&c.id)); + if children.is_empty() { + d.remove(g)?; + } else if plain && only_type { + let kids: Vec> = children.clone(); + let (par, idx, _) = d.position(g).ok_or(EngineError::NoNode(g))?; + d.remove(g)?; + for (i, k) in kids.into_iter().enumerate() { + d.insert(par, idx + i, (*k).clone())?; + } + } + } + let mut keep: Vec = roots.iter().copied().filter(|r| d.node(*r).is_some()).collect(); + keep.extend(&ids); + sel.set(keep); + Ok(ids) + })?; + 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.scale * l.face.units_per_em()})).collect::>(), + "unmatched": unmatched.iter().map(|i| i.0).collect::>(), + })) +} + +#[cfg(test)] +#[path = "retype_tests.rs"] +mod tests; diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs new file mode 100644 index 0000000000..6ed12289f4 --- /dev/null +++ b/crates/engine/src/cmd/retype_tests.rs @@ -0,0 +1,120 @@ +use serde_json::json; +use vectorcraft_doc::{NodeId, NodeKind, TextObject}; + +use crate::Session; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + s +} + +/// Point text, outlined: the id of the outlines' group. +fn outlined(s: &mut Session, p: serde_json::Value) -> u64 { + let id = s.execute("text.create", &p).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap() +} + +fn text_of(s: &Session, id: u64) -> TextObject { + let NodeKind::Text(t) = &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind else { panic!("text object") }; + (**t).clone() +} + +fn near(a: f64, b: f64, tol: f64) -> bool { + (a - b).abs() <= tol +} + +#[test] +fn outlined_point_text_retypes_to_the_same_text_font_size_and_place() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Retype me, 42!", "size": 36, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["Retype me, 42!"]), "{r}"); + assert_eq!(r["unmatched"], json!([])); + let id = r["ids"][0].as_u64().unwrap(); + let t = text_of(&s, id); + assert_eq!(t.plain_text(), "Retype me, 42!"); + let st = t.first_style(); + assert_eq!((st.font_family.as_str(), st.font_style.as_str()), ("Source Sans 3", "Regular")); + assert!(near(st.size, 36.0, 0.01), "size {}", st.size); + let o = t.xf.translation(); + assert!(near(o.x, 40.0, 0.01) && near(o.y, 100.0, 0.01), "baseline start {o:?}"); + // The outlines are gone, in one undo step that brings them back. + let d = &s.doc().unwrap().doc; + assert!(d.node(NodeId(g)).is_none(), "the emptied group goes"); + s.execute("edit.undo", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.node(NodeId(g)).is_some() && d.node(NodeId(id)).is_none()); +} + +#[test] +fn turned_bold_and_serif_type_keeps_its_font_and_angle() { + let mut s = session(); + let a = outlined(&mut s, json!({"x": 100, "y": 200, "text": "Bold", "size": 24, "font": "Source Sans 3", "style": "Bold", "rotation": 30})); + let b = outlined(&mut s, json!({"x": 300, "y": 80, "text": "Serif", "size": 18, "font": "Source Serif 4", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["Bold", "Serif"]), "{r}"); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + let bold = text_of(&s, ids[0]); + assert_eq!(bold.first_style().font_style, "Bold"); + assert!(near(bold.first_style().size, 24.0, 0.01)); + // text.create turns as kurbo does: compare the turn the new type has with the old one's. + let turned = kurbo::Affine::translate((100.0, 200.0)) * vectorcraft_geom::rotate_deg(30.0); + for (x, y) in bold.xf.as_coeffs().iter().zip(turned.as_coeffs()) { + assert!(near(*x, y, 1e-3), "{:?} vs {:?}", bold.xf, turned); + } + let serif = text_of(&s, ids[1]); + assert_eq!(serif.first_style().font_family, "Source Serif 4"); + assert!(near(serif.first_style().size, 18.0, 0.01)); +} + +#[test] +fn a_drawn_shape_is_reported_and_left_alone() { + let mut s = session(); + let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 40})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [rect]})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let e = s.execute("type.retype", &json!({})).unwrap_err().to_string(); + assert!(e.contains("no selected shape matches"), "{e}"); + assert!(s.doc().unwrap().doc == before, "nothing changes"); + assert!(s.execute("type.retype", &json!({"fonts": "Source Sans 3"})).is_err(), "fonts is a list"); +} + +#[test] +fn mixed_selection_retypes_the_glyphs_and_keeps_the_rest() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Mix", "size": 30})); + let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 200, "width": 80, "height": 40})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [g, rect]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["Mix"])); + assert_eq!(r["unmatched"], json!([rect])); + let d = &s.doc().unwrap().doc; + assert!(matches!(d.node(NodeId(rect)).unwrap().kind, NodeKind::Path { .. }), "the rectangle stays"); +} + +#[test] +fn two_words_keep_their_space() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 20, "y": 60, "text": "two words", "size": 20})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["two words"])); +} + +#[test] +fn craft_fonts_glyphs_retype_too() { + let Some(f) = vectorcraft_text::CRAFT_FONTS.iter().find(|f| f.is_japanese()) else { + eprintln!("skipped: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout to run it)"); + return; + }; + let mut s = session(); + let g = outlined(&mut s, json!({"x": 20, "y": 60, "text": "漢字です", "size": 20, "font": f.family, "style": f.style})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({"fonts": [f.family]})).unwrap(); + assert_eq!(r["texts"], json!(["漢字です"]), "{r}"); + assert_eq!(r["fonts"][0]["family"], json!(f.family)); +} diff --git a/crates/text/src/fontdb/lookup.rs b/crates/text/src/fontdb/lookup.rs index 27302aed2f..ef394cb079 100644 --- a/crates/text/src/fontdb/lookup.rs +++ b/crates/text/src/fontdb/lookup.rs @@ -368,6 +368,12 @@ impl FontDb { loaded.or_else(|| self.instance_by_id(id)) } + /// The faces loaded so far (the bundled fonts and the installed ones type has used), in load + /// order. Installed fonts that nothing has asked for yet are not among them. + pub fn loaded_faces(&self) -> Vec> { + self.read_faces().clone() + } + /// The face of character style `st`: [`Self::face_version`] of its font, instanced at its /// Variable Font settings ([`Self::instance`]). pub fn style_face(&self, st: &vectorcraft_doc::CharStyle) -> Option> { diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index f7f5d128ba..4e84f5ecd4 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -26,6 +26,7 @@ mod justify; mod kashida; mod kept; mod layout; +pub mod retype; mod shape; #[cfg(not(target_arch = "wasm32"))] mod suitcase; diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs new file mode 100644 index 0000000000..6b3d07ec73 --- /dev/null +++ b/crates/text/src/retype.rs @@ -0,0 +1,384 @@ +//! Retype's glyph matching (Type › Retype, #4934): which glyph of which loaded font an outlined +//! glyph's shape is, the same up to uniform scale, rotation and translation. +//! +//! Phase 1 is exact matching only: a shape matches a glyph when, after the best similarity +//! transform (a Procrustes fit over points sampled at equal steps of arc length along each +//! contour), the leftover distance is a tiny fraction of the shape's size. That holds for outlines +//! made from a font the app has (Create Outlines' output, and other apps' that keep each glyph's +//! contours whole and in the font's order). Near matches (other versions of a font, hinted or +//! simplified outlines, faux styles, glyphs merged into one path) are left unmatched; fuzzy +//! identification is phase 2. + +use std::collections::HashMap; +use std::sync::Arc; + +use kurbo::{BezPath, CubicBez, Line, ParamCurve, ParamCurveArclen, PathEl, PathSeg, Point, QuadBez, Shape}; + +use crate::{FontDb, FontFace}; + +/// At most this many faces are indexed. +pub const MAX_FACES: usize = 96; +/// At most this many encoded characters of one face are indexed (in code point order). +pub const MAX_GLYPHS_PER_FACE: usize = 65_536; +/// At most this many glyphs are indexed in all: faces past it are left out. +pub const MAX_GLYPHS: usize = 262_144; +/// Shapes with more path elements than this are not matched. +pub const MAX_ELEMENTS: usize = 4096; +/// Shapes (and glyphs) with more contours than this are not matched. +const MAX_CONTOURS: usize = 48; +/// Points sampled along each contour. +const SAMPLES: usize = 32; +/// The largest leftover distance (root mean square over the samples) for a match, as a fraction of +/// the shape's spread about its centre. +const TOLERANCE: f64 = 2e-3; +/// How far apart two shapes' spread-to-length ratios may be and still be compared. +const INVARIANT_SLACK: f64 = 0.02; + +/// One glyph an outlined shape matched. +#[derive(Clone)] +pub struct GlyphMatch { + pub face: Arc, + pub gid: u32, + /// The character the face's cmap maps to the glyph (the lowest, when several do). + pub ch: char, + /// Document units per font unit: the font size is `scale` × units per em. + pub scale: f64, + /// The glyph's turn, radians (as [`kurbo::Affine::rotate`] turns). + pub angle: f64, + /// Where the glyph's origin (its baseline start) lies. + pub origin: Point, + /// The leftover distance, relative to the shape's spread. + pub residual: f64, +} + +/// A shape reduced for matching: points along each contour, centred. +struct Signature { + contours: usize, + /// Centred points, [`SAMPLES`] per contour. + pts: Vec, + centre: Point, + /// Root mean square distance of the points from the centre. + spread: f64, + /// `spread` / the total contour length: unchanged by scale, turn and move. + invariant: f64, +} + +struct Entry { + face: usize, + gid: u32, + ch: char, + sig: Signature, +} + +/// The glyphs of a set of faces, ready to match shapes against. +pub struct RetypeIndex { + faces: Vec>, + entries: Vec, + /// Entry indices by contour count, sorted by invariant. + buckets: HashMap>, +} + +impl RetypeIndex { + /// Index the outline glyphs of `faces` (the first [`MAX_FACES`], each face once). + pub fn build(db: &FontDb, faces: impl IntoIterator>) -> Self { + let mut kept: Vec> = vec![]; + for f in faces { + if kept.len() >= MAX_FACES { + break; + } + if !kept.iter().any(|k| k.id() == f.id()) { + kept.push(f); + } + } + let mut entries = vec![]; + for (fi, face) in kept.iter().enumerate() { + if entries.len() >= MAX_GLYPHS { + break; + } + // One entry per glyph, under the lowest character that maps to it. + let mut by_gid: HashMap = HashMap::new(); + for &(c, gid) in face.mapped_chars().iter().take(MAX_GLYPHS_PER_FACE) { + if c.is_whitespace() || c.is_control() { + continue; + } + by_gid.entry(gid).and_modify(|e| *e = (*e).min(c)).or_insert(c); + } + let mut gids: Vec<(u32, char)> = by_gid.into_iter().collect(); + gids.sort_unstable(); + for (gid, ch) in gids { + let outline = db.outline(face, gid); + if let Some(sig) = signature(&outline) { + entries.push(Entry { face: fi, gid, ch, sig }); + } + } + } + let mut buckets: HashMap> = HashMap::new(); + for (i, e) in entries.iter().enumerate() { + buckets.entry(e.sig.contours).or_default().push(i); + } + for list in buckets.values_mut() { + list.sort_by(|a, b| { + let (x, y) = (entries.get(*a).map_or(0.0, |e| e.sig.invariant), entries.get(*b).map_or(0.0, |e| e.sig.invariant)); + x.total_cmp(&y) + }); + } + RetypeIndex { faces: kept, entries, buckets } + } + + /// The faces indexed. + pub fn faces(&self) -> &[Arc] { + &self.faces + } + + /// How many glyphs are indexed. + pub fn len(&self) -> usize { + self.entries.len() + } + + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + /// The glyphs `shape` (in document space) is, the closest one per face, closest first; empty + /// when it is no glyph of the indexed faces. + pub fn matches(&self, shape: &BezPath) -> Vec { + let Some(sig) = signature(shape) else { return vec![] }; + let Some(list) = self.buckets.get(&sig.contours) else { return vec![] }; + let lo = sig.invariant * (1.0 - INVARIANT_SLACK); + let hi = sig.invariant * (1.0 + INVARIANT_SLACK); + let start = list.partition_point(|i| self.entries.get(*i).is_some_and(|e| e.sig.invariant < lo)); + let mut best: HashMap = HashMap::new(); + for i in list.iter().skip(start) { + let Some(e) = self.entries.get(*i) else { continue }; + if e.sig.invariant > hi { + break; + } + let Some((z, residual)) = fit(&e.sig, &sig) else { continue }; + if residual > TOLERANCE { + continue; + } + let Some(face) = self.faces.get(e.face) else { continue }; + // The glyph's origin is (0, 0) in font units: it lands at centre − z·glyph centre. + let gc = mul(z, e.sig.centre); + let origin = Point::new(sig.centre.x - gc.x, sig.centre.y - gc.y); + let m = GlyphMatch { face: face.clone(), gid: e.gid, ch: e.ch, scale: z.0.hypot(z.1), angle: z.1.atan2(z.0), origin, residual }; + match best.get(&e.face) { + Some(b) if b.residual < m.residual || (b.residual == m.residual && b.ch <= m.ch) => {} + _ => { + best.insert(e.face, m); + } + } + } + let mut out: Vec<(usize, GlyphMatch)> = best.into_iter().collect(); + out.sort_by(|a, b| a.1.residual.total_cmp(&b.1.residual).then(a.0.cmp(&b.0))); + out.into_iter().map(|(_, m)| m).collect() + } +} + +/// Complex multiply: `z` (a scaled turn) applied to `p`. +fn mul(z: (f64, f64), p: Point) -> Point { + Point::new(z.0 * p.x - z.1 * p.y, z.1 * p.x + z.0 * p.y) +} + +/// The scaled turn `z` that best takes glyph `g`'s points onto shape `s`'s (both centred), and the +/// leftover distance relative to the shape's spread; `None` for degenerate shapes. +fn fit(g: &Signature, s: &Signature) -> Option<((f64, f64), f64)> { + if g.pts.len() != s.pts.len() || g.pts.is_empty() { + return None; + } + let (mut re, mut im, mut gg) = (0.0, 0.0, 0.0); + for (a, b) in g.pts.iter().zip(&s.pts) { + // Σ s · conj(g) + re += b.x * a.x + b.y * a.y; + im += b.y * a.x - b.x * a.y; + gg += a.x * a.x + a.y * a.y; + } + if gg <= 0.0 || !gg.is_finite() { + return None; + } + let z = (re / gg, im / gg); + let mut res = 0.0; + for (a, b) in g.pts.iter().zip(&s.pts) { + let p = mul(z, *a); + res += (p.x - b.x).powi(2) + (p.y - b.y).powi(2); + } + let n = s.pts.len() as f64; + let rel = (res / n).sqrt() / s.spread; + rel.is_finite().then_some((z, rel)) +} + +/// `path`'s contours as segments, the closing line included; `None` past the size caps. +fn contours(path: &BezPath) -> Option>> { + if path.elements().len() > MAX_ELEMENTS { + return None; + } + let mut out: Vec> = vec![]; + let mut cur: Vec = vec![]; + let (mut start, mut last) = (Point::ZERO, Point::ZERO); + let mut flush = |cur: &mut Vec, start: Point, last: Point| { + if last.distance(start) > 0.0 { + cur.push(PathSeg::Line(Line::new(last, start))); + } + if !cur.is_empty() { + out.push(std::mem::take(cur)); + } + }; + for el in path.elements() { + match *el { + PathEl::MoveTo(p) => { + flush(&mut cur, start, last); + start = p; + last = p; + } + PathEl::LineTo(p) => { + cur.push(PathSeg::Line(Line::new(last, p))); + last = p; + } + PathEl::QuadTo(a, p) => { + cur.push(PathSeg::Quad(QuadBez::new(last, a, p))); + last = p; + } + PathEl::CurveTo(a, b, p) => { + cur.push(PathSeg::Cubic(CubicBez::new(last, a, b, p))); + last = p; + } + PathEl::ClosePath => { + flush(&mut cur, start, last); + last = start; + } + } + } + flush(&mut cur, start, last); + (out.len() <= MAX_CONTOURS).then_some(out) +} + +fn signature(path: &BezPath) -> Option { + let bounds = path.bounding_box(); + let size = bounds.width().hypot(bounds.height()); + if !size.is_finite() || size <= 0.0 { + return None; + } + let accuracy = size * 1e-6; + let mut pts = vec![]; + let mut total = 0.0; + let mut contours_n = 0; + for c in contours(path)? { + let lens: Vec = c.iter().map(|s| s.arclen(accuracy)).collect(); + let len: f64 = lens.iter().sum(); + // A contour with no length (a lone move) draws nothing. + if !(len > size * 1e-9) || !len.is_finite() { + continue; + } + total += len; + contours_n += 1; + let (mut si, mut before) = (0usize, 0.0); + for k in 0..SAMPLES { + let at = len * k as f64 / SAMPLES as f64; + while si + 1 < c.len() && before + lens.get(si).copied().unwrap_or(0.0) < at { + before += lens.get(si).copied().unwrap_or(0.0); + si += 1; + } + let (Some(seg), Some(l)) = (c.get(si), lens.get(si)) else { return None }; + let t = if *l > 0.0 { seg.inv_arclen((at - before).clamp(0.0, *l), accuracy) } else { 0.0 }; + pts.push(seg.eval(t)); + } + } + if pts.is_empty() { + return None; + } + let n = pts.len() as f64; + let centre = Point::new(pts.iter().map(|p| p.x).sum::() / n, pts.iter().map(|p| p.y).sum::() / n); + for p in &mut pts { + *p = Point::new(p.x - centre.x, p.y - centre.y); + } + let spread = (pts.iter().map(|p| p.x * p.x + p.y * p.y).sum::() / n).sqrt(); + if !(spread > 0.0) || !spread.is_finite() { + return None; + } + Some(Signature { contours: contours_n, pts, centre, spread, invariant: spread / total }) +} + +#[cfg(test)] +mod tests { + use super::*; + use kurbo::Affine; + + fn letter() -> BezPath { + // A hand-made "P"-like shape: an outer contour and a counter. + let mut p = BezPath::new(); + p.move_to((0.0, 0.0)); + p.line_to((0.0, -700.0)); + p.curve_to((300.0, -700.0), (450.0, -600.0), (450.0, -480.0)); + p.quad_to((450.0, -300.0), (120.0, -300.0)); + p.line_to((120.0, 0.0)); + p.close_path(); + p.move_to((120.0, -600.0)); + p.line_to((120.0, -400.0)); + p.quad_to((330.0, -400.0), (330.0, -500.0)); + p.quad_to((330.0, -600.0), (120.0, -600.0)); + p.close_path(); + p + } + + #[test] + fn a_shape_matches_itself_scaled_turned_and_moved() { + let g = signature(&letter()).unwrap(); + let xf = Affine::translate((300.0, 200.0)) * Affine::rotate(0.4) * Affine::scale(0.024); + let s = signature(&(xf * letter())).unwrap(); + let (z, res) = fit(&g, &s).unwrap(); + assert!(res < 1e-6, "{res}"); + assert!((z.0.hypot(z.1) - 0.024).abs() < 1e-9); + assert!((z.1.atan2(z.0) - 0.4).abs() < 1e-9); + let origin = s.centre - mul(z, g.centre).to_vec2(); + assert!(origin.distance(Point::new(300.0, 200.0)) < 1e-6, "{origin:?}"); + } + + #[test] + fn lines_written_as_curves_still_match() { + // Paths store lines as cubics with handles on their anchors, or the closing line explicitly. + let mut alt = BezPath::new(); + alt.move_to((0.0, 0.0)); + alt.curve_to((0.0, 0.0), (0.0, -700.0), (0.0, -700.0)); + alt.curve_to((300.0, -700.0), (450.0, -600.0), (450.0, -480.0)); + alt.extend([PathEl::QuadTo((450.0, -300.0).into(), (120.0, -300.0).into())]); + alt.line_to((120.0, 0.0)); + alt.line_to((0.0, 0.0)); + alt.close_path(); + alt.move_to((120.0, -600.0)); + alt.line_to((120.0, -400.0)); + alt.quad_to((330.0, -400.0), (330.0, -500.0)); + alt.quad_to((330.0, -600.0), (120.0, -600.0)); + alt.close_path(); + let (_, res) = fit(&signature(&letter()).unwrap(), &signature(&alt).unwrap()).unwrap(); + assert!(res < 1e-6, "{res}"); + } + + #[test] + fn another_shape_does_not_match() { + let mut o = BezPath::new(); + o.extend(kurbo::Circle::new((200.0, -350.0), 300.0).path_elements(0.1)); + let mut box_ = BezPath::new(); + box_.extend(kurbo::Rect::new(0.0, -700.0, 450.0, 0.0).path_elements(0.1)); + let (a, b) = (signature(&o).unwrap(), signature(&box_).unwrap()); + assert!(fit(&a, &b).is_none_or(|(_, r)| r > TOLERANCE)); + } + + #[test] + fn degenerate_and_hostile_shapes_give_none() { + assert!(signature(&BezPath::new()).is_none()); + let mut dot = BezPath::new(); + dot.move_to((5.0, 5.0)); + dot.close_path(); + assert!(signature(&dot).is_none()); + let mut nan = BezPath::new(); + nan.move_to((f64::NAN, 0.0)); + nan.line_to((1.0, 1.0)); + assert!(signature(&nan).is_none()); + let mut huge = BezPath::new(); + huge.move_to((0.0, 0.0)); + for i in 0..(MAX_ELEMENTS + 1) { + huge.line_to((i as f64, (i % 7) as f64)); + } + assert!(signature(&huge).is_none()); + } +} diff --git a/docs/gaps.md b/docs/gaps.md index a6f6defbb0..a4e0dcd57a 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -466,7 +466,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Missing:** CJK vertical composition (custom mojikumi sets and the Mojikumi Settings dialog, kinsoku settings #633, manual tate-chu-yoko), Middle Eastern features beyond bidi, digit types, Character Direction and Kashidas (a split caret; the Middle Eastern & South Asian composers are done, #4935), - Touch Type, Retype, Snap to Glyph; optional preservation of font sizes during group scaling (#1034 enhancement). + Touch Type, Retype beyond exact matches of available fonts (phase 1 is in, #4934; near matches, the ranked font list and text in images remain), Snap to Glyph; optional preservation of font sizes during group scaling (#1034 enhancement). Itemized in [type-parity.md](type-parity.md). - **Impact:** professional typography and Japanese/Chinese publishing. - **Estimate:** 34–47 h (type core 14–19 h blocks beta). @@ -902,6 +902,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | G4 type: Retype phase 1 (#4934), `type.retype` for outlined text that exactly matches an available font; near matches, the ranked font list and images remain. Scores and estimates unchanged | | 2026-11-16 | minor | Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged. | | 2026-11-14 | minor | Type: Middle Eastern & South Asian and Standard composers per paragraph (#4935): Paragraph panel menu, paragraph styles, `text.setFormat {composer}` and the native file; the Standard composers set Indic, Arabic and Hebrew type glyph by glyph. `.ai`, EPS and PDF files carry no composer. Scores and estimates unchanged. | | 2026-11-14 | minor | Tech Circuit adds three original procedural brushes (Circuit Trace, Bus Lines, Terminal Nodes); ten built-in brush libraries. G5 remaining estimate 3–13 h (estimated); parity scores and headline totals unchanged. | diff --git a/docs/roadmap.md b/docs/roadmap.md index 258b86d04a..d9c3f7cb65 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** minor (PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). > @@ -163,7 +163,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) | 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 yet for type filled and stroked at less than full opacity, or a `TJ` whose kerning starts a new line part way through, which still come in as a filled object and a stroked one; 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; `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); 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); 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 | | M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder, Color Adjustments and Document Raster Effects Settings; PDF export warns when the pixel cap lowers raster-effect resolution; Artistic › Colored Pencil, Cutout, Dry Brush, Film Grain, Fresco, Neon Glow, Paint Daubs, Palette Knife, Poster Edges, Rough Pastels, Smudge Stick, Sponge, Underpainting and Watercolor and Sketch › Halftone Pattern, Bas Relief, Charcoal, Conté Crayon, Photocopy, Stamp, Torn Edges and Water Paper done (57/57 Photoshop filters); Revolve with automatic smooth vector shading, default-on circular caps and continuous rims, Extrude & Bevel, Inflate and Rotate with one to ten colored directional lights and four original lighting presets; SVG Filters, remaining raster effects and 3D materials and shadows pending | 81–130 | | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, ten generated libraries including Tech Circuit, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | @@ -212,6 +212,7 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | M7/G4: Retype phase 1 (#4934): `type.retype` turns outlined text that exactly matches an available font back into point text. Scores and estimates unchanged | | 2026-11-17 | minor | PDF import (#8300): a glyph filled only (text rendering mode 0) right after one filled and stroked (mode 2) joined the stroked run and came in stroked too: `2 Tr (B) Tj 0 Tr (C) Tj` came in as `BC` stroked throughout. A glyph filled only now joins only a run drawn alike, so it starts a run of its own, filled only, in the same type object, and takes a stroke only when the file draws one over it (the #8015 matching); a word filled whole then stroked whole, and fill and stroke rendering glyph by glyph, still come in as one run filled and stroked. Tests: `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked`, `glyphs_filled_and_stroked_one_by_one_stay_one_run`; scores and estimates unchanged. | | 2026-11-17 | minor | PDF import (#8015 follow-up): type filled and stroked at less than full opacity is no longer joined into one type object, since the file composites the fill and the stroke apiece, darker where they overlap, while one object's opacity applies to both together; it stays a filled object and a stroked one, as a fill and stroke at different opacities already did. An upright glyph (vertical type) filled and stroked is no longer kept as an outline for a line that comes in as its outlines, as glyphs filled only weren't, so such a line can't lose them. The #8015 entries now say what is left: translucent type filled and stroked, and a `TJ` whose kerning starts a new line part way through, still come in as two objects. Tests: `translucent_fill_and_stroke_text_stays_two_objects`, `a_vertical_line_with_one_glyph_filled_and_stroked_keeps_every_glyph_filled`; scores and estimates unchanged. | | 2026-11-16 | minor | PDF import: fill and stroke rendering (text rendering modes 2 and 6) draws all the glyphs of a text-showing operator (`Tj`, `TJ`, `'`, `"`) filled, then the same glyphs stroked, so a word shown at once came in as two type objects: a stroke-only copy over a fill-only one. Each stroke is now matched, in order, to the glyph filled with the same placement (where, how large, how wide, slanted and turned) in the same font with the same text on the line, and only that glyph takes the stroke, so the word comes in as one type object, filled and stroked; glyphs stroked with another join part way through still split into runs of their own, and stroked type over no filled glyph (modes 1 and 5) stays stroke only (#8015; `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`, `a_vertical_column_filled_then_stroked_is_one_filled_and_stroked_type` in `crates/pdf/src/tests/text_placement.rs`). Scores and estimates unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e9fc9a6820..0a663b7ea4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** minor (Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -259,15 +259,15 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated; Transform typing, sliders, preview, and undo are covered in `crates/ui-egui/src/panels/tests_appearance.rs` | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, the rest of 3D Classic (Map Art), Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | | Type core | 9 | 80% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout (the Middle Eastern & South Asian and Standard composers are done per paragraph, #4935; `.ai`/EPS/PDF files carry no composer), optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; eleven-language pattern hyphenation in both composers, with grapheme and shaping-cluster protection (#4947, `hyphen::tests` and `layout::wrapping_tests`); Sanskrit patterns pending an allowlisted source; recent-font groups in font pickers (#3515); full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); Fractional Widths per type object regression-tested; color emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; threading ports: every selected area type and type on a path shows its in and out ports (empty, arrow, red "+"), and the Selection tool threads from either, the in port into a frame before it, and a double-click on a threaded port breaks the thread there (`threads::tests::break_splits_the_thread_and_the_story_flows_into_the_first_part`, `select::tests::a_double_click_on_a_threaded_port_breaks_the_thread`, `canvas::tests::a_double_click_on_a_threaded_out_port_breaks_the_thread`) (#2572; `select::tests::a_click_on_the_in_port_threads_into_a_frame_before_it`, `text::tests::selected_type_shows_its_ports_in_each_state`, `threads::tests::add_before_threads_the_story_from_the_new_frame_into_the_clicked_one`, live screenshot); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests); the OpenType panel lists only `ss01`–`ss20` sets present in the selected font and uses its custom names when supplied; Type-range desktop Copy publishes styled art and keeps font family, size and color on canvas Paste after editing (#5636); paint-only Arabic harakat keep joining with conditional GDEF-mark ownership and Insert Kashidas base-letter paint (`tests::harakat`) | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), variable font axes, tab leaders, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | +| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), variable font axes, tab leaders, Touch Type, Retype beyond exact matches of available fonts | 20–28 | estimated; Retype phase 1 (`type.retype`, exact glyph matches, #4934); upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons and Weather Icons are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), tab leaders, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | +| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), tab leaders, Touch Type, Retype beyond exact matches of available fonts | 20–28 | estimated; Retype phase 1 (`type.retype`, exact glyph matches, #4934); upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons and Weather Icons are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; simpler contour walk, identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments, so Paths is monotone on the code-drawn sweep) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them; Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views (scores/hours unchanged) | | Live vector effects | 5 | 85% | Outline Object, SVG Filters | 4–8 | measured count 49/50 (Pathfinder 13/13 with Trap), depth estimated; Warp Options controls verified by focused checks and original-image review | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, original lighting presets, painter visibility), Revolve (Classic) with Angle, Cap, Offset and the Plastic, Diffuse, No Shading and Wireframe surfaces, the Quick Actions › Expand as Wireframes command (#6354), the Render Settings › Wireframe mode on Extrude & Bevel, Revolve, Inflate and Rotate; materials, shadows, ray tracing, the rest of 3D Classic (Map Art), Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); Revolve (Classic) is covered by the `revolve::classic` tests and `dialogs::revolve::tests::classic_revolve_shows_its_options_and_applies_as_one_step`; Expand as Wireframes is covered by `crates/effects/src/solids/wireframe/tests.rs` and `crates/engine/src/cmd/wireframe/tests.rs`, and Render Settings › Wireframe by `crates/effects/src/solids/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` (score, gaps and hours unchanged); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), variable font axes, tab leaders, Touch Type, Retype | 20–28 | estimated; No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | -| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), tab leaders, Touch Type, Retype | 20–28 | estimated; No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | +| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), variable font axes, tab leaders, Touch Type, Retype beyond exact matches of available fonts | 20–28 | estimated; Retype phase 1 (`type.retype`, exact glyph matches, #4934); No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | +| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), tab leaders, Touch Type, Retype beyond exact matches of available fonts | 20–28 | estimated; Retype phase 1 (`type.retype`, exact glyph matches, #4934); No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Raster effects (Effect Gallery) | 4 | 55% | — | — | estimated (raised from 52%: the Effect Gallery's filter thumbnails and in-dialog preview, an original landscape drawing passed through each filter, [Filter Gallery overview](https://helpx.adobe.com/photoshop/desktop/effects-filters/get-started-with-filters/filter-gallery.html), `dialogs::effect_gallery::tests::gallery_shows_thumbnails_and_an_in_dialog_preview`; the gallery itself shipped in #2883, six categories, per-filter settings, ordered stack, live canvas preview, one undo step, `stack_ok_is_one_undo_step`, `stack_preview_is_one_interaction`); measured count 57/57 (Artistic complete with Colored Pencil, Fresco, Paint Daubs, Palette Knife, Rough Pastels and Underpainting; Sketch complete with Torn Edges and Conté Crayon, `pixel::tests_sketch::conte_crayon_*`); texture redraw distances optimized (#1257), pixels verified; the score stays under 100% because the filters are original approximations; depth estimated | | Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons and Weather Icons are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) and on-canvas 9-slice guides (#5280) are done | 4–7 | estimated | | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; large images trace with a warning; Auto Color keeps rare distinct colours) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them | @@ -528,10 +528,10 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Appearance, transparency, graphic styles, masks | 5 | 98% | Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); raster effect reach in preview bounds (flattener presets apply in PDF, EPS and print) | 1–2 | | Live vector effects | 5 | 85% | Outline Object, Pathfinder Hard/Soft Mix and Trap (since done: #3061, #3063, #3785), SVG Filters, Transform Patterns and Scale Strokes & Effects on a fill's or stroke's own Transform effect | 6–10 | | 3D and Materials | 4 | ~25% | Initial Revolve, Extrude & Bevel, Inflate and Rotate, with simple lighting; materials, light presets, shadows, ray tracing, Rotate (Classic), Map Art and more complete visibility remain | 25–45 | -| Type advanced | 4 | 50% | CJK composition for vertical type (ruby, mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), custom kinsoku sets (beyond Hard, Soft and None) and the Mojikumi Settings dialog —, manual tate-chu-yoko), tab leaders, Touch Type, Retype; vertical point/area/path type and Type Orientation have initial support (beyond parity, not scored: inline symbols in text) | 20–28 | +| Type advanced | 4 | 50% | CJK composition for vertical type (ruby, mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), custom kinsoku sets (beyond Hard, Soft and None) and the Mojikumi Settings dialog —, manual tate-chu-yoko), tab leaders, Touch Type, Retype beyond exact matches of available fonts (phase 1, #4934); vertical point/area/path type and Type Orientation have initial support (beyond parity, not scored: inline symbols in text) | 20–28 | | Raster effects (Effect Gallery, Document Raster Effects Settings) | 4 | 35% | ~36 Photoshop-style filters (Artistic, Brush Strokes, Sketch, Stylize) and Texturizer's Load Texture (since done, see the area table above, as is the Effect Gallery, #2883); Document Raster Effects Settings, raster effects in PDF, the pixel-filter pipeline, Radial Blur, Smart Blur (Normal, Edge Only and Overlay Edge), Unsharp Mask, Glowing Edges, Distort (Diffuse Glow, Glass, Ocean Ripple), Pixelate (Color Halftone, Crystallize, Mezzotint, Pointillize), Texture (Craquelure, Grain, Mosaic Tiles, Patchwork, Stained Glass, Texturizer) and Video (De-Interlace, NTSC Colors) are done | 8–14 | | 3D and Materials | 4 | ~25% | Initial Revolve, Extrude & Bevel, Inflate and Rotate, with simple lighting and four original lighting presets; materials, shadows, ray tracing, Rotate (Classic), Map Art and more complete visibility remain | 25–45 | -| Type advanced | 4 | 50% | CJK composition for vertical type (mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), custom kinsoku sets (beyond Hard, Soft and None) and the Mojikumi Settings dialog —, manual tate-chu-yoko is done, its up/down settings remain; No Break is done), tab leaders, Touch Type, Retype; vertical point/area/path type and Type Orientation have initial support (beyond parity, not scored: inline symbols in text) | 20–28 | +| Type advanced | 4 | 50% | CJK composition for vertical type (mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), custom kinsoku sets (beyond Hard, Soft and None) and the Mojikumi Settings dialog —, manual tate-chu-yoko is done, its up/down settings remain; No Break is done), tab leaders, Touch Type, Retype beyond exact matches of available fonts (phase 1, #4934); vertical point/area/path type and Type Orientation have initial support (beyond parity, not scored: inline symbols in text) | 20–28 | | Type core | 9 | 80% | Middle Eastern features beyond bidi layout, Paragraph Direction, digit types and Kashidas (editable bidirectional SVG text, a split caret where directions meet; the Middle Eastern & South Asian composers are done, #4935, but `.ai`/EPS/PDF files carry no composer); paint-only harakat keep joining with conditional GDEF-mark colour ownership, but fonts without GDEF mark classes and some AAT/`morx` ligatures can still leave marks painted as their letters; Every-line Composer fidelity for justified and ragged text (available per object; mixed type sizes in a paragraph still break single-line in non-rectangular area type and with text wrap), Optical Margin Alignment, paragraph spacing limit for vertically justified area type, hidden characters, paragraph attributes in the Type tool's copy and paste (the characters keep their styles, the paragraphs take the destination's), mixed-value display in the Paragraph panel for a selection across differing paragraphs, partial selection of type-area anchors by marquee, optional font-size preservation during group scaling (scaled character controls fixed in #1034). Hyphenation and Justification options, Fractional Widths, System Layout, styled Type-range canvas Paste (#5636), and pattern hyphenation for eleven Indian languages with grapheme/cluster protection (#4947) are done; Sanskrit automatic patterns remain pending an allowlisted source | 14–19 | | Symbols, blends, envelopes, Repeat, perspective | 5 | 90% | further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons and Weather Icons are done), dynamic symbols' `.ai` round trip, envelope Anti-Alias/Preserve Shape output and warp point editing, brush interpolation in blends (M8 fidelity pass done); Symbol Options › Registration and Export Type and on-canvas dynamic part paint (gradient/pattern, opacity, blend) are done; symbol editing shows draggable 9-slice guides (#5280), while guides outside the artwork remain unsupported | 4–7 | | Image Trace, graphs, image tools | 3 | 72% | graph Column designs (Graph Design, Marker designs and series colours set with Group Selection are done), Create Object Mosaic, per-feature stroke/fill choice and varying widths in Image Trace's Create Strokes (Vector Halftone and the Image Trace View modes, Palette and Create Strokes are done) | 6–10 | @@ -2719,6 +2719,10 @@ Edit Custom Dictionary followed (2026-11-10), as the same page's "Edit the custo Check Spelling followed (2026-11-15): Edit › Spelling › Check Spelling… (`Cmd+I`, `ui.checkSpelling`) opens a modal dialog displaying the unrecognized word in its sentence context ("Not in Dictionary"), a list of suggestions with selection or double-click to replace into the "Change to" field, and action buttons: "Ignore" (skips current word), "Ignore All" (skips word in active document, `text.spelling.ignoreAll`), "Change" (replaces word in 1-step undo, `text.editRange`), "Change All" (replaces all occurrences in a single undo step via `command.batch`), "Add to Dictionary" (`text.spelling.addWord`), and "Done" / "Cancel". Supports keyboard navigation (Tab between controls, Enter to Change or Done, Escape to close) (#4936; `crates/ui-egui/src/dialogs/check_spelling.rs`). Spell check is complete. +## Retype, phase 1 (2026-11-18) + +The public pages describe Retype finding the fonts that match selected outlined text (or text in an image), from the fonts on the device among others, and applying them to live text ([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)). Phase 1 (#4934) is local and exact: Type › Retype (`type.retype`) compares each selected glyph shape with the glyphs of the loaded fonts, the document's fonts and any families named in `fonts`, the same up to uniform scale, rotation and translation, and sets the matched characters as point text in that font and size at the same baseline, one object per line, in one undo step. Shapes that match no font stay and are reported. Tested by round trips through Create Outlines (plain, bold and turned, serif, word spaces), a drawn shape and a mixed selection (`crates/engine/src/cmd/retype_tests.rs`). Near matches, the ranked font list, installed fonts not yet loaded and images remain (phase 2). + ## 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). @@ -2783,6 +2787,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | Type advanced: Retype phase 1 (`type.retype`, #4934), exact matches of available fonts become point text again; evidence added; near matches, the ranked font list and images remain; score and hours unchanged | | 2026-11-16 | minor | Layers panel: rows or the selected-art square dragged over the list show the copy cursor while Alt is held, as the drop then copies, and the grabbing hand otherwise (#8217). Scores and estimates unchanged. | | 2026-11-16 | minor | Gradient panel: the strip under the ramp, where a click adds a stop, shows the white arrow with a plus on Windows and X11, where the system copy cursor showed as the plain arrow (#8241). Scores and estimates unchanged. | | 2026-11-16 | minor | Properties panel: while the Type tool edits text, the Character section shows the font family and style and the Variable Font button of the first selected character (or of the character before the caret), not those of the text object's first run (#8189). Evidence: `panels::properties::tests::character_section_shows_the_type_tool_selections_style`. Scores and estimates unchanged. | diff --git a/docs/type-parity.md b/docs/type-parity.md index 458788b1b6..5bf888b952 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -1,6 +1,6 @@ # Type parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (modal Check Spelling dialog: Edit › Spelling › Check Spelling…, `ui.checkSpelling`, #4936; spell check complete; previously minor: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; `.ai` and EPS files do not carry the choice; scores and estimates unchanged; previously minor: kerning at the Type tool's caret at the start of a line sets the space before the character after it, #5111; previously minor: type's strokes in an envelope paint along its bent glyph outlines at their own weight, Distort Appearance on or off, as users' `.ai` files draw them, #6644; previously minor: a centred or right-aligned line of tracked type is aligned without the tracking after its last character, as the page of users' `.ai` files aligns it, #6610; previously minor: tracking and manual kerning in horizontally scaled type are thousandths of the em as the Horizontal Scale draws it, as the page of users' `.ai` files spaces such type; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: Direct Selection shows and drags the direction handles of type on a path's path, #3565; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas base-letter paint; scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: right-aligned area type sets the text after a line's last tab against the right edge; a soft return in justified type no longer keeps its line from being justified; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: modal Check Spelling dialog: Edit › Spelling › Check Spelling…, `ui.checkSpelling`, #4936; spell check complete; previously minor: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; `.ai` and EPS files do not carry the choice; scores and estimates unchanged; previously minor: kerning at the Type tool's caret at the start of a line sets the space before the character after it, #5111; previously minor: type's strokes in an envelope paint along its bent glyph outlines at their own weight, Distort Appearance on or off, as users' `.ai` files draw them, #6644; previously minor: a centred or right-aligned line of tracked type is aligned without the tracking after its last character, as the page of users' `.ai` files aligns it, #6610; previously minor: tracking and manual kerning in horizontally scaled type are thousandths of the em as the Horizontal Scale draws it, as the page of users' `.ai` files spaces such type; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: Direct Selection shows and drags the direction handles of type on a path's path, #3565; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas base-letter paint; scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: right-aligned area type sets the text after a line's last tab against the right edge; a soft return in justified type no longer keeps its line from being justified; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen) · **Target:** Adobe Illustrator 2026 (30.x) Glyphs review (#6084): a positional variant no supported feature draws is accepted as a glyph choice. Entire Font respects the selection's variable axes and font version; the default cell can reset an unlisted choice without GSUB alternates. Contextual choices use the supplying face, including fallback. Feature-only boundaries preserve ligature clusters and Arabic mark attachment. Encoded characters insert unchanged except Arabic presentation forms with a joining base letter; normalization reports success only after insertion succeeds. Latest follow-up regressions await runtime verification. Scores and estimates unchanged. @@ -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) | missing | Illustrator's uses a cloud model | +| 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. Missing (phase 2): near or fuzzy matches (another version of the font, simplified outlines, glyphs merged into one path), the ranked list of matching fonts with previews, installed fonts not yet loaded, area text for several lines, tracking, 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. | @@ -89,6 +89,7 @@ Character Styles menu New/Redefine and footer New capture the first selected cha | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | Retype phase 1 (#4934): `type.retype` turns outlined glyphs that exactly match an available font back into point text (font, size, baseline, turn, paint), reporting the shapes it cannot match; the Retype row is now partial. Scores and estimates unchanged | | 2026-11-15 | minor | Check Spelling dialog (#4936): Edit › Spelling › Check Spelling… (`Cmd+I`, `ui.checkSpelling`) modal dialog with sentence context, suggestions, Ignore, Ignore All, Change, Change All, Add to Dictionary, Done/Cancel, keyboard navigation, and one-step Undo/Redo; spell check complete. Scores and estimates unchanged. | | 2026-11-14 | minor | Paragraph composers (#4935): `text.setFormat {composer}` and paragraph styles take `singleLine` and `everyLine` (the Middle Eastern & South Asian composers, what all type used and the default) and `standardSingleLine` and `standardEveryLine`, which break lines the same way and set a complex script (Indic, Arabic, Hebrew) glyph by glyph as the font maps its characters, with no conjuncts, reordering, marks placed or joining forms. The choice is per paragraph, saved in the native file only when it is not Every-line, and not written to `.ai`, EPS or PDF files, whose composer setting this app has no recorded format for. Scores and estimates unchanged. Tests `tests::composers`. | | 2026-11-12 | minor | Glyphs review (#6084): validate contextual glyph choices against their supplying face, including fallback and overflow; keep feature-only boundaries inside ligatures and Arabic mark clusters while retaining drawing-attribute splits; preserve insertion failures instead of reporting normalization success. Deterministic engine, shaping and panel regression sources added; ligature range assertions use the fixture's unencoded glyph identity. Runtime proof pending. Scores and estimates unchanged. | From 75d9d61ce99346add6bb01997923d5afa4a12ebb Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Wed, 18 Nov 2026 02:36:38 +0530 Subject: [PATCH 02/15] M7/G4: rustfmt the retype module declaration (#4934) --- crates/engine/src/cmd.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 4fec3f90bd..e0fe77ecda 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -101,11 +101,11 @@ mod textedit; mod xmlattrs; pub use textedit::effective_kerning; +mod retype; pub mod textstyles; pub(crate) mod textwrap; pub(crate) mod threads; pub(crate) mod typecmd; -mod retype; mod typemenu; mod variablecmds; pub(crate) mod views; From 957712ca718d027b3d646f56cb08ef7c4cce168a Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Wed, 18 Nov 2026 02:48:38 +0530 Subject: [PATCH 03/15] M7/G4: retype float checks without negated comparisons (#4934) --- crates/text/src/retype.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index 6b3d07ec73..9e3f2a3ec4 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -266,7 +266,7 @@ fn signature(path: &BezPath) -> Option { let lens: Vec = c.iter().map(|s| s.arclen(accuracy)).collect(); let len: f64 = lens.iter().sum(); // A contour with no length (a lone move) draws nothing. - if !(len > size * 1e-9) || !len.is_finite() { + if !len.is_finite() || len <= size * 1e-9 { continue; } total += len; @@ -292,7 +292,7 @@ fn signature(path: &BezPath) -> Option { *p = Point::new(p.x - centre.x, p.y - centre.y); } let spread = (pts.iter().map(|p| p.x * p.x + p.y * p.y).sum::() / n).sqrt(); - if !(spread > 0.0) || !spread.is_finite() { + if !spread.is_finite() || spread <= 0.0 { return None; } Some(Signature { contours: contours_n, pts, centre, spread, invariant: spread / total }) From 90b37ad2694bfc09455c51c0888d6227e92ccde0 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Wed, 18 Nov 2026 03:02:33 +0530 Subject: [PATCH 04/15] M7/G4: retype keeps paint order, groups, transparency and font version (#4934) An unmatched shape between glyphs ends the line, so the type after it is still painted over it. Glyphs of different groups, paint or transparency never share a line, and the new type takes the glyphs' own opacity and blend mode. The type names the font version that matched. The glyph budget holds inside a face too. --- crates/engine/src/cmd/retype.rs | 58 +++++++++++++++++++-------- crates/engine/src/cmd/retype_tests.rs | 48 ++++++++++++++++++++++ crates/text/src/retype.rs | 4 ++ 3 files changed, 94 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index a5f3b98bde..395ce33b23 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -47,23 +47,28 @@ pub fn specs() -> Vec { /// A shape to match: a path or compound path, in document space. struct Piece { id: NodeId, + /// The group holding it (`None` for a selected shape at the top): glyphs of different + /// groups, which may composite differently, never share a line. + parent: Option, path: BezPath, appearance: Appearance, + /// The shape's own transparency, which the new type takes. + opacity: f32, + blend: vectorcraft_color::BlendMode, } -fn collect(n: &Node, depth: usize, out: &mut Vec) { +fn collect(n: &Node, parent: Option, depth: usize, out: &mut Vec) { if out.len() >= MAX_PIECES || depth > MAX_DEPTH { return; } + let piece = |path: BezPath| Piece { id: n.id, parent, path, appearance: (*n.appearance).clone(), opacity: n.opacity, blend: n.blend }; match &n.kind { NodeKind::Group { children, clip: false } => { for c in children { - collect(c, depth + 1, out); + collect(c, Some(n.id), depth + 1, out); } } - NodeKind::Path { path, clipping: false, guide: false, .. } => { - out.push(Piece { id: n.id, path: path.to_bezpath(), appearance: (*n.appearance).clone() }) - } + NodeKind::Path { path, clipping: false, guide: false, .. } => out.push(piece(path.to_bezpath())), NodeKind::Compound { children, .. } => { let mut path = BezPath::new(); for c in children { @@ -71,7 +76,7 @@ fn collect(n: &Node, depth: usize, out: &mut Vec) { path.extend(p.to_bezpath()); } } - out.push(Piece { id: n.id, path, appearance: (*n.appearance).clone() }); + out.push(piece(path)); } _ => {} } @@ -111,6 +116,9 @@ struct Line { origin: Point, end: Point, appearance: Appearance, + parent: Option, + opacity: f32, + blend: vectorcraft_color::BlendMode, } impl Line { @@ -118,13 +126,18 @@ impl Line { Vec2::new(self.angle.cos(), self.angle.sin()) } - /// Does glyph `m` continue this line (same font, size and turn, on its baseline, after its end)? - fn continues(&self, m: &GlyphMatch) -> bool { + /// Does glyph `m` of shape `pc` continue this line (same group, paint and transparency, same + /// font, size and turn, on its baseline, after its end)? + fn continues(&self, pc: &Piece, m: &GlyphMatch) -> bool { let size = self.scale * self.face.units_per_em(); let d = m.origin - self.origin; let dir = self.dir(); let across = d.cross(dir).abs(); - m.face.id() == self.face.id() + pc.parent == self.parent + && pc.appearance == self.appearance + && pc.opacity == self.opacity + && pc.blend == self.blend + && m.face.id() == self.face.id() && (m.scale - self.scale).abs() <= self.scale * 0.005 && (m.angle - self.angle).abs() < 1e-3 && across < size * 0.05 @@ -150,17 +163,20 @@ fn space_advance(face: &vectorcraft_text::FontFace) -> f64 { face.mapped_chars().iter().find(|(c, _)| *c == ' ').map(|(_, g)| face.advance(*g)).unwrap_or(0.0) } -fn new_line(id: NodeId, m: &GlyphMatch, appearance: &Appearance) -> Line { +fn new_line(pc: &Piece, m: &GlyphMatch) -> Line { let dir = Vec2::new(m.angle.cos(), m.angle.sin()); Line { - pieces: vec![id], + pieces: vec![pc.id], text: m.ch.to_string(), face: m.face.clone(), scale: m.scale, angle: m.angle, origin: m.origin, end: m.origin + dir * (m.face.advance(m.gid) * m.scale), - appearance: appearance.clone(), + appearance: pc.appearance.clone(), + parent: pc.parent, + opacity: pc.opacity, + blend: pc.blend, } } @@ -180,7 +196,7 @@ fn retype(s: &mut Session, p: &Value) -> Result { let mut pieces = vec![]; for r in &roots { if let Some(n) = d.node(*r) { - collect(n, 0, &mut pieces); + collect(n, None, 0, &mut pieces); } } if pieces.is_empty() { @@ -200,17 +216,21 @@ fn retype(s: &mut Session, p: &Value) -> Result { let rank = |face: u32| votes.iter().find(|(f, _)| *f == face).map_or(0, |v| v.1); let mut lines: Vec = vec![]; let mut unmatched = vec![]; + // An unmatched shape between glyphs ends the line: the type after it is painted after it. + let mut open = false; for (pc, ms) in pieces.iter().zip(&found) { // Earlier matches win ties: they are the closer fits. let best = ms.iter().enumerate().max_by_key(|(i, m)| (rank(m.face.id()), std::cmp::Reverse(*i))).map(|(_, m)| m); let Some(m) = best else { unmatched.push(pc.id); + open = false; continue; }; match lines.last_mut() { - Some(l) if l.continues(m) => l.push(pc.id, m), - _ => lines.push(new_line(pc.id, m, &pc.appearance)), + Some(l) if open && l.continues(pc, m) => l.push(pc.id, m), + _ => lines.push(new_line(pc, m)), } + open = true; } (lines, unmatched) }; @@ -227,6 +247,8 @@ fn retype(s: &mut Session, p: &Value) -> Result { let style = CharStyle { font_family: l.face.family.clone(), font_style: l.face.style.clone(), + // The version that matched, when two of the family and style are loaded. + font_version: (!l.face.version.is_empty()).then(|| l.face.version.clone()), size: l.scale * l.face.units_per_em(), fill: l.appearance.fill_paint(), stroke: l.appearance.stroke_paint(), @@ -241,7 +263,11 @@ fn retype(s: &mut Session, p: &Value) -> Result { t.system_layout = system_layout; super::typecmd::refresh_bounds(&mut t); let id = d.alloc_id(); - d.insert(par, idx, Node::new(id, NodeKind::Text(Box::new(t))))?; + let mut node = Node::new(id, NodeKind::Text(Box::new(t))); + // The glyphs' own transparency (the group's, kept, still applies over it). + node.opacity = l.opacity; + node.blend = l.blend; + d.insert(par, idx, node)?; for pc in &l.pieces { if let Some((Some(parent), _, _)) = d.position(*pc) { emptied.push(parent); diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 6ed12289f4..af91b8442d 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -118,3 +118,51 @@ fn craft_fonts_glyphs_retype_too() { assert_eq!(r["texts"], json!(["漢字です"]), "{r}"); assert_eq!(r["fonts"][0]["family"], json!(f.family)); } + +fn children_of(s: &Session, g: u64) -> Vec { + s.doc().unwrap().doc.node(NodeId(g)).unwrap().children().unwrap().iter().map(|c| c.id.0).collect() +} + +#[test] +fn a_shape_between_glyphs_ends_the_line_so_paint_order_holds() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40})); + let rect = s.execute("shape.rectangle", &json!({"x": 30, "y": 60, "width": 80, "height": 50})).unwrap()["id"].as_u64().unwrap(); + // The rectangle goes between A and B, inside the outlines' group. + s.edit("test", |d, _| { + let n = d.node(NodeId(rect)).unwrap().clone(); + d.remove(NodeId(rect))?; + d.insert(Some(NodeId(g)), 1, n)?; + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["A", "B"]), "{r}"); + assert_eq!(r["unmatched"], json!([rect])); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(children_of(&s, g), vec![ids[0], rect, ids[1]], "A under the rectangle, B over it"); +} + +#[test] +fn glyphs_of_different_groups_and_transparency_stay_apart() { + let mut s = session(); + let a = outlined(&mut s, json!({"x": 40, "y": 100, "text": "ab", "size": 20})); + let b = outlined(&mut s, json!({"x": 120, "y": 100, "text": "cd", "size": 20})); + let first_d = children_of(&s, b)[1]; + s.edit("test", |d, _| { + d.node_mut(NodeId(b)).unwrap().opacity = 0.5; + d.node_mut(NodeId(first_d)).unwrap().opacity = 0.25; + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["ab", "c", "d"]), "same baseline, other group; d has its own opacity: {r}"); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + let d = &s.doc().unwrap().doc; + assert!(d.node(NodeId(a)).is_none(), "a plain group gives way to its type"); + assert_eq!(d.node(NodeId(b)).unwrap().opacity, 0.5, "the half-transparent group stays"); + assert_eq!(children_of(&s, b), vec![ids[1], ids[2]]); + assert_eq!(s.doc().unwrap().doc.node(NodeId(ids[2])).unwrap().opacity, 0.25, "the glyph's own opacity carries over"); +} diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index 9e3f2a3ec4..5a1894e2d0 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -106,6 +106,10 @@ impl RetypeIndex { let mut gids: Vec<(u32, char)> = by_gid.into_iter().collect(); gids.sort_unstable(); for (gid, ch) in gids { + // The budget holds inside a face too: no glyph is loaded past it. + if entries.len() >= MAX_GLYPHS { + break; + } let outline = db.outline(face, gid); if let Some(sig) = signature(&outline) { entries.push(Entry { face: fi, gid, ch, sig }); From 290a58fc1865e4f407c3360bf4a94909f41087f5 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:38:40 +0530 Subject: [PATCH 05/15] M7/G4: retype review follow-ups (#4934) List type.retype among the commands plugins may call. Only closed shapes match glyphs. Live type, images and other art between glyphs, and unselected art between selected objects, end the line. Each selected object's own parent decides its group. Retyped type turns ligatures off, as the outlines drew each glyph on its own. --- crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/src/cmd/retype.rs | 57 ++++++++++++++----- crates/engine/src/cmd/retype_tests.rs | 37 ++++++++++++ 3 files changed, 82 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 6a0caf4cd6..28cce5a244 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -683,6 +683,7 @@ pub(super) const ALLOWED: &[&str] = &[ "type.pathOptions", "type.resetHorizontalScale", "type.resetTracking", + "type.retype", "type.ruby", "type.scaleTextAttributes", "type.size.decrease", diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index 395ce33b23..72ab30a711 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -47,9 +47,12 @@ pub fn specs() -> Vec { /// A shape to match: a path or compound path, in document space. struct Piece { id: NodeId, - /// The group holding it (`None` for a selected shape at the top): glyphs of different - /// groups, which may composite differently, never share a line. + /// The group or layer holding it: glyphs of different groups, which may composite + /// differently, never share a line. parent: Option, + /// Other art (not retyped) lies between it and the shape before it, so the type after that + /// art must stay painted after it: the line ends here. + after_barrier: bool, path: BezPath, appearance: Appearance, /// The shape's own transparency, which the new type takes. @@ -57,28 +60,45 @@ struct Piece { blend: vectorcraft_color::BlendMode, } -fn collect(n: &Node, parent: Option, depth: usize, out: &mut Vec) { +/// The shapes in `n` (held by `parent`), in paint order. `barrier` is set when art that is not a +/// shape lies before the next one; it starts set for a root that does not follow the last root. +fn collect(n: &Node, parent: Option, depth: usize, barrier: &mut bool, out: &mut Vec) { if out.len() >= MAX_PIECES || depth > MAX_DEPTH { + *barrier = true; return; } - let piece = |path: BezPath| Piece { id: n.id, parent, path, appearance: (*n.appearance).clone(), opacity: n.opacity, blend: n.blend }; + let piece = |path: BezPath, after_barrier: bool| Piece { + id: n.id, + parent, + after_barrier, + path, + appearance: (*n.appearance).clone(), + opacity: n.opacity, + blend: n.blend, + }; match &n.kind { NodeKind::Group { children, clip: false } => { for c in children { - collect(c, Some(n.id), depth + 1, out); + collect(c, Some(n.id), depth + 1, barrier, out); } } - NodeKind::Path { path, clipping: false, guide: false, .. } => out.push(piece(path.to_bezpath())), + // Only closed shapes can be glyphs: an open path stroked along a glyph's outline is not one. + NodeKind::Path { path, clipping: false, guide: false, .. } if path.is_closed() => out.push(piece(path.to_bezpath(), std::mem::take(barrier))), NodeKind::Compound { children, .. } => { let mut path = BezPath::new(); for c in children { - if let NodeKind::Path { path: p, .. } = &c.kind { - path.extend(p.to_bezpath()); + match &c.kind { + NodeKind::Path { path: p, .. } if p.is_closed() => path.extend(p.to_bezpath()), + _ => { + *barrier = true; + return; + } } } - out.push(piece(path)); + out.push(piece(path, std::mem::take(barrier))); } - _ => {} + // Live type, images, clip groups and the rest stay, and the type after them stays after them. + _ => *barrier = true, } } @@ -194,10 +214,16 @@ fn retype(s: &mut Session, p: &Value) -> Result { let (lines, unmatched) = { let d = &s.doc()?.doc; let mut pieces = vec![]; + let mut last: Option<(Option, usize)> = None; for r in &roots { - if let Some(n) = d.node(*r) { - collect(n, None, 0, &mut pieces); - } + let Some(n) = d.node(*r) else { continue }; + let parent = d.parent_of(*r); + let idx = d.position(*r).map(|(_, i, _)| i); + // A root right after the last one, in the same parent, continues its lines; unselected + // art between two roots is a barrier. + let mut barrier = !matches!((last, idx), (Some((p, i)), Some(j)) if p == parent && i + 1 == j); + last = idx.map(|i| (parent, i)); + collect(n, parent, 0, &mut barrier, &mut pieces); } if pieces.is_empty() { return Err(EngineError::Other("Retype: select outlined text (paths or compound paths)".into())); @@ -219,6 +245,9 @@ fn retype(s: &mut Session, p: &Value) -> Result { // An unmatched shape between glyphs ends the line: the type after it is painted after it. let mut open = false; for (pc, ms) in pieces.iter().zip(&found) { + if pc.after_barrier { + open = false; + } // Earlier matches win ties: they are the closer fits. let best = ms.iter().enumerate().max_by_key(|(i, m)| (rank(m.face.id()), std::cmp::Reverse(*i))).map(|(_, m)| m); let Some(m) = best else { @@ -249,6 +278,8 @@ fn retype(s: &mut Session, p: &Value) -> Result { font_style: l.face.style.clone(), // The version that matched, when two of the family and style are loaded. font_version: (!l.face.version.is_empty()).then(|| l.face.version.clone()), + // Each outlined glyph was drawn on its own; a ligature would draw another shape. + features: vec!["-liga".into()], size: l.scale * l.face.units_per_em(), fill: l.appearance.fill_paint(), stroke: l.appearance.stroke_paint(), diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index af91b8442d..57cb747414 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -166,3 +166,40 @@ fn glyphs_of_different_groups_and_transparency_stay_apart() { assert_eq!(children_of(&s, b), vec![ids[1], ids[2]]); assert_eq!(s.doc().unwrap().doc.node(NodeId(ids[2])).unwrap().opacity, 0.25, "the glyph's own opacity carries over"); } + +#[test] +fn live_type_between_glyphs_ends_the_line_too() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40})); + let live = s.execute("text.create", &json!({"x": 30, "y": 90, "text": "x", "size": 60})).unwrap()["id"].as_u64().unwrap(); + s.edit("test", |d, _| { + let n = d.node(NodeId(live)).unwrap().clone(); + d.remove(NodeId(live))?; + d.insert(Some(NodeId(g)), 1, n)?; + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["A", "B"]), "{r}"); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(children_of(&s, g), vec![ids[0], live, ids[1]], "B stays over the live type"); + let t = text_of(&s, ids[0]); + assert!(t.first_style().features.iter().any(|f| f == "-liga"), "glyphs drawn one by one: no ligatures"); +} + +#[test] +fn an_open_path_along_a_glyph_is_not_a_glyph() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "I", "size": 40})); + s.edit("test", |d, _| { + let glyph = d.node(NodeId(g)).unwrap().children().unwrap()[0].id; + for sp in &mut d.node_mut(glyph).unwrap().path_data_mut().unwrap().subpaths { + sp.closed = false; + } + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + assert!(s.execute("type.retype", &json!({})).is_err(), "nothing matches"); +} From fd079ceb2956318d93905d6f4fe991069ebf3e96 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Wed, 18 Nov 2026 09:04:12 +0530 Subject: [PATCH 06/15] M7/G4: retype carries a line break across selected objects (#4934) A selected object that yields no shape between two selected glyphs (live type, an open path) ends the line, as it does inside a group. Tests for that and for glyphs selected inside different groups. --- crates/engine/src/cmd/retype.rs | 7 ++++- crates/engine/src/cmd/retype_tests.rs | 37 +++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index 72ab30a711..8634ca356e 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -215,13 +215,18 @@ fn retype(s: &mut Session, p: &Value) -> Result { let d = &s.doc()?.doc; let mut pieces = vec![]; let mut last: Option<(Option, usize)> = None; + // Carried across roots: a selected root that yields no shape (live type, an open path) still + // ends the line. + let mut barrier = true; for r in &roots { let Some(n) = d.node(*r) else { continue }; let parent = d.parent_of(*r); let idx = d.position(*r).map(|(_, i, _)| i); // A root right after the last one, in the same parent, continues its lines; unselected // art between two roots is a barrier. - let mut barrier = !matches!((last, idx), (Some((p, i)), Some(j)) if p == parent && i + 1 == j); + if !matches!((last, idx), (Some((p, i)), Some(j)) if p == parent && i + 1 == j) { + barrier = true; + } last = idx.map(|i| (parent, i)); collect(n, parent, 0, &mut barrier, &mut pieces); } diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 57cb747414..266a016ea7 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -203,3 +203,40 @@ fn an_open_path_along_a_glyph_is_not_a_glyph() { s.execute("select.set", &json!({"ids": [g]})).unwrap(); assert!(s.execute("type.retype", &json!({})).is_err(), "nothing matches"); } + +#[test] +fn live_type_selected_between_loose_glyphs_still_ends_the_line() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40})); + let live = s.execute("text.create", &json!({"x": 30, "y": 90, "text": "x", "size": 60})).unwrap()["id"].as_u64().unwrap(); + let (a, b) = (children_of(&s, g)[0], children_of(&s, g)[1]); + // A, the live type and B as siblings in the layer, as Ungroup leaves them. + s.edit("test", |d, _| { + let (par, idx, _) = d.position(NodeId(g)).unwrap(); + let live_n = d.node(NodeId(live)).unwrap().clone(); + let (an, bn) = (d.node(NodeId(a)).unwrap().clone(), d.node(NodeId(b)).unwrap().clone()); + d.remove(NodeId(live))?; + d.remove(NodeId(g))?; + d.insert(par, idx, an)?; + d.insert(par, idx + 1, live_n)?; + d.insert(par, idx + 2, bn)?; + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [a, live, b]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["A", "B"]), "the selected live type between them ends the line: {r}"); +} + +#[test] +fn glyphs_selected_inside_groups_join_only_their_siblings() { + let mut s = session(); + let g1 = outlined(&mut s, json!({"x": 40, "y": 100, "text": "ab", "size": 20})); + let g2 = outlined(&mut s, json!({"x": 70, "y": 100, "text": "cd", "size": 20})); + let (a, b, c) = (children_of(&s, g1)[0], children_of(&s, g1)[1], children_of(&s, g2)[0]); + s.execute("select.set", &json!({"ids": [a, b, c]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["ab", "c"]), "a and b are siblings; c is in another group: {r}"); + let d = &s.doc().unwrap().doc; + assert!(d.node(NodeId(g2)).is_some(), "d's group stays with c's type and d in it"); +} From c42cfd23b7710d39e8aa651ef417ec209c941598 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:03:29 +0530 Subject: [PATCH 07/15] M7/G4: retype checks each line against its own layout (#4934) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Each retyped line is laid out and compared glyph by glyph with the outlines; it splits where its type would draw another glyph or the same glyph elsewhere (tracking, manual spacing, font substitutions), and a glyph its type cannot draw stays an outline. Shapes with their own opacity mask stay outlines. Shapes past the limits are reported as truncated. Glyphs of plain-shape symbols (box drawing, blocks, geometric shapes, private use) are not matched, so drawn rectangles stay art. Type › Retype is in the Type menu. --- crates/engine/src/cmd/retype.rs | 150 +++++++++++++++++++++----- crates/engine/src/cmd/retype_tests.rs | 59 ++++++++++ crates/text/src/retype.rs | 23 +++- crates/ui-egui/src/menus/tree.rs | 1 + 4 files changed, 204 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index 8634ca356e..2c19ae10a5 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -38,7 +38,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 and stroke, in one undo step; shapes that match no font stay as they are → {ids (the new type), texts, fonts: [{family, style, size}], unmatched: [id…]}; an error when no shape matches", + "{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 splits where its type would not draw the outlines' glyphs in their places (tracking, manual spacing, 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}], 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 )] @@ -58,13 +58,17 @@ struct Piece { /// The shape's own transparency, which the new type takes. opacity: f32, blend: vectorcraft_color::BlendMode, + /// The shape has an opacity mask of its own, which type cannot take: it stays an outline. + masked: bool, } /// The shapes in `n` (held by `parent`), in paint order. `barrier` is set when art that is not a /// shape lies before the next one; it starts set for a root that does not follow the last root. -fn collect(n: &Node, parent: Option, depth: usize, barrier: &mut bool, out: &mut Vec) { +/// `truncated` is set when shapes past [`MAX_PIECES`] or [`MAX_DEPTH`] were left out. +fn collect(n: &Node, parent: Option, depth: usize, barrier: &mut bool, truncated: &mut bool, out: &mut Vec) { if out.len() >= MAX_PIECES || depth > MAX_DEPTH { *barrier = true; + *truncated = true; return; } let piece = |path: BezPath, after_barrier: bool| Piece { @@ -75,11 +79,12 @@ fn collect(n: &Node, parent: Option, depth: usize, barrier: &mut bool, o appearance: (*n.appearance).clone(), opacity: n.opacity, blend: n.blend, + masked: n.extras().mask.is_some(), }; match &n.kind { NodeKind::Group { children, clip: false } => { for c in children { - collect(c, Some(n.id), depth + 1, barrier, out); + collect(c, Some(n.id), depth + 1, barrier, truncated, out); } } // Only closed shapes can be glyphs: an open path stroked along a glyph's outline is not one. @@ -129,6 +134,8 @@ fn candidate_faces(db: &FontDb, d: &Document, fonts: &[String]) -> Vec, + /// What each piece matched, as `pieces`. + matches: Vec, text: String, face: Arc, scale: f64, @@ -175,8 +182,110 @@ impl Line { } self.text.push(m.ch); self.pieces.push(id); + self.matches.push(m.clone()); self.end = m.origin + dir * (m.face.advance(m.gid) * m.scale); } + + /// The line of this one's glyphs `from..to`, with its group, paint and transparency. + fn part(&self, from: usize, to: usize) -> Option { + let (ids, ms) = (self.pieces.get(from..to)?, self.matches.get(from..to)?); + let (first, m) = (ids.first()?, ms.first()?); + let dir = Vec2::new(m.angle.cos(), m.angle.sin()); + let mut l = Line { + pieces: vec![*first], + matches: vec![m.clone()], + text: m.ch.to_string(), + face: m.face.clone(), + scale: m.scale, + angle: m.angle, + origin: m.origin, + end: m.origin + dir * (m.face.advance(m.gid) * m.scale), + appearance: self.appearance.clone(), + parent: self.parent, + opacity: self.opacity, + blend: self.blend, + }; + for (id, m) in ids.iter().zip(ms).skip(1) { + l.push(*id, m); + } + Some(l) + } + + /// The point type that sets this line. + fn text_object(&self, system_layout: bool) -> TextObject { + let style = CharStyle { + font_family: self.face.family.clone(), + font_style: self.face.style.clone(), + // The version that matched, when two of the family and style are loaded. + font_version: (!self.face.version.is_empty()).then(|| self.face.version.clone()), + // Each outlined glyph was drawn on its own; a ligature would draw another shape. + features: vec!["-liga".into()], + size: self.scale * self.face.units_per_em(), + fill: self.appearance.fill_paint(), + stroke: self.appearance.stroke_paint(), + stroke_width: self.appearance.stroke_width(), + ..Default::default() + }; + let mut t = TextObject::point(self.origin, &self.text, style); + if self.angle != 0.0 { + t.xf *= kurbo::Affine::rotate(self.angle); + } + t.para = super::create::new_type_para(); + t.system_layout = system_layout; + super::typecmd::refresh_bounds(&mut t); + t + } + + /// The first of this line's glyphs its type 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(&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)) + } +} + +/// `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 layouts are bounded by the number of glyphs. +fn verified(lines: Vec, system_layout: bool, unmatched: &mut Vec) -> Vec { + let mut budget = lines.iter().map(|l| l.pieces.len() * 2 + 2).sum::(); + let mut todo: std::collections::VecDeque = lines.into(); + let mut out = vec![]; + while let Some(l) = todo.pop_front() { + if budget == 0 { + // Unchecked glyphs stay outlines. + unmatched.extend(l.pieces); + continue; + } + budget -= 1; + let n = l.pieces.len(); + match l.first_mismatch(&l.text_object(system_layout)) { + None => out.push(l), + Some(0) => { + unmatched.extend(l.pieces.first().copied()); + if let Some(rest) = l.part(1, n) { + todo.push_front(rest); + } + } + Some(k) => { + for part in [l.part(k, n), l.part(0, k)].into_iter().flatten() { + todo.push_front(part); + } + } + } + } + out } fn space_advance(face: &vectorcraft_text::FontFace) -> f64 { @@ -187,6 +296,7 @@ fn new_line(pc: &Piece, m: &GlyphMatch) -> Line { let dir = Vec2::new(m.angle.cos(), m.angle.sin()); Line { pieces: vec![pc.id], + matches: vec![m.clone()], text: m.ch.to_string(), face: m.face.clone(), scale: m.scale, @@ -211,9 +321,11 @@ fn retype(s: &mut Session, p: &Value) -> Result { }; let roots = selected_roots(s)?; let db = FontDb::global(); - let (lines, unmatched) = { + let system_layout = s.doc()?.doc.setup.system_layout; + let (lines, unmatched, truncated) = { let d = &s.doc()?.doc; let mut pieces = vec![]; + let mut truncated = false; let mut last: Option<(Option, usize)> = None; // Carried across roots: a selected root that yields no shape (live type, an open path) still // ends the line. @@ -228,13 +340,13 @@ fn retype(s: &mut Session, p: &Value) -> Result { barrier = true; } last = idx.map(|i| (parent, i)); - collect(n, parent, 0, &mut barrier, &mut pieces); + collect(n, parent, 0, &mut barrier, &mut truncated, &mut pieces); } if pieces.is_empty() { return Err(EngineError::Other("Retype: select outlined text (paths or compound paths)".into())); } let index = RetypeIndex::build(db, candidate_faces(db, d, &fonts)); - let found: Vec> = pieces.iter().map(|pc| index.matches(&pc.path)).collect(); + let found: Vec> = pieces.iter().map(|pc| if pc.masked { vec![] } else { index.matches(&pc.path) }).collect(); // The face most shapes match, so a glyph several fonts share is set in the same font as // the glyphs around it. let mut votes: Vec<(u32, usize)> = vec![]; @@ -266,38 +378,19 @@ fn retype(s: &mut Session, p: &Value) -> Result { } open = true; } - (lines, unmatched) + let lines = verified(lines, system_layout, &mut unmatched); + (lines, 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 system_layout = s.doc()?.doc.setup.system_layout; let made = s.edit("Retype", |d, sel| { 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 style = CharStyle { - font_family: l.face.family.clone(), - font_style: l.face.style.clone(), - // The version that matched, when two of the family and style are loaded. - font_version: (!l.face.version.is_empty()).then(|| l.face.version.clone()), - // Each outlined glyph was drawn on its own; a ligature would draw another shape. - features: vec!["-liga".into()], - size: l.scale * l.face.units_per_em(), - fill: l.appearance.fill_paint(), - stroke: l.appearance.stroke_paint(), - stroke_width: l.appearance.stroke_width(), - ..Default::default() - }; - let mut t = TextObject::point(l.origin, &l.text, style); - if l.angle != 0.0 { - t.xf *= kurbo::Affine::rotate(l.angle); - } - t.para = super::create::new_type_para(); - t.system_layout = system_layout; - super::typecmd::refresh_bounds(&mut t); + let t = l.text_object(system_layout); let id = d.alloc_id(); let mut node = Node::new(id, NodeKind::Text(Box::new(t))); // The glyphs' own transparency (the group's, kept, still applies over it). @@ -347,6 +440,7 @@ fn retype(s: &mut Session, p: &Value) -> Result { "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.scale * l.face.units_per_em()})).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 266a016ea7..7f9cd7ac5d 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -240,3 +240,62 @@ fn glyphs_selected_inside_groups_join_only_their_siblings() { let d = &s.doc().unwrap().doc; assert!(d.node(NodeId(g2)).is_some(), "d's group stays with c's type and d in it"); } + +#[test] +fn tracked_type_splits_where_its_spacing_cannot_be_set_again() { + let mut s = session(); + let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": "abc", "size": 30})).unwrap()["id"].as_u64().unwrap(); + // Less than half a space: no whole number of spaces makes up the gap (0.4 em would be two + // spaces in this font, and the outlines cannot tell those apart from tracking). + s.execute("text.setRangeStyle", &json!({"id": id, "start": 1, "end": 3, "tracking": 50})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + 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(); + let texts: Vec = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect(); + assert_eq!(texts.concat(), "abc", "{r}"); + assert!(texts.len() > 1, "the tracked glyphs are set where the outlines are, not where untracked type puts them: {r}"); + assert_eq!(r["unmatched"], json!([])); +} + +#[test] +fn a_masked_glyph_stays_an_outline() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40})); + let a = children_of(&s, g)[0]; + s.edit("test", |d, _| { + let art = vectorcraft_doc::Node::path(d.alloc_id(), vectorcraft_geom::PathData::default(), Default::default()); + d.node_mut(NodeId(a)).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(art, true))); + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["B"]), "{r}"); + assert_eq!(r["unmatched"], json!([a])); + assert!(s.doc().unwrap().doc.node(NodeId(a)).unwrap().extras().mask.is_some(), "A keeps its mask"); +} + +#[test] +fn shapes_past_the_limits_are_reported_as_left_out() { + let mut s = session(); + let top = outlined(&mut s, json!({"x": 40, "y": 100, "text": "A", "size": 40})); + let deep = outlined(&mut s, json!({"x": 40, "y": 200, "text": "B", "size": 40})); + // B, deeper than Retype looks. + s.edit("test", |d, _| { + let (par, idx, _) = d.position(NodeId(deep)).unwrap(); + let mut n = d.node(NodeId(deep)).unwrap().clone(); + d.remove(NodeId(deep))?; + for _ in 0..20 { + n = vectorcraft_doc::Node::group(d.alloc_id(), vec![std::sync::Arc::new(n)]); + } + let wrapper = n.id.0; + d.insert(par, idx, n)?; + Ok(wrapper) + }) + .map(|w| s.execute("select.set", &json!({"ids": [top, w]})).unwrap()) + .unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["A"])); + assert_eq!(r["truncated"], json!(true), "{r}"); +} diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index 5a1894e2d0..c014951008 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -98,7 +98,7 @@ impl RetypeIndex { // One entry per glyph, under the lowest character that maps to it. let mut by_gid: HashMap = HashMap::new(); for &(c, gid) in face.mapped_chars().iter().take(MAX_GLYPHS_PER_FACE) { - if c.is_whitespace() || c.is_control() { + if c.is_whitespace() || c.is_control() || is_shape_symbol(c) { continue; } by_gid.entry(gid).and_modify(|e| *e = (*e).min(c)).or_insert(c); @@ -179,6 +179,16 @@ impl RetypeIndex { } } +/// Characters whose glyphs are plain shapes (box drawing, blocks, geometric shapes, legacy +/// computing symbols) or a font's own icons (private use): a drawn rectangle or circle is the same +/// shape as one of them, so matching them would turn art into text. They are not matched. +fn is_shape_symbol(c: char) -> bool { + matches!( + u32::from(c), + 0x2500..=0x25FF | 0x2B00..=0x2BFF | 0x1F780..=0x1F7FF | 0x1FB00..=0x1FBFF | 0xE000..=0xF8FF | 0xF0000..=0x10FFFF + ) +} + /// Complex multiply: `z` (a scaled turn) applied to `p`. fn mul(z: (f64, f64), p: Point) -> Point { Point::new(z.0 * p.x - z.1 * p.y, z.1 * p.x + z.0 * p.y) @@ -367,6 +377,17 @@ mod tests { assert!(fit(&a, &b).is_none_or(|(_, r)| r > TOLERANCE)); } + #[test] + fn plain_shape_symbols_are_not_matched() { + // A block element (U+1FB89) drew as a rectangle and took a drawn rectangle for it. + for c in ['\u{1FB89}', '\u{25A0}', '\u{2588}', '\u{E000}'] { + assert!(is_shape_symbol(c), "{c:?}"); + } + for c in ['A', 'l', '-', '\u{6F22}', '\u{0915}'] { + assert!(!is_shape_symbol(c), "{c:?}"); + } + } + #[test] fn degenerate_and_hostile_shapes_give_none() { assert!(signature(&BezPath::new()).is_none()); diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index 19088a259a..7f5acd6e51 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -471,6 +471,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { ), Sep, c("Create Outlines", "type.createOutlines"), + c("Retype", "type.retype"), c("Scale Text Attributes", "type.scaleTextAttributes"), c("Optical Margin Alignment", "type.opticalMarginAlignment"), Sep, From 5ed13b1249aad6914153ef892ae21402c1be54c9 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:20:55 +0530 Subject: [PATCH 08/15] M7/G4: retype keeps outlines whose paint type cannot take (#4934) Shapes with more than a basic appearance (several fills or strokes, effects, item transparency, brushes, width profiles, arrowheads) stay outlines. The stroke's caps, joins, miter limit, dashes and alignment carry over. A line's glyphs share one size and turn exactly, and a first glyph its line cannot draw is tried on its own. --- crates/engine/src/cmd/retype.rs | 37 +++++++++++++++++++-------- crates/engine/src/cmd/retype_tests.rs | 20 +++++++++++++++ 2 files changed, 47 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index 2c19ae10a5..be7df50d95 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -58,8 +58,9 @@ struct Piece { /// The shape's own transparency, which the new type takes. opacity: f32, blend: vectorcraft_color::BlendMode, - /// The shape has an opacity mask of its own, which type cannot take: it stays an outline. - masked: bool, + /// The shape has what type cannot take (its own opacity mask, more than one fill or stroke, + /// effects, a brush, width profile or arrowheads): it stays an outline. + keeps_outline: bool, } /// The shapes in `n` (held by `parent`), in paint order. `barrier` is set when art that is not a @@ -79,7 +80,7 @@ fn collect(n: &Node, parent: Option, depth: usize, barrier: &mut bool, t appearance: (*n.appearance).clone(), opacity: n.opacity, blend: n.blend, - masked: n.extras().mask.is_some(), + keeps_outline: n.extras().mask.is_some() || !type_can_paint(&n.appearance), }; match &n.kind { NodeKind::Group { children, clip: false } => { @@ -107,6 +108,12 @@ fn collect(n: &Node, parent: Option, depth: usize, barrier: &mut bool, t } } +/// Can type's character style paint `ap` as it is: a basic appearance (at most one fill and one +/// stroke, no effects, no item opacity or blend), with a plain stroke? +fn type_can_paint(ap: &Appearance) -> bool { + ap.is_basic() && ap.stroke().is_none_or(|s| s.start_arrow.is_none() && s.end_arrow.is_none() && s.profile.is_none() && s.brush.is_none()) +} + /// The faces to match against: the families in `fonts`, the document's fonts, then every loaded face. fn candidate_faces(db: &FontDb, d: &Document, fonts: &[String]) -> Vec> { let mut families: Vec = fonts.iter().take(MAX_FONT_PARAMS).cloned().collect(); @@ -165,8 +172,9 @@ impl Line { && pc.opacity == self.opacity && pc.blend == self.blend && m.face.id() == self.face.id() - && (m.scale - self.scale).abs() <= self.scale * 0.005 - && (m.angle - self.angle).abs() < 1e-3 + // One size and turn for the whole line: the type sets every glyph at the first one's. + && (m.scale - self.scale).abs() <= self.scale * 1e-4 + && (m.angle - self.angle).abs() < 1e-5 && across < size * 0.05 && (m.origin - self.end).dot(dir) > -size * 0.25 } @@ -226,6 +234,14 @@ impl Line { stroke_width: self.appearance.stroke_width(), ..Default::default() }; + let mut style = style; + if let Some(st) = self.appearance.stroke() { + style.stroke_cap = st.cap; + style.stroke_join = st.join; + style.stroke_miter_limit = st.miter_limit; + style.stroke_dash = st.dash.clone(); + style.stroke_align = st.align; + } let mut t = TextObject::point(self.origin, &self.text, style); if self.angle != 0.0 { t.xf *= kurbo::Affine::rotate(self.angle); @@ -272,12 +288,13 @@ fn verified(lines: Vec, system_layout: bool, unmatched: &mut Vec) let n = l.pieces.len(); match l.first_mismatch(&l.text_object(system_layout)) { None => out.push(l), - Some(0) => { - unmatched.extend(l.pieces.first().copied()); - if let Some(rest) = l.part(1, n) { - todo.push_front(rest); + // The first glyph on its own may still be drawn as it was (a contextual form changed it). + Some(0) if n > 1 => { + for part in [l.part(1, n), l.part(0, 1)].into_iter().flatten() { + todo.push_front(part); } } + Some(0) => unmatched.extend(l.pieces.first().copied()), Some(k) => { for part in [l.part(k, n), l.part(0, k)].into_iter().flatten() { todo.push_front(part); @@ -346,7 +363,7 @@ fn retype(s: &mut Session, p: &Value) -> Result { return Err(EngineError::Other("Retype: select outlined text (paths or compound paths)".into())); } let index = RetypeIndex::build(db, candidate_faces(db, d, &fonts)); - let found: Vec> = pieces.iter().map(|pc| if pc.masked { vec![] } else { index.matches(&pc.path) }).collect(); + let found: Vec> = pieces.iter().map(|pc| if pc.keeps_outline { vec![] } else { index.matches(&pc.path) }).collect(); // The face most shapes match, so a glyph several fonts share is set in the same font as // the glyphs around it. let mut votes: Vec<(u32, usize)> = vec![]; diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 7f9cd7ac5d..4c331720a1 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -299,3 +299,23 @@ fn shapes_past_the_limits_are_reported_as_left_out() { assert_eq!(r["texts"], json!(["A"])); assert_eq!(r["truncated"], json!(true), "{r}"); } + +#[test] +fn a_glyph_painted_beyond_what_type_takes_stays_an_outline() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40})); + let a = children_of(&s, g)[0]; + s.edit("test", |d, _| { + let n = d.node_mut(NodeId(a)).unwrap(); + let mut ap = (*n.appearance).clone(); + let fill = ap.items.iter().find(|i| i.is_fill()).unwrap().clone(); + ap.items.push(fill); + n.appearance = ap.into(); + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["B"]), "two fills: A stays an outline: {r}"); + assert_eq!(r["unmatched"], json!([a])); +} From 783437f7754e7bc1084e52af6008e29c1c0fa08a Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:58:41 +0530 Subject: [PATCH 09/15] M7/G4: retype review: hidden art, compositing, half turns, cost (#4934) Hidden and locked shapes stay outlines and end the line. Isolated and knockout groups keep their type inside. Type turned 180 degrees stays one object (angles compared wrapped). A lone one-contour glyph beside other shapes stays an outline unless it is the only shape selected. The index samples only glyphs whose key (segments per contour) a selected shape has, reads outlines past the shared outline cache, keeps each face's keys once worked out, and loads no more faces than it takes. With Microsoft YaHei (29,905 glyphs) loaded: 877 ms the first time, 23 ms after. --- crates/engine/src/cmd/retype.rs | 44 +++++++++-- crates/engine/src/cmd/retype_tests.rs | 104 ++++++++++++++++++++++++-- crates/text/src/fontdb/lookup.rs | 12 +++ crates/text/src/retype.rs | 90 ++++++++++++++++++---- 4 files changed, 222 insertions(+), 28 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index be7df50d95..28a74ac6a9 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -14,6 +14,7 @@ //! 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; use kurbo::{BezPath, Point, Vec2}; @@ -72,6 +73,11 @@ fn collect(n: &Node, parent: Option, depth: usize, barrier: &mut bool, t *truncated = true; return; } + // Hidden and locked art is left as it is: a hidden glyph must not come back as visible type. + if !n.visible || n.locked { + *barrier = true; + return; + } let piece = |path: BezPath, after_barrier: bool| Piece { id: n.id, parent, @@ -126,15 +132,20 @@ fn candidate_faces(db: &FontDb, d: &Document, fonts: &[String]) -> Vec= cap { + break 'families; + } if let Some(face) = db.face(f, &style) { faces.push(face); } } } - faces.extend(db.loaded_faces()); + faces.extend(db.loaded_faces().into_iter().take(cap.saturating_sub(faces.len()))); faces } @@ -174,7 +185,8 @@ impl Line { && m.face.id() == self.face.id() // One size and turn for the whole line: the type sets every glyph at the first one's. && (m.scale - self.scale).abs() <= self.scale * 1e-4 - && (m.angle - self.angle).abs() < 1e-5 + // Wrapped: type turned 180° has angles near +π and −π. + && ((m.angle - self.angle + PI).rem_euclid(TAU) - PI).abs() < 1e-5 && across < size * 0.05 && (m.origin - self.end).dot(dir) > -size * 0.25 } @@ -362,7 +374,11 @@ fn retype(s: &mut Session, p: &Value) -> Result { if pieces.is_empty() { return Err(EngineError::Other("Retype: select outlined text (paths or compound paths)".into())); } - let index = RetypeIndex::build(db, candidate_faces(db, d, &fonts)); + // Only glyphs with a selected shape's key (segments per contour) can match one: the others are + // not sampled. + let wanted: std::collections::BTreeSet> = + pieces.iter().filter(|pc| !pc.keeps_outline).filter_map(|pc| vectorcraft_text::retype::shape_key(&pc.path)).collect(); + let index = RetypeIndex::build(db, candidate_faces(db, d, &fonts), &wanted); let found: Vec> = pieces.iter().map(|pc| if pc.keeps_outline { vec![] } else { index.matches(&pc.path) }).collect(); // The face most shapes match, so a glyph several fonts share is set in the same font as // the glyphs around it. @@ -395,7 +411,19 @@ fn retype(s: &mut Session, p: &Value) -> Result { } open = true; } - let lines = verified(lines, system_layout, &mut unmatched); + let mut lines = verified(lines, system_layout, &mut unmatched); + // A lone one-contour glyph (a period, a hyphen, a bullet) is too plain to tell from drawn + // art (a dot, a bar): beside other shapes it stays an outline. Selected on its own, it is + // what was asked for. + if pieces.len() > 1 { + lines.retain(|l| { + let lone = matches!(l.matches.as_slice(), [m] if m.contours == 1); + if lone { + unmatched.extend(l.pieces.iter().copied()); + } + !lone + }); + } (lines, unmatched, truncated) }; if lines.is_empty() { @@ -434,7 +462,11 @@ fn retype(s: &mut Session, p: &Value) -> Result { && n.blend == vectorcraft_color::BlendMode::Normal && *n.appearance == Appearance::default() && n.name.is_none() - && n.extras().mask.is_none(); + && n.extras().mask.is_none() + // Isolation and knockout change how the group composites its type. + && !n.isolate + && n.knockout == vectorcraft_doc::Knockout::default() + && !n.knockout_shape; let only_type = children.iter().all(|c| ids.contains(&c.id)); if children.is_empty() { d.remove(g)?; diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 4c331720a1..cbbf1e0302 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -148,7 +148,7 @@ fn a_shape_between_glyphs_ends_the_line_so_paint_order_holds() { fn glyphs_of_different_groups_and_transparency_stay_apart() { let mut s = session(); let a = outlined(&mut s, json!({"x": 40, "y": 100, "text": "ab", "size": 20})); - let b = outlined(&mut s, json!({"x": 120, "y": 100, "text": "cd", "size": 20})); + let b = outlined(&mut s, json!({"x": 120, "y": 100, "text": "ed", "size": 20})); let first_d = children_of(&s, b)[1]; s.edit("test", |d, _| { d.node_mut(NodeId(b)).unwrap().opacity = 0.5; @@ -158,7 +158,7 @@ fn glyphs_of_different_groups_and_transparency_stay_apart() { .unwrap(); s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); let r = s.execute("type.retype", &json!({})).unwrap(); - assert_eq!(r["texts"], json!(["ab", "c", "d"]), "same baseline, other group; d has its own opacity: {r}"); + assert_eq!(r["texts"], json!(["ab", "e", "d"]), "same baseline, other group; d has its own opacity: {r}"); let ids: Vec = r["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); let d = &s.doc().unwrap().doc; assert!(d.node(NodeId(a)).is_none(), "a plain group gives way to its type"); @@ -232,11 +232,11 @@ fn live_type_selected_between_loose_glyphs_still_ends_the_line() { fn glyphs_selected_inside_groups_join_only_their_siblings() { let mut s = session(); let g1 = outlined(&mut s, json!({"x": 40, "y": 100, "text": "ab", "size": 20})); - let g2 = outlined(&mut s, json!({"x": 70, "y": 100, "text": "cd", "size": 20})); + let g2 = outlined(&mut s, json!({"x": 70, "y": 100, "text": "ed", "size": 20})); let (a, b, c) = (children_of(&s, g1)[0], children_of(&s, g1)[1], children_of(&s, g2)[0]); s.execute("select.set", &json!({"ids": [a, b, c]})).unwrap(); let r = s.execute("type.retype", &json!({})).unwrap(); - assert_eq!(r["texts"], json!(["ab", "c"]), "a and b are siblings; c is in another group: {r}"); + assert_eq!(r["texts"], json!(["ab", "e"]), "a and b are siblings; e is in another group: {r}"); let d = &s.doc().unwrap().doc; assert!(d.node(NodeId(g2)).is_some(), "d's group stays with c's type and d in it"); } @@ -244,7 +244,7 @@ fn glyphs_selected_inside_groups_join_only_their_siblings() { #[test] fn tracked_type_splits_where_its_spacing_cannot_be_set_again() { let mut s = session(); - let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": "abc", "size": 30})).unwrap()["id"].as_u64().unwrap(); + let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": "abe", "size": 30})).unwrap()["id"].as_u64().unwrap(); // Less than half a space: no whole number of spaces makes up the gap (0.4 em would be two // spaces in this font, and the outlines cannot tell those apart from tracking). s.execute("text.setRangeStyle", &json!({"id": id, "start": 1, "end": 3, "tracking": 50})).unwrap(); @@ -253,7 +253,7 @@ fn tracked_type_splits_where_its_spacing_cannot_be_set_again() { s.execute("select.set", &json!({"ids": [g]})).unwrap(); let r = s.execute("type.retype", &json!({})).unwrap(); let texts: Vec = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect(); - assert_eq!(texts.concat(), "abc", "{r}"); + assert_eq!(texts.concat(), "abe", "{r}"); assert!(texts.len() > 1, "the tracked glyphs are set where the outlines are, not where untracked type puts them: {r}"); assert_eq!(r["unmatched"], json!([])); } @@ -319,3 +319,95 @@ fn a_glyph_painted_beyond_what_type_takes_stays_an_outline() { assert_eq!(r["texts"], json!(["B"]), "two fills: A stays an outline: {r}"); assert_eq!(r["unmatched"], json!([a])); } + +#[test] +fn a_hidden_or_locked_glyph_stays_an_outline() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "ABD", "size": 40})); + let k = children_of(&s, g); + s.edit("test", |d, _| { + d.node_mut(NodeId(k[0])).unwrap().visible = false; + d.node_mut(NodeId(k[2])).unwrap().locked = true; + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["B"]), "{r}"); + let d = &s.doc().unwrap().doc; + assert!(!d.node(NodeId(k[0])).unwrap().visible, "A stays a hidden outline"); + assert!(d.node(NodeId(k[2])).unwrap().locked, "D stays a locked outline"); +} + +#[test] +fn an_isolated_or_knockout_group_keeps_its_type_inside() { + for knock in [false, true] { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40})); + s.edit("test", |d, _| { + let n = d.node_mut(NodeId(g)).unwrap(); + if knock { + n.knockout = vectorcraft_doc::Knockout::On; + } else { + n.isolate = true; + } + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + let id = r["ids"][0].as_u64().unwrap(); + assert_eq!(children_of(&s, g), vec![id], "knockout {knock}: the group stays, holding the type"); + } +} + +#[test] +fn type_turned_half_round_stays_one_object() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 300, "y": 200, "text": "Upside", "size": 30, "rotation": 180})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["Upside"]), "{r}"); +} + +#[test] +fn a_drawn_dot_or_bar_beside_type_stays_art() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40})); + let dot = s.execute("shape.ellipse", &json!({"x": 300, "y": 60, "width": 8, "height": 8})).unwrap()["id"].as_u64().unwrap(); + // A bar that is exactly a hyphen of the font, somewhere else: the worst case. + let bar = outlined(&mut s, json!({"x": 200, "y": 300, "text": "-", "size": 50})); + s.execute("select.set", &json!({"ids": [g, dot, bar]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["AB"]), "{r}"); + let un = r["unmatched"].as_array().unwrap(); + assert!(un.contains(&json!(dot)) && un.len() == 2, "the dot and the bar stay art: {r}"); + // Selected on its own, the hyphen is what was asked for. + s.execute("select.set", &json!({"ids": [bar]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["-"]), "{r}"); +} + +/// How long Retype takes with a large CJK face to match against (run with `--ignored +/// --nocapture`; skips when no such face is installed). Not a pass/fail budget: it prints. +#[test] +#[ignore = "timing: needs an installed CJK font"] +fn timing_with_a_large_cjk_face() { + let db = vectorcraft_text::FontDb::global(); + let Some(family) = ["Microsoft YaHei", "Yu Gothic", "MS Gothic", "Noto Sans CJK JP", "Hiragino Sans"].into_iter().find(|f| db.has_family(f)) + else { + eprintln!("skipped: no large CJK font installed"); + return; + }; + let face = db.resolve(family, "Regular").map(|(f, _)| f).unwrap(); + let mut s = session(); + let g = outlined(&mut s, json!({"x": 20, "y": 80, "text": "漢字のテスト ABC", "size": 24, "font": family, "style": face.style})); + for run in ["cold", "warm"] { + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let t0 = std::time::Instant::now(); + let r = s.execute("type.retype", &json!({"fonts": [family]})).unwrap(); + let ms = t0.elapsed().as_secs_f64() * 1000.0; + eprintln!("{run}: Retype with {family} ({} encoded glyphs) loaded: {ms:.0} ms → {}", face.mapped_chars().len(), r["texts"]); + s.execute("edit.undo", &json!({})).unwrap(); + } +} diff --git a/crates/text/src/fontdb/lookup.rs b/crates/text/src/fontdb/lookup.rs index ef394cb079..99844220f5 100644 --- a/crates/text/src/fontdb/lookup.rs +++ b/crates/text/src/fontdb/lookup.rs @@ -675,6 +675,18 @@ impl FontDb { p } + /// [`Self::outline`] without the cache: for reading many glyphs once (Retype's index), which + /// would otherwise push out the outlines the canvas keeps there. + pub fn outline_uncached(&self, face: &FontFace, gid: u32) -> BezPath { + let mut pen = FlipPen(BezPath::new()); + if let Some(f) = face.skrifa() + && let Some(g) = f.outline_glyphs().get(GlyphId::new(gid)) + { + let _ = g.draw(DrawSettings::unhinted(Size::unscaled(), face.location()), &mut pen); + } + pen.0 + } + /// Glyph `gid`'s colour bitmap (`sbix`, `CBDT`) in `face`, cached per (face, glyph). pub fn glyph_image(&self, face: &FontFace, gid: u32) -> Option> { if !face.colour_bitmaps { diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index c014951008..30a640c3c7 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -49,6 +49,8 @@ pub struct GlyphMatch { pub origin: Point, /// The leftover distance, relative to the shape's spread. pub residual: f64, + /// How many contours the glyph has. + pub contours: usize, } /// A shape reduced for matching: points along each contour, centred. @@ -79,8 +81,11 @@ pub struct RetypeIndex { } impl RetypeIndex { - /// Index the outline glyphs of `faces` (the first [`MAX_FACES`], each face once). - pub fn build(db: &FontDb, faces: impl IntoIterator>) -> Self { + /// Index the outline glyphs of `faces` (the first [`MAX_FACES`], each face once) that have one + /// of the shape keys in `keys` (the selected shapes' [`shape_key`]s): the others could match no + /// shape, so they are not sampled. Outlines are read past the shared outline + /// cache, which keeps the canvas's glyphs. + pub fn build(db: &FontDb, faces: impl IntoIterator>, keys: &std::collections::BTreeSet>) -> Self { let mut kept: Vec> = vec![]; for f in faces { if kept.len() >= MAX_FACES { @@ -95,22 +100,16 @@ impl RetypeIndex { if entries.len() >= MAX_GLYPHS { break; } - // One entry per glyph, under the lowest character that maps to it. - let mut by_gid: HashMap = HashMap::new(); - for &(c, gid) in face.mapped_chars().iter().take(MAX_GLYPHS_PER_FACE) { - if c.is_whitespace() || c.is_control() || is_shape_symbol(c) { - continue; - } - by_gid.entry(gid).and_modify(|e| *e = (*e).min(c)).or_insert(c); - } - let mut gids: Vec<(u32, char)> = by_gid.into_iter().collect(); - gids.sort_unstable(); - for (gid, ch) in gids { - // The budget holds inside a face too: no glyph is loaded past it. + for (gid, ch, key) in face_keys(db, face).iter() { + // The budget holds inside a face too: no glyph is sampled past it. if entries.len() >= MAX_GLYPHS { break; } - let outline = db.outline(face, gid); + if !keys.contains(key) { + continue; + } + let (gid, ch) = (*gid, *ch); + let outline = db.outline_uncached(face, gid); if let Some(sig) = signature(&outline) { entries.push(Entry { face: fi, gid, ch, sig }); } @@ -165,7 +164,16 @@ impl RetypeIndex { // The glyph's origin is (0, 0) in font units: it lands at centre − z·glyph centre. let gc = mul(z, e.sig.centre); let origin = Point::new(sig.centre.x - gc.x, sig.centre.y - gc.y); - let m = GlyphMatch { face: face.clone(), gid: e.gid, ch: e.ch, scale: z.0.hypot(z.1), angle: z.1.atan2(z.0), origin, residual }; + let m = GlyphMatch { + face: face.clone(), + gid: e.gid, + ch: e.ch, + scale: z.0.hypot(z.1), + angle: z.1.atan2(z.0), + origin, + residual, + contours: e.sig.contours, + }; match best.get(&e.face) { Some(b) if b.residual < m.residual || (b.residual == m.residual && b.ch <= m.ch) => {} _ => { @@ -179,6 +187,41 @@ impl RetypeIndex { } } +/// A face's glyphs as the index looks them up: (glyph, character, [`shape_key`]), one per glyph +/// under the lowest character that maps to it. +type FaceKeys = Arc)>>; + +/// How many faces' keys [`face_keys`] keeps. +const KEPT_FACE_KEYS: usize = 32; + +/// [`FaceKeys`] of `face`, worked out once per face (each glyph drawn once, past the outline +/// cache) and kept: a later Retype samples only the glyphs whose key a selected shape has. +fn face_keys(db: &FontDb, face: &FontFace) -> FaceKeys { + type Kept = std::sync::Mutex>; + static KEPT: std::sync::OnceLock = std::sync::OnceLock::new(); + let kept = KEPT.get_or_init(Default::default); + let at = (db.id(), face.id()); + if let Some(k) = kept.lock().unwrap_or_else(|e| e.into_inner()).get(&at) { + return k.clone(); + } + let mut by_gid: HashMap = HashMap::new(); + for &(c, gid) in face.mapped_chars().iter().take(MAX_GLYPHS_PER_FACE) { + if c.is_whitespace() || c.is_control() || is_shape_symbol(c) { + continue; + } + by_gid.entry(gid).and_modify(|e| *e = (*e).min(c)).or_insert(c); + } + let mut gids: Vec<(u32, char)> = by_gid.into_iter().collect(); + gids.sort_unstable(); + let keys: FaceKeys = Arc::new(gids.into_iter().filter_map(|(gid, ch)| Some((gid, ch, shape_key(&db.outline_uncached(face, gid))?))).collect()); + let mut kept = kept.lock().unwrap_or_else(|e| e.into_inner()); + if kept.len() >= KEPT_FACE_KEYS { + kept.clear(); + } + kept.insert(at, keys.clone()); + keys +} + /// Characters whose glyphs are plain shapes (box drawing, blocks, geometric shapes, legacy /// computing symbols) or a font's own icons (private use): a drawn rectangle or circle is the same /// shape as one of them, so matching them would turn art into text. They are not matched. @@ -266,6 +309,21 @@ fn contours(path: &BezPath) -> Option>> { (out.len() <= MAX_CONTOURS).then_some(out) } +/// How many contours with length `path` has, as matching counts them; `None` past the size caps. +/// A cheap key two shapes share when one is the other scaled, turned and moved: how many segments +/// each of its contours has, in order (segments that go nowhere left out, a closing line counted +/// once whether the path draws it or closes onto it). Glyphs whose key no selected shape has are +/// not sampled. `None` past the size caps. +pub fn shape_key(path: &BezPath) -> Option> { + let moves = |s: &PathSeg| match s { + PathSeg::Line(l) => l.p0 != l.p1, + PathSeg::Quad(q) => q.p0 != q.p1 || q.p1 != q.p2, + PathSeg::Cubic(c) => c.p0 != c.p1 || c.p1 != c.p2 || c.p2 != c.p3, + }; + let key: Vec = contours(path)?.iter().map(|c| c.iter().filter(|s| moves(s)).count()).filter(|n| *n > 0).collect(); + (!key.is_empty()).then_some(key) +} + fn signature(path: &BezPath) -> Option { let bounds = path.bounding_box(); let size = bounds.width().hypot(bounds.height()); From 06e8ce62b950128190951d135b68bea6141faa32 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:07:47 +0530 Subject: [PATCH 10/15] M7/G4: retype matching reads contours as drawn, checks whole outlines (#4934) Contours are read from a starting corner that does not depend on where the path starts (every tied corner tried), with straight edges split in two, degenerate curves and empty segments read as one line. A sampled fit only shortlists a glyph: its whole outline, turned onto the shape, must lie on it. Face keys are compact hashes, kept per process within a budget; kept keys stay when new ones do not fit, and go when fonts are added or rescanned. A compound path with a locked or hidden part stays whole. A group with an Attributes note, or any other extra, keeps its type inside. Faces are counted once against the cap, and no font is read when every shape stays an outline. --- crates/engine/src/cmd/retype.rs | 28 +- crates/engine/src/cmd/retype_tests.rs | 46 +++ crates/text/src/retype.rs | 434 +++++++++++++++++++++----- 3 files changed, 417 insertions(+), 91 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index 28a74ac6a9..df0d88a489 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -100,7 +100,8 @@ fn collect(n: &Node, parent: Option, depth: usize, barrier: &mut bool, t let mut path = BezPath::new(); for c in children { match &c.kind { - NodeKind::Path { path: p, .. } if p.is_closed() => path.extend(p.to_bezpath()), + // A hidden or locked path keeps its whole compound as it is. + NodeKind::Path { path: p, .. } if p.is_closed() && c.visible && !c.locked => path.extend(p.to_bezpath()), _ => { *barrier = true; return; @@ -140,12 +141,21 @@ fn candidate_faces(db: &FontDb, d: &Document, fonts: &[String]) -> Vec= cap { break 'families; } - if let Some(face) = db.face(f, &style) { + if let Some(face) = db.face(f, &style) + && !faces.iter().any(|k: &Arc| k.id() == face.id()) + { faces.push(face); } } } - faces.extend(db.loaded_faces().into_iter().take(cap.saturating_sub(faces.len()))); + for face in db.loaded_faces() { + if faces.len() >= cap { + break; + } + if !faces.iter().any(|k| k.id() == face.id()) { + faces.push(face); + } + } faces } @@ -376,9 +386,10 @@ fn retype(s: &mut Session, p: &Value) -> Result { } // Only glyphs with a selected shape's key (segments per contour) can match one: the others are // not sampled. - let wanted: std::collections::BTreeSet> = + let wanted: std::collections::BTreeSet = pieces.iter().filter(|pc| !pc.keeps_outline).filter_map(|pc| vectorcraft_text::retype::shape_key(&pc.path)).collect(); - let index = RetypeIndex::build(db, candidate_faces(db, d, &fonts), &wanted); + // Nothing to match (every shape stays an outline): no font is read. + let index = if wanted.is_empty() { RetypeIndex::default() } else { RetypeIndex::build(db, candidate_faces(db, d, &fonts), &wanted) }; let found: Vec> = pieces.iter().map(|pc| if pc.keeps_outline { vec![] } else { index.matches(&pc.path) }).collect(); // The face most shapes match, so a glyph several fonts share is set in the same font as // the glyphs around it. @@ -462,7 +473,12 @@ fn retype(s: &mut Session, p: &Value) -> Result { && n.blend == vectorcraft_color::BlendMode::Normal && *n.appearance == Appearance::default() && n.name.is_none() - && n.extras().mask.is_none() + // Its mask, Attributes note and the rest of what few objects have stay with it. + && { + let mut ex = n.extras().clone(); + ex.type_outlines = false; + ex == vectorcraft_doc::NodeExtras::default() + } // Isolation and knockout change how the group composites its type. && !n.isolate && n.knockout == vectorcraft_doc::Knockout::default() diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index cbbf1e0302..7812fc8e65 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -411,3 +411,49 @@ fn timing_with_a_large_cjk_face() { s.execute("edit.undo", &json!({})).unwrap(); } } + +#[test] +fn a_compound_with_a_locked_or_hidden_part_stays_whole() { + let mut s = session(); + // "B" outlines as a compound path of three contours. + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40})); + let b = children_of(&s, g)[1]; + let part = children_of(&s, b)[1]; + s.edit("test", |d, _| { + d.node_mut(NodeId(part)).unwrap().locked = true; + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["A"]), "{r}"); + let d = &s.doc().unwrap().doc; + assert!(d.node(NodeId(part)).unwrap().locked, "B's locked part, and B, stay as they are"); +} + +#[test] +fn a_group_with_an_attributes_note_keeps_its_type_inside() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40})); + s.execute("attributes.set", &json!({"ids": [g], "note": "logo, keep"})).unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + let id = r["ids"][0].as_u64().unwrap(); + assert_eq!(children_of(&s, g), vec![id], "the group and its note stay, holding the type"); +} + +#[test] +fn nothing_retypable_reads_no_font() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "A", "size": 40})); + let a = children_of(&s, g)[0]; + s.edit("test", |d, _| { + let art = vectorcraft_doc::Node::path(d.alloc_id(), vectorcraft_geom::PathData::default(), Default::default()); + d.node_mut(NodeId(a)).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(art, true))); + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let e = s.execute("type.retype", &json!({})).unwrap_err().to_string(); + assert!(e.contains("(1 checked)"), "the masked shape is reported, and no font was indexed: {e}"); +} diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index 30a640c3c7..80fed5f33a 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -1,18 +1,20 @@ //! Retype's glyph matching (Type › Retype, #4934): which glyph of which loaded font an outlined //! glyph's shape is, the same up to uniform scale, rotation and translation. //! -//! Phase 1 is exact matching only: a shape matches a glyph when, after the best similarity -//! transform (a Procrustes fit over points sampled at equal steps of arc length along each -//! contour), the leftover distance is a tiny fraction of the shape's size. That holds for outlines -//! made from a font the app has (Create Outlines' output, and other apps' that keep each glyph's -//! contours whole and in the font's order). Near matches (other versions of a font, hinted or -//! simplified outlines, faux styles, glyphs merged into one path) are left unmatched; fuzzy -//! identification is phase 2. +//! Phase 1 is exact matching only. Each contour is read from a starting corner that does not +//! depend on where the path happens to start (the corner farthest from the shape's corners' +//! centre; every such corner is tried when several tie), with straight edges split in two read as +//! one. Points sampled at equal steps of arc length along the contours shortlist the glyphs whose +//! best similarity transform (a Procrustes fit) leaves a tiny leftover distance, and the whole +//! outline, turned onto the shape, must then lie on it. That holds for outlines made from a font +//! the app has (Create Outlines' output, and other apps' that keep each glyph's contours whole and +//! in the font's order). Near matches (other versions of a font, hinted or simplified outlines, +//! faux styles, glyphs merged into one path) are left unmatched; fuzzy identification is phase 2. -use std::collections::HashMap; +use std::collections::{BTreeSet, HashMap}; use std::sync::Arc; -use kurbo::{BezPath, CubicBez, Line, ParamCurve, ParamCurveArclen, PathEl, PathSeg, Point, QuadBez, Shape}; +use kurbo::{Affine, BezPath, CubicBez, Line, ParamCurve, ParamCurveArclen, ParamCurveNearest, PathEl, PathSeg, Point, QuadBez, Shape}; use crate::{FontDb, FontFace}; @@ -28,9 +30,16 @@ pub const MAX_ELEMENTS: usize = 4096; const MAX_CONTOURS: usize = 48; /// Points sampled along each contour. const SAMPLES: usize = 32; +/// The most readings of a shape (one per choice of tied starting corners) that are tried. +const MAX_VARIANTS: usize = 64; /// The largest leftover distance (root mean square over the samples) for a match, as a fraction of /// the shape's spread about its centre. const TOLERANCE: f64 = 2e-3; +/// How far the whole outline, turned onto the shape, may lie from it (both ways), as a fraction of +/// the shape's spread. +const OUTLINE_TOLERANCE: f64 = 5e-3; +/// Points of a flattened outline past which the whole-outline check gives up (and so rejects). +const MAX_OUTLINE_POINTS: usize = 8192; /// How far apart two shapes' spread-to-length ratios may be and still be compared. const INVARIANT_SLACK: f64 = 0.02; @@ -70,9 +79,12 @@ struct Entry { gid: u32, ch: char, sig: Signature, + /// The glyph's outline in font units, for the whole-outline check. + outline: BezPath, } /// The glyphs of a set of faces, ready to match shapes against. +#[derive(Default)] pub struct RetypeIndex { faces: Vec>, entries: Vec, @@ -81,11 +93,11 @@ pub struct RetypeIndex { } impl RetypeIndex { - /// Index the outline glyphs of `faces` (the first [`MAX_FACES`], each face once) that have one - /// of the shape keys in `keys` (the selected shapes' [`shape_key`]s): the others could match no - /// shape, so they are not sampled. Outlines are read past the shared outline - /// cache, which keeps the canvas's glyphs. - pub fn build(db: &FontDb, faces: impl IntoIterator>, keys: &std::collections::BTreeSet>) -> Self { + /// Index the outline glyphs of `faces` (the first [`MAX_FACES`], each face once) whose + /// [`shape_key`] is in `keys` (the selected shapes' keys): the others could match no shape, so + /// they are not sampled. Outlines are read past the shared outline cache, which keeps the + /// canvas's glyphs. + pub fn build(db: &FontDb, faces: impl IntoIterator>, keys: &BTreeSet) -> Self { let mut kept: Vec> = vec![]; for f in faces { if kept.len() >= MAX_FACES { @@ -96,22 +108,18 @@ impl RetypeIndex { } } let mut entries = vec![]; - for (fi, face) in kept.iter().enumerate() { - if entries.len() >= MAX_GLYPHS { - break; - } - for (gid, ch, key) in face_keys(db, face).iter() { + 'faces: for (fi, face) in kept.iter().enumerate() { + for &(gid, ch, key) in face_keys(db, face).iter() { // The budget holds inside a face too: no glyph is sampled past it. if entries.len() >= MAX_GLYPHS { - break; + break 'faces; } - if !keys.contains(key) { + if !keys.contains(&key) { continue; } - let (gid, ch) = (*gid, *ch); let outline = db.outline_uncached(face, gid); - if let Some(sig) = signature(&outline) { - entries.push(Entry { face: fi, gid, ch, sig }); + if let Some(sig) = signatures(&outline, false).into_iter().next() { + entries.push(Entry { face: fi, gid, ch, sig, outline }); } } } @@ -145,10 +153,11 @@ impl RetypeIndex { /// The glyphs `shape` (in document space) is, the closest one per face, closest first; empty /// when it is no glyph of the indexed faces. pub fn matches(&self, shape: &BezPath) -> Vec { - let Some(sig) = signature(shape) else { return vec![] }; - let Some(list) = self.buckets.get(&sig.contours) else { return vec![] }; - let lo = sig.invariant * (1.0 - INVARIANT_SLACK); - let hi = sig.invariant * (1.0 + INVARIANT_SLACK); + let variants = signatures(shape, true); + let Some(first) = variants.first() else { return vec![] }; + let Some(list) = self.buckets.get(&first.contours) else { return vec![] }; + let lo = first.invariant * (1.0 - INVARIANT_SLACK); + let hi = first.invariant * (1.0 + INVARIANT_SLACK); let start = list.partition_point(|i| self.entries.get(*i).is_some_and(|e| e.sig.invariant < lo)); let mut best: HashMap = HashMap::new(); for i in list.iter().skip(start) { @@ -156,7 +165,11 @@ impl RetypeIndex { if e.sig.invariant > hi { break; } - let Some((z, residual)) = fit(&e.sig, &sig) else { continue }; + // The reading of the shape (its tied starting corners) that fits the glyph best. + let Some((sig, z, residual)) = variants.iter().filter_map(|s| fit(&e.sig, s).map(|(z, r)| (s, z, r))).min_by(|a, b| a.2.total_cmp(&b.2)) + else { + continue; + }; if residual > TOLERANCE { continue; } @@ -164,6 +177,12 @@ impl RetypeIndex { // The glyph's origin is (0, 0) in font units: it lands at centre − z·glyph centre. let gc = mul(z, e.sig.centre); let origin = Point::new(sig.centre.x - gc.x, sig.centre.y - gc.y); + // The samples can step over a detail (a notch between two of them): the whole outline, + // turned onto the shape, must lie on it. + let onto = Affine::new([z.0, z.1, -z.1, z.0, origin.x, origin.y]); + if !outlines_agree(&(onto * e.outline.clone()), shape, sig.spread * OUTLINE_TOLERANCE) { + continue; + } let m = GlyphMatch { face: face.clone(), gid: e.gid, @@ -189,20 +208,36 @@ impl RetypeIndex { /// A face's glyphs as the index looks them up: (glyph, character, [`shape_key`]), one per glyph /// under the lowest character that maps to it. -type FaceKeys = Arc)>>; +type FaceKeys = Arc>; -/// How many faces' keys [`face_keys`] keeps. -const KEPT_FACE_KEYS: usize = 32; +/// How many glyph keys [`face_keys`] keeps in all (16 bytes each). +const KEPT_KEYS: usize = 1 << 20; + +/// The faces' keys [`face_keys`] keeps, for the database generation they were read in. +#[derive(Default)] +struct KeptKeys { + generation: u64, + glyphs: usize, + faces: HashMap<(u64, u32), FaceKeys>, +} /// [`FaceKeys`] of `face`, worked out once per face (each glyph drawn once, past the outline -/// cache) and kept: a later Retype samples only the glyphs whose key a selected shape has. +/// cache) and kept: a later Retype samples only the glyphs whose key a selected shape has. Keys +/// already kept stay while new faces' keys would not fit, so a run over more faces than fit still +/// finds the same ones kept the next time; they are let go when fonts are added or rescanned. fn face_keys(db: &FontDb, face: &FontFace) -> FaceKeys { - type Kept = std::sync::Mutex>; - static KEPT: std::sync::OnceLock = std::sync::OnceLock::new(); + static KEPT: std::sync::OnceLock> = std::sync::OnceLock::new(); let kept = KEPT.get_or_init(Default::default); let at = (db.id(), face.id()); - if let Some(k) = kept.lock().unwrap_or_else(|e| e.into_inner()).get(&at) { - return k.clone(); + let generation = db.generation(); + { + let mut k = kept.lock().unwrap_or_else(|e| e.into_inner()); + if k.generation != generation { + *k = KeptKeys { generation, ..Default::default() }; + } + if let Some(keys) = k.faces.get(&at) { + return keys.clone(); + } } let mut by_gid: HashMap = HashMap::new(); for &(c, gid) in face.mapped_chars().iter().take(MAX_GLYPHS_PER_FACE) { @@ -214,11 +249,11 @@ fn face_keys(db: &FontDb, face: &FontFace) -> FaceKeys { let mut gids: Vec<(u32, char)> = by_gid.into_iter().collect(); gids.sort_unstable(); let keys: FaceKeys = Arc::new(gids.into_iter().filter_map(|(gid, ch)| Some((gid, ch, shape_key(&db.outline_uncached(face, gid))?))).collect()); - let mut kept = kept.lock().unwrap_or_else(|e| e.into_inner()); - if kept.len() >= KEPT_FACE_KEYS { - kept.clear(); + let mut k = kept.lock().unwrap_or_else(|e| e.into_inner()); + if k.generation == generation && k.glyphs + keys.len() <= KEPT_KEYS { + k.glyphs += keys.len(); + k.faces.insert(at, keys.clone()); } - kept.insert(at, keys.clone()); keys } @@ -264,7 +299,68 @@ fn fit(g: &Signature, s: &Signature) -> Option<((f64, f64), f64)> { rel.is_finite().then_some((z, rel)) } -/// `path`'s contours as segments, the closing line included; `None` past the size caps. +/// Do outlines `a` and `b` (in one space) lie on each other: every point of each, flattened, within +/// `tol` of the other? `false` when either is too large to check. +fn outlines_agree(a: &BezPath, b: &BezPath, tol: f64) -> bool { + if !tol.is_finite() || tol <= 0.0 { + return false; + } + let flat = |p: &BezPath| -> Option> { + let mut segs = vec![]; + let (mut start, mut last) = (Point::ZERO, Point::ZERO); + let mut too_many = false; + kurbo::flatten(p.iter(), tol / 4.0, |el| { + if segs.len() > MAX_OUTLINE_POINTS { + too_many = true; + return; + } + match el { + PathEl::MoveTo(q) => (start, last) = (q, q), + PathEl::LineTo(q) => { + segs.push((last, q)); + last = q; + } + PathEl::ClosePath => { + segs.push((last, start)); + last = start; + } + _ => {} + } + }); + (!too_many).then_some(segs) + }; + let (Some(sa), Some(sb)) = (flat(a), flat(b)) else { return false }; + let near = |p: Point, segs: &[(Point, Point)]| segs.iter().any(|(s, e)| Line::new(*s, *e).nearest(p, 1e-9).distance_sq <= tol * tol); + sa.iter().all(|(p, _)| near(*p, &sb)) && sb.iter().all(|(p, _)| near(*p, &sa)) +} + +/// `seg` as a line when it is one (a curve with its handles on its ends or on its line), else as it is. +fn as_line(seg: PathSeg) -> PathSeg { + let on_line = |a: Point, b: Point, p: Point| { + let ab = b - a; + let len = ab.hypot(); + len > 0.0 && (ab.cross(p - a)).abs() <= len * len * 1e-12 && (p - a).dot(ab) >= 0.0 && (p - b).dot(ab) <= 0.0 + }; + match seg { + PathSeg::Quad(q) if q.p1 == q.p0 || q.p1 == q.p2 || on_line(q.p0, q.p2, q.p1) => PathSeg::Line(Line::new(q.p0, q.p2)), + PathSeg::Cubic(c) if (c.p1 == c.p0 || on_line(c.p0, c.p3, c.p1)) && (c.p2 == c.p3 || on_line(c.p0, c.p3, c.p2)) => { + PathSeg::Line(Line::new(c.p0, c.p3)) + } + s => s, + } +} + +/// Lines `a` then `b` run on in one direction: one edge split in two. +fn runs_on(a: &PathSeg, b: &PathSeg) -> bool { + let (PathSeg::Line(a), PathSeg::Line(b)) = (a, b) else { return false }; + let (u, v) = (a.p1 - a.p0, b.p1 - b.p0); + let (lu, lv) = (u.hypot(), v.hypot()); + lu > 0.0 && lv > 0.0 && u.cross(v).abs() <= lu * lv * 1e-9 && u.dot(v) > 0.0 +} + +/// `path`'s contours as segments, the closing line included, read the same however the path was +/// written: segments that go nowhere are dropped, curves that are straight read as lines, and a +/// straight edge split in two (around the start too) reads as one. `None` past the size caps. fn contours(path: &BezPath) -> Option>> { if path.elements().len() > MAX_ELEMENTS { return None; @@ -272,9 +368,29 @@ fn contours(path: &BezPath) -> Option>> { let mut out: Vec> = vec![]; let mut cur: Vec = vec![]; let (mut start, mut last) = (Point::ZERO, Point::ZERO); - let mut flush = |cur: &mut Vec, start: Point, last: Point| { + let push = |cur: &mut Vec, seg: PathSeg| { + let seg = as_line(seg); + if seg.start() == seg.end() && matches!(seg, PathSeg::Line(_)) { + return; + } + match cur.last_mut() { + Some(prev) if runs_on(prev, &seg) => *prev = PathSeg::Line(Line::new(prev.start(), seg.end())), + _ => cur.push(seg), + } + }; + let flush = |cur: &mut Vec, start: Point, last: Point, out: &mut Vec>| { if last.distance(start) > 0.0 { - cur.push(PathSeg::Line(Line::new(last, start))); + push(cur, PathSeg::Line(Line::new(last, start))); + } + // An edge split at the contour's start: its two halves are the last and first segments. + if cur.len() > 1 + && let (Some(l), Some(f)) = (cur.last().copied(), cur.first().copied()) + && runs_on(&l, &f) + { + cur.pop(); + if let Some(first) = cur.first_mut() { + *first = PathSeg::Line(Line::new(l.start(), f.end())); + } } if !cur.is_empty() { out.push(std::mem::take(cur)); @@ -283,74 +399,135 @@ fn contours(path: &BezPath) -> Option>> { for el in path.elements() { match *el { PathEl::MoveTo(p) => { - flush(&mut cur, start, last); + flush(&mut cur, start, last, &mut out); start = p; last = p; } PathEl::LineTo(p) => { - cur.push(PathSeg::Line(Line::new(last, p))); + push(&mut cur, PathSeg::Line(Line::new(last, p))); last = p; } PathEl::QuadTo(a, p) => { - cur.push(PathSeg::Quad(QuadBez::new(last, a, p))); + push(&mut cur, PathSeg::Quad(QuadBez::new(last, a, p))); last = p; } PathEl::CurveTo(a, b, p) => { - cur.push(PathSeg::Cubic(CubicBez::new(last, a, b, p))); + push(&mut cur, PathSeg::Cubic(CubicBez::new(last, a, b, p))); last = p; } PathEl::ClosePath => { - flush(&mut cur, start, last); + flush(&mut cur, start, last, &mut out); last = start; } } + if out.len() > MAX_CONTOURS { + return None; + } } - flush(&mut cur, start, last); + flush(&mut cur, start, last, &mut out); (out.len() <= MAX_CONTOURS).then_some(out) } -/// How many contours with length `path` has, as matching counts them; `None` past the size caps. /// A cheap key two shapes share when one is the other scaled, turned and moved: how many segments -/// each of its contours has, in order (segments that go nowhere left out, a closing line counted -/// once whether the path draws it or closes onto it). Glyphs whose key no selected shape has are -/// not sampled. `None` past the size caps. -pub fn shape_key(path: &BezPath) -> Option> { - let moves = |s: &PathSeg| match s { - PathSeg::Line(l) => l.p0 != l.p1, - PathSeg::Quad(q) => q.p0 != q.p1 || q.p1 != q.p2, - PathSeg::Cubic(c) => c.p0 != c.p1 || c.p1 != c.p2 || c.p2 != c.p3, - }; - let key: Vec = contours(path)?.iter().map(|c| c.iter().filter(|s| moves(s)).count()).filter(|n| *n > 0).collect(); - (!key.is_empty()).then_some(key) +/// each of its contours has, in order, as [`contours`] reads them, hashed. Glyphs whose key no +/// selected shape has are not sampled. `None` past the size caps or for an empty shape. +pub fn shape_key(path: &BezPath) -> Option { + let cs = contours(path)?; + if cs.is_empty() { + return None; + } + // FNV-1a over the counts: equal keys for equal counts; a rare clash only samples a glyph more. + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + for n in std::iter::once(cs.len()).chain(cs.iter().map(Vec::len)) { + for b in (n as u64).to_le_bytes() { + h ^= u64::from(b); + h = h.wrapping_mul(0x0000_0100_0000_01b3); + } + } + Some(h) } -fn signature(path: &BezPath) -> Option { +/// `path` read for matching: one reading per choice of starting corners (the corner of each contour +/// farthest from the centre of all the shape's corners; every tied corner when `all_ties`, else the +/// first), at most [`MAX_VARIANTS`]. Empty for a shape with nothing to match. +fn signatures(path: &BezPath, all_ties: bool) -> Vec { let bounds = path.bounding_box(); let size = bounds.width().hypot(bounds.height()); if !size.is_finite() || size <= 0.0 { - return None; + return vec![]; } let accuracy = size * 1e-6; - let mut pts = vec![]; - let mut total = 0.0; - let mut contours_n = 0; - for c in contours(path)? { - let lens: Vec = c.iter().map(|s| s.arclen(accuracy)).collect(); - let len: f64 = lens.iter().sum(); - // A contour with no length (a lone move) draws nothing. - if !len.is_finite() || len <= size * 1e-9 { - continue; + let Some(cs) = contours(path) else { return vec![] }; + // Each contour with length, with its segments' lengths. + let cs: Vec<(Vec, Vec)> = cs + .into_iter() + .map(|c| { + let lens: Vec = c.iter().map(|s| s.arclen(accuracy)).collect(); + (c, lens) + }) + .filter(|(_, lens)| { + let len: f64 = lens.iter().sum(); + len.is_finite() && len > size * 1e-9 + }) + .collect(); + let corners: Vec = cs.iter().flat_map(|(c, _)| c.iter().map(|s| s.start())).collect(); + if corners.is_empty() { + return vec![]; + } + let n = corners.len() as f64; + let mid = Point::new(corners.iter().map(|p| p.x).sum::() / n, corners.iter().map(|p| p.y).sum::() / n); + // Each contour's starting corners: those farthest from `mid`, ties within a hair. + let starts: Vec> = cs + .iter() + .map(|(c, _)| { + let d: Vec = c.iter().map(|s| s.start().distance(mid)).collect(); + let far = d.iter().copied().fold(0.0, f64::max); + let tied: Vec = d.iter().enumerate().filter(|(_, v)| **v >= far - size * 1e-7).map(|(i, _)| i).collect(); + if all_ties { tied } else { tied.into_iter().take(1).collect() } + }) + .collect(); + let mut out = vec![]; + let mut pick = vec![0usize; cs.len()]; + loop { + if out.len() >= MAX_VARIANTS { + break; } - total += len; - contours_n += 1; - let (mut si, mut before) = (0usize, 0.0); - for k in 0..SAMPLES { - let at = len * k as f64 / SAMPLES as f64; - while si + 1 < c.len() && before + lens.get(si).copied().unwrap_or(0.0) < at { - before += lens.get(si).copied().unwrap_or(0.0); - si += 1; + if let Some(sig) = sample(&cs, &starts, &pick, accuracy) { + out.push(sig); + } + // The next choice of tied corners (a counter in mixed radix). + let mut i = 0; + loop { + let Some((p, s)) = pick.get_mut(i).zip(starts.get(i)) else { return out }; + *p += 1; + if *p < s.len() { + break; } - let (Some(seg), Some(l)) = (c.get(si), lens.get(si)) else { return None }; + *p = 0; + i += 1; + } + } + out +} + +/// One reading of the contours `cs`, contour `i` starting at segment `starts[i][pick[i]]`. +fn sample(cs: &[(Vec, Vec)], starts: &[Vec], pick: &[usize], accuracy: f64) -> Option { + let mut pts = Vec::with_capacity(cs.len() * SAMPLES); + let mut total = 0.0; + for (((c, lens), s), p) in cs.iter().zip(starts).zip(pick) { + let from = *s.get(*p)?; + let m = c.len(); + let len: f64 = lens.iter().sum(); + total += len; + let (mut k, mut before) = (0usize, 0.0); + let at_k = |k: usize| (from + k) % m; + for j in 0..SAMPLES { + let at = len * j as f64 / SAMPLES as f64; + while k + 1 < m && before + lens.get(at_k(k)).copied().unwrap_or(0.0) < at { + before += lens.get(at_k(k)).copied().unwrap_or(0.0); + k += 1; + } + let (Some(seg), Some(l)) = (c.get(at_k(k)), lens.get(at_k(k))) else { return None }; let t = if *l > 0.0 { seg.inv_arclen((at - before).clamp(0.0, *l), accuracy) } else { 0.0 }; pts.push(seg.eval(t)); } @@ -364,16 +541,21 @@ fn signature(path: &BezPath) -> Option { *p = Point::new(p.x - centre.x, p.y - centre.y); } let spread = (pts.iter().map(|p| p.x * p.x + p.y * p.y).sum::() / n).sqrt(); - if !spread.is_finite() || spread <= 0.0 { + if !spread.is_finite() || spread <= 0.0 || !total.is_finite() || total <= 0.0 { return None; } - Some(Signature { contours: contours_n, pts, centre, spread, invariant: spread / total }) + Some(Signature { contours: cs.len(), pts, centre, spread, invariant: spread / total }) +} + +/// The first reading of `path` (for tests). +#[cfg(test)] +fn signature(path: &BezPath) -> Option { + signatures(path, false).into_iter().next() } #[cfg(test)] mod tests { use super::*; - use kurbo::Affine; fn letter() -> BezPath { // A hand-made "P"-like shape: an outer contour and a counter. @@ -464,4 +646,86 @@ mod tests { } assert!(signature(&huge).is_none()); } + + /// The best fit of `shape`'s readings onto `glyph`'s first one. + fn best_fit(glyph: &BezPath, shape: &BezPath) -> f64 { + let g = signature(glyph).unwrap(); + signatures(shape, true).iter().filter_map(|s| fit(&g, s)).map(|(_, r)| r).fold(f64::INFINITY, f64::min) + } + + #[test] + fn a_contour_started_at_another_corner_still_matches() { + // The counter of letter(), started at its second corner instead of its first. + let mut p = BezPath::new(); + p.move_to((0.0, 0.0)); + p.line_to((0.0, -700.0)); + p.curve_to((300.0, -700.0), (450.0, -600.0), (450.0, -480.0)); + p.quad_to((450.0, -300.0), (120.0, -300.0)); + p.line_to((120.0, 0.0)); + p.close_path(); + p.move_to((120.0, -400.0)); + p.quad_to((330.0, -400.0), (330.0, -500.0)); + p.quad_to((330.0, -600.0), (120.0, -600.0)); + p.line_to((120.0, -400.0)); + p.close_path(); + let shape = Affine::translate((40.0, 90.0)) * Affine::rotate(-1.1) * Affine::scale(0.03) * p; + assert_eq!(shape_key(&shape), shape_key(&letter())); + assert!(best_fit(&letter(), &shape) < 1e-6); + // A triangle started at each of its corners. + let tri = |a: (f64, f64), b: (f64, f64), c: (f64, f64)| { + let mut t = BezPath::new(); + t.move_to(a); + t.line_to(b); + t.line_to(c); + t.close_path(); + t + }; + let g = tri((0.0, 0.0), (300.0, 0.0), (0.0, -400.0)); + for s in [tri((300.0, 0.0), (0.0, -400.0), (0.0, 0.0)), tri((0.0, -400.0), (0.0, 0.0), (300.0, 0.0))] { + assert!(best_fit(&g, &s) < 1e-6); + } + } + + #[test] + fn an_edge_split_in_two_reads_as_one() { + let mut p = BezPath::new(); + p.move_to((0.0, 0.0)); + p.line_to((0.0, -350.0)); + p.line_to((0.0, -700.0)); + p.curve_to((300.0, -700.0), (450.0, -600.0), (450.0, -480.0)); + p.quad_to((450.0, -300.0), (120.0, -300.0)); + p.line_to((120.0, 0.0)); + p.line_to((60.0, 0.0)); + p.close_path(); + p.move_to((120.0, -600.0)); + p.line_to((120.0, -400.0)); + p.quad_to((330.0, -400.0), (330.0, -500.0)); + p.quad_to((330.0, -600.0), (120.0, -600.0)); + p.close_path(); + assert_eq!(shape_key(&p), shape_key(&letter()), "split edges, the closing one too, read as one"); + assert!(best_fit(&letter(), &p) < 1e-6); + } + + #[test] + fn a_detail_between_samples_fails_the_whole_outline_check() { + let bar = |notch: f64| { + let mut p = BezPath::new(); + p.move_to((0.0, 0.0)); + p.line_to((1000.0, 0.0)); + p.line_to((1000.0, -100.0)); + // A notch 2 units wide, in or out, between two samples along the top edge. + p.line_to((501.0, -100.0)); + p.line_to((501.0, -100.0 + notch)); + p.line_to((499.0, -100.0 + notch)); + p.line_to((499.0, -100.0)); + p.line_to((0.0, -100.0)); + p.close_path(); + p + }; + let (out, inn) = (bar(-10.0), bar(10.0)); + assert_eq!(shape_key(&out), shape_key(&inn), "same key"); + let tol = signature(&inn).unwrap().spread * OUTLINE_TOLERANCE; + assert!(!outlines_agree(&out, &inn, tol), "the whole outline does"); + assert!(outlines_agree(&out, &out, tol)); + } } From c1613f2bf52add27100ae36ed00f537ded08ebc6 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:25:41 +0530 Subject: [PATCH 11/15] M7/G4: retype checks points along every edge; keys charged once (#4934) The whole-outline check tests points along every edge, so outlines with the same corners joined another way do not match; past a work limit it rejects. Face keys another Retype kept meanwhile are reused and charged once. The fonts parameter test uses outlines that would match. The parity note states the search limits. --- crates/engine/src/cmd/retype_tests.rs | 10 +++++- crates/text/src/retype.rs | 45 +++++++++++++++++++++++++-- docs/target-app-parity.md | 2 +- 3 files changed, 53 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 7812fc8e65..1c8cf5c2f2 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -80,7 +80,15 @@ fn a_drawn_shape_is_reported_and_left_alone() { let e = s.execute("type.retype", &json!({})).unwrap_err().to_string(); assert!(e.contains("no selected shape matches"), "{e}"); assert!(s.doc().unwrap().doc == before, "nothing changes"); - assert!(s.execute("type.retype", &json!({"fonts": "Source Sans 3"})).is_err(), "fonts is a list"); + // With outlines that would match, a bad `fonts` is refused for itself, and nothing changes. + let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "AB", "size": 40})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + for bad in [json!("Source Sans 3"), json!([1]), json!({"family": "x"})] { + let e = s.execute("type.retype", &json!({"fonts": bad})).unwrap_err().to_string(); + assert!(e.contains("fonts must be a list of family names"), "{e}"); + } + assert!(s.doc().unwrap().doc == before); } #[test] diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index 80fed5f33a..5ef5073909 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -40,6 +40,8 @@ const TOLERANCE: f64 = 2e-3; const OUTLINE_TOLERANCE: f64 = 5e-3; /// Points of a flattened outline past which the whole-outline check gives up (and so rejects). const MAX_OUTLINE_POINTS: usize = 8192; +/// Points along an outline past which the whole-outline check gives up (and so rejects). +const MAX_CHECKED_POINTS: usize = 65_536; /// How far apart two shapes' spread-to-length ratios may be and still be compared. const INVARIANT_SLACK: f64 = 0.02; @@ -250,7 +252,14 @@ fn face_keys(db: &FontDb, face: &FontFace) -> FaceKeys { gids.sort_unstable(); let keys: FaceKeys = Arc::new(gids.into_iter().filter_map(|(gid, ch)| Some((gid, ch, shape_key(&db.outline_uncached(face, gid))?))).collect()); let mut k = kept.lock().unwrap_or_else(|e| e.into_inner()); - if k.generation == generation && k.glyphs + keys.len() <= KEPT_KEYS { + if k.generation != generation { + return keys; + } + // Another Retype may have worked them out meanwhile: keep and charge one list. + if let Some(already) = k.faces.get(&at) { + return already.clone(); + } + if k.glyphs + keys.len() <= KEPT_KEYS { k.glyphs += keys.len(); k.faces.insert(at, keys.clone()); } @@ -331,7 +340,22 @@ fn outlines_agree(a: &BezPath, b: &BezPath, tol: f64) -> bool { }; let (Some(sa), Some(sb)) = (flat(a), flat(b)) else { return false }; let near = |p: Point, segs: &[(Point, Point)]| segs.iter().any(|(s, e)| Line::new(*s, *e).nearest(p, 1e-9).distance_sq <= tol * tol); - sa.iter().all(|(p, _)| near(*p, &sb)) && sb.iter().all(|(p, _)| near(*p, &sa)) + // Points along every edge, not only its ends: two outlines with the same corners joined in + // another order differ between them. Spaced `tol` apart; past the work limit, not a match. + let along = |segs: &[(Point, Point)]| -> Option> { + let mut pts = vec![]; + for (s, e) in segs { + let steps = (s.distance(*e) / tol).ceil(); + if !steps.is_finite() || pts.len() as f64 + steps > MAX_CHECKED_POINTS as f64 { + return None; + } + let steps = (steps as usize).max(1); + pts.extend((0..steps).map(|i| s.lerp(*e, i as f64 / steps as f64))); + } + Some(pts) + }; + let (Some(pa), Some(pb)) = (along(&sa), along(&sb)) else { return false }; + pa.iter().all(|p| near(*p, &sb)) && pb.iter().all(|p| near(*p, &sa)) } /// `seg` as a line when it is one (a curve with its handles on its ends or on its line), else as it is. @@ -728,4 +752,21 @@ mod tests { assert!(!outlines_agree(&out, &inn, tol), "the whole outline does"); assert!(outlines_agree(&out, &out, tol)); } + + #[test] + fn the_same_corners_joined_another_way_are_another_outline() { + let poly = |pts: &[(f64, f64)]| { + let mut p = BezPath::new(); + p.move_to(pts[0]); + for q in &pts[1..] { + p.line_to(*q); + } + p.close_path(); + p + }; + let square = poly(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]); + let bow = poly(&[(0.0, 0.0), (100.0, 100.0), (100.0, 0.0), (0.0, 100.0)]); + assert!(!outlines_agree(&square, &bow, 1.0), "every corner lies on the other, the edges do not"); + assert!(outlines_agree(&square, &square, 1.0)); + } } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index dbb538c08d..b845378576 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2861,7 +2861,7 @@ Check Spelling followed (2026-11-15): Edit › Spelling › Check Spelling… (` ## Retype, phase 1 (2026-11-18) -The public pages describe Retype finding the fonts that match selected outlined text (or text in an image), from the fonts on the device among others, and applying them to live text ([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)). Phase 1 (#4934) is local and exact: Type › Retype (`type.retype`) compares each selected glyph shape with the glyphs of the loaded fonts, the document's fonts and any families named in `fonts`, the same up to uniform scale, rotation and translation, and sets the matched characters as point text in that font and size at the same baseline, one object per line, in one undo step. Shapes that match no font stay and are reported. Tested by round trips through Create Outlines (plain, bold and turned, serif, word spaces), a drawn shape and a mixed selection (`crates/engine/src/cmd/retype_tests.rs`). Near matches, the ranked font list, installed fonts not yet loaded and images remain (phase 2). +The public pages describe Retype finding the fonts that match selected outlined text (or text in an image), from the fonts on the device among others, and applying them to live text ([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)). Phase 1 (#4934) is local and exact: Type › Retype (`type.retype`) compares each selected glyph shape with the glyphs of the loaded fonts, the document's fonts and any families named in `fonts`, the same up to uniform scale, rotation and translation, and sets the matched characters as point text in that font and size at the same baseline, one object per line, in one undo step. Shapes that match no font stay and are reported. The search is bounded, not exhaustive: at most 96 faces (named families first, then the document's fonts, then the other loaded faces), the first 65,536 encoded characters of each, and glyphs of plain-shape characters (box drawing, blocks, geometric shapes, private use) are left out; a glyph outside those limits is reported as matching no font. Exact matching also reads a curve an exporter split in two as a different shape (phase 2, with the other near matches). Tested by round trips through Create Outlines (plain, bold and turned, serif, word spaces), a drawn shape and a mixed selection (`crates/engine/src/cmd/retype_tests.rs`). Near matches, the ranked font list, installed fonts not yet loaded and images remain (phase 2). ## Control bar: Paragraph section while type is selected (2026-11-06) From 1c275797a717b160dc39a826c27e42085f1b700f Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:58:18 +0530 Subject: [PATCH 12/15] M7/G4: re-run CI after the runner shut down mid-build (#4934) From 1cffa0b862fff4e98f8ce96a0d96bf9cfeccded5 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:58:52 +0530 Subject: [PATCH 13/15] M7/G4: retype review: tracked letters, outline check cost, poses (#4934) The lone-glyph rule looks at lines as the outlines lie, before the layout check splits them, so tracked one-contour letters (L, I, T, H, E) become type. A shape keeps every glyph and pose it fits exactly, upright first (an L, and a turned L half round; an I upright or upside down), and the line around it chooses; a one-glyph line may turn to another candidate to take the next glyph. The whole-outline check flattens the shape once per shape, samples every corner and points twice the tolerance apart, and asks a flat uniform grid of segments. With Microsoft YaHei loaded: 300 CJK outlines in 350 ms (1.9 s before), one line in 25 ms. FontDb::outline reuses outline_uncached, and the compositing test covers knockout_shape. --- crates/engine/src/cmd/retype.rs | 101 ++++++++++-- crates/engine/src/cmd/retype_tests.rs | 65 +++++++- crates/text/src/fontdb/lookup.rs | 8 +- crates/text/src/retype.rs | 219 ++++++++++++++++++++------ 4 files changed, 314 insertions(+), 79 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index df0d88a489..2ce951f812 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -164,6 +164,9 @@ struct Line { pieces: Vec, /// What each piece matched, as `pieces`. matches: Vec, + /// Every glyph the first piece fits, while the line holds only it: the next glyph may tell + /// which one it is (see [`join`]). + first_cands: Vec, text: String, face: Arc, scale: f64, @@ -224,6 +227,7 @@ impl Line { let mut l = Line { pieces: vec![*first], matches: vec![m.clone()], + first_cands: vec![], text: m.ch.to_string(), face: m.face.clone(), scale: m.scale, @@ -331,11 +335,64 @@ fn space_advance(face: &vectorcraft_text::FontFace) -> f64 { face.mapped_chars().iter().find(|(c, _)| *c == ' ').map(|(_, g)| face.advance(*g)).unwrap_or(0.0) } -fn new_line(pc: &Piece, m: &GlyphMatch) -> Line { +/// Add shape `pc` to line `l` when one of its candidate glyphs `cands`, in one of its poses, +/// continues it (one shape can be several glyphs, and a glyph that looks the same turned fits in +/// more than one pose). A line of one shape may turn to another of that shape's candidates to take +/// the next one: an L or a turned L half round, an I upright or upside down, and the glyph after it +/// tells which. Whether it was added. +fn join(l: &mut Line, pc: &Piece, cands: &[GlyphMatch]) -> bool { + let fits = |l: &Line| cands.iter().flat_map(|c| c.poses()).find(|mp| l.continues(pc, mp)); + if let Some(mp) = fits(l) { + l.push(pc.id, &mp); + return true; + } + let (Some(id), [current]) = (l.pieces.first().copied(), l.matches.as_slice()) else { return false }; + let current = current.clone(); + let others: Vec = l + .first_cands + .iter() + .flat_map(|c| c.poses()) + .filter(|fp| !(fp.gid == current.gid && fp.face.id() == current.face.id() && fp.angle == current.angle)) + .collect(); + for fp in others { + let mut turned = reposed(l, id, &fp); + if let Some(mp) = fits(&turned) { + turned.push(pc.id, &mp); + *l = turned; + return true; + } + } + false +} + +/// Line `l`'s group, paint and transparency with glyph `m` (shape `id`) alone on it. +fn reposed(l: &Line, id: NodeId, m: &GlyphMatch) -> Line { let dir = Vec2::new(m.angle.cos(), m.angle.sin()); Line { + pieces: vec![id], + matches: vec![m.clone()], + first_cands: l.first_cands.clone(), + text: m.ch.to_string(), + face: m.face.clone(), + scale: m.scale, + angle: m.angle, + origin: m.origin, + end: m.origin + dir * (m.face.advance(m.gid) * m.scale), + appearance: l.appearance.clone(), + parent: l.parent, + opacity: l.opacity, + blend: l.blend, + } +} + +/// A new line of shape `pc` alone, as the first of its candidate glyphs `cands` (none: `None`). +fn new_line(pc: &Piece, cands: &[GlyphMatch]) -> Option { + let m = cands.first()?; + let dir = Vec2::new(m.angle.cos(), m.angle.sin()); + Some(Line { pieces: vec![pc.id], matches: vec![m.clone()], + first_cands: cands.to_vec(), text: m.ch.to_string(), face: m.face.clone(), scale: m.scale, @@ -346,7 +403,7 @@ fn new_line(pc: &Piece, m: &GlyphMatch) -> Line { parent: pc.parent, opacity: pc.opacity, blend: pc.blend, - } + }) } fn retype(s: &mut Session, p: &Value) -> Result { @@ -394,10 +451,16 @@ fn retype(s: &mut Session, p: &Value) -> Result { // The face most shapes match, so a glyph several fonts share is set in the same font as // the glyphs around it. let mut votes: Vec<(u32, usize)> = vec![]; - for m in found.iter().flatten() { - match votes.iter_mut().find(|(f, _)| *f == m.face.id()) { - Some(v) => v.1 += 1, - None => votes.push((m.face.id(), 1)), + for ms in &found { + // Each shape votes once for each face it fits. + let mut faces: Vec = ms.iter().map(|m| m.face.id()).collect(); + faces.sort_unstable(); + faces.dedup(); + for f in faces { + match votes.iter_mut().find(|(v, _)| *v == f) { + Some(v) => v.1 += 1, + None => votes.push((f, 1)), + } } } let rank = |face: u32| votes.iter().find(|(f, _)| *f == face).map_or(0, |v| v.1); @@ -409,26 +472,34 @@ fn retype(s: &mut Session, p: &Value) -> Result { if pc.after_barrier { open = false; } - // Earlier matches win ties: they are the closer fits. - let best = ms.iter().enumerate().max_by_key(|(i, m)| (rank(m.face.id()), std::cmp::Reverse(*i))).map(|(_, m)| m); - let Some(m) = best else { + // The shape's candidates in the face most shapes fit (the first such face, as the + // matches come upright and closest first). + let face = ms.iter().enumerate().max_by_key(|(i, m)| (rank(m.face.id()), std::cmp::Reverse(*i))).map(|(_, m)| m.face.id()); + let cands: Vec = ms.iter().filter(|m| Some(m.face.id()) == face).cloned().collect(); + if cands.is_empty() { unmatched.push(pc.id); open = false; continue; + } + let joined = match lines.last_mut() { + Some(l) if open => join(l, pc, &cands), + _ => false, }; - match lines.last_mut() { - Some(l) if open && l.continues(pc, m) => l.push(pc.id, m), - _ => lines.push(new_line(pc, m)), + if !joined { + lines.extend(new_line(pc, &cands)); } open = true; } - let mut lines = verified(lines, system_layout, &mut unmatched); // A lone one-contour glyph (a period, a hyphen, a bullet) is too plain to tell from drawn // art (a dot, a bar): beside other shapes it stays an outline. Selected on its own, it is - // what was asked for. + // what was asked for. Lone means alone on its baseline as the outlines lie, before the + // layout check splits lines (tracking and manual kerning split them glyph by glyph). + let lone_pieces: std::collections::HashSet = + lines.iter().filter(|l| matches!(l.matches.as_slice(), [m] if m.contours == 1)).flat_map(|l| l.pieces.iter().copied()).collect(); + let mut lines = verified(lines, system_layout, &mut unmatched); if pieces.len() > 1 { lines.retain(|l| { - let lone = matches!(l.matches.as_slice(), [m] if m.contours == 1); + let lone = matches!(l.pieces.as_slice(), [id] if lone_pieces.contains(id)); if lone { unmatched.extend(l.pieces.iter().copied()); } diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 1c8cf5c2f2..98736c5a4f 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -349,15 +349,15 @@ fn a_hidden_or_locked_glyph_stays_an_outline() { #[test] fn an_isolated_or_knockout_group_keeps_its_type_inside() { - for knock in [false, true] { + for case in ["isolate", "knockout", "knockout_shape"] { let mut s = session(); let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40})); s.edit("test", |d, _| { let n = d.node_mut(NodeId(g)).unwrap(); - if knock { - n.knockout = vectorcraft_doc::Knockout::On; - } else { - n.isolate = true; + match case { + "isolate" => n.isolate = true, + "knockout" => n.knockout = vectorcraft_doc::Knockout::On, + _ => n.knockout_shape = true, } Ok(()) }) @@ -365,7 +365,7 @@ fn an_isolated_or_knockout_group_keeps_its_type_inside() { s.execute("select.set", &json!({"ids": [g]})).unwrap(); let r = s.execute("type.retype", &json!({})).unwrap(); let id = r["ids"][0].as_u64().unwrap(); - assert_eq!(children_of(&s, g), vec![id], "knockout {knock}: the group stays, holding the type"); + assert_eq!(children_of(&s, g), vec![id], "{case}: the group stays, holding the type"); } } @@ -465,3 +465,56 @@ fn nothing_retypable_reads_no_font() { let e = s.execute("type.retype", &json!({})).unwrap_err().to_string(); assert!(e.contains("(1 checked)"), "the masked shape is reported, and no font was indexed: {e}"); } + +#[test] +fn tracked_one_contour_letters_still_become_type() { + for text in ["LIT", "HELLO", "LIST"] { + let mut s = session(); + let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": text, "size": 30})).unwrap()["id"].as_u64().unwrap(); + let n = text.len() as u64; + s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": n, "tracking": 50})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + 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(); + let texts: Vec = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect(); + assert_eq!(texts.concat(), text, "split by the tracking, every letter still becomes type: {r}"); + assert!(texts.len() > 1, "the tracking splits the line: {r}"); + assert_eq!(r["unmatched"], json!([]), "{r}"); + } +} + +/// How long Retype takes on a few hundred CJK outlines at once (run with `--ignored --nocapture`; +/// skips when no large CJK font is installed). Not a pass/fail budget: it prints. +#[test] +#[ignore = "timing: needs an installed CJK font"] +fn timing_with_hundreds_of_cjk_outlines() { + let db = vectorcraft_text::FontDb::global(); + let Some(family) = ["Microsoft YaHei", "Yu Gothic", "MS Gothic", "Noto Sans CJK JP", "Hiragino Sans"].into_iter().find(|f| db.has_family(f)) + else { + eprintln!("skipped: no large CJK font installed"); + return; + }; + let face = db.resolve(family, "Regular").map(|(f, _)| f).unwrap(); + // 300 common ideographs, ten lines of thirty. + let chars: Vec = (0x4E00u32..).filter_map(char::from_u32).filter(|c| face.covers(*c)).take(300).collect(); + let mut s = session(); + let mut groups = vec![]; + for (i, line) in chars.chunks(30).enumerate() { + let text: String = line.iter().collect(); + groups.push(outlined(&mut s, json!({"x": 20, "y": 40 + 30 * i, "text": text, "size": 20, "font": family, "style": face.style}))); + } + for run in ["cold", "warm"] { + s.execute("select.set", &json!({"ids": groups})).unwrap(); + let t0 = std::time::Instant::now(); + let r = s.execute("type.retype", &json!({"fonts": [family]})).unwrap(); + let ms = t0.elapsed().as_secs_f64() * 1000.0; + let typed: usize = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().chars().count()).sum(); + eprintln!( + "{run}: Retype of {} {family} outlines: {ms:.0} ms → {typed} characters typed, {} unmatched", + chars.len(), + r["unmatched"].as_array().unwrap().len() + ); + s.execute("edit.undo", &json!({})).unwrap(); + } +} diff --git a/crates/text/src/fontdb/lookup.rs b/crates/text/src/fontdb/lookup.rs index 99844220f5..3c2a613b56 100644 --- a/crates/text/src/fontdb/lookup.rs +++ b/crates/text/src/fontdb/lookup.rs @@ -660,13 +660,7 @@ impl FontDb { if let Some(p) = self.outlines.lock().unwrap_or_else(|e| e.into_inner()).get(&key) { return p.clone(); } - let mut pen = FlipPen(BezPath::new()); - if let Some(f) = face.skrifa() - && let Some(g) = f.outline_glyphs().get(GlyphId::new(gid)) - { - let _ = g.draw(DrawSettings::unhinted(Size::unscaled(), face.location()), &mut pen); - } - let p = Arc::new(pen.0); + let p = Arc::new(self.outline_uncached(face, gid)); let mut cache = self.outlines.lock().unwrap_or_else(|e| e.into_inner()); if cache.len() >= OUTLINE_CACHE_MAX { cache.clear(); diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index 5ef5073909..b778ce47dd 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -42,6 +42,8 @@ const OUTLINE_TOLERANCE: f64 = 5e-3; const MAX_OUTLINE_POINTS: usize = 8192; /// Points along an outline past which the whole-outline check gives up (and so rejects). const MAX_CHECKED_POINTS: usize = 65_536; +/// The most glyphs one shape is reported to be ([`RetypeIndex::matches`]). +pub const MAX_CANDIDATES: usize = 16; /// How far apart two shapes' spread-to-length ratios may be and still be compared. const INVARIANT_SLACK: f64 = 0.02; @@ -62,6 +64,32 @@ pub struct GlyphMatch { pub residual: f64, /// How many contours the glyph has. pub contours: usize, + /// Other poses the glyph fits the shape in equally (a glyph that looks the same turned). + pub alts: Vec, +} + +/// Where and how a glyph lies: its size, turn and origin. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Pose { + /// Document units per font unit. + pub scale: f64, + /// Radians, as [`kurbo::Affine::rotate`] turns. + pub angle: f64, + /// Where the glyph's origin lies. + pub origin: Point, +} + +impl GlyphMatch { + /// This match in each pose it fits: its own first, then [`Self::alts`]. + pub fn poses(&self) -> impl Iterator + '_ { + let own = Pose { scale: self.scale, angle: self.angle, origin: self.origin }; + std::iter::once(own).chain(self.alts.iter().copied()).map(move |p| GlyphMatch { + scale: p.scale, + angle: p.angle, + origin: p.origin, + ..self.clone() + }) + } } /// A shape reduced for matching: points along each contour, centred. @@ -152,8 +180,12 @@ impl RetypeIndex { self.entries.is_empty() } - /// The glyphs `shape` (in document space) is, the closest one per face, closest first; empty - /// when it is no glyph of the indexed faces. + /// The glyphs `shape` (in document space) is: every glyph that fits it exactly, upright ones + /// first, then the closest; empty when it is no glyph of the indexed faces. One shape can be + /// several glyphs: an L, and a turned L (U+A780) turned half round; a u, and an n upside down. + /// A glyph that looks the same turned (an I, an O, a hyphen) also fits in more than one pose: + /// the upright-most comes first and the others are kept in [`GlyphMatch::alts`]. The line + /// around the shape chooses among them. At most [`MAX_CANDIDATES`]. pub fn matches(&self, shape: &BezPath) -> Vec { let variants = signatures(shape, true); let Some(first) = variants.first() else { return vec![] }; @@ -161,53 +193,70 @@ impl RetypeIndex { let lo = first.invariant * (1.0 - INVARIANT_SLACK); let hi = first.invariant * (1.0 + INVARIANT_SLACK); let start = list.partition_point(|i| self.entries.get(*i).is_some_and(|e| e.sig.invariant < lo)); - let mut best: HashMap = HashMap::new(); + let tol = first.spread * OUTLINE_TOLERANCE; + // The shape flattened for the whole-outline check, once, when a glyph first gets that far. + let mut shape_flat: Option> = None; + let mut out: Vec<(usize, GlyphMatch)> = vec![]; for i in list.iter().skip(start) { let Some(e) = self.entries.get(*i) else { continue }; if e.sig.invariant > hi { break; } - // The reading of the shape (its tied starting corners) that fits the glyph best. - let Some((sig, z, residual)) = variants.iter().filter_map(|s| fit(&e.sig, s).map(|(z, r)| (s, z, r))).min_by(|a, b| a.2.total_cmp(&b.2)) - else { - continue; - }; - if residual > TOLERANCE { - continue; - } let Some(face) = self.faces.get(e.face) else { continue }; - // The glyph's origin is (0, 0) in font units: it lands at centre − z·glyph centre. - let gc = mul(z, e.sig.centre); - let origin = Point::new(sig.centre.x - gc.x, sig.centre.y - gc.y); - // The samples can step over a detail (a notch between two of them): the whole outline, - // turned onto the shape, must lie on it. - let onto = Affine::new([z.0, z.1, -z.1, z.0, origin.x, origin.y]); - if !outlines_agree(&(onto * e.outline.clone()), shape, sig.spread * OUTLINE_TOLERANCE) { - continue; + // Each reading of the shape (its tied starting corners) that fits the glyph is a pose. + let mut poses: Vec<(Pose, f64)> = vec![]; + for sig in &variants { + let Some((z, residual)) = fit(&e.sig, sig) else { continue }; + if residual > TOLERANCE { + continue; + } + // The glyph's origin is (0, 0) in font units: it lands at centre − z·glyph centre. + let gc = mul(z, e.sig.centre); + let pose = Pose { scale: z.0.hypot(z.1), angle: z.1.atan2(z.0), origin: Point::new(sig.centre.x - gc.x, sig.centre.y - gc.y) }; + if poses.iter().any(|(p, _)| wrapped(p.angle - pose.angle).abs() < 1e-6) { + continue; + } + // The samples can step over a detail (a notch between two of them): the whole + // outline, turned onto the shape, must lie on it. + let flat = shape_flat.get_or_insert_with(|| Flat::new(shape, tol)); + let Some(flat) = flat.as_ref() else { break }; + let onto = Affine::new([z.0, z.1, -z.1, z.0, pose.origin.x, pose.origin.y]); + if !Flat::new(&(onto * e.outline.clone()), tol).is_some_and(|g| g.agrees(flat)) { + continue; + } + poses.push((pose, residual)); } + // The upright-most pose first. + poses.sort_by(|a, b| wrapped(a.0.angle).abs().total_cmp(&wrapped(b.0.angle).abs())); + let Some(((pose, _), rest)) = poses.split_first() else { continue }; + let residual = poses.iter().map(|(_, r)| *r).fold(f64::INFINITY, f64::min); let m = GlyphMatch { face: face.clone(), gid: e.gid, ch: e.ch, - scale: z.0.hypot(z.1), - angle: z.1.atan2(z.0), - origin, + scale: pose.scale, + angle: pose.angle, + origin: pose.origin, residual, contours: e.sig.contours, + alts: rest.iter().map(|(p, _)| *p).collect(), }; - match best.get(&e.face) { - Some(b) if b.residual < m.residual || (b.residual == m.residual && b.ch <= m.ch) => {} - _ => { - best.insert(e.face, m); - } - } + out.push((e.face, m)); } - let mut out: Vec<(usize, GlyphMatch)> = best.into_iter().collect(); - out.sort_by(|a, b| a.1.residual.total_cmp(&b.1.residual).then(a.0.cmp(&b.0))); + let upright = |m: &GlyphMatch| wrapped(m.angle).abs() >= 1e-3; + out.sort_by(|a, b| { + upright(&a.1).cmp(&upright(&b.1)).then(a.1.residual.total_cmp(&b.1.residual)).then(a.0.cmp(&b.0)).then(a.1.ch.cmp(&b.1.ch)) + }); + out.truncate(MAX_CANDIDATES); out.into_iter().map(|(_, m)| m).collect() } } +/// `a` wrapped into −π..π. +fn wrapped(a: f64) -> f64 { + (a + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI +} + /// A face's glyphs as the index looks them up: (glyph, character, [`shape_key`]), one per glyph /// under the lowest character that maps to it. type FaceKeys = Arc>; @@ -308,17 +357,38 @@ fn fit(g: &Signature, s: &Signature) -> Option<((f64, f64), f64)> { rel.is_finite().then_some((z, rel)) } -/// Do outlines `a` and `b` (in one space) lie on each other: every point of each, flattened, within -/// `tol` of the other? `false` when either is too large to check. -fn outlines_agree(a: &BezPath, b: &BezPath, tol: f64) -> bool { - if !tol.is_finite() || tol <= 0.0 { - return false; - } - let flat = |p: &BezPath| -> Option> { +/// An outline flattened for the whole-outline check: its segments, points along them (every +/// corner, and points twice `tol` apart between corners: a detail narrower than that has corners +/// of its own), and a uniform grid listing each segment under every cell its box, grown by `tol`, +/// touches, so whether a point lies within `tol` of the outline is asked of the few segments +/// around it. +struct Flat { + segs: Vec<(Point, Point)>, + pts: Vec, + origin: Point, + cell: f64, + cols: usize, + rows: usize, + /// Segment indices per cell, row by row. + cells: Vec>, + tol: f64, +} + +impl Flat { + /// Cells along the longer side, at most. + const MAX_SIDE: f64 = 48.0; + /// Segment listings in all, at most: past it (or past [`MAX_OUTLINE_POINTS`] segments or + /// [`MAX_CHECKED_POINTS`] points), `None`, and so no match. + const MAX_LISTINGS: usize = 1 << 18; + + fn new(path: &BezPath, tol: f64) -> Option { + if !tol.is_finite() || tol <= 0.0 { + return None; + } let mut segs = vec![]; let (mut start, mut last) = (Point::ZERO, Point::ZERO); let mut too_many = false; - kurbo::flatten(p.iter(), tol / 4.0, |el| { + kurbo::flatten(path.iter(), tol / 2.0, |el| { if segs.len() > MAX_OUTLINE_POINTS { too_many = true; return; @@ -336,26 +406,73 @@ fn outlines_agree(a: &BezPath, b: &BezPath, tol: f64) -> bool { _ => {} } }); - (!too_many).then_some(segs) - }; - let (Some(sa), Some(sb)) = (flat(a), flat(b)) else { return false }; - let near = |p: Point, segs: &[(Point, Point)]| segs.iter().any(|(s, e)| Line::new(*s, *e).nearest(p, 1e-9).distance_sq <= tol * tol); - // Points along every edge, not only its ends: two outlines with the same corners joined in - // another order differ between them. Spaced `tol` apart; past the work limit, not a match. - let along = |segs: &[(Point, Point)]| -> Option> { + if too_many { + return None; + } let mut pts = vec![]; - for (s, e) in segs { - let steps = (s.distance(*e) / tol).ceil(); + for (s, e) in &segs { + let steps = (s.distance(*e) / (2.0 * tol)).ceil(); if !steps.is_finite() || pts.len() as f64 + steps > MAX_CHECKED_POINTS as f64 { return None; } let steps = (steps as usize).max(1); pts.extend((0..steps).map(|i| s.lerp(*e, i as f64 / steps as f64))); } - Some(pts) - }; - let (Some(pa), Some(pb)) = (along(&sa), along(&sb)) else { return false }; - pa.iter().all(|p| near(*p, &sb)) && pb.iter().all(|p| near(*p, &sa)) + let (first, _) = segs.first()?; + let mut bb = kurbo::Rect::from_points(*first, *first); + for (s, e) in &segs { + bb = bb.union_pt(*s).union_pt(*e); + } + let bb = bb.inflate(tol, tol); + let cell = (bb.width().max(bb.height()) / Self::MAX_SIDE).max(2.0 * tol); + if !cell.is_finite() || cell <= 0.0 { + return None; + } + let at = |v: f64, o: f64| (((v - o) / cell).floor().max(0.0) as usize).min(Self::MAX_SIDE as usize); + let (cols, rows) = (at(bb.x1, bb.x0) + 1, at(bb.y1, bb.y0) + 1); + let mut cells: Vec> = vec![vec![]; cols * rows]; + let mut listings = 0usize; + for (i, (s, e)) in segs.iter().enumerate() { + let r = kurbo::Rect::from_points(*s, *e).inflate(tol, tol); + for cy in at(r.y0, bb.y0)..=at(r.y1, bb.y0).min(rows - 1) { + for cx in at(r.x0, bb.x0)..=at(r.x1, bb.x0).min(cols - 1) { + listings += 1; + if listings > Self::MAX_LISTINGS { + return None; + } + if let Some(c) = cells.get_mut(cy * cols + cx) { + c.push(u32::try_from(i).ok()?); + } + } + } + } + Some(Flat { segs, pts, origin: Point::new(bb.x0, bb.y0), cell, cols, rows, cells, tol }) + } + + /// Does `p` lie within `tol` of a segment? + fn near(&self, p: Point) -> bool { + let (fx, fy) = ((p.x - self.origin.x) / self.cell, (p.y - self.origin.y) / self.cell); + if !(fx >= 0.0 && fy >= 0.0) || fx >= self.cols as f64 || fy >= self.rows as f64 { + return false; + } + let (cx, cy) = (fx as usize, fy as usize); + let tol2 = self.tol * self.tol; + self.cells.get(cy * self.cols + cx).is_some_and(|list| { + list.iter().filter_map(|i| self.segs.get(*i as usize)).any(|(s, e)| Line::new(*s, *e).nearest(p, 1e-9).distance_sq <= tol2) + }) + } + + /// Do the two outlines lie on each other: every point of each within `tol` of the other? + fn agrees(&self, other: &Flat) -> bool { + self.pts.iter().all(|p| other.near(*p)) && other.pts.iter().all(|p| self.near(*p)) + } +} + +/// Do outlines `a` and `b` (in one space) lie on each other: every point of each, flattened, within +/// `tol` of the other? `false` when either is too large to check. +#[cfg(test)] +fn outlines_agree(a: &BezPath, b: &BezPath, tol: f64) -> bool { + matches!((Flat::new(a, tol), Flat::new(b, tol)), (Some(fa), Some(fb)) if fa.agrees(&fb)) } /// `seg` as a line when it is one (a curve with its handles on its ends or on its line), else as it is. From 4fe27f830cb373bfd80a9929f2eac955ac48a05e Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:39:40 +0530 Subject: [PATCH 14/15] M7/G4: retype bounds readings tried and glyphs laid out (#4934) Readings of a shape are capped by those tried, not those kept, so a shape whose every reading fails stops at the cap. The layout check grows a window from each line start, doubling while the type draws the outlines, and starts the next line at a mismatch, so a line split at every glyph costs about twice its glyphs, not half their square; a glyph budget leaves anything past it as outlines. A tracked line of 450 glyphs: 259 ms. --- crates/engine/src/cmd/retype.rs | 74 +++++++++++++++++++-------- crates/engine/src/cmd/retype_tests.rs | 19 +++++++ crates/text/src/retype.rs | 26 +++++++++- 3 files changed, 95 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index 2ce951f812..b3a19862da 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -299,31 +299,61 @@ impl Line { /// `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 layouts are bounded by the number of glyphs. +/// The glyphs laid out are bounded by a multiple of the number of glyphs. fn verified(lines: Vec, system_layout: bool, unmatched: &mut Vec) -> Vec { - let mut budget = lines.iter().map(|l| l.pieces.len() * 2 + 2).sum::(); - let mut todo: std::collections::VecDeque = lines.into(); + // Glyphs laid out in all, at most: past it, the glyphs left unchecked stay outlines. + let mut budget = lines.iter().map(|l| l.pieces.len()).sum::().saturating_mul(8).saturating_add(256); let mut out = vec![]; - while let Some(l) = todo.pop_front() { - if budget == 0 { - // Unchecked glyphs stay outlines. - unmatched.extend(l.pieces); - continue; - } - budget -= 1; + for l in lines { let n = l.pieces.len(); - match l.first_mismatch(&l.text_object(system_layout)) { - None => out.push(l), - // The first glyph on its own may still be drawn as it was (a contextual form changed it). - Some(0) if n > 1 => { - for part in [l.part(1, n), l.part(0, 1)].into_iter().flatten() { - todo.push_front(part); - } - } - Some(0) => unmatched.extend(l.pieces.first().copied()), - Some(k) => { - for part in [l.part(k, n), l.part(0, k)].into_iter().flatten() { - todo.push_front(part); + // Each new line starts at `s`. Its type is laid out over a window from `s` that doubles + // while the type draws the window's glyphs as the outlines do, so finding where it stops + // costs about twice the glyphs before that point, not the whole rest of the line each time. + let mut s = 0; + while s < n { + let mut w = 8usize; + loop { + let e = n.min(s.saturating_add(w)); + let Some(part) = l.part(s, e) else { + s = n; + break; + }; + let Some(left) = budget.checked_sub(e - s) else { + // Unchecked glyphs stay outlines. + unmatched.extend(l.pieces.get(s..).unwrap_or_default().iter().copied()); + s = n; + break; + }; + budget = left; + match part.first_mismatch(&part.text_object(system_layout)) { + // The rest of the line is drawn as it was: one object. + None if e == n => { + out.push(part); + s = n; + break; + } + None => w = w.saturating_mul(2), + // The first glyph on its own may still be drawn as it was (a contextual form + // changed it in the line); else it stays an outline. + Some(0) => { + let alone = if e - s > 1 { l.part(s, s + 1) } else { Some(part) }; + match alone { + Some(a) if budget > 0 && a.first_mismatch(&a.text_object(system_layout)).is_none() => { + budget -= 1; + out.push(a); + } + _ => unmatched.extend(l.pieces.get(s).copied()), + } + s += 1; + break; + } + // The glyphs before the mismatch are drawn as they were: one object; the next + // line starts at the mismatch. + Some(k) => { + out.extend(l.part(s, s + k)); + s += k; + break; + } } } } diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 98736c5a4f..d691ab34fa 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -518,3 +518,22 @@ fn timing_with_hundreds_of_cjk_outlines() { s.execute("edit.undo", &json!({})).unwrap(); } } + +#[test] +fn a_long_tracked_line_is_checked_in_time() { + // Tracking splits the line at every glyph: the layout check must not lay out the rest of the + // line again after each split. + let text = "abe".repeat(150); + let mut s = session(); + let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": text, "size": 4})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": text.len(), "tracking": 50})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let t0 = std::time::Instant::now(); + let r = s.execute("type.retype", &json!({})).unwrap(); + let texts: Vec = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect(); + assert_eq!(texts.concat(), text); + assert_eq!(r["unmatched"], json!([])); + eprintln!("450 tracked glyphs: {:?}, {} objects", t0.elapsed(), texts.len()); +} diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index b778ce47dd..4c636aa1cd 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -590,7 +590,7 @@ pub fn shape_key(path: &BezPath) -> Option { /// `path` read for matching: one reading per choice of starting corners (the corner of each contour /// farthest from the centre of all the shape's corners; every tied corner when `all_ties`, else the -/// first), at most [`MAX_VARIANTS`]. Empty for a shape with nothing to match. +/// first), at most [`MAX_VARIANTS`] tried. Empty for a shape with nothing to match. fn signatures(path: &BezPath, all_ties: bool) -> Vec { let bounds = path.bounding_box(); let size = bounds.width().hypot(bounds.height()); @@ -629,10 +629,14 @@ fn signatures(path: &BezPath, all_ties: bool) -> Vec { .collect(); let mut out = vec![]; let mut pick = vec![0usize; cs.len()]; + // Readings tried, kept or not: a shape whose readings all fail (its sums run past what f64 + // holds) tries no more than this either. + let mut tried = 0usize; loop { - if out.len() >= MAX_VARIANTS { + if tried >= MAX_VARIANTS { break; } + tried += 1; if let Some(sig) = sample(&cs, &starts, &pick, accuracy) { out.push(sig); } @@ -870,6 +874,24 @@ mod tests { assert!(outlines_agree(&out, &out, tol)); } + #[test] + fn readings_that_all_fail_stop_at_the_cap() { + // 48 concentric squares (four tied corners each: 4^48 choices) so large that every reading + // overflows: the tries stop at the cap instead of running through the choices. + let mut p = BezPath::new(); + for i in 1..=48 { + let r = 1e153 * f64::from(i); + p.move_to((-r, -r)); + p.line_to((r, -r)); + p.line_to((r, r)); + p.line_to((-r, r)); + p.close_path(); + } + let t0 = std::time::Instant::now(); + assert!(signatures(&p, true).is_empty()); + assert!(t0.elapsed() < std::time::Duration::from_secs(5), "{:?}", t0.elapsed()); + } + #[test] fn the_same_corners_joined_another_way_are_another_outline() { let poly = |pts: &[(f64, f64)]| { From db525996f0bee66e041c53df40971d26bfbb6077 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:05:47 +0530 Subject: [PATCH 15/15] M7/G4: retype checks the part before a mismatch on its own (#4934) A font can place a glyph by the glyph after it, so the glyphs before a mismatch are laid out again as a line of their own before they replace their outlines. The glyph budget covers that second check. --- crates/engine/src/cmd/retype.rs | 100 +++++++++++++++++--------------- 1 file changed, 52 insertions(+), 48 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index b3a19862da..23774aaaa7 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -302,58 +302,47 @@ impl Line { /// The glyphs laid out are bounded by a multiple of the number of glyphs. fn verified(lines: Vec, system_layout: bool, unmatched: &mut Vec) -> Vec { // Glyphs laid out in all, at most: past it, the glyphs left unchecked stay outlines. - let mut budget = lines.iter().map(|l| l.pieces.len()).sum::().saturating_mul(8).saturating_add(256); + let mut budget = lines.iter().map(|l| l.pieces.len()).sum::().saturating_mul(16).saturating_add(256); + let mut todo: std::collections::VecDeque = lines.into(); let mut out = vec![]; - for l in lines { + while let Some(l) = todo.pop_front() { let n = l.pieces.len(); - // Each new line starts at `s`. Its type is laid out over a window from `s` that doubles - // while the type draws the window's glyphs as the outlines do, so finding where it stops - // costs about twice the glyphs before that point, not the whole rest of the line each time. - let mut s = 0; - while s < n { - let mut w = 8usize; - loop { - let e = n.min(s.saturating_add(w)); - let Some(part) = l.part(s, e) else { - s = n; + // The line's type is laid out over a window from its start that doubles while the type + // draws the window's glyphs as the outlines do, so finding where it stops costs about + // twice the glyphs before that point, not the whole rest of the line each time. + let mut w = 8usize; + loop { + let e = n.min(w); + let Some(part) = l.part(0, e) else { break }; + let Some(left) = budget.checked_sub(e) else { + // Unchecked glyphs stay outlines. + unmatched.extend(l.pieces.iter().copied()); + break; + }; + budget = left; + match part.first_mismatch(&part.text_object(system_layout)) { + // The whole line is drawn as it was: one object. + None if e == n => { + out.push(part); break; - }; - let Some(left) = budget.checked_sub(e - s) else { - // Unchecked glyphs stay outlines. - unmatched.extend(l.pieces.get(s..).unwrap_or_default().iter().copied()); - s = n; + } + None => w = w.saturating_mul(2), + // The first glyph on its own may still be drawn as it was (a contextual form + // changed it in the line); else it stays an outline. Checked again either way. + Some(0) if n > 1 => { + todo.extend_front_parts(&l, [(0, 1), (1, n)]); + break; + } + Some(0) => { + unmatched.extend(l.pieces.first().copied()); + break; + } + // The glyphs before the mismatch, then the rest, each checked as a line of its + // own: the type before the mismatch may draw otherwise without what follows it (a + // font can place a glyph by the glyph after it). + Some(k) => { + todo.extend_front_parts(&l, [(0, k), (k, n)]); break; - }; - budget = left; - match part.first_mismatch(&part.text_object(system_layout)) { - // The rest of the line is drawn as it was: one object. - None if e == n => { - out.push(part); - s = n; - break; - } - None => w = w.saturating_mul(2), - // The first glyph on its own may still be drawn as it was (a contextual form - // changed it in the line); else it stays an outline. - Some(0) => { - let alone = if e - s > 1 { l.part(s, s + 1) } else { Some(part) }; - match alone { - Some(a) if budget > 0 && a.first_mismatch(&a.text_object(system_layout)).is_none() => { - budget -= 1; - out.push(a); - } - _ => unmatched.extend(l.pieces.get(s).copied()), - } - s += 1; - break; - } - // The glyphs before the mismatch are drawn as they were: one object; the next - // line starts at the mismatch. - Some(k) => { - out.extend(l.part(s, s + k)); - s += k; - break; - } } } } @@ -361,6 +350,21 @@ fn verified(lines: Vec, system_layout: bool, unmatched: &mut Vec) 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]); +} + +impl FrontParts for std::collections::VecDeque { + fn extend_front_parts(&mut self, l: &Line, ranges: [(usize, usize); N]) { + for (a, b) in ranges.into_iter().rev() { + if let Some(p) = l.part(a, b) { + self.push_front(p); + } + } + } +} + fn space_advance(face: &vectorcraft_text::FontFace) -> f64 { face.mapped_chars().iter().find(|(c, _)| *c == ' ').map(|(_, g)| face.advance(*g)).unwrap_or(0.0) }