From 744f32977a75f5b0da273f9f207d2ea66c71b1be Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 11:52:00 -0800 Subject: [PATCH] Retype: near-only glyphs stay out of exact matching, and a glyph must paint the shape's area Glyphs indexed only for near matching no longer take part in exact matching, so a curve split in two is no exact match at tolerance 0. Each pose of a match reports its own residual. A near match spends its comparison allowance from the shared budget in one step and returns what it leaves, and does no sampling once the budget is spent. A glyph replaces a filled shape only when it paints the area the shape paints under the shape's fill rule. The docs define the tolerance by the outline spread and separate the no-conversion error from the unmatched list. --- crates/engine/src/cmd/retype.rs | 41 ++++-- crates/text/src/retype.rs | 233 ++++++++++++++++++++++++++++++-- docs/mcp.md | 7 +- docs/type-parity.md | 2 +- 4 files changed, 260 insertions(+), 23 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index 253edcd3a3..7daa1d424c 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -26,6 +26,7 @@ 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_geom::FillRule; use vectorcraft_text::FontDb; use vectorcraft_text::retype::{GlyphMatch, RetypeIndex}; @@ -45,7 +46,7 @@ pub fn specs() -> Vec { "Retype", ["Type"], None, - "{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} 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; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's size, is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups and 512 contours, and 16,384 contours per command) is split into them, and becomes type only when every one of them matches; 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; with a tolerance, within it); 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, score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…], truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error when no shape matches, or when tolerance is not a number from 0 to 0.05", + "{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} 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; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups and 512 contours, and 16,384 contours per command) is split into them, and becomes type only when every one of them matches; 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; with a tolerance, within it); a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it); 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, score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error, with no unmatched list, when no shape matches, or when tolerance is not a number from 0 to 0.05", has_selected_path, retype )] @@ -64,6 +65,10 @@ struct Piece { /// art must stay painted after it: the line ends here. after_barrier: bool, path: BezPath, + /// The shape is filled by the nonzero rule, not the even-odd rule. + nonzero: bool, + /// The shape has a visible fill: a shape that only has a stroke paints no area to compare. + filled: bool, appearance: Appearance, /// The shape's own transparency, which the new type takes. opacity: f32, @@ -87,11 +92,13 @@ fn collect(n: &Node, parent: Option, depth: usize, barrier: &mut bool, t *barrier = true; return; } - let piece = |path: BezPath, after_barrier: bool| Piece { + let piece = |path: BezPath, after_barrier: bool, rule: FillRule| Piece { id: n.id, parent, after_barrier, path, + nonzero: rule == FillRule::NonZero, + filled: n.appearance.fill().is_some_and(|f| f.visible && !f.paint.is_none()), appearance: (*n.appearance).clone(), opacity: n.opacity, blend: n.blend, @@ -104,8 +111,10 @@ fn collect(n: &Node, parent: Option, depth: usize, barrier: &mut bool, t } } // 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, .. } => { + NodeKind::Path { path, rule, clipping: false, guide: false, .. } if path.is_closed() => { + out.push(piece(path.to_bezpath(), std::mem::take(barrier), *rule)) + } + NodeKind::Compound { children, rule } => { let mut path = BezPath::new(); for c in children { match &c.kind { @@ -117,7 +126,7 @@ fn collect(n: &Node, parent: Option, depth: usize, barrier: &mut bool, t } } } - out.push(piece(path, std::mem::take(barrier))); + out.push(piece(path, std::mem::take(barrier), *rule)); } // Live type, images, clip groups and the rest stay, and the type after them stays after them. _ => *barrier = true, @@ -692,13 +701,27 @@ fn retype(s: &mut Session, p: &Value) -> Result { RetypeIndex::build_near(db, candidate_faces(db, d, &fonts), &wanted, &near_wanted) }; // Exact matches first; near ones, when allowed, only for a path with none. - let find = |path: &BezPath, part: bool, near: bool| { - let exact = if part { index.matches_either_way(path) } else { index.all_matches(path) }; - if exact.is_empty() && near { index.near_matches(path, tolerance) } else { exact } + // With a visible fill, a glyph is kept only when it paints the area the shape paints under + // the shape's fill rule (`fill` is `Some(nonzero)`). + let find = |path: &BezPath, part: bool, near: bool, fill: Option| { + let painted = |ms: Vec, tol: f64| -> Vec { + match fill { + Some(nonzero) => ms.iter().filter_map(|m| index.painted_agrees(m, path, nonzero, tol)).collect(), + None => ms, + } + }; + let exact = painted(if part { index.matches_either_way(path) } else { index.all_matches(path) }, 0.0); + if exact.is_empty() && near { painted(index.near_matches(path, tolerance), tolerance) } else { exact } }; // Each shape's parts (one, unless it holds several glyphs), each with its candidates. let found: Vec>> = - pieces.iter().zip(&groups).map(|(pc, g)| if pc.keeps_outline { vec![] } else { parts(&pc.path, g, &find) }).collect(); + pieces + .iter() + .zip(&groups) + .map(|(pc, g)| { + if pc.keeps_outline { vec![] } else { parts(&pc.path, g, &|p, part, near| find(p, part, near, pc.filled.then_some(pc.nonzero))) } + }) + .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/text/src/retype.rs b/crates/text/src/retype.rs index 9fd06a8f95..27c3b47313 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -106,6 +106,11 @@ pub struct GlyphMatch { pub contours: usize, /// Other poses the glyph fits the shape in equally (a glyph that looks the same turned). pub alts: Vec, + /// The leftover distance of each of [`Self::alts`], in the same order. + pub alt_residuals: Vec, + /// The leftover distance of the glyph's own pose: [`Self::residual`] is the least over all its + /// poses, which orders the matches. + pub pose_residual: f64, } /// Where and how a glyph lies: its size, turn and origin. @@ -134,11 +139,14 @@ 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 { + let own = (Pose { scale: self.scale, angle: self.angle, origin: self.origin }, self.pose_residual); + let alts = self.alts.iter().copied().zip(self.alt_residuals.iter().copied().chain(std::iter::repeat(self.residual))); + std::iter::once(own).chain(alts).map(move |(p, residual)| GlyphMatch { scale: p.scale, angle: p.angle, origin: p.origin, + residual, + pose_residual: residual, ..self.clone() }) } @@ -165,6 +173,9 @@ struct Entry { sig: Signature, /// The glyph's outline in font units, for the whole-outline check. outline: BezPath, + /// Whether the glyph was indexed for its exact key: only these take part in exact matching, + /// and the ones indexed only for near matching ([`RetypeIndex::near_matches`]) do not. + exact: bool, } /// The glyphs of a set of faces, ready to match shapes against. @@ -174,6 +185,8 @@ pub struct RetypeIndex { entries: Vec, /// Entry indices by contour count, sorted by invariant. buckets: HashMap>, + /// Entry indices by face id and glyph id. + by_glyph: HashMap<(u32, u32), usize>, /// The point comparisons [`Self::near_matches`] may still make, over every shape. near_work: AtomicU64, } @@ -241,7 +254,7 @@ impl RetypeIndex { if keys.contains(&key) { let outline = db.outline_uncached(face, gid); if let Some(sig) = signatures(&outline, false).into_iter().next() { - entries.push(Entry { face: fi, gid, ch, sig, outline }); + entries.push(Entry { face: fi, gid, ch, sig, outline, exact: true }); } continue; } @@ -264,7 +277,7 @@ impl RetypeIndex { break 'faces; } if let Some(sig) = signatures(&outline, false).into_iter().next() { - entries.push(Entry { face: fi, gid, ch, sig, outline }); + entries.push(Entry { face: fi, gid, ch, sig, outline, exact: false }); } } } @@ -278,7 +291,39 @@ impl RetypeIndex { x.total_cmp(&y) }); } - RetypeIndex { faces: kept, entries, buckets, near_work: AtomicU64::new(NEAR_WORK) } + let by_glyph = entries.iter().enumerate().filter_map(|(i, e)| Some(((kept.get(e.face)?.id(), e.gid), i))).collect(); + RetypeIndex { faces: kept, entries, buckets, by_glyph, near_work: AtomicU64::new(NEAR_WORK) } + } + + /// `m` kept to the poses in which the glyph paints the area `shape` paints, the shape filled + /// by the nonzero rule when `nonzero` is set and by the even-odd rule otherwise, the glyph + /// filled by the nonzero rule. Two outlines on each other can paint different areas: a ring + /// whose inner contour runs the same way as its outer one, filled by the nonzero rule, has no + /// hole. Probes lie on both sides of the shape's outline, left out where either outline is + /// within reach of them. `tolerance` is the one `m` was found with (0 for an exact match). The + /// first pose that agrees comes first; `None` when none does. + pub fn painted_agrees(&self, m: &GlyphMatch, shape: &BezPath, nonzero: bool, tolerance: f64) -> Option { + let Some(e) = self.by_glyph.get(&(m.face.id(), m.gid)).and_then(|i| self.entries.get(*i)) else { return Some(m.clone()) }; + let bb = shape.bounding_box(); + let tol = bb.width().hypot(bb.height()) * 0.5 * OUTLINE_TOLERANCE.max(3.0 * tolerance.clamp(0.0, MAX_TOLERANCE)); + let mut agreeing = m.poses().filter(|p| { + let onto = Affine::new([ + p.scale * p.angle.cos(), + p.scale * p.angle.sin(), + -p.scale * p.angle.sin(), + p.scale * p.angle.cos(), + p.origin.x, + p.origin.y, + ]); + paints_alike(shape, nonzero, &(onto * e.outline.clone()), tol) + }); + let first = agreeing.next()?; + let rest: Vec = agreeing.collect(); + Some(GlyphMatch { + alts: rest.iter().map(|p| Pose { scale: p.scale, angle: p.angle, origin: p.origin }).collect(), + alt_residuals: rest.iter().map(|p| p.pose_residual).collect(), + ..first + }) } /// The faces indexed. @@ -341,6 +386,9 @@ impl RetypeIndex { if e.sig.invariant > hi { break; } + if !e.exact { + continue; + } let Some(face) = self.faces.get(e.face) else { continue }; // Each reading of the shape (its tied starting corners) that fits the glyph is a pose. let mut poses: Vec<(Pose, f64)> = vec![]; @@ -367,7 +415,7 @@ impl RetypeIndex { } // 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 Some(((pose, own_residual), rest)) = poses.split_first() else { continue }; let residual = poses.iter().map(|(_, r)| *r).fold(f64::INFINITY, f64::min); let m = GlyphMatch { face: face.clone(), @@ -380,6 +428,8 @@ impl RetypeIndex { exact: true, contours: e.sig.contours, alts: rest.iter().map(|(p, _)| *p).collect(), + alt_residuals: rest.iter().map(|(_, r)| *r).collect(), + pose_residual: *own_residual, }; out.push((e.face, m)); } @@ -408,6 +458,10 @@ impl RetypeIndex { return vec![]; } let tolerance = tolerance.min(MAX_TOLERANCE); + // With no comparisons left, no shape is sampled or ranked. + if self.near_work.load(Ordering::Acquire) == 0 { + return vec![]; + } let Some(s) = near_signature(shape) else { return vec![] }; let Some(list) = self.buckets.get(&s.contours) else { return vec![] }; let lo = s.invariant * (1.0 - NEAR_INVARIANT_SLACK); @@ -433,9 +487,16 @@ impl RetypeIndex { list.iter().skip(start).filter_map(|i| self.entries.get(*i)).take_while(|e| e.sig.invariant <= hi).map(|e| (apart(e), e)).collect(); near.sort_by(|a, b| a.0.total_cmp(&b.0)); near.truncate(NEAR_FITS); - let total = self.near_work.load(Ordering::Relaxed); - let mut work = total.min(NEAR_SHAPE_WORK); - let given = work; + // This call's allowance comes out of the index's budget in one step, so calls that overlap + // never spend the same comparisons; what it leaves unspent goes back afterward. + let mut seen = self.near_work.load(Ordering::Acquire); + let mut work = loop { + let take = seen.min(NEAR_SHAPE_WORK); + match self.near_work.compare_exchange_weak(seen, seen - take, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => break take, + Err(now) => seen = now, + } + }; for (_, e) in near { if work == 0 { break; @@ -449,6 +510,7 @@ impl RetypeIndex { let mut poses = fits.into_iter().filter(|f| f.1 <= tolerance).filter_map(|(z, r)| Some((near_pose(e, &s, z, flat, tol)?, r))).take(MAX_NEAR_POSES); let Some((pose, residual)) = poses.next() else { continue }; + let rest: Vec<(Pose, f64)> = poses.collect(); let m = GlyphMatch { face: face.clone(), gid: e.gid, @@ -459,11 +521,13 @@ impl RetypeIndex { residual, exact: false, contours: e.sig.contours, - alts: poses.map(|(p, _)| p).collect(), + alts: rest.iter().map(|(p, _)| *p).collect(), + alt_residuals: rest.iter().map(|(_, r)| *r).collect(), + pose_residual: residual, }; out.push((e.face, m)); } - self.near_work.store(total.saturating_sub(given - work), Ordering::Relaxed); + self.near_work.fetch_add(work, Ordering::AcqRel); 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)) @@ -1049,6 +1113,42 @@ impl Flat { } } +/// Shape segments [`paints_alike`] probes beside, at most. +const MAX_FILL_PROBES: usize = 512; + +/// Do `shape` (filled by the nonzero rule when `nonzero` is set, else by the even-odd rule) and +/// `glyph` (filled by the nonzero rule), whose outlines lie within `tol` of each other, paint the +/// same area? Each probe lies `1.5 tol` or `3 tol` to a side of the middle of a segment of the shape's +/// outline; one within `tol` of either outline is skipped, so a region narrower than that is not +/// probed. `true` when an outline is too large to probe. +fn paints_alike(shape: &BezPath, nonzero: bool, glyph: &BezPath, tol: f64) -> bool { + let (Some(fs), Some(fg)) = (Flat::new(shape, tol), Flat::new(glyph, tol)) else { return true }; + let step = fs.segs.len().div_ceil(MAX_FILL_PROBES).max(1); + for (s, e) in fs.segs.iter().step_by(step) { + let d = *e - *s; + let len = d.hypot(); + if len <= 0.0 || !len.is_finite() { + continue; + } + let mid = s.midpoint(*e); + // The nearer probes reach counters and gaps too narrow for the farther ones. + for reach in [1.5, 3.0] { + let side = kurbo::Vec2::new(-d.y, d.x) * (reach * tol / len); + for q in [mid + side, mid - side] { + if fs.near(q) || fg.near(q) { + continue; + } + let w = shape.winding(q); + let painted = if nonzero { w != 0 } else { w.rem_euclid(2) == 1 }; + if painted != (glyph.winding(q) != 0) { + return false; + } + } + } + } + true +} + /// 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)] @@ -1671,6 +1771,117 @@ mod tests { assert!(found.iter().any(|c| matches!(c, 'o' | 'ο')), "{found:?}"); } + /// `p` with its first curve split in two at its middle: the same outline with another key. + fn first_curve_split(p: &BezPath) -> BezPath { + let mut out = BezPath::new(); + let (mut last, mut done) = (Point::ZERO, false); + for el in p.elements() { + match *el { + PathEl::CurveTo(a, b, c) if !done => { + let (x, y) = kurbo::CubicBez::new(last, a, b, c).subdivide(); + out.curve_to(x.p1, x.p2, x.p3); + out.curve_to(y.p1, y.p2, y.p3); + done = true; + last = c; + } + PathEl::QuadTo(a, c) if !done => { + let (x, y) = kurbo::QuadBez::new(last, a, c).subdivide(); + out.quad_to(x.p1, x.p2); + out.quad_to(y.p1, y.p2); + done = true; + last = c; + } + e => { + out.push(e); + if let PathEl::MoveTo(q) | PathEl::LineTo(q) | PathEl::QuadTo(_, q) | PathEl::CurveTo(_, _, q) = e { + last = q; + } + } + } + } + out + } + + #[test] + fn a_glyph_indexed_only_for_near_matching_is_no_exact_match() { + let db = FontDb::global(); + let face = db.face("Source Sans 3", "Regular").unwrap(); + let gid = face.mapped_chars().iter().find(|(c, _)| *c == 'o').map(|(_, g)| *g).unwrap(); + let split = first_curve_split(&db.outline_uncached(&face, gid)); + let shape = Affine::translate((100.0, 200.0)) * Affine::scale(0.04) * split; + assert_ne!(shape_key(&shape), shape_key(&(Affine::scale(0.04) * db.outline_uncached(&face, gid))), "another key"); + let keys: BTreeSet = shape_key(&shape).into_iter().collect(); + let index = RetypeIndex::build_near(db, [face], &keys, &[near_key(&shape).unwrap()]); + assert!(index.all_matches(&shape).is_empty(), "exact matching sees only the glyphs of the exact keys"); + assert!(index.matches_either_way(&shape).is_empty()); + assert!(index.near_matches(&shape, 0.02).iter().any(|m| m.ch == 'o')); + } + + #[test] + fn each_pose_of_a_match_reports_its_own_residual() { + let db = FontDb::global(); + let face = db.face("Source Sans 3", "Regular").unwrap(); + let turn = std::f64::consts::FRAC_PI_2; + let m = GlyphMatch { + face, + gid: 1, + ch: 'o', + scale: 1.0, + angle: 0.0, + origin: Point::ZERO, + residual: 0.010, + exact: false, + contours: 1, + alts: vec![Pose { scale: 1.0, angle: turn, origin: Point::ZERO }], + alt_residuals: vec![0.010], + pose_residual: 0.014, + }; + let seen: Vec<(f64, f64)> = m.poses().map(|p| (p.angle, p.residual)).collect(); + assert_eq!(seen, vec![(0.0, 0.014), (turn, 0.010)]); + } + + #[test] + fn a_ring_whose_contours_run_one_way_paints_no_hole() { + let db = FontDb::global(); + let face = db.face("Source Sans 3", "Regular").unwrap(); + let gid = face.mapped_chars().iter().find(|(c, _)| *c == 'o').map(|(_, g)| *g).unwrap(); + let ring = db.outline_uncached(&face, gid); + let els = ring.elements(); + let second = els.iter().rposition(|e| matches!(e, PathEl::MoveTo(_))).unwrap(); + let (mut outer, mut inner) = (BezPath::new(), BezPath::new()); + outer.extend(els[..second].iter().copied()); + inner.extend(els[second..].iter().copied()); + let mut same_way = outer.clone(); + same_way.extend(inner.reverse_subpaths().iter()); + let (ring, same_way) = + (Affine::translate((100.0, 200.0)) * Affine::scale(0.04) * ring, Affine::translate((100.0, 200.0)) * Affine::scale(0.04) * same_way); + let keys: BTreeSet = shape_key(&ring).into_iter().collect(); + let index = RetypeIndex::build_near(db, [face], &keys, &[near_key(&same_way).unwrap()]); + // Near matching reads each contour in either direction, so the outline matches the glyph's: + // only what it paints tells them apart. + let found = index.near_matches(&same_way, 0.02); + assert!(found.iter().any(|m| m.ch == 'o'), "the outline matches"); + assert!(found.iter().all(|m| index.painted_agrees(m, &same_way, true, 0.02).is_none()), "nonzero paints the counter"); + assert!(found.iter().any(|m| index.painted_agrees(m, &same_way, false, 0.02).is_some()), "even-odd leaves it empty"); + let found = index.all_matches(&ring); + assert!(found.iter().any(|m| index.painted_agrees(m, &ring, true, 0.0).is_some()), "the glyph's own windings paint a ring"); + } + + #[test] + fn near_matching_with_no_work_left_returns_nothing() { + let db = FontDb::global(); + let face = db.face("Source Sans 3", "Regular").unwrap(); + let gid = face.mapped_chars().iter().find(|(c, _)| *c == 'o').map(|(_, g)| *g).unwrap(); + let shape = Affine::translate((100.0, 200.0)) * Affine::scale(0.04) * simplified(&db.outline_uncached(&face, gid), 4.0); + let index = RetypeIndex::build_near(db, [face], &BTreeSet::new(), &[near_key(&shape).unwrap()]); + assert!(!index.near_matches(&shape, 0.02).is_empty()); + let after = index.near_work.load(Ordering::Acquire); + assert!((NEAR_WORK - NEAR_SHAPE_WORK..NEAR_WORK).contains(&after), "one allowance at most: {after}"); + index.near_work.store(0, Ordering::Release); + assert!(index.near_matches(&shape, 0.02).is_empty()); + assert_eq!(index.near_work.load(Ordering::Acquire), 0); + } + #[test] fn a_round_glyph_with_an_off_centre_counter_near_matches_at_its_turn() { // A round outer contour fits the shape at every turn; only the counter, off the centre, diff --git a/docs/mcp.md b/docs/mcp.md index 570e3bb84c..9fd086b690 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10946,7 +10946,8 @@ glyph. `type.retype` (Type › Retype) turns outlined glyphs back into point text. By default a shape must be exactly a glyph of an available font. With `tolerance` (0 to 0.05), a shape of at most 8 contours that is no glyph exactly becomes the -glyph it is closest to when its leftover distance from that glyph, relative to the shape's size, is at most the +glyph it is closest to when its leftover distance from that glyph, relative to the shape's outline spread (the root +mean square distance of its sampled outline points from their center), is at most the tolerance: an outline simplified, a curve split in two, or contours in another order, start or direction. The tolerance and this measure are VectorCraft's own. A near-matched glyph may differ from its line by the tolerance in size, turn and place; an exact glyph keeps the exact limits unless the line's first glyph, whose size and turn the line takes, is @@ -10958,7 +10959,9 @@ remaining groups can still all be matched, so an i's stem and dot become one i. way round, as Make Compound Path leaves some of them, still matches exactly. Exact matches of the whole shape come first, then exact matches of its groups, then near matches of the whole shape, then near matches of its groups. The compound becomes type only when every one of its glyphs does; otherwise it stays as it is and is reported once in -`unmatched`. Glyphs fused into one contour are not split, and a compound path of more than 256 groups or 512 contours +`unmatched` when another shape of the selection becomes type, and the command returns an error when no shape does. A +glyph also has to paint the area the shape paints under the shape's fill rule: a compound filled by the nonzero rule +whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it. Glyphs fused into one contour are not split, and a compound path of more than 256 groups or 512 contours is matched whole only. One command groups at most 16,384 contours, in selection order; the shapes after them are matched whole only. Near matching compares a shape with at most the 256 glyphs closest to it in proportion, in at most 50 million point comparisons per shape and 2 billion per command; past them, the glyphs not yet compared are left diff --git a/docs/type-parity.md b/docs/type-parity.md index bfd821ee10..b84bdc34e1 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -56,7 +56,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Alt + numeric-keypad codes while typing (Windows: `Alt+0176` → °) | partial | #5108: on Windows the character Windows posts when Alt comes up after keypad digits is typed at the caret like any other, in the typing's undo step, and the keypad digits typed with Alt run no shortcut. With NumLock off the keypad keys (Insert, End, arrows, Clear, Home, Page Up/Down without the extended-key flag) count as digits too and don't move the caret (`windows_alt_codes` unit tests; neither NumLock on nor off has been tried on a Windows machine yet). `type.insert {code}` (Windows Alt+0 code, Windows-1252 for 128–159) and `{unicode}` (hex code point) insert a character by its code (`menucmds::insert_a_character_by_its_code`). macOS and Linux have no such system convention and egui reports a keypad digit as the top-row digit, so there it does nothing; a floating panel window doesn't receive the character | | Caret: the arrows and Delete step over whole clusters (Thai consonant with its marks, combining accents, emoji); Backspace removes one character | done | in text with right-to-left characters the arrows move in visual order and stop on both sides of a character drawn with no width, such as a zero width non-joiner | | Touch Type tool | done | moves, scales and rotates one character through its kerning, baseline shift, scales and rotation (`text.touchType`); a character with a preceding logical character on the same line can move along the line in either reading direction; the first logical character moves only up and down. Positive `dx` follows reading order. These direction rules are VectorCraft's choices. | -| Retype (identify fonts in outlines/images) | partial | Phase 1 (#4934): Type › Retype (`type.retype`) turns outlined glyphs back into point text when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. Near matches: with `tolerance` (0 to 0.05), shapes of up to 8 contours that are nearly a glyph (simplified outlines, curves split in two, contours in another order or direction) match too, and each line reports a `score`; a compound path holding several glyphs is split into them and becomes type only when all of them match. Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Missing (phase 2): glyphs fused into one contour, near matches and compound paths of several glyphs in the panel's list, opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, installed fonts not yet loaded, area text for several lines, 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) | +| 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. Near matches: with `tolerance` (0 to 0.05), shapes of up to 8 contours whose leftover distance from a glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (simplified outlines, curves split in two, contours in another order or direction) match too, and each line reports a `score`; a compound path holding several glyphs is split into them and becomes type only when all of them match. Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Missing (phase 2): glyphs fused into one contour, near matches and compound paths of several glyphs in the panel's list, opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, installed fonts not yet loaded, area text for several lines, 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. |