M7/G4: Type › Retype, phase 1 (#4934)

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.
This commit is contained in:
ruchirguitar
2026-11-18 02:20:06 +05:30
parent 36b5a5920c
commit 24a37f8ba3
10 changed files with 827 additions and 13 deletions
+2
View File
@@ -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());
+293
View File
@@ -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
//! (<https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html>,
//! <https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html>):
//! 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<CommandSpec> {
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<Piece>) {
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<Arc<vectorcraft_text::FontFace>> {
let mut families: Vec<String> = 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<NodeId>,
text: String,
face: Arc<vectorcraft_text::FontFace>,
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<Value> {
const C: &str = "type.retype";
let fonts: Vec<String> = 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::<Result<_>>()?
}
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<Vec<GlyphMatch>> = 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<Line> = 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<Arc<Node>> = 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<NodeId> = 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::<Vec<_>>(),
"texts": lines.iter().map(|l| l.text.clone()).collect::<Vec<_>>(),
"fonts": lines.iter().map(|l| json!({"family": l.face.family, "style": l.face.style, "size": l.scale * l.face.units_per_em()})).collect::<Vec<_>>(),
"unmatched": unmatched.iter().map(|i| i.0).collect::<Vec<_>>(),
}))
}
#[cfg(test)]
#[path = "retype_tests.rs"]
mod tests;
+120
View File
@@ -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<u64> = 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));
}
+6
View File
@@ -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<Arc<FontFace>> {
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<Arc<FontFace>> {
+1
View File
@@ -26,6 +26,7 @@ mod justify;
mod kashida;
mod kept;
mod layout;
pub mod retype;
mod shape;
#[cfg(not(target_arch = "wasm32"))]
mod suitcase;
+384
View File
@@ -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<FontFace>,
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<Point>,
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<Arc<FontFace>>,
entries: Vec<Entry>,
/// Entry indices by contour count, sorted by invariant.
buckets: HashMap<usize, Vec<usize>>,
}
impl RetypeIndex {
/// Index the outline glyphs of `faces` (the first [`MAX_FACES`], each face once).
pub fn build(db: &FontDb, faces: impl IntoIterator<Item = Arc<FontFace>>) -> Self {
let mut kept: Vec<Arc<FontFace>> = 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<u32, char> = 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<usize, Vec<usize>> = 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<FontFace>] {
&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<GlyphMatch> {
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<usize, GlyphMatch> = 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<Vec<Vec<PathSeg>>> {
if path.elements().len() > MAX_ELEMENTS {
return None;
}
let mut out: Vec<Vec<PathSeg>> = vec![];
let mut cur: Vec<PathSeg> = vec![];
let (mut start, mut last) = (Point::ZERO, Point::ZERO);
let mut flush = |cur: &mut Vec<PathSeg>, 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<Signature> {
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<f64> = 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::<f64>() / n, pts.iter().map(|p| p.y).sum::<f64>() / 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::<f64>() / 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());
}
}
+3 -2
View File
File diff suppressed because one or more lines are too long
+3 -2
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+3 -2
View File
@@ -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. |