From e3ccd346add9c2bb196d9181b27d4e4eeb50a575 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 16:40:51 -0800 Subject: [PATCH 01/38] Selection: widget drags read the release point and a tool switch cancels them A drag of a corner, pie or blend widget, an Objects on Path widget, a bracket of type on a path or a 9-slice guide released away from its last drag event now drags there before it ends, so the release keeps what a drag to that point would show. The Objects on Path tool reads the release the same way. Switching tools during a drag of an Objects on Path widget, a bracket, a repeat control or a 9-slice guide now cancels it, as Escape does, in the Selection tool and the Objects on Path tool. Before, the preview stayed open after the tool was gone. --- crates/tools/src/blendwidget.rs | 12 ++- crates/tools/src/lib.rs | 20 +++++ crates/tools/src/mirror.rs | 16 ++++ crates/tools/src/nineslice.rs | 9 ++ crates/tools/src/objects_on_path.rs | 132 ++++++++++++++++++++++++++-- crates/tools/src/pie.rs | 10 +++ crates/tools/src/repeat_grid.rs | 11 +++ crates/tools/src/repeat_radial.rs | 11 +++ crates/tools/src/select.rs | 62 +++++++++---- crates/tools/src/select/tests.rs | 22 +++++ 10 files changed, 282 insertions(+), 23 deletions(-) diff --git a/crates/tools/src/blendwidget.rs b/crates/tools/src/blendwidget.rs index e09df663bb..3f53287625 100644 --- a/crates/tools/src/blendwidget.rs +++ b/crates/tools/src/blendwidget.rs @@ -512,7 +512,7 @@ mod tests { assert_eq!(a, vec![Action::Preview("object.blend.setEasing".into(), json!({"id": id.0, "ramp": 0.0}))], "clamped at 0"); let a = t.pointer(&c, &ev(PointerKind::Drag, at + Vec2::new(500.0, 0.0))); assert_eq!(a, vec![Action::Preview("object.blend.setEasing".into(), json!({"id": id.0, "ramp": 100.0}))], "clamped at 100"); - assert_eq!(t.pointer(&c, &ev(PointerKind::Up, at)), vec![Action::Commit]); + assert_eq!(t.pointer(&c, &ev(PointerKind::Up, at + Vec2::new(500.0, 0.0))), vec![Action::Commit]); // A click that doesn't move sends nothing. assert!(t.pointer(&c, &ev(PointerKind::Down, at)).is_empty()); assert!(t.pointer(&c, &ev(PointerKind::Up, at)).is_empty()); @@ -546,6 +546,16 @@ mod tests { assert_eq!(a[1], Action::Preview("object.blend.setEasing".into(), json!({"id": id.0, "ramp": 50.0}))); } + /// A drag with the Selection tool reads where it is released, and a tool switch cancels it. + #[test] + fn a_drag_reads_its_release() { + let (d, _, s) = blend_doc(&[(100.0, 200.0), (300.0, 200.0)], eased()); + let p = paint(); + let c = cx(&d, &s, &p); + let at = Point::new(200.0, 216.0); + check_widget_release_and_tool_switch(&c, at, at + Vec2::new(20.0, 0.0), at + Vec2::new(40.0, 0.0)); + } + /// Switching away from the Selection or Blend tool during a drag cancels it, and after a press /// that has not moved there is nothing to put back. #[test] diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 0b7bef755f..781d86da41 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -600,6 +600,26 @@ pub(crate) mod testutil { PaintDefaults::default() } + /// With the Selection tool, a widget pressed at `at` and dragged to `q`, then released at `r`, is + /// dragged to `r` before the drag ends: the release keeps what a drag to `r` shows. Switching + /// tools during the drag cancels it, and the release after it commits nothing. + pub fn check_widget_release_and_tool_switch(cx: &ToolContext, at: Point, q: Point, r: Point) { + let pressed = || { + let mut t = crate::select::SelectionTool::default(); + t.pointer(cx, &PointerEvent::new(PointerKind::Down, at.x, at.y)); + assert!(!t.pointer(cx, &PointerEvent::new(PointerKind::Drag, q.x, q.y)).is_empty(), "the drag to {q:?} changes the widget"); + t + }; + let mut want = pressed().pointer(cx, &PointerEvent::new(PointerKind::Drag, r.x, r.y)); + assert!(!want.is_empty(), "the drag to {r:?} changes the widget"); + want.push(Action::Commit); + assert_eq!(pressed().pointer(cx, &PointerEvent::new(PointerKind::Up, r.x, r.y)), want, "released at {r:?}"); + let mut t = pressed(); + assert_eq!(t.deactivate(cx), vec![Action::Cancel], "a tool switch cancels the drag"); + assert!(!t.busy() && !t.transforming()); + assert!(t.pointer(cx, &PointerEvent::new(PointerKind::Up, q.x, q.y)).is_empty(), "the release commits nothing"); + } + /// An 800 × 600 window on a view at 100% turned `deg` degrees clockwise (Rotate View): at 90° /// one pixel right on screen is one point up the page. pub fn turned_view(deg: f64) -> Option { diff --git a/crates/tools/src/mirror.rs b/crates/tools/src/mirror.rs index 5560fbc321..fac52cca3a 100644 --- a/crates/tools/src/mirror.rs +++ b/crates/tools/src/mirror.rs @@ -184,4 +184,20 @@ mod tests { spec.kind = RepeatKind::Mirror { angle: f64::NAN, center: Point::ZERO }; assert!(MirrorAxis::of(&doc, &selection, 1.0).is_none()); } + + /// With the Selection tool, a drag of the axis reads where it is released, and a tool switch + /// cancels it. + #[test] + fn an_axis_drag_reads_its_release_and_a_tool_switch_cancels_it() { + let (mut doc, id) = doc_with_rect(); + let mut source = doc.node(id).unwrap().clone(); + source.id = doc.alloc_id(); + doc.node_mut(id).unwrap().kind = NodeKind::Repeat(RepeatSpec::mirror(vec![Arc::new(source)], 90.0, 10.0)); + let mut selection = Selection::default(); + selection.set([id]); + let paint = paint(); + let cx = cx(&doc, &selection, &paint); + let at = MirrorAxis::of(&doc, &selection, 1.0).unwrap().center; + crate::testutil::check_widget_release_and_tool_switch(&cx, at, at + Vec2::new(20.0, 0.0), at + Vec2::new(40.0, 0.0)); + } } diff --git a/crates/tools/src/nineslice.rs b/crates/tools/src/nineslice.rs index 74f40b6bbf..d21a5f42a2 100644 --- a/crates/tools/src/nineslice.rs +++ b/crates/tools/src/nineslice.rs @@ -238,6 +238,15 @@ mod tests { assert_eq!(t.pointer(&c, &ev(PointerKind::Up, 150.0, 250.0)), vec![Action::Commit]); } + /// A guide drag reads where it is released, and a tool switch cancels it. + #[test] + fn a_guide_drag_reads_its_release_and_a_tool_switch_cancels_it() { + let d = editing(Some(SymbolNineSlice::default())); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + check_widget_release_and_tool_switch(&c, Point::new(126.0, 150.0), Point::new(115.0, 150.0), Point::new(105.0, 150.0)); + } + /// Escape during a guide drag cancels it and is the tool's; the release after it commits /// nothing. A double-click on a guide neither edits the art nor leaves the mode. #[test] diff --git a/crates/tools/src/objects_on_path.rs b/crates/tools/src/objects_on_path.rs index dbb6f8bfdf..906600f334 100644 --- a/crates/tools/src/objects_on_path.rs +++ b/crates/tools/src/objects_on_path.rs @@ -948,6 +948,9 @@ pub struct ObjectsOnPathTool { member: Option, /// Where the pointer is while no button is down, for the Select/Move widget it is over. pointer: Option, + /// Where the pointer was at the last press or drag: a widget drag released anywhere else is + /// dragged there before it ends. + held_at: Option, /// The reference point of each object attached next (0-8, row by row from the top left). pivot: u8, /// The angle of each object attached next, in degrees counter-clockwise from upright on the path. @@ -956,7 +959,18 @@ pub struct ObjectsOnPathTool { impl Default for ObjectsOnPathTool { fn default() -> Self { - Self { hover: None, press: None, rotating: None, spacing: None, moving: None, member: None, pointer: None, pivot: CENTER, rotate: 0.0 } + Self { + hover: None, + press: None, + rotating: None, + spacing: None, + moving: None, + member: None, + pointer: None, + held_at: None, + pivot: CENTER, + rotate: 0.0, + } } } @@ -967,31 +981,51 @@ impl Tool for ObjectsOnPathTool { fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { let p = ev.pos; + let released_away = ev.kind == PointerKind::Up && self.held_at != Some(p); + if matches!(ev.kind, PointerKind::Down | PointerKind::Drag) { + self.held_at = Some(p); + } if let Some(d) = &mut self.rotating { return match ev.kind { PointerKind::Drag => d.drag(cx, p, ev.mods.shift), - PointerKind::Up => self.rotating.take().map(RotateAllDrag::finish).unwrap_or_default(), + PointerKind::Up => { + let mut out = if released_away { d.drag(cx, p, ev.mods.shift) } else { vec![] }; + out.extend(self.rotating.take().map(RotateAllDrag::finish).unwrap_or_default()); + out + } _ => vec![], }; } if let Some(d) = &mut self.spacing { return match ev.kind { PointerKind::Drag => d.drag(cx, p, ev.mods.alt), - PointerKind::Up => self.spacing.take().map(SpaceDrag::finish).unwrap_or_default(), + PointerKind::Up => { + let mut out = if released_away { d.drag(cx, p, ev.mods.alt) } else { vec![] }; + out.extend(self.spacing.take().map(SpaceDrag::finish).unwrap_or_default()); + out + } _ => vec![], }; } if let Some(d) = &mut self.moving { return match ev.kind { PointerKind::Drag => d.drag(cx, p), - PointerKind::Up => self.moving.take().map(MoveAllDrag::finish).unwrap_or_default(), + PointerKind::Up => { + let mut out = if released_away { d.drag(cx, p) } else { vec![] }; + out.extend(self.moving.take().map(MoveAllDrag::finish).unwrap_or_default()); + out + } _ => vec![], }; } if let Some(d) = &mut self.member { return match ev.kind { PointerKind::Drag => d.drag(cx, p), - PointerKind::Up => self.member.take().map(MemberDrag::finish).unwrap_or_default(), + PointerKind::Up => { + let mut out = if released_away { d.drag(cx, p) } else { vec![] }; + out.extend(self.member.take().map(MemberDrag::finish).unwrap_or_default()); + out + } _ => vec![], }; } @@ -1084,6 +1118,11 @@ impl Tool for ObjectsOnPathTool { vec![] } + /// Switching tools while the button is down cancels the click or the drag, as Escape does. + fn deactivate(&mut self, cx: &ToolContext) -> Vec { + self.key(cx, ToolKey::Escape, Mods::default()) + } + fn options(&self) -> Value { json!({ "pivot": self.pivot, "rotate": self.rotate }) } @@ -1508,7 +1547,7 @@ mod tests { assert!(matches!(a.last(), Some(Action::Preview(_, p)) if p["spacing"] == "auto" && p["start"] == 0.0), "{id}: {a:?}"); assert_eq!(spaced(&t.pointer(&c, &ev(PointerKind::Drag, at.x - 900.0, at.y))), Some((0.0, 0.0)), "{id}"); assert_eq!(spaced(&t.pointer(&c, &alt(PointerKind::Drag, at.x - 900.0, at.y))), Some((0.0, 200.0)), "{id}"); - assert_eq!(t.pointer(&c, &ev(PointerKind::Up, at.x, at.y)), vec![Action::Commit], "{id}"); + assert_eq!(t.pointer(&c, &alt(PointerKind::Up, at.x - 900.0, at.y)), vec![Action::Commit], "{id}"); assert!(!t.busy(), "{id}"); // A click on the widget that does not move changes nothing. assert!(t.pointer(&c, &ev(PointerKind::Down, at.x, at.y)).is_empty()); @@ -1730,7 +1769,7 @@ mod tests { assert_eq!(moved(&t.pointer(&c, &ev(PointerKind::Drag, at.x + 900.0, at.y))), Some((300.0, None)), "{id}"); assert_eq!(moved(&t.pointer(&c, &ev(PointerKind::Drag, at.x + 880.0, at.y))), Some((280.0, None)), "{id}"); assert_eq!(moved(&t.pointer(&c, &ev(PointerKind::Drag, at.x - 900.0, at.y))), Some((0.0, None)), "{id}"); - assert_eq!(t.pointer(&c, &ev(PointerKind::Up, at.x, at.y)), vec![Action::Commit], "{id}"); + assert_eq!(t.pointer(&c, &ev(PointerKind::Up, at.x - 900.0, at.y)), vec![Action::Commit], "{id}"); assert!(!t.busy(), "{id}"); // A click on the widget that does not move changes nothing. assert!(t.pointer(&c, &ev(PointerKind::Down, at.x, at.y)).is_empty()); @@ -2007,6 +2046,85 @@ mod tests { } } + /// The release is read where it happens: a release away from the last drag event drags the + /// widget there before the drag ends, with the Selection tool and the Objects on Path tool. + #[test] + fn the_release_position_sets_each_widget() { + let new_tools = || -> [Box; 2] { [Box::new(crate::select::SelectionTool::default()), Box::new(ObjectsOnPathTool::default())] }; + let paint = paint(); + let (d, _, sel) = group_doc(0.0); + let c = cx(&d, &sel, &paint); + for mut t in new_tools() { + let (at, q, r) = (around(0.0), around(60.0), around(90.0)); + t.pointer(&c, &ev(PointerKind::Down, at.x, at.y)); + t.pointer(&c, &ev(PointerKind::Drag, q.x, q.y)); + let a = t.pointer(&c, &ev(PointerKind::Up, r.x, r.y)); + let (last, shown) = a.split_last().unwrap(); + assert_eq!(last, &Action::Commit, "{}", t.id()); + assert!(previewed(shown).is_some_and(|deg| (deg - 90.0).abs() < 1e-9), "{}: Rotate All {a:?}", t.id()); + } + let at = SpaceWidget::of(&d, &sel, 1.0).unwrap().at; + for mut t in new_tools() { + t.pointer(&c, &ev(PointerKind::Down, at.x, at.y)); + t.pointer(&c, &ev(PointerKind::Drag, at.x - 100.0, at.y)); + let a = t.pointer(&c, &ev(PointerKind::Up, at.x - 50.0, at.y)); + let (last, shown) = a.split_last().unwrap(); + assert_eq!(last, &Action::Commit, "{}", t.id()); + assert_eq!(spaced(shown), Some((350.0, 0.0)), "{}: Space {a:?}", t.id()); + } + let (d, _, sel) = spaced_doc(Some(100.0), 50.0); + let c = cx(&d, &sel, &paint); + let at = MoveAllWidget::of(&d, &sel, 1.0).unwrap().at; + for mut t in new_tools() { + t.pointer(&c, &ev(PointerKind::Down, at.x, at.y)); + t.pointer(&c, &ev(PointerKind::Drag, at.x + 80.0, at.y)); + let a = t.pointer(&c, &ev(PointerKind::Up, at.x + 90.0, at.y)); + let (last, shown) = a.split_last().unwrap(); + assert_eq!(last, &Action::Commit, "{}", t.id()); + assert_eq!(moved(shown), Some((140.0, None)), "{}: Move All {a:?}", t.id()); + } + let (d, _, sel, ids) = three_doc(); + let c = cx(&d, &sel, &paint); + for mut t in new_tools() { + t.pointer(&c, &ev(PointerKind::Down, 200.0, 300.0)); + t.pointer(&c, &ev(PointerKind::Drag, 280.0, 310.0)); + let a = t.pointer(&c, &ev(PointerKind::Up, 330.0, 300.0)); + assert_eq!(previewed_target(&a), Some(ids[2].0), "{}: Select/Move {a:?}", t.id()); + assert_eq!(a[1..], [Action::Commit, choose(ids[1])], "{}", t.id()); + } + } + + /// Switching tools during a widget drag cancels it, as Escape does, with the Selection tool and + /// the Objects on Path tool; after a press that has not moved there is nothing to put back. + #[test] + fn a_tool_switch_cancels_a_widget_drag() { + let new_tools = || -> [Box; 2] { [Box::new(crate::select::SelectionTool::default()), Box::new(ObjectsOnPathTool::default())] }; + let paint = paint(); + let (d, _, sel) = group_doc(0.0); + let (md, _, msel) = spaced_doc(Some(100.0), 50.0); + let (od, _, osel, _) = three_doc(); + let space = SpaceWidget::of(&d, &sel, 1.0).unwrap().at; + let move_all = MoveAllWidget::of(&md, &msel, 1.0).unwrap().at; + let presses = [ + (cx(&d, &sel, &paint), around(0.0), around(60.0)), + (cx(&d, &sel, &paint), space, space - Vec2::new(100.0, 0.0)), + (cx(&md, &msel, &paint), move_all, move_all + Vec2::new(80.0, 0.0)), + (cx(&od, &osel, &paint), Point::new(200.0, 300.0), Point::new(330.0, 300.0)), + ]; + for (c, at, q) in &presses { + for mut t in new_tools() { + t.pointer(c, &ev(PointerKind::Down, at.x, at.y)); + assert!(!t.pointer(c, &ev(PointerKind::Drag, q.x, q.y)).is_empty(), "{}", t.id()); + assert_eq!(t.deactivate(c), vec![Action::Cancel], "{} at {at:?}", t.id()); + assert!(!t.busy() && !t.transforming(), "{}", t.id()); + assert!(t.pointer(c, &ev(PointerKind::Up, q.x, q.y)).is_empty(), "{}: the release keeps nothing", t.id()); + t.pointer(c, &ev(PointerKind::Down, at.x, at.y)); + assert!(t.deactivate(c).is_empty(), "{}", t.id()); + assert!(!t.busy(), "{}", t.id()); + } + } + } + /// Round a closed path the drag goes on across the first anchor: the first object, dragged back /// past it, takes the last place. #[test] diff --git a/crates/tools/src/pie.rs b/crates/tools/src/pie.rs index af79c1ce46..edf126b798 100644 --- a/crates/tools/src/pie.rs +++ b/crates/tools/src/pie.rs @@ -305,6 +305,16 @@ mod tests { assert!(t.pointer(&c, &ev(PointerKind::Up, Point::new(100.0, 200.0))).is_empty(), "the release commits nothing"); } + /// A pie widget drag with the Selection tool reads where it is released, and a tool switch + /// cancels it. + #[test] + fn a_pie_widget_drag_reads_its_release_and_a_tool_switch_cancels_it() { + let (d, _, s) = doc_with_ellipse((0.0, 360.0)); + let p = paint(); + let c = cx(&d, &s, &p); + check_widget_release_and_tool_switch(&c, Point::new(312.0, 150.0), Point::new(200.0, 20.0), Point::new(100.0, 150.0)); + } + /// On a whole ellipse the two widgets sit at the very same point, whatever its size, place or /// angle, so a press there always takes the End widget. #[test] diff --git a/crates/tools/src/repeat_grid.rs b/crates/tools/src/repeat_grid.rs index 07187a6a5a..75def8909f 100644 --- a/crates/tools/src/repeat_grid.rs +++ b/crates/tools/src/repeat_grid.rs @@ -369,6 +369,17 @@ mod tests { assert!(GridDrag::hit(&c, g.rows_at, Mods { alt: true, ..Mods::default() }).is_none()); } + /// With the Selection tool, a handle drag reads where it is released, and a tool switch cancels + /// it. + #[test] + fn a_handle_drag_reads_its_release_and_a_tool_switch_cancels_it() { + let (doc, selection) = grid(); + let paint = paint(); + let c = cx(&doc, &selection, &paint); + let g = GridHandles::of(&doc, &selection, crate::select::selection_box(&c), 1.0).unwrap(); + crate::testutil::check_widget_release_and_tool_switch(&c, g.rows_at, g.rows_at + Vec2::new(0.0, 240.0), g.rows_at + Vec2::new(0.0, 360.0)); + } + #[test] fn a_bounding_box_handle_wins_where_they_overlap() { let (doc, selection) = grid(); diff --git a/crates/tools/src/repeat_radial.rs b/crates/tools/src/repeat_radial.rs index 42a9f4395f..6c9ed57d7a 100644 --- a/crates/tools/src/repeat_radial.rs +++ b/crates/tools/src/repeat_radial.rs @@ -533,6 +533,17 @@ mod tests { assert!(RadialDrag::hit(&c, h.instances_at, Mods { alt: true, ..Mods::default() }).is_none()); } + /// With the Selection tool, a handle drag reads where it is released, and a tool switch cancels + /// it. + #[test] + fn a_handle_drag_reads_its_release_and_a_tool_switch_cancels_it() { + let (doc, selection) = radial(); + let paint = paint(); + let c = cx(&doc, &selection, &paint); + let at = RadialHandles::of(&doc, &selection, crate::select::selection_box(&c), 1.0).unwrap().instances_at; + crate::testutil::check_widget_release_and_tool_switch(&c, at, at + Vec2::new(0.0, 32.0), at + Vec2::new(0.0, 64.0)); + } + #[test] fn dragging_the_radius_handle_moves_the_circle_in_and_out() { let (doc, selection) = radial(); diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index e9c3e2bb03..0a882a6bfa 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -58,6 +58,14 @@ use crate::sidewidget::{self, SideDrag}; use crate::typewidget; use crate::{Action, Cursor, Mods, Overlay, PixelOp, PointerEvent, PointerKind, Tool, ToolContext, ToolKey, json_ids}; +/// The release of the widget drag `d`: released away from the last press or drag (`away`), it is +/// dragged there first (`drag`); then it ends (`finish`). +fn released(mut d: D, away: bool, drag: impl FnOnce(&mut D) -> Vec, finish: impl FnOnce(D) -> Vec) -> Vec { + let mut out = if away { drag(&mut d) } else { vec![] }; + out.extend(finish(d)); + out +} + /// Direction is read on screen, even in a turned view. Within three pixels of the press's /// horizontal position, retain the previous rule so hand jitter does not flip it. fn marquee_direction(cx: &ToolContext, start: Point, cur: Point, previous: bool) -> bool { @@ -199,6 +207,9 @@ pub struct SelectionTool { loaded_at_press: Option<(NodeId, bool)>, /// Where the pointer last hovered: the type on a path bracket under it draws thicker. bracket_hover: Option, + /// Where the pointer was at the last press or drag: a widget drag released anywhere else is + /// dragged there before it ends. + held_at: Option, } /// What Distance Guides measure the selection to. @@ -905,15 +916,32 @@ impl Tool for SelectionTool { out } - /// Switching tools during a drag of a blend widget, a corner widget, a pie widget or a - /// polygon's side widget cancels it, as Escape does: its value goes back. + /// Switching tools during a drag of a widget (a blend, corner, pie or side widget, an Objects on + /// Path widget, a bracket of type on a path, a repeat's control or a 9-slice guide) cancels it, + /// as Escape does: its value goes back. fn deactivate(&mut self, _cx: &ToolContext) -> Vec { match std::mem::take(&mut self.state) { State::BlendWidget(d) if d.adjusting() => vec![Action::Cancel], State::Corner(c) if c.adjusting() => vec![Action::Cancel], State::Pie(d) if d.adjusting() => vec![Action::Cancel], + State::RotateAll(d) if d.adjusting() => vec![Action::Cancel], + State::Space(d) if d.adjusting() => vec![Action::Cancel], + State::MoveAll(d) if d.adjusting() => vec![Action::Cancel], + State::Member(d) if d.adjusting() => vec![Action::Cancel], + State::Bracket(b) if b.adjusting() => vec![Action::Cancel], State::Sides(d) => d.cancel(), - State::BlendWidget(_) | State::Corner(_) | State::Pie(_) => vec![], + State::Mirror(d) => d.cancel(), + State::GridRepeat(d) => d.cancel(), + State::RadialRepeat(d) => d.cancel(), + State::NineSlice(d) => d.cancel(), + State::BlendWidget(_) + | State::Corner(_) + | State::Pie(_) + | State::RotateAll(_) + | State::Space(_) + | State::MoveAll(_) + | State::Member(_) + | State::Bracket(_) => vec![], other => { self.state = other; vec![] @@ -978,6 +1006,10 @@ impl Tool for SelectionTool { /// the art; the drags then move, scale, rotate, marquee or drag what it took. fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { self.note_loaded_at_press(ev.kind); + let released_away = ev.kind == PointerKind::Up && self.held_at != Some(ev.pos); + if matches!(ev.kind, PointerKind::Down | PointerKind::Drag) { + self.held_at = Some(ev.pos); + } let hovering = ev.kind == PointerKind::Move && matches!(self.state, State::Idle); self.bracket_hover = hovering.then_some(ev.pos); self.alt_hover = hovering && ev.mods.alt; @@ -988,7 +1020,7 @@ impl Tool for SelectionTool { return out; } // The edited symbol's 9-slice guides take precedence over every other control and the art. - if let Some(out) = self.nine_slice_guides(cx, ev) { + if let Some(out) = self.nine_slice_guides(cx, ev, released_away) { return out; } // Mirror and grid repeat controls take precedence over art and ruler guides; the mirror @@ -1129,7 +1161,7 @@ impl Tool for SelectionTool { } (PointerKind::Up, State::Corner(c)) => { self.state = State::Idle; - c.finish() + released(c, released_away, |c| c.drag(cx, p), CornerDrag::finish) } (PointerKind::Drag, State::Pie(mut d)) => { let out = d.drag(cx, p); @@ -1138,7 +1170,7 @@ impl Tool for SelectionTool { } (PointerKind::Up, State::Pie(d)) => { self.state = State::Idle; - d.finish() + released(d, released_away, |d| d.drag(cx, p), PieDrag::finish) } (PointerKind::Drag, State::Sides(mut d)) => { let out = d.drag(cx, p); @@ -1156,7 +1188,7 @@ impl Tool for SelectionTool { } (PointerKind::Up, State::BlendWidget(d)) => { self.state = State::Idle; - d.finish() + released(d, released_away, |d| d.drag(cx, p), BlendWidgetDrag::finish) } (PointerKind::Drag, State::RotateAll(mut d)) => { let out = d.drag(cx, p, m.shift); @@ -1165,7 +1197,7 @@ impl Tool for SelectionTool { } (PointerKind::Up, State::RotateAll(d)) => { self.state = State::Idle; - d.finish() + released(d, released_away, |d| d.drag(cx, p, m.shift), RotateAllDrag::finish) } (PointerKind::Drag, State::Space(mut d)) => { let out = d.drag(cx, p, m.alt); @@ -1174,7 +1206,7 @@ impl Tool for SelectionTool { } (PointerKind::Up, State::Space(d)) => { self.state = State::Idle; - d.finish() + released(d, released_away, |d| d.drag(cx, p, m.alt), SpaceDrag::finish) } (PointerKind::Drag, State::MoveAll(mut d)) => { let out = d.drag(cx, p); @@ -1183,7 +1215,7 @@ impl Tool for SelectionTool { } (PointerKind::Up, State::MoveAll(d)) => { self.state = State::Idle; - d.finish() + released(d, released_away, |d| d.drag(cx, p), MoveAllDrag::finish) } (PointerKind::Drag, State::Member(mut d)) => { let out = d.drag(cx, p); @@ -1192,7 +1224,7 @@ impl Tool for SelectionTool { } (PointerKind::Up, State::Member(d)) => { self.state = State::Idle; - d.finish() + released(d, released_away, |d| d.drag(cx, p), MemberDrag::finish) } (PointerKind::Drag, State::Bracket(mut b)) => { let out = b.drag(cx, p, m.cmd); @@ -1201,7 +1233,7 @@ impl Tool for SelectionTool { } (PointerKind::Up, State::Bracket(b)) => { self.state = State::Idle; - b.finish() + released(b, released_away, |b| b.drag(cx, p, m.cmd), BracketDrag::finish) } (PointerKind::Up, State::Moving { began, deselect, key, exclude, .. }) => { self.release_move(cx, ev.backquote, began, deselect, key, exclude) @@ -1589,8 +1621,8 @@ impl SelectionTool { } /// A press on a 9-slice guide of the edited symbol starts dragging it; the drag and the - /// release go to it. - fn nine_slice_guides(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Option> { + /// release go to it, and a release away from the last drag (`released_away`) moves it there. + fn nine_slice_guides(&mut self, cx: &ToolContext, ev: &PointerEvent, released_away: bool) -> Option> { if let State::NineSlice(mut d) = self.state.clone() { return Some(match ev.kind { PointerKind::Drag => { @@ -1600,7 +1632,7 @@ impl SelectionTool { } PointerKind::Up => { self.state = State::Idle; - d.finish() + released(d, released_away, |d| d.drag(cx, ev.pos), crate::nineslice::GuideDrag::finish) } _ => vec![], }); diff --git a/crates/tools/src/select/tests.rs b/crates/tools/src/select/tests.rs index 5c52201a6f..ecc2297d67 100644 --- a/crates/tools/src/select/tests.rs +++ b/crates/tools/src/select/tests.rs @@ -448,6 +448,28 @@ fn escape_cancels_a_bracket_drag() { assert!(t.pointer(&cx, &ev(PointerKind::Up, 330.0, 290.0)).is_empty(), "the release commits nothing"); } +/// A bracket drag of type on a path reads where it is released, and a tool switch cancels it. +#[test] +fn a_bracket_drag_reads_its_release_and_a_tool_switch_cancels_it() { + let (d, id) = crate::testutil::doc_with_path_type(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let cx = cx(&d, &s, &p); + check_widget_release_and_tool_switch(&cx, Point::new(280.0, 290.0), Point::new(320.0, 290.0), Point::new(340.0, 290.0)); +} + +/// A corner widget drag reads where it is released, and a tool switch cancels it. +#[test] +fn a_corner_widget_drag_reads_its_release_and_a_tool_switch_cancels_it() { + let (d, id) = doc_with_live_rect(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let cx = cx(&d, &s, &p); + check_widget_release_and_tool_switch(&cx, Point::new(190.0, 191.0), Point::new(175.0, 176.0), Point::new(165.0, 166.0)); +} + /// #812: with Smart Guides on, hovering near an object's centre or an anchor labels it, and a /// press there grabs the object by that point. #[test] From 67fa32374d7fb90a400c731604d66bf66c48077a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 20:24:23 -0800 Subject: [PATCH 02/38] Retype: near matches within a tolerance, and words outlined as one compound path type.retype takes a tolerance (0 to 0.05, default 0 for exact matches only). Above 0, a shape of up to 8 contours that is no glyph exactly is read at equal steps of length from any start and in either direction, with its contours paired with the glyph's by length. It becomes the closest glyph when the leftover distance, relative to the shape's size, is at most the tolerance, and the glyph's outline and the shape's each lie within three times the tolerance of the other. Simplified outlines, curves split in two and contours in another order or direction match this way. 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 is a near match. Each entry of fonts in the result has a score from 1 (exact) to 0. A compound path holding several glyphs (a word made into one compound path) is split into groups of contours, a contour with the contours inside it, and matched in runs of up to three groups, longest first among those that leave the rest matchable, so an i's stem and dot become one i. Exact matches of the whole shape come first, then exact matches of its groups, then near matches. The compound becomes type only when every glyph matches; otherwise it stays and is reported once. Exact matching of those groups also reads contours that run the other way round, as Make Compound Path leaves them. A compound path of more than 256 groups or 512 contours is matched whole only, and so are the shapes after the first 16,384 contours one command groups. Near matching compares a shape with at most 256 glyphs, in at most 50 million point comparisons per shape and 2 billion per command, and looks glyphs up for at most 1,024 distinct shapes and runs per command, whole shapes first. At most 262,144 glyphs are drawn to check and 32,768 indexed for near matching, shared equally among the faces; a face's glyphs closest to the selected shapes are indexed first. The tolerance, the score and the splitting rules are VectorCraft's own. Part of #4934 --- crates/engine/src/cmd/retype.rs | 325 ++++++++-- crates/engine/src/cmd/retype_tests.rs | 473 ++++++++++++++ crates/text/src/retype.rs | 899 ++++++++++++++++++++++++-- docs/gaps.md | 2 +- docs/mcp.md | 31 +- docs/target-app-parity.md | 6 +- docs/type-parity.md | 2 +- 7 files changed, 1655 insertions(+), 83 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index cb548bd46e..253edcd3a3 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -11,8 +11,14 @@ //! ([`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. +//! they are and are reported. +//! +//! With a `tolerance`, a shape that matches no glyph exactly may still nearly match one: another +//! version of the font, or the outline simplified or built another way +//! ([`RetypeIndex::near_matches`]); each line reports how closely its glyphs fit. A compound path +//! holding several glyphs (a word outlined as one path) is split into its glyphs +//! ([`vectorcraft_text::retype::clusters`]), and becomes type only when every one of them does. +//! The tolerance, the score and the splitting rules are VectorCraft's own. Images are phase 2. use std::f64::consts::{PI, TAU}; use std::sync::Arc; @@ -39,7 +45,7 @@ pub fn specs() -> Vec { "Retype", ["Type"], None, - "{fonts?: [family…]} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live point text: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation (exact matches only); matched glyphs become point text in that font and size at the same baseline, one object per line, with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line splits where its type would not draw the outlines' glyphs in their places (tracking, manual spacing, font substitutions); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts, fonts: [{family, style, size}], unmatched: [id…], truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error when no shape matches", + "{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", has_selected_path, retype )] @@ -180,6 +186,9 @@ struct Line { parent: Option, opacity: f32, blend: vectorcraft_color::BlendMode, + /// The tolerance near matches were taken with (0: exact only): a near-matched glyph may differ + /// that much in size, turn and place from the rest of its line ([`Self::slack_for`]). + slack: f64, } impl Line { @@ -187,6 +196,12 @@ impl Line { Vec2::new(self.angle.cos(), self.angle.sin()) } + /// The slack glyph `m` of this line is allowed: [`Self::slack`] when `m` or the line's first + /// glyph, whose size and turn the line takes, is a near match, else 0. + fn slack_for(&self, m: &GlyphMatch) -> f64 { + if m.exact && self.matches.first().is_none_or(|f| f.exact) { 0.0 } else { self.slack } + } + /// Does glyph `m` of shape `pc` continue this line (same group, paint and transparency, same /// font, size and turn, on its baseline, after its end)? fn continues(&self, pc: &Piece, m: &GlyphMatch) -> bool { @@ -194,15 +209,16 @@ impl Line { let d = m.origin - self.origin; let dir = self.dir(); let across = d.cross(dir).abs(); + let slack = self.slack_for(m); pc.parent == self.parent && pc.appearance == self.appearance && pc.opacity == self.opacity && pc.blend == self.blend && m.face.id() == self.face.id() // One size and turn for the whole line: the type sets every glyph at the first one's. - && (m.scale - self.scale).abs() <= self.scale * 1e-4 + && (m.scale - self.scale).abs() <= self.scale * slack.max(1e-4) // Wrapped: type turned 180° has angles near +π and −π. - && ((m.angle - self.angle + PI).rem_euclid(TAU) - PI).abs() < 1e-5 + && ((m.angle - self.angle + PI).rem_euclid(TAU) - PI).abs() < slack.max(1e-5) && across < size * 0.05 && (m.origin - self.end).dot(dir) > -size * 0.25 } @@ -241,6 +257,7 @@ impl Line { parent: self.parent, opacity: self.opacity, blend: self.blend, + slack: self.slack, }; for (id, m) in ids.iter().zip(ms).skip(1) { l.push(*id, m); @@ -287,9 +304,9 @@ impl Line { fn first_mismatch(&self, t: &TextObject) -> Option { let lay = vectorcraft_text::layout(FontDb::global(), t); let mut drawn = lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty()); - let tol = (self.scale * self.face.units_per_em() * 0.01).max(0.01); for (k, m) in self.matches.iter().enumerate() { let Some(g) = drawn.next() else { return Some(k) }; + let tol = (self.scale * self.face.units_per_em() * (0.01 + self.slack_for(m))).max(0.01); let at = t.xf * (g.xf * Point::ORIGIN); if g.font_id != m.face.id() || g.gid != m.gid || at.distance(m.origin) > tol { return Some(k); @@ -419,11 +436,13 @@ fn reposed(l: &Line, id: NodeId, m: &GlyphMatch) -> Line { parent: l.parent, opacity: l.opacity, blend: l.blend, + slack: l.slack, } } -/// A new line of shape `pc` alone, as the first of its candidate glyphs `cands` (none: `None`). -fn new_line(pc: &Piece, cands: &[GlyphMatch]) -> Option { +/// A new line of shape `pc` alone, as the first of its candidate glyphs `cands` (none: `None`), +/// with near matches taken at tolerance `slack`. +fn new_line(pc: &Piece, cands: &[GlyphMatch], slack: f64) -> Option { let m = cands.first()?; let dir = Vec2::new(m.angle.cos(), m.angle.sin()); Some(Line { @@ -440,9 +459,183 @@ fn new_line(pc: &Piece, cands: &[GlyphMatch]) -> Option { parent: pc.parent, opacity: pc.opacity, blend: pc.blend, + slack, }) } +/// The lines, by index, to drop so that no shape of several glyphs becomes type in part: each line +/// is given by the shapes it sets, one per glyph, and `glyphs_of` says how many glyphs a shape +/// is. A line setting a glyph of a shape not all of whose glyphs are set goes, and then so do the +/// lines setting the other glyphs of the shapes it held. +fn partial_lines(lines: &[Vec], glyphs_of: &std::collections::HashMap) -> std::collections::HashSet { + let mut dropped = std::collections::HashSet::new(); + loop { + let mut set: std::collections::HashMap = std::collections::HashMap::new(); + for (_, l) in lines.iter().enumerate().filter(|(i, _)| !dropped.contains(i)) { + for id in l { + *set.entry(*id).or_default() += 1; + } + } + let partial: std::collections::HashSet = + set.iter().filter(|(id, n)| glyphs_of.get(*id).is_some_and(|want| *n < want)).map(|(id, _)| *id).collect(); + let before = dropped.len(); + for (i, l) in lines.iter().enumerate() { + if l.iter().any(|id| partial.contains(id)) { + dropped.insert(i); + } + } + if dropped.len() == before { + return dropped; + } + } +} + +/// Glyph runs longer than this (in contour groups) are not tried when a shape is split. +const MAX_RUN: usize = 3; + +/// A shape of more contour groups than this is not split: it is matched whole only. +const MAX_SPLIT_GROUPS: usize = 256; + +/// A shape of more contours than this is not split either, and its contours are not grouped. +const MAX_SPLIT_CONTOURS: usize = 512; + +/// Contours of all the selected shapes one command groups, at most: the shapes past them are +/// matched whole only. +const MAX_SPLIT_TOTAL_CONTOURS: usize = 16_384; + +/// `path`'s contour groups when it is split into glyphs: none for fewer than two or more than +/// [`MAX_SPLIT_GROUPS`], for more than [`MAX_SPLIT_CONTOURS`] contours, and for more contours than +/// `budget` holds. A path of two or more contours takes them from `budget` when it is grouped. +fn split_groups(path: &BezPath, budget: &mut usize) -> Vec { + // Grouping compares every contour with every other: count them first. + let n = path.elements().iter().filter(|e| matches!(e, kurbo::PathEl::MoveTo(_))).count(); + if !(2..=MAX_SPLIT_CONTOURS).contains(&n) || n > *budget { + return vec![]; + } + *budget -= n; + let groups = vectorcraft_text::retype::clusters(path); + if (2..=MAX_SPLIT_GROUPS).contains(&groups.len()) { groups } else { vec![] } +} + +/// The parts of shape `path` to match: the whole shape, or, when it is no glyph and holds several +/// contour `groups` ([`split_groups`]), runs of up to [`MAX_RUN`] groups in order, the longest that matches first (an i before a dotless i and a dot) among the runs after +/// which the rest of the groups can still be matched. Each part with its candidates; empty when +/// the shape matches nothing and its groups cannot all be matched. `find(path, part, near)` gives +/// 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> { + let whole = find(path, false, false); + if !whole.is_empty() { + return vec![whole]; + } + let exact = split_parts(groups, &|run| find(run, true, false)); + if !exact.is_empty() { + return exact; + } + let whole = find(path, false, true); + if !whole.is_empty() { + return vec![whole]; + } + split_parts(groups, &|run| find(run, true, true)) +} + +/// [`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> { + if groups.is_empty() { + return vec![]; + } + let g = groups.len(); + // From the last group back: the run that starts at each group, the longest that matches and + // leaves a rest that can all be matched, with its candidates. Runs past such a start are + // never tried for one whose rest cannot be matched. + let mut chosen: Vec)>> = (0..g).map(|_| None).collect(); + for i in (0..g).rev() { + for n in (1..=MAX_RUN.min(g - i)).rev() { + let rest_ok = i + n == g || chosen.get(i + n).is_some_and(Option::is_some); + if !rest_ok { + continue; + } + let Some(run) = groups.get(i..i + n) else { continue }; + let cands = find(&joined(run)); + if !cands.is_empty() { + if let Some(c) = chosen.get_mut(i) { + *c = Some((n, cands)); + } + break; + } + } + } + let mut out = 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); + i += n; + } + out +} + +/// Contour groups joined into one path. +fn joined(run: &[BezPath]) -> BezPath { + let mut p = BezPath::new(); + for g in run { + p.extend(g.iter()); + } + p +} + +/// Every run of contour `groups` ([`split_groups`]) [`parts`] may try. +fn runs(groups: &[BezPath]) -> Vec { + let mut out = vec![]; + for i in 0..groups.len() { + for n in 1..=MAX_RUN.min(groups.len() - i) { + if let Some(run) = groups.get(i..i + n) { + out.push(joined(run)); + } + } + } + out +} + +/// The keys the index looks glyphs up by for the `shapes` (each with its contour groups) and +/// every run of their groups: their exact [`shape_key`](vectorcraft_text::retype::shape_key)s and, +/// with a `tolerance` above 0, at most [`MAX_NEAR_KEYS`](vectorcraft_text::retype::MAX_NEAR_KEYS) +/// distinct [`near_key`](vectorcraft_text::retype::near_key)s: every whole shape's first, in the +/// order the shapes come, then the runs of their groups. Paths past that many near keys are not +/// looked up for near matches. +fn lookup_keys<'a>( + shapes: impl IntoIterator, + tolerance: f64, +) -> (std::collections::BTreeSet, Vec) { + use vectorcraft_text::retype::{MAX_NEAR_KEYS, near_key, shape_key}; + let mut wanted = std::collections::BTreeSet::new(); + let mut near_wanted = vec![]; + let mut add = |run: &BezPath| { + wanted.extend(shape_key(run)); + if tolerance > 0.0 + && near_wanted.len() < MAX_NEAR_KEYS + && let Some(k) = near_key(run) + && !near_wanted.contains(&k) + { + near_wanted.push(k); + } + }; + let shapes: Vec<(&BezPath, &[BezPath])> = shapes.into_iter().collect(); + // The whole shapes first, then the runs of their groups. + for (path, _) in &shapes { + add(path); + } + for (_, groups) in &shapes { + for run in runs(groups) { + add(&run); + } + } + (wanted, near_wanted) +} + fn retype(s: &mut Session, p: &Value) -> Result { const C: &str = "type.retype"; let fonts: Vec = match p.get("fonts") { @@ -452,6 +645,13 @@ fn retype(s: &mut Session, p: &Value) -> Result { } Some(_) => return Err(bad(C, "fonts must be a list of family names")), }; + let tolerance = match p.get("tolerance") { + None | Some(Value::Null) => 0.0, + Some(v) => match v.as_f64() { + Some(t) if (0.0..=vectorcraft_text::retype::MAX_TOLERANCE).contains(&t) => t, + _ => return Err(bad(C, "tolerance must be a number from 0 to 0.05")), + }, + }; let roots = selected_roots(s)?; let db = FontDb::global(); let system_layout = s.doc()?.doc.setup.system_layout; @@ -478,17 +678,31 @@ fn retype(s: &mut Session, p: &Value) -> Result { if pieces.is_empty() { return Err(EngineError::Other("Retype: select outlined text (paths or compound paths)".into())); } - // Only glyphs with a selected shape's key (segments per contour) can match one: the others are - // not sampled. - let wanted: std::collections::BTreeSet = - pieces.iter().filter(|pc| !pc.keeps_outline).filter_map(|pc| vectorcraft_text::retype::shape_key(&pc.path)).collect(); + // Only glyphs with a selected shape's key (segments per contour) can match one exactly, and + // only glyphs with as many contours and a close area-to-length ratio nearly: the others are + // not sampled. A shape of several glyphs is looked up by the runs of its groups too. + let mut budget = MAX_SPLIT_TOTAL_CONTOURS; + let groups: Vec> = pieces.iter().map(|pc| if pc.keeps_outline { vec![] } else { split_groups(&pc.path, &mut budget) }).collect(); + let (wanted, near_wanted) = + lookup_keys(pieces.iter().zip(&groups).filter(|(pc, _)| !pc.keeps_outline).map(|(pc, g)| (&pc.path, g.as_slice())), tolerance); // Nothing to match (every shape stays an outline): no font is read. - let index = if wanted.is_empty() { RetypeIndex::default() } else { RetypeIndex::build(db, candidate_faces(db, d, &fonts), &wanted) }; - let found: Vec> = pieces.iter().map(|pc| if pc.keeps_outline { vec![] } else { index.matches(&pc.path) }).collect(); + let index = if wanted.is_empty() && near_wanted.is_empty() { + RetypeIndex::default() + } else { + 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 } + }; + // 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(); // 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 ms in &found { + for ms in found.iter().flatten() { // Each shape votes once for each face it fits. let mut faces: Vec = ms.iter().map(|m| m.face.id()).collect(); faces.sort_unstable(); @@ -505,36 +719,42 @@ fn retype(s: &mut Session, p: &Value) -> Result { let mut unmatched = vec![]; // An unmatched shape between glyphs ends the line: the type after it is painted after it. let mut open = false; - for (pc, ms) in pieces.iter().zip(&found) { + // How many glyphs each shape is: a shape of several becomes type only when all of them do. + let mut glyphs_of: std::collections::HashMap = std::collections::HashMap::new(); + for (pc, parts) in pieces.iter().zip(&found) { if pc.after_barrier { open = false; } - // The shape's candidates in the face most shapes fit (the first such face, as the - // matches come upright and closest first). - let face = ms.iter().enumerate().max_by_key(|(i, m)| (rank(m.face.id()), std::cmp::Reverse(*i))).map(|(_, m)| m.face.id()); - let cands: Vec = ms.iter().filter(|m| Some(m.face.id()) == face).cloned().collect(); - if cands.is_empty() { + if parts.is_empty() { unmatched.push(pc.id); open = false; continue; } - let joined = match lines.last_mut() { - Some(l) if open => join(l, pc, &cands), - _ => false, - }; - if !joined { - lines.extend(new_line(pc, &cands)); + glyphs_of.insert(pc.id, parts.len()); + for ms in parts { + // The part's candidates in the face most shapes fit (the first such face, as the + // matches come upright and closest first). + let face = ms.iter().enumerate().max_by_key(|(i, m)| (rank(m.face.id()), std::cmp::Reverse(*i))).map(|(_, m)| m.face.id()); + let cands: Vec = ms.iter().filter(|m| Some(m.face.id()) == face).cloned().collect(); + let joined = match lines.last_mut() { + Some(l) if open => join(l, pc, &cands), + _ => false, + }; + if !joined { + lines.extend(new_line(pc, &cands, tolerance)); + } + open = true; } - open = true; } // A lone one-contour glyph (a period, a hyphen, a bullet) is too plain to tell from drawn - // art (a dot, a bar): beside other shapes it stays an outline. Selected on its own, it is - // what was asked for. Lone means alone on its baseline as the outlines lie, before the - // layout check splits lines (tracking and manual kerning split them glyph by glyph). + // art (a dot, a bar): beside other shapes, the other glyphs of a split compound path + // included, it stays an outline. Selected on its own, it is what was asked for. Lone means + // alone on its baseline as the outlines lie, before the layout check splits lines (tracking + // and manual kerning split them glyph by glyph). let lone_pieces: std::collections::HashSet = lines.iter().filter(|l| matches!(l.matches.as_slice(), [m] if m.contours == 1)).flat_map(|l| l.pieces.iter().copied()).collect(); let mut lines = verified(lines, system_layout, &mut unmatched); - if pieces.len() > 1 { + if pieces.len() > 1 || glyphs_of.values().any(|n| *n > 1) { lines.retain(|l| { let lone = matches!(l.pieces.as_slice(), [id] if lone_pieces.contains(id)); if lone { @@ -543,6 +763,20 @@ fn retype(s: &mut Session, p: &Value) -> Result { !lone }); } + let dropped = partial_lines(&lines.iter().map(|l| l.pieces.clone()).collect::>(), &glyphs_of); + let mut k = 0; + lines.retain(|l| { + let keep = !dropped.contains(&k); + k += 1; + if !keep { + unmatched.extend(l.pieces.iter().copied()); + } + keep + }); + // A shape of several glyphs is reported once, and not when it became type. + let kept: std::collections::HashSet = lines.iter().flat_map(|l| l.pieces.iter().copied()).collect(); + let mut seen = std::collections::HashSet::new(); + unmatched.retain(|id| !kept.contains(id) && seen.insert(*id)); (lines, unmatched, truncated) }; if lines.is_empty() { @@ -551,6 +785,9 @@ fn retype(s: &mut Session, p: &Value) -> Result { let made = s.edit("Retype", |d, sel| { let mut ids = vec![]; let mut emptied = vec![]; + // Every line's type goes in before the shapes go: a shape of several glyphs is the first + // shape of more than one line. Each goes just before its first shape, so lines from one + // shape keep their order. for l in &lines { let Some(first) = l.pieces.first() else { continue }; let (par, idx, _) = d.position(*first).ok_or(EngineError::NoNode(*first))?; @@ -561,14 +798,18 @@ fn retype(s: &mut Session, p: &Value) -> Result { node.opacity = l.opacity; node.blend = l.blend; d.insert(par, idx, node)?; - for pc in &l.pieces { - if let Some((Some(parent), _, _)) = d.position(*pc) { - emptied.push(parent); - } - d.remove(*pc)?; - } ids.push(id); } + let mut removed = std::collections::HashSet::new(); + for pc in lines.iter().flat_map(|l| l.pieces.iter()) { + if !removed.insert(*pc) { + continue; + } + if let Some((Some(parent), _, _)) = d.position(*pc) { + emptied.push(parent); + } + d.remove(*pc)?; + } // 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. @@ -611,7 +852,13 @@ fn retype(s: &mut Session, p: &Value) -> Result { Ok(json!({ "ids": made.iter().map(|i| i.0).collect::>(), "texts": lines.iter().map(|l| l.text.clone()).collect::>(), - "fonts": lines.iter().map(|l| json!({"family": l.face.family, "style": l.face.style, "size": l.scale * l.face.units_per_em()})).collect::>(), + "fonts": lines + .iter() + .map(|l| { + let score = l.matches.iter().map(GlyphMatch::score).fold(1.0, f64::min); + json!({"family": l.face.family, "style": l.face.style, "size": l.scale * l.face.units_per_em(), "score": (score * 1000.0).round() / 1000.0}) + }) + .collect::>(), "unmatched": unmatched.iter().map(|i| i.0).collect::>(), "truncated": truncated, })) diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index d691ab34fa..5c043a9e6f 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -537,3 +537,476 @@ fn a_long_tracked_line_is_checked_in_time() { assert_eq!(r["unmatched"], json!([])); eprintln!("450 tracked glyphs: {:?}, {} objects", t0.elapsed(), texts.len()); } + +/// Every path in the document flattened into lines `tol` from its curves, each contour started at +/// its second point and run backwards: outlines simplified and built nothing like the font's. +fn simplify_every_path(s: &mut Session, tol: f64) { + let mut ids = vec![]; + s.doc().unwrap().doc.walk(|n| { + if matches!(n.kind, NodeKind::Path { .. }) { + ids.push(n.id); + } + }); + simplify_paths(s, &ids, tol); +} + +/// [`simplify_every_path`] for the paths `ids` only. +fn simplify_paths(s: &mut Session, ids: &[NodeId], tol: f64) { + s.edit("test", |d, _| { + for id in ids { + let data = d.node_mut(*id).unwrap().path_data_mut().unwrap(); + let mut contours: Vec> = vec![]; + kurbo::flatten(data.to_bezpath().iter(), tol, |el| match el { + kurbo::PathEl::MoveTo(q) => contours.push(vec![q]), + kurbo::PathEl::LineTo(q) => contours.last_mut().unwrap().push(q), + _ => {} + }); + let mut out = kurbo::BezPath::new(); + for mut c in contours { + if c.len() > 1 && c.first() == c.last() { + c.pop(); + } + c.rotate_left(1); + c.reverse(); + out.move_to(c[0]); + for q in &c[1..] { + out.line_to(*q); + } + out.close_path(); + } + *data = vectorcraft_geom::PathData::from_bezpath(&out); + } + Ok(()) + }) + .unwrap(); +} + +#[test] +fn simplified_outlines_retype_only_with_a_tolerance_and_report_their_score() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Rag", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + simplify_every_path(&mut s, 0.05); + s.execute("select.set", &json!({"ids": [g]})).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"), "no exact match: {e}"); + for bad in [json!(-0.01), json!(0.06), json!("0.02"), json!(true)] { + let e = s.execute("type.retype", &json!({"tolerance": bad})).unwrap_err().to_string(); + assert!(e.contains("tolerance must be a number from 0 to 0.05"), "{e}"); + } + assert!(s.doc().unwrap().doc == before, "nothing changes"); + let r = s.execute("type.retype", &json!({"tolerance": 0.02})).unwrap(); + assert_eq!(r["texts"], json!(["Rag"]), "{r}"); + assert_eq!(r["unmatched"], json!([])); + assert_eq!((r["fonts"][0]["family"].as_str(), r["fonts"][0]["style"].as_str()), (Some("Source Sans 3"), Some("Regular"))); + let score = r["fonts"][0]["score"].as_f64().unwrap(); + assert!(score > 0.5 && score < 1.0, "a near match scores below an exact one: {score}"); + let t = text_of(&s, r["ids"][0].as_u64().unwrap()); + assert!(near(t.first_style().size, 40.0, 0.4), "size {}", t.first_style().size); + let o = t.xf.translation(); + assert!(near(o.x, 40.0, 0.4) && near(o.y, 100.0, 0.4), "baseline start {o:?}"); +} + +#[test] +fn exact_matches_score_one() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Rag", "size": 40})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({"tolerance": 0.02})).unwrap(); + assert_eq!(r["texts"], json!(["Rag"]), "{r}"); + assert_eq!(r["fonts"][0]["score"], json!(1.0)); +} + +#[test] +fn exact_matches_with_a_small_leftover_still_score_one() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Rag", "size": 40})); + // Each glyph stretched 0.1% across its own centre: still within the exact matcher's reach, with + // a leftover distance above 0. + let mut ids = vec![]; + s.doc().unwrap().doc.walk(|n| { + if matches!(n.kind, NodeKind::Path { .. }) { + ids.push(n.id); + } + }); + s.edit("test", |d, _| { + for id in &ids { + let data = d.node_mut(*id).unwrap().path_data_mut().unwrap(); + let p = data.to_bezpath(); + let c = kurbo::Shape::bounding_box(&p).center(); + let xf = kurbo::Affine::translate(c.to_vec2()) * kurbo::Affine::scale_non_uniform(1.001, 1.0) * kurbo::Affine::translate(-c.to_vec2()); + *data = vectorcraft_geom::PathData::from_bezpath(&(xf * p)); + } + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + // Each glyph's size now differs a little, so each is its own line. + let texts: Vec<&str> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap()).collect(); + assert_eq!(texts.concat(), "Rag", "{r}"); + for f in r["fonts"].as_array().unwrap() { + assert_eq!(f["score"], json!(1.0), "{r}"); + } +} + +#[test] +fn exact_glyphs_of_another_size_are_another_line_even_with_a_tolerance() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Tia", "size": 40})); + // The a (two contours, so not a lone one-contour glyph) made 4% larger about where it starts + // on the baseline: still exactly the glyph. + let a = *children_of(&s, g).last().unwrap(); + // The a's paths (a compound path's, or its own). + let paths: Vec = match s.doc().unwrap().doc.node(NodeId(a)).unwrap().children() { + Some(c) => c.iter().map(|c| c.id.0).collect(), + None => vec![a], + }; + s.edit("test", |d, _| { + let x0 = paths + .iter() + .map(|id| kurbo::Shape::bounding_box(&d.node_mut(NodeId(*id)).unwrap().path_data_mut().unwrap().to_bezpath()).x0) + .fold(f64::INFINITY, f64::min); + let at = kurbo::Vec2::new(x0, 100.0); + let xf = kurbo::Affine::translate(at) * kurbo::Affine::scale(1.04) * kurbo::Affine::translate(-at); + for id in &paths { + let data = d.node_mut(NodeId(*id)).unwrap().path_data_mut().unwrap(); + *data = vectorcraft_geom::PathData::from_bezpath(&(xf * data.to_bezpath())); + } + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({"tolerance": 0.05})).unwrap(); + assert_eq!(r["texts"], json!(["Ti", "a"]), "{r}"); + let sizes: Vec = r["fonts"].as_array().unwrap().iter().map(|f| f["size"].as_f64().unwrap()).collect(); + assert!(near(sizes[0], 40.0, 0.01) && near(sizes[1], 41.6, 0.01), "{sizes:?}"); + assert!(r["fonts"].as_array().unwrap().iter().all(|f| f["score"] == json!(1.0)), "{r}"); +} + +#[test] +fn turned_near_matched_round_glyphs_keep_the_line_turn() { + // Round glyphs (o, O, the period) and glyphs that look alike half round (N, x, z) fit + // simplified outlines at more than one turn: each takes the turn of its line. + for (text, rotation) in [("no.", 90), ("no.", 180), ("zoo", 135), ("NOON", 180), ("xoxo", 200), ("on", 120)] { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 300, "y": 200, "text": text, "size": 40, "rotation": rotation})); + simplify_every_path(&mut s, 0.05); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({"tolerance": 0.02})).unwrap(); + assert_eq!(r["texts"], json!([text]), "turned {rotation}: {r}"); + assert_eq!(r["unmatched"], json!([]), "{r}"); + } +} + +#[test] +fn a_near_glyph_moved_by_more_than_the_tolerance_ends_the_line() { + // The m (one path) of simplified outlines moved along the baseline by `shift` of the font + // size (40), retyped with a tolerance of 0.03: it may sit 1% + 3% of the size from where the + // type draws it. + let run = |shift: f64| { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Tim", "size": 40})); + simplify_every_path(&mut s, 0.05); + let m = *children_of(&s, g).last().unwrap(); + s.edit("test", |d, _| { + let data = d.node_mut(NodeId(m)).unwrap().path_data_mut().unwrap(); + *data = vectorcraft_geom::PathData::from_bezpath(&(kurbo::Affine::translate((40.0 * shift, 0.0)) * data.to_bezpath())); + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({"tolerance": 0.03})).unwrap(); + let texts: Vec = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect(); + assert_eq!(texts.concat(), "Tim", "{r}"); + texts.len() + }; + assert_eq!(run(0.02), 1, "within the tolerance: one line"); + assert!(run(0.06) > 1, "past it: the line splits where the m was moved"); +} + +#[test] +fn an_exact_glyph_moved_splits_the_line_whatever_the_tolerance() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Tim", "size": 40})); + let m = *children_of(&s, g).last().unwrap(); + s.edit("test", |d, _| { + let data = d.node_mut(NodeId(m)).unwrap().path_data_mut().unwrap(); + *data = vectorcraft_geom::PathData::from_bezpath(&(kurbo::Affine::translate((40.0 * 0.03, 0.0)) * data.to_bezpath())); + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({"tolerance": 0.05})).unwrap(); + assert_eq!(r["texts"], json!(["Ti", "m"]), "exact glyphs keep the exact limits: {r}"); +} + +#[test] +fn an_exact_glyph_after_a_near_one_keeps_the_exact_limits() { + // T exact, o simplified (a near match), m exact moved by 3% of the size along the baseline. + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Tom", "size": 40})); + let kids = children_of(&s, g); + let o: Vec = match s.doc().unwrap().doc.node(NodeId(kids[1])).unwrap().children() { + Some(c) => c.iter().map(|c| c.id).collect(), + None => vec![NodeId(kids[1])], + }; + simplify_paths(&mut s, &o, 0.05); + let m = kids[2]; + s.edit("test", |d, _| { + let data = d.node_mut(NodeId(m)).unwrap().path_data_mut().unwrap(); + *data = vectorcraft_geom::PathData::from_bezpath(&(kurbo::Affine::translate((40.0 * 0.03, 0.0)) * data.to_bezpath())); + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({"tolerance": 0.05})).unwrap(); + assert_eq!(r["texts"], json!(["To", "m"]), "the near o does not loosen the m's limits: {r}"); +} + +/// The outlines of `text` made into one compound path: the compound's id. +fn one_compound(s: &mut Session, text: &str) -> u64 { + let g = outlined(s, json!({"x": 40, "y": 100, "text": text, "size": 40})); + let glyphs = children_of(s, g); + s.execute("select.set", &json!({"ids": glyphs})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap() +} + +#[test] +fn a_word_outlined_as_one_compound_path_splits_into_its_glyphs() { + let mut s = session(); + let c = one_compound(&mut s, "Tim"); + s.execute("select.set", &json!({"ids": [c]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["Tim"]), "the i's stem and dot are one glyph: {r}"); + assert_eq!(r["unmatched"], json!([])); + assert!(s.doc().unwrap().doc.node(NodeId(c)).is_none(), "the compound becomes the type"); +} + +#[test] +fn a_lone_period_in_a_compound_selected_alone_stays_an_outline() { + let mut s = session(); + // An A and, far below it, a period, made into one compound path and selected alone: the + // period, alone on its baseline beside the A, is a dot as much as a period, so it stays an + // outline, and so does the A in the same compound. + let t = outlined(&mut s, json!({"x": 40, "y": 100, "text": "A", "size": 40})); + let dot = outlined(&mut s, json!({"x": 40, "y": 300, "text": ".", "size": 40})); + let mut ids = children_of(&s, t); + ids.extend(children_of(&s, dot)); + s.execute("select.set", &json!({"ids": ids})).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 period became type: {r}"), + Err(e) => e.to_string(), + }; + assert!(e.contains("(1 checked)"), "{e}"); + assert!(s.doc().unwrap().doc == before, "nothing changes"); +} + +#[test] +fn lines_from_one_compound_path_keep_their_order() { + let mut s = session(); + // Two lines of outlines made into one compound path. + let top = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Tim", "size": 40})); + let low = outlined(&mut s, json!({"x": 40, "y": 220, "text": "Ham", "size": 40})); + let mut glyphs = children_of(&s, top); + glyphs.extend(children_of(&s, low)); + s.execute("select.set", &json!({"ids": glyphs})).unwrap(); + let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [c]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 2, "{r}"); + let texts: Vec = ids.iter().map(|id| text_of(&s, *id).plain_text()).collect(); + let d = &s.doc().unwrap().doc; + let at: Vec = ids.iter().map(|id| d.position(NodeId(*id)).unwrap().1).collect(); + // The lines stack in the order of the compound's contours: the first line behind the second. + let first = texts.iter().position(|t| t == "Tim").unwrap(); + let second = texts.iter().position(|t| t == "Ham").unwrap(); + assert!(at[first] < at[second], "{texts:?} at {at:?}"); +} + +#[test] +fn a_compound_whose_parts_are_not_all_glyphs_stays_whole() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Ti", "size": 40})); + let mut ids = children_of(&s, g); + // A shape no glyph is, beside the letters, in the same compound. + ids.push(s.execute("shape.star", &json!({"cx": 140, "cy": 85, "radius1": 12, "radius2": 5, "points": 7})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": ids})).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 = s.execute("type.retype", &json!({})).unwrap_err().to_string(); + assert!(e.contains("(1 checked)"), "reported once: {e}"); + assert!(s.doc().unwrap().doc == before, "nothing changes"); +} + +#[test] +fn a_compound_whose_glyph_stays_an_outline_keeps_its_other_glyphs_too() { + let mut s = session(); + // An A (two contours), and far below it a period: a lone one-contour glyph beside other + // shapes stays an outline, so the A, in the same compound, must stay too. + let t = outlined(&mut s, json!({"x": 40, "y": 100, "text": "A", "size": 40})); + let dot = outlined(&mut s, json!({"x": 40, "y": 300, "text": ".", "size": 40})); + let paths = |s: &Session, id: u64| match s.doc().unwrap().doc.node(NodeId(id)).unwrap().children() { + Some(c) => c.iter().map(|c| c.id.0).collect(), + None => vec![id], + }; + let mut ids: Vec = paths(&s, t); + ids.extend(paths(&s, dot)); + assert_eq!(ids.len(), 2, "one path each"); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + let r = s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [c, r]})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let e = match s.execute("type.retype", &json!({})) { + Ok(r) => panic!("the A became type without its period: {r}"), + Err(e) => e.to_string(), + }; + assert!(e.contains("(2 checked)"), "{e}"); + assert!(s.doc().unwrap().doc == before, "nothing changes"); +} + +#[test] +fn a_split_takes_a_shorter_run_when_the_longest_leaves_a_group_unmatched() { + use kurbo::Shape; + // Three groups A, B and C side by side. A and B together are a glyph, but then C alone is + // none; A alone and B and C together are glyphs, so the split is A, BC. + let mut p = kurbo::BezPath::new(); + for x in [0.0, 100.0, 200.0] { + p.extend(kurbo::Rect::new(x, 0.0, x + 40.0, 40.0).path_elements(0.1)); + } + let find = |path: &kurbo::BezPath, part: bool, _near: bool| -> Vec<&'static str> { + let b = path.bounding_box(); + match (part, b.x0.round() as i64, b.x1.round() as i64) { + (true, 0, 140) => vec!["AB"], + (true, 0, 40) => vec!["A"], + (true, 100, 240) => vec!["BC"], + _ => vec![], + } + }; + let groups = all_groups(&p); + assert_eq!(super::parts(&p, &groups, &find), vec![vec!["A"], vec!["BC"]]); + // 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()); +} + +/// `path`'s contour groups, with no limit on the contours grouped. +fn all_groups(path: &kurbo::BezPath) -> Vec { + let mut budget = usize::MAX; + super::split_groups(path, &mut budget) +} + +#[test] +fn exact_matches_of_the_parts_come_before_a_near_match_of_the_whole() { + use kurbo::Shape; + // Two groups side by side, each exactly a glyph (two periods), and the whole only nearly one + // (a dieresis): the parts win. + let mut p = kurbo::BezPath::new(); + for x in [0.0, 100.0] { + p.extend(kurbo::Rect::new(x, 0.0, x + 40.0, 40.0).path_elements(0.1)); + } + let find = |path: &kurbo::BezPath, part: bool, near: bool| -> Vec<&'static str> { + let b = path.bounding_box(); + match (part, near, b.x0.round() as i64, b.x1.round() as i64) { + (false, true, 0, 140) => vec!["dieresis"], + (true, _, 0, 40) | (true, _, 100, 140) => vec!["period"], + _ => vec![], + } + }; + let groups = all_groups(&p); + assert_eq!(super::parts(&p, &groups, &find), 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(); + match (part, near, b.x0.round() as i64, b.x1.round() as i64) { + (false, true, 0, 140) => vec!["dieresis"], + (true, true, 0, 40) | (true, true, 100, 140) => vec!["period"], + _ => vec![], + } + }; + assert_eq!(super::parts(&p, &groups, &near_only), vec![vec!["dieresis"]]); +} + +#[test] +fn a_shape_that_lost_a_glyph_drops_the_lines_of_its_other_glyphs() { + use std::collections::HashMap; + // Shapes 1 and 2 are two glyphs each, shape 3 one. Line 0 sets one glyph of 1 and one of 2; + // line 1 sets the other glyph of 2 and shape 3. Shape 1's other glyph is set nowhere. + let (a, b, c) = (NodeId(1), NodeId(2), NodeId(3)); + let glyphs_of: HashMap = [(a, 2), (b, 2), (c, 1)].into(); + let lines = vec![vec![a, b], vec![b, c]]; + let dropped = super::partial_lines(&lines, &glyphs_of); + assert!(dropped.contains(&0), "shape 1 is set only in part: {dropped:?}"); + assert!(dropped.contains(&1), "then shape 2 is too: {dropped:?}"); + // Every glyph set: nothing goes. + let whole = vec![vec![a, b], vec![a, b, c]]; + assert!(super::partial_lines(&whole, &glyphs_of).is_empty()); +} + +#[test] +fn the_runs_and_near_keys_a_selection_is_looked_up_by_are_bounded() { + use kurbo::Shape; + use vectorcraft_text::retype::MAX_NEAR_KEYS; + // A compound path of `n` rectangles side by side, each of another width: every run of up to + // three of them has its own near key. + let row = |n: usize| { + let mut p = kurbo::BezPath::new(); + for i in 0..n { + let x = i as f64 * 100.0; + p.extend(kurbo::Rect::new(x, 0.0, x + 10.0 + i as f64 * 0.37, 40.0).path_elements(0.1)); + } + p + }; + // Each shape with its contour groups, as the command looks them up. + let with_groups = |shapes: &[kurbo::BezPath]| -> Vec<(kurbo::BezPath, Vec)> { + let mut budget = super::MAX_SPLIT_TOTAL_CONTOURS; + shapes.iter().map(|p| (p.clone(), super::split_groups(p, &mut budget))).collect() + }; + let keys_of = |shapes: &[(kurbo::BezPath, Vec)], tolerance: f64| { + super::lookup_keys(shapes.iter().map(|(p, g)| (p, g.as_slice())), tolerance) + }; + let few = with_groups(&[row(20)]); + assert_eq!(super::runs(&few[0].1).len(), 20 + 19 + 18, "every run of 1 to 3 groups"); + let (_, keys) = keys_of(&few, 0.01); + assert!(keys.len() > 20, "{}", keys.len()); + assert!(keys_of(&few, 0.0).1.is_empty(), "no near keys without a tolerance"); + // Past 256 groups the shape is matched whole only, and past 512 contours its contours are not + // grouped at all. + assert!(all_groups(&row(300)).is_empty()); + assert_eq!(all_groups(&row(256)).len(), 256); + let mut nested = kurbo::BezPath::new(); + for i in 0..200 { + // Each square with two squares inside it: 200 groups of 3 contours. + let x = i as f64 * 100.0; + nested.extend(kurbo::Rect::new(x, 0.0, x + 90.0, 90.0).path_elements(0.1)); + nested.extend(kurbo::Rect::new(x + 10.0, 10.0, x + 40.0, 40.0).path_elements(0.1)); + nested.extend(kurbo::Rect::new(x + 50.0, 50.0, x + 80.0, 80.0).path_elements(0.1)); + } + assert!(all_groups(&nested).is_empty(), "600 contours"); + assert_eq!(vectorcraft_text::retype::clusters(&nested).len(), 200, "which would make 200 groups"); + // Many shapes with many runs each: the near keys stop at the cap. + let mut shapes: Vec = (0..8).map(|k| kurbo::Affine::scale_non_uniform(1.0, 1.0 + k as f64 * 0.5) * row(200)).collect(); + let (_, keys) = keys_of(&with_groups(&shapes), 0.01); + assert_eq!(keys.len(), MAX_NEAR_KEYS); + // A plain shape selected after them still gets its own near key: whole shapes come first. + let plain = kurbo::Circle::new((0.0, 0.0), 30.0).to_path(0.1); + let key = vectorcraft_text::retype::near_key(&plain).unwrap(); + shapes.push(plain); + let (_, keys) = keys_of(&with_groups(&shapes), 0.01); + assert!(keys.contains(&key)); + // One command groups at most MAX_SPLIT_TOTAL_CONTOURS contours: the shapes after them are + // matched whole only. + let full = vec![row(256); super::MAX_SPLIT_TOTAL_CONTOURS / 256 + 1]; + let split: Vec = with_groups(&full).iter().map(|(_, g)| g.len()).collect(); + assert!(split[..split.len() - 1].iter().all(|n| *n == 256), "{split:?}"); + assert_eq!(split.last(), Some(&0)); +} diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index d7c7be71d6..9fd06a8f95 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -8,13 +8,22 @@ //! best similarity transform (a Procrustes fit) leaves a tiny leftover distance, and the whole //! outline, turned onto the shape, must then lie on it. That holds for outlines made from a font //! the app has (Create Outlines' output, and other apps' that keep each glyph's contours whole and -//! in the font's order). Near matches (other versions of a font, hinted or simplified outlines, -//! faux styles, glyphs merged into one path) are left unmatched; fuzzy identification is phase 2. +//! in the font's order). +//! +//! Near matches ([`RetypeIndex::near_matches`]) take a tolerance: the shape and the glyph are +//! both read at equal steps of length from any start and in either direction, their contours paired +//! by length, so outlines built another way (a simplified outline, a curve split in two, contours +//! in another order or direction) still fit, and [`GlyphMatch::score`] says how closely. +//! [`clusters`] splits a path holding several glyphs (a word outlined as one compound path) into +//! the contour groups that can each be a glyph. Glyphs fused into one contour are not split. use std::collections::{BTreeSet, HashMap}; use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; -use kurbo::{Affine, BezPath, CubicBez, Line, ParamCurve, ParamCurveArclen, ParamCurveNearest, PathEl, PathSeg, Point, QuadBez, Shape}; +use kurbo::{ + Affine, BezPath, CubicBez, Line, ParamCurve, ParamCurveArclen, ParamCurveArea, ParamCurveNearest, PathEl, PathSeg, Point, QuadBez, Shape, +}; use crate::{FontDb, FontFace}; @@ -42,10 +51,38 @@ const OUTLINE_TOLERANCE: f64 = 5e-3; const MAX_OUTLINE_POINTS: usize = 8192; /// Points along an outline past which the whole-outline check gives up (and so rejects). const MAX_CHECKED_POINTS: usize = 65_536; -/// The most glyphs one shape is reported to be ([`RetypeIndex::matches`]). +/// The most glyphs one shape is reported to be ([`RetypeIndex::matches`]), and the most of one face +/// [`RetypeIndex::near_matches`] reports. pub const MAX_CANDIDATES: usize = 16; /// How far apart two shapes' spread-to-length ratios may be and still be compared. const INVARIANT_SLACK: f64 = 0.02; +/// The largest tolerance [`RetypeIndex::near_matches`] takes, and the leftover distance at which +/// [`GlyphMatch::score`] reaches 0. +pub const MAX_TOLERANCE: f64 = 0.05; +/// Points sampled along each contour of a shape for near matching, per point of a glyph's. +const NEAR_OVERSAMPLE: usize = 4; +/// Shapes (and glyphs) with more contours than this are not near matched. +const MAX_NEAR_CONTOURS: usize = 8; +/// How far apart two shapes' spread-to-length ratios may be and still be near matched. +const NEAR_INVARIANT_SLACK: f64 = 0.1; +/// How far apart two shapes' area-to-squared-length ratios may be and still be near matched. +const NEAR_COMPACT_SLACK: f64 = 0.15; +/// Glyphs drawn to check whether they could near match a shape, at most. +const MAX_NEAR_CHECKS: usize = 262_144; +/// Glyphs indexed for near matching, at most. +const MAX_NEAR_GLYPHS: usize = 32_768; +/// Near keys [`RetypeIndex::build_near`] looks glyphs up by, at most: past them, the rest are left +/// out. +pub const MAX_NEAR_KEYS: usize = 1024; +/// Point comparisons near matching makes in all, over every shape of one index: past them, shapes +/// are not near matched. +const NEAR_WORK: u64 = 2_000_000_000; +/// Point comparisons near matching makes for one shape, at most. +const NEAR_SHAPE_WORK: u64 = 50_000_000; +/// Glyphs one shape is near matched against, at most: those closest to it in proportion. +const NEAR_FITS: usize = 256; +/// Contours [`clusters`] reads, at most: past it, none. +const MAX_CLUSTER_CONTOURS: usize = 1024; /// One glyph an outlined shape matched. #[derive(Clone)] @@ -62,6 +99,9 @@ pub struct GlyphMatch { pub origin: Point, /// The leftover distance, relative to the shape's spread. pub residual: f64, + /// Whether the shape is exactly the glyph ([`RetypeIndex::matches`]) rather than nearly + /// ([`RetypeIndex::near_matches`]). + pub exact: bool, /// How many contours the glyph has. pub contours: usize, /// Other poses the glyph fits the shape in equally (a glyph that looks the same turned). @@ -80,6 +120,18 @@ pub struct Pose { } impl GlyphMatch { + /// How closely the glyph fits the shape: 1 for an exact match, and for a near one from 1 down + /// to 0 at a leftover distance of [`MAX_TOLERANCE`] or more. + pub fn score(&self) -> f64 { + if self.exact { + return 1.0; + } + if !self.residual.is_finite() { + return 0.0; + } + (1.0 - self.residual / MAX_TOLERANCE).clamp(0.0, 1.0) + } + /// 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 }; @@ -102,6 +154,8 @@ struct Signature { spread: f64, /// `spread` / the total contour length: unchanged by scale, turn and move. invariant: f64, + /// Each contour's length. + lens: Vec, } struct Entry { @@ -120,6 +174,8 @@ pub struct RetypeIndex { entries: Vec, /// Entry indices by contour count, sorted by invariant. buckets: HashMap>, + /// The point comparisons [`Self::near_matches`] may still make, over every shape. + near_work: AtomicU64, } impl RetypeIndex { @@ -128,6 +184,32 @@ impl RetypeIndex { /// they are not sampled. Outlines are read past the shared outline cache, which keeps the /// canvas's glyphs. pub fn build(db: &FontDb, faces: impl IntoIterator>, keys: &BTreeSet) -> Self { + Self::build_near(db, faces, keys, &[]) + } + + /// [`Self::build`], also indexing for [`Self::near_matches`] the glyphs that could near match + /// a shape with one of the [`near_key`]s in `near` (the first [`MAX_NEAR_KEYS`]): the same + /// number of contours (at most 8) and a close area-to-length ratio. At most 262,144 glyphs are + /// drawn to check that, and at most 32,768 indexed for it, each face taking an equal share of + /// both; of a face's glyphs, those closest in that ratio are indexed. + pub fn build_near(db: &FontDb, faces: impl IntoIterator>, keys: &BTreeSet, near: &[NearKey]) -> Self { + Self::build_near_within(db, faces, keys, near, MAX_NEAR_GLYPHS) + } + + /// [`Self::build_near`] indexing at most `near_glyphs` glyphs for near matching. + fn build_near_within( + db: &FontDb, + faces: impl IntoIterator>, + keys: &BTreeSet, + near: &[NearKey], + near_glyphs: usize, + ) -> Self { + let near: Vec = near + .iter() + .copied() + .filter(|k| k.contours <= MAX_NEAR_CONTOURS && k.compact.is_finite() && k.compact > 0.0) + .take(MAX_NEAR_KEYS) + .collect(); let mut kept: Vec> = vec![]; for f in faces { if kept.len() >= MAX_FACES { @@ -137,17 +219,50 @@ impl RetypeIndex { kept.push(f); } } + // Each face gets an equal share of the near checks and entries, so a face with many glyphs + // (a CJK face) does not use them up before the faces after it. + let share = |cap: usize| cap / kept.len().max(1); let mut entries = vec![]; 'faces: for (fi, face) in kept.iter().enumerate() { - for &(gid, ch, key) in face_keys(db, face).iter() { + let mut face_checks = 0usize; + // The face's glyphs that could near match, with how far their key is from the closest + // wanted one: the closest share of them are indexed, whatever their glyph order. + let keep = share(near_glyphs); + let mut close: Vec<(f64, u32, char, BezPath)> = vec![]; + let trim = |close: &mut Vec<(f64, u32, char, BezPath)>| { + close.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1))); + close.truncate(keep); + }; + for &(gid, ch, key, count) in face_keys(db, face).iter() { // The budget holds inside a face too: no glyph is sampled past it. if entries.len() >= MAX_GLYPHS { break 'faces; } - if !keys.contains(&key) { + 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 }); + } continue; } + let count = usize::from(count); + if keep == 0 || face_checks >= share(MAX_NEAR_CHECKS) || !near.iter().any(|k| k.contours == count) { + continue; + } + face_checks += 1; let outline = db.outline_uncached(face, gid); + let Some(g) = near_key(&outline) else { continue }; + let Some(d) = near.iter().filter(|k| k.close_to(&g)).map(|k| k.apart(&g)).min_by(f64::total_cmp) else { continue }; + close.push((d, gid, ch, outline)); + if close.len() >= keep.saturating_mul(2) { + trim(&mut close); + } + } + trim(&mut close); + for (_, gid, ch, outline) in close { + if entries.len() >= MAX_GLYPHS { + break 'faces; + } if let Some(sig) = signatures(&outline, false).into_iter().next() { entries.push(Entry { face: fi, gid, ch, sig, outline }); } @@ -163,7 +278,7 @@ impl RetypeIndex { x.total_cmp(&y) }); } - RetypeIndex { faces: kept, entries, buckets } + RetypeIndex { faces: kept, entries, buckets, near_work: AtomicU64::new(NEAR_WORK) } } /// The faces indexed. @@ -195,7 +310,23 @@ impl RetypeIndex { /// Every glyph `shape` fits exactly, in every face, in the order of [`RetypeIndex::matches`], /// which returns the first [`MAX_CANDIDATES`] of them. pub fn all_matches(&self, shape: &BezPath) -> Vec { - let variants = signatures(shape, true); + self.matches_read(shape, shape) + } + + /// [`Self::all_matches`], and when the shape fits no glyph as it is, its contours read the + /// other way round: for a part of a compound path, which Make Compound Path may have turned so + /// it cuts a hole in the paths behind it. + pub fn matches_either_way(&self, shape: &BezPath) -> Vec { + let found = self.matches_read(shape, shape); + if !found.is_empty() { + return found; + } + self.matches_read(shape, &shape.reverse_subpaths()) + } + + /// [`Self::all_matches`] of `shape`, its contours read as in `reading` (the same outline). + fn matches_read(&self, shape: &BezPath, reading: &BezPath) -> Vec { + let variants = signatures(reading, true); let Some(first) = variants.first() else { return vec![] }; let Some(list) = self.buckets.get(&first.contours) else { return vec![] }; let lo = first.invariant * (1.0 - INVARIANT_SLACK); @@ -246,6 +377,7 @@ impl RetypeIndex { angle: pose.angle, origin: pose.origin, residual, + exact: true, contours: e.sig.contours, alts: rest.iter().map(|(p, _)| *p).collect(), }; @@ -257,6 +389,441 @@ impl RetypeIndex { }); out.into_iter().map(|(_, m)| m).collect() } + + /// The glyphs `shape` (in document space) nearly is: every glyph of the index with as many + /// contours whose best fit leaves a leftover distance of at most `tolerance` (relative to the + /// shape's spread, at most [`MAX_TOLERANCE`]) and whose whole outline, turned onto the shape, + /// lies within three times the tolerance of it (at least 0.5%). The shape and the glyph are + /// read from any start, in either direction, with their contours paired by length, so the + /// shape need not be built as the glyph is. Upright ones first, then the closest; the other + /// turns a glyph fits in (at most 7) are kept in [`GlyphMatch::alts`]; at most + /// [`MAX_CANDIDATES`] for each face. Empty for a tolerance of 0 or less, and for shapes of more + /// than 8 contours. A shape is compared with at most the 256 glyphs closest to it in proportion + /// (the spread-to-length ratio, and the share of the length each contour has), closest first, + /// in at most 50 million point comparisons, and the index's calls make at most 2 billion in + /// all; once they are spent, the glyphs not yet compared are left out. + pub fn near_matches(&self, shape: &BezPath, tolerance: f64) -> Vec { + // NaN too. + if tolerance.is_nan() || tolerance <= 0.0 { + return vec![]; + } + let tolerance = tolerance.min(MAX_TOLERANCE); + 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); + let hi = s.invariant * (1.0 + NEAR_INVARIANT_SLACK); + let start = list.partition_point(|i| self.entries.get(*i).is_some_and(|e| e.sig.invariant < lo)); + let tol = s.spread * OUTLINE_TOLERANCE.max(3.0 * tolerance); + let mut shape_flat: Option> = None; + let mut out: Vec<(usize, GlyphMatch)> = vec![]; + // The glyphs closest to the shape in proportion, at most NEAR_FITS, closest first: their + // spread-to-length ratio, and the share of the length each contour has, longest first. + let shares = |sig: &Signature| { + let total: f64 = sig.lens.iter().sum(); + let mut v: Vec = sig.lens.iter().map(|l| l / total).collect(); + v.sort_by(|a, b| b.total_cmp(a)); + v + }; + let own = shares(&s); + let apart = |e: &Entry| { + let d = (e.sig.invariant - s.invariant).abs() / s.invariant + shares(&e.sig).iter().zip(&own).map(|(a, b)| (a - b).abs()).sum::(); + if d.is_finite() { d } else { f64::INFINITY } + }; + let mut near: Vec<(f64, &Entry)> = + 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; + for (_, e) in near { + if work == 0 { + break; + } + let Some(face) = self.faces.get(e.face) else { continue }; + let fits = near_fit(&e.sig, &s, tolerance, &mut work); + let flat = shape_flat.get_or_insert_with(|| Flat::new(shape, tol)); + let Some(flat) = flat.as_ref() else { break }; + // Every turn the glyph fits the shape at, nearest upright first: the first is its + // pose, the others its alternatives (a glyph that looks alike turned). + 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 m = GlyphMatch { + face: face.clone(), + gid: e.gid, + ch: e.ch, + scale: pose.scale, + angle: pose.angle, + origin: pose.origin, + residual, + exact: false, + contours: e.sig.contours, + alts: poses.map(|(p, _)| p).collect(), + }; + out.push((e.face, m)); + } + self.near_work.store(total.saturating_sub(given - work), Ordering::Relaxed); + 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)) + }); + keep_per_face(&mut out); + out.into_iter().map(|(_, m)| m).collect() + } +} + +/// Turns of one glyph [`RetypeIndex::near_matches`] keeps, at most: its pose and its alternatives. +const MAX_NEAR_POSES: usize = 8; + +/// `out` (each match with its face's index) without the matches past the first +/// [`MAX_CANDIDATES`] of each face, so faces drawn alike (copies of one font under other names) +/// do not crowd out the glyphs of the faces after them. +fn keep_per_face(out: &mut Vec<(usize, GlyphMatch)>) { + let mut seen: HashMap = HashMap::new(); + out.retain(|(face, _)| { + let n = seen.entry(*face).or_default(); + *n += 1; + *n <= MAX_CANDIDATES + }); +} + +/// Entry `e`'s pose on near-matching shape `s` at scaled turn `z`, when its whole outline, so +/// placed, lies within `tol` of the shape's (`flat`). +fn near_pose(e: &Entry, s: &Signature, z: (f64, f64), flat: &Flat, tol: f64) -> Option { + let gc = mul(z, e.sig.centre); + let origin = Point::new(s.centre.x - gc.x, s.centre.y - gc.y); + let onto = Affine::new([z.0, z.1, -z.1, z.0, origin.x, origin.y]); + Flat::new(&(onto * e.outline.clone()), tol).is_some_and(|g| g.agrees(flat)).then(|| Pose { scale: z.0.hypot(z.1), angle: z.1.atan2(z.0), origin }) +} + +/// What near matching compares first: a shape's number of contours and its area over its squared +/// length, both unchanged by scale, turn and move, and close for outlines drawn alike. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct NearKey { + pub contours: usize, + pub compact: f64, +} + +impl NearKey { + /// Could shapes with these keys near match? + fn close_to(&self, other: &NearKey) -> bool { + self.contours == other.contours && self.apart(other) <= NEAR_COMPACT_SLACK + } + + /// How far apart the two keys' area-to-squared-length ratios are, relative to the larger. + fn apart(&self, other: &NearKey) -> f64 { + (self.compact - other.compact).abs() / self.compact.max(other.compact) + } +} + +/// `path`'s [`NearKey`]; `None` past the size caps, for an empty shape or one of more than 8 +/// contours. +pub fn near_key(path: &BezPath) -> Option { + let (cs, _, _) = measured(path)?; + if cs.is_empty() || cs.len() > MAX_NEAR_CONTOURS { + return None; + } + let (mut area, mut len) = (0.0, 0.0); + for (c, lens) in &cs { + area += c.iter().map(|s| s.signed_area()).sum::().abs(); + len += lens.iter().sum::(); + } + let compact = area / (len * len); + (compact.is_finite() && compact > 0.0).then_some(NearKey { contours: cs.len(), compact }) +} + +/// `path` read for near matching: points at equal steps of length along each contour from where +/// it starts, [`NEAR_OVERSAMPLE`] times as many as a glyph's. `None` for more than 8 contours. +fn near_signature(path: &BezPath) -> Option { + let (cs, _, accuracy) = measured(path)?; + if cs.is_empty() || cs.len() > MAX_NEAR_CONTOURS { + return None; + } + let starts = vec![vec![0usize]; cs.len()]; + let pick = vec![0usize; cs.len()]; + sample(&cs, &starts, &pick, accuracy, SAMPLES * NEAR_OVERSAMPLE) +} + +/// The scaled turn that best takes glyph `g`'s points onto near-matching shape `s`'s (read by +/// [`near_signature`]), whatever contour each starts at, in either direction and order, and the +/// leftover distance relative to the shape's spread. The longest contours are paired first and give +/// the turns to try (spread over the circle when that pair fits about as well at many). Under each +/// turn, every glyph contour takes the shape contour, start and direction closest to it, and the +/// turn is fitted again over them all, for up to [`REFITS`] rounds. The turns that fit about +/// equally well (a glyph that looks alike turned) and within `limit` are kept, the one nearest +/// upright first ([`fits_within`]). Each point comparison is taken from `work`; none when it runs +/// out before the first turn is fitted, and the turns fitted so far when it runs out after. +fn near_fit(g: &Signature, s: &Signature, limit: f64, work: &mut u64) -> Vec<((f64, f64), f64)> { + fits_within(near_turns(g, s, work).unwrap_or_default(), limit) +} + +/// The turns [`near_fit`] fits, each with its leftover distance. +fn near_turns(g: &Signature, s: &Signature, work: &mut u64) -> Option> { + let nc = g.contours; + let m = SAMPLES * NEAR_OVERSAMPLE; + if nc == 0 || s.contours != nc || g.pts.len() != nc * SAMPLES || s.pts.len() != nc * m || g.lens.len() != nc || s.lens.len() != nc { + return None; + } + // Comparisons the longest pair's every start and direction take, and one round of pairing + // every contour and fitting the turn. + let first_cost = (4 * m * SAMPLES) as u64; + let round_cost = ((nc * (nc + 1) * m + 20 * nc) * SAMPLES) as u64; + let Some(left) = work.checked_sub(first_cost) else { + *work = 0; + return None; + }; + *work = left; + let by_len = |lens: &[f64]| { + let mut o: Vec = (0..lens.len()).collect(); + o.sort_by(|a, b| lens.get(*b).copied().unwrap_or(0.0).total_cmp(&lens.get(*a).copied().unwrap_or(0.0))); + o + }; + let (go, so) = (by_len(&g.lens), by_len(&s.lens)); + let (&ga, &sa) = (go.first()?, so.first()?); + let gpts = |c: usize| g.pts.get(c * SAMPLES..(c + 1) * SAMPLES); + let spts = |c: usize| s.pts.get(c * m..(c + 1) * m); + // The point of shape contour `b` matched to glyph sample j, from start k (in samples, and + // between two samples read on the line joining them), forward or back. + let at = |b: &[Point], k: f64, j: usize, back: bool| { + let step = (j * NEAR_OVERSAMPLE) as f64; + let x = (if back { k - step } else { k + step }).rem_euclid(m as f64); + let i = (x.floor() as usize).min(m - 1); + let (p, q) = (b.get(i).copied().unwrap_or(Point::ZERO), b.get((i + 1) % m).copied().unwrap_or(Point::ZERO)); + p.lerp(q, x - i as f64) + }; + // The fit of glyph contour `a` onto shape contour `b` from start k: Σ b·conj(a) and Σ|a|². + let sums = |a: &[Point], b: &[Point], k: f64, back: bool| { + let (mut re, mut im, mut aa) = (0.0, 0.0, 0.0); + for (j, p) in a.iter().enumerate() { + let q = at(b, k, j, back); + re += q.x * p.x + q.y * p.y; + im += q.y * p.x - q.x * p.y; + aa += p.x * p.x + p.y * p.y; + } + (re, im, aa) + }; + let sse = |a: &[Point], b: &[Point], k: f64, back: bool, z: (f64, f64)| { + a.iter().enumerate().map(|(j, p)| at(b, k, j, back).distance_squared(mul(z, *p))).sum::() + }; + // Every start and direction of the longest pair, with its own best turn. + let (a0, b0) = (gpts(ga)?, spts(sa)?); + let mut firsts: Vec<(f64, (f64, f64))> = vec![]; + for back in [false, true] { + for k in 0..m { + let (re, im, aa) = sums(a0, b0, k as f64, back); + if aa <= 0.0 || !aa.is_finite() { + return None; + } + let z = (re / aa, im / aa); + firsts.push((sse(a0, b0, k as f64, back, z), z)); + } + } + firsts.sort_by(|a, b| a.0.total_cmp(&b.0)); + let best = firsts.first()?.0; + // The turns that fit the longest pair about as well as the best. A longest contour that is + // nearly round fits at every angle, and only the other contours tell the turns apart, so + // besides the turns nearest upright, the best in each of TURN_BINS equal ranges of angle is + // tried, at most MAX_TURNS of them, evenly by angle. + const TURN_BINS: usize = 64; + const MAX_TURNS: usize = 24; + let window = best * 1.5 + 1e-12 * s.spread * s.spread; + let mut bins: Vec> = vec![None; TURN_BINS]; + for &(e, z) in firsts.iter().take_while(|(e, _)| *e <= window) { + let ang = z.1.atan2(z.0); + if !ang.is_finite() { + continue; + } + let b = (((ang + std::f64::consts::PI) / std::f64::consts::TAU * TURN_BINS as f64) as usize).min(TURN_BINS - 1); + if let Some(slot) = bins.get_mut(b) + && slot.is_none_or(|(old, _)| e < old) + { + *slot = Some((e, z)); + } + } + // First the best turn and up to five others nearest upright, told apart by their angle, then + // the spread ones. + let mut turns: Vec<(f64, f64)> = firsts.first().map(|f| f.1).into_iter().collect(); + let mut upright: Vec<(f64, f64)> = firsts.iter().take_while(|(e, _)| *e <= window).map(|(_, z)| *z).collect(); + upright.sort_by(|a, b| wrapped(a.1.atan2(a.0)).abs().total_cmp(&wrapped(b.1.atan2(b.0)).abs())); + for z in upright { + if turns.len() >= 6 { + break; + } + let ang = z.1.atan2(z.0); + if turns.iter().all(|t| wrapped(t.1.atan2(t.0) - ang).abs() > 0.05) { + turns.push(z); + } + } + // One contour: every start of it was tried above, and its own fit is final. + if nc > 1 { + let spread: Vec<(f64, f64)> = bins.into_iter().flatten().map(|(_, z)| z).collect(); + let step = spread.len().div_ceil(MAX_TURNS).max(1); + turns.extend(spread.into_iter().step_by(step)); + } + let rounds = if nc > 1 { REFITS } else { 1 }; + let n = (nc * SAMPLES) as f64; + // Each glyph contour, longest first, takes the shape contour, start and direction that fit it + // best under turn `z`; then the turn is fitted over every pair. The new turn and the leftover + // distance; `None` inside for a fit with nothing to go on, and `None` for malformed readings. + let pair_and_fit = |z: (f64, f64)| -> Option> { + let mut free: Vec = so.clone(); + let mut pairs: Vec<(usize, usize, f64, bool)> = vec![]; + for &gc in &go { + let a = gpts(gc)?; + let mut pick: Option<(f64, usize, f64, bool)> = None; + for (fi, &sc) in free.iter().enumerate() { + let b = spts(sc)?; + for back in [false, true] { + for k in 0..m { + let e = sse(a, b, k as f64, back, z); + if pick.is_none_or(|p| e < p.0) { + pick = Some((e, fi, k as f64, back)); + } + } + } + } + let (mut e, fi, mut k, back) = pick?; + let sc = free.remove(fi); + // The start between samples: the shape's samples need not fall where the glyph's do. + let b = spts(sc)?; + let k0 = k; + for d in 1..16 { + let kd = k0 - 0.5 + d as f64 / 16.0; + let ed = sse(a, b, kd, back, z); + if ed < e { + (e, k) = (ed, kd); + } + } + pairs.push((gc, sc, k, back)); + } + let (mut re, mut im, mut aa) = (0.0, 0.0, 0.0); + for &(gc, sc, k, back) in &pairs { + let (r, i, a) = sums(gpts(gc)?, spts(sc)?, k, back); + re += r; + im += i; + aa += a; + } + if aa <= 0.0 || !aa.is_finite() { + return Some(None); + } + let z = (re / aa, im / aa); + let mut total = 0.0; + for &(gc, sc, k, back) in &pairs { + total += sse(gpts(gc)?, spts(sc)?, k, back, z); + } + let rel = (total / n).sqrt() / s.spread; + Some(rel.is_finite().then_some((z, rel))) + }; + let mut results: Vec<((f64, f64), f64)> = vec![]; + 'turns: for z0 in turns { + // Each glyph contour is paired under the turn, the turn is fitted again over the pairs, + // and the contours are paired again under the new turn, until it settles: a turn that + // starts a little off (a round longest contour) moves onto the one the other contours set. + let mut z = z0; + let mut fitted: Option<((f64, f64), f64)> = None; + for _ in 0..rounds { + let Some(left) = work.checked_sub(round_cost) else { + *work = 0; + results.extend(fitted); + break 'turns; + }; + *work = left; + let Some((nz, rel)) = pair_and_fit(z)? else { break }; + let settled = (nz.0 - z.0).hypot(nz.1 - z.1) <= 1e-6 * z.0.hypot(z.1); + if fitted.is_none_or(|f| rel <= f.1) { + fitted = Some((nz, rel)); + } + z = nz; + if settled { + break; + } + } + results.extend(fitted); + } + Some(results) +} + +/// Of fitted turns and their leftover distances, those that fit about as well as the best (within +/// 1.5 times its distance) and within `limit`, nearest upright first, one per turn (turns less +/// than 0.001 apart are one); the best one alone when none is within `limit`. +fn fits_within(results: Vec<((f64, f64), f64)>, limit: f64) -> Vec<((f64, f64), f64)> { + let best = results.iter().map(|r| r.1).fold(f64::INFINITY, f64::min); + let cap = (best * 1.5 + 1e-9).min(limit.max(best)); + let turn = |r: &((f64, f64), f64)| r.0.1.atan2(r.0.0); + let mut kept: Vec<((f64, f64), f64)> = results.into_iter().filter(|r| r.1 <= cap).collect(); + kept.sort_by(|a, b| wrapped(turn(a)).abs().total_cmp(&wrapped(turn(b)).abs()).then(a.1.total_cmp(&b.1))); + let mut out: Vec<((f64, f64), f64)> = vec![]; + for r in kept { + if out.iter().all(|o| wrapped(turn(o) - turn(&r)).abs() >= 1e-3) { + out.push(r); + } + } + out +} + +/// Rounds of pairing and fitting [`near_fit`] gives each turn, at most. +const REFITS: usize = 4; + +/// `path`'s contours in groups that can each be one glyph: a contour with the contours that lie +/// inside it (a letter's counters, and what lies inside those), in the order the outer contours +/// come. A path of several glyphs (a word outlined as one compound path) gives one group per glyph +/// part (an i gives two: its stem and its dot). Empty past 1,024 contours. +pub fn clusters(path: &BezPath) -> Vec { + let mut subs: Vec = vec![]; + for el in path.elements() { + match el { + PathEl::MoveTo(_) => { + if subs.len() >= MAX_CLUSTER_CONTOURS { + return vec![]; + } + subs.push(BezPath::new()); + if let Some(s) = subs.last_mut() { + s.push(*el); + } + } + _ => match subs.last_mut() { + Some(s) => s.push(*el), + None => return vec![], + }, + } + } + let boxes: Vec = subs.iter().map(Shape::bounding_box).collect(); + let starts: Vec> = subs.iter().map(|s| s.elements().first().and_then(|e| e.end_point())).collect(); + // Each contour's container: the smallest contour around it. + let parent: Vec> = (0..subs.len()) + .map(|i| { + let (Some(bi), Some(Some(p))) = (boxes.get(i), starts.get(i)) else { return None }; + (0..subs.len()) + .filter(|&j| j != i) + .filter_map(|j| Some((j, boxes.get(j)?, subs.get(j)?))) + .filter(|(_, bj, sj)| { + bj.area() > bi.area() && bj.x0 <= bi.x0 && bj.y0 <= bi.y0 && bj.x1 >= bi.x1 && bj.y1 >= bi.y1 && sj.winding(*p) != 0 + }) + .min_by(|a, b| a.1.area().total_cmp(&b.1.area())) + .map(|(j, _, _)| j) + }) + .collect(); + let root = |mut i: usize| { + // Containers are strictly larger, so the chain ends; the bound keeps it so. + for _ in 0..subs.len() { + match parent.get(i).copied().flatten() { + Some(p) => i = p, + None => break, + } + } + i + }; + let mut groups: Vec<(usize, BezPath)> = vec![]; + for (i, s) in subs.iter().enumerate() { + let r = root(i); + match groups.iter_mut().find(|(g, _)| *g == r) { + Some((_, p)) => p.extend(s.iter()), + None => groups.push((r, s.clone())), + } + } + groups.sort_by_key(|(r, _)| *r); + groups.into_iter().map(|(_, p)| p).collect() } /// `a` wrapped into −π..π. @@ -264,11 +831,11 @@ fn wrapped(a: f64) -> f64 { (a + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI } -/// A face's glyphs as the index looks them up: (glyph, character, [`shape_key`]), one per glyph -/// under the lowest character that maps to it. -type FaceKeys = Arc>; +/// A face's glyphs as the index looks them up: (glyph, character, [`shape_key`], contours), one per +/// glyph under the lowest character that maps to it. +type FaceKeys = Arc>; -/// How many glyph keys [`face_keys`] keeps in all (16 bytes each). +/// How many glyph keys [`face_keys`] keeps in all (24 bytes each). const KEPT_KEYS: usize = 1 << 20; /// The faces' keys [`face_keys`] keeps, for the database generation they were read in. @@ -306,7 +873,14 @@ fn face_keys(db: &FontDb, face: &FontFace) -> FaceKeys { } let mut gids: Vec<(u32, char)> = by_gid.into_iter().collect(); gids.sort_unstable(); - let keys: FaceKeys = Arc::new(gids.into_iter().filter_map(|(gid, ch)| Some((gid, ch, shape_key(&db.outline_uncached(face, gid))?))).collect()); + let keys: FaceKeys = Arc::new( + gids.into_iter() + .filter_map(|(gid, ch)| { + let (key, count) = key_and_count(&db.outline_uncached(face, gid))?; + Some((gid, ch, key, u16::try_from(count).ok()?)) + }) + .collect(), + ); let mut k = kept.lock().unwrap_or_else(|e| e.into_inner()); if k.generation != generation { return keys; @@ -580,6 +1154,11 @@ fn contours(path: &BezPath) -> Option>> { /// each of its contours has, in order, as [`contours`] reads them, hashed. Glyphs whose key no /// selected shape has are not sampled. `None` past the size caps or for an empty shape. pub fn shape_key(path: &BezPath) -> Option { + key_and_count(path).map(|(k, _)| k) +} + +/// [`shape_key`] and the number of contours it counts. +fn key_and_count(path: &BezPath) -> Option<(u64, usize)> { let cs = contours(path)?; if cs.is_empty() { return None; @@ -592,32 +1171,14 @@ pub fn shape_key(path: &BezPath) -> Option { h = h.wrapping_mul(0x0000_0100_0000_01b3); } } - Some(h) + Some((h, cs.len())) } /// `path` read for matching: one reading per choice of starting corners (the corner of each contour /// farthest from the centre of all the shape's corners; every tied corner when `all_ties`, else the /// first), at most [`MAX_VARIANTS`] tried. Empty for a shape with nothing to match. fn signatures(path: &BezPath, all_ties: bool) -> Vec { - let bounds = path.bounding_box(); - let size = bounds.width().hypot(bounds.height()); - if !size.is_finite() || size <= 0.0 { - return vec![]; - } - let accuracy = size * 1e-6; - let Some(cs) = contours(path) else { return vec![] }; - // Each contour with length, with its segments' lengths. - let cs: Vec<(Vec, Vec)> = cs - .into_iter() - .map(|c| { - let lens: Vec = c.iter().map(|s| s.arclen(accuracy)).collect(); - (c, lens) - }) - .filter(|(_, lens)| { - let len: f64 = lens.iter().sum(); - len.is_finite() && len > size * 1e-9 - }) - .collect(); + let Some((cs, size, accuracy)) = measured(path) else { return vec![] }; let corners: Vec = cs.iter().flat_map(|(c, _)| c.iter().map(|s| s.start())).collect(); if corners.is_empty() { return vec![]; @@ -644,7 +1205,7 @@ fn signatures(path: &BezPath, all_ties: bool) -> Vec { break; } tried += 1; - if let Some(sig) = sample(&cs, &starts, &pick, accuracy) { + if let Some(sig) = sample(&cs, &starts, &pick, accuracy, SAMPLES) { out.push(sig); } // The next choice of tied corners (a counter in mixed radix). @@ -662,19 +1223,47 @@ fn signatures(path: &BezPath, all_ties: bool) -> Vec { out } -/// One reading of the contours `cs`, contour `i` starting at segment `starts[i][pick[i]]`. -fn sample(cs: &[(Vec, Vec)], starts: &[Vec], pick: &[usize], accuracy: f64) -> Option { - let mut pts = Vec::with_capacity(cs.len() * SAMPLES); +/// `path`'s contours as [`contours`] reads them, each with its segments' lengths, leaving out +/// contours of no length, the shape's size (its bounding box's diagonal) and the accuracy lengths +/// are measured to (a millionth of the size). `None` past the size caps and for a shape of no size. +#[allow(clippy::type_complexity)] +fn measured(path: &BezPath) -> Option<(Vec<(Vec, Vec)>, f64, f64)> { + 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 cs = contours(path)? + .into_iter() + .map(|c| { + let lens: Vec = c.iter().map(|s| s.arclen(accuracy)).collect(); + (c, lens) + }) + .filter(|(_, lens)| { + let len: f64 = lens.iter().sum(); + len.is_finite() && len > size * 1e-9 + }) + .collect(); + Some((cs, size, accuracy)) +} + +/// One reading of the contours `cs`, contour `i` starting at segment `starts[i][pick[i]]`, `n` +/// points along each. +fn sample(cs: &[(Vec, Vec)], starts: &[Vec], pick: &[usize], accuracy: f64, n: usize) -> Option { + let mut pts = Vec::with_capacity(cs.len() * n); + let mut lens_out = Vec::with_capacity(cs.len()); let mut total = 0.0; for (((c, lens), s), p) in cs.iter().zip(starts).zip(pick) { let from = *s.get(*p)?; let m = c.len(); let len: f64 = lens.iter().sum(); total += len; + lens_out.push(len); let (mut k, mut before) = (0usize, 0.0); let at_k = |k: usize| (from + k) % m; - for j in 0..SAMPLES { - let at = len * j as f64 / SAMPLES as f64; + for j in 0..n { + let at = len * j as f64 / n as f64; while k + 1 < m && before + lens.get(at_k(k)).copied().unwrap_or(0.0) < at { before += lens.get(at_k(k)).copied().unwrap_or(0.0); k += 1; @@ -696,7 +1285,7 @@ fn sample(cs: &[(Vec, Vec)], starts: &[Vec], pick: &[usize] if !spread.is_finite() || spread <= 0.0 || !total.is_finite() || total <= 0.0 { return None; } - Some(Signature { contours: cs.len(), pts, centre, spread, invariant: spread / total }) + Some(Signature { contours: cs.len(), pts, centre, spread, invariant: spread / total, lens: lens_out }) } /// The first reading of `path` (for tests). @@ -899,6 +1488,236 @@ mod tests { assert!(t0.elapsed() < std::time::Duration::from_secs(5), "{:?}", t0.elapsed()); } + /// `p` flattened into lines `tol` from its curves, each contour started at its second point and + /// run backwards: a simplified outline built nothing like the original. + fn simplified(p: &BezPath, tol: f64) -> BezPath { + let mut contours: Vec> = vec![]; + kurbo::flatten(p.iter(), tol, |el| match el { + PathEl::MoveTo(q) => contours.push(vec![q]), + PathEl::LineTo(q) => { + if let Some(c) = contours.last_mut() { + c.push(q); + } + } + _ => {} + }); + let mut out = BezPath::new(); + for mut c in contours { + c.rotate_left(1); + c.reverse(); + out.move_to(c[0]); + for q in &c[1..] { + out.line_to(*q); + } + out.close_path(); + } + out + } + + fn near_residual(glyph: &BezPath, shape: &BezPath) -> f64 { + near_fit_all(&signature(glyph).unwrap(), &near_signature(shape).unwrap()).map_or(f64::INFINITY, |(_, r)| r) + } + + /// [`near_fit`]'s first fit, with no limit on its work. + fn near_fit_all(g: &Signature, s: &Signature) -> Option<((f64, f64), f64)> { + let mut work = u64::MAX; + near_fit(g, s, MAX_TOLERANCE, &mut work).into_iter().next() + } + + /// [`fits_within`]'s first fit. + fn nearest_upright(results: Vec<((f64, f64), f64)>, limit: f64) -> Option<((f64, f64), f64)> { + fits_within(results, limit).into_iter().next() + } + + #[test] + fn a_simplified_outline_near_matches_and_another_shape_does_not() { + let xf = Affine::translate((300.0, 200.0)) * Affine::rotate(0.4) * Affine::scale(0.024); + let shape = xf * simplified(&letter(), 2.0); + assert_ne!(shape_key(&shape), shape_key(&letter()), "built another way: the exact index never samples it"); + assert!(best_fit(&letter(), &shape) > TOLERANCE, "no exact match"); + let r = near_residual(&letter(), &shape); + assert!(r < 0.005, "near match {r}"); + let (z, _) = near_fit_all(&signature(&letter()).unwrap(), &near_signature(&shape).unwrap()).unwrap(); + // With too little work left, no fit, and nothing left after. + let mut work = 1000; + assert!(near_fit(&signature(&letter()).unwrap(), &near_signature(&shape).unwrap(), MAX_TOLERANCE, &mut work).is_empty()); + assert_eq!(work, 0); + assert!((z.0.hypot(z.1) - 0.024).abs() < 0.024 * 0.01 && (z.1.atan2(z.0) - 0.4).abs() < 0.01, "{z:?}"); + let (a, b) = (near_key(&letter()).unwrap(), near_key(&shape).unwrap()); + assert!(a.close_to(&b), "{a:?} {b:?}"); + // The exact reading of the letter itself near matches it too, with next to nothing left over. + assert!(near_residual(&letter(), &letter()) < 1e-3); + // A box is not near a circle. + 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, 600.0, 0.0).path_elements(0.1)); + assert!(near_residual(&o, &box_) > MAX_TOLERANCE); + assert!(!near_key(&o).unwrap().close_to(&near_key(&box_).unwrap())); + } + + #[test] + fn a_turned_round_glyph_near_matches_upright() { + // A circle fits at every turn: the turn kept is the upright one. + let mut o = BezPath::new(); + o.extend(kurbo::Circle::new((0.0, 0.0), 300.0).path_elements(0.1)); + let (z, r) = near_fit_all(&signature(&o).unwrap(), &near_signature(&simplified(&o, 1.0)).unwrap()).unwrap(); + assert!(r < 0.005, "{r}"); + assert!(z.1.atan2(z.0).abs() < 0.06, "{z:?}"); + } + + #[test] + fn the_upright_turn_is_kept_only_within_the_limit() { + let turned = |a: f64, r: f64| ((a.cos(), a.sin()), r); + // The best fit is turned a quarter round; an upright one fits nearly as well. + let fits = || vec![turned(std::f64::consts::FRAC_PI_2, 0.010), turned(0.0, 0.014)]; + let angle = |f: Option<((f64, f64), f64)>| f.map(|((c, s), _)| s.atan2(c)); + assert_eq!(angle(nearest_upright(fits(), 0.02)), Some(0.0), "both within the limit: the upright one"); + let kept = nearest_upright(fits(), 0.012).unwrap(); + assert!((kept.1 - 0.010).abs() < 1e-12, "only the best is within the limit: the best {kept:?}"); + let kept = nearest_upright(fits(), 0.005).unwrap(); + assert!((kept.1 - 0.010).abs() < 1e-12, "none within the limit: the best {kept:?}"); + assert!(nearest_upright(vec![], 0.05).is_none()); + // Every turn within the limit is kept, upright first, once each. + let all = fits_within( + vec![turned(std::f64::consts::PI, 0.011), turned(std::f64::consts::FRAC_PI_2, 0.010), turned(0.0, 0.014), turned(1e-4, 0.0141)], + 0.02, + ); + let angles: Vec = all.iter().map(|((c, s), _)| s.atan2(*c)).collect(); + assert_eq!(angles.len(), 3, "{angles:?}"); + assert!(angles[0] == 0.0 && (angles[1] - std::f64::consts::FRAC_PI_2).abs() < 1e-12, "{angles:?}"); + } + + #[test] + fn a_curve_split_in_two_still_near_matches() { + // letter() with its cubic split at its middle: exactly another shape, nearly the same. + let (a, b) = kurbo::CubicBez::new((0.0, -700.0), (300.0, -700.0), (450.0, -600.0), (450.0, -480.0)).subdivide(); + let mut p = BezPath::new(); + p.move_to((0.0, 0.0)); + p.line_to((0.0, -700.0)); + p.curve_to(a.p1, a.p2, a.p3); + p.curve_to(b.p1, b.p2, b.p3); + 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(); + assert_ne!(shape_key(&p), shape_key(&letter())); + let shape = Affine::translate((40.0, 90.0)) * Affine::scale(0.03) * p; + assert!(near_residual(&letter(), &shape) < 0.005); + } + + #[test] + fn contours_in_another_order_still_near_match() { + // letter() with its counter first, simplified. + let l = letter(); + let els = l.elements(); + let second = els.iter().rposition(|e| matches!(e, PathEl::MoveTo(_))).unwrap(); + let mut back = BezPath::new(); + back.extend(els[second..].iter().copied()); + back.extend(els[..second].iter().copied()); + let shape = Affine::translate((40.0, 90.0)) * Affine::rotate(0.3) * Affine::scale(0.03) * simplified(&back, 2.0); + assert!(near_residual(&letter(), &shape) < 0.005); + } + + #[test] + fn copies_of_a_font_do_not_crowd_out_the_faces_after_them() { + use crate::test_fonts::{HEIGHT_FAMILY, HEIGHT_OUTSIDE_FAMILY, HEIGHTLESS_FAMILY, NUMBERLESS_FAMILY}; + // Source Sans 3 Regular and four copies of it under other names: each face has several + // glyphs drawn as the period (. · ∙ ․), more than MAX_CANDIDATES in all. + let db = FontDb::with_font_dirs(vec![]); + for bytes in [ + crate::test_fonts::height_font(true), + crate::test_fonts::height_font(false), + crate::test_fonts::height_outside_font(), + crate::test_fonts::numberless_font(), + ] { + db.add_font(bytes.unwrap()); + } + let faces: Vec> = ["Source Sans 3", HEIGHT_FAMILY, HEIGHTLESS_FAMILY, HEIGHT_OUTSIDE_FAMILY, NUMBERLESS_FAMILY] + .iter() + .map(|f| db.face(f, "Regular").unwrap()) + .collect(); + let gid = faces[0].mapped_chars().iter().find(|(c, _)| *c == '.').map(|(_, g)| *g).unwrap(); + let period = Affine::translate((100.0, 200.0)) * Affine::scale(0.04) * db.outline_uncached(&faces[0], gid); + let has_every_period = |found: &[GlyphMatch]| faces.iter().all(|f| found.iter().any(|m| m.ch == '.' && m.face.id() == f.id())); + let keys: BTreeSet = shape_key(&period).into_iter().collect(); + let index = RetypeIndex::build(&db, faces.clone(), &keys); + // The parts of a split compound path are looked up in every face, as whole shapes are. + let found = index.matches_either_way(&period); + assert!(found.len() > MAX_CANDIDATES && has_every_period(&found), "exact: {} matches", found.len()); + let simple = simplified(&period, 0.05); + let index = RetypeIndex::build_near(&db, faces.clone(), &BTreeSet::new(), &[near_key(&simple).unwrap()]); + let found = index.near_matches(&simple, 0.02); + assert!(found.len() > MAX_CANDIDATES && has_every_period(&found), "near: {} matches", found.len()); + } + + #[test] + fn a_face_past_its_near_share_keeps_the_glyphs_closest_to_the_shapes() { + // One glyph of the face is indexed for near matching: the one closest to a simplified o, + // whatever comes before the o in glyph order. + 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 key = near_key(&shape).unwrap(); + let index = RetypeIndex::build_near_within(db, [face], &BTreeSet::new(), &[key], 1); + assert_eq!(index.len(), 1); + let found: Vec = index.near_matches(&shape, 0.02).iter().map(|m| m.ch).collect(); + // The Latin o or the Greek omicron, drawn the same. + assert!(found.iter().any(|c| matches!(c, 'o' | 'ο')), "{found:?}"); + } + + #[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, + // tells the turn, which is far from upright. + let polygon = |cx: f64, cy: f64, r: f64, n: usize, back: bool| { + let mut p = BezPath::new(); + for i in 0..n { + let a = std::f64::consts::TAU * i as f64 / n as f64 * if back { -1.0 } else { 1.0 }; + let q = Point::new(cx + r * a.cos(), cy + r * a.sin()); + if i == 0 { p.move_to(q) } else { p.line_to(q) } + } + p.close_path(); + p + }; + // The outer contour has 720 corners: as round as the samples can tell. + let mut g = polygon(0.0, 0.0, 300.0, 720, false); + g.extend(polygon(120.0, 40.0, 80.0, 24, true).iter()); + let xf = Affine::translate((500.0, 400.0)) * Affine::rotate(2.0) * Affine::scale(0.05); + let shape = xf * simplified(&g, 1.0); + let (z, r) = near_fit_all(&signature(&g).unwrap(), &near_signature(&shape).unwrap()).unwrap(); + assert!(r < 0.01, "{r}"); + assert!(wrapped(z.1.atan2(z.0) - 2.0).abs() < 0.02, "{z:?}"); + } + + #[test] + fn clusters_split_a_word_into_its_glyph_parts() { + let mut word = letter(); + word.extend((Affine::translate((600.0, 0.0)) * letter()).iter()); + // An i: a stem and a dot beside it. + word.extend(kurbo::Rect::new(1200.0, -500.0, 1260.0, 0.0).path_elements(0.1)); + word.extend(kurbo::Circle::new((1230.0, -600.0), 40.0).path_elements(0.1)); + let parts = clusters(&word); + assert_eq!(parts.len(), 4, "two letters (each with its counter), a stem and a dot"); + assert_eq!(shape_key(&parts[0]), shape_key(&letter())); + assert_eq!(shape_key(&parts[1]), shape_key(&letter())); + assert_eq!(parts[2].elements().iter().filter(|e| matches!(e, PathEl::MoveTo(_))).count(), 1); + // A counter written before its outer contour still goes with it, in the outer's place. + let mut back = BezPath::new(); + let l = letter(); + let els = l.elements(); + let second = els.iter().rposition(|e| matches!(e, PathEl::MoveTo(_))).unwrap(); + back.extend(els[second..].iter().copied()); + back.extend(els[..second].iter().copied()); + assert_eq!(clusters(&back).len(), 1); + assert!(clusters(&BezPath::new()).is_empty()); + } + #[test] fn the_same_corners_joined_another_way_are_another_outline() { let poly = |pts: &[(f64, f64)]| { diff --git a/docs/gaps.md b/docs/gaps.md index 288296debf..c94e0fbc56 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -500,7 +500,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Missing:** CJK vertical composition (custom mojikumi sets and the Mojikumi Settings dialog, kinsoku settings #633, manual tate-chu-yoko), Middle Eastern features beyond bidi, digit types, Character Direction and Kashidas (a split caret; the Middle Eastern & South Asian composers are done, #4935), - Touch Type, Retype beyond exact matches of available fonts (phase 1 is in, #4934, and the Retype panel lists the exactly matching fonts; near matches, installed fonts not yet loaded and text in images remain), Snap to Glyph; optional preservation of font sizes during group scaling (#1034 enhancement). + Touch Type, Retype beyond exact matches of available fonts (phase 1 is in, #4934, the Retype panel lists the exactly matching fonts, and `type.retype` takes near matches within a tolerance and words outlined as one compound path; glyphs fused into one contour, near matches in the panel's list, installed fonts not yet loaded and text in images remain), Snap to Glyph; optional preservation of font sizes during group scaling (#1034 enhancement). Itemized in [type-parity.md](type-parity.md). - **Impact:** professional typography and Japanese/Chinese publishing. - **Estimate:** 34–47 h (type core 14–19 h blocks beta). diff --git a/docs/mcp.md b/docs/mcp.md index 79f6183e79..570e3bb84c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10944,6 +10944,34 @@ hidden state and stay live on the group; none of them is copied onto the glyph p glyph. `object.expand` outlines type with this command, so Fill and Stroke expand those paths' gradients, patterns and strokes. +`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 +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 +a near match. Each entry of `fonts` in the result has a `score`, from 1 when every glyph of the line is exact down to 0 +at a leftover distance of 0.05. A compound path that holds several +glyphs, such as a word made into one compound path, is split into groups of contours (a contour with the contours +inside it) in path order, and runs of up to three groups are matched, the longest first among those after which the +remaining groups can still all be matched, so an i's stem and dot become one i. A group whose contours run the other +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 +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 +out. It looks glyphs up for at most 1,024 distinct shapes and runs per command: every selected shape first, in +selection order, then the runs of groups of the compound paths. Glyphs close only to the shapes and runs past that +limit are not looked up. At most 262,144 glyphs are drawn to check whether they could near match, and at most 32,768 +are indexed for it, each face taking an equal share of both; of a face's glyphs, those closest to the selected shapes +in proportion are indexed. + +```json +{"name":"run_command","arguments":{"command":"type.retype","params":{"tolerance":0.02}}} +``` + `type.createOutlines` (Type › Create Outlines) and `effect.expandAppearance` (when it outlines type, as Expand Appearance describes) take an outlined frame of threaded text out of its thread with the text it shows, and the other frames keep the text they hold. When the thread's last frame is outlined, the text it has no room for, which its @@ -12101,7 +12129,8 @@ on an open path that are not drawn because they fall before the path's start can `type.retypeFonts {count?}` lists the fonts whose glyphs match the selected outlined text. It compares each selected path and compound path, inside groups too, with the glyphs of up to 96 loaded fonts, those of the document's live type -first, by the matching `type.retype` uses, and it counts only exact matches. When two versions of a font are loaded, +first, by the matching `type.retype` uses, and it counts only exact matches of whole shapes: it does not split a +compound path into glyphs or take near matches. When two versions of a font are loaded, only the version its family and style name gives is compared, which is the version that choosing the font sets. The fonts rank by how many shapes each matches, then by the mean distance left after fitting, then by family and style name. `count` is a whole number from 1 to 96 (default 10); any other value is an error. The reply is diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 83bcd03586..c28cbf272f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3008,7 +3008,11 @@ Check Spelling followed (2026-11-15): Edit › Spelling › Check Spelling… (` ## Retype, phase 1 (2026-11-18) -The public pages describe Retype finding the fonts that match selected outlined text (or text in an image), from the fonts on the device among others, and applying them to live text ([identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html)). Phase 1 (#4934) is local and exact: Type › Retype (`type.retype`) compares each selected glyph shape with the glyphs of the loaded fonts, the document's fonts and any families named in `fonts`, the same up to uniform scale, rotation and translation, and sets the matched characters as point text in that font and size at the same baseline, one object per line, in one undo step. Shapes that match no font stay and are reported. The search is bounded, not exhaustive: at most 96 faces (named families first, then the document's fonts, then the other loaded faces), the first 65,536 encoded characters of each, and glyphs of plain-shape characters (box drawing, blocks, geometric shapes, private use) are left out; a glyph outside those limits is reported as matching no font. Exact matching also reads a curve an exporter split in two as a different shape (phase 2, with the other near matches). Tested by round trips through Create Outlines (plain, bold and turned, serif, word spaces), a drawn shape and a mixed selection (`crates/engine/src/cmd/retype_tests.rs`). Near matches, the ranked font list, installed fonts not yet loaded and images remain (phase 2). +The public pages describe Retype finding the fonts that match selected outlined text (or text in an image), from the fonts on the device among others, and applying them to live text ([identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html)). Phase 1 (#4934) is local and exact: Type › Retype (`type.retype`) compares each selected glyph shape with the glyphs of the loaded fonts, the document's fonts and any families named in `fonts`, the same up to uniform scale, rotation and translation, and sets the matched characters as point text in that font and size at the same baseline, one object per line, in one undo step. Shapes that match no font stay and are reported. The search is bounded, not exhaustive: at most 96 faces (named families first, then the document's fonts, then the other loaded faces), the first 65,536 encoded characters of each, and glyphs of plain-shape characters (box drawing, blocks, geometric shapes, private use) are left out; a glyph outside those limits is reported as matching no font. Exact matching also reads a curve an exporter split in two as a different shape; near matching with a tolerance (below) reads it as the glyph. Tested by round trips through Create Outlines (plain, bold and turned, serif, word spaces), a drawn shape and a mixed selection (`crates/engine/src/cmd/retype_tests.rs`). Installed fonts not yet loaded and images remain (phase 2). + +## Retype near matches (2026-11-18) + +The public page orders Retype's matching fonts by how close each is to the text's appearance ([identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html)), so outlines need not be exactly a font's glyphs. `type.retype` takes a `tolerance` (0 to 0.05, default 0 for exact matches only). Above 0, a shape of up to 8 contours that is no glyph exactly is read at equal steps of length from any start and in either direction, its contours paired with the glyph's by length, and it becomes the glyph it is closest to when the leftover distance, relative to the shape's size, is at most the tolerance and the glyph's outline and the shape's each lie within three times the tolerance (relative to the shape's size, and at least 0.5%) of the other. 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 a near match. Each line in the result has a `score` from 1 (exact) to 0. A compound path holding several glyphs (a word made into one compound path) is split into groups of contours and matched in runs of up to three groups, and becomes type only when every glyph does; exact matching of those groups also reads contours that run the other way round, as Make Compound Path leaves them. Exact matches of the whole shape come first, then exact matches of its groups, then near matches. The tolerance, the score and the splitting are VectorCraft's own. Tested with outlines flattened into lines, restarted, reversed and simplified, a curve split in two, contours in another order, turned lines of round glyphs, a word made into one compound path, and a compound with a part that is no glyph (`crates/engine/src/cmd/retype_tests.rs`, `crates/text/src/retype.rs`). The Retype panel's list (below) still takes exact matches of whole shapes only. Glyphs fused into one contour, installed fonts not yet loaded and images remain. ## Retype panel (2026-11-18) diff --git a/docs/type-parity.md b/docs/type-parity.md index d97f5bc105..bfd821ee10 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. Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Missing (phase 2): near or fuzzy matches (another version of the font, simplified outlines, glyphs merged into one path), opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, installed fonts not yet loaded, area text for several lines, 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 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) | | 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. | From 61ad1e44895ca2e69dc44027f67291edd3b3a0a2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 06:23:15 -0800 Subject: [PATCH 03/38] Selection: split the release-point tracking out of the pointer handler --- crates/tools/src/select.rs | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 994b21ff21..4fe087f3fd 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -789,6 +789,16 @@ impl SelectionTool { } } + /// Notes where a press or a drag last held the pointer, and says whether a release lands + /// somewhere else. + fn note_held_at(&mut self, ev: &PointerEvent) -> bool { + let released_away = ev.kind == PointerKind::Up && self.held_at != Some(ev.pos); + if matches!(ev.kind, PointerKind::Down | PointerKind::Drag) { + self.held_at = Some(ev.pos); + } + released_away + } + /// The pointer loaded with the text of area type or type on a path `from` ([`State::Loaded`]): /// a press starts placing it, and its release threads it (`text.thread.add`), into a frame put /// `before` `from` or after it. None when `from` can no longer thread: the press is an @@ -1044,10 +1054,7 @@ impl Tool for SelectionTool { /// the art; the drags then move, scale, rotate, marquee or drag what it took. fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { self.note_loaded_at_press(ev.kind); - let released_away = ev.kind == PointerKind::Up && self.held_at != Some(ev.pos); - if matches!(ev.kind, PointerKind::Down | PointerKind::Drag) { - self.held_at = Some(ev.pos); - } + let released_away = self.note_held_at(ev); let hovering = ev.kind == PointerKind::Move && matches!(self.state, State::Idle); self.bracket_hover = hovering.then_some(ev.pos); self.alt_hover = hovering && ev.mods.alt; From 62ff5832d4e87f251cb46ed5b90620d4b8e48ff0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 10:52:35 -0800 Subject: [PATCH 04/38] Tests: set the retype tests' type in a bundled font Outlined text without a font took the system's default face, so a near match of round glyphs depended on the machine's installed fonts. The outlined helper now sets such text in Source Sans 3. --- crates/engine/src/cmd/retype_tests.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 5c043a9e6f..48bf680e75 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -10,7 +10,13 @@ fn session() -> Session { } /// Point text, outlined: the id of the outlines' group. -fn outlined(s: &mut Session, p: serde_json::Value) -> u64 { +fn outlined(s: &mut Session, mut p: serde_json::Value) -> u64 { + // A text without a font is set in the system's default face, which differs from machine to + // machine and decides which glyphs a near match can tell apart. + if p.get("font").is_none() { + p["font"] = json!("Source Sans 3"); + p["style"] = json!("Regular"); + } 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() From 744f32977a75f5b0da273f9f207d2ea66c71b1be Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 11:52:00 -0800 Subject: [PATCH 05/38] 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. | From bba03f1e2b308ad2a237ac53e35c84e73e50956c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 12:05:41 -0800 Subject: [PATCH 06/38] Retype: an explicit null for fonts or tolerance is an invalid parameter --- crates/engine/src/cmd/retype.rs | 4 ++-- crates/engine/src/cmd/retype_tests.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index 7daa1d424c..d7381200f9 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -648,14 +648,14 @@ fn lookup_keys<'a>( fn retype(s: &mut Session, p: &Value) -> Result { const C: &str = "type.retype"; let fonts: Vec = match p.get("fonts") { - None | Some(Value::Null) => vec![], + None => vec![], Some(Value::Array(a)) => { a.iter().map(|v| v.as_str().map(str::to_owned).ok_or_else(|| bad(C, "fonts must be a list of family names"))).collect::>()? } Some(_) => return Err(bad(C, "fonts must be a list of family names")), }; let tolerance = match p.get("tolerance") { - None | Some(Value::Null) => 0.0, + None => 0.0, Some(v) => match v.as_f64() { Some(t) if (0.0..=vectorcraft_text::retype::MAX_TOLERANCE).contains(&t) => t, _ => return Err(bad(C, "tolerance must be a number from 0 to 0.05")), diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 48bf680e75..0a99f20924 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -90,7 +90,7 @@ fn a_drawn_shape_is_reported_and_left_alone() { let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "AB", "size": 40})); s.execute("select.set", &json!({"ids": [g]})).unwrap(); let before = s.doc().unwrap().doc.clone(); - for bad in [json!("Source Sans 3"), json!([1]), json!({"family": "x"})] { + for bad in [json!("Source Sans 3"), json!([1]), json!({"family": "x"}), json!(null)] { let e = s.execute("type.retype", &json!({"fonts": bad})).unwrap_err().to_string(); assert!(e.contains("fonts must be a list of family names"), "{e}"); } @@ -596,7 +596,7 @@ fn simplified_outlines_retype_only_with_a_tolerance_and_report_their_score() { 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"), "no exact match: {e}"); - for bad in [json!(-0.01), json!(0.06), json!("0.02"), json!(true)] { + for bad in [json!(-0.01), json!(0.06), json!("0.02"), json!(true), json!(null)] { let e = s.execute("type.retype", &json!({"tolerance": bad})).unwrap_err().to_string(); assert!(e.contains("tolerance must be a number from 0 to 0.05"), "{e}"); } From 782b6782ffb9609728b7d116540f992716e91401 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 13:29:45 -0800 Subject: [PATCH 07/38] 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 From 8158107e82e561ab31d188ac31f000986571f097 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 16:40:10 -0800 Subject: [PATCH 08/38] Retype: a counter too narrow in any direction, or an outline too large to probe, keeps the shape an outline The fill check rejects a counter whose convex hull is narrower than three times the outline tolerance in some direction, so a turned strip is caught as well as an upright one, and rejects a shape whose outline is too large to flatten. Exact parts of a split compound are checked at tolerance 0 even when near matches are allowed, so a split that only exact matching found is not accepted under the wider tolerance. The tracking sentence in docs/type-parity.md names its three-glyph condition. --- crates/engine/src/cmd/retype.rs | 27 +++-- crates/engine/src/cmd/retype_tests.rs | 73 ++++++++++++- crates/text/src/retype.rs | 147 ++++++++++++++++++++++++-- docs/mcp.md | 6 +- docs/type-parity.md | 2 +- 5 files changed, 231 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index 605ddd08ec..c846c34a51 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -48,7 +48,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 type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; 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 unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; 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 (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), 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", + "{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 type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; 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 unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; 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 counter narrower than three times the outline tolerance across in some direction, an outline too large to check, 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 (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), 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 )] @@ -1178,14 +1178,20 @@ 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. 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> { +/// its groups nearly. A split of several parts is kept only when `together(runs, near)` accepts the +/// paths of its runs (the parts, set one beside another, paint what the shape paints); `near` is +/// set when the parts were found by near matching. +fn parts( + path: &BezPath, + groups: &[BezPath], + find: &dyn Fn(&BezPath, bool, bool) -> Vec, + together: &dyn Fn(&[BezPath], bool) -> 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), together); + let exact = split_parts(groups, &|run| find(run, true, false), &|runs| together(runs, false)); if !exact.is_empty() { return exact; } @@ -1193,7 +1199,7 @@ 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), together) + split_parts(groups, &|run| find(run, true, true), &|runs| together(runs, true)) } /// [`parts`] of a shape split into contour `groups`, each run's candidates from `find`; empty for @@ -1374,7 +1380,14 @@ fn retype(s: &mut Session, p: &Value) -> Result { 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 that all match exactly are checked at tolerance 0, in the near phase as in + // the exact one; only a part that matches nearly brings the tolerance in. + let together = |runs: &[BezPath], near: bool| { + fill.is_none_or(|nz| { + let nearly = near && runs.iter().any(|r| find(r, true, false, fill).is_empty()); + vectorcraft_text::retype::parts_paint_alike(&pc.path, runs, nz, if nearly { tolerance } else { 0.0 }) + }) + }; parts(&pc.path, g, &|p, part, near| find(p, part, near, fill), &together) }) .collect(); diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 05c8210542..f32b036fde 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -1202,6 +1202,50 @@ fn glyphs_that_overlap_in_an_even_odd_compound_stay_an_outline() { assert!(s.doc().unwrap().doc == before, "nothing changes"); } +#[test] +fn overlapping_exact_glyphs_stay_an_outline_when_near_matches_are_allowed() { + // Exact parts the even-odd rule rejects stay rejected when the near phase finds them again. + for dx in [-9.0, -11.0, -12.0, -13.0, -14.0] { + let mut s = session(); + 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": dx, "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(); + for tolerance in [0.0, 0.05] { + if let Ok(r) = s.execute("type.retype", &json!({"tolerance": tolerance})) { + panic!("the overlapping o's became type at dx {dx}, tolerance {tolerance}: {r}"); + } + } + } +} + +#[test] +fn exact_parts_of_a_compound_are_checked_at_tolerance_zero() { + let mut s = session(); + // A T and an o whose boxes overlap by 4 units, one painted area apart (the o sits under the + // bar's arm): a strip that the probes of tolerance 0.05 cannot see into but those of an exact + // match can. Both parts match exactly, so asking for near matches does not change the result. + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "To", "size": 40})); + let kids = children_of(&s, g); + let (t, o) = (kids[0], kids[1]); + let bounds = |s: &Session, id: u64| s.doc().unwrap().doc.node(NodeId(id)).unwrap().geometric_bounds().unwrap(); + let dx = bounds(&s, t).x1 - 4.0 - bounds(&s, o).x0; + s.execute("object.move", &json!({"ids": [o], "dx": dx, "dy": 0})).unwrap(); + s.execute("select.set", &json!({"ids": kids})).unwrap(); + let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + for params in [json!({}), json!({"tolerance": 0.05})] { + s.execute("select.set", &json!({"ids": [c]})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let r = s.execute("type.retype", ¶ms).unwrap(); + assert_eq!(r["unmatched"], json!([]), "{params}: {r}"); + assert!(s.doc().unwrap().doc.node(NodeId(c)).is_none(), "{params}: the compound becomes type"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc == before, "{params}: undo restores it"); + } +} + #[test] fn glyphs_side_by_side_in_an_even_odd_compound_still_become_type() { let mut s = session(); @@ -1257,15 +1301,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, &|_| true), 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()); + 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, &|_| true).is_empty()); + assert!(super::parts(&p, &groups, &none, &|_, _| true).is_empty()); } /// `path`'s contour groups, with no limit on the contours grouped. @@ -1292,7 +1336,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, &|_| true), 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(); @@ -1302,7 +1346,26 @@ fn exact_matches_of_the_parts_come_before_a_near_match_of_the_whole() { _ => vec![], } }; - assert_eq!(super::parts(&p, &groups, &near_only, &|_| true), vec![vec!["dieresis"]]); + assert_eq!(super::parts(&p, &groups, &near_only, &|_, _| true), vec![vec!["dieresis"]]); + // The split's paint check is told whether the parts were found nearly: exact parts are + // checked at tolerance 0 whatever tolerance the command was given. + let seen = std::cell::RefCell::new(vec![]); + let record = |_: &[kurbo::BezPath], near: bool| { + seen.borrow_mut().push(near); + true + }; + assert_eq!(super::parts(&p, &groups, &find, &record), vec![vec!["period"], vec!["period"]]); + assert_eq!(*seen.borrow(), vec![false]); + seen.borrow_mut().clear(); + let split_near_only = |path: &kurbo::BezPath, part: bool, near: bool| -> Vec<&'static str> { + let b = path.bounding_box(); + match (part, near, b.x0.round() as i64, b.x1.round() as i64) { + (true, true, 0, 40) | (true, true, 100, 140) => vec!["period"], + _ => vec![], + } + }; + assert_eq!(super::parts(&p, &groups, &split_near_only, &record), vec![vec!["period"], vec!["period"]]); + assert_eq!(*seen.borrow(), vec![true]); } #[test] diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index 8a65126569..1c9f8795b1 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -1120,14 +1120,14 @@ 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. `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. +/// probed. `false` when a counter of the shape (a contour inside another) is narrower than `3 tol` +/// across in some direction, however it is turned, since the probes cannot then tell whether the +/// area inside it is painted, and `false` 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 (Some(fs), Some(fg)) = (Flat::new(shape, tol), Flat::new(glyph, tol)) else { return false }; 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; @@ -1154,9 +1154,74 @@ 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)? +/// The least width of the convex hull of `path` over every direction it could be measured in, its +/// points flattened to within `tol`; 0 when the hull has fewer than three corners and when the +/// path flattens to more than [`MAX_OUTLINE_POINTS`] points. +fn hull_width(path: &BezPath, tol: f64) -> f64 { + let mut pts: Vec = vec![]; + let mut too_many = false; + kurbo::flatten(path.iter(), tol, |el| { + if let PathEl::MoveTo(q) | PathEl::LineTo(q) = el { + if pts.len() >= MAX_OUTLINE_POINTS { + too_many = true; + } else { + pts.push(q); + } + } + }); + if too_many { + return 0.0; + } + pts.sort_by(|a, b| a.x.total_cmp(&b.x).then(a.y.total_cmp(&b.y))); + // Points a thousandth of `tol` apart are one point: their chord has no direction to speak of. + let eps = tol * 1e-3; + pts.dedup_by(|b, a| a.distance(*b) <= eps); + let cross = |o: Point, a: Point, b: Point| (a - o).cross(b - o); + let mut hull: Vec = vec![]; + for pass in 0..2 { + let from = hull.len(); + let ordered: Vec = if pass == 0 { pts.clone() } else { pts.iter().rev().copied().collect() }; + for p in ordered { + while hull.len() >= from + 2 && hull.get(hull.len() - 2).zip(hull.last()).is_some_and(|(a, b)| cross(*a, *b, p) <= 0.0) { + hull.pop(); + } + hull.push(p); + } + hull.pop(); + } + if hull.len() < 3 { + return 0.0; + } + // Rotating calipers: the point farthest from each edge only moves forward from one edge to the + // next, so the whole walk visits each hull point a bounded number of times. + let n = hull.len(); + let mut least = f64::INFINITY; + let mut j = 1; + for (i, a) in hull.iter().enumerate() { + let Some(b) = hull.get((i + 1) % n) else { continue }; + let edge = *b - *a; + let len = edge.hypot(); + if len <= 0.0 || !len.is_finite() { + continue; + } + let away = |k: usize| hull.get(k % n).map_or(0.0, |p| (edge.cross(*p - *a) / len).abs()); + let mut steps = 0; + while steps < n && away(j + 1) >= away(j) { + j += 1; + steps += 1; + } + least = least.min(away(j)); + j %= n; + } + if least.is_finite() { least } else { 0.0 } +} + +/// Does `path` have a contour inside another contour (a counter) whose convex hull is no wider +/// than `width` in some direction? fn narrow_contour(path: &BezPath, width: f64) -> bool { + if !width.is_finite() || width <= 0.0 { + return false; + } let mut all: Vec = vec![]; for el in path.elements() { if matches!(el, PathEl::MoveTo(_)) { @@ -1168,8 +1233,7 @@ fn narrow_contour(path: &BezPath, width: f64) -> bool { } 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) + all.iter().enumerate().any(|(j, o)| j != i && o.winding(at) != 0) && hull_width(c, width / 30.0) <= width }) } @@ -1970,6 +2034,73 @@ mod tests { assert!(paints_alike(&wide_hole, true, &wide_hole, 1.0)); } + #[test] + fn a_counter_turned_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 60 by 10 counter turned 45 degrees: its box is about 49.5 square, wider than the + // threshold of about 31.8, but it is 10 across. + let strip = |back: bool| { + let turn = Affine::translate((50.0, 50.0)) * Affine::rotate(std::f64::consts::FRAC_PI_4); + let mut p = kurbo::Rect::new(-30.0, -5.0, 30.0, 5.0).to_path(0.1); + if back { + p = p.reverse_subpaths(); + } + turn * p + }; + let mut filled = square(0.0, 0.0, 100.0, 100.0, false); + filled.extend(strip(false).iter()); + let mut holed = square(0.0, 0.0, 100.0, 100.0, false); + holed.extend(strip(true).iter()); + let tol = 100.0_f64.hypot(100.0) * 0.5 * 3.0 * MAX_TOLERANCE; + assert!(narrow_contour(&filled, 3.0 * tol)); + assert!(!paints_alike(&filled, true, &holed, tol)); + // The same strip with its sides along the axes is told apart as before. + let mut level = square(0.0, 0.0, 100.0, 100.0, false); + level.extend(square(20.0, 45.0, 80.0, 55.0, false).iter()); + assert!(narrow_contour(&level, 3.0 * tol)); + // A counter wider than the threshold in every direction is not narrow. + 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()); + assert!(!narrow_contour(&wide, 3.0 * tol)); + } + + #[test] + fn the_hull_width_is_the_least_width_in_any_direction() { + let strip = kurbo::Rect::new(-30.0, -5.0, 30.0, 5.0).to_path(0.1); + for deg in [0.0_f64, 17.0, 45.0, 90.0, 133.0] { + let w = hull_width(&(Affine::rotate(deg.to_radians()) * strip.clone()), 0.01); + assert!((w - 10.0).abs() < 0.05, "{deg} degrees: {w}"); + } + let circle = kurbo::Circle::new((5.0, 7.0), 50.0).to_path(0.1); + assert!((hull_width(&circle, 0.01) - 100.0).abs() < 0.5, "{}", hull_width(&circle, 0.01)); + // A triangle's least width is its shortest height. + let mut tri = BezPath::new(); + tri.move_to((0.0, 0.0)); + tri.line_to((40.0, 0.0)); + tri.line_to((0.0, 30.0)); + tri.close_path(); + assert!((hull_width(&tri, 0.01) - 24.0).abs() < 1e-9); + assert_eq!(hull_width(&BezPath::new(), 0.01), 0.0); + } + + #[test] + fn an_outline_too_large_to_probe_does_not_count_as_agreeing() { + let n = MAX_OUTLINE_POINTS + 64; + let mut many = BezPath::new(); + for i in 0..n { + let a = std::f64::consts::TAU * i as f64 / n as f64; + let p = Point::new(50.0 + 50.0 * a.cos(), 50.0 + 50.0 * a.sin()); + if i == 0 { many.move_to(p) } else { many.line_to(p) } + } + many.close_path(); + assert!(Flat::new(&many, 0.5).is_none(), "too many segments to flatten"); + assert!(!paints_alike(&many, true, &many, 0.5)); + assert!(paints_alike(&kurbo::Circle::new((50.0, 50.0), 50.0).to_path(0.1), true, &kurbo::Circle::new((50.0, 50.0), 50.0).to_path(0.1), 0.5)); + } + #[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); diff --git a/docs/mcp.md b/docs/mcp.md index 30b2f3ea56..910853c024 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11332,9 +11332,9 @@ 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. 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 +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 counter narrower than three times the +outline tolerance across in some direction, turned or not, cannot be checked this way and stays an outline: at `tolerance` 0.05, a +counter 10 units wide in a 100 by 100 shape, or a 60 by 10 one turned 45 degrees. So does a shape whose outline is too large to check. 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 diff --git a/docs/type-parity.md b/docs/type-parity.md index d8e2c1e474..33867c2a92 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 type when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line unless lines stack into one object as described below, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. 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. Evenly spaced glyphs keep their spacing as tracking (gaps one space wide stay word spaces when type draws them), and lines stacked at one leading and lined up at their starts, ends or centers become one area type object with that leading and alignment (VectorCraft's own rules, checked against the layout). Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Missing (phase 2): 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, text in images. Public behaviour: [identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html) | +| Retype (identify fonts in outlines/images) | partial | Phase 1 (#4934): Type › Retype (`type.retype`) turns outlined glyphs back into type when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line unless lines stack into one object as described below, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. 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. A line of three or more exactly matched glyphs keeps the spacing most of its gaps share as tracking (gaps one space wide stay word spaces when type draws them); other lines are set untracked, each glyph at its own position, and lines stacked at one leading and lined up at their starts, ends or centers become one area type object with that leading and alignment (VectorCraft's own rules, checked against the layout). Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Missing (phase 2): 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, 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. | From fe7d225d6f5e07ec24664c1049ffbfc9e2f78b83 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 17:07:50 -0800 Subject: [PATCH 09/38] Retype: a contour reaching outside a concave one is no counter of it, and a rejected split gives way to another A contour counts as lying inside another only when up to eight of its anchor points do. When the paint check rejects the split with the longest runs, the split with the shortest runs is tried before the shape stays an outline. --- crates/engine/src/cmd/retype.rs | 68 ++++++++++++++++----------- crates/engine/src/cmd/retype_tests.rs | 25 ++++++++++ crates/text/src/retype.rs | 48 +++++++++++++++++-- 3 files changed, 110 insertions(+), 31 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index c846c34a51..c9c4281935 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -1210,39 +1210,51 @@ fn split_parts(groups: &[BezPath], find: &dyn Fn(&BezPath) -> Vec, togethe return vec![]; } let g = groups.len(); - // From the last group back: the run that starts at each group, the longest that matches and - // leaves a rest that can all be matched, with its candidates. Runs past such a start are - // never tried for one whose rest cannot be matched. - let mut chosen: Vec)>> = (0..g).map(|_| None).collect(); - for i in (0..g).rev() { - for n in (1..=MAX_RUN.min(g - i)).rev() { - let rest_ok = i + n == g || chosen.get(i + n).is_some_and(Option::is_some); - if !rest_ok { - continue; + // The split with the longest runs first; when `together` rejects it, the one with the shortest + // runs, which is the other end of the complete splits. + for longest in [true, false] { + // From the last group back: the run that starts at each group, the longest (or shortest) + // that matches and leaves a rest that can all be matched, with its candidates. Runs past + // such a start are never tried for one whose rest cannot be matched. + let mut chosen: Vec)>> = (0..g).map(|_| None).collect(); + for i in (0..g).rev() { + let mut lens: Vec = (1..=MAX_RUN.min(g - i)).collect(); + if longest { + lens.reverse(); } - let Some(run) = groups.get(i..i + n) else { continue }; - let cands = find(&joined(run)); - if !cands.is_empty() { - if let Some(c) = chosen.get_mut(i) { - *c = Some((n, cands)); + for n in lens { + let rest_ok = i + n == g || chosen.get(i + n).is_some_and(Option::is_some); + if !rest_ok { + continue; + } + let Some(run) = groups.get(i..i + n) else { continue }; + let cands = find(&joined(run)); + if !cands.is_empty() { + if let Some(c) = chosen.get_mut(i) { + *c = Some((n, cands)); + } + break; } - break; } } + 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 out; + } + // Every run a single group: the other order gives the same split. + if out.len() == g { + break; + } } - 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 + vec![] } /// Contour groups joined into one path. diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index f32b036fde..3882c50f5e 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -1312,6 +1312,31 @@ fn a_split_takes_a_shorter_run_when_the_longest_leaves_a_group_unmatched() { assert!(super::parts(&p, &groups, &none, &|_, _| true).is_empty()); } +#[test] +fn a_split_the_paint_check_rejects_gives_way_to_another_complete_split() { + use kurbo::Shape; + let mut p = kurbo::BezPath::new(); + for x in [0.0, 100.0, 200.0] { + p.extend(kurbo::Rect::new(x, 0.0, x + 40.0, 40.0).path_elements(0.1)); + } + let find = |path: &kurbo::BezPath, part: bool, _near: bool| -> Vec<&'static str> { + let b = path.bounding_box(); + match (part, b.x0.round() as i64, b.x1.round() as i64) { + (true, 0, 140) => vec!["AB"], + (true, 0, 40) => vec!["A"], + (true, 100, 140) => vec!["B"], + (true, 200, 240) => vec!["C"], + _ => vec![], + } + }; + let groups = all_groups(&p); + // The longest runs first (AB, C) are rejected; the three single glyphs are kept. + let singles = |runs: &[kurbo::BezPath], _near: bool| runs.len() == 3; + assert_eq!(super::parts(&p, &groups, &find, &singles), vec![vec!["A"], vec!["B"], vec!["C"]]); + // When no complete split is accepted, nothing. + assert!(super::parts(&p, &groups, &find, &|_, _| false).is_empty()); +} + /// `path`'s contour groups, with no limit on the contours grouped. fn all_groups(path: &kurbo::BezPath) -> Vec { let mut budget = usize::MAX; diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index 1c9f8795b1..6df2f396f2 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -829,6 +829,9 @@ fn fits_within(results: Vec<((f64, f64), f64)>, limit: f64) -> Vec<((f64, f64), /// Rounds of pairing and fitting [`near_fit`] gives each turn, at most. const REFITS: usize = 4; +/// Anchor points of a contour [`clusters`] tests against a candidate container, at most. +const MAX_CONTAINMENT_PROBES: usize = 8; + /// `path`'s contours in groups that can each be one glyph: a contour with the contours that lie /// inside it (a letter's counters, and what lies inside those), in the order the outer contours /// come. A path of several glyphs (a word outlined as one compound path) gives one group per glyph @@ -853,16 +856,33 @@ pub fn clusters(path: &BezPath) -> Vec { } } let boxes: Vec = subs.iter().map(Shape::bounding_box).collect(); - let starts: Vec> = subs.iter().map(|s| s.elements().first().and_then(|e| e.end_point())).collect(); + // Up to MAX_CONTAINMENT_PROBES of each contour's anchor points, evenly spread: a contour lies in + // another only when every one of them does. + let probes: Vec> = subs + .iter() + .map(|s| { + let anchors: Vec = s.elements().iter().filter_map(|e| e.end_point()).collect(); + let step = anchors.len().div_ceil(MAX_CONTAINMENT_PROBES).max(1); + anchors.into_iter().step_by(step).collect() + }) + .collect(); // Each contour's container: the smallest contour around it. let parent: Vec> = (0..subs.len()) .map(|i| { - let (Some(bi), Some(Some(p))) = (boxes.get(i), starts.get(i)) else { return None }; + let (Some(bi), Some(pi)) = (boxes.get(i), probes.get(i)) else { return None }; + if pi.is_empty() { + return None; + } (0..subs.len()) .filter(|&j| j != i) .filter_map(|j| Some((j, boxes.get(j)?, subs.get(j)?))) .filter(|(_, bj, sj)| { - bj.area() > bi.area() && bj.x0 <= bi.x0 && bj.y0 <= bi.y0 && bj.x1 >= bi.x1 && bj.y1 >= bi.y1 && sj.winding(*p) != 0 + bj.area() > bi.area() + && bj.x0 <= bi.x0 + && bj.y0 <= bi.y0 + && bj.x1 >= bi.x1 + && bj.y1 >= bi.y1 + && pi.iter().all(|p| sj.winding(*p) != 0) }) .min_by(|a, b| a.1.area().total_cmp(&b.1.area())) .map(|(j, _, _)| j) @@ -2067,6 +2087,28 @@ mod tests { assert!(!narrow_contour(&wide, 3.0 * tol)); } + #[test] + fn a_contour_reaching_outside_a_concave_one_is_no_counter_of_it() { + // An L, and a triangle that starts inside the L and inside its box but reaches outside it. + let mut l = BezPath::new(); + for (i, (x, y)) in [(0.0, 0.0), (100.0, 0.0), (100.0, 20.0), (20.0, 20.0), (20.0, 100.0), (0.0, 100.0)].into_iter().enumerate() { + if i == 0 { l.move_to((x, y)) } else { l.line_to((x, y)) } + } + l.close_path(); + let mut tri = BezPath::new(); + tri.move_to((5.0, 5.0)); + tri.line_to((90.0, 90.0)); + tri.line_to((5.0, 50.0)); + tri.close_path(); + let mut both = l.clone(); + both.extend(tri.iter()); + assert_eq!(clusters(&both).len(), 2); + // A contour wholly inside stays with its container. + let mut inside = l.clone(); + inside.extend(kurbo::Rect::new(5.0, 5.0, 15.0, 15.0).to_path(0.1).iter()); + assert_eq!(clusters(&inside).len(), 1); + } + #[test] fn the_hull_width_is_the_least_width_in_any_direction() { let strip = kurbo::Rect::new(-30.0, -5.0, 30.0, 5.0).to_path(0.1); From 8483baf11fde0a2df80f1f2b32dae292578c530e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 20:13:02 -0800 Subject: [PATCH 10/38] Retype: the type docs say which two-glyph lines take another line's tracking A line of two glyphs that untracked type does not draw in place takes the tracking of the nearest tracked line in the same font, size and turn, and keeps it only when type at that tracking draws both glyphs in place. A line of one or two glyphs that joins tracked lines in one object takes their tracking. The Retype row in docs/type-parity.md said other lines are set untracked. --- docs/type-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/type-parity.md b/docs/type-parity.md index 33867c2a92..868b944bcd 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 type when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line unless lines stack into one object as described below, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. 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. A line of three or more exactly matched glyphs keeps the spacing most of its gaps share as tracking (gaps one space wide stay word spaces when type draws them); other lines are set untracked, each glyph at its own position, and lines stacked at one leading and lined up at their starts, ends or centers become one area type object with that leading and alignment (VectorCraft's own rules, checked against the layout). Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Missing (phase 2): 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, text in images. Public behaviour: [identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html) | +| Retype (identify fonts in outlines/images) | partial | Phase 1 (#4934): Type › Retype (`type.retype`) turns outlined glyphs back into type when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line unless lines stack into one object as described below, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. 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. A line of three or more exactly matched glyphs keeps the spacing most of its gaps share as tracking (gaps one space wide stay word spaces when type draws them). A line of two glyphs that untracked type does not draw in place takes the tracking of the nearest tracked line in the same font, size and turn, and keeps it only when type at that tracking draws both glyphs in place; a line of one or two glyphs that joins tracked lines in one object takes their tracking. Other lines are set untracked, each glyph at its own position, and lines stacked at one leading and lined up at their starts, ends or centers become one area type object with that leading and alignment (VectorCraft's own rules, checked against the layout). Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Missing (phase 2): 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, 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. | From 90130f37ed321f07d82a556eb3f882608c17262a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 20:55:39 -0800 Subject: [PATCH 11/38] Shape tools: the Smart Guide label of a hover goes when the pointer leaves the canvas With Smart Guides on, hovering a shape tool over another object's anchor or edge shows the "anchor" or "path" label where the new shape would start. When the pointer then left the canvas, went under a panel or menu, or a middle-button drag started panning, the label stayed on the canvas at the last hover point. The Rectangle, Rounded Rectangle, Ellipse, Polygon, Star and Line Segment tools now drop it when their hover ends, and so do the Arc, Spiral, Rectangular Grid and Polar Grid tools, as the Scissors tool already does. --- crates/tools/src/draw2/family.rs | 21 +++++++++++++++++++++ crates/tools/src/shape.rs | 4 +++- crates/tools/src/shape/tests.rs | 17 +++++++++++++++++ 3 files changed, 41 insertions(+), 1 deletion(-) diff --git a/crates/tools/src/draw2/family.rs b/crates/tools/src/draw2/family.rs index 87c11abba9..a815c02d2a 100644 --- a/crates/tools/src/draw2/family.rs +++ b/crates/tools/src/draw2/family.rs @@ -448,6 +448,10 @@ impl Tool for FamilyTool { _ => self.grid_skew_key(key).is_some(), } } + /// The pointer left the canvas: the Smart Guide of the hover goes. + fn hover_ended(&mut self, _cx: &ToolContext) { + self.snap.clear(); + } fn overlays(&self, cx: &ToolContext) -> Vec { let mut o = self.snap.guides().to_vec(); if let Some(s) = self.start.filter(|_| self.began && cx.measurement_labels) { @@ -1254,6 +1258,23 @@ mod tests { assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == "align"))); } + /// The "anchor" label a hover shows goes when the pointer leaves the canvas. + #[test] + fn leaving_the_canvas_drops_the_hover_label() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let label = |o: &[Overlay]| o.iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == "anchor")); + for id in ["arc", "spiral", "rectangularGrid", "polarGrid"] { + let mut t = FamilyTool::new(id); + t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 98.0, 102.0)); + assert!(label(&t.overlays(&cx)), "{id}"); + t.hover_ended(&cx); + assert!(!label(&t.overlays(&cx)), "{id}: {:?}", t.overlays(&cx)); + } + } + /// A grid's Default Size and Reference Point are options for a click's dialog; the drag /// draws the box it is dragged to and leaves them out of its command. #[test] diff --git a/crates/tools/src/shape.rs b/crates/tools/src/shape.rs index 7376efd5b0..b93c94dddc 100644 --- a/crates/tools/src/shape.rs +++ b/crates/tools/src/shape.rs @@ -973,9 +973,11 @@ impl Tool for ShapeTool { fn ends_on_escape(&self, _cx: &ToolContext) -> bool { !self.through.is_empty() } - /// The pointer left the canvas: the circle's preview through it goes. + /// The pointer left the canvas: the circle's preview through it and the Smart Guide of the + /// hover go. fn hover_ended(&mut self, _cx: &ToolContext) { self.hover = None; + self.snap.clear(); } /// An edit, Undo or Redo made outside the tool, or another document, drops the points placed /// for a circle. diff --git a/crates/tools/src/shape/tests.rs b/crates/tools/src/shape/tests.rs index 59ae1d8e83..fa089bf4e7 100644 --- a/crates/tools/src/shape/tests.rs +++ b/crates/tools/src/shape/tests.rs @@ -968,6 +968,23 @@ fn corners_snap_to_smart_guides() { assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text == &cx.segment_measure_label(from, to)))); } +/// The "anchor" label a hover shows goes when the pointer leaves the canvas, for every shape tool. +#[test] +fn leaving_the_canvas_drops_the_hover_label() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let label = |o: &[Overlay]| o.iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == "anchor")); + for id in ["rectangle", "roundedRectangle", "ellipse", "polygon", "star", "lineSegment"] { + let mut t = ShapeTool::new(id); + t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 98.0, 102.0)); + assert!(label(&t.overlays(&cx)), "{id}"); + t.hover_ended(&cx); + assert!(!label(&t.overlays(&cx)), "{id}: {:?}", t.overlays(&cx)); + } +} + /// Line Segment Tool Options: Length and Angle are options (for a click's dialog), and Fill /// Line makes the drag's line take the current fill. #[test] From 2fa3e32c838350d64d9e8629caf3e7cce24f9ed5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 21:57:11 -0800 Subject: [PATCH 12/38] Retype: stacked lines split from one compound path become one object Lines that a compound path of several glyphs splits into share that shape, so the check that one line's shape comes right after the last line's never passed for them, and each line stayed an object of its own. Two lines of one shape now follow each other, and the other joining rules decide as for lines of separate shapes. The lines of the existing paint-order test are moved farther apart so they still make two objects. --- crates/engine/src/cmd/retype.rs | 5 +++-- crates/engine/src/cmd/retype_tests.rs | 22 ++++++++++++++++++++-- docs/mcp.md | 2 +- 3 files changed, 24 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index c9c4281935..563678293e 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -999,7 +999,7 @@ fn share_tracking(lines: &mut [Line], system_layout: bool) { /// `lines`, in paint order, as the objects Retype makes: runs of lines that stack as the lines of /// one paragraph do become one object ([`Block`]). `follows(a, b)`: shape `b` comes right after -/// shape `a`, with nothing between them in paint order. `budget`: see [`Block::made`]. +/// shape `a`, or is `a`, with nothing between them in paint order. `budget`: see [`Block::made`]. fn blocks(lines: Vec, follows: impl Fn(NodeId, NodeId) -> bool, system_layout: bool, budget: &mut usize) -> Vec { let mut out = vec![]; let mut block: Option = None; @@ -1489,8 +1489,9 @@ fn retype(s: &mut Session, p: &Value) -> Result { let mut seen = std::collections::HashSet::new(); unmatched.retain(|id| !kept.contains(id) && seen.insert(*id)); let at: std::collections::HashMap = pieces.iter().enumerate().map(|(i, pc)| (pc.id, i)).collect(); + // Lines split from one compound path share its shape, with nothing between them. let follows = |a: NodeId, b: NodeId| match (at.get(&a), at.get(&b)) { - (Some(i), Some(j)) => *j == i + 1 && pieces.get(*j).is_some_and(|pc| !pc.after_barrier), + (Some(i), Some(j)) => *j == *i || (*j == i + 1 && pieces.get(*j).is_some_and(|pc| !pc.after_barrier)), _ => false, }; // Joining lines takes at most four tries' work per glyph (see [`Block::made`]), with room diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 3882c50f5e..e5231b47b0 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -1146,9 +1146,10 @@ fn a_lone_period_in_a_compound_selected_alone_stays_an_outline() { #[test] fn lines_from_one_compound_path_keep_their_order() { let mut s = session(); - // Two lines of outlines made into one compound path. + // Two lines of outlines made into one compound path, farther apart than the lines of one + // paragraph, so each stays an object of its own. let top = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Tim", "size": 40})); - let low = outlined(&mut s, json!({"x": 40, "y": 220, "text": "Ham", "size": 40})); + let low = outlined(&mut s, json!({"x": 40, "y": 300, "text": "Ham", "size": 40})); let mut glyphs = children_of(&s, top); glyphs.extend(children_of(&s, low)); s.execute("select.set", &json!({"ids": glyphs})).unwrap(); @@ -1166,6 +1167,23 @@ fn lines_from_one_compound_path_keep_their_order() { assert!(at[first] < at[second], "{texts:?} at {at:?}"); } +#[test] +fn stacked_lines_from_one_compound_path_become_one_object() { + let mut s = session(); + // Two lines of one paragraph, outlined and made into one compound path: they join as the + // lines of separate outlines do. + let text = "Tim\nHam"; + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 40})); + let glyphs = children_of(&s, g); + s.execute("select.set", &json!({"ids": glyphs})).unwrap(); + let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [c]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!([text]), "{r}"); + assert_eq!(r["unmatched"], json!([]), "{r}"); + assert!(s.doc().unwrap().doc.node(NodeId(c)).is_none(), "the compound becomes the type"); +} + #[test] fn a_compound_whose_parts_are_not_all_glyphs_stays_whole() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index 910853c024..412809d4f8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -12526,7 +12526,7 @@ tracking their own gaps give. These rules are VectorCraft's own. Each entry of t ## Retype several lines -`type.retype` joins lines that follow each other in paint order, with the same group, paint, font, size, turn and +`type.retype` joins lines that follow each other in paint order (lines split from one compound path do), with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the tracking of the others), into one type object when each line's baseline is the same distance below the one before (between 0.25 and 3 times the size) and the lines line up at their starts, ends or centers. The object is area type with Convert To Area Type's frame, its lines separated by line breaks, with left, right or center alignment, checked in that order. Its From cf80c118712c43ae747b7bc714d297109f5e0ad0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 23:05:44 -0800 Subject: [PATCH 13/38] Retype: a compound tries its other complete splits when the paint check rejects the first two A compound path whose split with the longest runs and split with the shortest runs both failed the paint check stayed an outline, even when another complete split (AB and CD for groups A, B, C and D) passed it. The split search now checks the other complete splits in order, at most 32 per shape for exact matches and 32 for near matches, and looks each run of groups up at most once, only when the search reaches it. --- crates/engine/src/cmd/retype.rs | 191 +++++++++++++++++++++----- crates/engine/src/cmd/retype_tests.rs | 69 ++++++++++ docs/mcp.md | 4 +- 3 files changed, 225 insertions(+), 39 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index 563678293e..69272c1928 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -1147,6 +1147,10 @@ fn partial_lines(lines: &[Vec], glyphs_of: &std::collections::HashMap( } /// [`parts`] of a shape split into contour `groups`, each run's candidates from `find`; empty for -/// no groups, when the groups cannot all be matched and when `together` rejects the runs of a split -/// of several parts. +/// no groups, when the groups cannot all be matched and when `together` rejects every split of +/// several parts it is asked about. The complete splits are tried with the longest runs first, +/// then with the shortest runs, then the others in order, a longer run at an earlier group first. +/// `together` is asked about at most [`MAX_SPLIT_TRIES`] splits. `find` is asked about a run only +/// when the search reaches it, and about each run at most once, so at most [`MAX_RUN`] times per +/// group. fn split_parts(groups: &[BezPath], find: &dyn Fn(&BezPath) -> Vec, together: &dyn Fn(&[BezPath]) -> bool) -> Vec> { - if groups.is_empty() { + let g = groups.len(); + let mut s = Splits { groups, find, found: (0..g).map(|_| (0..MAX_RUN).map(|_| None).collect()).collect(), whole: vec![None; g] }; + // A split is the runs it takes, each as (start, number of groups). + let mut first = vec![]; + if g == 0 || !s.extend(&mut first, false) { return vec![]; } - let g = groups.len(); - // The split with the longest runs first; when `together` rejects it, the one with the shortest - // runs, which is the other end of the complete splits. - for longest in [true, false] { - // From the last group back: the run that starts at each group, the longest (or shortest) - // that matches and leaves a rest that can all be matched, with its candidates. Runs past - // such a start are never tried for one whose rest cannot be matched. - let mut chosen: Vec)>> = (0..g).map(|_| None).collect(); - for i in (0..g).rev() { - let mut lens: Vec = (1..=MAX_RUN.min(g - i)).collect(); - if longest { - lens.reverse(); + let runs_of = + |split: &[(usize, usize)]| -> Vec { split.iter().map(|&(at, n)| groups.get(at..at + n).map(joined).unwrap_or_default()).collect() }; + let accepted = 'search: { + if first.len() == 1 { + break 'search Some(first); + } + // The shortest runs are looked up only once the longest are rejected. + let mut shortest = vec![]; + let mut shortest_next = true; + let mut rest = first.clone(); + let mut candidate = Some(first.clone()); + let mut tried = 0; + while let Some(split) = candidate.take() { + if tried == MAX_SPLIT_TRIES { + break; } - for n in lens { - let rest_ok = i + n == g || chosen.get(i + n).is_some_and(Option::is_some); - if !rest_ok { - continue; + tried += 1; + if together(&runs_of(&split)) { + break 'search Some(split); + } + if std::mem::take(&mut shortest_next) && s.extend(&mut shortest, true) && shortest != first { + candidate = Some(shortest.clone()); + continue; + } + candidate = loop { + if !s.advance(&mut rest) { + break None; } - let Some(run) = groups.get(i..i + n) else { continue }; - let cands = find(&joined(run)); - if !cands.is_empty() { - if let Some(c) = chosen.get_mut(i) { - *c = Some((n, cands)); + if rest != shortest { + break Some(rest.clone()); + } + }; + } + None + }; + let Some(split) = accepted else { return vec![] }; + let mut out = vec![]; + for (at, n) in split { + let Some(Some(cands)) = s.found.get_mut(at).and_then(|f| f.get_mut(n.wrapping_sub(1))).map(Option::take) else { return vec![] }; + out.push(cands); + } + out +} + +/// The state of one [`split_parts`] search: each run's candidates and whether the groups from each +/// start can all be matched, each found when the search first needs it. +struct Splits<'a, M> { + groups: &'a [BezPath], + find: &'a dyn Fn(&BezPath) -> Vec, + /// By start and length less one: the run's candidates, once looked up. + found: Vec>>>, + /// By start: whether the groups from there on can all be matched, once known. + whole: Vec>, +} + +impl Splits<'_, M> { + /// Whether the run of `n` groups at `at` matches, looking it up the first time. + fn matches(&mut self, at: usize, n: usize) -> bool { + let Some(slot) = self.found.get_mut(at).and_then(|f| f.get_mut(n.wrapping_sub(1))) else { return false }; + if slot.is_none() { + let cands = self.groups.get(at..at + n).map(|run| (self.find)(&joined(run))).unwrap_or_default(); + *slot = Some(cands); + } + slot.as_ref().is_some_and(|c| !c.is_empty()) + } + + /// Whether the groups from `at` on can all be matched. The search goes from `at` forward, the + /// longest run first, and no start is searched twice, so it ends after at most [`MAX_RUN`] + /// lookups and checks per group. + fn completes(&mut self, at: usize) -> bool { + let g = self.groups.len(); + if at >= g { + return at == g; + } + if let Some(known) = self.whole.get(at).copied().flatten() { + return known; + } + // From `at`: the starts still to settle, each with the run length to try next. + let mut stack: Vec<(usize, usize)> = vec![(at, MAX_RUN.min(g - at))]; + while let Some(&(i, n)) = stack.last() { + if self.whole.get(i).copied().flatten().is_some() { + stack.pop(); + continue; + } + if n == 0 { + if let Some(w) = self.whole.get_mut(i) { + *w = Some(false); + } + stack.pop(); + continue; + } + if let Some(top) = stack.last_mut() { + top.1 = n - 1; + } + if !self.matches(i, n) { + continue; + } + let next = i + n; + match if next == g { Some(true) } else { self.whole.get(next).copied().flatten() } { + Some(true) => { + if let Some(w) = self.whole.get_mut(i) { + *w = Some(true); } - break; + stack.pop(); + } + Some(false) => {} + None => { + // Settle `next` first, then try this run again. + if let Some(top) = stack.last_mut() { + top.1 = n; + } + stack.push((next, MAX_RUN.min(g - next))); } } } - let mut out = vec![]; - let mut runs = vec![]; - let mut i = 0; + self.whole.get(at).copied().flatten() == Some(true) + } + + /// Whether `n` groups at `at` are a run a complete split can take. + fn fits(&mut self, at: usize, n: usize) -> bool { + self.matches(at, n) && self.completes(at + n) + } + + /// Takes `split` on to the last group, with the longest run that fits at each start (or, with + /// `shortest`, the shortest); false when no run fits. + fn extend(&mut self, split: &mut Vec<(usize, usize)>, shortest: bool) -> bool { + let g = self.groups.len(); + let mut i = split.last().map_or(0, |&(at, n)| at + n); 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()); + let most = MAX_RUN.min(g - i); + let lens: Vec = if shortest { (1..=most).collect() } else { (1..=most).rev().collect() }; + let Some(n) = lens.into_iter().find(|&n| self.fits(i, n)) else { return false }; + split.push((i, n)); i += n; } - if out.len() == 1 || together(&runs) { - return out; + true + } + + /// Moves `split` on to the next complete split, in order: the runs before the last start where + /// a shorter run fits kept, that shorter run, and the longest runs after it. False past the last. + fn advance(&mut self, split: &mut Vec<(usize, usize)>) -> bool { + while let Some((at, n)) = split.pop() { + if let Some(m) = (1..n).rev().find(|&m| self.fits(at, m)) { + split.push((at, m)); + return self.extend(split, false); + } } - // Every run a single group: the other order gives the same split. - if out.len() == g { - break; - } + false } - vec![] } /// Contour groups joined into one path. diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index e5231b47b0..61cbe532bd 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -1355,6 +1355,75 @@ fn a_split_the_paint_check_rejects_gives_way_to_another_complete_split() { assert!(super::parts(&p, &groups, &find, &|_, _| false).is_empty()); } +#[test] +fn a_split_between_the_longest_and_the_shortest_runs_is_tried() { + use kurbo::Shape; + // Four groups A, B, C and D. ABC and D (the longest runs first) and the four single glyphs + // (the shortest) are complete splits the paint check rejects; AB and CD is the one it accepts. + let mut p = kurbo::BezPath::new(); + for x in [0.0, 100.0, 200.0, 300.0] { + p.extend(kurbo::Rect::new(x, 0.0, x + 40.0, 40.0).path_elements(0.1)); + } + let find = |path: &kurbo::BezPath, part: bool, _near: bool| -> Vec<&'static str> { + let b = path.bounding_box(); + match (part, b.x0.round() as i64, b.x1.round() as i64) { + (true, 0, 240) => vec!["ABC"], + (true, 0, 140) => vec!["AB"], + (true, 200, 340) => vec!["CD"], + (true, 0, 40) => vec!["A"], + (true, 100, 140) => vec!["B"], + (true, 200, 240) => vec!["C"], + (true, 300, 340) => vec!["D"], + _ => vec![], + } + }; + let groups = all_groups(&p); + let pairs = |runs: &[kurbo::BezPath], _near: bool| runs.len() == 2 && runs.first().is_some_and(|r| r.bounding_box().x1.round() as i64 == 140); + assert_eq!(super::parts(&p, &groups, &find, &pairs), vec![vec!["AB"], vec!["CD"]]); +} + +#[test] +fn at_most_max_split_tries_complete_splits_are_checked() { + use kurbo::Shape; + // Twelve groups, every run of up to three of them a glyph: far more complete splits than the + // cap. The paint check is asked about the cap's number of them and no more, and each run is + // looked up at most once. + let mut p = kurbo::BezPath::new(); + for i in 0..12 { + let x = f64::from(i) * 100.0; + p.extend(kurbo::Rect::new(x, 0.0, x + 40.0, 40.0).path_elements(0.1)); + } + let groups = all_groups(&p); + assert_eq!(groups.len(), 12); + let looked_up = std::cell::Cell::new(0usize); + let find = |_: &kurbo::BezPath| -> Vec<&'static str> { + looked_up.set(looked_up.get() + 1); + vec!["glyph"] + }; + let asked = &std::cell::Cell::new(0usize); + let accept_at = |n: usize| { + move |_: &[kurbo::BezPath]| { + asked.set(asked.get() + 1); + asked.get() == n + } + }; + // Rejected every time: the search stops at the cap. + assert!(super::split_parts(&groups, &find, &accept_at(usize::MAX)).is_empty()); + assert_eq!(asked.get(), super::MAX_SPLIT_TRIES); + assert!(looked_up.get() <= super::MAX_RUN * groups.len(), "{} lookups", looked_up.get()); + // A first split that is accepted looks up its own runs only: four runs of three groups. + asked.set(0); + looked_up.set(0); + assert_eq!(super::split_parts(&groups, &find, &accept_at(1)).len(), 4); + assert_eq!(looked_up.get(), 4); + // The last split tried is still taken; the one past the cap is not tried. + asked.set(0); + assert!(super::split_parts(&groups, &find, &accept_at(super::MAX_SPLIT_TRIES)).len() > 1); + asked.set(0); + assert!(super::split_parts(&groups, &find, &accept_at(super::MAX_SPLIT_TRIES + 1)).is_empty()); + assert_eq!(asked.get(), super::MAX_SPLIT_TRIES); +} + /// `path`'s contour groups, with no limit on the contours grouped. fn all_groups(path: &kurbo::BezPath) -> Vec { let mut budget = usize::MAX; diff --git a/docs/mcp.md b/docs/mcp.md index 412809d4f8..543e4472c3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11336,7 +11336,9 @@ whose inner contour runs the same way as its outer one paints its center, so a r outline tolerance across in some direction, turned or not, cannot be checked this way and stays an outline: at `tolerance` 0.05, a counter 10 units wide in a 100 by 100 shape, or a 60 by 10 one turned 45 degrees. So does a shape whose outline is too large to check. 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 +other under the even-odd rule) stays an outline. When the split with the longest runs fails that check, the split with the +shortest runs is checked, then the other complete splits in order, up to 32 splits per shape for exact matches and 32 +for near matches; when none passes, the shape 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 From b237da4672231767e8d8ca526e49e78d83d4ff77 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 00:24:20 -0800 Subject: [PATCH 14/38] Retype: a near glyph whose size and turn would draw it past the tolerance ends the line A near-matched glyph joins a line when its size and turn are each within the tolerance of the line's, and the line's type then draws it at the line's size and turn. Together with the glyph's own leftover distance, that change could put the drawn glyph further from its shape than the tolerance: an m 4% larger and turned 0.04 radians stayed on its line at tolerance 0.05. The layout check now also measures, for each near-matched glyph (and each glyph of a line whose first glyph is one), how far the change from its matched size and turn moves the drawn outline relative to its spread, combined with its own leftover distance, and splits the line before it when that passes the tolerance, or when the glyph's center sits further away than its origin may. --- crates/engine/src/cmd/retype.rs | 42 +++++++++++++++- crates/engine/src/cmd/retype_tests.rs | 69 +++++++++++++++++++++++++++ docs/mcp.md | 4 +- 3 files changed, 113 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index 69272c1928..26991f032c 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -48,7 +48,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 type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; 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 unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; 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 counter narrower than three times the outline tolerance across in some direction, an outline too large to check, 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 (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), 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", + "{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 type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; 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 unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; 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 counter narrower than three times the outline tolerance across in some direction, an outline too large to check, 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 (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), 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 )] @@ -637,11 +637,51 @@ fn first_mismatch(t: &TextObject, matches: &[GlyphMatch], size: f64, slack: f64) if g.font_id != m.face.id() || g.gid != m.gid || at.distance(m.origin) > tol { return Some(k); } + // The type sets the glyph at its line's size and turn, which may differ from the glyph's + // own: the glyph drawn so must still lie within the tolerance of the shape (its center + // within the same distance as its origin). + if !(m.exact && first_exact) { + let (shape, moved) = set_apart(t, g, m); + // An exact match's own leftover is within the exact matcher's reach, not the tolerance. + let own = if m.exact { 0.0 } else { m.pose_residual }; + if own.hypot(shape) > slack + 1e-9 || moved > tol { + return Some(k); + } + } } // Ink the outlines did not have: the last glyph is where it went wrong. drawn.next().map(|_| matches.len().saturating_sub(1)) } +/// How glyph `g`, as type `t` draws it, differs from glyph `m` in the size, turn and place `m` +/// was matched in. The first value bounds, whatever points the outline is sampled at, the root +/// mean square distance between the two outlines' points about their center, relative to the +/// root mean square distance of `m`'s points from that center (the measure of near matches' +/// leftover distance): the largest stretch of the change from `m`'s size and turn to the drawn +/// one, which for a change of size and turn alone is that distance exactly. The second is how far +/// apart the two draw the center of the glyph's bounding box. Both are infinite when they cannot +/// be measured. +fn set_apart(t: &TextObject, g: &vectorcraft_text::PositionedGlyph, m: &GlyphMatch) -> (f64, f64) { + let (sin, cos) = m.angle.sin_cos(); + let matched = kurbo::Affine::new([m.scale * cos, m.scale * sin, -m.scale * sin, m.scale * cos, m.origin.x, m.origin.y]); + let (gd, md) = (g.xf.determinant(), matched.determinant()); + if !gd.is_finite() || gd.abs() < 1e-12 || !md.is_finite() || md.abs() < 1e-12 { + return (f64::INFINITY, f64::INFINITY); + } + let drawn = t.xf * g.xf; + // The change from the matched glyph to the drawn one, less the identity, without the move. + let [a, b, c, d, _, _] = (drawn * matched.inverse()).as_coeffs(); + let (a, d) = (a - 1.0, d - 1.0); + // The largest singular value of [[a, c], [b, d]]. + let (p, q) = ((a * a + b * b + c * c + d * d) / 2.0, a * d - b * c); + let shape = (p + (p * p - q * q).max(0.0).sqrt()).sqrt(); + // The center of the glyph's box, in font units. + let center = g.xf.inverse() * kurbo::Shape::bounding_box(&g.outline).center(); + let moved = (drawn * center).distance(matched * center); + let finite = |v: f64| if v.is_finite() { v } else { f64::INFINITY }; + (finite(shape), finite(moved)) +} + /// `lines` checked against their own layout: a line splits where its type stops drawing the /// outlines, and a glyph its type cannot draw even on its own stays an outline (`unmatched`). /// The glyphs laid out are bounded by a multiple of the number of glyphs. diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 61cbe532bd..1d8097f54c 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -1063,6 +1063,75 @@ fn a_near_glyph_moved_by_more_than_the_tolerance_ends_the_line() { assert!(run(0.06) > 1, "past it: the line splits where the m was moved"); } +/// The bounding box of shape `id` (a path, or a compound path's paths), in document space. +fn shape_box(s: &Session, id: u64) -> kurbo::Rect { + let d = &s.doc().unwrap().doc; + let n = d.node(NodeId(id)).unwrap(); + let paths: Vec<&vectorcraft_doc::Node> = match n.children() { + Some(c) => c.iter().map(|c| &**c).collect(), + None => vec![n], + }; + paths + .iter() + .filter_map(|p| match &p.kind { + NodeKind::Path { path, .. } => Some(kurbo::Shape::bounding_box(&path.to_bezpath())), + _ => None, + }) + .reduce(|a, b| a.union(b)) + .unwrap() +} + +/// The bounding box of each glyph with ink that type `t` draws, in document space. +fn drawn_boxes(t: &TextObject) -> Vec { + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty()).map(|g| kurbo::Shape::bounding_box(&(t.xf * g.outline.clone()))).collect() +} + +#[test] +fn a_near_glyph_whose_size_and_turn_differ_past_the_tolerance_ends_the_line() { + // The m of simplified outlines made 4% larger, and turned 0.04 radians as well, about where it + // starts on the baseline, retyped with a tolerance of 0.05. Each change alone is within the + // size and turn a near-matched line allows, but drawn at the line's size and turn the m would + // lie further than 0.05 of its spread from its outline: it becomes type of its own. Larger + // alone, it is still within the tolerance and stays on the line. + for (scale, turn, lines) in [(1.04, 0.0, 1), (1.04, 0.04, 2)] { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Tim", "size": 40})); + simplify_every_path(&mut s, 0.05); + let kids = children_of(&s, g); + let m = *kids.last().unwrap(); + let x0 = shape_box(&s, m).x0; + s.edit("test", |d, _| { + let at = kurbo::Vec2::new(x0, 100.0); + let xf = kurbo::Affine::translate(at) * kurbo::Affine::rotate(turn) * kurbo::Affine::scale(scale) * kurbo::Affine::translate(-at); + let data = d.node_mut(NodeId(m)).unwrap().path_data_mut().unwrap(); + *data = vectorcraft_geom::PathData::from_bezpath(&(xf * data.to_bezpath())); + Ok(()) + }) + .unwrap(); + let before: Vec = kids.iter().map(|k| shape_box(&s, *k)).collect(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({"tolerance": 0.05})).unwrap(); + let texts: Vec<&str> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap()).collect(); + assert_eq!(texts.concat(), "Tim", "{r}"); + assert_eq!(texts.len(), lines, "scale {scale}, turn {turn}: {r}"); + if lines == 1 { + continue; + } + let drawn: Vec = r["ids"].as_array().unwrap().iter().flat_map(|id| drawn_boxes(&text_of(&s, id.as_u64().unwrap()))).collect(); + assert_eq!(drawn.len(), before.len(), "{r}"); + for b in &before { + // The glyph drawn nearest where the outline was. + let d = drawn.iter().min_by(|p, q| p.center().distance(b.center()).total_cmp(&q.center().distance(b.center()))).unwrap(); + let size = b.width().hypot(b.height()); + assert!( + (d.width() - b.width()).abs() < size * 0.01 && (d.height() - b.height()).abs() < size * 0.01, + "scale {scale}, turn {turn}: the outline's box {b:?}, the type's {d:?}: {r}" + ); + } + } +} + #[test] fn an_exact_glyph_moved_splits_the_line_whatever_the_tolerance() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index 543e4472c3..a75c2f8ff8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11322,7 +11322,9 @@ mean square distance of its sampled outline points from their center), is at mos 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 -a near match. Each entry of `fonts` in the result has a `score`, from 1 when every glyph of the line is exact down to 0 +a near match. The line also splits before a near-matched glyph, or a glyph of a line whose first glyph is one, that +the type would draw further from its shape than the tolerance by the same measure (its own leftover distance together +with the change of size and turn) or with its center further away than its origin may be. Each entry of `fonts` in the result has a `score`, from 1 when every glyph of the line is exact down to 0 at a leftover distance of 0.05. A compound path that holds several glyphs, such as a word made into one compound path, is split into groups of contours (a contour with the contours inside it) in path order, and runs of up to three groups are matched, the longest first among those after which the From d1859cf03febea597918e6d05affdc1f382bb97c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 00:44:37 -0800 Subject: [PATCH 15/38] Retype: a compound path of more than 65,536 path elements is not split into glyphs Splitting a compound path copies its contours and compares each with the others. A selected compound of a few contours with a very large number of path elements was split however many elements it had. Such a shape is now matched whole only, like one of more than 256 groups or 512 contours. --- crates/engine/src/cmd/retype.rs | 15 ++++++++++----- crates/engine/src/cmd/retype_tests.rs | 24 ++++++++++++++++++++++++ docs/mcp.md | 4 ++-- 3 files changed, 36 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index 26991f032c..f4efd65cb3 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -48,7 +48,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 type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; 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 unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; 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 counter narrower than three times the outline tolerance across in some direction, an outline too large to check, 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 (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), 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", + "{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 type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; 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, 512 contours and 65,536 path elements, 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 unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; 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 counter narrower than three times the outline tolerance across in some direction, an outline too large to check, 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 (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), 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 )] @@ -1201,13 +1201,18 @@ const MAX_SPLIT_CONTOURS: usize = 512; /// matched whole only. const MAX_SPLIT_TOTAL_CONTOURS: usize = 16_384; +/// A shape of more path elements than this is not split, and its contours are not grouped: 16 +/// times the most a glyph may have ([`vectorcraft_text::retype::MAX_ELEMENTS`]). +const MAX_SPLIT_ELEMENTS: usize = 16 * vectorcraft_text::retype::MAX_ELEMENTS; + /// `path`'s contour groups when it is split into glyphs: none for fewer than two or more than -/// [`MAX_SPLIT_GROUPS`], for more than [`MAX_SPLIT_CONTOURS`] contours, and for more contours than -/// `budget` holds. A path of two or more contours takes them from `budget` when it is grouped. +/// [`MAX_SPLIT_GROUPS`], for more than [`MAX_SPLIT_CONTOURS`] contours or [`MAX_SPLIT_ELEMENTS`] +/// path elements, and for more contours than `budget` holds. A path of two or more contours takes +/// them from `budget` when it is grouped. fn split_groups(path: &BezPath, budget: &mut usize) -> Vec { - // Grouping compares every contour with every other: count them first. + // Grouping copies the contours and compares every contour with every other: count first. let n = path.elements().iter().filter(|e| matches!(e, kurbo::PathEl::MoveTo(_))).count(); - if !(2..=MAX_SPLIT_CONTOURS).contains(&n) || n > *budget { + if !(2..=MAX_SPLIT_CONTOURS).contains(&n) || n > *budget || path.elements().len() > MAX_SPLIT_ELEMENTS { return vec![]; } *budget -= n; diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 1d8097f54c..4ee5388692 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -1565,6 +1565,30 @@ fn a_shape_that_lost_a_glyph_drops_the_lines_of_its_other_glyphs() { assert!(super::partial_lines(&whole, &glyphs_of).is_empty()); } +#[test] +fn a_compound_of_too_many_path_elements_is_not_grouped() { + // Two contours side by side, each a polygon of `k` corners. + let two = |k: usize| { + let mut p = kurbo::BezPath::new(); + for x in [0.0, 300.0] { + for i in 0..k { + let a = i as f64 / k as f64 * std::f64::consts::TAU; + let q = kurbo::Point::new(x + 100.0 + 100.0 * a.cos(), 100.0 + 100.0 * a.sin()); + if i == 0 { p.move_to(q) } else { p.line_to(q) } + } + p.close_path(); + } + p + }; + let mut budget = usize::MAX; + assert_eq!(super::split_groups(&two(100), &mut budget).len(), 2, "a small compound is grouped"); + let big = two(super::MAX_SPLIT_ELEMENTS / 2); + assert!(big.elements().len() > super::MAX_SPLIT_ELEMENTS); + let mut budget = usize::MAX; + assert!(super::split_groups(&big, &mut budget).is_empty(), "past the element limit it is matched whole only"); + assert_eq!(budget, usize::MAX, "and takes no contours from the budget"); +} + #[test] fn the_runs_and_near_keys_a_selection_is_looked_up_by_are_bounded() { use kurbo::Shape; diff --git a/docs/mcp.md b/docs/mcp.md index a75c2f8ff8..bb74d45a8f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11340,8 +11340,8 @@ counter 10 units wide in a 100 by 100 shape, or a 60 by 10 one turned 45 degrees 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. When the split with the longest runs fails that check, the split with the shortest runs is checked, then the other complete splits in order, up to 32 splits per shape for exact matches and 32 -for near matches; when none passes, the shape 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 +for near matches; when none passes, the shape stays an outline. Glyphs fused into one contour are not split, and a compound path of more than 256 groups, 512 contours +or 65,536 path elements 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 out. It looks glyphs up for at most 1,024 distinct shapes and runs per command: every selected shape first, in From f9548440bd1ae09c3a153aab4e73c144c2f5041b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 01:40:36 -0800 Subject: [PATCH 16/38] Retype: a translucent compound path whose glyphs overlap stays an outline The glyphs of a split compound path can become separate type objects, for example on two lines. A compound filled by the nonzero rule whose glyphs overlap passed the paint check, and with an opacity below 100% the two objects then painted the overlap twice. A split whose parts overlap now keeps the shape an outline when the shape has an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke. --- crates/engine/src/cmd/retype.rs | 32 ++++++++++++++------ crates/engine/src/cmd/retype_tests.rs | 43 +++++++++++++++++++++++++++ docs/mcp.md | 4 ++- 3 files changed, 69 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index f4efd65cb3..b464696542 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -48,7 +48,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 type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; 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, 512 contours and 65,536 path elements, 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 unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; 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 counter narrower than three times the outline tolerance across in some direction, an outline too large to check, 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 (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), 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", + "{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 type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; 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, 512 contours and 65,536 path elements, 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 unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; 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 counter narrower than three times the outline tolerance across in some direction, an outline too large to check, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, or that overlap at all when the compound has an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke, 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 (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), 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 )] @@ -596,10 +596,16 @@ impl Line { /// Normal blend, a solid fill or none, and no stroke? One object composites its transparency and /// blend once, spans a gradient over all of it, and strokes after filling every glyph. fn paints_as_one(l: &Line) -> bool { - l.opacity == 1.0 - && l.blend == vectorcraft_color::BlendMode::Normal - && matches!(l.appearance.fill_paint(), vectorcraft_color::Paint::None | vectorcraft_color::Paint::Solid { .. }) - && matches!(l.appearance.stroke_paint(), vectorcraft_color::Paint::None) + paints_once(l.opacity, l.blend, &l.appearance) +} + +/// Does art with `opacity`, `blend` and `appearance` paint its overlaps the same as one object +/// and as several ([`paints_as_one`])? +fn paints_once(opacity: f32, blend: vectorcraft_color::BlendMode, appearance: &Appearance) -> bool { + opacity == 1.0 + && blend == vectorcraft_color::BlendMode::Normal + && matches!(appearance.fill_paint(), vectorcraft_color::Paint::None | vectorcraft_color::Paint::Solid { .. }) + && matches!(appearance.stroke_paint(), vectorcraft_color::Paint::None) } /// The tracking Retype sets, in 1/1000 em. @@ -1554,11 +1560,19 @@ fn retype(s: &mut Session, p: &Value) -> Result { let fill = pc.filled.then_some(pc.nonzero); // Parts that all match exactly are checked at tolerance 0, in the near phase as in // the exact one; only a part that matches nearly brings the tolerance in. + // The glyphs of a split may become separate objects: when the shape does not paint + // its overlaps as several objects would (translucent, another blend, a gradient or + // pattern fill, a stroke), its parts must not overlap, which the parts read by the + // even-odd rule against them all joined show. + let once = paints_once(pc.opacity, pc.blend, &pc.appearance); let together = |runs: &[BezPath], near: bool| { - fill.is_none_or(|nz| { - let nearly = near && runs.iter().any(|r| find(r, true, false, fill).is_empty()); - vectorcraft_text::retype::parts_paint_alike(&pc.path, runs, nz, if nearly { tolerance } else { 0.0 }) - }) + if fill.is_none() && once { + return true; + } + let nearly = near && runs.iter().any(|r| find(r, true, false, fill).is_empty()); + let tol = if nearly { tolerance } else { 0.0 }; + fill.is_none_or(|nz| vectorcraft_text::retype::parts_paint_alike(&pc.path, runs, nz, tol)) + && (once || vectorcraft_text::retype::parts_paint_alike(&joined(runs), runs, false, tol)) }; parts(&pc.path, g, &|p, part, near| find(p, part, near, fill), &together) }) diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 4ee5388692..f939dcf410 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -1289,6 +1289,49 @@ fn glyphs_that_overlap_in_an_even_odd_compound_stay_an_outline() { assert!(s.doc().unwrap().doc == before, "nothing changes"); } +#[test] +fn a_translucent_compound_whose_glyphs_overlap_stays_an_outline() { + // Two i's, the second moved half onto the first and down off its baseline, made into one + // compound path filled by the nonzero rule with every contour running one way: the parts paint + // the shape's area, but on two lines they become two objects, and at 50% opacity their + // overlap would be painted twice. + for opacity in [1.0f32, 0.5] { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "ii", "size": 40})); + let kids = children_of(&s, g); + let dx = shape_box(&s, kids[0]).x0 - shape_box(&s, kids[1]).x0 + 2.0; + s.execute("object.move", &json!({"ids": [kids[1]], "dx": dx, "dy": 6})).unwrap(); + s.execute("select.set", &json!({"ids": kids})).unwrap(); + let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + let paths = children_of(&s, c); + s.edit("test", |d, _| { + // Make Compound Path turns the second glyph's contours the other way round. + for p in &paths { + let data = d.node_mut(NodeId(*p)).unwrap().path_data_mut().unwrap(); + let b = data.to_bezpath(); + if kurbo::Shape::area(&b) < 0.0 { + *data = vectorcraft_geom::PathData::from_bezpath(&b.reverse_subpaths()); + } + } + let n = d.node_mut(NodeId(c)).unwrap(); + n.opacity = opacity; + if let NodeKind::Compound { rule, .. } = &mut n.kind { + *rule = vectorcraft_geom::FillRule::NonZero; + } + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [c]})).unwrap(); + let r = s.execute("type.retype", &json!({})); + if opacity == 1.0 { + let r = r.unwrap(); + assert_eq!(r["texts"], json!(["i", "i"]), "opaque, the two lines become type: {r}"); + } else { + assert!(r.is_err(), "translucent, the compound stays an outline: {r:?}"); + } + } +} + #[test] fn overlapping_exact_glyphs_stay_an_outline_when_near_matches_are_allowed() { // Exact parts the even-odd rule rejects stay rejected when the near phase finds them again. diff --git a/docs/mcp.md b/docs/mcp.md index bb74d45a8f..dcaccb2992 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11338,7 +11338,9 @@ whose inner contour runs the same way as its outer one paints its center, so a r outline tolerance across in some direction, turned or not, cannot be checked this way and stays an outline: at `tolerance` 0.05, a counter 10 units wide in a 100 by 100 shape, or a 60 by 10 one turned 45 degrees. So does a shape whose outline is too large to check. 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. When the split with the longest runs fails that check, the split with the +other under the even-odd rule) stays an outline. A split whose parts overlap at all also stays an outline when the +compound has an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke, since the +glyphs may become separate objects that paint the overlap twice. When the split with the longest runs fails that check, the split with the shortest runs is checked, then the other complete splits in order, up to 32 splits per shape for exact matches and 32 for near matches; when none passes, the shape stays an outline. Glyphs fused into one contour are not split, and a compound path of more than 256 groups, 512 contours or 65,536 path elements is matched whole only. One command groups at most 16,384 contours, in selection order; the shapes after them are From 4e5345968b07c37dd78b9a392ac76db2e2955253 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 01:59:28 -0800 Subject: [PATCH 17/38] Retype: ranking near-match candidates counts against the comparison budget Near matching ranked every glyph of the shape's contour count and proportion before comparing the 256 closest, and that ranking was not counted against the point comparisons each shape and command may make, so a large selection over many fonts could spend unbounded time there. Each glyph ranked now takes one comparison per contour and one more from the same budget, the ranking keeps the closest glyphs without sorting the rest, and the shares of contour length are read without allocating per glyph. --- crates/text/src/retype.rs | 87 +++++++++++++++++++++++++++++---------- docs/mcp.md | 4 +- 2 files changed, 67 insertions(+), 24 deletions(-) diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index 6df2f396f2..0a991c669f 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -451,7 +451,8 @@ impl RetypeIndex { /// than 8 contours. A shape is compared with at most the 256 glyphs closest to it in proportion /// (the spread-to-length ratio, and the share of the length each contour has), closest first, /// in at most 50 million point comparisons, and the index's calls make at most 2 billion in - /// all; once they are spent, the glyphs not yet compared are left out. + /// all (ranking a glyph by proportion counts as one per contour and one more); once they are + /// spent, the glyphs not yet ranked or compared are left out. pub fn near_matches(&self, shape: &BezPath, tolerance: f64) -> Vec { // NaN too. if tolerance.is_nan() || tolerance <= 0.0 { @@ -463,30 +464,12 @@ impl RetypeIndex { 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); - let hi = s.invariant * (1.0 + NEAR_INVARIANT_SLACK); - let start = list.partition_point(|i| self.entries.get(*i).is_some_and(|e| e.sig.invariant < lo)); + if !self.buckets.contains_key(&s.contours) { + return vec![]; + } let tol = s.spread * OUTLINE_TOLERANCE.max(3.0 * tolerance); let mut shape_flat: Option> = None; let mut out: Vec<(usize, GlyphMatch)> = vec![]; - // The glyphs closest to the shape in proportion, at most NEAR_FITS, closest first: their - // spread-to-length ratio, and the share of the length each contour has, longest first. - let shares = |sig: &Signature| { - let total: f64 = sig.lens.iter().sum(); - let mut v: Vec = sig.lens.iter().map(|l| l / total).collect(); - v.sort_by(|a, b| b.total_cmp(a)); - v - }; - let own = shares(&s); - let apart = |e: &Entry| { - let d = (e.sig.invariant - s.invariant).abs() / s.invariant + shares(&e.sig).iter().zip(&own).map(|(a, b)| (a - b).abs()).sum::(); - if d.is_finite() { d } else { f64::INFINITY } - }; - let mut near: Vec<(f64, &Entry)> = - 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); // 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); @@ -497,6 +480,7 @@ impl RetypeIndex { Err(now) => seen = now, } }; + let near = self.ranked_near(&s, &mut work); for (_, e) in near { if work == 0 { break; @@ -535,6 +519,47 @@ impl RetypeIndex { keep_per_face(&mut out); out.into_iter().map(|(_, m)| m).collect() } + + /// The glyphs of as many contours as near-matching shape `s` that are closest to it in + /// proportion, at most [`NEAR_FITS`], closest first: their spread-to-length ratio, and the + /// share of the length each contour has, longest first. Ranking a glyph takes one comparison + /// per contour, and one more, from `work`; once it is spent, the glyphs not yet ranked are + /// left out. + fn ranked_near(&self, s: &Signature, work: &mut u64) -> Vec<(f64, &Entry)> { + let Some(list) = self.buckets.get(&s.contours) else { return vec![] }; + let lo = s.invariant * (1.0 - NEAR_INVARIANT_SLACK); + let hi = s.invariant * (1.0 + NEAR_INVARIANT_SLACK); + let start = list.partition_point(|i| self.entries.get(*i).is_some_and(|e| e.sig.invariant < lo)); + // Each contour's share of the length, longest first (a near-matched shape has at most + // MAX_NEAR_CONTOURS contours, and the glyphs ranked as many). + let shares = |sig: &Signature| { + let mut v = [0.0f64; MAX_NEAR_CONTOURS]; + let total: f64 = sig.lens.iter().sum(); + for (o, l) in v.iter_mut().zip(&sig.lens) { + *o = l / total; + } + v.sort_by(|a, b| b.total_cmp(a)); + v + }; + let own = shares(s); + let apart = |e: &Entry| { + let d = (e.sig.invariant - s.invariant).abs() / s.invariant + shares(&e.sig).iter().zip(&own).map(|(a, b)| (a - b).abs()).sum::(); + if d.is_finite() { d } else { f64::INFINITY } + }; + let cost = s.contours as u64 + 1; + let mut near: Vec<(f64, &Entry)> = vec![]; + for e in list.iter().skip(start).filter_map(|i| self.entries.get(*i)).take_while(|e| e.sig.invariant <= hi) { + let Some(left) = work.checked_sub(cost) else { break }; + *work = left; + near.push((apart(e), e)); + } + if near.len() > NEAR_FITS { + near.select_nth_unstable_by(NEAR_FITS, |a, b| a.0.total_cmp(&b.0)); + near.truncate(NEAR_FITS); + } + near.sort_by(|a, b| a.0.total_cmp(&b.0)); + near + } } /// Turns of one glyph [`RetypeIndex::near_matches`] keeps, at most: its pose and its alternatives. @@ -2181,6 +2206,24 @@ mod tests { assert_eq!(index.near_work.load(Ordering::Acquire), 0); } + #[test] + fn ranking_near_match_candidates_takes_from_the_work_budget() { + 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()]); + let s = near_signature(&shape).unwrap(); + let mut all = u64::MAX; + let ranked = index.ranked_near(&s, &mut all).len(); + assert!(ranked >= 1, "the o is ranked"); + assert_eq!(u64::MAX - all, ranked as u64 * 3, "each glyph of two contours takes three"); + // Enough to rank one glyph of two contours and nothing more. + let mut work = 4; + assert_eq!(index.ranked_near(&s, &mut work).len(), 1); + assert_eq!(work, 1); + } + #[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 dcaccb2992..edbcdcb3f5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11345,8 +11345,8 @@ shortest runs is checked, then the other complete splits in order, up to 32 spli for near matches; when none passes, the shape stays an outline. Glyphs fused into one contour are not split, and a compound path of more than 256 groups, 512 contours or 65,536 path elements 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 -out. It looks glyphs up for at most 1,024 distinct shapes and runs per command: every selected shape first, in +most 50 million point comparisons per shape and 2 billion per command, ranking a glyph by proportion counting as one +comparison per contour and one more; past them, the glyphs not yet ranked or compared are left out. It looks glyphs up for at most 1,024 distinct shapes and runs per command: every selected shape first, in selection order, then the runs of groups of the compound paths. Glyphs close only to the shapes and runs past that limit are not looked up. At most 262,144 glyphs are drawn to check whether they could near match, and at most 32,768 are indexed for it, each face taking an equal share of both; of a face's glyphs, those closest to the selected shapes From c5959c36ae153b196bc70e93349ef96f2a443a68 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 05:43:25 -0800 Subject: [PATCH 18/38] Retype: glyphs that fit several fonts equally often take the font they fit closest in all Each shape votes for every face it fits, and each glyph is set in the face with the most votes. When faces tied, each glyph took its own closest face, so one line could be set in several fonts. With Noto Sans CJK SC loaded, simplified Source Sans 3 outlines of "Tim" fit both faces (and Noto Sans Hebrew) three times each: T and m took Source Sans 3 and i took Noto Sans CJK SC, so T and m were left as lone outlines. A tie now goes to the face with the least leftover distance summed over the shapes that fit it, so every glyph that fits that face takes it. --- crates/engine/src/cmd/retype.rs | 46 +++++++++++++++++++++++---------- 1 file changed, 32 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index b464696542..0885ce4ddd 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -1578,21 +1578,40 @@ fn retype(s: &mut Session, p: &Value) -> Result { }) .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![]; + // the glyphs around it. Among faces that as many shapes match, the one whose glyphs fit + // them closest in all (the least leftover distance summed over those shapes), so every + // part that fits it takes the same face, exact matches as near ones. Simplified outlines + // of one font can nearly fit another font's look-alike glyphs, some of them more closely. + // A part's matches are all exact or all near, so the distances a face sums compare alike. + let mut votes: Vec<(u32, usize, f64)> = vec![]; for ms in found.iter().flatten() { - // Each shape votes once for each face it fits. - let mut faces: Vec = ms.iter().map(|m| m.face.id()).collect(); - faces.sort_unstable(); - faces.dedup(); - for f in faces { - match votes.iter_mut().find(|(v, _)| *v == f) { - Some(v) => v.1 += 1, - None => votes.push((f, 1)), + // Each shape votes once for each face it fits, with the leftover distance of its + // closest glyph in that face. + let mut faces: Vec<(u32, f64)> = vec![]; + for m in ms { + let residual = if m.residual.is_finite() { m.residual } else { f64::INFINITY }; + match faces.iter_mut().find(|(f, _)| *f == m.face.id()) { + Some(f) => f.1 = f.1.min(residual), + None => faces.push((m.face.id(), residual)), + } + } + for (f, residual) in faces { + match votes.iter_mut().find(|(v, ..)| *v == f) { + Some(v) => { + v.1 += 1; + v.2 += residual; + } + None => votes.push((f, 1, residual)), } } } - let rank = |face: u32| votes.iter().find(|(f, _)| *f == face).map_or(0, |v| v.1); + let rank = |face: u32| votes.iter().find(|(f, ..)| *f == face).map_or((0, f64::INFINITY), |v| (v.1, v.2)); + // Most votes, then the least summed distance, then the first (the matches come upright and + // closest first). + let ranked = |(i, a): &(usize, &GlyphMatch), (j, b): &(usize, &GlyphMatch)| { + let ((va, da), (vb, db)) = (rank(a.face.id()), rank(b.face.id())); + va.cmp(&vb).then(db.total_cmp(&da)).then(j.cmp(i)) + }; let mut lines: Vec = vec![]; let mut unmatched = vec![]; // An unmatched shape between glyphs ends the line: the type after it is painted after it. @@ -1610,9 +1629,8 @@ fn retype(s: &mut Session, p: &Value) -> Result { } glyphs_of.insert(pc.id, parts.len()); for ms in parts { - // The part's candidates in the face most shapes fit (the first such face, as the - // matches come upright and closest first). - let face = ms.iter().enumerate().max_by_key(|(i, m)| (rank(m.face.id()), std::cmp::Reverse(*i))).map(|(_, m)| m.face.id()); + // The part's candidates in the face most shapes fit (see `ranked`). + let face = ms.iter().enumerate().max_by(ranked).map(|(_, m)| m.face.id()); let cands: Vec = ms.iter().filter(|m| Some(m.face.id()) == face).cloned().collect(); let joined = match lines.last_mut() { Some(l) if open => join(l, pc, &cands), From f9c00a5ae5e6dabe6da128b16815f7cd84df0968 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 06:26:51 -0800 Subject: [PATCH 19/38] Live Paint: graphic styles on a group's contents give fills to its faces and strokes to its edges Follows #8765. graphicStyle.apply with target "contents" gave every face and edge of a Live Paint group the whole style, so faces drew the style's strokes along their outlines and edges drew its fills. Each face now takes only the style's fills and each edge only its strokes, with or without add, and neither is linked to the style. An add that gives a face or edge nothing leaves it and its link as they are, and an apply that changes nothing records no undo step. appearance.clear on the contents leaves a face one empty fill and an edge one empty stroke, and appearance.reduceToBasic keeps only a face's fill and only an edge's stroke. Docs: docs/mcp.md, params text, docs/target-app-parity.md. --- crates/engine/src/cmd/appearance.rs | 32 ++++++++++- crates/engine/src/cmd/style.rs | 23 ++++++-- crates/engine/src/tests/build.rs | 87 +++++++++++++++++++++++++++++ docs/mcp.md | 8 ++- docs/target-app-parity.md | 2 +- 5 files changed, 143 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 3b23d62634..037983da5c 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -67,7 +67,7 @@ pub fn specs() -> Vec { "Clear Appearance", ["Window", "Appearance"], None, - "{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind", + "{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own; in the contents of a Live Paint group, a face one empty fill and an edge one empty stroke) and reset its opacity and blend mode. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind", has_doc, clear_appearance ), @@ -76,7 +76,7 @@ pub fn specs() -> Vec { "Reduce to Basic Appearance", ["Window", "Appearance"], None, - "{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes)", + "{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked; in the contents of a Live Paint group, a face keeps only the fill and an edge only the stroke), and drop the object's effects. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes)", has_doc, reduce_basic ), @@ -529,6 +529,24 @@ pub(crate) fn contents_skipped(s: &Session, p: &Value, fill: bool) -> Result Result<(HashSet, HashSet)> { + if !targets_contents(p)? { + return Ok((HashSet::new(), HashSet::new())); + } + let (faces, edges, _) = super::paint::live_paint_split(&s.doc()?.doc, &appearance_roots(s, p)?); + Ok((faces, edges)) +} + +/// Remove from `n` its stroke rows (`fill`) or its fill rows: a Live Paint face draws fills and an edge strokes. +pub(crate) fn keep_rows_of_kind(n: &mut Node, fill: bool) { + if n.appearance.items.iter().any(|it| it.is_fill() != fill) { + n.appearance.items.retain(|it| it.is_fill() == fill); + } +} + /// The refusal of an appearance edit whose targets are all the art of graph designs drawn in graph series. const DESIGN_ART: &str = "the art of a graph design in a graph series is drawn again from the design: edit the design to change it"; @@ -1044,12 +1062,17 @@ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result { fn clear_appearance(s: &mut Session, p: &Value) -> Result { let ids = require_whole_targets(s, p, "appearance.clear")?; + let (faces, edges) = contents_parts(s, p)?; // When every object is cleared already, the document and its undo history stay as they are. let before = s.doc()?.doc.clone(); super::overprint::edit_counted(s, "Clear Appearance", |d| { for id in &ids { if let Some(n) = d.node_mut(*id) { clear(n); + // A Live Paint group's face keeps an empty fill and its edge an empty stroke. + if faces.contains(id) || edges.contains(id) { + keep_rows_of_kind(n, faces.contains(id)); + } super::object::snap_if_aligned(n); } } @@ -1284,6 +1307,7 @@ fn is_group(n: &Node) -> bool { fn reduce_basic(s: &mut Session, p: &Value) -> Result { let ids = require_whole_targets(s, p, "appearance.reduceToBasic")?; + let (faces, edges) = contents_parts(s, p)?; // When every object comes out as it was, the document and its undo history stay as they are. let before = s.doc()?.doc.clone(); // The Appearance panel's active row (a row of the first selected object's stack, and in each @@ -1322,6 +1346,10 @@ fn reduce_basic(s: &mut Session, p: &Value) -> Result { st.blend = BlendMode::Normal; n.appearance.items.push(AppearanceItem::Stroke(st)); } + // A Live Paint group's face keeps only its fill and its edge only its stroke. + if faces.contains(id) || edges.contains(id) { + keep_rows_of_kind(n, faces.contains(id)); + } super::object::snap_if_aligned(n); } } diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs index 1b5fec0a3b..14c6957e23 100644 --- a/crates/engine/src/cmd/style.rs +++ b/crates/engine/src/cmd/style.rs @@ -31,7 +31,7 @@ pub fn specs() -> Vec { "Apply Graphic Style", ["Window", "Graphic Styles"], None, - "{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows (with `add`: of the kinds of row the style shows) and, without `add`, its object opacity and blend mode for every label or line of its kind. With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}", + "{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. In the contents of a Live Paint group, each face takes only the style's fills and each edge only its strokes, and neither is linked. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows (with `add`: of the kinds of row the style shows) and, without `add`, its object opacity and blend mode for every label or line of its kind. With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}", has_doc, style_apply ), @@ -351,6 +351,9 @@ fn style_apply(s: &mut Session, p: &Value) -> Result { // The series groups their paths stand for: a style that replaces the appearance clears what they hold themselves, // and a style added on top unlinks them. let groups = super::appearance::stood_for(&own, &ids); + // In the contents of a Live Paint group, a face takes the style's fills and an edge its strokes. + let (faces, edges) = super::appearance::contents_parts(s, p)?; + let part = |id: &NodeId| (faces.contains(id) || edges.contains(id)).then(|| faces.contains(id)); if ids.is_empty() { if p.get("ids").is_some() || p.get("id").is_some() { return Err(bad("graphicStyle.apply", "no such objects")); @@ -361,13 +364,20 @@ fn style_apply(s: &mut Session, p: &Value) -> Result { return Ok(json!({ "newArt": true })); } let before = s.doc()?.doc.clone(); - s.edit("Apply Graphic Style", |d, _| { + // An apply that changes nothing (a fill-only style added to edges only) records no undo step. + super::overprint::edit_counted(s, "Apply Graphic Style", |d| { if add { let g = d.graphic_styles[i].clone(); for id in &ids { if let Some(n) = d.node_mut(*id) { let ap = g.appearance_on(n).into_owned(); - n.appearance.items.extend(ap.items); + let kind = part(id); + let rows: Vec<_> = ap.items.into_iter().filter(|it| kind.is_none_or(|fill| it.is_fill() == fill)).collect(); + // A face or edge the style adds nothing to keeps its appearance and its link. + if kind.is_some() && rows.is_empty() && ap.effects.is_empty() { + continue; + } + n.appearance.items.extend(rows); n.appearance.effects.extend(ap.effects); n.extras_mut().graphic_style = None; } @@ -387,13 +397,18 @@ fn style_apply(s: &mut Session, p: &Value) -> Result { let mut shared = None; for id in &ids { apply_style(d, *id, &g, &mut shared, chars); + // A face or edge that keeps only the rows of its kind no longer has the style's look, so it is not linked. + if let (Some(fill), Some(n)) = (part(id), d.node_mut(*id)) { + super::appearance::keep_rows_of_kind(n, fill); + n.extras_mut().graphic_style = None; + } } super::appearance::clear_stood_for(d, &groups); super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false, true); // A label or graph line keeps its new rows for its kind. super::graph::capture_label_rows(d, &ids); } - Ok(()) + Ok(usize::from(*d != *before)) })?; ok() } diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 316e9b8ffc..b37550d5c5 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -4630,6 +4630,93 @@ fn live_paint_group_with_only_source_paths_ignores_add_fill_and_add_stroke_of_it assert!(s.execute("appearance.addFill", &json!({"target": "contents"})).is_err(), "no selection is still refused"); } +/// Whether every face of Live Paint group `g` holds only fill rows and every edge only stroke rows. +fn parts_hold_their_kind(s: &Session, g: NodeId) -> bool { + let (faces, edges) = part_looks(s, g); + faces.iter().all(|a| a.items.iter().all(|it| it.is_fill())) && edges.iter().all(|a| a.items.iter().all(|it| !it.is_fill())) +} + +/// A graphic style applied to the contents of a Live Paint group, replacing their appearance or added to it, gives +/// the faces its fills and the edges its strokes, and the faces and edges are not linked to it. +#[test] +fn live_paint_group_contents_take_a_graphic_style_by_kind() { + let red = Paint::solid(Color::from_hex("#ff0000").unwrap()); + let blue = Paint::solid(Color::from_hex("#0000ff").unwrap()); + for add in [false, true] { + let mut s = session(); + let g = live(&mut s); + let r = rect(&mut s, 400.0, 0.0, 50.0, 50.0); + s.execute("select.set", &json!({"ids": [r.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap(); + s.execute("graphicStyle.new", &json!({"name": "Both", "id": r.0})).unwrap(); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.execute("graphicStyle.apply", &json!({"name": "Both", "target": "contents", "add": add})).unwrap(); + assert!(parts_hold_their_kind(&s, g), "add {add}: faces hold fills and edges strokes"); + let (faces, edges) = part_looks(&s, g); + assert!(faces.iter().all(|a| a.items.iter().any(|it| *it.paint() == red)), "add {add}: each face takes the style's fill"); + assert!(edges.iter().all(|a| a.items.iter().any(|it| *it.paint() == blue)), "add {add}: each edge takes the style's stroke"); + let n = node(&s, g); + let mut parts = vectorcraft_tools::builder::faces(&n).into_iter().chain(vectorcraft_tools::builder::edges(&n)); + assert!(parts.all(|p| p.extras().graphic_style.is_none()), "add {add}: no face or edge is linked"); + } +} + +/// A fill-only graphic style added to the contents of a Live Paint group without faces changes nothing and records no +/// undo step. +#[test] +fn live_paint_group_contents_without_faces_take_no_fill_only_style() { + let mut s = session(); + let g = live(&mut s); + let faces: Vec = vectorcraft_tools::builder::faces(&node(&s, g)).iter().map(|p| p.id).collect(); + s.edit("t", |d, _| { + d.children_mut(Some(g)).unwrap().retain(|c| !faces.contains(&c.id)); + Ok(()) + }) + .unwrap(); + let r = rect(&mut s, 400.0, 0.0, 50.0, 50.0); + s.edit("t", |d, _| { + let fill = AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::from_hex("#ff0000").unwrap()))); + d.node_mut(r).unwrap().appearance = vectorcraft_doc::Appearance { items: vec![fill], ..Default::default() }.into(); + Ok(()) + }) + .unwrap(); + s.execute("graphicStyle.new", &json!({"name": "Fill", "id": r.0})).unwrap(); + // The edges are linked to a style of their own, which they keep. + let edge = vectorcraft_tools::builder::edges(&node(&s, g))[0].id; + s.execute("graphicStyle.new", &json!({"name": "Edge", "id": edge.0})).unwrap(); + assert!(node(&s, g).children().unwrap().iter().any(|c| c.extras().graphic_style.is_some()), "an edge is linked"); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + let (before, undo) = (node(&s, g), s.doc().unwrap().history.undo.len()); + s.execute("graphicStyle.apply", &json!({"name": "Fill", "target": "contents", "add": true})).unwrap(); + assert_eq!(node(&s, g), before, "the edges keep their rows and their link"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step"); +} + +/// Clear Appearance and Reduce to Basic Appearance on the contents of a Live Paint group leave each face with fill +/// rows only and each edge with stroke rows only. +#[test] +fn live_paint_group_contents_clear_and_reduce_keep_each_part_to_its_kind() { + for cmd in ["appearance.clear", "appearance.reduceToBasic"] { + let mut s = session(); + let g = live(&mut s); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff00ff"})).unwrap(); + s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap(); + // A face and an edge given rows of the other kind through their own ids. + let n = node(&s, g); + let (face, edge) = (vectorcraft_tools::builder::faces(&n)[0].id, vectorcraft_tools::builder::edges(&n)[0].id); + s.execute("appearance.addStroke", &json!({"ids": [face.0]})).unwrap(); + s.execute("appearance.addFill", &json!({"ids": [edge.0]})).unwrap(); + assert!(!parts_hold_their_kind(&s, g), "{cmd}: the face and the edge hold rows of the other kind"); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.execute(cmd, &json!({"target": "contents"})).unwrap(); + assert!(parts_hold_their_kind(&s, g), "{cmd}: faces hold fills and edges strokes"); + let (faces, edges) = part_looks(&s, g); + assert!(faces.iter().chain(&edges).all(|a| !a.items.is_empty()), "{cmd}: each face and edge keeps a row"); + } +} + /// A selected Live Paint group with no part of the edited kind is still a selection: a stroke edit /// of a group without edges, or a fill gradient edit of a group without faces, changes nothing and /// leaves the settings for new art as they are. diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..2b70c411c3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5702,11 +5702,15 @@ fills and strokes above it paint over the members (characters), those below unde `appearance.contents_index`. The `appearance.*`, `effect.*` and `graphicStyle.apply` commands edit the selected objects themselves (a group's own stack; layers through `ids`) or, with `target: "contents"`, the objects inside the groups and layers. In a Live Paint group those are its faces and edges, not its hidden source paths. -`appearance.addFill` adds a fill to the faces only, and `appearance.addStroke` adds a stroke to the edges only; a selected group left with only its hidden source paths is returned without a change. A +`appearance.addFill` adds a fill to the faces only, and `appearance.addStroke` adds a stroke to the edges only. On a +selected group left with only its hidden source paths, either command changes nothing. A fill or stroke command with an `item` and `target: "contents"` (such as `paint.setFill`, `stroke.set`, `paint.invert`, `paint.setGradientGeom` and `object.setOverprint`) changes the faces for a fill row and the edges for a stroke row. The row commands (`appearance.setItem`, `appearance.removeItem` and the others) find their rows on each -face and edge as on any other object in the contents. +face and edge as on any other object in the contents. `graphicStyle.apply` gives each face only the style's fills and +each edge only its strokes, with or without `add`, and links neither to the style. `appearance.clear` leaves a face +one empty fill and an edge one empty stroke, and `appearance.reduceToBasic` keeps only a face's fill and only an +edge's stroke. `appearance.targetContents` selects a group's members (double-clicking the Contents row). SVG and PDF export bake a group's own fills, strokes and geometry effects into paths; its raster effects stay a filter on the whole group in SVG and become an image of the whole group in PDF. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b1d981428a..7a211b564a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1935,7 +1935,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur As VectorCraft's own rule, OK in Live Paint Selection Tool Options, Live Paint Bucket Options, Gap Options and Tile Edge Color gives an error for a color with an alpha part (`#rrggbbaa` or `#rgba`) and changes nothing. As VectorCraft's own rule, a Live Paint edit that changes nothing records no undo step, keeps the redo steps and leaves a saved document saved: a Live Paint Bucket click or drag over faces that already have the fill, a stroke on an edge that already has the paint and weight, Gap Options OK with the options the groups have and no gap to close, and Make or Merge with one Live Paint group alone. Such a fill or stroke also leaves the recent colors as they are. Regression tests: `live_paint_fill_same_paint_is_no_op`, `live_paint_bucket_click_with_the_face_paint_is_no_op`, `live_paint_stroke_edge_same_paint_and_width_is_no_op`, `live_paint_gap_options_same_values_are_no_op`, `live_paint_gap_options_close_without_gaps_is_no_op`, `live_paint_make_existing_group_is_no_op` and `live_paint_merge_single_group_is_no_op` in `crates/engine/src/tests/build.rs`, and `ok_on_unchanged_options_records_no_undo_step` in `crates/ui-egui/src/dialogs/live_paint_gaps.rs`. As VectorCraft's own rule, the Live Paint Bucket replaces all of a face's fills, or all of an edge's strokes, with one fill or stroke of the paint, shown, fully opaque and blending normally, so a lower fill or stroke no longer draws under the new paint and a fill or stroke of none leaves nothing of that kind drawing; the face's strokes, the edge's fills, the part's own opacity and the topmost shown stroke's dashes, caps and arrowheads stay as they are, and a part that already has only that one fill or stroke records no undo step. [The help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html) says the tool paints faces with the current fill and edges with the current stroke. Regression tests: `live_paint_bucket_replaces_every_fill_row`, `live_paint_stroke_edge_replaces_every_stroke_row` and `live_paint_stroke_edge_paints_the_shown_stroke` in `crates/engine/src/tests/build.rs`. - As VectorCraft's own rule, with a tool other than the Live Paint Bucket, a fill given to a whole selected Live Paint group paints its faces only and a stroke paints its edges only, and the hidden source paths keep their paint. Swap Fill and Stroke trades the fill the faces share with the stroke the edges share, and Default Fill and Stroke leaves the faces with no fill and gives the edges a 0.5 pt black stroke (`docs/mcp.md`). The Eyedropper gives the picked fill attributes to the faces and the picked stroke attributes to the edges, and picks up a whole group as its first face's fills with its first edge's strokes. Overprint Fill goes to the faces and Overprint Stroke goes to the edges. The proxies show the same paint whatever the order of a selection that holds the group and one of its parts. Appearance panel edits of the group's contents leave the hidden source paths as they are, a new fill goes on the faces, and a new stroke goes on the edges. Evidence: `tests::build::{live_paint_group_fill_goes_to_faces_and_stroke_to_edges, live_paint_group_swap_trades_the_faces_fill_and_the_edges_stroke, live_paint_group_default_clears_the_faces_and_gives_the_edges_a_thin_black_stroke, live_paint_group_invert_recolors_the_faces_fill, live_paint_group_gradient_vector_and_freeform_edits_change_its_faces, live_paint_group_stroke_panel_edits_change_its_edges, live_paint_group_rules_stop_where_paint_commands_stop, live_paint_group_without_parts_of_the_edited_kind_leaves_new_art_alone, live_paint_group_proxies_do_not_depend_on_the_selection_order, live_paint_group_eyedropper_gives_the_fill_to_faces_and_the_stroke_to_edges, live_paint_group_eyedropper_gives_every_fill_and_stroke_row, live_paint_group_contents_edits_follow_the_group_rule, live_paint_group_item_edits_and_overprint_follow_the_group_rule, live_paint_group_inside_a_selected_group_keeps_the_proxies_independent_of_order, live_paint_group_eyedropper_picks_up_the_group_and_appends_without_effects}`. + As VectorCraft's own rule, with a tool other than the Live Paint Bucket, a fill given to a whole selected Live Paint group paints its faces only and a stroke paints its edges only, and the hidden source paths keep their paint. Swap Fill and Stroke trades the fill the faces share with the stroke the edges share, and Default Fill and Stroke leaves the faces with no fill and gives the edges a 0.5 pt black stroke (`docs/mcp.md`). The Eyedropper gives the picked fill attributes to the faces and the picked stroke attributes to the edges, and picks up a whole group as its first face's fills with its first edge's strokes. Overprint Fill goes to the faces and Overprint Stroke goes to the edges. The proxies show the same paint whatever the order of a selection that holds the group and one of its parts. Appearance panel edits of the group's contents leave the hidden source paths as they are, a new fill goes on the faces, and a new stroke goes on the edges; a graphic style gives the faces only its fills and the edges only its strokes, and Clear Appearance and Reduce to Basic Appearance leave the faces only fill rows and the edges only stroke rows. Evidence: `tests::build::{live_paint_group_fill_goes_to_faces_and_stroke_to_edges, live_paint_group_swap_trades_the_faces_fill_and_the_edges_stroke, live_paint_group_default_clears_the_faces_and_gives_the_edges_a_thin_black_stroke, live_paint_group_invert_recolors_the_faces_fill, live_paint_group_gradient_vector_and_freeform_edits_change_its_faces, live_paint_group_stroke_panel_edits_change_its_edges, live_paint_group_rules_stop_where_paint_commands_stop, live_paint_group_without_parts_of_the_edited_kind_leaves_new_art_alone, live_paint_group_proxies_do_not_depend_on_the_selection_order, live_paint_group_eyedropper_gives_the_fill_to_faces_and_the_stroke_to_edges, live_paint_group_eyedropper_gives_every_fill_and_stroke_row, live_paint_group_contents_edits_follow_the_group_rule, live_paint_group_item_edits_and_overprint_follow_the_group_rule, live_paint_group_inside_a_selected_group_keeps_the_proxies_independent_of_order, live_paint_group_eyedropper_picks_up_the_group_and_appends_without_effects, live_paint_group_eyedropper_reversed_skips_an_empty_group_for_the_next_whole_group, live_paint_group_eyedropper_does_not_target_its_own_source_group, live_paint_group_with_only_source_paths_leaves_new_art_alone_for_a_contents_edit, live_paint_group_with_only_source_paths_ignores_add_fill_and_add_stroke_of_its_contents, live_paint_group_contents_take_a_graphic_style_by_kind, live_paint_group_contents_without_faces_take_no_fill_only_style, live_paint_group_contents_clear_and_reduce_keep_each_part_to_its_kind}`. As VectorCraft's own rule, `tool.setOption` for the Live Paint Bucket and the Live Paint Selection tool, chosen or not, checks every value before it sets any: a switch that is not `true` or `false`, a `color` that is not an RGB color or a layer color's name, or that has an alpha part, a `width` that is not a number and an option the tool does not have give an error naming the option, and nothing is set or saved. A `width` outside 1 to 20 px is still set to the nearest end of that range. Saved settings that hold an invalid value still load, and the tool keeps its default for that option. Evidence: `tests::build::{live_paint_tool_options_refuse_invalid_values_and_change_nothing, live_paint_tool_options_take_rgb_colors_and_clamp_the_width, live_paint_tools_load_saved_settings_with_invalid_values}`. As VectorCraft's own rule, `tool.setOption` for the Shape Builder, chosen or not, checks every value the same way: a switch that is not `true` or `false`, a `pickColorFrom` or `selection` that is not one of its names, a `gapLength` that is not a number, a `highlightColor` that is not an RGB color or a layer color's name, or that has an alpha part, and an option the tool does not have give an error naming the option, and nothing is set or saved. A `gapLength` outside 0 to 72 pt is still set to the nearest end of that range. Evidence: `tests::build::{shape_builder_tool_options_refuse_invalid_values_and_change_nothing, shape_builder_tool_options_take_valid_values_and_clamp_the_gap}`. A drag of 3 screen pixels or more with the Live Paint Selection tool draws a marquee and selects the faces and edges it touches, partly enclosed ones included, and a Shift-drag adds them to the selection or removes them from it ([Modify Live Paint groups](https://web.archive.org/web/20261006115247/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/modify-live-paint-groups.html)). A click and a marquee change the selection on release, and Escape before the release leaves the selection as it was. Locked Live Paint groups, those on a locked layer or artboard, and in isolation mode those outside the isolated art are not highlighted or selected. From 4df75635da84c5dc3979b4b4212f1e7ce7a308bd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 14:14:26 -0800 Subject: [PATCH 20/38] Tests: a confined single-file PDF of several artboards checks every artboard it carries A single-file PDF with Preserve Editing of an artboard range carries the whole document, so a confined export of it checks the links on every chosen artboard. The new test exports artboards 1-2 as one PDF, then places an image linked outside the read roots on the second artboard only and checks that the export is refused without writing its folder. It also checks that assets.export refuses pdfs `single`, the source that pdfs `single` does not accept. --- crates/engine/src/tests/links.rs | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/crates/engine/src/tests/links.rs b/crates/engine/src/tests/links.rs index 5dd3357641..268fa79ad0 100644 --- a/crates/engine/src/tests/links.rs +++ b/crates/engine/src/tests/links.rs @@ -2617,6 +2617,37 @@ fn confined_screens_rows_check_the_artboard_each_file_holds() { } } +/// A confined caller's single-file PDF with Preserve Editing of several artboards carries the art +/// of every artboard on its pages: an image linked outside the read roots on the second artboard +/// alone refuses it. A single-file PDF of assets is refused before any link is checked. +#[test] +fn confined_single_file_pdf_checks_every_artboard_it_carries() { + use crate::file_access::{AutomationRoots, confine}; + + let away = Folder::new("single-pdf-away"); + let home = Folder::new("single-pdf-home"); + let photo = away.file("photo.png"); + write(&photo, &png(60, 30, RED)); + let mut s = session(); + let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); + let rect: vectorcraft_doc::NodeId = serde_json::from_value(r["id"].clone()).unwrap(); + s.execute("artboard.new", &json!({"x": 2000, "y": 0, "width": 200, "height": 200})).unwrap(); + let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap(); + let p = |folder: &str| json!({"range": "1-2", "folder": home.file(folder), "pdfs": "single", "formats": [{"format": "pdf", "preserveEditing": true}]}); + let r = confine(roots.as_ref(), || s.execute("document.exportForScreens", &p("plain"))).unwrap_or_else(|e| panic!("{e}")); + assert_eq!(r["files"].as_array().map(Vec::len), Some(1), "{r}"); + let r = s.execute("file.place", &json!({"path": photo, "at": [2100, 100]})).unwrap(); + assert_eq!(r["linked"], true, "{r}"); + let e = confine(roots.as_ref(), || s.execute("document.exportForScreens", &p("linked"))).expect_err("second artboard links outside").to_string(); + assert!(e.contains("a linked image file is outside the read roots"), "{e}"); + assert!(!Path::new(&home.file("linked")).exists(), "the refused export writes no folder"); + let asset = s.execute("assets.add", &json!({"ids": [rect.0]})).unwrap()["assets"][0].as_u64().unwrap(); + let assets = json!({"assets": [asset], "folder": home.file("assets"), "pdfs": "single", "formats": [{"format": "pdf", "preserveEditing": true}]}); + let e = confine(roots.as_ref(), || s.execute("assets.export", &assets)).expect_err("single-file PDF of assets").to_string(); + assert!(e.contains("pdfs `single` writes artboards as the pages of one PDF"), "{e}"); + assert!(!Path::new(&home.file("assets")).exists(), "the refused export writes no folder"); +} + /// A confined caller's native outputs (a native file or template, an EPS or `.ai` file, a PDF with /// Preserve Editing, a package's document) carry the document without the Export for Screens /// folder when it is outside the read roots, with the other export settings and the art; the open From 3023335b59b2f2e96afb12e27d80cb4fc8290c2f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 14:09:24 -0800 Subject: [PATCH 21/38] Mesh: picked points stay picked between the mesh-point tools Gradient mesh points picked with the Mesh tool, Direct Selection, the Lasso or the Polygonal Lasso now stay picked when another of these tools is chosen, and when one of them lends Direct Selection for a Cmd/Ctrl click, so a fill color chosen afterwards recolors just those points. Before, only a switch to or from the Eyedropper kept them. Any other tool, Group Selection included, drops them. Session::switch_tool, lend_selection_tool and give_back_tool share one test of which tools pick mesh points. Giving the tool back leaves the lender's picks alone when they did not change, so the Mesh tool keeps the point whose handles it shows. Tests: crates/engine/src/tests/mesh_picks.rs. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/tests.rs | 1 + crates/engine/src/tests/mesh_picks.rs | 107 +++++++++++++++++++++ crates/engine/src/tooling.rs | 36 ++++--- crates/tools/src/addons/polygonal_lasso.rs | 2 +- crates/tools/src/direct.rs | 2 +- crates/tools/src/meshblend.rs | 2 +- crates/tools/src/meshedit.rs | 2 +- crates/tools/src/xform/wand.rs | 2 +- docs/mcp.md | 6 +- docs/target-app-parity.md | 1 + 10 files changed, 142 insertions(+), 19 deletions(-) create mode 100644 crates/engine/src/tests/mesh_picks.rs diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index c39c88cbbb..d92bcb7d71 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -112,6 +112,7 @@ mod live; mod livecorners; mod maskview; pub(super) mod menucmds; +mod mesh_picks; mod nativefile; mod newart; mod newdoc; diff --git a/crates/engine/src/tests/mesh_picks.rs b/crates/engine/src/tests/mesh_picks.rs new file mode 100644 index 0000000000..0159709fdb --- /dev/null +++ b/crates/engine/src/tests/mesh_picks.rs @@ -0,0 +1,107 @@ +//! Gradient mesh points picked with one of the tools that pick them (the Mesh tool, Direct +//! Selection, the Lasso, the Polygonal Lasso) stay picked when another of them is chosen, or lent +//! for a Cmd-click, so a fill color then recolors just them. + +use serde_json::json; +use vectorcraft_color::Color; +use vectorcraft_doc::NodeKind; +use vectorcraft_tools::{Mods, PointerEvent, PointerKind}; + +use crate::*; + +/// A session with a selected 1 x 1 gradient mesh (four white points) at (10, 10), 50 pt square. +fn mesh_session() -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + let m = NodeId(s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.mesh.create", &json!({"ids": [m.0], "rows": 1, "cols": 1})).unwrap(); + s.execute("select.set", &json!({"ids": [m.0]})).unwrap(); + (s, m) +} + +fn colors(s: &Session, m: NodeId) -> Vec { + match &s.doc().unwrap().doc.node(m).unwrap().kind { + NodeKind::Mesh(g) => g.points.iter().map(|p| p.color).collect(), + k => panic!("not a mesh: {k:?}"), + } +} + +/// Click mesh point `i` of `m` with the active tool. +fn press(s: &mut Session, m: NodeId, i: usize, mods: Mods) { + let q = match &s.doc().unwrap().doc.node(m).unwrap().kind { + NodeKind::Mesh(g) => g.points[i].p, + k => panic!("not a mesh: {k:?}"), + }; + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, q.x, q.y).with_mods(mods), ViewInfo::default()).unwrap(); + } +} + +/// A point picked with the Mesh tool stays picked through Direct Selection, the Lasso and the +/// Polygonal Lasso and back to the Mesh tool: each fill color recolors just that point. +#[test] +fn mesh_point_picks_carry_between_the_mesh_point_tools() { + let (mut s, m) = mesh_session(); + let v = ViewInfo::default(); + let white = colors(&s, m)[0]; + s.select_tool("mesh", v).unwrap(); + press(&mut s, m, 0, Mods::default()); + for (tool, hex, c) in [ + ("directSelection", "#0000ff", Color::rgb8(0, 0, 255)), + ("lasso", "#00ff00", Color::rgb8(0, 255, 0)), + ("polygonalLasso", "#ff0000", Color::rgb8(255, 0, 0)), + ("directSelection", "#ffff00", Color::rgb8(255, 255, 0)), + ("mesh", "#00ffff", Color::rgb8(0, 255, 255)), + ] { + s.select_tool(tool, v).unwrap(); + s.execute("paint.setFill", &json!({"color": hex})).unwrap(); + assert_eq!(colors(&s, m), [c, white, white, white], "{tool} recolors only the picked point"); + } +} + +/// A point picked with Direct Selection stays picked for the Mesh tool. +#[test] +fn direct_selection_picks_carry_to_the_mesh_tool() { + let (mut s, m) = mesh_session(); + let v = ViewInfo::default(); + let white = colors(&s, m)[0]; + s.select_tool("directSelection", v).unwrap(); + press(&mut s, m, 2, Mods::default()); + s.select_tool("mesh", v).unwrap(); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + assert_eq!(colors(&s, m), [white, white, Color::rgb8(0, 0, 255), white]); +} + +/// The Selection tool picks no mesh points: after it, the Mesh tool starts with none picked, and a +/// fill color leaves every point as it was. +#[test] +fn a_tool_that_picks_no_mesh_points_drops_the_picks() { + let (mut s, m) = mesh_session(); + let v = ViewInfo::default(); + let before = colors(&s, m); + s.select_tool("mesh", v).unwrap(); + press(&mut s, m, 0, Mods::default()); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [m.0]})).unwrap(); + s.select_tool("mesh", v).unwrap(); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + assert_eq!(colors(&s, m), before, "no point is picked"); +} + +/// Direct Selection lent to the Mesh tool for a Cmd-click starts from the Mesh tool's picks, so a +/// Shift-click adds to them, and gives back what it left picked. +#[test] +fn the_lent_direct_selection_carries_the_mesh_tools_picks() { + let (mut s, m) = mesh_session(); + let v = ViewInfo::default(); + let white = colors(&s, m)[0]; + // Cmd lends the selection tool chosen last. + s.select_tool("directSelection", v).unwrap(); + s.select_tool("mesh", v).unwrap(); + press(&mut s, m, 0, Mods::default()); + press(&mut s, m, 3, Mods { cmd: true, shift: true, ..Default::default() }); + assert_eq!(s.tool_id(), "mesh"); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + let b = Color::rgb8(0, 0, 255); + assert_eq!(colors(&s, m), [b, white, white, b], "both points stay picked"); +} diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 7b1caffb7c..7c1af811ed 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -186,12 +186,13 @@ impl Session { let text_selection = ((id == "eyedropper" && is_type(self.tool.id())) || (self.tool.id() == "eyedropper" && is_type(id))) .then(|| self.tool.options()) .filter(|o| o.get("editing").is_some_and(|v| !v.is_null()) && o.get("start") != o.get("end")); - // The gradient mesh points the Mesh tool, Direct Selection or the Lasso picked stay picked - // for the Eyedropper, which samples into them (#8090), and for the tool after it. - let mesh_points = (id == "eyedropper" || self.tool.id() == "eyedropper") + // The gradient mesh points the Mesh tool, Direct Selection, the Lasso or the Polygonal Lasso + // picked stay picked when another of these tools or the Eyedropper, which samples into + // them (#8090), is chosen: a fill color then recolors just them. None stay picked when + // none were. + let mesh_points = (Self::picks_mesh_points(id) && Self::picks_mesh_points(self.tool.id())) .then(|| self.tool.options().get("meshPoints").cloned()) - .flatten() - .filter(|v| v.as_array().is_some_and(|a| !a.is_empty())); + .flatten(); self.deactivate_tool(view)?; self.keep_tool_settings(); self.tool = self.make_tool(id); @@ -208,6 +209,13 @@ impl Session { Ok(()) } + /// Does tool `id` pick gradient mesh points (its `meshPoints` option): the Mesh tool, Direct + /// Selection, the Lasso, the Polygonal Lasso and the Eyedropper? Group Selection, which + /// selects whole objects, does not. + fn picks_mesh_points(id: &str) -> bool { + matches!(id, "mesh" | "directSelection" | "lasso" | "polygonalLasso" | "eyedropper") + } + /// Deactivate the tool and apply the actions it returns. In a batch, a Cancel is left out: the /// batch settled the tool's drag when it began, and the open interaction holds the batch's /// steps, which the batch keeps or rolls back as a whole. @@ -292,9 +300,9 @@ impl Session { // double-click or triple-click compares. self.tool.press_elsewhere(); let mut lent = self.make_tool(id); - // The gradient mesh points the Eyedropper holds are the lent tool's picks, which a Shift - // click adds to (#8090). - if self.tool.id() == "eyedropper" { + // The gradient mesh points the lending tool picked (the Mesh tool's, the Lasso's, the + // Eyedropper's) are the lent tool's picks, which a Shift click adds to (#8090). + if Self::picks_mesh_points(self.tool.id()) && Self::picks_mesh_points(id) { let points = self.tool.options().get("meshPoints").cloned().unwrap_or_else(|| Value::Array(vec![])); lent.set_option("meshPoints", &points); } @@ -312,10 +320,14 @@ impl Session { /// Cmd+click that takes the type being edited out of the selection ends its edit (#3779). pub(crate) fn give_back_tool(&mut self, view: ViewInfo) -> Result<()> { let Some(lender) = self.lender.take() else { return Ok(()) }; - // The points the lent tool left picked go back to the Eyedropper, none when it unpicked - // them all (#8090). Group Selection picks no mesh points, so the Eyedropper keeps its own. - let mesh_points = - (lender.id() == "eyedropper" && self.tool.id() != "groupSelection").then(|| self.tool.options().get("meshPoints").cloned()).flatten(); + // The points the lent tool left picked go back to the tool it was lent to when that tool + // picks mesh points, none when it unpicked them all (#8090). Group Selection and the + // Selection tool pick no mesh points, so the tool keeps its own. Unchanged picks are not + // set again, so the Mesh tool keeps the point whose handles it shows. + let mesh_points = (Self::picks_mesh_points(lender.id()) && Self::picks_mesh_points(self.tool.id())) + .then(|| self.tool.options().get("meshPoints").cloned()) + .flatten() + .filter(|p| lender.options().get("meshPoints") != Some(p)); let r = self.deactivate_tool(view); self.keep_tool_settings(); self.tool = lender; diff --git a/crates/tools/src/addons/polygonal_lasso.rs b/crates/tools/src/addons/polygonal_lasso.rs index b212943117..2810b0b309 100644 --- a/crates/tools/src/addons/polygonal_lasso.rs +++ b/crates/tools/src/addons/polygonal_lasso.rs @@ -167,7 +167,7 @@ impl Tool for PolygonalLassoTool { self.mesh.options() } - /// Pick the gradient mesh points the Eyedropper held (`meshPoints`). + /// Pick the gradient mesh points the tool chosen before held (`meshPoints`). fn set_option(&mut self, key: &str, value: &serde_json::Value) { if key == "meshPoints" { self.mesh.set_options(value); diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index cd4432c3c8..c889671a6e 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -823,7 +823,7 @@ impl Tool for DirectSelectionTool { fn options(&self) -> Value { self.mesh.options() } - /// Direct Selection picks the gradient mesh points the Eyedropper held (`meshPoints`); Group + /// Direct Selection picks the gradient mesh points the tool chosen before held (`meshPoints`); Group /// Selection, which selects whole objects, does not. /// The session sets `lentByCmd` on the tool Cmd/Ctrl lends for one gesture /// ([`DirectSelectionTool::mirrors`]). diff --git a/crates/tools/src/meshblend.rs b/crates/tools/src/meshblend.rs index c9ab307028..89e640d48e 100644 --- a/crates/tools/src/meshblend.rs +++ b/crates/tools/src/meshblend.rs @@ -360,7 +360,7 @@ impl Tool for MeshTool { fn options(&self) -> serde_json::Value { self.edit.options() } - /// Pick the gradient mesh points the Eyedropper held (`meshPoints`). + /// Pick the gradient mesh points the tool chosen before held (`meshPoints`). fn set_option(&mut self, key: &str, value: &serde_json::Value) { if key == "meshPoints" { self.edit.set_options(value); diff --git a/crates/tools/src/meshedit.rs b/crates/tools/src/meshedit.rs index 71ae329c4c..2dbeaf07a7 100644 --- a/crates/tools/src/meshedit.rs +++ b/crates/tools/src/meshedit.rs @@ -325,7 +325,7 @@ impl MeshEdit { } /// Pick the points a `meshPoints` option lists (see [`points_of`]), with none focused: the - /// points the Eyedropper held when the tool switched back. + /// points the tool chosen before (another mesh-point tool or the Eyedropper) held. pub fn set_options(&mut self, value: &Value) { if self.drag.is_some() { return; diff --git a/crates/tools/src/xform/wand.rs b/crates/tools/src/xform/wand.rs index d2074e386e..991f43881c 100644 --- a/crates/tools/src/xform/wand.rs +++ b/crates/tools/src/xform/wand.rs @@ -165,7 +165,7 @@ impl Tool for LassoTool { self.mesh.options() } - /// Pick the gradient mesh points the Eyedropper held (`meshPoints`). + /// Pick the gradient mesh points the tool chosen before held (`meshPoints`). fn set_option(&mut self, key: &str, value: &Value) { if key == "meshPoints" { self.mesh.set_options(value); diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..a2dfff4bfa 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -14191,8 +14191,10 @@ away); its click on a gradient mesh's line picks the line's two ends, and a click inside a patch picks the four points around it. The picked points show filled. Dragging one of them moves them all as one undo step (`object.mesh.movePoints`), a click on one of several picked points picks it alone, and the arrow keys nudge them by the keyboard increment. The active tool lists them in its options -(`tool.setOption {}` returns them as `meshPoints: [{id, index}…]`). Switching to the Eyedropper keeps them picked, its -options list them too, and the Mesh tool, Direct Selection or a Lasso chosen next picks them again. While a selected, editable mesh has +(`tool.setOption {}` returns them as `meshPoints: [{id, index}…]`). Switching between the Mesh tool, Direct Selection, +the Lasso, the Polygonal Lasso and the Eyedropper keeps them picked, and so does a Cmd/Ctrl-click with the selection +tool one of them lends; any other tool, Group Selection included, drops them. The Eyedropper's options list them too. +While a selected, editable mesh has points picked, an Eyedropper click or Shift-click on an image or other art samples the color under the pointer into those points alone as `paint.sampleColor {color, stroke: false, ids}` with the meshes that have points picked: one undo step, none when the color is unchanged. Other selected objects keep their paint. A click on one of those meshes, and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 57ac87a396..25b0e47a10 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1905,6 +1905,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Several mesh points at once (#4207, #4208, #4170):** the Mesh tool and Direct Selection pick several points of a gradient mesh or mesh envelope: Shift-click adds a point or takes a picked one away, Direct Selection's marquee picks the points inside it (Shift toggles them) and selects their meshes, and its click on a mesh line picks the line's two ends and one inside a patch the four points around it. The picked points show filled; dragging one moves them all as one undo step and the arrow keys nudge them (`object.mesh.movePoints {id, points, dx, dy}` or `{items, dx, dy}`), and a click on one of several picked points picks it alone. A solid fill colour (`paint.setFill`: Color panel, Swatches, Eyedropper) recolours every picked point, and the Transparency panel's Opacity fades them instead of the object, the panel showing their opacity (blank when it differs); `object.mesh.setPointColor` takes `points` or `items`. Public reference: [Edit mesh objects](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-meshes/edit-mesh-objects.html) (Shift selects multiple mesh points; a fill colour colours the selected point), [Macworld, gradient mesh](https://www.macworld.com/article/202693/gmesh2.html) (Direct Selection: a mesh line selects the points at both ends, a patch the points around it, Shift-click adds or removes points), [Peachpit](https://www.peachpit.com/articles/article.aspx?p=1638270) (each mesh point can have its own colour or transparency). Tests: `shift_clicks_pick_mesh_points_that_drag_and_nudge_together` and `direct_selection_picks_mesh_points_by_marquee_line_and_patch` in `crates/tools/src/meshedit.rs`, `picked_mesh_points_take_the_fill_opacity_and_drag_together` in `crates/engine/src/tests/editcolors.rs`, `mesh_points_move_and_colour_together` in `crates/engine/src/tests/live.rs`. Scores and hours unchanged. - **Picked mesh points in the panels** (VectorCraft's own rule): with points of a gradient mesh picked by the Mesh tool, Direct Selection or the Lasso, the Fill proxy, the Color panel and the Color Wheel show the first picked point's color, so their sliders keep the color a drag sets, and "?" shows when the picked points' colors differ. The Control bar shows the first picked point's opacity. Tests: `the_fill_proxy_shows_the_picked_mesh_points_color`, `the_fill_proxy_follows_where_the_fill_goes_with_an_appearance_row_active` and `the_fill_proxy_counts_picked_mesh_points_beside_other_objects` in `crates/engine/src/tests/xform.rs`, `picked_mesh_points_are_the_color_the_panel_shows_and_edits` in `crates/ui-egui/src/panels/color/tests.rs`, `picking_mesh_points_shows_their_opacity` in `crates/ui-egui/src/panels/transparency.rs`. Scores and hours unchanged. - **The Eyedropper samples into picked mesh points (#8090):** mesh points picked with the Mesh tool, Direct Selection or the Lasso stay picked after switching to the Eyedropper and go back to one of those tools chosen next, and a click or Shift-click on an image or other art then samples the color under the pointer into every picked point as one undo step, leaving the mesh's other points and its appearance as they were. VectorCraft's own rules: a plain click on vector art samples its color into the points instead of copying its appearance, other selected objects keep their paint, and a click on a mesh with points picked works as before. Public references: [Edit mesh objects](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-meshes/edit-mesh-objects.html) (a mesh point is recolored by selecting it and choosing a fill color), [Appearance attributes](https://helpx.adobe.com/illustrator/using/appearance-attributes.html) (Shift-click samples the color from a part of a mesh object or a placed image and applies it to the selected fill). Tests: `picked_mesh_points_take_the_eyedropper_sample` in `crates/engine/src/tests/eyedropper.rs`, `picked_mesh_points_take_the_color_a_click_samples` in `crates/tools/src/xform/eyedropper.rs`, `mesh_point_tools_take_back_the_eyedroppers_picks` in `crates/tools/src/meshedit.rs`. Scores and hours unchanged. +- **Picked mesh points survive a tool switch:** mesh points picked with the Mesh tool, Direct Selection, the Lasso or the Polygonal Lasso stay picked when another of these tools is chosen, and when one of them lends Direct Selection for a Cmd/Ctrl-click, so a fill color chosen afterwards recolors just those points. Any other tool, Group Selection included, drops them. Public references: [Edit mesh objects](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-meshes/edit-mesh-objects.html) (a mesh point picked with the Mesh tool is recolored by choosing a fill color in the Swatches or Color panel), [Archived help guide, page 202](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=202) (the Mesh tool and Direct Selection both move mesh points). Carrying the picks between the tools is VectorCraft's own rule. Tests: `crates/engine/src/tests/mesh_picks.rs`. Scores and hours unchanged. - **Image Trace Flat Logo mode:** a fourth mode beside Black and White, Grayscale and Color, for flat-colour logos. Each pixel is read as a blend of the logo's colours (found automatically or named), the blend is interpolated smoothly and every outline is placed where two colours are equally present, so edges are accurate to a fraction of a pixel. Outlines are then cleaned: corners the blur rounded are put back, near-straight runs and near-circular arcs become exact lines and arcs, the rest is fitted with as few Béziers as the tolerance allows, touching colours overlap by a hair so no gap opens, and an outline that strays from the raw contour is fitted plainly instead. Gradients and photos are refused with advice to use Color. Line art whose only solid area is white paper (strokes a pixel or two wide) takes its colours from the strokes' cores, with the lighter shades along a stroke's anti-aliased edge folded into its ink; a page whose ink (a channel at least 48 below white) covers under 1% of it traces to nothing, as blank paper does. *Measured* (a local experiment, not run in CI): a flat-colour logo's vector original was rendered down to a soft 199 × 100 px transparent PNG, traced, and the result compared with the original at 1600 px wide. The built-in colour presets (6 Colors, 16 Colors, High Fidelity Photo, Low Fidelity Photo) had a mean edge error of 2.5 to 3.4 px and region overlap of 0.88 to 0.91; Flat Logo had 0.78 px and 0.966 (0.48 px and 0.975 from a crisp source), in about 0.1 s. Limits: flat-colour art only; needle-thin sharp tips are shortened by about 1.7 source pixels because the blur erases them; it works at no more than 1024 px on the long side (larger images are averaged down first); only one logo family has been scored against a vector original. - **Image Trace, Flat Logo named colors only:** with `logoColors` named, `"logoWhite": false` traces those colors only, so white areas take the nearest of them and no white is added; a named white is kept, and enclosed transparent areas stay holes; code-drawn tests in `crates/trace` and `crates/engine`. - **Image Trace, Flat Logo flat-art check with named colors:** with `logoColors` named, whether the image is flat art is judged by its own colors, as many as are named, with white, or as the Colors setting gives, whichever is more. Named colors 20 levels off a flat badge's colors still trace it, a hatch on a light ground gives the same result with close and far named colors, a gradient's refusal score does not depend on how far the named colors are from it, and areas of colors that were not named are traced in the named colors instead of being refused; code-drawn tests in `crates/trace`. From 2d0389c8fdf0042820ba5d4483555e81dcb83e4c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 14:44:44 -0800 Subject: [PATCH 22/38] Gradient: moving out of a freeform object ends the Lines mode line In freeform Lines mode, moving the pointer out of the object and back now ends the line being drawn, so the next click on the object starts a new line. The help page describes this way of starting another line in the same object: https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=262 The line ends on the first pointer move, with no button held, that leaves the object. The object counts as its path's area inside any clipping masks above it, plus its own painted art (stroke, glyphs); other art lying over it does not end the line, and outline view, a layer with Preview off and the path-only selection preferences do not shrink the area. Escape and a click off the art still end the line. --- crates/tools/src/xform/freeform.rs | 160 +++++++++++++++++++++++++++-- docs/target-app-parity.md | 1 + 2 files changed, 154 insertions(+), 7 deletions(-) diff --git a/crates/tools/src/xform/freeform.rs b/crates/tools/src/xform/freeform.rs index 89c6faa933..8a5a461a2b 100644 --- a/crates/tools/src/xform/freeform.rs +++ b/crates/tools/src/xform/freeform.rs @@ -8,14 +8,15 @@ //! //! Points mode (the Gradient panel's Draw toggle): a click inside the selected art adds a point //! there, coloured as the gradient is there. Lines mode: successive clicks draw a smooth line -//! through the points they add, until Escape (or a click off the art) ends it; clicking an -//! existing point first starts the line from it. Delete or Backspace removes the selected point. +//! through the points they add, until Escape, a click off the art or moving the pointer out of +//! the object ends it; clicking an existing point first starts the line from it. Delete or +//! Backspace removes the selected point. use serde_json::{Value, json}; use vectorcraft_color::freeform::LineHit; use vectorcraft_color::{Color, Freeform, FreeformMode, FreeformPoint}; use vectorcraft_doc::NodeId; -use vectorcraft_doc::hit::hit_test; +use vectorcraft_doc::hit::{HitOptions, hit_test, hit_test_visible_skipping}; use vectorcraft_geom::{Point, Shape, Vec2}; use super::paint_owner; @@ -183,6 +184,43 @@ fn on_art(cx: &ToolContext, p: Point) -> bool { hit_test(cx.doc, p, cx.hit_options()).is_some_and(|h| cx.selection.objects.contains(&paint_owner(cx.doc, h.leaf))) } +/// Is `p` on object `id`: inside its path's area (where a dragged point stays) and every clipping +/// mask above it, or on its own art where a click hits it with the art lying over it left out (a +/// stroke, type's glyphs)? +fn on_object(cx: &ToolContext, id: NodeId, p: Point) -> bool { + let Some(n) = cx.doc.node(id) else { return false }; + let ancestry = cx.doc.ancestry(id).unwrap_or_default(); + let contains = |shapes: &[(vectorcraft_geom::BezPath, vectorcraft_geom::FillRule)]| { + shapes.iter().any(|(bp, rule)| vectorcraft_geom::hit::fill_contains(bp, *rule, p)) + }; + // A mask with a live effect clips by the effect's result, which the hit test below measures. + let plain = |clip: &vectorcraft_doc::Node| { + let mut effects = false; + clip.walk(&mut |c| { + effects |= c.appearance.effects.iter().any(|e| e.visible) || c.appearance.items.iter().any(|i| i.effects().iter().any(|e| e.visible)); + }); + !effects + }; + let unmasked = || { + ancestry.iter().filter_map(|a| cx.doc.node(*a)).filter(|a| a.clips()).all(|a| { + a.children() + .and_then(|c| c.first()) + .is_none_or(|clip| clip.id == id || plain(clip) && contains(&vectorcraft_doc::hit::clip_regions(clip))) + }) + }; + if contains(&n.clip_shapes(None)) && unmasked() { + return true; + } + let mut keep = std::collections::HashSet::new(); + n.walk(&mut |c| { + keep.insert(c.id); + }); + keep.extend(ancestry); + // The art as painted, whatever the view and the path-only selection preferences. + let opt = HitOptions { outline: false, path_only: false, type_path_only: false, ..cx.hit_options() }; + hit_test_visible_skipping(cx.doc, p, opt, &|n| !keep.contains(&n)).is_some_and(|h| h.leaf == id || h.ancestry.contains(&id)) +} + pub(super) fn press(cx: &ToolContext, a: &Annotator, p: Point) -> (Vec, Gesture) { let mut out = vec![]; let grab = if let Some(i) = a.point_at(cx, p) { @@ -293,8 +331,13 @@ pub(super) fn double_click(cx: &ToolContext, a: &Annotator, p: Point) -> Vec Date: Fri, 20 Nov 2026 15:02:12 -0800 Subject: [PATCH 23/38] Docs: Relink and Update Links keep a clipping mask edited in the document The PSD clipping-path entry said that links.update and links.relink leave a plain group whenever the new file names no clipping path. A clip group whose clipping path was changed in the document, and a clipping mask made in the document, are kept when Placement Options do not clip the image: a new file with no clipping path leaves the mask clipping the image, and a new file's clip group goes inside the mask. --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 57ac87a396..0efd8dffc7 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2321,7 +2321,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - BMP files named `.dib` or `.rle` (run-length encoded bitmaps included), Photoshop files named `.pdd` and PNG files named `.pns` open and place, linked or embedded, as BMP, PSD and PNG files, in any letter case: the Open and Place dialogs list them with their format, the Links panel names their format, and Edit Original opens them. Exports write only `.bmp`, `.psd` and `.png` (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/links.rs`). - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer, merging a layer that uses a Knockout option with the layers below it, and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), a Knockout value of 1 is read as a shallow knockout and applied to a layer or group inside a group, which is merged with the visible layers below it in that group (its pixels clear them to transparency, it is drawn there at its fill opacity, and its opacity fades the result; in a pass-through group only when it and the visible layers below it are in the Normal mode; a knockout at 0 opacity, or at 0 fill where it covers none of their painted pixels, isn't merged for the knockout), and adjustment layers, layer effects, vector masks and the other knockouts (top-level layers, clipped layers, layers that others are clipped to, pass-through groups with layers in other modes, other Knockout values, and merges that need more memory than allowed) aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - File › Open of a PSD or PSB file with two or more layers, and File › Place of one without Link, show PSD Import Options: Convert Layers to Objects with Import Hidden Layers, or Flatten Layers to a Single Image, the options [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded. A file placed with Link shows its flat image and isn't asked about. `file.place` takes `layers` and `hiddenLayers`, and `document.psdInfo` counts a file's layers without opening it. VectorCraft's own rules: placed layers come in as one group named after the file, a layer as an image and a layer group as a group, at the place the merged image would take and clipped to the canvas when layers reach past it; the dialog asks from two layers up and starts from the choices made last. Layer comps aren't read (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). - - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none, and files that name no clipping path come in as before. `links.unembed` keeps the clip group, and the PNG or TIFF it writes is read with the path on File › Open, File › Place, `links.relink` and `links.update` (`crates/engine/src/cmd/fileio/tests_psdread.rs`). + - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none. When Placement Options do not clip the image, a clip group whose clipping path was changed in the document (its anchors, whether it is closed, or its fill rule) and a clipping mask made in the document are kept: a new file that names no clipping path leaves the mask clipping the image, and the clip group of a new file that names one goes inside the mask. Files that name no clipping path come in as before. `links.unembed` keeps the clip group, and the PNG or TIFF it writes is read with the path on File › Open, File › Place, `links.relink` and `links.update` (`crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/dcs.rs`). - Import Slices: File › Open of a PSD or PSB file with slices, and File › Place of one without Link, bring its slices in as user slices, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded; PSD Import Options offers Import Slices for such a file. `document.open` and `file.place` take `importSlices`, and `document.psdInfo` counts the slices. The slices are read from image resource 1050 in version 6 and in the descriptor of versions 7 and 8, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it. VectorCraft's own rules: Import Slices applies to Convert Layers to Objects and to Flatten Layers to a Single Image alike, and makes the dialog ask for a file with fewer than two layers; placed slices move and scale with the art in the same undo step; each slice keeps its name, type, link, target, message, alternative text, cell text and background color; slices the file generated automatically, and slices wholly outside the canvas, are left out; slices that can't be read are left out with a warning while the art comes in; with Show Import Options off, a PSD file is placed with the PSD Import Options chosen last, and on, each PSD file of the place cursor asks for them (`crates/engine/src/cmd/fileio/tests_psdslices.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). The import fuzz tests open, count and place PSD files whose resource 1050 is in version 6 (with a version 16 descriptor after a record) and in the descriptors of versions 7 and 8, with their data mutated, cut short with the resource's length saying so, and cut short in the file; a slice count past 10,000 or past the slices stored, and data one byte short, bring the art in without its slices and with a warning. `tests_psdslices::damaged_slices_never_panic` now fails when a command reports an internal error (`import_fuzz::the_sliced_psd_samples_bring_in_their_user_slices`, `import_fuzz::sliced_psd_samples_with_huge_counts_or_cut_short_come_in_without_their_slices`, `import_fuzz::mutated_psd_slices_never_panic`). Scores and estimates unchanged. - PSD export writes slices: the user and object slices that reach into the exported artboard go into image resource 1050 in version 6, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it and as Import Slices reads it, so an opened PSD file's slices survive its export. VectorCraft's own rules: slices are written with Write Layers and as a flat image alike, clipped to the artboard in its pixels; an object slice is written as a user slice over its object's bounds, and an HTML Text slice as No Image with its type's text; auto slices are left out and laid out again on open; text alignment is written as the default (`crates/render/src/encode/tests_psd.rs`, `crates/engine/src/cmd/fileio/tests_psdslices.rs`). From d9dba9c467ca37b06919000ea20812c9bbfa5642 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:02:27 -0800 Subject: [PATCH 24/38] Legacy .ai: gradient definitions are found by a key of their gradient Each gradient fill looked for its definition by comparing its gradient with every definition written so far, so a document with thousands of distinct gradients spent most of the export in these comparisons. The writer now keeps each definition's place under a key made from every field of its gradient, the same key the editing data's writer uses, which moves to a module both writers share. Each candidate under a key is still compared in full, and the first equal definition in definition order is used. Spot color names, written spot colors and fonts are also found through maps and sets, while the lists the file is written from keep their order. The written file is unchanged, byte for byte. On Linux, writing 10,006 gradient fills (5,000 distinct and 5,000 of 50 others) took 79 ms of thread CPU time through the index and 291 ms comparing each definition in turn (median of 7 runs, release build). --- crates/eps/src/ai_editing/writer/paints.rs | 23 +---- crates/eps/src/gradient_key.rs | 29 ++++++ crates/eps/src/legacy_ai/tests.rs | 113 +++++++++++++++++++++ crates/eps/src/legacy_ai/writer.rs | 54 ++++++++-- crates/eps/src/lib.rs | 2 + 5 files changed, 190 insertions(+), 31 deletions(-) create mode 100644 crates/eps/src/gradient_key.rs diff --git a/crates/eps/src/ai_editing/writer/paints.rs b/crates/eps/src/ai_editing/writer/paints.rs index 5a850d7db3..f1573c39ba 100644 --- a/crates/eps/src/ai_editing/writer/paints.rs +++ b/crates/eps/src/ai_editing/writer/paints.rs @@ -3,7 +3,6 @@ use std::collections::HashMap; use std::fmt::Write; -use std::hash::{Hash, Hasher}; use vectorcraft_color::gradient::GradientGeom; use vectorcraft_color::swatch::REGISTRATION; @@ -14,6 +13,7 @@ use vectorcraft_geom::{Affine, BezPath, Rect, Shape, Vec2}; use super::{MAX_NEST, Writer, Xy}; use crate::ai_ops::{self, average, unit}; +use crate::gradient_key::gradient_key; use crate::ps; pub(in crate::ai_editing) const GRADIENTS: &str = @@ -64,27 +64,6 @@ fn same_gradient(a: &Gradient, b: &Gradient) -> bool { a == b } -/// A key of `g` for [`GradientDefs`]: the same gradients have the same key (each number by its -/// bits, with -0 as 0); different gradients may share one. -fn gradient_key(g: &Gradient) -> u64 { - let bits = |x: f32| if x == 0.0 { 0 } else { x.to_bits() }; - let mut h = std::hash::DefaultHasher::new(); - std::mem::discriminant(&g.kind).hash(&mut h); - std::mem::discriminant(&g.method).hash(&mut h); - (g.dither, g.spread, g.repeats, g.stops.len()).hash(&mut h); - for s in &g.stops { - let (model, c) = match s.color { - Color::Rgb { r, g, b } => (0u8, [r, g, b, 0.0]), - Color::Cmyk { c, m, y, k } => (1, [c, m, y, k]), - Color::Gray { k } => (2, [k, 0.0, 0.0, 0.0]), - Color::Lab { l, a, b } => (3, [l, a, b, 0.0]), - }; - (model, c.map(bits), [s.offset, s.opacity, s.midpoint, s.tint].map(bits)).hash(&mut h); - (&s.swatch, s.plates.map(|p| p.map(bits))).hash(&mut h); - } - h.finish() -} - /// The gradient definitions, in the order they are first used, found by name and by gradient /// without comparing each one. #[derive(Default)] diff --git a/crates/eps/src/gradient_key.rs b/crates/eps/src/gradient_key.rs new file mode 100644 index 0000000000..3bdb7f833a --- /dev/null +++ b/crates/eps/src/gradient_key.rs @@ -0,0 +1,29 @@ +//! A key of a gradient for the gradient definitions the legacy `.ai` writer +//! ([`crate::legacy_ai`]) and the editing data writer ([`crate::ai_editing`]) look up: the writers +//! keep each definition's place under its gradient's key and compare only the gradients that +//! share it. + +use std::hash::{Hash, Hasher}; + +use vectorcraft_color::{Color, Gradient}; + +/// A key of `g`: the same gradients have the same key (each number by its bits, with -0 as 0); +/// different gradients may share one. +pub(crate) fn gradient_key(g: &Gradient) -> u64 { + let bits = |x: f32| if x == 0.0 { 0 } else { x.to_bits() }; + let mut h = std::hash::DefaultHasher::new(); + std::mem::discriminant(&g.kind).hash(&mut h); + std::mem::discriminant(&g.method).hash(&mut h); + (g.dither, g.spread, g.repeats, g.stops.len()).hash(&mut h); + for s in &g.stops { + let (model, c) = match s.color { + Color::Rgb { r, g, b } => (0u8, [r, g, b, 0.0]), + Color::Cmyk { c, m, y, k } => (1, [c, m, y, k]), + Color::Gray { k } => (2, [k, 0.0, 0.0, 0.0]), + Color::Lab { l, a, b } => (3, [l, a, b, 0.0]), + }; + (model, c.map(bits), [s.offset, s.opacity, s.midpoint, s.tint].map(bits)).hash(&mut h); + (&s.swatch, s.plates.map(|p| p.map(bits))).hash(&mut h); + } + h.finish() +} diff --git a/crates/eps/src/legacy_ai/tests.rs b/crates/eps/src/legacy_ai/tests.rs index 6018bc6920..2f5a528340 100644 --- a/crates/eps/src/legacy_ai/tests.rs +++ b/crates/eps/src/legacy_ai/tests.rs @@ -1696,6 +1696,119 @@ fn colliding_gradient_and_spot_names_are_numbered_as_before() { assert!(text.contains("%%DocumentCustomColors: (?)\n%%+ (? 2)\n%%+ (? 3)\n%%+ (? 2 2)\n"), "{text}"); } +/// `doc` written with its gradient definitions found by comparing each in turn (`scanned`) or +/// through their index. +fn export_scanned(doc: &Document, scanned: bool) -> LegacyAiOutput { + let o = LegacyAiOptions { created: Some(0), ..LegacyAiOptions::default() }; + super::writer::SCANNED_DEFINITIONS.with(|s| s.set(scanned)); + let out = export_legacy_ai(doc, &o); + super::writer::SCANNED_DEFINITIONS.with(|s| s.set(false)); + out.unwrap() +} + +/// A document of rectangles filled with gradients: one with a gradient swatch `Sky` of its own; +/// `distinct` with gradients of their own; `reused` with one of `ramps` others in turn; one with a +/// gradient swatch `Dawn` whose gradient is the first of those `ramps`; two whose gradients differ +/// only in the sign of a zero offset; and two with the same gradient, whose midpoint is not a +/// number. +fn many_gradients(distinct: u16, reused: u16, ramps: u16) -> Document { + let mut doc = Document::new(1000.0, 1000.0); + let layer = doc.layers[0].id; + let shade = |i: u16, n: u16| f32::from(i) / f32::from(n.max(1)); + let mut paints = vec![gradient_from(Color::rgb(0.1, 0.2, 0.3), Some("Sky"))]; + for i in 0..distinct { + paints.push(gradient_from(Color::rgb(shade(i, distinct), 0.5, 0.0), None)); + } + for i in 0..reused { + paints.push(gradient_from(Color::cmyk(0.0, shade(i % ramps.max(1), ramps), 0.5, 0.0), None)); + } + paints.push(gradient_from(Color::cmyk(0.0, 0.0, 0.5, 0.0), Some("Dawn"))); + let stops = |offset: f32, midpoint: f32| { + let mut first = GradientStop::new(offset, Color::rgb(0.2, 0.3, 0.4)); + first.midpoint = midpoint; + let g = Gradient::new(GradientKind::Linear, vec![first, GradientStop::new(1.0, Color::BLACK)]); + Paint::Gradient(Box::new(GradientPaint::new(g))) + }; + paints.extend([stops(0.0, 0.5), stops(-0.0, 0.5), stops(0.0, f32::NAN), stops(0.0, f32::NAN)]); + for (i, paint) in (0u16..).zip(paints) { + let (x, y) = (f64::from(i % 40) * 25.0, f64::from(i / 40 % 40) * 25.0); + let n = shape(&mut doc, shapes::rectangle(Rect::new(x, y, x + 20.0, y + 20.0)), paint, Paint::None); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + doc +} + +/// Gradient definitions found through their index are those found by comparing each in turn: the +/// file is the same, byte for byte, with the same warnings. An earlier definition of the same +/// gradient serves a gradient swatch of another name; gradients that differ only in the sign of a +/// zero share a definition; a gradient that is not equal to itself is defined each time. +#[test] +fn indexed_gradient_definitions_write_the_same_file() { + let doc = many_gradients(300, 300, 7); + let (indexed, scanned) = (export_scanned(&doc, false), export_scanned(&doc, true)); + let differ = indexed.bytes.iter().zip(&scanned.bytes).position(|(a, b)| a != b); + assert!(indexed.bytes == scanned.bytes, "the files differ from byte {differ:?} ({} and {} bytes)", indexed.bytes.len(), scanned.bytes.len()); + assert_eq!(indexed.warnings, scanned.warnings); + assert_eq!(indexed.setting_notes, scanned.setting_notes); + let text = String::from_utf8(indexed.bytes).unwrap(); + let defined: Vec<&str> = text.lines().filter_map(|l| l.strip_suffix(" 0 2 Bd")).collect(); + // `Sky`, 300 of their own, 7 reused, 1 for both signs of zero and 2 for the gradient that + // is not a number. + assert_eq!(defined.len(), 1 + 300 + 7 + 1 + 2, "{defined:?}"); + assert_eq!(defined.first(), Some(&"(Sky)")); + assert!(!defined.contains(&"(Dawn)"), "{defined:?}"); +} + +/// A gradient is matched with the definitions of the same gradient, not with each definition: +/// 1,000 gradients of their own and 1,000 of 10 others take a comparison or so each, where +/// comparing each definition in turn takes hundreds of thousands. +#[test] +fn legacy_gradient_definitions_are_found_without_comparing_each() { + let doc = many_gradients(1000, 1000, 10); + let comparisons = |scanned: bool| { + super::writer::GRADIENT_COMPARISONS.with(|c| c.set(0)); + export_scanned(&doc, scanned); + super::writer::GRADIENT_COMPARISONS.with(std::cell::Cell::get) + }; + let (indexed, scanned) = (comparisons(false), comparisons(true)); + assert!(indexed <= 2 * 2006, "{indexed} comparisons through the index"); + assert!(scanned > 100 * indexed, "{scanned} comparisons scanning, {indexed} through the index"); +} + +/// The time to write 5,000 rectangles with gradients of their own and 5,000 with 50 others, with +/// the definitions found by comparing each in turn and through their index: the median of 7 runs +/// of each, alternating, with the files compared. Run with +/// `cargo test --release -p vectorcraft-eps --lib -- --ignored --nocapture legacy_gradient_definitions_timing`. +#[test] +#[ignore = "timing"] +fn legacy_gradient_definitions_timing() { + let doc = many_gradients(5000, 5000, 50); + let mut times = [vec![], vec![]]; + let mut files: [Option>; 2] = [None, None]; + let mut how = ""; + for _ in 0..7 { + for (k, scanned) in [true, false].into_iter().enumerate() { + let (start, h) = thread_time(); + let out = export_scanned(&doc, scanned); + times[k].push(thread_time().0.saturating_sub(start)); + how = h; + files[k].get_or_insert(out.bytes); + } + } + assert_eq!(files[0], files[1]); + for t in &mut times { + t.sort(); + } + let ms = |d: std::time::Duration| d.as_secs_f64() * 1000.0; + println!("10,006 gradient fills, median of 7 runs ({how}):"); + println!("| definitions found | median (ms) | runs (ms) |"); + println!("|---|---:|---|"); + for (k, label) in ["comparing each in turn", "through the index"].into_iter().enumerate() { + let runs: Vec = times[k].iter().map(|d| format!("{:.1}", ms(*d))).collect(); + println!("| {label} | {:.1} | {} |", ms(times[k][3]), runs.join(", ")); + } +} + /// The time this thread has run, and how it was measured. fn thread_time() -> (std::time::Duration, &'static str) { if let Some(ns) = std::fs::read_to_string("/proc/thread-self/schedstat").ok().and_then(|s| s.split_whitespace().next()?.parse::().ok()) { diff --git a/crates/eps/src/legacy_ai/writer.rs b/crates/eps/src/legacy_ai/writer.rs index 7e7dbfe4fc..2fa0fcb6c2 100644 --- a/crates/eps/src/legacy_ai/writer.rs +++ b/crates/eps/src/legacy_ai/writer.rs @@ -10,6 +10,7 @@ use super::{ TextObject, UNDECODED, Vec2, Write, ai_ops, latin, ps, stroke, }; use super::{CONIC, CONIC_WEDGES, DEEP_DISTORTED, DIAMOND, GRAPHS, HUE_STOPS, PERCEPTUAL_STOPS, SPREAD, SPREAD_CAPPED}; +use crate::gradient_key::gradient_key; #[cfg(test)] thread_local! { @@ -18,6 +19,18 @@ thread_local! { /// Whether [`Numbered::take`] numbers names on this thread by searching the names given so /// far, one number at a time, for each number it tries. pub(super) static SCANNED_NAMES: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// Whether [`Writer::defined`] finds a gradient's definition on this thread by comparing the + /// gradient with each definition in turn. + pub(super) static SCANNED_DEFINITIONS: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// How many times [`Writer::defined`] has compared two gradients on this thread. + pub(super) static GRADIENT_COMPARISONS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Are gradients `a` and `b` the same? +fn same_gradient(a: &Gradient, b: &Gradient) -> bool { + #[cfg(test)] + GRADIENT_COMPARISONS.with(|c| c.set(c.get() + 1)); + a == b } /// An image's coverage ([`ImageBlob::coverage`]): its width, its height and one byte a pixel. @@ -34,7 +47,7 @@ pub(super) struct Writer<'a> { /// Spot colors used: the name written and full CMYK equivalent. pub(super) spots: Vec<(String, [f32; 4])>, /// The name each spot color (by its swatch's name) is written with ([`Self::spot`]). - spot_names: Vec<(String, String)>, + spot_names: std::collections::HashMap, pub(super) warnings: Vec, /// Notes on what the options asked for ([`crate::LegacyAiOutput::setting_notes`]). pub(super) setting_notes: Vec, @@ -73,6 +86,13 @@ pub(super) struct Writer<'a> { gradient_names: Numbered, /// The names spot colors are written with ([`Self::spot`]). spot_written: Numbered, + /// The names of [`Self::spots`]. + spot_set: std::collections::HashSet, + /// The PostScript names of [`Self::fonts`]. + font_set: std::collections::HashSet, + /// The places in [`Self::gradients`] of the definitions, in order, by their gradient's key + /// ([`gradient_key`]). + gradient_index: std::collections::HashMap>, } impl<'a> Writer<'a> { @@ -84,7 +104,7 @@ impl<'a> Writer<'a> { body: String::new(), gradients: vec![], spots: vec![], - spot_names: vec![], + spot_names: std::collections::HashMap::new(), warnings: vec![], setting_notes: vec![], locked: false, @@ -103,6 +123,9 @@ impl<'a> Writer<'a> { in_graph: false, gradient_names: Numbered::default(), spot_written: Numbered::default(), + spot_set: std::collections::HashSet::new(), + font_set: std::collections::HashSet::new(), + gradient_index: std::collections::HashMap::new(), } } @@ -160,16 +183,17 @@ impl<'a> Writer<'a> { /// Windows-1252 are written as `?` (with a warning), and it is numbered when another spot color /// is already written with that name; the name is the same each time. fn spot(&mut self, name: &str, cmyk: [f32; 4]) -> String { - let written = match self.spot_names.iter().find(|(n, _)| n == name) { - Some((_, w)) => w.clone(), + let written = match self.spot_names.get(name) { + Some(w) => w.clone(), None => { let base = self.latin_name(name, TITLE_AND_COLOR_NAMES); let written = self.spot_written.take(base); - self.spot_names.push((name.to_string(), written.clone())); + self.spot_names.insert(name.to_string(), written.clone()); written } }; - if !self.spots.iter().any(|(n, _)| *n == written) { + if !self.spot_set.contains(&written) { + self.spot_set.insert(written.clone()); self.spots.push((written.clone(), cmyk)); } written @@ -178,7 +202,7 @@ impl<'a> Writer<'a> { /// The name spot color `name` (its swatch's name) is written with, once [`Self::spot`] has /// noted it. pub(super) fn spot_name<'n>(&'n self, name: &'n str) -> &'n str { - self.spot_names.iter().find(|(n, _)| n == name).map_or(name, |(_, w)| w.as_str()) + self.spot_names.get(name).map_or(name, String::as_str) } /// A top-level layer. False when it isn't a layer. @@ -831,15 +855,26 @@ impl<'a> Writer<'a> { /// The name of the definition of `g` (its swatch's name when it has one, with each character /// outside Windows-1252 written as `?` and a warning), defined the first time. fn define(&mut self, g: &Gradient, swatch: Option<&str>) -> String { - if let Some((name, _)) = self.gradients.iter().find(|(_, d)| d == g) { + let key = gradient_key(g); + if let Some((name, _)) = self.defined(g, key).and_then(|i| self.gradients.get(i)) { return name.clone(); } let base = self.latin_name(swatch.filter(|s| !s.is_empty()).unwrap_or("Gradient"), TITLE_AND_COLOR_NAMES); let name = self.gradient_names.take(base); + self.gradient_index.entry(key).or_default().push(self.gradients.len()); self.gradients.push((name.clone(), g.clone())); name } + /// The place in [`Self::gradients`] of the first definition of `g`, whose key is `key`. + fn defined(&self, g: &Gradient, key: u64) -> Option { + #[cfg(test)] + if SCANNED_DEFINITIONS.with(std::cell::Cell::get) { + return self.gradients.iter().position(|(_, d)| same_gradient(d, g)); + } + self.gradient_index.get(&key)?.iter().copied().find(|i| self.gradients.get(*i).is_some_and(|(_, d)| same_gradient(d, g))) + } + // ---------- type ---------- /// Type: a text object when the format can hold it as text, else its outlines (type with @@ -1016,7 +1051,8 @@ impl<'a> Writer<'a> { self.line_style(&st.stroke_layer()); } let (name, truetype, ascent, descent) = font_of(st); - if !self.fonts.iter().any(|(n, _)| *n == name) { + if !self.font_set.contains(&name) { + self.font_set.insert(name.clone()); self.fonts.push((name.clone(), truetype)); } let size = finite(st.size, 12.0); diff --git a/crates/eps/src/lib.rs b/crates/eps/src/lib.rs index 39737dae3a..44d974bd35 100644 --- a/crates/eps/src/lib.rs +++ b/crates/eps/src/lib.rs @@ -32,12 +32,14 @@ //! ([`export_ai_editing`], [`ai_private_data`]). //! - `ai_ops`: the path and line style operators those two write. //! - `ai_graph`: the records of a live graph those two write around its group. +//! - `gradient_key`: the key those two find gradient definitions by. //! - [`dcs`]: DCS files, an EPS file with one program per printing plate, read for placing. mod ai_editing; mod ai_graph; mod ai_ops; pub mod dcs; +mod gradient_key; mod import; mod latin; mod legacy_ai; From 5c9b0004fea11d1ca074fbecc06b8d46968865ac Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:02:35 -0800 Subject: [PATCH 25/38] Command Palette: docs order typo matches by the field the word is met in Among results matched through a typo, the ranking key compares the typo grade (a word met in the label grades better than one met in the menu path) before the other words' grades and the label's length, so two results can come in a different order than the word spelled right gives them. The paragraph now states that order. --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 57ac87a396..8e7a28bc6c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1588,7 +1588,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A modal window that opens without a press in the window (a dialog opened from the macOS menu bar or by an automation command, the About window, a file dialog, the update prompt, or the progress window of a plug-in, trace or open run) closes the Command Palette, a tool group's flyout, the All Tools drawer and any open menu or popup in the pass it opens. While such a window is open, the palette stays closed, so opening it from the macOS menu bar or by an automation command does not take the keyboard from the window; it opens again once the window closes (`palette` tests `a_dialog_opened_from_the_system_menu_closes_the_palette`, `the_about_window_closes_the_palette`, `a_progress_window_closes_the_palette`, `the_palette_opened_over_a_dialog_closes`, `a_click_on_the_menu_bar_closes_the_palette_before_a_dialog_opens`, `a_dialog_opened_without_a_press_closes_a_flyout`, `a_dialog_opened_without_a_press_closes_the_tools_drawer`, `a_dialog_opened_without_a_press_closes_a_menu`, `the_palette_opened_as_a_dialog_closes_stays_open_until_the_next_dialog`). The Command Palette ranks its results by how well they match. A query that is a result's id lists that result first (`view.goto1` lists Saved View 1 above Saved View 10); then come results whose name is the query, results whose name without its menu path starts with it, and results whose initials it is ("ea" finds Export As…). Within each of those, a result where every word of the query is a whole word of its name ranks above one where a word only starts a word of the name, then one where it is a word of the menu that holds it, then of its id, then text inside a word, so a query that is a menu's title ("object") lists results named with that word above the items of that menu. A tool ranks above a menu command, panel, effect or filter plug-in that matches as well, so "rect" lists the Rectangle Tool above Effect › Convert to Shape › Rectangle…, and of two results of the same kind the shorter name comes first. Words of the menu bar item that runs a result also find it, the item's own label included ("exit" finds Quit VectorCraft, which File › Exit runs); with the native macOS menu bar, the items that bar moves into its application menu are found under it (Preferences… under Settings). Every result the earlier search found is still found, and the highlight stays on its result when a plug-in is installed, a shortcut changes or the language changes while the palette is open (`palette::search` tests `a_better_word_grade_ranks_first`, `a_better_whole_query_tier_ranks_first`, `kind_and_length_never_lift_a_worse_grade`, `a_menu_title_does_not_lift_its_items`, `common_queries_list_the_command_near_the_top`, `every_result_is_found_first_by_its_name_and_its_id`, `every_result_found_before_is_still_found_and_shown`, `results_know_their_place_in_the_menu_bar`, `native_homes_follow_the_native_application_menu`; `palette` test `the_highlight_stays_on_its_result_when_the_results_change`). A Command Palette query word in an English plural or verb form finds a result whose English name or menu path holds the base word: "rounded corners" lists Effect › Stylize › Round Corners… first, and "scaling" finds Object › Transform › Scale…. The search drops `'s`; `es` after `s`, `x`, `z`, `ch` or `sh` (also trying the word with only its `s` dropped, so "rasterizes" finds Rasterize…); a final `s` in words of more than 3 letters, except after `ss`, `us` or `is`; `ing` in words of more than 5 letters and `ed` in words of more than 4. After `ing` or `ed`, a doubled `b`, `d`, `g`, `m`, `n`, `p`, `r` or `t` is tried both single and doubled, the single letter only when at least 3 letters are left ("cutting" meets Cut, "added" meets Add); otherwise the word is also tried with an `e` ("scaling" meets Scale…). It turns `ies` into `y` or `ie` in words of more than 5 letters and `sses` into `ss`, and leaves `series` and `species` as they are. Among results that the whole query matches the same way (as an id, as a label, at the start of a label, as initials, or none of these), a result whose name holds the base word of a query word ranks below one that holds the query word whole and above one where the query word only starts a word of the name, so "scale zz" lists a name with "Zz Scaling" above one with "Zz Scalers". "scale" alone still lists "Scalers" above "Scaling", because "Scalers" starts with the query. A partly typed word that is not itself a word of any result ("scal") does not meet a base word. Names shown in other languages and ids are not changed this way, and every result found before is still found (`palette::search` tests `plurals_and_verb_forms_meet_their_base_word`, `a_plural_or_verb_form_finds_the_result`, `a_better_word_grade_ranks_first`, `a_partly_typed_word_does_not_lift_a_verb_form`, `a_whole_query_tier_comes_before_a_stem_form`, `results_matched_without_a_stem_keep_their_order`). - A Command Palette query word with a typo still finds the result: "gruop" lists Object › Group first, and "eyedroper", "rectange" and "elipse" list the same first results as the words spelled right, the Eyedropper, Rectangle and Ellipse tools among them. When a query word of 4 or more letters is not a word, a base word or the start of a word of any result's name, menu path or id, the search compares it (also when another result matches it through a word with the same meaning, so "spin" finds Span as well as Rotate) with the words of result names and menu paths, and a word 1 edit away (2 for a query word of 8 or more letters) matches; a letter added, left out or changed, or two letters next to each other swapped, is one edit. A query word meets at most the 32 nearest such words. Results matched through a typo come after every result the query matches in its name, menu path or id without one, and before every result the query matches only through its description; among them the query is read with the misspelled word replaced by the word it meets, so they come in the order the word spelled right gives; then a result whose label holds the word comes before one whose menu path holds it. Ids, and query words and result words with Chinese, Japanese or Korean letters, are not compared this way, and matching through a typo does not change the order of the results matched without one (`palette::search` tests `edits_are_counted_up_to_a_bound`, `a_word_with_a_typo_finds_the_result`, `a_typo_meets_at_most_32_words`, `a_word_with_the_same_meaning_elsewhere_still_finds_a_typo`, `a_description_match_ranks_below_a_typo`, `misspelled_words_find_the_command`). + A Command Palette query word with a typo still finds the result: "gruop" lists Object › Group first, and "eyedroper", "rectange" and "elipse" list the same first results as the words spelled right, the Eyedropper, Rectangle and Ellipse tools among them. When a query word of 4 or more letters is not a word, a base word or the start of a word of any result's name, menu path or id, the search compares it (also when another result matches it through a word with the same meaning, so "spin" finds Span as well as Rotate) with the words of result names and menu paths, and a word 1 edit away (2 for a query word of 8 or more letters) matches; a letter added, left out or changed, or two letters next to each other swapped, is one edit. A query word meets at most the 32 nearest such words. Results matched through a typo come after every result the query matches in its name, menu path or id without one, and before every result the query matches only through its description; among them, how the whole query matches is judged with the misspelled word replaced by the word it meets. Results that match it equally then come in this order: a result whose label holds the word before one whose menu path holds it, then by the grades of the other words, and after that as every other result is ordered, so two such results can come in a different order than the word spelled right gives them. Ids, and query words and result words with Chinese, Japanese or Korean letters, are not compared this way, and matching through a typo does not change the order of the results matched without one (`palette::search` tests `edits_are_counted_up_to_a_bound`, `a_word_with_a_typo_finds_the_result`, `a_typo_meets_at_most_32_words`, `a_word_with_the_same_meaning_elsewhere_still_finds_a_typo`, `a_description_match_ranks_below_a_typo`, `misspelled_words_find_the_command`). A Command Palette query word also finds a result whose name or menu path holds a word with the same meaning: "remove bg" lists Remove Background… first, "outline text" lists Type › Create Outlines first, and "flip", "combine", "vectorize" and "colour" list Reflect…, Unite, an Image Trace command and the Color panel among the first 3 results. The words come from VectorCraft's own table of 21 groups of English words (`palette/words.rs`, at most 60 groups of at most 6 words); a word that is the whole label of another command, such as Merge or Mirror, is in no group, and neither is Insert. A word or its English base word that is in a group meets the other words of its group in labels and menu paths, and their base words, but not ids or word starts. A result whose label holds the word itself ranks above one whose label holds a word with the same meaning, which ranks above one whose menu path holds the word, so "type" now lists Scale Text Attributes above Type › Orientation › Vertical. A catalog may add a group's words in its language with a row in the `search` context (the group's English words joined by ", ", then that language's words), used while that language is the UI language; no catalog has to have these rows (`palette::search` tests `a_word_with_the_same_meaning_finds_the_result`, `a_catalog_row_adds_words_to_a_group`, `words_with_the_same_meaning_find_the_command`; `palette::words` tests; `i18n` test `search_rows_name_a_group_and_add_single_words`). The Command Palette ranks the commands listed in Recent Commands first among the results that match a query as well as they do and have the same use grade (described below), the most recent first, and below every result that matches it better: after a pick of Effect › Convert to Shape › Rectangle…, "rect" lists it above the Rectangle Tool unless the Rectangle Tool has the higher use grade, so Enter runs it again. A recent pick ranks after the whole-query match, the word grades, the matches through a typo, a description or a word with the same meaning, and the use grade, and before the kind of result and the name's length. The ranking uses the list Recent Commands shows. This is VectorCraft's own behavior (`palette::search` test `a_recent_pick_ranks_first_within_its_grades`; `palette` tests `a_recent_pick_ranks_first_among_results_that_match_as_well`, `the_kept_ranking_follows_the_recent_picks`). The Command Palette also counts how many times each command is picked and ranks the commands picked most often first among the results that match a query as well as they do, also after they leave Recent Commands, and below every result that matches it better. A pick is counted only when Recent Commands records it, so a refused pick and a pick of Search Commands… are not counted. Counts are compared in grades that double: grade 1 starts at 1 pick, grade 2 at 3, grade 3 at 7, and so on up to grade 9, and a command picked once ranks above the commands never picked. The grade ranks after the word grades and the typo, description and same-meaning matches, and before the place among the recent picks. The count is kept for at most 200 commands: a new command then removes, of the half of the commands picked longest ago, the one with the fewest picks, of those the one picked longest ago. When a count reaches 1,000, every count is halved and commands left at 0 are dropped. The counts are saved with the other interface settings (`command_uses` in `ui.json`); a count above 999 loads as 999 and an unreadable entry is dropped. The web build keeps them for the session. This is VectorCraft's own behavior (`palette::search` test `a_command_picked_often_ranks_first_within_its_grades`; `palette` tests `a_command_picked_often_ranks_first_among_results_that_match_as_well`, `the_kept_ranking_follows_the_pick_counts`, `a_count_does_not_pass_a_better_match`, `pick_counts_rank_in_grades_that_double`, `the_201st_command_removes_the_least_used_and_keeps_itself`, `new_commands_build_up_counts_when_every_counted_one_has_more_picks`, `counts_are_halved_at_one_thousand`, `saved_pick_counts_load_what_is_readable`, `only_a_pick_recorded_in_recent_commands_is_counted`). From a82de18956d5261134899800fcda6cf1cc33cf30 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:14:53 -0800 Subject: [PATCH 26/38] Symbols: in Draw Behind a placed instance goes directly below the selection symbol.place, symbol.placeFromDocument and symbol.addFromLibrary with `place` now read the drawing mode: in Draw Behind the new instance goes directly below the selected object, or at the bottom of the current layer when nothing is selected, as the help page describes for placing symbols (https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html). Place Symbol Instance in the Symbols panel and a symbol dragged onto the canvas from the Symbols panel or a symbol library all go through these commands. VectorCraft's own rules: with several objects selected the instance goes below the bottommost one, a selected path in a compound path puts it beside the compound path, and a clipping path stays at the bottom of its clip group or clipping layer. Draw Normal and Draw Inside keep the instance on top of the current layer, and a locked or hidden layer still refuses it with no edit. --- crates/engine/src/cmd/brushsym.rs | 4 +- crates/engine/src/cmd/brushsym/symbols.rs | 38 ++++++++++++- crates/engine/src/cmd/symbollib.rs | 16 +++--- crates/engine/src/tests/brushsym.rs | 67 +++++++++++++++++++++++ crates/engine/src/tests/symbollib.rs | 42 ++++++++++++++ docs/mcp.md | 8 ++- docs/target-app-parity.md | 2 +- 7 files changed, 162 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index fbd4512fa3..580f2d7a30 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -48,7 +48,7 @@ use dynamic::{symbol_instance_reset, symbol_instance_select_part, symbol_instanc use symbolism::symbol_set_density; use symbols::selected_instances; pub(crate) use symbols::{ - expand_instances_under, expandable_instances, instance_in_place, natural_size, normalize, place_xf, set_natural_size, store_symbol, + Placement, expand_instances_under, expandable_instances, instance_in_place, natural_size, normalize, place_xf, set_natural_size, store_symbol, stored_natural_size, }; use symbols::{ @@ -234,7 +234,7 @@ pub fn specs() -> Vec { "Place Symbol Instance", [], None, - "{name?, x?, y?} place an instance so its registration point is at (x, y) (default: artboard centre; name default: current) → {id}", + "{name?, x?, y?} place an instance so its registration point is at (x, y) (default: artboard centre; name default: current), on top of the current layer, or in Draw Behind directly below the bottommost selected object (at the bottom of the current layer with nothing selected) → {id}", has_doc, symbol_place ), diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 14e52ffe4f..ac85e71de4 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -33,6 +33,40 @@ pub(crate) fn place_xf(at: Point, (w, h): (f64, f64), reg: SymbolRegistration) - Affine::translate(c.to_vec2()) * Affine::scale_non_uniform(w / (2.0 * HALF), h / (2.0 * HALF)) } +/// Where a placed symbol instance goes in the active document, worked out before the edit from +/// the drawing mode, the selection and the layer new art goes into. +pub(crate) struct Placement { + parent: Option, + behind: bool, + anchor: Option, +} + +impl Placement { + /// On top of the layer new art goes into; in Draw Behind, directly below the bottommost + /// selected object (beside the compound path that holds it), or at the bottom of that layer + /// when nothing is selected. An error when that layer is locked or hidden. + pub(crate) fn of(s: &Session) -> Result { + let st = s.doc()?; + let parent = st.target_parent()?; + let behind = s.draw_mode == crate::DrawMode::Behind; + let compound_of = |id: NodeId| st.doc.parent_of(id).filter(|p| st.doc.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))); + let anchor = behind.then(|| st.selection.in_paint_order(&st.doc).first().copied()).flatten().map(|id| compound_of(id).unwrap_or(id)); + Ok(Self { parent, behind, anchor }) + } + + /// Inserts instance `n` where this placement puts it. In a clip group or a clipping layer the + /// clipping path stays at the bottom. + pub(crate) fn insert(&self, d: &mut Document, n: Node) -> Result { + let (parent, index) = match (self.behind, self.anchor.and_then(|a| d.position(a))) { + (false, _) => return Ok(d.insert(self.parent, usize::MAX, n)?), + (true, Some((par, i, _))) => (par, i), + (true, None) => (self.parent, 0), + }; + let floor = usize::from(parent.and_then(|p| d.node(p)).is_some_and(Node::clips)); + Ok(d.insert(parent, index.max(floor), n)?) + } +} + fn registration_param(p: &Value, cmd: &str) -> Result> { match p.get("registration") { None => Ok(None), @@ -437,10 +471,10 @@ pub(super) fn symbol_place(s: &mut Session, p: &Value) -> Result { let at = Point::new(number_or(p, "x", centre.x, "symbol.place")?, number_or(p, "y", centre.y, "symbol.place")?); let size = natural_size(d, &name); let reg = d.symbol_registration(&name); - let parent = s.doc()?.target_parent()?; + let spot = Placement::of(s)?; let id = s.edit("Place Symbol Instance", |d, sel| { let id = d.alloc_id(); - d.insert(parent, usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: name.clone(), xf: place_xf(at, size, reg) }))?; + spot.insert(d, Node::new(id, NodeKind::SymbolInstance { symbol: name.clone(), xf: place_xf(at, size, reg) }))?; sel.set([id]); Ok(id) })?; diff --git a/crates/engine/src/cmd/symbollib.rs b/crates/engine/src/cmd/symbollib.rs index 660e15248c..60db399f42 100644 --- a/crates/engine/src/cmd/symbollib.rs +++ b/crates/engine/src/cmd/symbollib.rs @@ -15,7 +15,7 @@ use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, Symbol, SymbolNineSlice}; use vectorcraft_geom::{Affine, Anchor, AnchorKind, PathData, Point, Rect, SubPath, shapes}; -use super::brushsym::{CURRENT_SYMBOL, natural_size, normalize, place_xf, set_natural_size}; +use super::brushsym::{CURRENT_SYMBOL, Placement, natural_size, normalize, place_xf, set_natural_size}; use super::clipboard::Clipboard; use super::clipboard::resources::SwatchChoices; use super::swatch::str_list; @@ -50,7 +50,7 @@ pub fn specs() -> Vec { "Add to Symbols", ["Window", "Symbol Libraries"], None, - "{library: id or name, name? | names?: [symbol names in the library] (default: all of it), place?: false (also place an instance of the first one, its registration point at x, y: default the first artboard's centre), x?, y?, swatchConflict? (as edit.paste)} copy library symbols into the document's Symbols as one undo step (with the place), with their Symbol Options and the resources they use (the symbols they nest, patterns, swatches, brushes, graphic styles, images). A symbol the document already has (same name and art) isn't added again; a name another symbol has gets a number (\"Star 2\"). The first one becomes the current symbol → {library, names: [each symbol's name in the document], added: [names added], existing: [names already there], placed?: id}", + "{library: id or name, name? | names?: [symbol names in the library] (default: all of it), place?: false (also place an instance of the first one, its registration point at x, y: default the first artboard's centre, in the stacking order symbol.place gives it, Draw Behind included), x?, y?, swatchConflict? (as edit.paste)} copy library symbols into the document's Symbols as one undo step (with the place), with their Symbol Options and the resources they use (the symbols they nest, patterns, swatches, brushes, graphic styles, images). A symbol the document already has (same name and art) isn't added again; a name another symbol has gets a number (\"Star 2\"). The first one becomes the current symbol → {library, names: [each symbol's name in the document], added: [names added], existing: [names already there], placed?: id}", has_doc, add ), @@ -59,7 +59,7 @@ pub fn specs() -> Vec { "Place Symbol Instance", [], None, - "{sourceDocument: uid, name: a symbol of that document, x?, y?} place an instance of a symbol of another open document so its registration point is at (x, y) (default: the first artboard's center), as a symbol dragged from that document's Symbols panel onto the canvas is placed. The symbol, the symbols it nests and the resources they use are added as a drop of art from that document adds them, in the same undo step as the instance: a symbol the active document already has with the same name, art and Symbol Options is used, and one with the same name but other art or Symbol Options gets a number (\"Leaf 2\"); each symbol added takes its Symbol Options along. When sourceDocument is the active document, its own symbol is placed, as symbol.place places it. An error, with no edit, when that document is no longer open or has no symbol `name` → {id, name: the symbol's name in the active document}", + "{sourceDocument: uid, name: a symbol of that document, x?, y?} place an instance of a symbol of another open document so its registration point is at (x, y) (default: the first artboard's center), in the stacking order symbol.place gives it (Draw Behind included), as a symbol dragged from that document's Symbols panel onto the canvas is placed. The symbol, the symbols it nests and the resources they use are added as a drop of art from that document adds them, in the same undo step as the instance: a symbol the active document already has with the same name, art and Symbol Options is used, and one with the same name but other art or Symbol Options gets a number (\"Leaf 2\"); each symbol added takes its Symbol Options along. When sourceDocument is the active document, its own symbol is placed, as symbol.place places it. An error, with no edit, when that document is no longer open or has no symbol `name` → {id, name: the symbol's name in the active document}", has_doc, place_from_document ), @@ -816,7 +816,7 @@ fn add(s: &mut Session, p: &Value) -> Result { let doc_names: Vec = picked.iter().map(|n| target(&imported.renamed, n)).collect(); let centre = st.doc.artboards.first().map(|a| a.rect.center()).unwrap_or(Point::ZERO); let at = if place { Some(Point::new(number_or(p, "x", centre.x, C)?, number_or(p, "y", centre.y, C)?)) } else { None }; - let parent = if place { st.target_parent()? } else { None }; + let spot = if place { Some(Placement::of(s)?) } else { None }; let mut out = json!({ "library": shown_library_id(s, &info.id) }); if imported.added > 0 || place { let placed = s.edit("Add to Symbols", |d, sel| { @@ -830,10 +830,10 @@ fn add(s: &mut Session, p: &Value) -> Result { } let Some(first) = doc_names.first() else { return Ok(None) }; d.unknown.insert(CURRENT_SYMBOL.into(), json!(first)); - let Some(at) = at else { return Ok(None) }; + let (Some(at), Some(spot)) = (at, &spot) else { return Ok(None) }; let xf = place_xf(at, natural_size(d, first), d.symbol_registration(first)); let id = d.alloc_id(); - d.insert(parent, usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: first.clone(), xf }))?; + spot.insert(d, Node::new(id, NodeKind::SymbolInstance { symbol: first.clone(), xf }))?; sel.set([id]); Ok(Some(id)) })?; @@ -860,7 +860,7 @@ fn place_from_document(s: &mut Session, p: &Value) -> Result { let st = s.doc()?; let centre = st.doc.artboards.first().map(|a| a.rect.center()).unwrap_or(Point::ZERO); let at = Point::new(number_or(p, "x", centre.x, C)?, number_or(p, "y", centre.y, C)?); - let parent = st.target_parent()?; + let spot = Placement::of(s)?; let same = uid == st.uid; let src = s.documents().iter().find(|d| d.uid == uid).map(|d| Arc::clone(&d.doc)); let src = src.ok_or_else(|| bad(C, "the document the symbol came from is no longer open"))?; @@ -883,7 +883,7 @@ fn place_from_document(s: &mut Session, p: &Value) -> Result { }; let xf = place_xf(at, natural_size(d, &placed), d.symbol_registration(&placed)); let id = d.alloc_id(); - d.insert(parent, usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: placed.clone(), xf }))?; + spot.insert(d, Node::new(id, NodeKind::SymbolInstance { symbol: placed.clone(), xf }))?; sel.set([id]); Ok((id, placed)) })?; diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index 1d53214ec9..62b1bac629 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -2228,6 +2228,73 @@ fn place_and_break_link_round_trip_geometry() { assert_eq!(n.appearance.stroke_width(), 1.0, "strokes are not scaled by normalisation"); } +/// In Draw Behind, Place Symbol Instance puts the instance directly below the bottommost selected +/// object (beside the compound path that holds a selected path, above a clipping path), or at the +/// bottom of the current layer with nothing selected, selected and in one undo step. Draw Normal +/// and Draw Inside keep it on top, and a locked layer refuses it with no edit. +#[test] +fn placed_instances_go_below_the_selection_in_draw_behind() { + let mut s = session(); + let (inst, name, _) = make_symbol(&mut s); + let (a, b) = (rect(&mut s, 0.0, 0.0, 10.0, 10.0), rect(&mut s, 20.0, 0.0, 10.0, 10.0)); + let layer = s.doc().unwrap().doc.layers[0].id; + let kids = |s: &Session, id: NodeId| node(s, id).children().unwrap().iter().map(|c| c.id).collect::>(); + let place = |s: &mut Session| NodeId(s.execute("symbol.place", &json!({"name": name, "x": 300, "y": 200})).unwrap()["id"].as_u64().unwrap()); + s.execute("view.drawMode", &json!({"mode": "behind"})).unwrap(); + select(&mut s, &[b]); + let before = undo_len(&s); + let p = place(&mut s); + assert_eq!(kids(&s, layer), vec![inst, a, p, b], "directly below the selected object"); + assert_eq!(undo_len(&s), before + 1); + assert_eq!(s.doc().unwrap().selection.objects, [p]); + assert!(close(bounds(&s, p), Rect::new(260.0, 180.0, 340.0, 220.0), 1e-9), "{:?}", bounds(&s, p)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(kids(&s, layer), vec![inst, a, b]); + // Below the bottommost of several selected objects. + select(&mut s, &[b, a]); + let p = place(&mut s); + assert_eq!(kids(&s, layer), vec![inst, p, a, b]); + s.execute("edit.undo", &json!({})).unwrap(); + // With nothing selected, at the bottom of the current layer. + select(&mut s, &[]); + let p = place(&mut s); + assert_eq!(kids(&s, layer), vec![p, inst, a, b]); + s.execute("edit.undo", &json!({})).unwrap(); + // A path selected in a compound path: beside the compound path, not inside it. + select(&mut s, &[a, b]); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let compound = kids(&s, layer)[1]; + let member = kids(&s, compound)[1]; + select(&mut s, &[member]); + let p = place(&mut s); + assert_eq!(kids(&s, layer), vec![inst, p, compound]); + assert_eq!(kids(&s, compound).len(), 2); + s.execute("edit.undo", &json!({})).unwrap(); + // Draw Normal and Draw Inside put it on top of the layer. + for mode in ["normal", "inside"] { + select(&mut s, &[compound]); + s.execute("view.drawMode", &json!({"mode": mode})).unwrap(); + let p = place(&mut s); + assert_eq!(kids(&s, layer), vec![inst, compound, p], "{mode}"); + s.execute("edit.undo", &json!({})).unwrap(); + } + // In a clipping layer the clipping path stays at the bottom, the selected clipping path too. + s.execute("view.drawMode", &json!({"mode": "behind"})).unwrap(); + s.execute("layer.clippingMask.toggle", &json!({"id": layer.0})).unwrap(); + assert_eq!(kids(&s, layer), vec![compound, inst]); + for picked in [&[][..], &[compound]] { + select(&mut s, picked); + let p = place(&mut s); + assert_eq!(kids(&s, layer), vec![compound, p, inst], "{picked:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + } + // A locked layer takes nothing. + s.execute("layer.setProps", &json!({"id": layer.0, "locked": true})).unwrap(); + let before = (undo_len(&s), s.doc().unwrap().doc.clone()); + assert!(s.execute("symbol.place", &json!({"name": name})).is_err()); + assert_eq!((undo_len(&s), &s.doc().unwrap().doc), (before.0, &before.1)); +} + #[test] fn hidden_instance_fill_does_not_tint_expanded_symbol_art() { for command in ["symbol.breakLink", "object.expand"] { diff --git a/crates/engine/src/tests/symbollib.rs b/crates/engine/src/tests/symbollib.rs index de7f938f78..19d2333b6e 100644 --- a/crates/engine/src/tests/symbollib.rs +++ b/crates/engine/src/tests/symbollib.rs @@ -514,3 +514,45 @@ fn another_documents_symbol_is_added_and_placed_in_one_step() { let e = s.execute("symbol.placeFromDocument", &json!({"sourceDocument": source, "name": "Star"})).unwrap_err(); assert!(e.to_string().contains("no longer open"), "{e}"); } + +/// A symbol dragged onto the canvas, from another document's Symbols panel or from a symbol +/// library, is stacked as Place Symbol Instance stacks it: in Draw Behind directly below the +/// selected object, or at the bottom of the current layer with nothing selected, in one undo step +/// with the symbol it adds. A locked layer refuses it with no edit. +#[test] +fn dropped_symbols_go_below_the_selection_in_draw_behind() { + let mut s = kit(); + let source = s.doc().unwrap().uid; + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let rect = + |s: &mut Session, x: f64| NodeId(run(s, "shape.rectangle", json!({"x": x, "y": 0, "width": 10, "height": 10}))["id"].as_u64().unwrap()); + let (a, b) = (rect(&mut s, 0.0), rect(&mut s, 20.0)); + let layer = doc(&s).layers[0].id; + let kids = |s: &Session| doc(s).node(layer).unwrap().children().unwrap().iter().map(|c| c.id).collect::>(); + run(&mut s, "view.drawMode", json!({"mode": "behind"})); + let drops = [ + ("symbol.placeFromDocument", json!({"sourceDocument": source, "name": "Badge", "x": 30, "y": 40}), "id"), + ("symbol.addFromLibrary", json!({"library": "basic shapes", "name": "Square", "place": true, "x": 30, "y": 40}), "placed"), + ]; + for (cmd, p, key) in &drops { + for (picked, at) in [(vec![b], 1), (vec![], 0)] { + run(&mut s, "select.set", json!({"ids": picked.iter().map(|i| i.0).collect::>()})); + let before = undo_len(&s); + let placed = NodeId(run(&mut s, cmd, p.clone())[*key].as_u64().unwrap()); + let mut want = vec![a, b]; + want.insert(at, placed); + assert_eq!(kids(&s), want, "{cmd} {picked:?}"); + assert_eq!(undo_len(&s), before + 1, "{cmd}"); + assert_eq!(s.doc().unwrap().selection.objects, [placed]); + run(&mut s, "edit.undo", json!({})); + assert!(symbols(&s).is_empty(), "{cmd}: the undo takes the added symbol too"); + } + } + // A locked layer takes nothing. + run(&mut s, "layer.setProps", json!({"id": layer.0, "locked": true})); + let before = (undo_len(&s), doc(&s).clone()); + for (cmd, p, _) in &drops { + assert!(s.execute(cmd, p).is_err(), "{cmd}"); + assert_eq!((undo_len(&s), doc(&s)), (before.0, &before.1), "{cmd}"); + } +} diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..4bc570f99b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3885,7 +3885,10 @@ already walks Image Trace. Short agent entry points: art, where it is, snaps the art again after it is edited, and does not count instances in `select.object.notAlignedToPixelGrid`; `alignToPixelGrid` alone with the value the symbol already has adds no undo step), - `symbol.place {name?, x?, y?}`, `symbol.placeFromDocument {sourceDocument, name, x?, y?}` (an instance of a symbol + `symbol.place {name?, x?, y?}` (on top of the current layer; in Draw Behind directly below the bottommost selected + object, beside the compound path that holds it, or at the bottom of the current layer with nothing selected, above + a clipping path; `symbol.placeFromDocument` and `symbol.addFromLibrary` with `place` stack the instance the same + way), `symbol.placeFromDocument {sourceDocument, name, x?, y?}` (an instance of a symbol of another open document, as a symbol dragged from that document's Symbols panel onto the canvas places it: the symbol, the symbols it nests and the resources they use are added as `edit.dropSelection` adds them, in the same undo step, and a symbol with the same name but other art or Symbol Options is added under a free name; an error @@ -9132,7 +9135,8 @@ undo step. When a matched layer, or a layer around it, is hidden or locked, the Drawing modes (`view.drawMode`) apply too: in Draw Inside, `edit.paste`, `edit.pasteInPlace` and `edit.pasteOnAllArtboards` put the objects inside the object drawn into (its clip group, made on the first paste), whatever Paste Remembers Layers says; in Draw Behind, -`edit.pasteInPlace` and `edit.pasteOnAllArtboards` put them just below the selection. `edit.pasteInFront` and +`edit.pasteInPlace` and `edit.pasteOnAllArtboards` put them just below the selection, and a placed symbol instance +(`symbol.place`) goes just below the selection too. `edit.pasteInFront` and `edit.pasteInBack` ignore the drawing mode. When the object drawn into is the one isolation mode isolates (`object.isolate`, or a double-click on it with the Selection tool), art drawn or pasted inside it takes isolation mode into its clip group, so the new art can be picked and isn't dimmed; `edit.undo` or `edit.redo` that removes the isolated object ends diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 57ac87a396..9fa3b6635b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1421,7 +1421,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Compound paths:** Make keeps the backmost object's appearance and each contour; selecting a member in Direct Selection reads and changes the compound's fill rule in Attributes. Direction remains a per-member edit. Rendered holes, unchanged contour geometry, no-op history and Undo/Redo are covered by `engine/tests/it/compound_attributes.rs` (#1197). Behaviour reference: [public compound-path documentation](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/create-compound-paths.html). Make Compound Path on a group (such as outlined type) keeps the paint of its backmost path instead of drawing nothing, and compound paths joined into one keep their holes (#1537). - **Saved selections:** Select ▸ Save Selection… asks for a name and keeps the selection in the document (saved with the file, undoable, up to 25); each one is listed at the bottom of the Select menu and a click selects its objects again; Edit Selection… lists them to rename or delete, applied together on OK. A file's saved selections are capped and checked against its objects when it opens. Select ▸ Update Selection replaces the objects of the saved selection last recalled with the selected objects, in one undo step that marks the document changed (`select.update`). After Edit Selection… renames that saved selection, Update Selection replaces it under the new name; after Edit Selection… deletes it, Update Selection is disabled until another saved selection is recalled or the delete is undone. Undo and Redo do not change which saved selection is recalled. - - **Drawing modes:** in Draw Inside, a double-click with a selection tool outside the object being drawn into sets the drawing mode to Draw Normal, as Shift+D does. Pastes follow the drawing mode ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) (#3705): in Draw Inside, Paste, Paste in Place and Paste on All Artboards put the copies inside the object drawn into, in one undo step, Paste Remembers Layers aside; in Draw Behind, Paste in Place and Paste on All Artboards put them just below the selection; Paste in Front and Paste in Back ignore the mode. Shift+D cycles Draw Normal → Draw Behind → Draw Inside → Draw Normal, skipping Draw Inside unless one path, compound path or type is selected. With the object drawn into isolated (a double-click on it with the Selection tool), art drawn or pasted inside it takes isolation mode into its clip group, so it can be clicked and isn't dimmed, as art added in isolation mode belongs with what is isolated ([isolation mode](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html)) (#3705); undo or redo that removes the isolated object ends isolation mode. While Draw Inside lasts, a dotted open rectangle marks the corners of the object drawn into (#4319). In Draw Behind, New Layer (the Layers panel's button, its menu, Ctrl/Cmd+L and the Layer Options dialog) puts the new layer directly below the current layer, at its level, as [the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=234) describes and [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) lists; Ctrl/Cmd-click still puts it on top and Ctrl/Cmd+Alt-click below, and New Sublayer is not affected (VectorCraft's own rule). + - **Drawing modes:** in Draw Inside, a double-click with a selection tool outside the object being drawn into sets the drawing mode to Draw Normal, as Shift+D does. Pastes follow the drawing mode ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) (#3705): in Draw Inside, Paste, Paste in Place and Paste on All Artboards put the copies inside the object drawn into, in one undo step, Paste Remembers Layers aside; in Draw Behind, Paste in Place and Paste on All Artboards put them just below the selection; Paste in Front and Paste in Back ignore the mode. Shift+D cycles Draw Normal → Draw Behind → Draw Inside → Draw Normal, skipping Draw Inside unless one path, compound path or type is selected. With the object drawn into isolated (a double-click on it with the Selection tool), art drawn or pasted inside it takes isolation mode into its clip group, so it can be clicked and isn't dimmed, as art added in isolation mode belongs with what is isolated ([isolation mode](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html)) (#3705); undo or redo that removes the isolated object ends isolation mode. While Draw Inside lasts, a dotted open rectangle marks the corners of the object drawn into (#4319). In Draw Behind, New Layer (the Layers panel's button, its menu, Ctrl/Cmd+L and the Layer Options dialog) puts the new layer directly below the current layer, at its level, as [the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=234) describes and [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) lists; Ctrl/Cmd-click still puts it on top and Ctrl/Cmd+Alt-click below, and New Sublayer is not affected (VectorCraft's own rule). In Draw Behind, a placed symbol instance (Place Symbol Instance in the Symbols panel, and a symbol dragged onto the canvas from the Symbols panel or a symbol library) goes directly below the selected object, or at the bottom of the current layer with nothing selected, as [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) describes for placing symbols; below the bottommost of several selected objects, beside the compound path that holds a selected path, and above a clipping path are VectorCraft's own rules. Draw Normal and Draw Inside keep it on top of the current layer. - **Drawing:** Pen, Curvature, anchor tools, Pencil, Paintbrush, Blob Brush, Smooth, Path Eraser, Join. Direction handles dragged with Direct Selection or the Anchor Point tool snap to smart guides, and Shift keeps them at 45° steps from their anchor. The Pen continues any open path from the end clicked, and while drawing, a click on an end of another open path joins the two into one (#776). The Curvature tool edits any selected path, whatever drew it, keeping its shape except where edited (#798): a click on a point makes it current and a drag moves it, re-curving only its two segments; double-click, or Alt-click on any point but an end of an open path, toggles it smooth or corner and Delete removes it; a click on a segment adds a point without changing the shape; with an end of an open path current, clicks go on from it and its other end closes it (`path.curvatureEdit`). An Alt-click on an end of a selected open path makes that end current without changing it, so the next click goes on from it, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-shapes-with-the-curvature-tool.html) describes for continuing a path; an Alt-click that starts a new path places a corner point, as later Alt-clicks do. Every point a drawing tool places snaps to Smart Guides through one snapper (#506): the Pen's and Curvature tool's anchors, the Pencil's ends, the shape tools' start and dragged corner or radius (Rectangle, Rounded Rectangle, Ellipse, Polygon, Star, Line Segment, Arc, Spiral, the grids), the Type tool's click and frame, a new artboard's corners. A filled Pencil path keeps a stroke of None (#1804, part of #1679). While a Pencil or Paintbrush stroke is drawn back to within Close Paths When Ends Are Within of its start, the cursor shows the closing ring and a release there closes the path, as [Draw straight lines with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-straight-lines-with-the-pencil-tool.html) describes for the Pencil. The [ and ] keys reach the Blob Brush, the Eraser and the Symbolism tools in the app (#1734, part of #1661). Blob Brush and Eraser Tool Options' Size is Fixed or Pressure with a Variation (#4590, #3961): with Pressure a pen stroke is Size − Variation wide where it presses lightest and Size + Variation where it presses hardest, and a mouse stroke keeps the Size. `path.blob` and `path.eraseRegion` refuse a Size outside 0.1 to 1000 pt and a Variation outside 0 to 1000 pt, also with Size set to Fixed, and the drawing commands that read pen values refuse a pressure outside 0 to 1, a tilt outside −90° to 90°, a rotation outside 0° to 360° and a point array of more than six numbers, with an error naming the key; the document, the selection and the undo history stay as they were. The pressure and tilt ranges are those of [Pointer Events](https://www.w3.org/TR/pointerevents3/); the Size, Variation and rotation ranges are VectorCraft's own values (`tests::draw2::pen_values_outside_their_ranges_are_refused`). From 5ca427ff2d09df4573c510798d0e165074aaf1ba Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:15:06 -0800 Subject: [PATCH 27/38] Dimension: a guide member of a compound path does not hold a preview-bounds corner With Use Preview Bounds on, the member of a stroked compound path whose own box reaches nearest a corner holds the Linear point placed there. A visible, unlocked member made into a guide could hold it, so the dimension was linked to the guide, although paths made into guides give no corners. A guide member now gives no corner, as a hidden or locked member does. --- crates/tools/src/dimension.rs | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index 5e2e179bdf..b9ac881910 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -313,12 +313,12 @@ fn preview_corner(cx: &ToolContext, p: Point, cache: &mut PreviewBoxes) -> Optio } // The path whose own box reaches furthest towards the corner holds it: in a // compound path, the member that puts that corner where it is. A hidden or - // locked member gives no corner. + // locked member, or one made into a guide, gives no corner. let mut holder: Option<(f64, NodeId, bool)> = None; for m in members() { let Some(b) = *w.cache.geometric.entry(m.id).or_insert_with(|| m.geometric_bounds()) else { continue }; let gap = corners(b).get(k).map_or(f64::INFINITY, |c| c.distance(q)); - let editable = m.visible && !m.locked; + let editable = m.visible && !m.locked && !m.is_guide(); if holder.is_none_or(|(near, _, was)| gap < near || (gap == near && editable && !was)) { holder = Some((gap, m.id, editable)); } @@ -1781,6 +1781,23 @@ mod tests { let (q, _) = t.snap_linear(&c, Point::new(81.0, 81.0)); assert!(!near(q, Point::new(80.0, 80.0)) && t.corner.is_none(), "{kind}: {q:?}"); } + // A visible, unlocked member of a stroked compound path made into a guide does not hold + // the corner its box puts there. + let mut d = vectorcraft_doc::Document::new(500.0, 500.0); + let (l, hole, part, whole) = (d.layers[0].id, d.alloc_id(), d.alloc_id(), d.alloc_id()); + let mut guide = Node::path(part, vectorcraft_geom::shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0)), Default::default()); + if let NodeKind::Path { guide, .. } = &mut guide.kind { + *guide = true; + } + let small = Node::path(hole, vectorcraft_geom::shapes::rectangle(Rect::new(140.0, 140.0, 160.0, 160.0)), Default::default()); + let mut n = + Node::new(whole, NodeKind::Compound { children: vec![std::sync::Arc::new(small), std::sync::Arc::new(guide)], rule: Default::default() }); + n.appearance = vectorcraft_doc::Appearance::default_art().into(); + d.insert(Some(l), 0, n).expect("the compound path"); + let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) }; + let mut t = DimensionTool::default(); + let (q, _) = t.snap_linear(&c, Point::new(99.6, 99.6)); + assert!(t.corner.is_none() && !near(q, Point::new(99.5, 99.5)), "{q:?} {:?}", t.corner); // Two stroked rectangles sharing the edge x = 200; the right one is on top. let (mut d, left) = doc_with_rect(); let (l, right) = (d.layers[0].id, d.alloc_id()); From ef9d6022400e36b44a03f2faec93f318ce54b41d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:16:47 -0800 Subject: [PATCH 28/38] Docs: name the clipping path tolerance and the distorted image case on Update Links A clipping path counts as changed in the document when an anchor or handle moves by a thousandth of a point or more, and links.update leaves a distorted image's clipping as it is. --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0efd8dffc7..2374e8c0aa 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2321,7 +2321,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - BMP files named `.dib` or `.rle` (run-length encoded bitmaps included), Photoshop files named `.pdd` and PNG files named `.pns` open and place, linked or embedded, as BMP, PSD and PNG files, in any letter case: the Open and Place dialogs list them with their format, the Links panel names their format, and Edit Original opens them. Exports write only `.bmp`, `.psd` and `.png` (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/links.rs`). - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer, merging a layer that uses a Knockout option with the layers below it, and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), a Knockout value of 1 is read as a shallow knockout and applied to a layer or group inside a group, which is merged with the visible layers below it in that group (its pixels clear them to transparency, it is drawn there at its fill opacity, and its opacity fades the result; in a pass-through group only when it and the visible layers below it are in the Normal mode; a knockout at 0 opacity, or at 0 fill where it covers none of their painted pixels, isn't merged for the knockout), and adjustment layers, layer effects, vector masks and the other knockouts (top-level layers, clipped layers, layers that others are clipped to, pass-through groups with layers in other modes, other Knockout values, and merges that need more memory than allowed) aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - File › Open of a PSD or PSB file with two or more layers, and File › Place of one without Link, show PSD Import Options: Convert Layers to Objects with Import Hidden Layers, or Flatten Layers to a Single Image, the options [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded. A file placed with Link shows its flat image and isn't asked about. `file.place` takes `layers` and `hiddenLayers`, and `document.psdInfo` counts a file's layers without opening it. VectorCraft's own rules: placed layers come in as one group named after the file, a layer as an image and a layer group as a group, at the place the merged image would take and clipped to the canvas when layers reach past it; the dialog asks from two layers up and starts from the choices made last. Layer comps aren't read (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). - - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none. When Placement Options do not clip the image, a clip group whose clipping path was changed in the document (its anchors, whether it is closed, or its fill rule) and a clipping mask made in the document are kept: a new file that names no clipping path leaves the mask clipping the image, and the clip group of a new file that names one goes inside the mask. Files that name no clipping path come in as before. `links.unembed` keeps the clip group, and the PNG or TIFF it writes is read with the path on File › Open, File › Place, `links.relink` and `links.update` (`crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/dcs.rs`). + - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none; `links.update` leaves a distorted image's clipping as it is. When Placement Options do not clip the image, a clip group whose clipping path was changed in the document (an anchor or handle moved by a thousandth of a point or more, anchors added or removed, a subpath opened or closed, or its fill rule changed) and a clipping mask made in the document are kept: a new file that names no clipping path leaves the mask clipping the image, and the clip group of a new file that names one goes inside the mask. Files that name no clipping path come in as before. `links.unembed` keeps the clip group, and the PNG or TIFF it writes is read with the path on File › Open, File › Place, `links.relink` and `links.update` (`crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/dcs.rs`). - Import Slices: File › Open of a PSD or PSB file with slices, and File › Place of one without Link, bring its slices in as user slices, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded; PSD Import Options offers Import Slices for such a file. `document.open` and `file.place` take `importSlices`, and `document.psdInfo` counts the slices. The slices are read from image resource 1050 in version 6 and in the descriptor of versions 7 and 8, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it. VectorCraft's own rules: Import Slices applies to Convert Layers to Objects and to Flatten Layers to a Single Image alike, and makes the dialog ask for a file with fewer than two layers; placed slices move and scale with the art in the same undo step; each slice keeps its name, type, link, target, message, alternative text, cell text and background color; slices the file generated automatically, and slices wholly outside the canvas, are left out; slices that can't be read are left out with a warning while the art comes in; with Show Import Options off, a PSD file is placed with the PSD Import Options chosen last, and on, each PSD file of the place cursor asks for them (`crates/engine/src/cmd/fileio/tests_psdslices.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). The import fuzz tests open, count and place PSD files whose resource 1050 is in version 6 (with a version 16 descriptor after a record) and in the descriptors of versions 7 and 8, with their data mutated, cut short with the resource's length saying so, and cut short in the file; a slice count past 10,000 or past the slices stored, and data one byte short, bring the art in without its slices and with a warning. `tests_psdslices::damaged_slices_never_panic` now fails when a command reports an internal error (`import_fuzz::the_sliced_psd_samples_bring_in_their_user_slices`, `import_fuzz::sliced_psd_samples_with_huge_counts_or_cut_short_come_in_without_their_slices`, `import_fuzz::mutated_psd_slices_never_panic`). Scores and estimates unchanged. - PSD export writes slices: the user and object slices that reach into the exported artboard go into image resource 1050 in version 6, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it and as Import Slices reads it, so an opened PSD file's slices survive its export. VectorCraft's own rules: slices are written with Write Layers and as a flat image alike, clipped to the artboard in its pixels; an object slice is written as a user slice over its object's bounds, and an HTML Text slice as No Image with its type's text; auto slices are left out and laid out again on open; text alignment is written as the default (`crates/render/src/encode/tests_psd.rs`, `crates/engine/src/cmd/fileio/tests_psdslices.rs`). From 4051d6c9cae7cbda120047cdadf9f2375a142fc8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:17:45 -0800 Subject: [PATCH 29/38] Command Palette: docs state the order for two typo words With more than one query word matched through a typo, a result whose label holds every such word comes first, and then the other words' grades and how many such words the menu path holds decide. Two results that hold the two words in label and menu path the other way round tie on these grades. --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 8e7a28bc6c..d3038ee060 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1588,7 +1588,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A modal window that opens without a press in the window (a dialog opened from the macOS menu bar or by an automation command, the About window, a file dialog, the update prompt, or the progress window of a plug-in, trace or open run) closes the Command Palette, a tool group's flyout, the All Tools drawer and any open menu or popup in the pass it opens. While such a window is open, the palette stays closed, so opening it from the macOS menu bar or by an automation command does not take the keyboard from the window; it opens again once the window closes (`palette` tests `a_dialog_opened_from_the_system_menu_closes_the_palette`, `the_about_window_closes_the_palette`, `a_progress_window_closes_the_palette`, `the_palette_opened_over_a_dialog_closes`, `a_click_on_the_menu_bar_closes_the_palette_before_a_dialog_opens`, `a_dialog_opened_without_a_press_closes_a_flyout`, `a_dialog_opened_without_a_press_closes_the_tools_drawer`, `a_dialog_opened_without_a_press_closes_a_menu`, `the_palette_opened_as_a_dialog_closes_stays_open_until_the_next_dialog`). The Command Palette ranks its results by how well they match. A query that is a result's id lists that result first (`view.goto1` lists Saved View 1 above Saved View 10); then come results whose name is the query, results whose name without its menu path starts with it, and results whose initials it is ("ea" finds Export As…). Within each of those, a result where every word of the query is a whole word of its name ranks above one where a word only starts a word of the name, then one where it is a word of the menu that holds it, then of its id, then text inside a word, so a query that is a menu's title ("object") lists results named with that word above the items of that menu. A tool ranks above a menu command, panel, effect or filter plug-in that matches as well, so "rect" lists the Rectangle Tool above Effect › Convert to Shape › Rectangle…, and of two results of the same kind the shorter name comes first. Words of the menu bar item that runs a result also find it, the item's own label included ("exit" finds Quit VectorCraft, which File › Exit runs); with the native macOS menu bar, the items that bar moves into its application menu are found under it (Preferences… under Settings). Every result the earlier search found is still found, and the highlight stays on its result when a plug-in is installed, a shortcut changes or the language changes while the palette is open (`palette::search` tests `a_better_word_grade_ranks_first`, `a_better_whole_query_tier_ranks_first`, `kind_and_length_never_lift_a_worse_grade`, `a_menu_title_does_not_lift_its_items`, `common_queries_list_the_command_near_the_top`, `every_result_is_found_first_by_its_name_and_its_id`, `every_result_found_before_is_still_found_and_shown`, `results_know_their_place_in_the_menu_bar`, `native_homes_follow_the_native_application_menu`; `palette` test `the_highlight_stays_on_its_result_when_the_results_change`). A Command Palette query word in an English plural or verb form finds a result whose English name or menu path holds the base word: "rounded corners" lists Effect › Stylize › Round Corners… first, and "scaling" finds Object › Transform › Scale…. The search drops `'s`; `es` after `s`, `x`, `z`, `ch` or `sh` (also trying the word with only its `s` dropped, so "rasterizes" finds Rasterize…); a final `s` in words of more than 3 letters, except after `ss`, `us` or `is`; `ing` in words of more than 5 letters and `ed` in words of more than 4. After `ing` or `ed`, a doubled `b`, `d`, `g`, `m`, `n`, `p`, `r` or `t` is tried both single and doubled, the single letter only when at least 3 letters are left ("cutting" meets Cut, "added" meets Add); otherwise the word is also tried with an `e` ("scaling" meets Scale…). It turns `ies` into `y` or `ie` in words of more than 5 letters and `sses` into `ss`, and leaves `series` and `species` as they are. Among results that the whole query matches the same way (as an id, as a label, at the start of a label, as initials, or none of these), a result whose name holds the base word of a query word ranks below one that holds the query word whole and above one where the query word only starts a word of the name, so "scale zz" lists a name with "Zz Scaling" above one with "Zz Scalers". "scale" alone still lists "Scalers" above "Scaling", because "Scalers" starts with the query. A partly typed word that is not itself a word of any result ("scal") does not meet a base word. Names shown in other languages and ids are not changed this way, and every result found before is still found (`palette::search` tests `plurals_and_verb_forms_meet_their_base_word`, `a_plural_or_verb_form_finds_the_result`, `a_better_word_grade_ranks_first`, `a_partly_typed_word_does_not_lift_a_verb_form`, `a_whole_query_tier_comes_before_a_stem_form`, `results_matched_without_a_stem_keep_their_order`). - A Command Palette query word with a typo still finds the result: "gruop" lists Object › Group first, and "eyedroper", "rectange" and "elipse" list the same first results as the words spelled right, the Eyedropper, Rectangle and Ellipse tools among them. When a query word of 4 or more letters is not a word, a base word or the start of a word of any result's name, menu path or id, the search compares it (also when another result matches it through a word with the same meaning, so "spin" finds Span as well as Rotate) with the words of result names and menu paths, and a word 1 edit away (2 for a query word of 8 or more letters) matches; a letter added, left out or changed, or two letters next to each other swapped, is one edit. A query word meets at most the 32 nearest such words. Results matched through a typo come after every result the query matches in its name, menu path or id without one, and before every result the query matches only through its description; among them, how the whole query matches is judged with the misspelled word replaced by the word it meets. Results that match it equally then come in this order: a result whose label holds the word before one whose menu path holds it, then by the grades of the other words, and after that as every other result is ordered, so two such results can come in a different order than the word spelled right gives them. Ids, and query words and result words with Chinese, Japanese or Korean letters, are not compared this way, and matching through a typo does not change the order of the results matched without one (`palette::search` tests `edits_are_counted_up_to_a_bound`, `a_word_with_a_typo_finds_the_result`, `a_typo_meets_at_most_32_words`, `a_word_with_the_same_meaning_elsewhere_still_finds_a_typo`, `a_description_match_ranks_below_a_typo`, `misspelled_words_find_the_command`). + A Command Palette query word with a typo still finds the result: "gruop" lists Object › Group first, and "eyedroper", "rectange" and "elipse" list the same first results as the words spelled right, the Eyedropper, Rectangle and Ellipse tools among them. When a query word of 4 or more letters is not a word, a base word or the start of a word of any result's name, menu path or id, the search compares it (also when another result matches it through a word with the same meaning, so "spin" finds Span as well as Rotate) with the words of result names and menu paths, and a word 1 edit away (2 for a query word of 8 or more letters) matches; a letter added, left out or changed, or two letters next to each other swapped, is one edit. A query word meets at most the 32 nearest such words. Results matched through a typo come after every result the query matches in its name, menu path or id without one, and before every result the query matches only through its description; among them, how the whole query matches is judged with the misspelled word replaced by the word it meets. Results that match it equally then come in this order: a result whose label holds every word matched through a typo before one whose menu path holds such a word, then by the grades of the other words and how many such words the menu path holds, and after that as every other result is ordered, so two such results can come in a different order than the words spelled right give them. With two words matched through typos, a result whose label holds one and whose menu path holds the other ties on these grades with a result that holds them the other way round. Ids, and query words and result words with Chinese, Japanese or Korean letters, are not compared this way, and matching through a typo does not change the order of the results matched without one (`palette::search` tests `edits_are_counted_up_to_a_bound`, `a_word_with_a_typo_finds_the_result`, `a_typo_meets_at_most_32_words`, `a_word_with_the_same_meaning_elsewhere_still_finds_a_typo`, `a_description_match_ranks_below_a_typo`, `misspelled_words_find_the_command`). A Command Palette query word also finds a result whose name or menu path holds a word with the same meaning: "remove bg" lists Remove Background… first, "outline text" lists Type › Create Outlines first, and "flip", "combine", "vectorize" and "colour" list Reflect…, Unite, an Image Trace command and the Color panel among the first 3 results. The words come from VectorCraft's own table of 21 groups of English words (`palette/words.rs`, at most 60 groups of at most 6 words); a word that is the whole label of another command, such as Merge or Mirror, is in no group, and neither is Insert. A word or its English base word that is in a group meets the other words of its group in labels and menu paths, and their base words, but not ids or word starts. A result whose label holds the word itself ranks above one whose label holds a word with the same meaning, which ranks above one whose menu path holds the word, so "type" now lists Scale Text Attributes above Type › Orientation › Vertical. A catalog may add a group's words in its language with a row in the `search` context (the group's English words joined by ", ", then that language's words), used while that language is the UI language; no catalog has to have these rows (`palette::search` tests `a_word_with_the_same_meaning_finds_the_result`, `a_catalog_row_adds_words_to_a_group`, `words_with_the_same_meaning_find_the_command`; `palette::words` tests; `i18n` test `search_rows_name_a_group_and_add_single_words`). The Command Palette ranks the commands listed in Recent Commands first among the results that match a query as well as they do and have the same use grade (described below), the most recent first, and below every result that matches it better: after a pick of Effect › Convert to Shape › Rectangle…, "rect" lists it above the Rectangle Tool unless the Rectangle Tool has the higher use grade, so Enter runs it again. A recent pick ranks after the whole-query match, the word grades, the matches through a typo, a description or a word with the same meaning, and the use grade, and before the kind of result and the name's length. The ranking uses the list Recent Commands shows. This is VectorCraft's own behavior (`palette::search` test `a_recent_pick_ranks_first_within_its_grades`; `palette` tests `a_recent_pick_ranks_first_among_results_that_match_as_well`, `the_kept_ranking_follows_the_recent_picks`). The Command Palette also counts how many times each command is picked and ranks the commands picked most often first among the results that match a query as well as they do, also after they leave Recent Commands, and below every result that matches it better. A pick is counted only when Recent Commands records it, so a refused pick and a pick of Search Commands… are not counted. Counts are compared in grades that double: grade 1 starts at 1 pick, grade 2 at 3, grade 3 at 7, and so on up to grade 9, and a command picked once ranks above the commands never picked. The grade ranks after the word grades and the typo, description and same-meaning matches, and before the place among the recent picks. The count is kept for at most 200 commands: a new command then removes, of the half of the commands picked longest ago, the one with the fewest picks, of those the one picked longest ago. When a count reaches 1,000, every count is halved and commands left at 0 are dropped. The counts are saved with the other interface settings (`command_uses` in `ui.json`); a count above 999 loads as 999 and an unreadable entry is dropped. The web build keeps them for the session. This is VectorCraft's own behavior (`palette::search` test `a_command_picked_often_ranks_first_within_its_grades`; `palette` tests `a_command_picked_often_ranks_first_among_results_that_match_as_well`, `the_kept_ranking_follows_the_pick_counts`, `a_count_does_not_pass_a_better_match`, `pick_counts_rank_in_grades_that_double`, `the_201st_command_removes_the_least_used_and_keeps_itself`, `new_commands_build_up_counts_when_every_counted_one_has_more_picks`, `counts_are_halved_at_one_thousand`, `saved_pick_counts_load_what_is_readable`, `only_a_pick_recorded_in_recent_commands_is_counted`). From 55611881a4dc26a72f4b77e2ac30408fb0f7de19 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:23:48 -0800 Subject: [PATCH 30/38] Docs: a blurred 3D shadow expands to an image The 3D shadows section of docs/mcp.md said Expand Appearance keeps the shadow as a path. Since #7761 a shadow blurred by the first light's Softness expands to an image; only a hard shadow stays a path, as docs/three-d.md already says. --- docs/mcp.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..6486c31308 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5147,7 +5147,7 @@ art", and a loaded file draws the source path, as it does for a solid past its l documentation names the controls and their ranges ([3D and Materials panel options](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/3d-materials-panel-options.html)). The settings are saved in the native file; SVG and PDF exports draw the shadow, and `effect.expandAppearance` keeps -it as a path. Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic) have no shadow. See [three-d.md](three-d.md#shadows). +a hard shadow as a path and turns a blurred one into an image. Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic) have no shadow. See [three-d.md](three-d.md#shadows). ```json {"name":"run_command","arguments":{"command":"effect.setParams","params":{"index":0,"item":null,"params":{"shadow":true,"shadowPosition":"below","shadowDistance":10,"shadowBounds":150}}}} From 14e22a1dff2d155b86dd463752b68686ed6771a4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:28:27 -0800 Subject: [PATCH 31/38] Mesh: a Lasso click that deselects also unpicks the mesh points A plain Lasso click away from the art deselects everything but kept the mesh points the tool held, so the Mesh tool chosen next showed the deselected points as picked, nudged them with the arrow keys and recolored them with a fill color. The click now unpicks them. Shift and Alt clicks still change nothing. docs/target-app-parity.md also lists the Eyedropper among the tools that keep the picks, and docs/mcp.md describes the Lasso click. Test: a_lasso_click_that_deselects_unpicks_the_mesh_points in crates/engine/src/tests/mesh_picks.rs. --- crates/engine/src/tests/mesh_picks.rs | 20 ++++++++++++++++++++ crates/tools/src/xform/wand.rs | 7 ++++++- docs/mcp.md | 3 ++- docs/target-app-parity.md | 2 +- 4 files changed, 29 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/tests/mesh_picks.rs b/crates/engine/src/tests/mesh_picks.rs index 0159709fdb..93556481da 100644 --- a/crates/engine/src/tests/mesh_picks.rs +++ b/crates/engine/src/tests/mesh_picks.rs @@ -88,6 +88,26 @@ fn a_tool_that_picks_no_mesh_points_drops_the_picks() { assert_eq!(colors(&s, m), before, "no point is picked"); } +/// A plain Lasso click away from the art deselects it and unpicks the points the Mesh tool picked, +/// so the Mesh tool chosen next has none picked. +#[test] +fn a_lasso_click_that_deselects_unpicks_the_mesh_points() { + let (mut s, m) = mesh_session(); + let v = ViewInfo::default(); + let before = colors(&s, m); + s.select_tool("mesh", v).unwrap(); + press(&mut s, m, 0, Mods::default()); + s.select_tool("lasso", v).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 500.0, 500.0), v).unwrap(); + } + assert!(s.doc().unwrap().selection.objects.is_empty(), "the click deselects the mesh"); + s.execute("select.set", &json!({"ids": [m.0]})).unwrap(); + s.select_tool("mesh", v).unwrap(); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + assert_eq!(colors(&s, m), before, "no point is picked"); +} + /// Direct Selection lent to the Mesh tool for a Cmd-click starts from the Mesh tool's picks, so a /// Shift-click adds to them, and gives back what it left picked. #[test] diff --git a/crates/tools/src/xform/wand.rs b/crates/tools/src/xform/wand.rs index 991f43881c..d6e3192266 100644 --- a/crates/tools/src/xform/wand.rs +++ b/crates/tools/src/xform/wand.rs @@ -145,7 +145,12 @@ impl Tool for LassoTool { let poly = std::mem::take(&mut self.points); let (add, sub) = (ev.mods.shift, ev.mods.alt); if poly.len() < 3 { - return if add || sub { vec![] } else { vec![Action::Exec("select.none".into(), json!({}))] }; + if add || sub { + return vec![]; + } + // The click deselects everything, so no mesh point stays picked. + self.mesh.unfocus(); + return vec![Action::Exec("select.none".into(), json!({}))]; } vec![lasso_select(cx, &mut self.mesh, &poly, add, sub)] } diff --git a/docs/mcp.md b/docs/mcp.md index a2dfff4bfa..f6ffab55d8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -14193,7 +14193,8 @@ moves them all as one undo step (`object.mesh.movePoints`), a click on one of se and the arrow keys nudge them by the keyboard increment. The active tool lists them in its options (`tool.setOption {}` returns them as `meshPoints: [{id, index}…]`). Switching between the Mesh tool, Direct Selection, the Lasso, the Polygonal Lasso and the Eyedropper keeps them picked, and so does a Cmd/Ctrl-click with the selection -tool one of them lends; any other tool, Group Selection included, drops them. The Eyedropper's options list them too. +tool one of them lends; any other tool, Group Selection included, drops them. A plain Lasso click away from the art +(`select.none`) unpicks them. The Eyedropper's options list them too. While a selected, editable mesh has points picked, an Eyedropper click or Shift-click on an image or other art samples the color under the pointer into those points alone as `paint.sampleColor {color, stroke: false, ids}` with the meshes that have points picked: one undo diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 25b0e47a10..baeac9f26a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1905,7 +1905,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Several mesh points at once (#4207, #4208, #4170):** the Mesh tool and Direct Selection pick several points of a gradient mesh or mesh envelope: Shift-click adds a point or takes a picked one away, Direct Selection's marquee picks the points inside it (Shift toggles them) and selects their meshes, and its click on a mesh line picks the line's two ends and one inside a patch the four points around it. The picked points show filled; dragging one moves them all as one undo step and the arrow keys nudge them (`object.mesh.movePoints {id, points, dx, dy}` or `{items, dx, dy}`), and a click on one of several picked points picks it alone. A solid fill colour (`paint.setFill`: Color panel, Swatches, Eyedropper) recolours every picked point, and the Transparency panel's Opacity fades them instead of the object, the panel showing their opacity (blank when it differs); `object.mesh.setPointColor` takes `points` or `items`. Public reference: [Edit mesh objects](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-meshes/edit-mesh-objects.html) (Shift selects multiple mesh points; a fill colour colours the selected point), [Macworld, gradient mesh](https://www.macworld.com/article/202693/gmesh2.html) (Direct Selection: a mesh line selects the points at both ends, a patch the points around it, Shift-click adds or removes points), [Peachpit](https://www.peachpit.com/articles/article.aspx?p=1638270) (each mesh point can have its own colour or transparency). Tests: `shift_clicks_pick_mesh_points_that_drag_and_nudge_together` and `direct_selection_picks_mesh_points_by_marquee_line_and_patch` in `crates/tools/src/meshedit.rs`, `picked_mesh_points_take_the_fill_opacity_and_drag_together` in `crates/engine/src/tests/editcolors.rs`, `mesh_points_move_and_colour_together` in `crates/engine/src/tests/live.rs`. Scores and hours unchanged. - **Picked mesh points in the panels** (VectorCraft's own rule): with points of a gradient mesh picked by the Mesh tool, Direct Selection or the Lasso, the Fill proxy, the Color panel and the Color Wheel show the first picked point's color, so their sliders keep the color a drag sets, and "?" shows when the picked points' colors differ. The Control bar shows the first picked point's opacity. Tests: `the_fill_proxy_shows_the_picked_mesh_points_color`, `the_fill_proxy_follows_where_the_fill_goes_with_an_appearance_row_active` and `the_fill_proxy_counts_picked_mesh_points_beside_other_objects` in `crates/engine/src/tests/xform.rs`, `picked_mesh_points_are_the_color_the_panel_shows_and_edits` in `crates/ui-egui/src/panels/color/tests.rs`, `picking_mesh_points_shows_their_opacity` in `crates/ui-egui/src/panels/transparency.rs`. Scores and hours unchanged. - **The Eyedropper samples into picked mesh points (#8090):** mesh points picked with the Mesh tool, Direct Selection or the Lasso stay picked after switching to the Eyedropper and go back to one of those tools chosen next, and a click or Shift-click on an image or other art then samples the color under the pointer into every picked point as one undo step, leaving the mesh's other points and its appearance as they were. VectorCraft's own rules: a plain click on vector art samples its color into the points instead of copying its appearance, other selected objects keep their paint, and a click on a mesh with points picked works as before. Public references: [Edit mesh objects](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-meshes/edit-mesh-objects.html) (a mesh point is recolored by selecting it and choosing a fill color), [Appearance attributes](https://helpx.adobe.com/illustrator/using/appearance-attributes.html) (Shift-click samples the color from a part of a mesh object or a placed image and applies it to the selected fill). Tests: `picked_mesh_points_take_the_eyedropper_sample` in `crates/engine/src/tests/eyedropper.rs`, `picked_mesh_points_take_the_color_a_click_samples` in `crates/tools/src/xform/eyedropper.rs`, `mesh_point_tools_take_back_the_eyedroppers_picks` in `crates/tools/src/meshedit.rs`. Scores and hours unchanged. -- **Picked mesh points survive a tool switch:** mesh points picked with the Mesh tool, Direct Selection, the Lasso or the Polygonal Lasso stay picked when another of these tools is chosen, and when one of them lends Direct Selection for a Cmd/Ctrl-click, so a fill color chosen afterwards recolors just those points. Any other tool, Group Selection included, drops them. Public references: [Edit mesh objects](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-meshes/edit-mesh-objects.html) (a mesh point picked with the Mesh tool is recolored by choosing a fill color in the Swatches or Color panel), [Archived help guide, page 202](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=202) (the Mesh tool and Direct Selection both move mesh points). Carrying the picks between the tools is VectorCraft's own rule. Tests: `crates/engine/src/tests/mesh_picks.rs`. Scores and hours unchanged. +- **Picked mesh points survive a tool switch:** mesh points picked with the Mesh tool, Direct Selection, the Lasso or the Polygonal Lasso stay picked when another of these tools or the Eyedropper is chosen, and when one of them lends Direct Selection for a Cmd/Ctrl-click, so a fill color chosen afterward recolors just those points. A plain Lasso click away from the art deselects it and unpicks them. Any other tool, Group Selection included, drops them. Public references: [Edit mesh objects](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-meshes/edit-mesh-objects.html) (a mesh point picked with the Mesh tool is recolored by choosing a fill color in the Swatches or Color panel), [Archived help guide, page 202](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=202) (the Mesh tool and Direct Selection both move mesh points). Carrying the picks between the tools is VectorCraft's own rule. Tests: `crates/engine/src/tests/mesh_picks.rs`. Scores and hours unchanged. - **Image Trace Flat Logo mode:** a fourth mode beside Black and White, Grayscale and Color, for flat-colour logos. Each pixel is read as a blend of the logo's colours (found automatically or named), the blend is interpolated smoothly and every outline is placed where two colours are equally present, so edges are accurate to a fraction of a pixel. Outlines are then cleaned: corners the blur rounded are put back, near-straight runs and near-circular arcs become exact lines and arcs, the rest is fitted with as few Béziers as the tolerance allows, touching colours overlap by a hair so no gap opens, and an outline that strays from the raw contour is fitted plainly instead. Gradients and photos are refused with advice to use Color. Line art whose only solid area is white paper (strokes a pixel or two wide) takes its colours from the strokes' cores, with the lighter shades along a stroke's anti-aliased edge folded into its ink; a page whose ink (a channel at least 48 below white) covers under 1% of it traces to nothing, as blank paper does. *Measured* (a local experiment, not run in CI): a flat-colour logo's vector original was rendered down to a soft 199 × 100 px transparent PNG, traced, and the result compared with the original at 1600 px wide. The built-in colour presets (6 Colors, 16 Colors, High Fidelity Photo, Low Fidelity Photo) had a mean edge error of 2.5 to 3.4 px and region overlap of 0.88 to 0.91; Flat Logo had 0.78 px and 0.966 (0.48 px and 0.975 from a crisp source), in about 0.1 s. Limits: flat-colour art only; needle-thin sharp tips are shortened by about 1.7 source pixels because the blur erases them; it works at no more than 1024 px on the long side (larger images are averaged down first); only one logo family has been scored against a vector original. - **Image Trace, Flat Logo named colors only:** with `logoColors` named, `"logoWhite": false` traces those colors only, so white areas take the nearest of them and no white is added; a named white is kept, and enclosed transparent areas stay holes; code-drawn tests in `crates/trace` and `crates/engine`. - **Image Trace, Flat Logo flat-art check with named colors:** with `logoColors` named, whether the image is flat art is judged by its own colors, as many as are named, with white, or as the Colors setting gives, whichever is more. Named colors 20 levels off a flat badge's colors still trace it, a hatch on a light ground gives the same result with close and far named colors, a gradient's refusal score does not depend on how far the named colors are from it, and areas of colors that were not named are traced in the named colors instead of being refused; code-drawn tests in `crates/trace`. From f88a6b5877a8826fe4c3a1a6ed6e2152a1b93846 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:47:54 -0800 Subject: [PATCH 32/38] Eraser: a drag's outline takes the tip halfway along each step in two more cases The outline of an Eraser drag takes, at each step, the tip the pen gives halfway along it, as path.eraseRegion erases. Two cases still used the tips at the step's ends: - A round tip whose Size follows the pen drew each step as wide as the mean of the tips at its ends. Where an end is held at the 0.1 pt least size, that mean differs from the tip halfway along: with Size 10 pt on Pressure by 20 pt, a step from no pressure to full pressure showed 15.05 pt wide where the release erases 10 pt. - A pen turned or tilted in place at the last point updated the last step only when the tip at that point changed. With Size 10 pt on Tilt by 20 pt, tilting from 80 to 85 degrees after an upright point keeps the end tip at 0.1 pt while the tip halfway along goes from 12.22 pt to 11.11 pt, and the outline kept the old one. The area outline now keeps and compares the tip halfway along the last step. --- crates/tools/src/draw2/gesture.rs | 14 ++---- crates/tools/src/draw2/gesture/area.rs | 29 +++++------ crates/tools/src/draw2/gesture/tests.rs | 67 +++++++++++++++++++++++++ 3 files changed, 86 insertions(+), 24 deletions(-) diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index ba5e8afe9c..dc123e6cc1 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -1300,12 +1300,6 @@ impl GestureTool { self.poses.len() == self.points.len() } - /// The tip at point `i` of the stroke, as `path.eraseRegion` reads the pen there - /// ([`Self::controls_of_point`]). - fn tip_of_point(&self, i: usize) -> [f64; 3] { - self.tip_of_controls(self.controls_of_point(i)) - } - /// The tip halfway along the step from point `j` to point `j + 1`, as `path.eraseRegion` reads /// the pen there: the pressure and tilt halfway between those at the two points, and the /// bearing and rotation halfway between them the shorter way round. A tip whose angle follows @@ -1945,7 +1939,7 @@ impl Tool for GestureTool { }; let mut area = self.area.take().filter(|a| a.fits(key, &self.points)).unwrap_or_else(|| AreaPreview::new(key, self.points[0])); let sized = |[angle, roundness, size]: [f64; 3]| [angle, roundness, if size_varies { size } else { self.size }]; - area.step(&self.points, &|i| sized(self.tip_of_point(i)), &|j| sized(self.tip_between(j))); + area.step(&self.points, &|j| sized(self.tip_between(j))); let paths = area.paths(&self.points); o.extend(paths.settled.into_iter().map(|path| Overlay::SharedPath { path, color, width: 1.0, dash: None })); o.extend(paths.live.into_iter().map(|path| Overlay::Path { path, color, width: 1.0, dashed: false })); @@ -1953,9 +1947,9 @@ impl Tool for GestureTool { self.area.set(Some(area)); } else if size_varies { // With Size on a mode that follows the pen, each step of the drag shows as wide as the - // tip the pen gives at its ends. A long drag's steps are kept from call to call - // ([`LinePreview::segments`]). - let width_of = |j: usize| ((self.tip_of_point(j)[2] + self.tip_of_point(j + 1)[2]) / 2.0 * cx.zoom) as f32; + // tip the pen gives halfway along it, as `path.eraseRegion` reads it. A long drag's + // steps are kept from call to call ([`LinePreview::segments`]). + let width_of = |j: usize| (self.tip_between(j)[2] * cx.zoom) as f32; if self.points.len() > line::PIECE_SEGMENTS + 1 { let mut kept = self.line.take().unwrap_or_default(); for (j, path) in kept.segments(&self.points).into_iter().enumerate() { diff --git a/crates/tools/src/draw2/gesture/area.rs b/crates/tools/src/draw2/gesture/area.rs index 5a33e6e77f..9c3a9f8cb6 100644 --- a/crates/tools/src/draw2/gesture/area.rs +++ b/crates/tools/src/draw2/gesture/area.rs @@ -157,8 +157,8 @@ pub(super) struct AreaPreview { sq: Vec, /// The last point taken, on the page. last: Point, - /// The tip at the last point taken, when the tip varies along the drag. - last_tip: Option, + /// The tip halfway along the last segment taken, when the tip varies along the drag. + last_middle: Option, /// The tip's radius along each segment, where its tip is round. It is also as far as the /// segment's area reaches from the segment in the grid's space. radius: Vec, @@ -196,7 +196,7 @@ impl AreaPreview { side: widest.max(MIN_BRUSH_SIZE), sq: vec![], last: first, - last_tip: None, + last_middle: None, radius: vec![], to_round: vec![], pieces: vec![], @@ -240,20 +240,22 @@ impl AreaPreview { } /// Take the points of the drag `pts` added since the last call and check outlines, within this - /// call's limits. When the tip varies along the drag, `tip(i)` gives the tip at point `i`, and - /// segment `j` takes `middle(j)`, the tip halfway along it. A last point whose tip changed since - /// it was taken (a pen turned or tilted in place) gives its segment the new tip. - pub(super) fn step(&mut self, pts: &[Point], tip: &dyn Fn(usize) -> Tip, middle: &dyn Fn(usize) -> Tip) { + /// call's limits. When the tip varies along the drag, segment `j` takes `middle(j)`, the tip + /// halfway along it. A last segment whose tip halfway along it changed since it was taken (a pen + /// turned or tilted in place at its end) takes the new tip, also where the tip at its end stays + /// the same (a size held at its least). + pub(super) fn step(&mut self, pts: &[Point], middle: &dyn Fn(usize) -> Tip) { self.work = AreaWork::default(); let mut changed = BTreeSet::new(); if self.key.varies && let Some(j) = self.sq.len().checked_sub(2) - && self.last_tip.is_some_and(|t| t != tip(j + 1)) + && self.last_middle.is_some_and(|t| t != middle(j)) { let k = self.piece_of(j); let old = self.radius[j]; - self.set_tip(j, middle(j)); - self.last_tip = Some(tip(j + 1)); + let tip = middle(j); + self.set_tip(j, tip); + self.last_middle = Some(tip); changed.insert(k); // The pieces near the old tip or the new one are checked again. let new = self.radius[j]; @@ -266,13 +268,12 @@ impl AreaPreview { self.sq.push(self.squash * pts[i]); self.last = pts[i]; self.work.points += 1; - if self.key.varies { - self.last_tip = Some(tip(i)); - } let Some(j) = i.checked_sub(1) else { continue }; if self.key.varies { self.radius.push(0.0); - self.set_tip(j, middle(j)); + let tip = middle(j); + self.set_tip(j, tip); + self.last_middle = Some(tip); } else { self.radius.push(self.key.size / 2.0); } diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 87d18ca4b4..1ffcf1c37b 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -3622,6 +3622,73 @@ fn the_eraser_drag_area_takes_the_tip_halfway_along_each_step() { t.pointer(&cx, &PointerEvent { pressure: 1.0, ..PointerEvent::new(PointerKind::Up, 150.0, 150.0) }); } +/// A step of a round Eraser drag whose Size follows the pen shows as wide as the tip halfway along +/// it, as the release erases: with Size 10 pt on Pressure by up to 20 pt, a step from no pressure +/// (the tip at its 0.1 pt least) to full pressure (30 pt) shows 10 pt wide, not the 15.05 pt +/// halfway between the tips at its ends. +#[test] +fn a_round_eraser_drag_step_is_as_wide_as_the_tip_halfway_along_it() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = ToolContext { precise_cursors: true, ..cx(&d, &s, &p) }; + let mut t = GestureTool::new("eraser"); + for (k, v) in [("size", json!(10)), ("sizeMode", json!("pressure")), ("sizeVariation", json!(20))] { + t.set_option(k, &v); + } + t.pointer(&cx, &PointerEvent { pressure: 0.0, ..PointerEvent::new(PointerKind::Down, 50.0, 150.0) }); + t.pointer(&cx, &PointerEvent { pressure: 1.0, ..PointerEvent::new(PointerKind::Drag, 150.0, 150.0) }); + let o = t.overlays(&cx); + assert!(matches!(&o[..], [Overlay::Path { width, .. }] if (*width - 10.0).abs() < 1e-4), "{o:?}"); + t.pointer(&cx, &PointerEvent { pressure: 1.0, ..PointerEvent::new(PointerKind::Up, 150.0, 150.0) }); +} + +/// A pen tilted in place at the last point of an Eraser drag gives the last step the new tip halfway +/// along it, even where the tip at that point stays the same: with Size 10 pt on Tilt by up to 20 pt, +/// the tip at a pen leaning 80° and at one leaning 85° is the 0.1 pt least, while halfway along a +/// step from an upright pen it goes from 12.22 pt to 11.11 pt. +#[test] +fn the_eraser_drag_area_takes_the_new_tip_halfway_along_a_step_whose_end_tip_stays() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = ToolContext { precise_cursors: true, ..cx(&d, &s, &p) }; + let bounds = |t: &GestureTool| { + drain_area(t, &cx); + let o = t.overlays(&cx); + o.iter() + .filter_map(|o| match o { + Overlay::Path { path, .. } => Some(vectorcraft_geom::Shape::bounding_box(path)), + Overlay::SharedPath { path, .. } => Some(vectorcraft_geom::Shape::bounding_box(&**path)), + _ => None, + }) + .reduce(|a, b| a.union(b)) + .unwrap_or_else(|| panic!("{o:?}")) + }; + // The tip lying level, 4 times as long as it is wide: a step from x 50 to x 150 with a tip + // `size` long reaches `size` / 2 before and after it and `size` / 8 above and below. + let near = |b: vectorcraft_geom::Rect, size: f64| { + let want = (50.0 - size / 2.0, 150.0 - size / 8.0, 150.0 + size / 2.0, 150.0 + size / 8.0); + assert!([b.x0 - want.0, b.y0 - want.1, b.x1 - want.2, b.y1 - want.3].iter().all(|e| e.abs() < 0.01), "{b:?} vs {want:?}"); + }; + let mut t = GestureTool::new("eraser"); + for (k, v) in [("size", json!(10)), ("roundness", json!(25)), ("sizeMode", json!("tilt")), ("sizeVariation", json!(20))] { + t.set_option(k, &v); + } + let press = |t: &mut GestureTool, lean: f32, kind: PointerKind, x: f64| { + let pen = Some(PenPose { tilt: Some([lean, 0.0]), rotation: None, wheel: None }); + t.pointer(&cx, &PointerEvent { pen, pressure: 1.0, ..PointerEvent::new(kind, x, 150.0) }); + }; + press(&mut t, 0.0, PointerKind::Down, 50.0); + press(&mut t, 80.0, PointerKind::Drag, 150.0); + // Tilt reads 1 upright and 1/9 at 80°, 5/9 halfway: 10 + 20 × (2 × 5/9 − 1) pt. + near(bounds(&t), 10.0 + 20.0 / 9.0); + // At 85° Tilt reads 1/18, 19/36 halfway. + press(&mut t, 85.0, PointerKind::Drag, 150.0); + near(bounds(&t), 10.0 + 20.0 / 18.0); + press(&mut t, 85.0, PointerKind::Up, 150.0); +} + /// The outline of a long Eraser drag whose tip turns and changes shape with the pen is built a /// bounded amount per frame, and once finished it shows nothing inside the area: no point of it /// lies well inside the area of any step, each step with the tip halfway along it. From 2ea35324b7acc9c1150c56a11cbcd631b89071bb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:53:47 -0800 Subject: [PATCH 33/38] Pathfinder: Outline of a compound shape with no fill adds no stroke of its own The paint source for a compound shape's area held every painting item of the shape, strokes included. When the shape had no fill, Outline fell back to that stroke and gave the edges a 1 pt stroke in its paint, while the shape's own appearance stroked the result again. The area now takes only the shape's top painting fill, so an unfilled compound shape's Outline edges carry no paint of their own. --- crates/effects/src/group.rs | 5 +++-- crates/effects/src/group/tests.rs | 19 +++++++++++++++++++ docs/mcp.md | 3 ++- 3 files changed, 24 insertions(+), 3 deletions(-) diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index aeffaacfb6..eaaf6a99e8 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -583,9 +583,10 @@ pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option Option { diff --git a/crates/effects/src/group/tests.rs b/crates/effects/src/group/tests.rs index 1c62508347..345bb4a0bd 100644 --- a/crates/effects/src/group/tests.rs +++ b/crates/effects/src/group/tests.rs @@ -263,6 +263,25 @@ fn outline_strokes_a_compound_shapes_area_in_its_fill() { } } +/// Outline of a compound shape with no fill gives the edges no paint of their own when Remove +/// Unpainted Artwork is off. The shape's own appearance strokes the result, so the shape's stroke +/// is not copied onto the edges. +#[test] +fn outline_of_an_unfilled_compound_shape_adds_no_stroke() { + let mut g = compound_shape(ShapeMode::Add); + let mut a = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 4.0); + if let Some(AppearanceItem::Stroke(s)) = a.items.last_mut() { + s.opacity = 0.5; + } + g.appearance = a.into(); + g.appearance.effects.push(Effect { id: "pathfinder.outline".into(), params: serde_json::json!({"removeUnpainted": false}), visible: true }); + let out = pathfinder_children(None, &g, None).unwrap(); + assert!(!out.is_empty(), "{out:#?}"); + for n in &out { + assert!(!n.appearance.items.iter().any(paints), "{n:#?}"); + } +} + /// With Remove Unpainted Artwork, Divide keeps the pieces of an unfilled member when its group's /// own visible fill paints them and leaves them out when the group has no fill. Outline leaves out /// the member's segments either way. diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..f696d61045 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6218,7 +6218,8 @@ Each Effect › Pathfinder effect (`pathfinder.add` … `pathfinder.softMix`, no in its params: `precision` (a number, 0.001–10 pt), `removeRedundantPoints` and `removeUnpainted` (true or false), which mean what they mean for the panel's operations; the other operations ignore `removeUnpainted`. With `removeUnpainted` on, a compound shape's area counts as filled when the shape has a visible fill of its own, and Divide keeps every piece -when the group or compound shape has one. Outline strokes a compound shape's area in the shape's own fill. `effect.apply` +when the group or compound shape has one. Outline strokes a compound shape's area in the shape's own fill, and gives +the edges no paint when the shape has no fill (the shape's own strokes still draw over the result). `effect.apply` fills the ones `params` leave out from the current Pathfinder Options, and the values join its journal entry. An effect saved without them evaluates with precision 0.01 and both switches off, as before effects kept them. `effect.setParams {index, params: {precision?, removeRedundantPoints?, removeUnpainted?}}` edits them as one undo step; values the From 5721f9693195d2e0a55e68537a74aad96680336a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 16:14:07 -0800 Subject: [PATCH 34/38] Expand Appearance: Safe Mode checks symbol art that a group's raster effect draws A plain symbol instance does not expand on its own, so the Safe Mode plug-in check skipped its symbol's art. When a group or layer around the instance has a raster effect (its own, or on one of its fills or strokes), the group's image draws that art, plug-in effect included, and Expand Appearance committed pixels without the plug-in effect instead of returning the Safe Mode error. The check now looks into every object of such a group or layer, symbol art included. --- crates/engine/src/cmd/effectcmd.rs | 10 ++++-- crates/engine/tests/plugin_safe_mode.rs | 43 +++++++++++++++++++++++++ docs/mcp.md | 3 +- 3 files changed, 53 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index edb5561796..cb399eca1c 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -97,7 +97,7 @@ fn effect_specs() -> Vec { "Expand Appearance", ["Object"], None, - "{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry or raster effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them, its raster effects an image as for other objects; a symbol instance in that art whose topmost fill or stroke has such an effect (its own or one the outer instance passes on) becomes its art and image in turn. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. One expansion makes at most 1,024 images of raster effects, 256 megapixels in all (VectorCraft's own limits): an object or symbol instance whose image would go past them stays as it is, with its effects, and when nothing else expands that is an error. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says; or raster effects were left past the limits), rasterLeft? (how many objects were left so)}", + "{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry or raster effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them, its raster effects an image as for other objects; a symbol instance in that art whose topmost fill or stroke has such an effect (its own or one the outer instance passes on) becomes its art and image in turn. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. One expansion makes at most 1,024 images of raster effects, 256 megapixels in all (VectorCraft's own limits): an object or symbol instance whose image would go past them stays as it is, with its effects, and when nothing else expands that is an error. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places, a plain instance in a group or layer whose raster effect makes an image of it included) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says; or raster effects were left past the limits), rasterLeft? (how many objects were left so)}", can_expand, expand_appearance ), @@ -1611,13 +1611,18 @@ fn expanded_node( /// Does `n`, an object in it, or the art of a symbol placed in it hold a plug-in effect that /// expanding it draws: a visible one, the object's own or a visible fill's or stroke's, on an -/// object that expands ([`expandable`]; in a symbol's art, `in_art`, every object does). A symbol's +/// object that expands ([`expandable`]; in a symbol's art, `in_art`, every object does, and so does +/// every object in a group or layer with a raster effect, whose image draws all of it). A symbol's /// art counts where an instance of it expands. `seen` holds the symbols already looked into. fn holds_plugin_effect(d: &Document, n: &Node, in_art: bool, seen: &mut std::collections::HashSet) -> bool { let plugin = |e: &Effect| e.visible && vectorcraft_plugins::effect::plugin_id(&e.id).is_some(); let mut symbols = vec![]; + let mut drawn = vec![]; let mut holds = false; n.walk(&mut |c| { + if !in_art && is_container(c) && !rasterfx::raster_fx(c).is_empty() { + drawn.push(c); + } if !in_art && !expandable(c) { return; } @@ -1627,6 +1632,7 @@ fn holds_plugin_effect(d: &Document, n: &Node, in_art: bool, seen: &mut std::col } }); holds + || drawn.into_iter().any(|g| holds_plugin_effect(d, g, true, seen)) || symbols.into_iter().any(|name| { seen.insert(name.clone()) && d.symbols.iter().find(|s| s.name == name).is_some_and(|s| holds_plugin_effect(d, &s.art, true, seen)) }) diff --git a/crates/engine/tests/plugin_safe_mode.rs b/crates/engine/tests/plugin_safe_mode.rs index 9ff0d0668a..a469e68f20 100644 --- a/crates/engine/tests/plugin_safe_mode.rs +++ b/crates/engine/tests/plugin_safe_mode.rs @@ -463,6 +463,49 @@ fn expand_appearance_keeps_a_plug_in_effect_safe_mode_skips() { s.execute("effect.expandAppearance", &json!({})).unwrap(); } +/// In Safe Mode, Expand Appearance refuses a group whose raster effect makes an image of a plain +/// instance in it when the instance's symbol art holds a plug-in effect. +#[test] +fn expand_appearance_in_safe_mode_checks_symbol_art_a_group_image_draws() { + let _f = fresh(); + let mut s = Session::new(); + let fx = wat::parse_str(tpl::returning(&tpl::manifest("test.sm.sym", "effect", "{}"), r#"{"objects":[]}"#)).unwrap(); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&fx)})).unwrap(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + s.execute("effect.apply", &json!({"effect": "plugin.test.sm.sym"})).unwrap(); + s.execute("symbol.new", &json!({"name": "fx"})).unwrap(); + let plain = s.execute("symbol.place", &json!({"name": "fx", "x": 100, "y": 100})).unwrap()["id"].clone(); + let refused = |s: &mut Session, group: &Value| { + let before = s.execute("document.inspect", &json!({})).unwrap(); + safe_mode::set_active(Some(safe_mode::Source::Flag)); + let err = s.execute("effect.expandAppearance", &json!({"ids": [group]})).unwrap_err().to_string(); + safe_mode::set_active(None); + assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{err}"); + assert_eq!(s.execute("document.inspect", &json!({})).unwrap(), before, "nothing changes"); + }; + // A Gaussian Blur of the group's own. + let group = s.execute("object.group", &json!({"ids": [plain]})).unwrap()["id"].clone(); + s.execute("effect.apply", &json!({"effect": "blur.gaussian", "ids": [group], "params": {"radius": 2}})).unwrap(); + refused(&mut s, &group); + // A Gaussian Blur on a fill of a group around a group that holds another plain instance. + let blurred_fill = { + let t = s.execute("shape.rectangle", &json!({"x": 150, "y": 10, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("effect.apply", &json!({"effect": "blur.gaussian", "ids": [t], "item": 0, "params": {"radius": 2}})).unwrap(); + s.doc().unwrap().doc.node(vectorcraft_engine::doc::NodeId(t)).unwrap().appearance.items[0].clone() + }; + let plain = s.execute("symbol.place", &json!({"name": "fx", "x": 100, "y": 20})).unwrap()["id"].clone(); + let inner = s.execute("object.group", &json!({"ids": [plain]})).unwrap()["id"].clone(); + let outer = s.execute("object.group", &json!({"ids": [inner]})).unwrap()["id"].as_u64().unwrap(); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc) + .node_mut(vectorcraft_engine::doc::NodeId(outer)) + .unwrap() + .appearance + .items + .push(blurred_fill); + refused(&mut s, &json!(outer)); +} + /// In Safe Mode, a plug-in effect in the art of a graph design in a series stops Expand Appearance of the graph only /// when an effect of the series group draws that art with the group. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..44c8d11c38 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13212,7 +13212,8 @@ session and refuses `--connect`. In Safe Mode no plug-in loads or runs: `plugin.install`, `plugin.run`, `plugin.reload` and exporters return an error, and a live-effect plug-in draws its object's geometry unchanged while the object keeps the effect: `effect.list` gives that effect `skipped: true`, and the Appearance panel shows "(Safe Mode)" after its name and the plug-in's id in its tooltip. `effect.expandAppearance` returns an -error and changes nothing when an object it would expand holds such an effect, in it or in a symbol it places. `vectorcraft` rejects an option it does not know (such as +error and changes nothing when an object it would expand holds such an effect, in it or in a symbol it places. That includes a +plain symbol instance in a group or layer with a raster effect, since the group's image draws the symbol's art. `vectorcraft` rejects an option it does not know (such as `--safe-mod`) instead of opening it as a file; `--` before a file name that starts with `-` opens it. The web build keeps no installed plug-ins from one page load to the next and has no launch marker, so it never offers the choice. `plugin.safeMode` returns `{active, source, disabled, pendingItem}`; a command does not turn Safe Mode on or off. `plugin.setEnabled {id | file, enabled}` turns a plug-in on or From 91e2551f47f89fc511bd1f024764749fecfc4d8a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 16:38:04 -0800 Subject: [PATCH 35/38] Kinsoku sets: tests for pasted type and shaped lines under a custom set Pasted type whose custom set was edited after the copy is checked against a fresh layout by its line ends, which move from A to B while the line count stays the same, so the test fails without the relayout in Relink. The every-line composer's first-word measure is checked in a frame whose top is narrower than the word the custom set's Cannot End Line makes, so the test fails when that measure uses the built-in setting instead. --- crates/engine/src/cmd/kinsokusets/tests.rs | 30 +++++++++++++ crates/text/src/layout/wrapping_tests.rs | 52 ++++++++++++++++++++++ 2 files changed, 82 insertions(+) diff --git a/crates/engine/src/cmd/kinsokusets/tests.rs b/crates/engine/src/cmd/kinsokusets/tests.rs index 1d1c8980c0..04456872b2 100644 --- a/crates/engine/src/cmd/kinsokusets/tests.rs +++ b/crates/engine/src/cmd/kinsokusets/tests.rs @@ -332,6 +332,36 @@ fn pasted_type_brings_its_kinsoku_sets() { assert_eq!(style_set(&s), Value::Null); } +/// Type pasted back after its set was edited breaks its lines by the set as it is now: with B in +/// Cannot End Line the first line of `A B C` ends at A, and once the set holds nothing, it ends at B. +#[test] +fn pasted_type_relayouts_after_its_kinsoku_set_was_edited() { + let mut s = session(); + s.execute("type.kinsokuSets.set", &json!({"sets": [{"name": "Tight", "cannotEnd": "B"}]})).unwrap(); + let create = json!({"x": 10, "y": 10, "text": "A B C", "size": 20, "font": "JetBrains Mono", "area": {"width": 40, "height": 120}}); + let id = s.execute("text.create", &create).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("text.setFormat", &json!({"kinsoku": "Tight"})).unwrap(); + let lines = |t: &vectorcraft_doc::TextObject| t.baselines().collect::>(); + let first_width = |t: &vectorcraft_doc::TextObject| t.baselines().next().map(|(a, b)| b.x - a.x).unwrap_or_default(); + let copied = text(&s, id); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("type.kinsokuSets.set", &json!({"sets": [{"name": "Tight"}]})).unwrap(); + // The set's edit lays the type in the document out anew, and its first line takes B. + let edited = text(&s, id); + assert_eq!(lines(&edited).len(), 2); + assert!(first_width(&edited) > first_width(&copied), "{:?} against {:?}", lines(&edited), lines(&copied)); + + let v = s.execute("edit.paste", &json!({})).unwrap(); + let t = text(&s, v["ids"][0].as_u64().unwrap()); + let now = s.doc().unwrap().doc.kinsoku_sets[0].clone(); + assert_eq!(t.para_at(0).kinsoku_set.as_deref(), Some(&now)); + let mut fresh = t.clone(); + crate::cmd::typecmd::refresh_bounds(&mut fresh); + assert_eq!(lines(&t), lines(&fresh), "the pasted type is laid out with the edited set"); + assert_eq!(first_width(&t), first_width(&edited)); +} + /// A pasted set whose name, at the longest a name can be, the document's set with other /// characters already has comes in under a free name that fits: the number takes the place of the /// name's last characters, and a space left at the end of them is dropped. A second paste uses diff --git a/crates/text/src/layout/wrapping_tests.rs b/crates/text/src/layout/wrapping_tests.rs index 96ccc3e5c7..225e58a053 100644 --- a/crates/text/src/layout/wrapping_tests.rs +++ b/crates/text/src/layout/wrapping_tests.rs @@ -1312,6 +1312,58 @@ fn shaped_composition_searches_share_the_frame_budget() { assert_eq!(three.steps_left.get(), breaking::MAX_TOTAL_STEPS, "the layout's own steps"); } +/// The every-line composer places a line where its first word fits, and measures that word by the +/// paragraph's custom Kinsoku set: with A in the set's Cannot End Line, the first word of `A BC` +/// runs past the space to the end, so the line `A` skips the frame's 20 pt top and takes the +/// 50 pt band below it. Without the set the word is `A` alone and the top holds it. +#[test] +fn shaped_first_word_uses_the_custom_kinsoku_set() { + use super::shaped::{Budget, Shaped}; + use crate::composer::Measure; + use std::cell::Cell; + use std::rc::Rc; + let text = "A BC"; + let glyphs = full_width(text); + let set = custom_set("", "A", "", &[]); + assert_eq!(breaking::word_width(&glyphs, 0, &[], breaking::KinsokuRules::Custom(&set), Burasagari::None), 40.0); + assert_eq!(breaking::word_width(&glyphs, 0, &[], Kinsoku::Hard, Burasagari::None), 10.0); + // 20 pt wide down to 40 pt, and 50 pt wide below. + let frame = BezPath::from_vec(vec![ + PathEl::MoveTo((0.0, 0.0).into()), + PathEl::LineTo((20.0, 0.0).into()), + PathEl::LineTo((20.0, 40.0).into()), + PathEl::LineTo((50.0, 40.0).into()), + PathEl::LineTo((50.0, 120.0).into()), + PathEl::LineTo((0.0, 120.0).into()), + PathEl::ClosePath, + ]); + let regions = region::Region::cells(&frame, &LayoutOptions::default(), &[]); + let pen = breaking::Pen { + regions: Some(®ions), + ri: 0, + prev: None, + pending: 0.0, + fb: FirstBaseline::Ascent, + fb_min: 0.0, + queued: vec![], + above: Default::default(), + model: LeadingModel::default(), + next_top: None, + no_room_for: f64::INFINITY, + steps_left: Rc::new(Cell::new(breaking::MAX_TOTAL_STEPS)), + search: Rc::new(Budget::default()), + }; + let first_line = |para: &ParaStyle| { + let mut measure = Shaped::new(&glyphs, &[], para, &|_| 0.0, false, false, &pen); + let state = measure.first(); + measure.line(&state, 0, 1).ok().flatten().map(|(width, _)| width) + }; + let hard = ParaStyle { kinsoku: Kinsoku::Hard, ..ParaStyle::default() }; + let custom = ParaStyle { kinsoku_set: Some(Arc::new(set)), ..hard.clone() }; + assert_eq!(first_line(&hard), Some(20.0), "the frame's top holds the word A"); + assert_eq!(first_line(&custom), Some(50.0), "the word A BC needs the band below"); +} + /// The glyphs of `text`, each 10 pt wide, with Korean words kept whole unless `anywhere` (Korean /// Line Break Anywhere on). fn korean(text: &str, anywhere: bool) -> Vec { From 873a5562a75579fd8b0fb3c80064e445f0b6bac6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 17:07:31 -0800 Subject: [PATCH 36/38] Gradient: a freeform line stays open over its object's stroke on a layer with Preview off The check for whether the pointer is still on the object hit the object's painted art with outline off, but the hit test turned outline back on for a layer with Preview off, so a move onto the stroke past the fill ended the line. A new HitOptions field, ignore_layer_preview, keeps the point hit tests from switching to outline for such layers, and the freeform check sets it. the_stroke_counts_as_the_object now runs with the layer's Preview on and off. --- crates/doc/src/hit.rs | 12 ++++++-- crates/doc/src/hit/tests.rs | 1 + crates/tools/src/context.rs | 1 + crates/tools/src/xform/freeform.rs | 44 ++++++++++++++++++------------ 4 files changed, 38 insertions(+), 20 deletions(-) diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index fcbe2f9db1..7c0de44cab 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -78,6 +78,9 @@ pub struct HitOptions { /// Off, the empty part of the frame (away from its edge and its lines of type) takes no /// clicks, so they reach the art behind (#7274). pub area_type_interior: bool, + /// The point hit tests ([`hit_test`], [`hit_test_visible`] and [`hit_test_visible_skipping`]) + /// hit the art on a layer whose Preview is off as painted, not in outline. + pub ignore_layer_preview: bool, } impl Default for HitOptions { @@ -90,6 +93,7 @@ impl Default for HitOptions { skip_guides: false, clip_outlines: false, area_type_interior: false, + ignore_layer_preview: false, scope: None, } } @@ -847,7 +851,7 @@ fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(No continue; } chain.push(layer.id); - let opt = if matches!(layer.kind, NodeKind::Layer { preview: false, .. }) { HitOptions { outline: true, ..opt } } else { opt }; + let opt = if !opt.ignore_layer_preview && previews_off(layer) { HitOptions { outline: true, ..opt } } else { opt }; if let Some(h) = hit_children(layer, p, opt, &symbols, skip, &mut chain, editable_only) { return Some(finish(h)); } @@ -1211,7 +1215,9 @@ fn hit_children( chain.push(c.id); let hit = plain(i == 0 && clip.is_some(), || match &c.kind { // A sublayer whose Preview is off is clicked in outline, like an outline view. - NodeKind::Layer { preview: false, .. } => hit_children(c, p, HitOptions { outline: true, ..opt }, symbols, skip, chain, editable_only), + NodeKind::Layer { preview: false, .. } if !opt.ignore_layer_preview => { + hit_children(c, p, HitOptions { outline: true, ..opt }, symbols, skip, chain, editable_only) + } NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Intertwine { .. } => { hit_children(c, p, opt, symbols, skip, chain, editable_only) } @@ -1325,7 +1331,7 @@ fn art_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, accept: & match &n.kind { NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } | NodeKind::Intertwine { children } => { // A layer with Preview off is clicked in outline, as [`hit_children`] clicks it. - let opt = HitOptions { outline: opt.outline || previews_off(n), ..opt }; + let opt = HitOptions { outline: opt.outline || !opt.ignore_layer_preview && previews_off(n), ..opt }; if n.clips() && let Some(clip) = children.first() { diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index e94b2b8ba8..ad037931a0 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -1463,6 +1463,7 @@ const SELECTING: HitOptions = HitOptions { skip_guides: false, clip_outlines: true, area_type_interior: false, + ignore_layer_preview: false, scope: None, }; diff --git a/crates/tools/src/context.rs b/crates/tools/src/context.rs index 50553a87bc..1a37860179 100644 --- a/crates/tools/src/context.rs +++ b/crates/tools/src/context.rs @@ -451,6 +451,7 @@ impl ToolContext<'_> { skip_guides: !self.guides, clip_outlines: false, area_type_interior: false, + ignore_layer_preview: false, } } diff --git a/crates/tools/src/xform/freeform.rs b/crates/tools/src/xform/freeform.rs index 8a5a461a2b..3e3eef28b2 100644 --- a/crates/tools/src/xform/freeform.rs +++ b/crates/tools/src/xform/freeform.rs @@ -216,8 +216,9 @@ fn on_object(cx: &ToolContext, id: NodeId, p: Point) -> bool { keep.insert(c.id); }); keep.extend(ancestry); - // The art as painted, whatever the view and the path-only selection preferences. - let opt = HitOptions { outline: false, path_only: false, type_path_only: false, ..cx.hit_options() }; + // The art as painted, whatever the view, the layers' Preview and the path-only selection + // preferences. + let opt = HitOptions { outline: false, path_only: false, type_path_only: false, ignore_layer_preview: true, ..cx.hit_options() }; hit_test_visible_skipping(cx.doc, p, opt, &|n| !keep.contains(&n)).is_some_and(|h| h.leaf == id || h.ancestry.contains(&id)) } @@ -530,23 +531,32 @@ mod tests { } /// The object's stroke is part of the object: moving onto it past the filled area keeps the - /// line open, and moving past the stroke ends it. + /// line open, and moving past the stroke ends it. The same holds on a layer with Preview off. #[test] fn the_stroke_counts_as_the_object() { - let (mut d, s) = doc(FreeformMode::Lines); - let id = s.objects[0]; - d.node_mut(id).unwrap().appearance.stroke_mut().unwrap().width = 20.0; - let p = paint(); - let mut cx = cx(&d, &s, &p); - let mut t = GradientTool::default(); - let add = |x: f64, y: f64, line: bool| Action::Exec("paint.freeform.addPoint".into(), json!({"at": [x, y], "line": line, "stroke": false})); - assert_eq!(click(&mut t, &cx, 140.0, 150.0), vec![add(140.0, 150.0, false)]); - cx.freeform_point = Some(2); - t.pointer(&cx, &ev(PointerKind::Move, 206.0, 150.0)); - assert!(t.claims_key(&cx, ToolKey::Escape), "on the stroke the line stays open"); - assert_eq!(click(&mut t, &cx, 160.0, 150.0), vec![add(160.0, 150.0, true)]); - t.pointer(&cx, &ev(PointerKind::Move, 230.0, 150.0)); - assert!(!t.claims_key(&cx, ToolKey::Escape), "past the stroke the line has ended"); + for preview in [true, false] { + let (mut d, s) = doc(FreeformMode::Lines); + let id = s.objects[0]; + d.node_mut(id).unwrap().appearance.stroke_mut().unwrap().width = 20.0; + let l = d.layers[0].id; + if let vectorcraft_doc::NodeKind::Layer { preview: p, .. } = &mut d.node_mut(l).unwrap().kind { + *p = preview; + } + let p = paint(); + let mut cx = cx(&d, &s, &p); + let mut t = GradientTool::default(); + cx.freeform_point = Some(2); + // The line starts from the existing point. + assert!(click(&mut t, &cx, 150.0, 180.0).is_empty()); + t.pointer(&cx, &ev(PointerKind::Move, 206.0, 150.0)); + assert!(t.claims_key(&cx, ToolKey::Escape), "on the stroke the line stays open (Preview {preview})"); + if preview { + let add = Action::Exec("paint.freeform.addPoint".into(), json!({"at": [160.0, 150.0], "line": true, "stroke": false})); + assert_eq!(click(&mut t, &cx, 160.0, 150.0), vec![add]); + } + t.pointer(&cx, &ev(PointerKind::Move, 230.0, 150.0)); + assert!(!t.claims_key(&cx, ToolKey::Escape), "past the stroke the line has ended (Preview {preview})"); + } } /// In a clipping mask, the part of the object the mask hides is outside it: moving there ends From 417ed9443192ea08878b3e583dfad2dc4504c2d1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 17:22:26 -0800 Subject: [PATCH 37/38] Script checker: setting a File's length, hidden or readonly counts as a file write Setting a File object's length truncates or pads the file, and setting readonly or hidden changes it, but script.check reported no outside category for those assignments. It now reports file.write and filesWritten for them: plain and compound assignment, ++ and -- before or after, and the property name as a string literal in brackets. A new integration test lists every global and member the script host adds to the JavaScript engine (the own properties of the global object, of each object or function it holds and of each function's prototype, compared with a plain engine) and fails when one has no row. Each name that reaches outside the document has a probe script, and the test checks that script.check gives it the expected outside id. vc is listed as not checked: script.check reads scripts written for the reference app's scripting, and what vc.run does depends on the command. The test also checks that the checker lists every preprocessor directive the host reads, through the new DirectiveName::ALL. File object properties: https://extendscript.docsforadobe.dev/file-system-access/file-object/ --- crates/engine/tests/it/main.rs | 1 + .../tests/it/script_host_vs_scriptcheck.rs | 167 ++++++++++++++++++ crates/js/src/token.rs | 20 ++- crates/scriptcheck/src/analyze.rs | 4 + crates/scriptcheck/src/analyze/features.rs | 55 +++++- crates/scriptcheck/src/catalog.rs | 3 + crates/scriptcheck/src/tests.rs | 34 ++++ docs/mcp.md | 8 +- 8 files changed, 273 insertions(+), 19 deletions(-) create mode 100644 crates/engine/tests/it/script_host_vs_scriptcheck.rs diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 836190aca6..9a4644575d 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -32,6 +32,7 @@ mod pen_rubber_band; mod ruler_guide_nodes; mod ruler_guide_perf; mod ruler_origin; +mod script_host_vs_scriptcheck; mod selection_commands; mod stroke_visibility; mod text_stroke_scale; diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs new file mode 100644 index 0000000000..aaf3f8acda --- /dev/null +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -0,0 +1,167 @@ +//! Every global and member the script host (`script.run`) adds to the JavaScript engine is in one of +//! the tables below, and each name that reaches outside the document has the `outside` id +//! `script.check` (`vectorcraft-scriptcheck`) gives it. The names are read from a run: the own +//! properties of the global object, of each object or function it holds and of each function's +//! `prototype`, with a setter listed again as `name=`. The names a plain `vectorcraft_js::Realm` also +//! has are the language's, which reach files and other apps only through the host; `eval` and +//! `Function` still have rows, since they run code the checker can't read. A name the host adds +//! without a row fails the test. + +use std::collections::BTreeSet; + +use serde_json::json; +use vectorcraft_engine::Session; +use vectorcraft_js::{DirectiveName, JsValue, Realm}; +use vectorcraft_scriptcheck::{Limits, check}; + +/// The names that reach outside the document: each with a script that uses it and the `outside` id +/// the checker gives that script. +const OUTSIDE: &[(&str, &str, &str)] = &[ + ("eval", "eval(s);", "unseenCode"), + ("Function", "var g = new Function(s);", "unseenCode"), + ("$.evalFile", "$.evalFile(p);", "unseenCode"), + ("$.getenv", "var h = $.getenv(n);", "environment"), + ("$.setenv", "$.setenv(n, v);", "environment"), + ("File.prototype.open", "var f = new File(p); f.open('w');", "filesWritten"), + ("File.prototype.write", "var f = new File(p); f.write(s);", "filesWritten"), + ("File.prototype.writeln", "var f = new File(p); f.writeln(s);", "filesWritten"), + ("File.prototype.copy", "var f = new File(p); f.copy(q);", "filesWritten"), + ("File.prototype.createAlias", "var f = new File(p); f.createAlias(q);", "filesWritten"), + ("File.prototype.remove", "var f = new File(p); f.remove();", "filesWritten"), + ("File.prototype.rename", "var f = new File(p); f.rename(q);", "filesWritten"), + ("File.prototype.length=", "var f = new File(p); f.length = 0;", "filesWritten"), + ("File.prototype.hidden=", "var f = new File(p); f.hidden = true;", "filesWritten"), + ("File.prototype.readonly=", "var f = new File(p); f.readonly = true;", "filesWritten"), + ("File.prototype.execute", "var f = new File(p); f.execute();", "filesOpened"), + ("Folder.prototype.create", "var d = new Folder(p); d.create();", "filesWritten"), + ("Folder.prototype.remove", "var d = new Folder(p); d.remove();", "filesWritten"), + ("Folder.prototype.rename", "var d = new Folder(p); d.rename(q);", "filesWritten"), + ("Folder.prototype.execute", "var d = new Folder(p); d.execute();", "filesOpened"), +]; + +/// The names the host adds that stay inside the document and the run, by the object that has them. +/// Reading a file or a folder, a file dialog and a message to the person do not change anything +/// outside it. +const INSIDE: &[(&str, &str)] = &[ + ("", "$ File Folder alert confirm localize prompt toSource"), + ("Object.prototype.", "toSource"), + ("localize.", "length"), + ("toSource.", "length"), + ( + "$.", + "about appEncoding appEncoding= bp build buildDate colorPicker decimalPoint engineName error fileName flags \ + flags= gc global hiresTimer includePath level line locale locale= localize localize= memCache memCache= os screens \ + sleep stack strict version write writeln", + ), + ("File.", "decode encode fs isEncodingAvailable openDialog saveDialog length prototype"), + ( + "File.prototype.", + "absoluteURI alias changePath close constructor created creator displayName encoding encoding= eof error error= \ + exists fsName fullName getRelativeURI hidden length lineFeed lineFeed= modified name openDlg parent path read \ + readch readln readonly relativeURI resolve saveDlg seek tell toString type", + ), + ( + "Folder.", + "appData appPackage commonFiles current current= decode desktop encode fs isEncodingAvailable length myDocuments \ + prototype selectDialog startup system temp trash userData", + ), + ( + "Folder.prototype.", + "absoluteURI alias changePath constructor created displayName error error= exists fsName fullName getFiles \ + getRelativeURI modified name parent path relativeURI resolve selectDlg toString", + ), +]; + +/// The name the checker does not read, which also stands for its members: `script.check` reads +/// scripts written for the reference app, `vc` is VectorCraft's own API, and what `vc.run` does +/// depends on the command it runs. +const NOT_CHECKED: &str = "vc"; + +/// An expression whose value is the list of names, one to a line. +const LIST: &str = r#"(function () { + var out = []; + function add(o, prefix) { + var own = Object.getOwnPropertyNames(o); + for (var i = 0; i < own.length; i++) { + out.push(prefix + own[i]); + var d = Object.getOwnPropertyDescriptor(o, own[i]); + if (d && d.set) out.push(prefix + own[i] + "="); + } + } + var g = (function () { return this; })(); + var globals = Object.getOwnPropertyNames(g); + add(g, ""); + for (var i = 0; i < globals.length; i++) { + var v = g[globals[i]]; + if (v !== null && (typeof v == "object" || typeof v == "function")) { + add(v, globals[i] + "."); + if (typeof v == "function" && v.prototype !== null && typeof v.prototype == "object") add(v.prototype, globals[i] + ".prototype."); + } + } + return out.join("\n"); +})()"#; + +/// The names a script run by the host has. +fn host_names() -> BTreeSet { + let mut s = Session::new(); + let r = s.execute("script.run", &json!({"source": format!("vc.log({LIST});"), "name": "list.js"})).unwrap(); + let text = r["log"][0].as_str().unwrap_or_else(|| panic!("no list in {r}")); + text.lines().map(str::to_string).collect() +} + +/// The names a plain JavaScript engine has. +fn language_names() -> BTreeSet { + match Realm::new().run(LIST) { + Ok(JsValue::String(text)) => text.lines().map(str::to_string).collect(), + other => panic!("no list: {other:?}"), + } +} + +fn table_names() -> BTreeSet { + let inside = INSIDE.iter().flat_map(|(prefix, names)| names.split_whitespace().map(move |n| format!("{prefix}{n}"))); + OUTSIDE.iter().map(|(n, ..)| n.to_string()).chain(inside).chain([NOT_CHECKED.to_string()]).collect() +} + +#[test] +fn every_name_the_host_adds_has_a_row() { + let host = host_names(); + let language = language_names(); + let table = table_names(); + let not_checked = |n: &&String| n.starts_with(&format!("{NOT_CHECKED}.")); + let missing: Vec<_> = host.difference(&language).filter(|n| !table.contains(*n) && !not_checked(n)).collect(); + assert!(missing.is_empty(), "the host adds these names, which no table here lists: {missing:?}"); + let gone: Vec<_> = table.difference(&host).collect(); + assert!(gone.is_empty(), "the tables list these names, which a script run by the host does not have: {gone:?}"); +} + +#[test] +fn every_name_that_reaches_outside_has_its_checker_id() { + for (name, script, id) in OUTSIDE { + let r = check("probe.jsx", script.as_bytes(), None, &Limits::default()); + let ids: Vec<_> = r.outside.iter().map(|o| o.id).collect(); + assert!(ids.contains(id), "{name}: the checker gives {ids:?} for {script:?}, not {id}"); + } +} + +/// A line with the directive `d`. The match has no catch-all, so a new directive needs a row, and +/// [`DirectiveName::from_name`] reads only the directives in [`DirectiveName::ALL`]. +fn directive_line(d: DirectiveName) -> &'static str { + match d { + DirectiveName::Include => "#include \"lib.jsxinc\"", + DirectiveName::IncludePath => "#includepath \"lib\"", + DirectiveName::Script => "#script Tidy", + DirectiveName::Strict => "#strict on", + DirectiveName::Target => "#target vectorcraft", + DirectiveName::TargetEngine => "#targetengine session", + } +} + +#[test] +fn the_checker_lists_every_directive_the_host_reads() { + for d in DirectiveName::ALL { + let line = directive_line(d); + let r = check("probe.jsx", format!("{line}\nvar a = 1;\n").as_bytes(), None, &Limits::default()); + let listed: Vec<_> = r.directives.iter().map(|d| d.name.to_string()).collect(); + assert_eq!(listed, [d.as_str()], "{line}"); + } +} diff --git a/crates/js/src/token.rs b/crates/js/src/token.rs index 7998822e53..304ea0e0ab 100644 --- a/crates/js/src/token.rs +++ b/crates/js/src/token.rs @@ -288,17 +288,19 @@ pub enum DirectiveName { } impl DirectiveName { + /// Every directive a preprocessor line can name. + pub const ALL: [DirectiveName; 6] = [ + DirectiveName::Include, + DirectiveName::IncludePath, + DirectiveName::Script, + DirectiveName::Strict, + DirectiveName::Target, + DirectiveName::TargetEngine, + ]; + /// The directive named `name`, compared without case. pub fn from_name(name: &str) -> Option { - const NAMES: [(&str, DirectiveName); 6] = [ - ("include", DirectiveName::Include), - ("includepath", DirectiveName::IncludePath), - ("script", DirectiveName::Script), - ("strict", DirectiveName::Strict), - ("target", DirectiveName::Target), - ("targetengine", DirectiveName::TargetEngine), - ]; - NAMES.iter().find(|(n, _)| n.eq_ignore_ascii_case(name)).map(|(_, d)| *d) + DirectiveName::ALL.into_iter().find(|d| d.as_str().eq_ignore_ascii_case(name)) } pub fn as_str(self) -> &'static str { diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index b8f887ff37..b7c70345d0 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -239,6 +239,10 @@ enum Pending<'s> { MenuString(Option, &'s str), /// `.open(`: a string literal with the open mode may follow. Open(Option), + /// A File object's `length`, `hidden` or `readonly` (`f.length`, `f['length']`): an assignment + /// or an update (`++`, `--`) that sets it may follow. With `true`, a prefix update came before + /// the receiver, and it sets the property unless a member or a call follows it. + Setter(Option, bool), /// A platform name where a property key or a label may stand (first, or after `{`, `,`, `;` or /// `}`): it is a key or a label when `:` follows. Name(&'s str, Option), diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index b5dd2299eb..7bf8c9d203 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -1,6 +1,6 @@ //! The platform features, menu commands and later syntax the analysis recognises. -use super::{Analyzer, FeatureId, NEWER, OutsideId, Pending, Sig, T, catalog, is, member_mark, newer_number, report, unquote, word}; +use super::{Analyzer, COMPOUND, FeatureId, NEWER, OutsideId, Pending, Sig, T, catalog, is, member_mark, newer_number, report, unquote, word}; /// A global name of the platform the report looks for (`$`, `File`, `Socket`, `alert`, `eval`…). pub(super) fn platform_name(n: &str) -> bool { @@ -72,6 +72,17 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.open_mode(&unquote(t.text, 2), l); } } + Pending::Setter(l, prefix) => { + let sets = if prefix { + !t.is(".") && !t.is("[") && !t.is("(") + } else { + // An update operator after a line break belongs to the next line's operand. + t.kind == T::Punct && (t.text == "=" || COMPOUND.contains(&t.text) || (matches!(t.text, "++" | "--") && !t.nl)) + }; + if sets { + self.file_setter(l); + } + } } match t.kind { T::Ident => self.name(t, line), @@ -113,7 +124,29 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { match pending { Pending::Window(l) | Pending::WindowType(l) => self.acc.feature(FeatureId::ScriptuiWindow, l), Pending::Menu(l) | Pending::MenuString(l, _) => self.menu(None, l), - Pending::Open(_) | Pending::Name(..) | Pending::None => {} + Pending::Setter(l, true) => self.file_setter(l), + Pending::Open(_) | Pending::Setter(_, false) | Pending::Name(..) | Pending::None => {} + } + } + + /// A File object's `length`, `hidden` or `readonly` set at `line`: the file changes. + fn file_setter(&mut self, line: Option) { + self.acc.feature(FeatureId::FileWrite, line); + self.acc.outside(OutsideId::FilesWritten, line, None); + } + + /// `name`, a property of `receiver` read with `.` or as a string literal in brackets, `before` + /// coming before the receiver: when it is a File object's setter, the next token says whether it + /// is set ([`Pending::Setter`]). An update operator in `before` is a prefix (`++f.length`) when + /// the receiver is on its line, or when it starts a line or comes where an expression may start; + /// otherwise it ends the operand before it (`i++` and a line break, then `f.length`). + fn setter(&mut self, name: &str, receiver: Option>, before: Option>, line: Option) { + if catalog::FILE_SETTERS.contains(&name) && self.file_receiver(receiver, before) { + // Before a receiver that ends in `)` (`new File(i++).length`), the operator is inside the + // parentheses. + let update = before.filter(|b| (b.is("++") || b.is("--")) && receiver.is_some_and(|r| r.kind == T::Ident)); + let prefix = update.is_some_and(|b| b.nl || b.expr || receiver.is_some_and(|r| !r.nl)); + self.pending = Pending::Setter(line, prefix); } } @@ -170,6 +203,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { if n == catalog::REFLECT { self.acc.feature(FeatureId::Reflection, line); } + self.setter(n, h1, h2, line); return; } if member_mark(h0) { @@ -231,6 +265,11 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { fn punct(&mut self, t: &Sig<'s>, line: Option) { let [h0, h1, h2, h3] = self.h; match t.text { + // `f['length']`: a File object's setter may follow. + "]" if is(h1, "[") && h0.is_some_and(|s| s.kind == T::Str) => { + let name = h0.map(|s| unquote(s.text, 16)).unwrap_or_default(); + self.setter(&name, h2, h3, line); + } "(" => self.call(line), // `Name.prototype["+"] = …` defines an operator. "=" => { @@ -251,10 +290,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { let Some(callee) = h0.filter(|s| s.kind == T::Ident) else { return }; let n = callee.text; if is(h1, ".") { - // The receiver is a variable holding a File or Folder object (not a property of the same - // name), or a File or Folder object made in place or held in grouping parentheses - // ([`Sig::file`]). - let file = h2.is_some_and(|r| r.file || (r.kind == T::Ident && !member_mark(h3) && self.files.contains(r.text))); + let file = self.file_receiver(h2, h3); if n == catalog::MENU_COMMAND { self.pending = Pending::Menu(line); } else if n == catalog::OPEN && file { @@ -288,6 +324,13 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } + /// Whether `receiver`, which `before` comes before, is a variable holding a File or Folder object + /// (not a property of the same name), or a File or Folder object made in place or held in + /// grouping parentheses ([`Sig::file`]). + fn file_receiver(&self, receiver: Option>, before: Option>) -> bool { + receiver.is_some_and(|r| r.file || (r.kind == T::Ident && !member_mark(before) && self.files.contains(r.text))) + } + fn string(&mut self, t: &Sig<'s>, line: Option) { let [h0, h1, h2, _] = self.h; if t.text.contains(catalog::ACTION_TEXT) { diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index 8954736d25..6f25fe6df3 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -32,6 +32,9 @@ pub(crate) const FOLDER: &str = "Folder"; pub(crate) const FILE_READS: &[&str] = &["read", "readch", "readln"]; pub(crate) const FOLDER_READS: &[&str] = &["getFiles"]; pub(crate) const FILE_WRITES: &[&str] = &["write", "writeln", "remove", "rename", "copy", "createAlias", "create"]; +/// The properties of a File object whose setting changes the file: its length, and its hidden and +/// read-only flags. +pub(crate) const FILE_SETTERS: &[&str] = &["length", "hidden", "readonly"]; pub(crate) const FILE_DIALOGS: &[&str] = &["openDialog", "saveDialog"]; pub(crate) const FOLDER_DIALOGS: &[&str] = &["selectDialog"]; pub(crate) const INSTANCE_DIALOGS: &[&str] = &["openDlg", "saveDlg", "selectDlg"]; diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 853f212c11..cf71cefc0f 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -530,6 +530,40 @@ fn the_scripts_own_platform_names_are_not_the_platforms() { assert_eq!(r.outside.iter().map(|o| o.id).collect::>(), ["filesWritten"]); } +/// Setting a File object's length, hidden or read-only flag changes the file; reading them, comparing +/// them and setting them on another object does not. +#[test] +fn setting_a_files_length_or_flags_writes_it() { + let r = report(concat!( + "var f = new File(p);\n", + "f.length = 0;\n", + "f.readonly = true;\n", + "f.hidden |= 1;\n", + "f.length++;\n", + "new File(q).length = 4;\n", + "if (x) --f.length;\n", + "f['readonly'] = false;\n", + "++\n", + "f.length;\n", + "var k = ++\n", + "f['length'];\n", + "++f.length.x; var z = new File(i++).length;\n", + "var n = f.length;\n", + "if (f.readonly == true) {}\n", + "o.length = 0;\n", + "o.f.length = 0;\n", + "var s = [1]; s.length = 0;\n", + "var m = f['length'];\n", + "i++\n", + "f.length;\n", + "f.length\n", + "++i;\n", + )); + let outside: Vec<(&str, &[usize])> = r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect(); + assert_eq!(outside, [("filesWritten", &[2, 3, 4, 5, 6, 7, 8, 10, 12][..])]); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[2, 3, 4, 5, 6, 7, 8, 10, 12][..])); +} + #[test] fn a_function_after_a_line_that_ends_a_statement_is_a_declaration() { let r = report("var n = 1\nfunction File() {}\nFile('x');\nvar m = 2 /* a\n */ function Socket() {}\nnew Socket();\n"); diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..25ac2afa31 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2556,10 +2556,10 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script, - `menuCommands.strings` lists the string literals the script passes to `executeMenuCommand` (`app.executeMenuCommand('…')`), each with a count and its lines, and `menuCommands.dynamic` counts the calls whose argument isn't a string literal. -- `outside` lists what the script does outside the document: `filesWritten` (with the open modes used), - `filesOpened` (files opened in other apps), `network`, `nativeCode`, `otherApps` (messages to other apps), - `environment` (environment variables), `unseenCode` (`eval`, `new Function` and `$.evalFile`) and - `preferences` (the reference app's preferences changed). +- `outside` lists what the script does outside the document: `filesWritten` (with the open modes used; setting a + File object's `length`, `hidden` or `readonly` counts too), `filesOpened` (files opened in other apps), `network`, + `nativeCode`, `otherApps` (messages to other apps), `environment` (environment variables), `unseenCode` (`eval`, + `new Function` and `$.evalFile`) and `preferences` (the reference app's preferences changed). - `problems` lists what would stop the script loading as written (strings, comments, regular expressions, template literals and XML literals that aren't closed, brackets that don't match, syntax newer than ES3 and unknown directives) and notes on its text (bytes that aren't valid UTF-8, mixed line endings, and nesting deeper From b2e77841607351cfbe93aeea9342baa982789053 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 19:05:54 -0800 Subject: [PATCH 38/38] Docs: progress line for the script checker's File setters and host test docs/target-app-parity.md gets a line for the file.write report on a File object's length, hidden and readonly and for the test that lists every name the script host adds, with the tests that cover them. The test's comment on vc no longer names another app. --- crates/engine/tests/it/script_host_vs_scriptcheck.rs | 5 ++--- docs/target-app-parity.md | 1 + 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index aaf3f8acda..660433b800 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -72,9 +72,8 @@ const INSIDE: &[(&str, &str)] = &[ ), ]; -/// The name the checker does not read, which also stands for its members: `script.check` reads -/// scripts written for the reference app, `vc` is VectorCraft's own API, and what `vc.run` does -/// depends on the command it runs. +/// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's +/// own API, and what `vc.run` does depends on the command it runs. const NOT_CHECKED: &str = "vc"; /// An expression whose value is the list of names, one to a line. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 57ac87a396..9933a858b0 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1071,6 +1071,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Headless CLI (`vectorcraft-cli run`, `convert`, `info`, `bench`, `perf`, `mcp`). A `run` step, like a `command_batch` step over MCP, can use an earlier step's result (`"$1.id"`, #785); `run --commands FILE` (or `-` for standard input) reads the steps from a JSON array or JSON Lines, past the Windows command-line limit (#3147, `apps/vectorcraft-cli/tests/it/cli.rs` `run_reads_*`, `run_refuses_malformed_commands_naming_the_step`). - File › Scripts › Check Script… reads a script written for Illustrator (`.jsx`, `.jsxinc` or a compiled `.jsxbin`) without running any of it and reports what it needs (the document model, files, dialogs, menu commands, features only Illustrator has), what it would do outside the document, the menu commands and document-model members it uses, its directives and included files, and the problems that would stop it loading (`script.check`, which also reads `.js` files); File › Open and drag-and-drop show the report for `.jsx`, `.jsxinc` and `.jsxbin` files. - Check Script reads names by the same identifier rule as `vectorcraft-js`: Unicode 17.0 `ID_Start` characters, `$` and `_` start a name, and `ID_Continue` characters and `$` continue it (https://www.unicode.org/reports/tr31/, https://tc39.es/ecma262/#sec-names-and-keywords). U+2118, U+203F, U+00B7 and the zero width non-joiner and joiner are name characters, and U+00B2 and U+2E2F are not. Of the characters Unicode 17.0 assigned, U+088F starts a name and U+1ACF may follow its first character. A `\uXXXX` escape is read as its character only where a name may hold it, so `\u0030abc` does not become a name that starts with a digit; a `\u{…}` escape takes any number of hexadecimal digits up to U+10FFFF, and one that is empty, unclosed, out of range or a surrogate is not part of a name. Each `\u{…}` escape read in a name is reported as syntax newer than ES3, which has only the four-digit form (https://ecma-international.org/wp-content/uploads/ECMA-262_3rd_edition_december_1999.pdf, section 7.6). A private name may start with an escape (`this.#\u{61}pp` is the private name `#app`), and a private name at the start of a line inside braces is not read as a directive unless its name is a directive's. Tests: `crates/scriptcheck/src/tests.rs` (`names_are_made_of_the_unicode_identifier_characters`, `an_escape_stands_for_a_character_only_where_a_name_may_hold_it`, `braced_escapes_in_names_are_read_by_their_value`, `braced_name_escape_reports_later_syntax_and_member`, `private_names_with_escaped_starts_are_single_tokens`, `private_name_at_line_start_is_not_a_directive`), `crates/engine/tests/it/js_lexer_vs_scriptcheck.rs` (`both_lexers_take_the_same_characters_into_names`). + - Check Script reports `file.write` and `filesWritten` when a script sets a File object's `length`, `hidden` or `readonly` (https://extendscript.docsforadobe.dev/file-system-access/file-object/), by plain or compound assignment, `++` or `--`, or the name as a string literal in brackets. A test lists every global and member the script host adds to the JavaScript engine, except VectorCraft's own `vc` and its members, and fails when one has no row; for each one that reaches outside the document it checks that `script.check` reports the expected `outside` id, and it checks that the checker lists every directive the host reads. Tests: `crates/scriptcheck/src/tests.rs` (`setting_a_files_length_or_flags_writes_it`), `crates/engine/tests/it/script_host_vs_scriptcheck.rs` (`every_name_the_host_adds_has_a_row`, `every_name_that_reaches_outside_has_its_checker_id`, `the_checker_lists_every_directive_the_host_reads`). - `vectorcraft-js` parses JavaScript as ECMAScript 5.1 defines it, with the legacy octal forms, block functions and lenient regular expressions of Annex B, into a syntax tree with source spans; it reads the `#target`, `#include` and other preprocessor lines as directives without running them, and a script that breaks the grammar or an early-error rule gives a `SyntaxError` with its line and column. Nesting past the parser's depth limit (`Options::max_depth`, 200 by default) gives a `SyntaxError` instead of exhausting the stack. `cargo xtask test262` fetches the conformance suite at a pinned commit and parses its ES5 tests: 5,411 of 5,418 runs pass (the 7 others use `let` and `const`). This entry covers parsing; the next entry covers running scripts. Tests: `crates/js/src/tests.rs`, `crates/engine/tests/it/js_lexer_vs_scriptcheck.rs`. - `vectorcraft-js` identifiers, written out or as `\uXXXX` and `\u{...}` escapes, take the characters Unicode's `ID_Start` and `ID_Continue` properties allow (https://www.unicode.org/reports/tr31/), plus `$` and, at the start, `_`, as later ECMAScript editions define them (https://tc39.es/ecma262/#sec-names-and-keywords). `Other_ID_Start` characters such as U+2118 and `Other_ID_Continue` characters such as U+00B7 and the zero width non-joiner and joiner are accepted, and no `Pattern_Syntax` or `Pattern_White_Space` character is. Letter categories come from Unicode 17.0, so U+088F starts an identifier and U+1ACF may follow its first character; characters assigned after Unicode 17.0 are not yet identifier characters. Tests: `crates/js/src/tests.rs` (`identifier_characters_are_unicode_17_id_start_and_id_continue`, which checks every code point, `identifiers_take_the_characters_unicode_17_assigned`, `identifiers_take_the_other_id_start_and_continue_characters`, `identifiers_refuse_pattern_syntax_surrogates_and_bad_escapes`, `no_pattern_syntax_or_white_space_character_is_an_identifier_character`). - `vectorcraft-js`'s `Realm` runs ECMAScript 5.1 scripts: the parsed script compiles to verified bytecode that a non-recursive interpreter runs, with closures, `this`, `arguments`, `with`, direct and indirect `eval`, `new Function`, `try`/`catch`/`finally`, labeled `break` and `continue`, and `for`-`in` in insertion order, over a mark-and-sweep heap, with the built-ins the next two entries list. Every run is bounded by fuel, heap bytes, frames, nested host calls and an interrupt flag (smaller defaults in the wasm build), and a run that reaches a limit stops with a limit error that `try` cannot catch. `cargo xtask test262` also runs the suite's ES5 language tests that need only the built-ins present: 4,280 of 4,286 runs pass (4 of the others expect the completion values of later editions, and 2 expect a configurable function `length`). The app does not call it yet. Tests: `crates/js/src/interp_tests.rs`, `crates/js/tests/test262.rs`.