From 782b6782ffb9609728b7d116540f992716e91401 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 13:29:45 -0800 Subject: [PATCH] Retype: a split compound must paint what the compound paints, and counters too narrow to probe stay outlines The parts of a split compound path are set as separate glyphs, so an overlap that the compound's fill rule leaves unpainted would come out painted. A split whose parts paint differently from the compound, whose combined outline is too large to probe, or whose parts' boxes overlap in a strip too thin to probe, stays an outline. A counter narrower than three times the outline tolerance cannot be checked by the fill probes, so the shape stays an outline. The params text says a command errors when no shape becomes type. --- crates/engine/src/cmd/retype.rs | 41 ++++++--- crates/engine/src/cmd/retype_tests.rs | 39 +++++++- crates/text/src/retype.rs | 128 +++++++++++++++++++++++++- docs/mcp.md | 6 +- 4 files changed, 193 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index d7381200f9..a7fbc31754 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -46,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 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", + "{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; a contour narrower than three times the outline tolerance, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, also keep the shape an outline); 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 becomes type, or when tolerance is not a number from 0 to 0.05", has_selected_path, retype )] @@ -533,13 +533,14 @@ fn split_groups(path: &BezPath, budget: &mut usize) -> Vec { /// a path's candidates: its `part` flag is set for a part of a split shape, whose contours Make /// Compound Path may have turned the other way round, and its `near` flag allows near matches. /// Exact matches come first: the whole shape, then its groups, then the whole shape nearly, then -/// its groups nearly. -fn parts(path: &BezPath, groups: &[BezPath], find: &dyn Fn(&BezPath, bool, bool) -> Vec) -> Vec> { +/// its groups nearly. A split of several parts is kept only when `together` accepts the paths of +/// its runs (the parts, set one beside another, paint what the shape paints). +fn parts(path: &BezPath, groups: &[BezPath], find: &dyn Fn(&BezPath, bool, bool) -> Vec, together: &dyn Fn(&[BezPath]) -> bool) -> Vec> { let whole = find(path, false, false); if !whole.is_empty() { return vec![whole]; } - let exact = split_parts(groups, &|run| find(run, true, false)); + let exact = split_parts(groups, &|run| find(run, true, false), together); if !exact.is_empty() { return exact; } @@ -547,12 +548,13 @@ fn parts(path: &BezPath, groups: &[BezPath], find: &dyn Fn(&BezPath, bool, bo if !whole.is_empty() { return vec![whole]; } - split_parts(groups, &|run| find(run, true, true)) + split_parts(groups, &|run| find(run, true, true), together) } /// [`parts`] of a shape split into contour `groups`, each run's candidates from `find`; empty for -/// no groups and when the groups cannot all be matched. -fn split_parts(groups: &[BezPath], find: &dyn Fn(&BezPath) -> Vec) -> Vec> { +/// no groups, when the groups cannot all be matched and when `together` rejects the runs of a split +/// of several parts. +fn split_parts(groups: &[BezPath], find: &dyn Fn(&BezPath) -> Vec, together: &dyn Fn(&[BezPath]) -> bool) -> Vec> { if groups.is_empty() { return vec![]; } @@ -578,12 +580,17 @@ fn split_parts(groups: &[BezPath], find: &dyn Fn(&BezPath) -> Vec) -> Vec< } } let mut out = vec![]; + let mut runs = vec![]; let mut i = 0; while i < g { let Some(Some((n, cands))) = chosen.get_mut(i).map(Option::take) else { return vec![] }; out.push(cands); + runs.push(groups.get(i..i + n).map(joined).unwrap_or_default()); i += n; } + if out.len() > 1 && !together(&runs) { + return vec![]; + } out } @@ -714,14 +721,18 @@ fn retype(s: &mut Session, p: &Value) -> Result { 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, &|p, part, near| find(p, part, near, pc.filled.then_some(pc.nonzero))) } - }) - .collect(); + let found: Vec>> = pieces + .iter() + .zip(&groups) + .map(|(pc, g)| { + if pc.keeps_outline { + return vec![]; + } + let fill = pc.filled.then_some(pc.nonzero); + let together = |runs: &[BezPath]| fill.is_none_or(|nz| vectorcraft_text::retype::parts_paint_alike(&pc.path, runs, nz, tolerance)); + parts(&pc.path, g, &|p, part, near| find(p, part, near, fill), &together) + }) + .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 0a99f20924..fc2817fe7c 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -850,6 +850,35 @@ fn a_compound_whose_parts_are_not_all_glyphs_stays_whole() { assert!(s.doc().unwrap().doc == before, "nothing changes"); } +#[test] +fn glyphs_that_overlap_in_an_even_odd_compound_stay_an_outline() { + let mut s = session(); + // Two o's moved onto each other and made into one compound path: the even-odd rule leaves + // the overlap unpainted, and two glyphs set side by side would paint it. + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "oo", "size": 40})); + let kids = children_of(&s, g); + s.execute("object.move", &json!({"ids": [kids[1]], "dx": -9, "dy": 0})).unwrap(); + s.execute("select.set", &json!({"ids": kids})).unwrap(); + let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [c]})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let e = match s.execute("type.retype", &json!({})) { + Ok(r) => panic!("the overlapping o's became type: {r}"), + Err(e) => e.to_string(), + }; + assert!(e.contains("(1 checked)"), "{e}"); + assert!(s.doc().unwrap().doc == before, "nothing changes"); +} + +#[test] +fn glyphs_side_by_side_in_an_even_odd_compound_still_become_type() { + let mut s = session(); + let c = one_compound(&mut s, "oo"); + s.execute("select.set", &json!({"ids": [c]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["oo"]), "{r}"); +} + #[test] fn a_compound_whose_glyph_stays_an_outline_keeps_its_other_glyphs_too() { let mut s = session(); @@ -896,13 +925,15 @@ fn a_split_takes_a_shorter_run_when_the_longest_leaves_a_group_unmatched() { } }; let groups = all_groups(&p); - assert_eq!(super::parts(&p, &groups, &find), vec![vec!["A"], vec!["BC"]]); + assert_eq!(super::parts(&p, &groups, &find, &|_| true), vec![vec!["A"], vec!["BC"]]); + // A split the parts' paint does not allow is dropped. + assert!(super::parts(&p, &groups, &find, &|_| false).is_empty()); // With no way to match every group, nothing. let none = |path: &kurbo::BezPath, part: bool, _near: bool| -> Vec<&'static str> { let b = path.bounding_box(); if part && b.x0.round() as i64 == 0 && b.x1.round() as i64 == 140 { vec!["AB"] } else { vec![] } }; - assert!(super::parts(&p, &groups, &none).is_empty()); + assert!(super::parts(&p, &groups, &none, &|_| true).is_empty()); } /// `path`'s contour groups, with no limit on the contours grouped. @@ -929,7 +960,7 @@ fn exact_matches_of_the_parts_come_before_a_near_match_of_the_whole() { } }; let groups = all_groups(&p); - assert_eq!(super::parts(&p, &groups, &find), vec![vec!["period"], vec!["period"]]); + assert_eq!(super::parts(&p, &groups, &find, &|_| true), vec![vec!["period"], vec!["period"]]); // When the parts match only nearly too, the whole near match comes first. let near_only = |path: &kurbo::BezPath, part: bool, near: bool| -> Vec<&'static str> { let b = path.bounding_box(); @@ -939,7 +970,7 @@ fn exact_matches_of_the_parts_come_before_a_near_match_of_the_whole() { _ => vec![], } }; - assert_eq!(super::parts(&p, &groups, &near_only), vec![vec!["dieresis"]]); + assert_eq!(super::parts(&p, &groups, &near_only, &|_| true), vec![vec!["dieresis"]]); } #[test] diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index 27c3b47313..8a65126569 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -1120,8 +1120,13 @@ const MAX_FILL_PROBES: usize = 512; /// `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. +/// probed. `false` when a contour of the shape is narrower than `3 tol` on its shorter side, since +/// the probes cannot then tell whether the area inside it is painted; `true` when an outline is too +/// large to probe. fn paints_alike(shape: &BezPath, nonzero: bool, glyph: &BezPath, tol: f64) -> bool { + if narrow_contour(shape, 3.0 * tol) { + return false; + } 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) { @@ -1149,6 +1154,81 @@ fn paints_alike(shape: &BezPath, nonzero: bool, glyph: &BezPath, tol: f64) -> bo true } +/// Does `path` have a contour no wider than `width` on its shorter side that lies inside another +/// contour (a counter)? +fn narrow_contour(path: &BezPath, width: f64) -> bool { + let mut all: Vec = vec![]; + for el in path.elements() { + if matches!(el, PathEl::MoveTo(_)) { + all.push(BezPath::new()); + } + if let Some(cur) = all.last_mut() { + cur.push(*el); + } + } + all.iter().enumerate().any(|(i, c)| { + let Some(PathEl::MoveTo(at)) = c.elements().first().copied() else { return false }; + let bb = c.bounding_box(); + bb.width().min(bb.height()) <= width && all.iter().enumerate().any(|(j, o)| j != i && o.winding(at) != 0) + }) +} + +/// Do `parts` (the runs of contours a compound path `shape` is split into, each already checked +/// by [`RetypeIndex::painted_agrees`] on its own) paint together the area `shape` paints, the +/// shape filled by the nonzero rule when `nonzero` is set and by the even-odd rule otherwise? Each +/// part is read by the same rule, and the glyphs that replace them are set one beside another, so +/// an overlap that the shape's rule cancels would come out painted. Probes lie on both sides of +/// every part's outline, as in [`RetypeIndex::painted_agrees`]; `tolerance` is the one the parts +/// were found with (0 for exact matches). `false` when an outline is too large to probe, and when +/// two parts' boxes overlap in a strip no wider than `3 tol`, which the probes cannot see into. +pub fn parts_paint_alike(shape: &BezPath, parts: &[BezPath], nonzero: bool, tolerance: f64) -> bool { + 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 painted = |p: &BezPath, q: Point| { + let w = p.winding(q); + if nonzero { w != 0 } else { w.rem_euclid(2) == 1 } + }; + let mut flats = vec![]; + for p in parts.iter().chain(std::iter::once(shape)) { + let Some(f) = Flat::new(p, tol) else { return false }; + flats.push(f); + } + // Two parts whose boxes overlap in a strip too thin to probe cannot be told from parts that + // overlap in their paint. + let boxes: Vec = parts.iter().map(Shape::bounding_box).collect(); + for (i, a) in boxes.iter().enumerate() { + for b in boxes.iter().skip(i + 1) { + let both = a.intersect(*b); + if both.area() > 0.0 && both.width().min(both.height()) <= 3.0 * tol { + return false; + } + } + } + for own in flats.iter().take(parts.len()) { + let step = own.segs.len().div_ceil(MAX_FILL_PROBES).max(1); + for (s, e) in own.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); + 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 flats.iter().any(|f| f.near(q)) { + continue; + } + if painted(shape, q) != parts.iter().any(|o| painted(o, q)) { + 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)] @@ -1867,6 +1947,52 @@ mod tests { 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 a_counter_too_narrow_to_probe_does_not_count_as_agreeing() { + let square = |x0: f64, y0: f64, x1: f64, y1: f64, back: bool| { + let p = kurbo::Rect::new(x0, y0, x1, y1).to_path(0.1); + if back { p.reverse_subpaths() } else { p } + }; + // A 100 by 100 square with a 10 by 10 counter: the shape's counter runs the way its outer + // contour does (filled by the nonzero rule), the glyph's runs the other way (a hole). + let mut filled = square(0.0, 0.0, 100.0, 100.0, false); + filled.extend(square(45.0, 45.0, 55.0, 55.0, false).iter()); + let mut holed = square(0.0, 0.0, 100.0, 100.0, false); + holed.extend(square(45.0, 45.0, 55.0, 55.0, true).iter()); + let tol = 100.0_f64.hypot(100.0) * 0.5 * 3.0 * MAX_TOLERANCE; + assert!(!paints_alike(&filled, true, &holed, tol), "no probe can see the counter"); + // A counter wide enough to probe is told apart as before. + let mut wide = square(0.0, 0.0, 100.0, 100.0, false); + wide.extend(square(10.0, 10.0, 90.0, 90.0, false).iter()); + let mut wide_hole = square(0.0, 0.0, 100.0, 100.0, false); + wide_hole.extend(square(10.0, 10.0, 90.0, 90.0, true).iter()); + assert!(!paints_alike(&wide, true, &wide_hole, 1.0)); + assert!(paints_alike(&wide_hole, true, &wide_hole, 1.0)); + } + + #[test] + fn parts_that_overlap_under_the_even_odd_rule_do_not_paint_the_shape() { + let square = |x0: f64, y0: f64, x1: f64, y1: f64| kurbo::Rect::new(x0, y0, x1, y1).to_path(0.1); + let (a, b) = (square(0.0, 0.0, 60.0, 60.0), square(40.0, 0.0, 100.0, 60.0)); + let mut both = a.clone(); + both.extend(b.iter()); + assert!(!parts_paint_alike(&both, &[a.clone(), b.clone()], false, 0.0), "the overlap is a hole in the shape"); + assert!(parts_paint_alike(&both, &[a.clone(), b.clone()], true, 0.0), "the nonzero rule paints it"); + // Windings that cancel under the nonzero rule leave the overlap unpainted too. + let mut turned = a.clone(); + turned.extend(b.reverse_subpaths().iter()); + assert!(!parts_paint_alike(&turned, &[a.clone(), b.reverse_subpaths()], true, 0.0)); + // An overlap too thin for the probes to land in is not taken for none. + let thin = square(59.9, 0.0, 100.0, 60.0); + let mut strip = a.clone(); + strip.extend(thin.iter()); + assert!(!parts_paint_alike(&strip, &[a.clone(), thin], false, 0.0)); + let apart = square(80.0, 0.0, 140.0, 60.0); + let mut aside = a.clone(); + aside.extend(apart.iter()); + assert!(parts_paint_alike(&aside, &[a, apart], false, 0.0)); + } + #[test] fn near_matching_with_no_work_left_returns_nothing() { let db = FontDb::global(); diff --git a/docs/mcp.md b/docs/mcp.md index 9fd086b690..4de3405a7b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10961,7 +10961,11 @@ first, then exact matches of its groups, then near matches of the whole shape, t compound becomes type only when every one of its glyphs does; otherwise it stays as it is and is reported once in `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 +whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it. A shape with a contour narrower than three times the +outline tolerance on its shorter side cannot be checked this way and stays an outline: at `tolerance` 0.05, a +counter 10 units wide in a 100 by 100 shape. The glyphs of a compound path that splits into several are set one beside +another, so a split whose parts overlap where the shape's fill rule leaves the overlap unpainted (two o's on each +other under the even-odd rule) stays an outline. 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