From e3ccd346add9c2bb196d9181b27d4e4eeb50a575 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 16:40:51 -0800 Subject: [PATCH 01/53] 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/53] 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/53] 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/53] 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/53] 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/53] 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/53] 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/53] 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/53] 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/53] 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/53] 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/53] 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/53] 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/53] 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/53] 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/53] 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/53] 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/53] 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/53] 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/53] 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/53] 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/53] 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/53] 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/53] 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/53] 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/53] 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/53] 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/53] 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/53] 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/53] 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/53] 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 4ed194779e42c3b0013bd5dca007b83a8a53c2a9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:37:59 -0800 Subject: [PATCH 32/53] Type: tests check where the Single-line Composer sets lines around text wrap composer_x_mixed_sizes_around_text_wrap and composer_x_mixed_sizes_overflow_around_text_wrap compared only the Single-line Composer's line texts with the Every-line Composer's. Both tests now run their room, overflow and wrap-object checks on each composer, so a Single-line layout that breaks the same lines but sets a span past its room or into the object fails. --- crates/text/src/tests/combos.rs | 73 +++++++++++++++++---------------- 1 file changed, 37 insertions(+), 36 deletions(-) diff --git a/crates/text/src/tests/combos.rs b/crates/text/src/tests/combos.rs index a2d837e286..aca8d6bbde 100644 --- a/crates/text/src/tests/combos.rs +++ b/crates/text/src/tests/combos.rs @@ -421,26 +421,27 @@ fn composer_x_mixed_sizes_around_text_wrap() { let l = layout(db(), &t); (line_texts(&t, &l), l, t) }; - let (every, l, t) = set(Composer::EveryLine); - assert_eq!( - every, - ["Destroy all creatures with", "toughness\u{a0}X", "or less. Then", "draw a card for", "each creature", "destroyed this", "way."] - ); - assert!(past_their_room(&t, &l).is_empty() && !l.overflow, "{:?}", l.lines); - // Two spans share each baseline beside the object. - assert_eq!(l.lines[1].baseline, l.lines[2].baseline); - assert!(l.lines[1].ascent > 30.0 && l.lines[2].avail.0 > object.x1, "{:?}", l.lines); - let text = t.plain_text(); - let hits = l.glyphs.iter().filter(|g| { - let li = &l.lines[g.line]; - let across = li.baseline - li.ascent < object.y1 && li.baseline + li.descent > object.y0; - across && !text[g.byte..].starts_with(char::is_whitespace) && g.origin.x < object.x1 && g.origin.x + g.advance > object.x0 - }); - assert_eq!(hits.count(), 0, "{:?}", l.lines); // The single-line composer measures each line across its height too, and breaks this - // paragraph the same way. - let (greedy, _, _) = set(Composer::SingleLine); - assert_eq!(every, greedy); + // paragraph the same way, with its lines set clear of the object as well. + for composer in [Composer::EveryLine, Composer::SingleLine] { + let (texts, l, t) = set(composer); + assert_eq!( + texts, + ["Destroy all creatures with", "toughness\u{a0}X", "or less. Then", "draw a card for", "each creature", "destroyed this", "way."], + "{composer:?}" + ); + assert!(past_their_room(&t, &l).is_empty() && !l.overflow, "{composer:?}: {:?}", l.lines); + // Two spans share each baseline beside the object. + assert_eq!(l.lines[1].baseline, l.lines[2].baseline, "{composer:?}"); + assert!(l.lines[1].ascent > 30.0 && l.lines[2].avail.0 > object.x1, "{composer:?}: {:?}", l.lines); + let text = t.plain_text(); + let hits = l.glyphs.iter().filter(|g| { + let li = &l.lines[g.line]; + let across = li.baseline - li.ascent < object.y1 && li.baseline + li.descent > object.y0; + across && !text[g.byte..].starts_with(char::is_whitespace) && g.origin.x < object.x1 && g.origin.x + g.advance > object.x0 + }); + assert_eq!(hits.count(), 0, "{composer:?}: {:?}", l.lines); + } } #[test] @@ -581,23 +582,23 @@ fn composer_x_mixed_sizes_overflow_around_text_wrap() { let l = layout(db(), &t); (line_texts(&t, &l), l, t) }; - let (every, l, t) = set(Composer::EveryLine); - assert!(l.overflow && l.lines.len() >= 3, "{:?}", l.lines); - assert!(l.lines.windows(2).all(|p| p[0].end == p[1].start && p[0].start < p[0].end), "{:?}", l.lines); - assert!(past_their_room(&t, &l).is_empty(), "{:?}", l.lines); - let text = t.plain_text(); - let hits = l.glyphs.iter().filter(|g| { - let li = &l.lines[g.line]; - let across = li.baseline - li.ascent < object.y1 && li.baseline + li.descent > object.y0; - across && !text[g.byte..].starts_with(char::is_whitespace) && g.origin.x < object.x1 && g.origin.x + g.advance > object.x0 - }); - assert_eq!(hits.count(), 0, "{:?}", l.lines); - // The lines that fit break as in `composer_x_mixed_sizes_around_text_wrap`'s taller frame. - assert_eq!(every, ["Destroy all creatures with", "toughness\u{a0}X", "or less. Then", "draw a card for", "each creature"]); - // The single-line composer measures each line across its height too, and breaks the lines - // that fit the same way. - let (greedy, ..) = set(Composer::SingleLine); - assert_eq!(every, greedy); + // The single-line composer measures each line across its height too, and breaks and sets the + // lines that fit the same way. + for composer in [Composer::EveryLine, Composer::SingleLine] { + let (texts, l, t) = set(composer); + assert!(l.overflow && l.lines.len() >= 3, "{composer:?}: {:?}", l.lines); + assert!(l.lines.windows(2).all(|p| p[0].end == p[1].start && p[0].start < p[0].end), "{composer:?}: {:?}", l.lines); + assert!(past_their_room(&t, &l).is_empty(), "{composer:?}: {:?}", l.lines); + let text = t.plain_text(); + let hits = l.glyphs.iter().filter(|g| { + let li = &l.lines[g.line]; + let across = li.baseline - li.ascent < object.y1 && li.baseline + li.descent > object.y0; + across && !text[g.byte..].starts_with(char::is_whitespace) && g.origin.x < object.x1 && g.origin.x + g.advance > object.x0 + }); + assert_eq!(hits.count(), 0, "{composer:?}: {:?}", l.lines); + // The lines that fit break as in `composer_x_mixed_sizes_around_text_wrap`'s taller frame. + assert_eq!(texts, ["Destroy all creatures with", "toughness\u{a0}X", "or less. Then", "draw a card for", "each creature"], "{composer:?}"); + } } #[test] From adda7c1c6ec33e2bf24a8479349fbaedb4af2d1a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:40:31 -0800 Subject: [PATCH 33/53] Tests: font changes on other threads wait while a Type layout count runs The Type overlay layout-count tests in vectorcraft-tools held a read lock that only tests which add fonts or change hyphenation exceptions take for writing. Other tests still load system fonts on demand (a fallback for a character no loaded font covers, a cataloged family on first use), which changes FontDb::global()'s generation, the key of every kept frame layout. type_overlays_keep_at_most_frame_layouts_max then laid out 2051 frames instead of 2 in 18 of 21 full `cargo test -p vectorcraft-tools --lib` runs on Linux. vectorcraft_text::test_fonts::steady_fonts (test and test-fonts builds only) now holds back font changes on other threads: adding faces, a rescan and setting or removing a composite font wait before they publish anything. A first scan does not wait, and steady_fonts catalogs the database before it returns. steady_layout_inputs() takes it for the global database. With it, 0 of 20 full runs failed. --- crates/text/src/fontdb/composite.rs | 4 + crates/text/src/fontdb/db.rs | 7 +- crates/text/src/test_fonts.rs | 130 ++++++++++++++++++++++++++++ crates/text/src/tests/sysfonts.rs | 115 ++++++++++++++++++++++++ crates/tools/src/lib.rs | 8 +- 5 files changed, 261 insertions(+), 3 deletions(-) diff --git a/crates/text/src/fontdb/composite.rs b/crates/text/src/fontdb/composite.rs index 7b17fb74de..bdcb84ae8c 100644 --- a/crates/text/src/fontdb/composite.rs +++ b/crates/text/src/fontdb/composite.rs @@ -91,6 +91,8 @@ impl FontDb { /// guard's thread uses the fonts it lends and not this one. pub fn set_composite_font(&self, font: &CompositeFont) -> bool { let key = font.name.to_lowercase(); + #[cfg(any(test, feature = "test-fonts"))] + let _change = crate::test_fonts::font_change(); { let mut map = self.composites.write().unwrap_or_else(|e| e.into_inner()); if map.get(&key).is_some_and(|f| **f == *font) { @@ -104,6 +106,8 @@ impl FontDb { /// Forget the composite font named `name` (any case). Whether there was one. pub fn remove_composite_font(&self, name: &str) -> bool { + #[cfg(any(test, feature = "test-fonts"))] + let _change = crate::test_fonts::font_change(); let removed = self.composites.write().unwrap_or_else(|e| e.into_inner()).remove(&name.to_lowercase()).is_some(); if removed { self.changed(); diff --git a/crates/text/src/fontdb/db.rs b/crates/text/src/fontdb/db.rs index 3be2c871de..046db94dfd 100644 --- a/crates/text/src/fontdb/db.rs +++ b/crates/text/src/fontdb/db.rs @@ -305,6 +305,8 @@ impl FontDb { } } } + #[cfg(any(test, feature = "test-fonts"))] + let _change = (!made.is_empty()).then(crate::test_fonts::font_change); let mut faces = self.faces.write().unwrap_or_else(std::sync::PoisonError::into_inner); let before = faces.len(); for f in made { @@ -325,7 +327,7 @@ impl FontDb { /// Catalog the installed fonts unless that has been done: the first caller scans the font /// folders, any other waits for that scan to finish. A no-op on wasm. - pub(super) fn ensure_catalog(&self) { + pub(crate) fn ensure_catalog(&self) { #[cfg(not(target_arch = "wasm32"))] self.cataloged.get_or_init(|| { self.scan_font_dirs(); @@ -448,6 +450,9 @@ impl FontDb { } log::debug!("cataloged {n} system font faces"); let installed: std::collections::HashSet = catalog.values().flat_map(|c| c.faces.iter().map(|cf| cf.path.clone())).collect(); + // The first scan waits for nothing: a guard is made only for a database already cataloged. + #[cfg(any(test, feature = "test-fonts"))] + let _change = self.cataloged.get().is_some().then(crate::test_fonts::font_change); *self.stamp.lock().unwrap_or_else(|e| e.into_inner()) = Some(ScanStamp { paths, modified: modified_at }); *self.catalog.write().unwrap_or_else(|e| e.into_inner()) = catalog; *self.aliases.write().unwrap_or_else(|e| e.into_inner()) = aliases; diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index 7a2a23f089..1ba4fe3f99 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -45,6 +45,136 @@ pub fn drop_kept_layouts() { crate::kept::drop_kept_layouts(); } +/// Who holds [`SteadyFonts`] and who changes fonts ([`font_change`]), guarded by [`steadiness`] and +/// signaled through [`STEADINESS_CHANGED`]. +struct Steadiness { + /// Threads that hold a [`SteadyFonts`]. + holders: usize, + /// Font changes waiting to start. + waiting: usize, + /// Of `waiting`, those made on a thread that holds a [`SteadyFonts`]. + holders_waiting: usize, + /// Whether a font change is under way. + changing: bool, +} + +static STEADINESS: std::sync::Mutex = std::sync::Mutex::new(Steadiness { holders: 0, waiting: 0, holders_waiting: 0, changing: false }); +static STEADINESS_CHANGED: std::sync::Condvar = std::sync::Condvar::new(); + +fn steadiness() -> std::sync::MutexGuard<'static, Steadiness> { + STEADINESS.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + +/// Wait for [`STEADINESS_CHANGED`]. +fn await_steadiness(s: std::sync::MutexGuard<'static, Steadiness>) -> std::sync::MutexGuard<'static, Steadiness> { + STEADINESS_CHANGED.wait(s).unwrap_or_else(std::sync::PoisonError::into_inner) +} + +std::thread_local! { + /// How many [`SteadyFonts`] this thread holds. + static STEADY: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Whether this thread holds the [`FontChange`] under way. + static CHANGING: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// While held, a cataloged font database's fonts and its +/// [`FontDb::generation`](crate::FontDb::generation) change only on this thread: a change on another +/// thread (a system font loaded for a character no loaded font covers, fonts added, a rescan, a +/// composite font set or removed) waits until it is dropped, before it publishes anything. A change +/// on this thread waits until no other thread holds one, unless every other thread that holds one is +/// itself waiting to change fonts. Tests hold it to count the layouts that a cache keyed on the +/// generation keeps. The guards one thread holds count as one, until the last of them is dropped, in +/// whatever order they are. +pub struct SteadyFonts { + /// Dropped on the thread that made it. + _thread: std::marker::PhantomData<*const ()>, +} + +impl Drop for SteadyFonts { + fn drop(&mut self) { + let last = STEADY.with(|n| { + n.set(n.get() - 1); + n.get() == 0 + }); + if last { + steadiness().holders -= 1; + STEADINESS_CHANGED.notify_all(); + } + } +} + +/// [`SteadyFonts`] for `db`. Catalogs `db`'s installed fonts first: a first scan does not wait for +/// any guard, so this thread can wait for one running on another thread while it holds a guard. A +/// thread's first guard waits for the font changes under way or waiting. +pub fn steady_fonts(db: &crate::FontDb) -> SteadyFonts { + db.ensure_catalog(); + if STEADY.with(std::cell::Cell::get) == 0 { + let mut s = steadiness(); + while !CHANGING.with(std::cell::Cell::get) && (s.changing || s.waiting > 0) { + s = await_steadiness(s); + } + s.holders += 1; + } + STEADY.with(|n| n.set(n.get() + 1)); + SteadyFonts { _thread: std::marker::PhantomData } +} + +/// Held while a font database's fonts change, from before the change is published until its +/// generation has changed ([`font_change`]). +pub(crate) struct FontChange { + /// Made while this thread already held one (a change made inside another, as a test hook run + /// when faces are published can). + nested: bool, +} + +impl Drop for FontChange { + fn drop(&mut self) { + if !self.nested { + CHANGING.with(|c| c.set(false)); + steadiness().changing = false; + STEADINESS_CHANGED.notify_all(); + } + } +} + +/// [`FontChange`]: waits until no other change is under way and no other thread holds a +/// [`SteadyFonts`] (on a thread that holds one: none that is not itself waiting to change fonts). +/// Inside a change this thread is making, it does not wait. +pub(crate) fn font_change() -> FontChange { + if CHANGING.with(std::cell::Cell::get) { + return FontChange { nested: true }; + } + let holder = STEADY.with(std::cell::Cell::get) > 0; + let mut s = steadiness(); + #[cfg(test)] + font_changers().push(std::thread::current().id()); + s.waiting += 1; + s.holders_waiting += usize::from(holder); + while s.changing || if holder { s.holders > s.holders_waiting } else { s.holders > 0 } { + s = await_steadiness(s); + } + s.waiting -= 1; + s.holders_waiting -= usize::from(holder); + s.changing = true; + CHANGING.with(|c| c.set(true)); + FontChange { nested: false } +} + +/// Whether a font change on another thread would wait now (a [`SteadyFonts`] is held, or another +/// change is under way). +#[cfg(test)] +pub(crate) fn font_changes_held_back() -> bool { + let s = steadiness(); + s.holders > 0 || s.changing +} + +/// The threads that have asked to change a font database's generation ([`font_change`]). +#[cfg(test)] +pub(crate) fn font_changers() -> std::sync::MutexGuard<'static, Vec> { + static CHANGERS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + CHANGERS.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + /// The family of [`variable_font`]. pub const VARIABLE_FAMILY: &str = "Varitest Sans"; diff --git a/crates/text/src/tests/sysfonts.rs b/crates/text/src/tests/sysfonts.rs index ada5c45dd1..06c4db899c 100644 --- a/crates/text/src/tests/sysfonts.rs +++ b/crates/text/src/tests/sysfonts.rs @@ -50,6 +50,121 @@ fn concurrent_fallback_lookups_all_find_the_installed_face() { std::fs::remove_dir(dir).unwrap(); } +/// Two [`test_fonts::steady_fonts`] guards on one thread hold font changes back until the last of +/// them is dropped, whichever was made first. +#[test] +fn steady_fonts_hold_back_font_changes_until_the_last_guard_is_dropped() { + let db = FontDb::with_font_dirs(vec![]); + let outer = crate::test_fonts::steady_fonts(&db); + let inner = crate::test_fonts::steady_fonts(&db); + drop(outer); + assert!(crate::test_fonts::font_changes_held_back(), "the inner guard is still held"); + drop(inner); + let first = crate::test_fonts::steady_fonts(&db); + let second = crate::test_fonts::steady_fonts(&db); + drop(second); + assert!(crate::test_fonts::font_changes_held_back(), "the first guard is still held"); + drop(first); +} + +/// While a thread holds [`test_fonts::steady_fonts`], a font added on another thread, which may +/// hold one too, changes the database's generation only once the guard is dropped. A thread that +/// holds the only guard adds a font itself while another thread's change waits, which then still +/// waits for the guard. +#[test] +fn steady_fonts_hold_back_other_threads_font_changes() { + for guarded in [false, true] { + let db = FontDb::with_font_dirs(vec![]); + let font = crate::test_fonts::variable_font().unwrap(); + let steady = crate::test_fonts::steady_fonts(&db); + let before = db.generation(); + std::thread::scope(|scope| { + let adding = scope.spawn(|| { + let _steady = guarded.then(|| crate::test_fonts::steady_fonts(&db)); + db.add_font(font) + }); + let id = adding.thread().id(); + while !adding.is_finished() && !crate::test_fonts::font_changers().contains(&id) { + std::thread::yield_now(); + } + assert_eq!(db.generation(), before, "guarded {guarded}: the other thread's change waits for the guard"); + let listed = db.families().iter().any(|f| f == crate::test_fonts::VARIABLE_FAMILY); + assert!(!listed, "guarded {guarded}: the other thread publishes the font only once the guard is dropped"); + drop(steady); + assert!(adding.join().unwrap() > 0, "guarded {guarded}: the font is new to this database"); + }); + assert_ne!(db.generation(), before, "guarded {guarded}: the change is made once the guard is dropped"); + } + let db = FontDb::with_font_dirs(vec![]); + let steady = crate::test_fonts::steady_fonts(&db); + std::thread::scope(|scope| { + let adding = scope.spawn(|| db.add_font(crate::test_fonts::two_axis_font().unwrap())); + let id = adding.thread().id(); + while !adding.is_finished() && !crate::test_fonts::font_changers().contains(&id) { + std::thread::yield_now(); + } + let before = db.generation(); + assert!(db.add_font(crate::test_fonts::variable_font().unwrap()) > 0); + let after = db.generation(); + assert_ne!(after, before, "the guard's own thread changes the fonts"); + assert!(!adding.is_finished(), "the waiting change still waits for the guard"); + assert_eq!(db.generation(), after, "the waiting change still waits for the guard"); + drop(steady); + assert!(adding.join().unwrap() > 0); + }); +} + +/// The first scan of a database's installed fonts does not wait for [`test_fonts::steady_fonts`] +/// held for another database, so a thread holding one can catalog a database that another thread +/// is scanning. +#[test] +fn a_first_scan_does_not_wait_for_steady_fonts() { + let (held, scanned) = (FontDb::with_font_dirs(vec![]), FontDb::with_font_dirs(vec![])); + let steady = crate::test_fonts::steady_fonts(&held); + std::thread::scope(|scope| { + let scanning = scope.spawn(|| scanned.load_system_fonts()); + let id = scanning.thread().id(); + while !scanning.is_finished() && !crate::test_fonts::font_changers().contains(&id) { + std::thread::yield_now(); + } + let finished = scanning.is_finished(); + drop(steady); + assert!(finished, "the first scan waited for the guard"); + scanning.join().unwrap(); + }); +} + +/// A font that a hook adds while another add publishes its faces, on the same thread, is added +/// without that thread waiting for its own change. +#[test] +fn a_font_added_while_faces_are_published_is_added() { + let db = Arc::new(FontDb::with_font_dirs(vec![])); + let adder = db.clone(); + // Not scoped: a thread that waits for its own change never finishes, and the test still reports. + let adding = std::thread::spawn(move || { + let (hook_db, mut extra) = (adder.clone(), crate::test_fonts::two_axis_font()); + crate::fontdb::on_faces_published(Some(Box::new(move || { + if let Some(font) = extra.take() { + hook_db.add_font(font); + } + }))); + let added = adder.add_font(crate::test_fonts::variable_font().unwrap()); + crate::fontdb::on_faces_published(None); + added + }); + let id = adding.thread().id(); + let changes = || crate::test_fonts::font_changers().iter().filter(|t| **t == id).count(); + while !adding.is_finished() && changes() < 2 { + std::thread::yield_now(); + } + assert!(adding.is_finished(), "the hook's add waited for the change around it"); + assert!(adding.join().unwrap() > 0); + let families = db.families(); + for family in [crate::test_fonts::VARIABLE_FAMILY, crate::test_fonts::TWO_AXIS_FAMILY] { + assert!(families.iter().any(|f| f == family), "{family} is added"); + } +} + /// A bundled Source Sans 3 file renamed [`FAMILY`] (as long as the original name). fn renamed(file: &str) -> Vec { renamed_to(file, FAMILY) diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 688f295478..98d0b999cb 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -705,8 +705,12 @@ pub(crate) mod testutil { /// and a count must not include a refresh another test caused. static LAYOUT_INPUTS: std::sync::RwLock<()> = std::sync::RwLock::new(()); - pub fn steady_layout_inputs() -> std::sync::RwLockReadGuard<'static, ()> { - LAYOUT_INPUTS.read().unwrap_or_else(|e| e.into_inner()) + /// Catalogs the installed fonts, then also holds back the font changes other tests make without + /// [`changing_layout_inputs`] (a system font loaded for a character no loaded font covers, a + /// rescan) until it is dropped. + pub fn steady_layout_inputs() -> (std::sync::RwLockReadGuard<'static, ()>, vectorcraft_text::test_fonts::SteadyFonts) { + let inputs = LAYOUT_INPUTS.read().unwrap_or_else(|e| e.into_inner()); + (inputs, vectorcraft_text::test_fonts::steady_fonts(vectorcraft_text::FontDb::global())) } pub fn changing_layout_inputs() -> std::sync::RwLockWriteGuard<'static, ()> { From f88a6b5877a8826fe4c3a1a6ed6e2152a1b93846 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:47:54 -0800 Subject: [PATCH 34/53] 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 35/53] 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 9455a3f10e4f16178753337974d3665e4318fe71 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:56:57 -0800 Subject: [PATCH 36/53] Dimension: a first Linear point keeps its link when the art moves before the second click A first point picked on a corner of a path's preview bounds was linked to the path only at the second click, by fitting the coordinate from the first click to the path's anchors as they were then. When the path moved in between, the dimension measured from where the corner had been: picking the upper-left corner of a stroked rectangle, moving the rectangle 20 points right and picking its upper-right corner measured 121 points instead of 101. The tool now records the first point's link at its click (held against the corner's path, or on the segment under it) and keeps that link for the dimension while it still resolves. The first point, the rubber band, Shift and the dimension start from where the art puts the point now, and a first point on an anchor follows its anchor the same way. A link that no longer resolves falls back to the point as picked. --- crates/tools/src/dimension.rs | 143 +++++++++++++++++++++++++++++++--- docs/dimensions.md | 5 +- 2 files changed, 135 insertions(+), 13 deletions(-) diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index 5e2e179bdf..46cc0694e8 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -77,6 +77,10 @@ pub struct DimensionTool { /// The path that holds the first Linear point, when it was picked on a corner of that path's /// preview bounds. first_corner: Option, + /// The link the first Linear point took at its click when it was not on an anchor: held + /// against the path whose preview-bounds corner it was picked on, or on the segment under it. + /// When the art moves before the second click, the first point moves with it. + first_link: Option, /// Whether the press under way began on an anchor a Linear click picks. press_on_anchor: bool, /// The second point clicked for the Linear dimension being placed, and where the pointer was @@ -564,28 +568,34 @@ fn nearest_on(cx: &ToolContext, edge: &SegmentRef, p: Point) -> Option { /// point, so that it moves with that path. None when neither point has a path to link to. /// `held_a` and `held_b` name the path holding a point picked on a corner of that path's /// preview bounds: such a point is held against that path, however far its strokes or effects -/// put the corner from the path and whatever other segment lies there. +/// put the corner from the path and whatever other segment lies there. `link_a` is the link the +/// first point took at its own click ([`own_link`]): while it still resolves, the point keeps it, +/// whatever other art lies there now. fn points_source( cx: &ToolContext, (a, ra, held_a): (Point, &Option, Option), (b, rb, held_b): (Point, &Option, Option), + link_a: Option, ) -> Option { // A path deleted since the pick holds nothing. let holder = |held: Option| held.filter(|node| cx.doc.node(*node).is_some()); let (corner_a, corner_b) = (holder(held_a), holder(held_b)); + let link_a = link_a.filter(|link| ra.is_none() && link.position(cx.doc).is_some()); let edge = |p: Point, corner: Option| if corner.is_some() { None } else { pick(cx, p) }; - let (edge_a, edge_b) = (edge(a, corner_a), edge(b, corner_b)); + let (edge_a, edge_b) = (if link_a.is_some() { None } else { edge(a, corner_a) }, edge(b, corner_b)); let node = |r: &Option, corner: Option, e: &Option| { r.as_ref().map(|r| r.node).or(corner).or_else(|| e.as_ref().map(|e| e.node)) }; - let (path_a, path_b) = (node(ra, corner_a, &edge_a), node(rb, corner_b, &edge_b)); + let path_a = link_a.as_ref().map(FreePoint::node).or_else(|| node(ra, corner_a, &edge_a)); + let path_b = node(rb, corner_b, &edge_b); let free = |p: Point, r: &Option, edge: &Option, own: Option, other: Option| { if r.is_some() { return None; } edge.as_ref().and_then(|e| FreePoint::on_segment(cx.doc, e, p)).or_else(|| own.or(other).and_then(|node| FreePoint::on(cx.doc, node, p))) }; - let (free_a, free_b) = (free(a, ra, &edge_a, path_a, path_b), free(b, rb, &edge_b, path_b, path_a)); + let free_a = link_a.or_else(|| free(a, ra, &edge_a, path_a, path_b)); + let free_b = free(b, rb, &edge_b, path_b, path_a); (ra.is_some() || rb.is_some() || free_a.is_some() || free_b.is_some()).then(|| DimensionSource::Points { a: ra.clone(), b: rb.clone(), @@ -595,6 +605,17 @@ fn points_source( }) } +/// The link a point picked at `p` off any anchor takes from its own pick, as [`points_source`] +/// links it: held against `corner`'s path when it was picked on a corner of that path's preview +/// bounds, else on the segment under it, or held against that segment's path. None when nothing +/// under it holds it. +fn own_link(cx: &ToolContext, p: Point, corner: Option) -> Option { + match corner.filter(|node| cx.doc.node(*node).is_some()) { + Some(node) => FreePoint::on(cx.doc, node, p), + None => pick(cx, p).and_then(|e| FreePoint::on_segment(cx.doc, &e, p).or_else(|| FreePoint::on(cx.doc, e.node, p))), + } +} + impl DimensionTool { /// Where a Linear pick at `p` lands: with Use Preview Bounds on, on the nearest corner of a /// path's preview bounds within reach, where they differ from its anchors, unless another @@ -610,6 +631,7 @@ impl DimensionTool { /// A point the guides leave where the pointer is (right on a guide line) stays there, and with /// Snap to Pixel or Snap to Grid on a point stays where they place it. fn snap_linear(&mut self, cx: &ToolContext, p: Point) -> (Point, Option) { + self.follow_first(cx); let leave = self.points.last().map(|(first, anchor)| match anchor { Some(_) => crate::guides::Leave::segment(cx, *first, false), None => crate::guides::Leave::contact(*first), @@ -652,6 +674,26 @@ impl DimensionTool { None => (p, None), } } + /// Moves the first Linear point to where its link puts it in the document as it is now: on + /// its anchor, or where [`Self::first_link`] holds it. A point whose link no longer resolves, + /// or that has none, stays where it was picked. + fn follow_first(&mut self, cx: &ToolContext) { + if let Some(now) = self.first_now(cx) + && let [(at, _)] = self.points.as_mut_slice() + { + *at = now; + } + } + /// Where the first Linear point is in the document as it is now ([`Self::follow_first`]), + /// while it is the only point picked. + fn first_now(&self, cx: &ToolContext) -> Option { + let [(at, reference)] = self.points.as_slice() else { return None }; + let now = match reference { + Some(r) => r.position(cx.doc), + None => self.first_link.as_ref().and_then(|link| link.position(cx.doc)), + }; + Some(now.unwrap_or(*at)) + } fn target(&self, cx: &ToolContext, p: Point) -> Option { let edge = pick(cx, p)?; match self.kind { @@ -800,6 +842,7 @@ impl DimensionTool { self.on_end = false; self.corner = None; self.first_corner = None; + self.first_link = None; self.points.clear(); self.lines.clear(); self.dragging = false; @@ -824,12 +867,13 @@ impl DimensionTool { reference = reference.filter(|r| r.position(cx.doc) == Some(at)); corner = corner.filter(|_| at.distance(snapped) <= 1e-9); } - self.points.push((at, reference)); - if self.points.len() == 1 { + if self.points.is_empty() { self.first_corner = corner; + self.first_link = reference.is_none().then(|| own_link(cx, at, corner)).flatten(); } + self.points.push((at, reference)); if let [(a, ra), (b, rb)] = self.points.as_slice() { - let source = points_source(cx, (*a, ra, self.first_corner), (*b, rb, corner)); + let source = points_source(cx, (*a, ra, self.first_corner), (*b, rb, corner), self.first_link.take()); self.first_corner = None; let mut d = self.recipe(DimensionMode::Linear, *a, *b, Point::ZERO, source); if d.resolve(cx.doc).is_ok() { @@ -1041,8 +1085,10 @@ impl Tool for DimensionTool { None => {} } } + // The first point where the art puts it now, also when the art moved without a pointer move. + let first = self.first_now(cx); for (p, _) in &self.points { - out.push(Overlay::Anchor { p: *p, color, filled: true, size: 6.0 }); + out.push(Overlay::Anchor { p: first.unwrap_or(*p), color, filled: true, size: 6.0 }); } for edge in &self.lines { segment(edge, &mut out); @@ -1057,10 +1103,10 @@ impl Tool for DimensionTool { let on_anchor = reference.is_some() || self.on_end; out.push(Overlay::Anchor { p: *q, color, filled: !on_anchor, size: if on_anchor { 10.0 } else { 6.0 } }); } - if let Some((p, _)) = self.points.last() { + if let Some(p) = first.or_else(|| self.points.last().map(|(p, _)| *p)) { let target = snapped.map_or(self.at, |(q, _)| q); - let b = if self.shift { constrained(cx, *p, target) } else { target }; - out.push(Overlay::Line { a: *p, b, color, dashed: true }); + let b = if self.shift { constrained(cx, p, target) } else { target }; + out.push(Overlay::Line { a: p, b, color, dashed: true }); } // The Smart Guides of the point the next click picks (after the rubber band). if linear_pick { @@ -1814,7 +1860,7 @@ mod tests { let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) }; let (corner, b) = (Point::new(99.5, 99.5), Point::new(250.0, 99.5)); for (held, node) in [(Some(id), id), (None, line)] { - let source = points_source(&c, (corner, &None, held), (b, &None, None)); + let source = points_source(&c, (corner, &None, held), (b, &None, None), None); let Some(DimensionSource::Points { free_a: Some(free), .. }) = &source else { panic!("{source:?}") }; let linked = match free { FreePoint::Anchors { node, .. } => *node, @@ -1824,6 +1870,79 @@ mod tests { } } + /// A first point keeps its link when the art moves before the second click: a point picked on + /// a corner of the preview bounds, on a segment or on an anchor is measured, shown and + /// constrained by Shift from where the art puts it now. + #[test] + fn a_first_point_follows_art_moved_before_the_second_click() { + let (d, id) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let near = |a: Point, b: Point| a.distance(b) < 1e-9; + let moved = |by: (f64, f64)| { + let mut m = d.clone(); + m.node_mut(id).expect("the rectangle").transform(vectorcraft_geom::Affine::translate(by), false); + m + }; + let click = |t: &mut DimensionTool, c: &ToolContext, (x, y): (f64, f64), shift: bool| { + for kind in [PointerKind::Move, PointerKind::Down, PointerKind::Up] { + let mut ev = PointerEvent::new(kind, x, y); + ev.mods.shift = shift; + t.pointer(c, &ev); + } + }; + let base = |doc| ToolContext { preview_bounds: true, smart_guides: false, snap_to_point: false, ..cx(doc, &s, &p) }; + // A corner of the preview bounds, then the rectangle moved 20 points right. + let right = moved((20.0, 0.0)); + let mut t = DimensionTool::default(); + click(&mut t, &base(&d), (101.0, 101.0), false); + let c = ToolContext { revision: (0, 1), ..base(&right) }; + let shown = t.overlays(&c).into_iter().any(|o| matches!(o, Overlay::Anchor { p, filled: true, .. } if near(p, Point::new(119.5, 99.5)))); + assert!(shown, "the first point shows at the moved corner before the pointer moves"); + t.pointer(&c, &PointerEvent::new(PointerKind::Move, 219.0, 101.0)); + let band = t.overlays(&c).into_iter().any(|o| matches!(o, Overlay::Line { a, dashed: true, .. } if near(a, Point::new(119.5, 99.5)))); + assert!(band, "the rubber band starts at the moved corner"); + click(&mut t, &c, (219.0, 101.0), false); + let pending = t.pending.take().expect("both points were picked"); + assert!(near(pending.a, Point::new(119.5, 99.5)) && near(pending.b, Point::new(220.5, 99.5)), "{:?} {:?}", pending.a, pending.b); + assert!((pending.length - 101.0).abs() < 1e-9, "{}", pending.length); + let Some(DimensionSource::Points { free_a: Some(free), .. }) = &pending.source else { panic!("{:?}", pending.source) }; + assert!(free.position(&right).is_some_and(|q| near(q, Point::new(119.5, 99.5))), "{free:?}"); + // A point on the top segment, then the rectangle moved 20 points down. + let down = moved((0.0, 20.0)); + let mut t = DimensionTool::default(); + let unbounded = |doc| ToolContext { preview_bounds: false, ..base(doc) }; + click(&mut t, &unbounded(&d), (150.0, 100.0), false); + click(&mut t, &ToolContext { revision: (0, 1), ..unbounded(&down) }, (300.0, 300.0), false); + let pending = t.pending.take().expect("both points were picked"); + assert!(near(pending.a, Point::new(150.0, 120.0)), "{:?}", pending.a); + let Some(DimensionSource::Points { free_a: Some(FreePoint::OnSegment { edge, .. }), .. }) = &pending.source else { + panic!("{:?}", pending.source) + }; + assert_eq!(edge.node, id); + // The same, with a line drawn on top along the moved segment before the second click: the + // point keeps the segment it was picked on, where a pick there now finds the line. + let mut covered = down.clone(); + let (l, line) = (covered.layers[0].id, covered.alloc_id()); + let path = + vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(0.0, 120.0), Point::new(300.0, 120.0)], false)); + covered.insert(Some(l), 0, Node::path(line, path, Default::default())).expect("the line"); + let c = unbounded(&covered); + let at = Point::new(150.0, 120.0); + assert_eq!(pick(&c, at).map(|e| e.node), Some(line)); + let link = own_link(&unbounded(&d), Point::new(150.0, 100.0), None); + assert!(matches!(&link, Some(FreePoint::OnSegment { edge, .. }) if edge.node == id), "{link:?}"); + let source = points_source(&c, (at, &None, None), (Point::new(300.0, 300.0), &None, None), link); + let Some(DimensionSource::Points { free_a: Some(FreePoint::OnSegment { edge, .. }), .. }) = &source else { panic!("{source:?}") }; + assert_eq!(edge.node, id, "the line on top does not take the point"); + // An anchor, then the rectangle moved 20 points down: Shift constrains from the anchor's + // new place. + let mut t = DimensionTool::default(); + click(&mut t, &unbounded(&d), (100.0, 100.0), false); + click(&mut t, &ToolContext { revision: (0, 1), ..unbounded(&down) }, (300.0, 124.0), true); + let pending = t.pending.take().expect("both points were picked"); + assert!(near(pending.a, Point::new(100.0, 120.0)) && (pending.b.y - 120.0).abs() < 1e-9, "{:?} {:?}", pending.a, pending.b); + } + /// Hovering right on the end of a dimension's line shows the anchor ring there. #[test] fn hovering_right_on_a_dimension_lines_end_shows_the_anchor_ring() { diff --git a/docs/dimensions.md b/docs/dimensions.md index 7acc2155f6..389154d0a8 100644 --- a/docs/dimensions.md +++ b/docs/dimensions.md @@ -31,7 +31,10 @@ The **Dimension Tool** is in the Modify section of the toolbar. Its strip offers anchor, guide, grid or pixel snapping places lands on the closest point of a segment, or of a line of a dimension already drawn, within 8 pixels. With Smart Guides and Anchor/Path Labels on, a point on an anchor or a line end shows the "anchor" label, and a point on a segment or - line shows the "path" label. These rules apply to the Linear points. + line shows the "path" label. These rules apply to the Linear points. A first point picked on + an anchor, on a segment or on a corner of preview bounds moves with that art when the art moves + before the second click: the rubber band, Shift and the dimension start from where the art puts + the point then. With Use Preview Bounds on (Preferences › General), a Linear point can land on a corner of the preview bounds of a path or compound path whose strokes or effects reach past its anchors. The [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) From 5721f9693195d2e0a55e68537a74aad96680336a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 16:14:07 -0800 Subject: [PATCH 37/53] 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 38/53] 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 b501ea022209a3f3fe323fe8dc1624740b362af9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 16:44:28 -0800 Subject: [PATCH 39/53] Docs: the File formats rows leave out blends a saved .ai keeps live Since #8289 a saved .ai's editing copy keeps live the blends the .ai reader opens with their settings and as they are drawn. The three File formats rows in docs/target-app-parity.md still listed every live object other than four graph types as read back as art. They now name those blends as kept live too. Blends written as their steps stay in the gap, and file-format-parity.md lists them. --- docs/target-app-parity.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 57ac87a396..e9c90f9622 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -311,9 +311,9 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; large images trace with a warning; Auto Color keeps rare distinct colours) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them | | Layers, artboards, document setup | 5 | 78% | Selected-artboard deletion is consistent across panel actions (all-selected retains artboard 1); history prunes removed indices while preserving valid multiselection; remaining: 30.0's artboard locking and colours and managing artboards from the canvas, Layers row menu commands beyond Collect for Export and menus on blend spine rows (guide row menus are done; click-to-fit objects is done, #1227) | 5–8 | estimated (lowered from 82%: target moved); Artboard deletion keys keep artwork and the first of an all-selected set; Artboard Options' Show Center Mark and Show Cross Hairs draw on the canvas only (exports and print leave them out), regression-tested; Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio (per artboard, native format) are done ([video display options](#evidence-what-ships-today-by-area)), score unchanged | | View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged); cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission (regression evidence below) | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.; PDF type filled and stroked at less than full opacity comes in as a filled object and a stroked one (#8015) | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); DXF export's Include Placed Images and Include Fill Hatches options, off in CNC / CAM (`images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`; score, gaps and hours unchanged); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`; the distance from the path under Align to Path is measured from the top of each character's em box, half the height of the top of its H or the bottom of its font's bounding box (`tests_native::aligned_type_lies_as_far_from_its_path_as_the_file_lays_it_out`), and the fit under Gravity does not reproduce the file's layout), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` and EPS import: a path whose Art brush colors its art with Tints of a stroke color linked to a swatch comes in brushed, its tints linked to the swatch (#8200, `an_art_brush_tinting_with_a_spot_color_comes_in_brushed_in_tints_of_it` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. `.ai` and EPS import: clipping paths grouped in a compound path are the compound path's subpaths, so the compound clipping path clips its clipping group instead of coming in as nested clipping groups (#8128, `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. PDF import: type filled and stroked by one text-showing operator (rendering modes 2 and 6) comes in as one type object, filled and stroked, not a stroked copy over a filled one (#8015, `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`); not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one (`translucent_fill_and_stroke_text_stays_two_objects`); score and hours unchanged. PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543, `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`); score and hours unchanged. PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300, `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked` in `crates/pdf/src/tests/textstroke.rs`); score and hours unchanged. | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, textures, map art and shading in 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.; PDF type filled and stroked at less than full opacity comes in as a filled object and a stroked one (#8015) | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` and EPS import: a path whose Art brush colors its art with Tints of a stroke color linked to a swatch comes in brushed, its tints linked to the swatch (#8200, `an_art_brush_tinting_with_a_spot_color_comes_in_brushed_in_tints_of_it` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. `.ai` and EPS import: clipping paths grouped in a compound path are the compound path's subpaths, so the compound clipping path clips its clipping group instead of coming in as nested clipping groups (#8128, `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. PDF import: type filled and stroked by one text-showing operator (rendering modes 2 and 6) comes in as one type object, filled and stroked, not a stroked copy over a filled one (#8015, `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`); not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one (`translucent_fill_and_stroke_text_stays_two_objects`); score and hours unchanged. PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543, `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`); score and hours unchanged. PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300, `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked` in `crates/pdf/src/tests/textstroke.rs`); score and hours unchanged. | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.; PDF type filled and stroked at less than full opacity comes in as a filled object and a stroked one (#8015) | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Save refusal continuation (#6146): `READ_ONLY_LOCATION`, Save As on ordinary UI Save only; regression execution pending; score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` and EPS import: a path whose Art brush colors its art with Tints of a stroke color linked to a swatch comes in brushed, its tints linked to the swatch (#8200, `an_art_brush_tinting_with_a_spot_color_comes_in_brushed_in_tints_of_it` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. `.ai` and EPS import: clipping paths grouped in a compound path are the compound path's subpaths, so the compound clipping path clips its clipping group instead of coming in as nested clipping groups (#8128, `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. PDF import: type filled and stroked by one text-showing operator (rendering modes 2 and 6) comes in as one type object, filled and stroked, not a stroked copy over a filled one (#8015, `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`); not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one (`translucent_fill_and_stroke_text_stays_two_objects`); score and hours unchanged. PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543, `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`); score and hours unchanged. PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300, `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked` in `crates/pdf/src/tests/textstroke.rs`); score and hours unchanged. | +| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs, and blends the `.ai` reader opens with their settings and as they are drawn, the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.; PDF type filled and stroked at less than full opacity comes in as a filled object and a stroked one (#8015) | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); DXF export's Include Placed Images and Include Fill Hatches options, off in CNC / CAM (`images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`; score, gaps and hours unchanged); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`; the distance from the path under Align to Path is measured from the top of each character's em box, half the height of the top of its H or the bottom of its font's bounding box (`tests_native::aligned_type_lies_as_far_from_its_path_as_the_file_lays_it_out`), and the fit under Gravity does not reproduce the file's layout), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` and EPS import: a path whose Art brush colors its art with Tints of a stroke color linked to a swatch comes in brushed, its tints linked to the swatch (#8200, `an_art_brush_tinting_with_a_spot_color_comes_in_brushed_in_tints_of_it` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. `.ai` and EPS import: clipping paths grouped in a compound path are the compound path's subpaths, so the compound clipping path clips its clipping group instead of coming in as nested clipping groups (#8128, `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. PDF import: type filled and stroked by one text-showing operator (rendering modes 2 and 6) comes in as one type object, filled and stroked, not a stroked copy over a filled one (#8015, `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`); not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one (`translucent_fill_and_stroke_text_stays_two_objects`); score and hours unchanged. PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543, `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`); score and hours unchanged. PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300, `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked` in `crates/pdf/src/tests/textstroke.rs`); score and hours unchanged. | +| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs, and blends the `.ai` reader opens with their settings and as they are drawn, the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, textures, map art and shading in 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.; PDF type filled and stroked at less than full opacity comes in as a filled object and a stroked one (#8015) | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` and EPS import: a path whose Art brush colors its art with Tints of a stroke color linked to a swatch comes in brushed, its tints linked to the swatch (#8200, `an_art_brush_tinting_with_a_spot_color_comes_in_brushed_in_tints_of_it` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. `.ai` and EPS import: clipping paths grouped in a compound path are the compound path's subpaths, so the compound clipping path clips its clipping group instead of coming in as nested clipping groups (#8128, `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. PDF import: type filled and stroked by one text-showing operator (rendering modes 2 and 6) comes in as one type object, filled and stroked, not a stroked copy over a filled one (#8015, `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`); not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one (`translucent_fill_and_stroke_text_stays_two_objects`); score and hours unchanged. PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543, `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`); score and hours unchanged. PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300, `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked` in `crates/pdf/src/tests/textstroke.rs`); score and hours unchanged. | +| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs, and blends the `.ai` reader opens with their settings and as they are drawn, the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.; PDF type filled and stroked at less than full opacity comes in as a filled object and a stroked one (#8015) | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Save refusal continuation (#6146): `READ_ONLY_LOCATION`, Save As on ordinary UI Save only; regression execution pending; score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` and EPS import: a path whose Art brush colors its art with Tints of a stroke color linked to a swatch comes in brushed, its tints linked to the swatch (#8200, `an_art_brush_tinting_with_a_spot_color_comes_in_brushed_in_tints_of_it` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. `.ai` and EPS import: clipping paths grouped in a compound path are the compound path's subpaths, so the compound clipping path clips its clipping group instead of coming in as nested clipping groups (#8128, `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. PDF import: type filled and stroked by one text-showing operator (rendering modes 2 and 6) comes in as one type object, filled and stroked, not a stroked copy over a filled one (#8015, `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`); not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one (`translucent_fill_and_stroke_text_stays_two_objects`); score and hours unchanged. PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543, `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`); score and hours unchanged. PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300, `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked` in `crates/pdf/src/tests/textstroke.rs`); score and hours unchanged. | | View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged) | | View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged) | | Guides, grids, smart guides, snapping, rulers | 3 | 80% | "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658) | 4–7 | estimated (lowered from 85%: target moved); Control bar snapping quick access includes Snap to Glyph and Alignment Guides (#6164); new ruler-guide Alt orientation implemented; global/artboard ruler modes (`view.globalRulers`) and video rulers (View › Rulers › Show Video Rulers, #2849) done; status-bar X/Y uses the active ruler origin and General units; score unchanged | From bbc183f7936f76ab2eec22cec454f28d4c3a39c5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 16:39:53 -0800 Subject: [PATCH 40/53] Tests: fetch a pinned public script corpus and report its headless pass rate Part of #1210. - `cargo xtask corpus --scripts` fetches 397 scripts and 1 included file from 19 MIT and Apache-2.0 repositories at pinned commits into corpus/scripts, each repository's license file beside its scripts. xtask/script-corpus.txt lists every file with its size and SHA-256; a download replaces the previous copy only when both match. One more candidate is listed as excluded because it is over the 1 MiB limit for one script. The fetch caps 64 MiB of scripts and 128 MiB of transfer, refuses `..`, absolute paths, reserved names, case-fold collisions and links, and holds a lock file while it runs. - `cargo xtask corpus` takes at most one of --download, --affinity and --scripts, and refuses other arguments with the usage text. - `cargo xtask scripts --pass-rate [--report ]` runs each script in a process of its own (the ignored `row` test in crates/engine/tests/script_corpus.rs): a new document, 5,000,000 instructions, no dialog answers, file reads only in the script's repository folder and a new folder of its own, file writes only in that folder, stopped after 10 seconds. It writes a JSON report with the pass rate overall, per repository and for scripts without dialogs or windows, how many parse, and each script's outcome, with local folders removed from messages. Script failures never fail the command, and without the corpus it prints a skip line and exits 0. --- crates/engine/tests/script_corpus.rs | 128 +++ docs/target-app-parity.md | 1 + xtask/script-corpus.txt | 443 +++++++++ xtask/src/main.rs | 29 +- xtask/src/script_corpus.rs | 1316 ++++++++++++++++++++++++++ 5 files changed, 1913 insertions(+), 4 deletions(-) create mode 100644 crates/engine/tests/script_corpus.rs create mode 100644 xtask/script-corpus.txt create mode 100644 xtask/src/script_corpus.rs diff --git a/crates/engine/tests/script_corpus.rs b/crates/engine/tests/script_corpus.rs new file mode 100644 index 0000000000..870bfbabc2 --- /dev/null +++ b/crates/engine/tests/script_corpus.rs @@ -0,0 +1,128 @@ +//! The runner of `cargo xtask scripts --pass-rate` (`xtask/src/script_corpus.rs`): the ignored test +//! `row` runs one script of the public script corpus and prints its result on one line, and xtask +//! starts it once for each script, in a process of its own that it stops after its time limit. +//! +//! A row gets a new session with one new document and runs `script.run` with the script's path, +//! 5,000,000 instructions and no dialog answers. Before the session starts, the process confines +//! itself to the automation roots the run's folders give: reads only in the script's repository +//! folder and the run's own folder, and writes only in the run's own folder, which holds the data +//! folder (`Folder.userData`) and, through the temporary-folder variables xtask sets, the run's +//! temporary folder (`Folder.temp`). The other tests check the result line on scripts given as +//! text. +// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::path::PathBuf; + +use serde_json::{Value, json}; +use vectorcraft_engine::Session; +use vectorcraft_engine::file_access::{AutomationRoots, confine_process}; + +/// The instructions each script may run. +const FUEL: u64 = 5_000_000; +/// The most characters of a message a result keeps. +const MAX_MESSAGE_CHARS: usize = 300; + +/// A session with one new document. +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s +} + +/// Runs `script.run` with `params` and gives the result line's JSON: whether the run started (a +/// script `script.run` refuses before it runs has no report), whether it ended well, and the +/// failure's kind, message (at most [`MAX_MESSAGE_CHARS`] characters), line and column, the fuel +/// and host calls it used, its `File.execute` calls, and whether a dialog found no answer. +fn result(s: &mut Session, params: &Value) -> Value { + let ran = s.execute("script.run", params); + let report = s.script_report().cloned().unwrap_or(Value::Null); + let message = report["message"].as_str().map(str::to_owned).or_else(|| ran.as_ref().err().map(ToString::to_string)).unwrap_or_default(); + json!({ + "started": !report.is_null(), + "ok": ran.is_ok(), + "kind": report["kind"], + "message": message.chars().take(MAX_MESSAGE_CHARS).collect::(), + "line": report["line"], + "column": report["column"], + "fuelUsed": report["fuelUsed"], + "hostCalls": report["hostCalls"], + "fileExecutes": report["hostCallCounts"]["fileExecutes"], + "missingAnswer": report["dialogs"].as_array().is_some_and(|d| d.iter().any(|x| x["answer"] == "missing")), + }) +} + +fn source(text: &str) -> Value { + json!({"source": text, "name": "corpus.js", "maxFuel": FUEL, "answers": []}) +} + +#[test] +#[ignore = "cargo xtask scripts --pass-rate runs it once for each script"] +fn row() { + let (Some(script), Some(folder), Some(work)) = ( + std::env::var_os("VECTORCRAFT_SCRIPT_CORPUS_ROW"), + std::env::var_os("VECTORCRAFT_SCRIPT_CORPUS_SOURCE"), + std::env::var_os("VECTORCRAFT_SCRIPT_CORPUS_WORK"), + ) else { + println!("skipped: run by cargo xtask scripts --pass-rate"); + return; + }; + let (folder, work) = (PathBuf::from(folder), PathBuf::from(work)); + let roots = AutomationRoots::new(&[folder.as_path(), work.as_path()], &[work.as_path()]).unwrap().unwrap(); + assert!(confine_process(roots)); + let mut s = session(); + s.attach_script_data(work.join("data")); + let script = script.to_string_lossy().into_owned(); + let line = result(&mut s, &json!({"path": script, "maxFuel": FUEL, "answers": []})); + println!("script-corpus-row {line}"); +} + +#[test] +fn a_script_that_ends_well_passes() { + let r = result(&mut session(), &source("var a = [1, 2].join('-');")); + assert_eq!(r["started"], true); + assert_eq!(r["ok"], true); + assert!(r["fuelUsed"].as_u64().unwrap() > 0); +} + +#[test] +fn a_failure_gives_its_kind_and_place() { + let r = result(&mut session(), &source("var a = 1;\nvar = ;")); + assert_eq!((r["ok"].clone(), r["kind"].clone(), r["line"].clone()), (json!(false), json!("syntax"), json!(2))); + let r = result(&mut session(), &source("var d = app.activeDocument;")); + assert_eq!(r["kind"], "thrown"); + assert!(r["message"].as_str().unwrap().starts_with("ReferenceError: app"), "{r}"); + let r = result(&mut session(), &source("while (true) {}")); + assert_eq!(r["kind"], "limit"); + assert!(r["fuelUsed"].as_u64().unwrap() <= FUEL); +} + +#[test] +fn a_dialog_without_an_answer_is_marked() { + let r = result(&mut session(), &source("alert('hello');")); + assert_eq!(r["ok"], false); + assert_eq!(r["missingAnswer"], true); + let r = result(&mut session(), &source("var n = 1;")); + assert_eq!(r["missingAnswer"], false); +} + +#[test] +fn file_execute_is_counted_and_refused() { + let r = result(&mut session(), &source("var ok = new File('x.txt').execute(); if (ok) throw new Error('ran');")); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(r["fileExecutes"], 1); +} + +#[test] +fn a_script_refused_before_it_runs_has_not_started() { + let r = result(&mut session(), &json!({"path": "notes.txt", "maxFuel": FUEL, "answers": []})); + assert_eq!(r["started"], false); + assert_eq!(r["ok"], false); + assert!(r["message"].as_str().unwrap().contains(".js or .jsx"), "{r}"); +} + +#[test] +fn a_long_message_is_cut() { + let r = result(&mut session(), &source(&format!("throw new Error('{}');", "x".repeat(1000)))); + assert_eq!(r["message"].as_str().unwrap().chars().count(), MAX_MESSAGE_CHARS); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 57ac87a396..dba7a43a86 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1076,6 +1076,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `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`. - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 6,798 of 6,866 runs pass (the 34 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. + - Scripts: `cargo xtask corpus --scripts` fetches 397 public scripts and 1 file they include from 19 MIT and Apache-2.0 repositories at pinned commits into `corpus/scripts` (gitignored), each repository's license file beside its scripts. `xtask/script-corpus.txt` lists every file with its size and SHA-256, and a download is checked against both before it replaces anything; one more candidate is left out because it is over the 1 MiB limit for one script. `cargo xtask scripts --pass-rate [--report ]` runs each script headless in a process of its own (a new document, 5,000,000 instructions, no dialog answers, file reads only in its repository's folder and a new folder of its own, file writes only in that folder, no command it can start, stopped after 10 seconds) and writes a JSON report: the pass rate overall, per repository and for the scripts without dialogs or windows, how many parse, and each script's outcome. Script failures never fail the command, and without the corpus it skips. These limits are VectorCraft's own. Tests: `xtask/src/script_corpus.rs`, `crates/engine/tests/script_corpus.rs`. - With `Options::e4x` set, an E4X name standing alone (`@a`, `@ns::a`, `@[expr]`, `ns::a`, `*`) inside `with` or a filter predicate can be assigned, with `=` or a compound operator, incremented, decremented, deleted and used as a `for` or `for each` variable, as well as read. Each of these uses the nearest XML or XMLList value in scope that holds the name and evaluates the name once. When no XML value in scope holds the name, the read or write throws a `ReferenceError` before the right-hand side runs and creates no child or attribute, as ECMA-357 section 11.1 (https://ecma-international.org/publications-and-standards/standards/ecma-357/) specifies, so a filter such as `list.(@id == '1')` throws when an item has no `@id` and no outer XML value holds one. Tests: `crates/js/src/xml_tests.rs`. - `vectorcraft-js` runs ECMAScript for XML (ECMA-357, 2nd edition, https://ecma-international.org/publications-and-standards/standards/ecma-357/) when `Options::e4x` is set, which it is not by default: XML and XMLList literals with embedded `{}` expressions, the `..`, `.@`, `.*`, `.()` and `::` selectors, assignment and `delete` on selected nodes, `for each`, `default xml namespace`, and the `XML`, `XMLList`, `Namespace` and `QName` objects with their methods and settings. `xml.xpath(expression[, variables])` evaluates an XPath 1.0 expression (https://www.w3.org/TR/1999/REC-xpath-19991116/) with all 13 axes and the 27 core functions, and returns the selected nodes as an XMLList in document order without repeats. Each property of `variables` binds the variable of its name, an XMLList runs the expression on each of its elements in turn, and a prefix in a name test resolves through the context element's in-scope namespaces. An expression that breaks the grammar gives a `SyntaxError`; an unknown function, a wrong argument count, an unbound prefix or variable, and a result that is not a node-set or that holds the root or a namespace node give a `TypeError`. `id()` selects nothing, and evaluation uses no native stack, takes fuel and counts against the heap limit. `` in an XML string gives a `SyntaxError`. An XML declaration at the start of an XML string, after optional white space, is checked against XML 1.0's grammar (https://www.w3.org/TR/xml/#NT-XMLDecl): a version of `1.` and digits, then an optional encoding name and an optional standalone `yes` or `no`, in that order; any other declaration, or one with a character XML does not allow, gives a `SyntaxError`. The parser takes fuel for the length of every name, white space run and declaration it scans, and for the text it searched when a quote, CDATA section, comment or processing instruction is not closed. Parsing, serializing, comparing and copying trees use no native stack, and each takes fuel and counts against the heap limit. Inserting a node into itself or its descendants throws a `TypeError` before the tree changes, a literal or XML string nested past `Options::max_depth` gives a `SyntaxError`, and a tree built past that depth stops at the heap limit. Tests: `crates/js/src/xml_tests.rs`. - Scripts: `inScopeNamespaces()`, `namespace()`, `namespaceDeclarations()`, the XPath `namespace` axis, prefixes in an XPath expression and the qualified names `name()` gives count the namespaces they collect from a node and its ancestors against the heap limit, so a node with many namespaces in scope stops the script at the heap limit instead of growing past it. `addNamespace()`, `setNamespace()`, `setName()` and `removeNamespace()` read an element's attributes in place instead of copying them, and `removeNamespace()` counts its walk of the tree; `child()` by index, `comments()`, `text()`, `elements()`, `processingInstructions()` and `normalize()` on an XMLList count their copy of its items; `replace()` counts its copy of the children it matched; and `name()` counts the prefixed name it builds. The `XML`, `XMLList`, `Namespace` and `QName` constructors, `isXMLName()`, `attribute()`, `namespace()`, `propertyIsEnumerable()`, `setName()`, `setLocalName()`, `addNamespace()`, `removeNamespace()` and `setNamespace()` count the copy they make when they flatten a long string argument, and `QName.prototype.toString()` counts its result before it builds it. Tests: `crates/js/src/xml_tests.rs`. diff --git a/xtask/script-corpus.txt b/xtask/script-corpus.txt new file mode 100644 index 0000000000..676e030cab --- /dev/null +++ b/xtask/script-corpus.txt @@ -0,0 +1,443 @@ +# The public scripts `cargo xtask corpus --scripts` fetches into corpus/scripts/ (xtask/src/script_corpus.rs). +# `source ` starts a repository. Each line under it is +# ` `: kind `license` is the repository's license file, fetched beside its scripts; +# `script` is a .js or .jsx file that `cargo xtask scripts --pass-rate` runs; `include` is fetched for the scripts +# that include it and is not run on its own; `excluded` is a candidate script that is not fetched (the report +# lists it with its reason). Paths are as in the repository at that commit. +source alexander-ladygin/illustrator-scripts fc7625410b62c833fce100f67cf18a97588279c5 MIT +license 1074 26a8d6a18b1eeebdb99b8a9e9b6e87e56a76600337262f3bbecc589a06c002d0 LICENSE +script 132319 978432f0e356dd9954e3f5fd2022fe56f8c6cb53142d8ba4e587a9940b529149 alignEx.jsx +script 8087 6cc08d9ab1ed0e1f69b4ed004dd8d8f2afda880227b0b71a5b4b62f3b64fc551 artboardItemsMoveToNewLayer.jsx +script 10042 549523ed07e81c63107d265da3ce4f4faea60677b729bba665e4f0663b481c27 artboardsResizeWithObjects.jsx +script 5630 c14b6b7933a01d2cbbf51ada98065c6360a549bfcfe93f9d5d1cfea143c1abe5 artboardsRotateWithObjects.jsx +script 7177 80412e4bb73f9e3d81825b0f597296604b7560a3cb16f4b8ffac3d36f8a8af17 batchTextEdit.jsx +script 11047 551e572300da895a4e5c14d48460ba1985183676eb232e7f8277e33968a44f27 bigBang.jsx +script 112308 f6d68d072eea54eaa12fc595bb47e24dc7f1f20b17be3a5911d3afdc6506d3df calendarikko.jsx +script 21641 201daecf2b2d0c223f436ff93f0ef1583818870f5f0638f6662ba7672bccecee circular.jsx +script 1875 db72895668fa6d121ea83f04800d4d51ef87103ff23fc4dfa02bdf329a2e9a64 clippBottom.jsx +script 3958 bb26bb10b450363dda30174cb7ba6063eb5c6023fe763082faa9bb9d155283c0 compoundFix.jsx +script 9917 eff5f9a425af9362930aab9d6c329576e271ab868219ea39ef1afa77def508c7 createArtboardsFromTheSelection.jsx +script 5104 c4ea8ebc3662ae3cc004d6697b6e3ecd9fe9565a3b40ea85f88422810e8de0b0 createRectangleOnArtboard.jsx +script 21076 5033d7f1bc0cee5d499856b5048b3fb4bac693ee3853d7388a26a56bffbff8bf cropulka.jsx +script 60629 0c44b21678ebf409c15afb40af218775af75d172b8474f6f72e309dd9e390409 duplicator.jsx +script 25056 265da1acdda206e2f2f1e085a921c48e054d36edbf3cfdcc109cece3c6a60fd6 fillinger.jsx +script 4467 bc80c3b14d59548150dbefb6642eac050e02dc01199c6552a3876de512291ab2 forceCloseOtherDocuments.jsx +script 47091 a28943fd8d7442783b11d559bbeeba77da126e94e154ffef79435a4c14e7609a griddder.jsx +script 12668 8ed8db2b1e0a6d1da844b2f33f9aaacbf642bf8497a30a295d88b3bca3d15e7d harmonizer.jsx +script 2738 7d2be43e89c80f8a695538784f3556c86ff8c98989bfb1deca2e455b7b60dd9a inlineSVGToAI.jsx +script 263272 9f475d3a6125c12a61aa23c0fdc4159e59429af770e00c5088bca9054ab9327e libraries/AI_PS_Library.js +script 11226 6bcf99cea6224732d264ebab9a88bc347fcaa0525ed5cddfc15e0cab6e27cd06 long_shadow.jsx +script 9422 a63ee3cc0576fd918a6281f7e9549f76ff5275d9a05466822fb062d5e962c5c3 minusOffset.jsx +script 13997 6640be5743c72f1bc49587df659df64f5b8f2a6bb4be4316caffcefa9573a7e4 niceSlice.jsx +script 14607 d2894353631448b0ea3d1f42e0ee6f5e775126d2b83c1b091bc194e4f7125c91 optimizero.jsx +script 1038 7f8f05c50fcf8b7a58675a1b6a1c9a9df7bd4241a1dade551c90d9344d94a609 puzzleClipper.jsx +script 8620 dff8c79b9b9f6631a11e233c28ec7854d0818eee231a8d3c7891a844d3e03e94 random-dash.jsx +script 42986 562aa47d6db1869f060c8235f617c6f7c687227eeaa66b8b173d7f7d681e5296 randomus.jsx +script 9930 12049ff8476ed5abe883247e3ae9a126a2f8788d9bf2c7c7b94b9af13d9af05d replaceItems.jsx +script 13820 ff4d764d2869d307e20eee134928d624c897c74c4f385260dc9995e205303ce8 rich_glitch.jsx +script 24804 dbbfa5ca937c0d799997572e5424d4ece097a22a212446f75364617479776bab round_any_corner.jsx +script 27674 d5267bbfd545a1298d9d14e037f2ecb672023bad05edcc2117dbdc82b58efcb4 setMaker.jsx +script 51416 52548c81ec0f5a6aa5c029d89fa9a5bcae6cc8134e71e682c442fefe28c2668e smallWorker.jsx +script 11794 86ce50484365b5b865a6b0dd15774886e5bbdabb7cfe323b8c1bdf44543925e7 transferSwatches.jsx +source creold/illustrator-scripts 9b3e3eeade9ba748f41612ec4697bb6a5c2489c2 MIT +license 1070 e1d0ab3fff40a66da1322a6e4276755172468c63eb6fad3525db1cea46fc4c98 LICENSE +script 7479 fe7d2c9a59cb780b3a4f66c14347c814a310cb6a7a4a2006859430c0339251e6 jsx/AlignTextBaseline.jsx +script 16922 389cfe137b3d885659dd07418a07d7e01aee3f5e95e1d11b2e544e789617f5f4 jsx/AlignToArtboards.jsx +script 30176 392b008c680dd7399d3fbd0395c34a22cece068b4768348bdf029a09caf1277f jsx/ArtboardsFinder.jsx +script 9199 51f9ad977e28180c32544578a774fddd24665da9bcbece1e4ea2e0fb3b48fcc4 jsx/ArtboardsRemapper.jsx +script 38092 cfbd2169a33806c074bd79061f2d97166ae04e4a69c23ae7f87753b99fc985c3 jsx/AverageColors.jsx +script 4496 2af6148ca3da7ff8987045ef364c77ddbb0b4e87b4b3198db930c9030af23bb0 jsx/AverageStrokesWidth.jsx +script 59202 f3d6a96ddb7096329dccda004067a910c09433c03351573854367d5e6f3b0d8e jsx/BatchRenamer.jsx +script 10256 8831fc386a97d4d4539a3c03f1c18944032606ccbc65a1e3ac7a15d81146fae8 jsx/BatchTrace.jsx +script 250535 96621d04950b7ed9c8a40655283a27654d91b0a808fd85a0d75829a8355470f8 jsx/BeautifySwatchNames-Lite.jsx +excluded 1519873 e073e85c0a88d35f398631329164ae1b1c68ca7724d4920440358776177e1cea jsx/BeautifySwatchNames.jsx +script 7797 b60a734fbeb997610c67ab78aa0b5b302c934b47b23bf6d1668826a0ad4ded56 jsx/CenterClipsToArtboards.jsx +script 26621 99a9dffc039d587ed118814172907e8edf74d99c2fd71049f6511057ae58482a jsx/ChangeOpacity.jsx +script 5280 30127edf09e2063bf9a5c482728b43bcbbbd229cc74265e450345692f715e9ce jsx/CheckPixelPerfect.jsx +script 12875 5bf2ffffd614a1da4f70de770a868431e2fbe3af3ee4d4ebc4fb505d9a7a66f3 jsx/ColorBlindSimulator.jsx +script 16384 9135324a5e64b7bb515d4d30e6831775d0e68c62cb6d8551a6d948c9abfc088e jsx/ColorCorrector.jsx +script 7298 4ab1c1bf517306ebb430060b78db8e25b56269c3730df748f94b3406992ebf2c jsx/ColorGroupReplacer.jsx +script 20400 bf817d007767c4058d05d8d87c004343a740b74944f45c27bddd286749182079 jsx/ContrastChecker.jsx +script 7588 823611406ef077f8b228bcc0f83c27439ddde3a5e43e69df77a10f4b6de57ff0 jsx/ConvertToGradient.jsx +script 4945 60c07c7953f4f793ea1e167c0aa0acf7408d947dae598c4be61cf2ff8a895e9b jsx/CornersSelector.jsx +script 21805 531d8c4a9db511a54a4e6516feec4376114e4af0d89cbe267ffe06aac583152b jsx/CycleColors.jsx +script 7973 27bce158fdbdf78488be5fd05e7ef740f50a542d101a6bfea43024ba6f5fe844 jsx/CycleGradient.jsx +script 3503 9b70ef9a912ef15daac072acb9d3514b23292063fc33090eeef34b61c7721511 jsx/CycleGradientBackward.jsx +script 3497 a8253ad22586d5e3f1a9b45065f195d266b5cc96e4b8a0dd037a7e03f7a0a036 jsx/CycleGradientForward.jsx +script 3642 c29ceb2bd54eca460fe549c712ceeb445b49aaf28ce276309722c36f74734d85 jsx/CycleGradientRandom.jsx +script 3883 1b49992ca4fc21883c42b1021b4450175441ad3fccdd1c2385229e25bde1b5e2 jsx/DistributeGradientStops.jsx +script 8190 0d37354da0669ece53ca6205f8f8226c1aee088252299900ea3c6475f6283f34 jsx/DivideBottomPath.jsx +script 5577 e61adf1f64e8217b69b2235eecd772099625dfad2992b08b6730d0fdb31d53dc jsx/DrawPathBySelectedPoints.jsx +script 47500 1971f163163319cfd0e9168ad0c9de4a40f52194c25fa81d98fbdaa4706ac9f8 jsx/DrawPolyline.jsx +script 29114 54e0166bb6b73dc1e0fcbd74a4b7ec91f9bc6ad2599e2bc25d76b19f8419f5fd jsx/DrawRectanglesByArtboards.jsx +script 20550 477a3640dadb3566594a9b3e600ac5665c9dadc893b86b8032f2e31b1d2ea121 jsx/DuplicateArtboardsLight.jsx +script 19045 3cf9443e99324e81d5db1ef581634f8fa47477268316ae1bd662e00d19af9685 jsx/DuplicateToArtboards.jsx +script 8222 267f8b3a2a98dadc4b3101b8a4f924e982ed292087e5f5b945bef2a4baa25a5a jsx/Export-selection-as-AI.jsx +script 11789 9e620b11b865546937ca28fca9cb3342fd829ddd75d8cfcb214e7341dd1320a5 jsx/ExportToDXF.jsx +script 7389 aa0584dc45b09eeea7063dfcf71e679db98592c126c9eeb8adc1bd8633f4d2e6 jsx/ExtUngroup.jsx +script 27759 1a711eb965a92aead0d02af1599789c3b2053940b6ce836a9a8709e61ad32955 jsx/FitArtboardsToArtwork.jsx +script 8749 afc827858fa9125abbe652154bc7b9e86a005f4a80ee4ec40dee0172fcabdea6 jsx/FitSelectionToArtboards-Lite.jsx +script 14970 7e71e6db10de93e263f5e9ccb67c86ddcd1a995a1593a6e7eed31b8348fd1340 jsx/FitSelectionToArtboards.jsx +script 1916 95b58bb7eed94570f3586f8c9c2f67fcfd6d516c724f546bde66c055a0b55902 jsx/GrayscaleToOpacity.jsx +script 11361 c486905a89a03ae05d791af6365e39334d8d7b145f8bbb1aad8e750b2855f20c jsx/GroupArtboardObjects.jsx +script 17158 58bb73d9d001f294242614559d443c67b7d7f8b20fb31443c65b0fde79d0d124 jsx/HexToSwatches.jsx +script 22888 376e8fe17a2481235f8767100dae5e74c4a0518e2c4d1007ed70cd871befda9d jsx/InsertText.jsx +script 31793 1180944a70dab573cd1c3a9a43ee4fd01d3959f439294b047fa8a81742237f92 jsx/MakeNumbersSequence.jsx +script 10975 d7add50f284598d7398abb217882988f6a0ba3e177ea71dea8e323a6d2097720 jsx/MakeTrappingStroke.jsx +script 28670 a54949c8a425a5fbb0f8a562fd6b850539a2a8cf56e4222b23a080595a2d02ac jsx/MaskArtboards.jsx +script 13581 75d767139e32ac430caadddaa108b9eb8d9fceebaca8b2791d7ce8fe37e3d3a3 jsx/MatchColors.jsx +script 9988 47493f096afc25da55680a41589f1524c972137432a0153cd0b10e5c85c008d3 jsx/MirrorMove.jsx +script 19654 2b2a01cdd3340168a41efbc1ce477fb12ef71d87e5080bebd7462f7f5a7a871c jsx/MoveArtboards.jsx +script 21221 5b3e367b8ea06f95b7391d9d3812151c6df26cafa8fcb75d63cf676e17b04353 jsx/MultiEditText.jsx +script 33557 b49d78dd3cb80754a8f65135abb69a904dc5a2135832efa8601bec9e53a8dc54 jsx/NamedItemsFinder.jsx +script 14021 6f5d862a9ea39b46858291c26edb478f338d4aa2f7d8e1fc38bee7e118a04455 jsx/NumeratesPoints.jsx +script 1558 7272c7e512b7813c654313ef72ee8f7b72cf695d1456a3b57c22a68b8be81128 jsx/ObjectsCounter.jsx +script 5997 000741403d136d478442e076c42fca7a271bb90d756095b6a8514890dc820458 jsx/OpacityMaskClip.jsx +script 15624 0a9573e9edb8a1e055aba14d4be4ea54f5c17c382216f9100f501fecd4e2ba13 jsx/PlaceSymbols.jsx +script 17702 905ae929086bb815c151e2c038bfb8c53cba906d51d72a59ccbe94edaf9edf7b jsx/PointsMoveRandom.jsx +script 14096 8eacfbb0719aa506f03f6818012fcaf0781700d96ce4233a4c4470fbfc517559 jsx/RandomScribble.jsx +script 12442 ab821379f4a3a7cdb57bf687d48bb687b47c200191c49832d0003d2334ade630 jsx/RandomStrokeWidth.jsx +script 5498 e682dda0d3939dc908be93d30b82aaaef2e089b62836792d6f932db935e38dfb jsx/RememberSelectionLayers.jsx +script 3515 ca820de22d813eec31318c2ef1877b953fd37a42b069151ae4d8768b5f29386e jsx/RemoveGradientStops.jsx +script 13103 1ec8b59212f3ba4924798708e249f84fb70ed2933b529f63d30ee5c24e6e94f4 jsx/RenameArtboardAsLayer.jsx +script 15432 06b36a428734db65128703a0d2f0e63100a859a01cdcb70cd6b985f351b6897b jsx/RenameArtboardAsSize.jsx +script 13466 664723f883b87656dc189ae351e92a163bb8701a3d4130019f91e10ce98db77c jsx/RenameArtboardAsTopObj.jsx +script 36302 ddbe60c0d34890f8c35f6c252d2d5d8ede79268b51f06c4780dbdcde7f444981 jsx/RenameItems.jsx +script 3772 4d3dfa028594eff3d170cfc12a202a5fa1642ad3e26c42c246a391e9e16f15d3 jsx/RenameLayerAsText.jsx +script 4859 b76154fe0283bd0b68af1c93207962802947c130d0e8593f583afebd79746477 jsx/ReplaceFormattedText.jsx +script 8766 700eedee71cdcfd1fea68f766216d8b75aee36613fd32aa10a173cf040a30acc jsx/Rescale.jsx +script 5240 824c33bd9f8c4c4da2e86e2d0a61f76bb2f6ed8ac976e0a13f1874aa0fa089d0 jsx/ResizeOnLargerSide.jsx +script 21230 aa201ff225531338f758c2bd84a98927934c98524296ab591a125b9550abc449 jsx/ResizeToSize.jsx +script 2905 e28f1357aed2b2ca50c03d769c2350d69d3c4650549bf2aafdc33d1fec5f807e jsx/ReverseGradientColor.jsx +script 9422 1cfbf0c674787b181ecca75e0539c1b91b98149555f6815bfeb627ec14ae625d jsx/RoundCoordinates.jsx +script 2745 a045c2b2bd16e53fe108c46b0f759e6be5f72275ae1d67ad1d3e22a0fc54cc64 jsx/SelectAllLayersAbove.jsx +script 2734 164f75e1ef476e451a48db541150bd615dabb63950620ee60b025c3686475810 jsx/SelectAllLayersBelow.jsx +script 11361 9ced2b7e3ed838481cefb23d9d58a79192b51673a061a2b34d0dea79df024766 jsx/SelectArtboardObjects.jsx +script 10146 51bfd99c621cbfc0fc2ab6645902489f72025a7e897aed5c67718fe7b1d7fd54 jsx/SelectBySwatches.jsx +script 3375 9739e793412040e60b966f4f6f0e5bd23f39d9033f211236e83ac57216011281 jsx/SelectOnlyPoints.jsx +script 42449 3553647a7851fbf6569220d1577651ca3eaf0fa5e887e830710305e1ec1341e0 jsx/SelectPointsByType.jsx +script 2913 daef4b5cef71dba7bfb7e29bb7bad84c2eac5552836a59299533a0a58e26db3a jsx/SelectRotatedItems.jsx +script 13061 0d2b18ddb23cfd7162b89247b121e2b528ffea13d93fa2dd602f8fbd91df9307 jsx/SetPointsCoordinates.jsx +script 36000 028f9434fb5bc8e1af9d3f68e1dae0d9c56d4e2d560130c5f7781e81e0932e42 jsx/ShowObjectNames-FontPicker.jsx +script 35651 269dd1fb0fdf3573a853fe006e6e3018e7020feaefc6275401014b0615076cc9 jsx/ShowObjectNames.jsx +script 8109 d5ec9e652ac0b3b3ca8c9aeb593c97dd374c5344f1e054be2af70fe5c134a57d jsx/SortLayerItems.jsx +script 12599 66109a29cf55045a7c568b7b5e62030accbb8962a8a94ab60a13eeb8e53368ab jsx/SplitPath.jsx +script 32206 32c013094c6e83b511721a293b64dab5902995814371fd59c3d5f7d2225661a7 jsx/StrokeColorFromFill.jsx +script 35072 aca7117f43769c84f6eb5547a5a435973e1fcae8bd3225526a7e562b14329ec7 jsx/StrokesWeightDown.jsx +script 34995 d13254406eb4c35e70ffe3194d250e0697db21dfa1394c9b760bedb53520b9e4 jsx/StrokesWeightUp.jsx +script 6894 3f746e4f476d780ecc7eebea308c9f96468d74bc2cab229264a809d4c4e818e8 jsx/SubtractTopPath.jsx +script 23357 7cc0cf0e9a6b6b11ca597b41f20e935172cce94b855d5b849ac2fb9817770aa3 jsx/SwapObjects.jsx +script 5038 fe73423b8a9ee8f06e327bd94d3460dc990f7815f53b4079573e3485a24c29e2 jsx/SyncGlobalColorsNames.jsx +script 14989 1414f58421784d50b25cad7dc30ba44b7288aeab16ac49344162fc28d987c173 jsx/TextBlock.jsx +script 34397 ff6f1574270dead0974695aef29259813b10c9b1d3053609f04b13a5f2e15a46 jsx/TransformPoints.jsx +script 22100 9f429ee0b03a17b7fb09a8088f9e2b0c562cadc8a7fdbaf3feb7caf006663053 jsx/TriangleMaker.jsx +script 10214 49b9564f6d1fde27a885e1294593850a9521f17448e89521a6b8be499472d364 jsx/TrimMasks.jsx +script 5380 b64a19923beb8c665ff722fe8929b1a5cfc10842c00f4621ea1a45d56bea1a0c jsx/TrimOpenEnds.jsx +script 17037 f9b9dffbdb5d48b11beeefa3d860f29d866bc24a9fe1faa40308dd5854bd5c44 jsx/Zoom-and-center.jsx +source shspage/illustrator-scripts 4c3d1d613e474bd579dd8cffad9190a701113aef MIT +license 1079 b355bc80e01fdb822789c2bbfb9fca512f2166e38579b91c1b49d7d408d5c20b LICENSE.txt +script 5389 7f8c1a43cd4b816cd831701183c928028a2fe021c44b8a9801215e58121944b4 batchTextEdit.jsx +script 14952 ff62b9dbb1d24faa2214d665bb9868c0807ba5e09ac097c2fedad8438e2a47d0 breakDashes.jsx +script 14606 f28f13d51f922d8649f8457faed656baa79589c4d646d11cebdb46d0550edd52 etc/dupAlongThePath.jsx +script 16931 de0635484ff2e93eebabab60b064bc98e036569cf649f463e9cdf7653701b913 etc/grass.jsx +script 4601 a1d86293354155ceb62ab18beb616e63749bf4bf2c1619eb9f40a25accd8181e etc/inscribedCircle.jsx +script 3583 d07835cf7077ba46d93a1e1d57240a9168d5fd274c29f701543e9dde0f674f77 etc/newLayer(&L).jsx +script 6303 1977d44d627f31e24d2fd9c6fae58fcdab05340bfcd9c86704eaa15d11388141 etc/ovalize.jsx +script 4975 67b339d4f56c672c2f3d05ee31e83952963313719256bfe10d826f2ac3f67203 etc/resizeToLength.jsx +script 11468 fa38c82980014d079a536b458501e051d9fe192ad94325f04634ee1741cdfce6 etc/smoothing.jsx +script 34546 f2eac104011c061aa63c1bc968f5edc8763f07b548ea256ab43adf43198e2f78 flatten.jsx +script 32341 d6c4e4f38ffdd093a6c4cb874457486b9165e15aa039eded45fffd4f49aa4042 handleGlue.jsx +script 9528 29b2d86a5208d415509c86eff1c9935fbb96afa1b4b38a134f19d3c1ab38f24b noiseFill.jsx +script 8644 91bd524bc53982727e8c5f5a180daf1e655fe7946e4936a5fe2a4c82ac548b09 noiseRotate.jsx +script 8742 7b27807fd732cd12173ef4b2894ce3a59facd3a1e4c01c08471226600e69662c noiseScale.jsx +script 13650 a4c61a1ff96bc64609ab38af6441dc81aab28ff48c032d5bf780ff16124561d1 notches.jsx +script 13352 a6ba95dfbe99cfe877975cdcfcb65f81e1eeb2065c2bdb685d4da33fb9b2fb7f softgel.jsx +source Shanfan/Illustrator-Scripts-Archive 418b0e082d7962c7ff8beaf574b30b9c2d46cc5a MIT +license 1078 7995fe294eae5f37a89f4299378cb269d8ec38bcb8de6cbe8bc5c7899386b955 LICENSE.md +script 7203 0925168939df83832d253c2c00d047bb2103ba1e0674d8c3675d44c0e6837ce4 jsx/Adjust Dashes (offset).jsx +script 5330 ace6cbe435fc6a6b89977918499814173c54dfa2b61ca805b785f74eabae6715 jsx/Adjust Dashes.jsx +script 13998 d188faf4687b6fe6e9a733e9cc23c43da8e18489f148910ae80c2f4889196ccb jsx/Arc Correction.jsx +script 4394 967d373e50fa9c530c591ffc2dae10da01acc093ecff7413c3b200329409a0a5 jsx/Archimedean Spiral.jsx +script 10317 16e4e551c361555ddbdb9acfd8534c099331b93d5845a12520004364d54d7d61 jsx/Arrow-A.jsx +script 10321 48187fc84925902da42f881e0b85578f86388323a0d47ad1a81b38906d194a8f jsx/Arrow-V.jsx +script 4136 011a9028ee01471dd775b2324a6abe1fb82d874e446bf6fbb629af30b86b44fd jsx/Circle.jsx +script 5736 3fa25e7327057b3da78bb4e7e060a43fb5fd111438b759e051bfa4adbe6e5049 jsx/Circumcircle.jsx +script 10548 2d32764e6d518cf420b711ae9746833182599213a607986b0137858e7ec30869 jsx/Common Tangents.jsx +script 3369 2efd3c220b6253500635a3ed75ec0d3713aba1fbbb0782190b7c084d655588d4 jsx/Cut At Selected Anchors.jsx +script 11435 936faba661d8cff56742ab15d5d2bfc85becd325765229279af737487cd80ddf jsx/Dance.jsx +script 11436 65b2d21186d7c4ba72fcdd63c3846aa4c8abc4fd96370c4461cca4c080a8c591 jsx/Divide (length).jsx +script 2695 aa7ec99086c8a406103a49c852ee3094a02ccf6ee6a4db3fc752eaf061fa37eb jsx/Dup At Selected Anchors.jsx +script 3098 46d6e2489e05a6f8c3579b1d9facfa796dfc56e18ad8ddfe5e778421848b5065 jsx/Extend Handles.jsx +script 8876 cfa4e046462c0bbaecad633b6520ff34ec0eacb958476c5c667dd402978a349e jsx/Join Reasonably.jsx +script 3945 dff19fd6f318b4e5fef22fcd45dd2ea473730fc90357d64b07179273de5df54c jsx/Merge Overlapped Anchors.jsx +script 6122 f991d96524aecdc93a8d7775482a1ed02d2df34c092124cfb02ab6d0e02845b5 jsx/Metaball (Arc).jsx +script 6132 0d0c20eead046494f080a5636089b04fb67741f3002e189daafc2763800d7d1d jsx/Metaball.jsx +script 10594 96aa018f2a33683beb93ea039ddd4066f88c4bdf5ea2725ff9fea2b239652265 jsx/Path Length.jsx +script 1651 e74c02791dd698d96edcbdff7859d4a496c8bbc8a2398786fe79624ea6cc7147 jsx/Remove Anchors.jsx +script 2562 468f0d63e54358c754fe4697d07dc73c4b5b17112955c021226a6f2c755c1bbc jsx/Reverse.jsx +script 19881 b09e847df2da0b167a486c611e5e89f07f0c4b260809975781a642fa4abd2416 jsx/Round Any Corner.jsx +script 3681 960a67e71fdccfb19a1cf58da55416d803d84628b0da9bc02249d4182e54c6ca jsx/Sine Curve.jsx +script 14009 bf96731e6657085b70ef3cfdd7c6a285e5f87f0f7ae0877ce7513746aae4bd2e jsx/Tangents From A Point.jsx +script 7005 d08e8551ff5e9e7c3e93f28f9c7c66fbd23cc2773b1c3b654262ec7b4751a1cb jsx/Tree-like.jsx +source sky-chaser-high/adobe-illustrator-scripts 7f2a08b2c3cd32ea875c1596d64a171268b61508 MIT +license 1072 b47ba518a57ad4d7e85667eada4ee8f4ae36cb64d3d27d7dacdc8d90600f39e2 LICENSE +script 10685 b05569a8242b9c635d315350cbd3d0495d064bc9fe80e22774a1fb6c16a2df6b libs/XMP.js +script 12802 84a4a4bcab07aef3c5329c8b078a19af89687d935011214c3829db1b51a4016a scripts/addAnchorPoints.js +script 2803 da63c36cfa1f25aaa9f5ff7f762cf425ff67717d23f55ce4ac1f3eff64226983 scripts/addNumericSeparators.js +script 3655 0f60b536501db775ff51e6124444d60ec2929aca35874d26cda3003c6357a3ce scripts/addSelectedGradientsToSwatch.js +script 13906 b2dea2bb8a1dc644e4ecab6600defe315bae18c68082c6db5440c1d9a74eb889 scripts/adjustHandle.js +script 4063 c1ed80c535bdafd90758f1850d795ac540ce5d9d817e60cb35514e8dc741f881 scripts/alignInCenterOfSpace(Horizontal).js +script 4062 114bbae3de6d0db1f4adf6e4df865de8c9d352adb09e7baad26e39e9537752a9 scripts/alignInCenterOfSpace(Vertical).js +script 232692 cca7f5b06d29a60b85a110906e54c5851f569f5bf6b62e2a9ad40ba8f108382c scripts/alignObjects.js +script 14291 b2e35eae3c7c339c3459d5d5b9e8c2c8ed3dfdfbe1c86f5b3361de5882a90c30 scripts/bulkRelink.js +script 11419 5af421a4777aef4548108583feca4b8458ace229efa0957ec7dc94299ef85a49 scripts/checkDayOfWeek.js +script 3904 2b54e1e17e96682f24f2e8ca7890b016657baba5dca4f4030837680e0535a615 scripts/closePath.js +script 15795 85cd291f9d86870b47306b284f0ae45f1f7c7dcc5b267fa4a3095442f1cb3d00 scripts/compareScale.js +script 5246 ac5abbe9ba49c4a78778f76e4aa5e1fcc3371a41660cb933e5583a19c0f6b731 scripts/convertAllAnchorPointsToCorner.js +script 4023 8122efe2e9238dfa0a5e7b75b3c58f25b58fd6c193879855d99c92600aa0c315 scripts/convertToGlobalColor.js +script 4006 4d6213f8cd72a7a8da12daab135c33253a164d8a703dcc02d59a1cd0d44c6bcd scripts/convertToSpotColor.js +script 1903 d9ccfc359f6629eabffbbc0a2225f5f744fbf45f95bab1383436f1d5c7e94685 scripts/convertTypeOnAPathToPointType.js +script 1878 0179ecbb35e9514d0ebca3f4306f18a637e886680c661cafe7dba334654100c3 scripts/copyLine(emptySelection).js +script 2704 050498a045a9a75b51ba23558a248455daf1a2057c202096b60554786a1bc00f scripts/copyLineDown.js +script 2610 14663dc1fc2ae8a36fc85cadea55f158153a863a11415d244f30305d9a2a8b9c scripts/copyLineUp.js +script 41579 6572aa1e7ca5e59c5d0ad08b72dfc2ed8838ce1227aab2b312ed31c2db45842c scripts/createColorChart.js +script 4230 c4cc55e5a8b5481314701ad8f625d90758612c62db00a231016ba1b93d875903 scripts/createGridLines.js +script 19974 0dee263b9e4f1b3c886f874e6aa1f073d4d86d9ca326a5f3ab59cfb6f4a27fa1 scripts/createPageNumbers.js +script 25152 e40403cad3b3dd8c74899629e5fe4be0c9d58b7b2fa74a26bd150ebe8d44a5f6 scripts/createTextParallelToPathSegment.js +script 251214 d6660a07293c54dabe8034ec3f70778f4891c51a38877a870a35bf3ff357f0bc scripts/createThreadedText.js +script 1810 41c3c59ce849ab15f4b7c430073799843d33562a8e1a854801e8cd943a827b7f scripts/cutLine(emptySelection).js +script 5467 a4ff5d916cfbd756ffef6a3a0181c7926520c47c4db18262cbec85ed14486a55 scripts/decreaseSelectedAnchorPointsCCW.js +script 5458 a601eeb5cbd0a9992db6ac5d07058502d0152f01cf946b4843d6324b59dcdc40 scripts/decreaseSelectedAnchorPointsCW.js +script 2590 d1d8ba9217f1588b429fd65aed9e6a47964df34e13d3151daf730d5004126f51 scripts/deleteAllLeft.js +script 2323 4f2e1930f650aff4cea4aaafedc75a025ede8596912f152fc24b809acbbf95ba scripts/deleteAllRight.js +script 1409 c2aac34be61e371058bb3cc68f280b370b5adf7e59d0cb8b619a00fe4350ffdc scripts/deleteAllSwatches.js +script 1380 4b9f08ef0f9fe586a2193ca79fb39bcc7f505f0894d4c3f96d823f52a669a8c5 scripts/deleteHiddenLayers.js +script 1310 ceb4c95f1fa7137a91bba65d91d4afd99b9f64e53d304b0306b33843d8cc2e1e scripts/deleteLockedLayers.js +script 2070 ed4da13755dc9def79bf21ef07e216e720d5da0e68a6225d7864f1d1c73b9f1d scripts/deleteTrailingSpaces.js +script 2042 ee6524a56cd040cca404c8ab47a6cfeb83b4b786777c49168f3c9b474fdd0e9c scripts/deleteUnusedLayers.js +script 3032 23f34e9ecab741186ffbb5dc8709cdc0c5c7adbc06684a22e24833e1f6561053 scripts/deleteWord.js +script 4209 e610e4ad0125948c0b57039f83c89441a73b3baf2bbb232e61eff0292a411844 scripts/disjoinPath.js +script 4242 aec068b4f7c228aa8b5108f82580b366184b172730a38668636a9afd9dbcdf5e scripts/distributeInSpace(Horizontal).js +script 4239 1e3577cd2a15c10cdb8d249935b7065ccf52ac43b9d2932fa93f998797b65be6 scripts/distributeInSpace(Vertical).js +script 4734 55e80180ff5e06f4eb30b2f2f642b2451884c83c1ea5f8d34433182ce993ab46 scripts/drawCircumscribedCircle.js +script 24978 dbbebda1eeb6de5eff305bc97888b350ce01f2c22f53602cc07895a67b801fa8 scripts/drawNormalLine.js +script 12492 bf685ff554477d8c14173f984f9419be0405168b30eb815a0da5ec9ca43a6424 scripts/drawRectangle.js +script 12601 34684d3cc3371347e7e90b5dedb4b6c431adbe5d1bc5f7f8bffef7b6d076355f scripts/drawS-curve.js +script 17354 3ee04d2c5e1c6a702892848a52a5df07ba18e54b22f0c2d90ae7097eb697e96f scripts/drawShapeOnAnchorPoint.js +script 18851 7afef90a2f8d4369790464f38e6d3d78eff63077d60e349a249e355a533ece5b scripts/drawShapeParallelToPathSegment.js +script 3046 eba415ec6dd3972266a4b0a9247ce47c8323f80198c66c1960a9a4706b31e3e5 scripts/encloseWordInParentheses.js +script 31445 44bfd6ca2d35bb02c72381e33457973e5c885ff2d8fa04d693600a16394b7788 scripts/exportAsPDF.js +script 4841 6ce9cf7edadbc1b81d85199913028d2e69ccd3d2753eaabdc891a6cbdd7c6c9a scripts/exportColorValuesToCSV.js +script 23658 e4ac0796977ef9ea5900c82ce4e4b49e6e0a0dbdd8153eddc7b4e77d9fba5922 scripts/extendHandle.js +script 10589 743e6a25f628640348cb217dd61e2a4fe4a6b417249c1aa5a27279acf6800fa8 scripts/extendLine.js +script 4057 91cda5d45cb1685212eea6987f4bd454e3e51622ff0a5a902af590c640e8ee45 scripts/extractColorsFromGradient.js +script 4839 0107f4eb43a90a6e8f4486414460fb3a1a122eafcc36917c34b64c802c8912c6 scripts/fitGuideInArtboard.js +script 3821 668d68ddc6443aef3e520912eb4e350564c2f1e6e1521748e22c249f3b27c95c scripts/fitSelectedObjectsInWindow.js +script 4464 34e19da16a5120a7a38e4ac56d670ea7077aa53ac03d02248b36c65789c0f842 scripts/generateGradientColor.js +script 7625 893a8fea1d434695cd285f07db352165030cd1d20fe10bfc64c441d954535ee8 scripts/goToLine.js +script 3990 6bad84226ecf2bb09670816b475ac639d2585ffc8322f6f03f92559a7e34e17d scripts/goToNextText.js +script 4050 295646556a94d74cd12208c95099ac2872d2ffadf0af45ddb7216cbd8b922ae1 scripts/goToPreviousText.js +script 17195 7d0738082b1c7b849b80058a9987391719e5378e0c92cf9d3d17f0ce667c5f87 scripts/highlightWord.js +script 5801 d41e19dca0fde9d48d5a79c92af61d6f780e39631e47d8addee0cadf868d6352 scripts/importCSVtoSwatch.js +script 5467 210930998e475721fcb5194d27735197cfd2238311122938057deb1376ab2348 scripts/increaseSelectedAnchorPointsCCW.js +script 5458 4a4d415581356ba12107a0371fe14071fab3b73320788f0f4b453e7b325cf04b scripts/increaseSelectedAnchorPointsCW.js +script 1795 5e359c3fdc7cc76ca4a6e567e1c14bf7d970ab1186a2c3247a5699c49ec5f077 scripts/insertLineAbove.js +script 1851 e29e6e0b00c2046d5d9043a4439847f10e3f5e83faa64b2d55a6f32879bcbb9c scripts/insertLineBelow.js +script 1221 019e26ffb9d7a80528c4357687fe876312bb8c2b646196099e338d81a77b58ae scripts/invertLockedLayer.js +script 1225 f2168ed70f5b40600b3ac76ced74bcea56276657fbec4c392e881223cbe4dd03 scripts/invertVisibleLayer.js +script 7504 a76d55bafbaf7361c880e549f24f0fd9ff25da7584b35879f210777b3a64f779 scripts/justifyContentSpaceBetween.js +script 10012 9d95240d36bd34484484e3e90f68bcee910569db2caad3ce705446a21330bd39 scripts/makeCircularGuides.js +script 8713 c715f39a85d14d875fb97ac140fa0afa90de90b00b5702e4375a433fc08683a5 scripts/makeCrosshairGuides.js +script 4349 a8aff48b167b4019e2a8a7e0a824363b2a918d4abe6109b02486f4abdfcf5372 scripts/markMissingLink.js +script 5269 5a34e26827a8df6bdde535ce2988a24264e0d4867d9d96623bdc3f0623f4631d scripts/matchLocationOfGradientStop.js +script 23906 d7259bf6fd8af0524cfa8e2c548c8cf207fb50e3332a47533502414689d4ef31 scripts/matchSelectedObjectScales.js +script 27049 85b5ad98fdd1d10b67ecc6e9a3bc20af56da9590d9d29249df4d52920dd16831 scripts/measureDistance.js +script 6921 d068dfa9ad1295ed4c660741d4fba88f20b52158484fd9d05f5cd0d0ed3ce774 scripts/moveGuides.js +script 2407 b9f7cd9a702c44cc42292e08a288cee09053901d8083c3de9ccfc4373ce7f9a3 scripts/moveLineDown.js +script 2930 2c85b53de847282c382e3944ce9cb1eeda9b43088050a6f6cc0b684c60f70438 scripts/moveLineUp.js +script 1756 a956eb04dda2b79d1ab36767624c03f07322b3f9fb6f0ad105b3b4f44482f560 scripts/moveSublayerToMainLayer.js +script 2089 b0fc23dd3f8c23c7597d4ecd6af84350301e187d9fdf309d43a20becbf78423a scripts/navigateToFirstArtboard.js +script 2103 082f15d4b992d644938ad475a194784a214a559af5a7f9a2c750e0c253f5eb92 scripts/navigateToLastArtboard.js +script 2196 c97a9d9e92ac403669570ed9044c1f00f450f66d847561fa9a87ce2327899ab4 scripts/navigateToNextArtboard.js +script 2212 b9f45e4e2af01dd3ec5912354bfc57fb8dfc2f308a56ca91fd204d26532acbab scripts/navigateToPreviousArtboard.js +script 16281 29ff5860cf6a21043c0966212cde64936f968234f61e4c1bfaa95003401891eb scripts/randomTextColor.js +script 412907 21de4e84b2489125174cc70a4cbd9ca1644d95ed84d4eaa76362cdc3442cbf99 scripts/rearrangeObjects.js +script 7746 80d5ef18b7123d35234ec1d305abc24916931e88dd8eaff50c2f07faad8265e2 scripts/relinkFileExtension.js +script 26317 00a73c639a08ece07fa70bf28638ed98b78e9b560eeea735d9878c9c285ebf5a scripts/relinkFileExtensionExtra.js +script 4832 2041c0dd0d035305ea8d5530367daf3959e1caec1b27fb580afa69addbb0bab9 scripts/relinkToFolder.js +script 3359 6babb89a7f7a631078e1e071e812dc6018dbca73dbc03aa569f9a7ede3d8f2f6 scripts/removeColorInGuideObject.js +script 21675 1cc55d2e529d0729a4bf7c144ac3fa3aead07c20771b4ceed0929323a24f63ca scripts/renameArtboard.js +script 21678 9757266dd6d38f681f08807012f460fc76f455d1242b795f3db286b5aa14ff76 scripts/renameLayer.js +script 16128 619991ae586b8677dd3b60e83678138ccd9663f5ba3b45ec667d1ff95a1d585f scripts/renameLinkedFile.js +script 3431 0d56e5c9932f6f29e97ebbdce2e7ce128e02109d696a2c7a24e001e43df00b13 scripts/resetToFullScale.js +script 5642 c56761ebd486fe981c16c1f61fdb7f225915b51e89d57578a5fb1b3534a7dca5 scripts/rotateTextToMatchPathSegmentAngle.js +script 3035 76c72c89e8cb33c965d0690c64bcb8b1f9969daf305f1627e5b4b08a934f982d scripts/roundColorValue.js +script 2686 3041bb126d340d2a5cdc35320a0b6215d0ab82f7db4c20ba15200d74e4f035da scripts/roundLocationOfGradientStop.js +script 1436 1d4567613cfc2167c8cab6f6efdc6bb404b6b6889b5c4500d906562345d94ede scripts/selectGuides.js +script 6616 9c790c2ef4951a7e8badb0c0af0c886575f4455dde0fff15d23d3ee2021f4f5f scripts/selectLink.js +script 281018 e3be8d657b99ef5c7a43808e35d6aa21d04a34ed9f5418e4cfd6c8535da894b4 scripts/shiftObjects.js +script 5462 8fc0be1e776724766c50453ee8ab853d0f26b144d1c2aa546927fa75dd2c6776 scripts/shiftSelectedAnchorPointsCCW.js +script 5453 130ac2b786198d56e1b75329f291fba49a3bb0ff097e4cd0f9eac26ebb5c2bbd scripts/shiftSelectedAnchorPointsCW.js +script 5053 e84ad1d0a42d9eff5b9901b9a200845638659aff73398edc609e1b25efe5ab6f scripts/showArtboardName.js +script 4866 320fad9559943c7c45bae558be7941903046079b541ebe920dffdf0594cb6ec7 scripts/showColorValues.js +script 11810 6155fcbe6d87886d3bc2a39fd70fd63a9fd06d18d9435321f426afa44f3518c4 scripts/showDimensions.js +script 2786 70119dbd78a262a7672788ebb3e25d8dad937590546033412ec212ef57582b09 scripts/shuffleGradientColor.js +script 2818 09b0d3bfcc4d73ca00a9ad8a83ae72b22da99c27dafb6d583a8cdf52f2896086 scripts/shuffleObjects.js +script 3087 8711d80957dbdf149f812001ded8676d3d2ab0933eec7b4a4a3e557bf8f6314c scripts/sortArtboards.js +script 12507 783f87be99ef29c7b9ba767f654230910b72716100da0322206b2e52f809d5df scripts/sortLines.js +script 14120 187596237ee1a5e6970e36554ecce8802ad8a598339d6afcf25b82309c883af9 scripts/splitText.js +script 5446 4c1b3e21c774cf4b9e76b6b6e17ade2c1745b5ba3c93ccd47fab7a5ad54955bc scripts/splitTextAtCursorPosition.js +script 16055 bc4f79f01de270b1d89b7934e7b218b07ddfdcba745261c7277631b8b0ed8ddd scripts/stepAndRepeat.js +script 5724 5a189347fffcfba864806f7eb0b4bce3514ec52bf19422e012b85fd37a33aed1 scripts/sumNumbers.js +script 1532 4d44d27ad0fa1441c1f882e90b52a61fec007f0442433c287b8d9dd53e93f4e8 scripts/swapTextContents.js +script 1750 2ac2fad9d5130c42c8e60505fc1a6eea9a2b9f40ac42dc14208253efff43a826 scripts/textAlign_Center.js +script 2016 a1e8a216f79897ec70fc1bc53c9bf3172e6a74bfca3227cc0fc3215bb31c620d scripts/textAlign_Left.js +script 1748 d8f15ae33e692fc8f7387de430f4fa90dbf4d502bb620e9c50466934fc3338c4 scripts/textAlign_Right.js +script 2904 ae6649933c593f483af86e93f79e33fa435bf1a9bb8e3a6558fcd5c02547c192 scripts/toggleShowHandles.js +script 1744 7f6baddcfd67181c185c3fc54fa004cda4ed9c9669564fc0d1781e34c8d5bd64 scripts/unifyLayerColors.js +script 21805 e16cba4c513aa15b62648d4810078d68bb99d799b03ce915dac3857bdc09d4fa scripts/unitCalculator.js +source joshbduncan/illustrator-scripts 1bf271e19b6efb8e3cf181f73ba56e918407e09f MIT +license 1077 602702bb20b4f3bd1f6ddcdf04f3dcdf33091456ad6597e4f8a8e4c680cb79ed LICENSE +script 2989 238eb4574c9c707944fc0da5a38cf7d58cfd607809442bd69420c92e4e9dc5ee jsx/ArtboardFloodFill.jsx +script 4100 dc2ffb948d251e9ada5033ff28b25f38b1cacf648d09b3a115e1da2f33d34951 jsx/ArtboardRectGuides.jsx +script 2851 47a1dd8d204ae5e498060b6c36533341e33c26cf45bdce5b6eda4795e309d046 jsx/ArtboardToAi.jsx +script 2645 ba2dca2636280bd0ecd28c1f81765da8491a1d0c08bdfe744648d1acf139fce6 jsx/ArtboardToPDF.jsx +script 2581 be41cceb3bd674223ce4556e5536263ee99a2289a8b0e1813c9a0dd416bcc464 jsx/ArtboardsToAi.jsx +script 2449 fb77bf2b296792b6537dd9d273f22f8fc156617c1fdef126042c1b6976137d5a jsx/ArtboardsToPDF.jsx +script 8992 15e95745723dd9e443ddd9a4ca87398a08b2790cc5aee0723a2f2f4a34aaeec6 jsx/ColorRandomly.jsx +script 5003 7ec5349aa061100f6623d4104521d180df78346b15d3eb22ad4dca65e2db82d8 jsx/ComplementaryColorTrio.jsx +script 1583 d1ab728aaeef17d2619c4b8b9b386c5c081b4c90c0c1f5e16343059462bf01be jsx/ConsecutiveNumbers.jsx +script 2833 da3abe575de483d33632cdc1353fa9ee3c7b124981a97908bbd0ccbada41bec5 jsx/EditPointsOnly.jsx +script 3669 5e8d2ae44a12befa1e91424ef751c1f6b9e818468e76a49e6bb9bc78db7fb250 jsx/EllipseStepsBetween.jsx +script 7940 0b62aa79fd6a5764b0bda74b7fa24659ff90175a0e9d9c2eab17beca59929044 jsx/ExportPrintCutPDFs.jsx +script 4834 1de2220f08c7a0cac2b9830368f86e2bbd5e9b9350fd5f61c1fda67cf5e44272 jsx/FontVisualizer.jsx +script 24426 438741e829f1e2001006ad4ba0efda6c760f10f85a3ed142df864f5b7321e2f3 jsx/MatchObjects.jsx +script 13324 e84fa981ebc096b1769fd5c3b170029fa875a8cd07fae59f3307f93511d10e74 jsx/OffsetObjects.jsx +script 1606 61a8564424882d07be79aea81a68a78a3d47f2ad772597abb28e9e7e6079a70b jsx/ReleaseAllContainers.jsx +script 2151 4093bd321fe39aaa79d4ab5dd2bd6521b36b5e990116d23c401f529fa4d4a61a jsx/RemoveBezierHandles.jsx +script 4962 d017ddf2371c8a108d0fbbd25d873a2f5610a7b510e08925b5e628ddfd899eda jsx/RenameLayers.jsx +script 54874 e927affa49420b8bd50eb7717469f32362b9f383fb7df5b6a0cf52e8289e4c8c jsx/RepeatAfterMe.jsx +script 37020 b4fa9f8efa9265e15013daadbf266e468a40b53fa71143b40c01cb7039082d1d jsx/ScreenSepMarks.jsx +script 6233 6c53363723cc0b1254eadf4293f9b642854afde3562801a47bb71c0e2a4e0f17 jsx/SelectObjectsByName.jsx +script 5080 9b8fcf550eff80fbc577738f99ba22d3d6ea1819251bd763f116f7841158f63b jsx/ShowHideLayers.jsx +script 723 3ff6f1ad312b6a0ead65d082d4e86ce453897f9ee2c4b1a58c3f4e8df722114b snippets/AddGuideCrosshair.jsx +script 18804 c5d55cdfb73edcd62a8c7852a926fc4966bbebf7175de7e5cdc873c0562884ff snippets/AddPointsToAPathExample.jsx +script 1052 39c251907cd7ac3e00f58dc7089a3a0d49ad2d7dbdb2fde3151cab8554d1ea0f snippets/AltCalcPoints.jsx +script 841 a1402fabf870e58a5dc85cee7307eb1fb0f8c048a9daf67d4318208c68612309 snippets/CollectAllLayers.jsx +script 315 a89b9bd83ac08b5150bfd633019d555f2a0cf7edd8b85fdc6818e0deb43cc504 snippets/ColorPickerDialogExample.jsx +script 1491 f56049ce85aa1a33649a741bf701a41128c8ebdc01cd9303612dcfe584b2c2b2 snippets/ColorWithSpotIfExistsElseMake.jsx +script 1067 07da56557bf58b34bb7c33f62c0390a78eb7a1f9a90da13392e33cc1e143f654 snippets/CompareLayerToLayers.jsx +script 824 5b4866b264f86ac578e1c2d67f076e7cb4cc40b4170398e559ea3622e51989c6 snippets/CompoundPathPlay.jsx +script 2327 fd22eb189f1891af260310cc849a605af793ec2e45e73e7f166fb4fdce91f3f2 snippets/DiePathDimensions.jsx +script 3245 ab7ac7deecda0da164535f370664ae066b2aa7ab34893cd684738082637d0204 snippets/DrawCrossMarkAtHorizontalLineSegments.jsx +script 2667 db27d8a3065d2ecf97756847e38b35057a869e82ca6c8f160c0dc00da79fcc8c snippets/DrawScannableDatamatrixBarcode.jsx +script 1553 ff1dbfd44e367d2ab161abd6c95b98cffeed69df5cbca9832f47262372038c7e snippets/ExportActiveArtboardAsJPEG.jsx +script 2667 1df7fc1a5211f8163deebcf650af0d689c1659cf2e82f4dd7cb283d2859a5729 snippets/ExportArtboardAsJPEGWithoutArtboardName.jsx +script 1525 562a34c699c78d560847e6e8da2b6219b13386dee2f9c358b04af8dc1d77e32b snippets/ExportArtboardJPEGSWithNameOnly.jsx +script 1671 bf1ed56b6e41809796cbdcd3380e047622170bd84f300423d6b08a15f76ef4b5 snippets/ExportArtboardSetsToPDF.jsx +script 2075 e280f25bf5bb62c619791987b5901ca939c99ec53ac0dbc71b39715482669a9d snippets/ExportArtboardWithNameOnly.jsx +script 2066 87c735eff677cc943118ed3526cceb029ade5e4e7ad13e7df655ea3501e41b04 snippets/ExportArtboardsToPDFandJPEG.jsx +script 2081 59c7060bf8bb681b913911a256df83adc5e8e5dbf4a0f1a2d8f634103e942e10 snippets/GapOffset.jsx +script 1400 b626c5e147949f89a22e09c1654be8eb1b1de35723dee3bd0fc147e0ab478441 snippets/GetVisibleItemsFromArtboards.jsx +script 4697 a39e9c2c60f3151949beaa94fb0c7c6d8c60d5809d70ec198631110ccb6103cd snippets/GroupLayersOfSameName.jsx +script 4324 6527d5d7a64a80ae7402b82c98ad9a3f73d925a58dbec3677565339ac039395a snippets/GroupObjectsThenGapOffset.jsx +script 2663 dabba873fcc6fae25e394fbc3d7236221c4af22afa0c3a1d7eed65cae9f56af8 snippets/MarkCircleCentersWithCrosshair.jsx +script 6779 02ada6f11c94a2978b38fea9fd7e8c6b2d591a2e0501a1be2511282c291bb5e0 snippets/MatchTopObjectToBottom.jsx +script 1974 860e5087db24c885287281be392b45809fddbbb9a17d9bb8797ab45437dd4d52 snippets/MoveItemsWithDimensionColorToNewLayer.jsx +script 2358 7f3c60bcf5d5bd20555d3193b1f90567bcf659bcb1b439e550edd956ea0c3a5d snippets/RGBSwatchGroupFromCSV.jsx +script 736 6b1cbcb1e864a9e5ebebb388cce9c9b5807f0295b11e752fe1e2c135d8c919c9 snippets/RecursivelyRenameLayers.jsx +script 672 6cc601fba406278bc6e22239766f7e00a1966125f7728a9fbe9ce88b64a82066 snippets/RenameArtboards.jsx +script 924 a5d7f62e6ef92bd84f2b26024a31557d2580dc75a34d91e5c5ba792b1fda916c snippets/ReplaceWordMatchStyle.jsx +script 3258 6476b9a5e7eb8ab03f996bd85711fbe0903a04173ec5cbacbbc1199d5e36def0 snippets/ScriptUtils.jsx +script 3359 a15ffb58bd5fc62947ca8090697878f5fe97178c9314ce903d14627b73bade28 snippets/SearchableDocumentSymbolsDialog.jsx +script 373 8afb6d04fc77d7084339ef47be8c1ab8dfd98a3fbcb02808e2e2ced38d996f66 snippets/StrokeTextRange.jsx +script 1872 55e3f870d54f10647dca846cfd3b038efd443cf720cdff5346a4fcad9a9b1f72 snippets/UngroupUnclipUncompoundAlt.jsx +script 4142 138c776d1a2dfcec1392ce47828c6872dce8af9efbe961201b71c69af9c3c09b snippets/scale_apply.jsx +script 3285 828b0e40e2772d0516952b348d391f1b8f69a3cb2faeb3eaf523d0f5fcc1944f snippets/scale_get.jsx +script 6437 5b76377fa1affbeb5ee1503c03decb025dfe8b53f29d88ee1f6fac617303c1e0 utils/DrawVisibleBounds.jsx +script 4511 8316b18f4ad5e2e8ba68eebb9b5adcbcbbe08a32d6732dc031da3461d1fe6fa8 utils/GetSelectionBounds.jsx +script 3316 5d4e689ba9dce9f4cdb07382e4ed44d92af442d0f0360e9590b3f3c75585adfa utils/GetVisibleBounds.jsx +script 1434 bfc476237c11b47b88fef9c944f04b35afecb79768d4331a02a00e39a419e009 utils/GroupObjectsByRow.jsx +script 1016 fcb5519528f96562bff465fadffbf9373d5746bd65528f43d46b882793afa94f utils/WriteTextToDoc.jsx +source mericson/illustrator-scripts f493f6ad23032e99b48c592549378e4e79275d07 MIT +license 1063 3b346cf5044dba9b132575751749a47f5a78dd79d11d49ac59c09d1e66cbf30f LICENSE +script 11077 a3873dcf4c9d4cc5b7d36d1613855b6c7403b00f28b6725060fea6b5696a494e Preflight.jsx +source bronzehedwick/Adobe-Export-Scripts 28027a831974f95c482f297f63119ce6430d743a MIT +license 1085 244cf82b347521f0685541734d8815cbdb71a970d4d55b61e721563af19982bf LICENSE.txt +script 2627 43858d158da5adc1d03e6e575e9e99990bdf45a3e9004d8e2b7ca0fa8b9e3ff0 Illustrator/Export Layout Folder.jsx +script 22791 604eda43804f0dad7d4d65df01dac94ed6653a6a18cd790b52655911b4f7961b Illustrator/Export Layout.jsx +source Pixeden/illustrator-scripts 25dca41ef482d321ece6a9f8630d406da0be32b4 MIT +license 1064 e3e8d472f2e0c94bb891d9ef3d4588fc0f4de88c1d1f0aba24a722c51ffb17d5 LICENSE +script 1251 be92c74810208607b6b0a6c352bae183b82d80643ecc7b2c3e057516a3807fce center-in-artboard.js +script 2053 505d0ba303d9622c177094073359630dc9568e9ed4382d93c371da6b25b81c6f export-png.js +script 1721 80e109de87a9d9cc4469a073f7d489e9732ceb385c431afeb68475ae8656fc86 is-unified.js +script 4107 c5d2f8a690227c62708caebfda7360e0531d706ff264548c686cac62b7b267be name-basic-layers.js +script 4048 33ed153eb337a86fb4f058416c5e24c6aaab786d92b7592fac6f1aa14c892bd7 name-color-layers.js +script 732 d6cb0da4f1b127959e76b138a0fff4f328806bc048dcb73fdcdfd90ae23a7ad2 rename-artboards.js +script 2143 eae36f5abe12c5f61b91af15ce775fcc9ea63750985cefaa175adc9cbeb33ca6 to-print.js +script 1098 503c81734644151d917830027cc7f4561d795172085ed8b320c2e738e0ed9db4 ungroup.js +script 1689 840ae05a5ab19ddc8cda693de27dd84276939e118fb41c08a68de33af640fc55 unifyColor.js +source fraxen/illustratorscripts 7e5875e66fab920faba37530061c75e248231aea Apache-2.0 +license 11323 6dc0e068dcf3a5bc8e054205b85b7720e1d49265bbc64bf515d2cf79197df69a LICENSE +script 2498 469420c07d8a4492d048353d900586f7a3870cc3bb6e6956446fe78e8d6ba797 cleanArcMapExport.jsx +script 1168 5b96de4cfa5033cbb1cc7b9946e1fdfe5350184e1f5a86479f36279b95abec64 clean_smaller.jsx +script 1973 3fc0117296811c6daa09993558d0203b6d6641df354b4ecc805a8709538cc5c6 convertText.jsx +script 17489 e6beb70674b588b401f3b8526cb34066b199c6202d9f180377b5c80ba21ed77b finalsave.jsx +script 1469 e3c5d3437cfeba7be509cf12d2a751165db2d6abb193229c525f5d6ad7303773 finalsave_dir.jsx +script 9036 b5482c73ed639583883f322136cd1942d1bc4668a35cdb31cf407be01539e29a findAndReplaceGraphic_transformToFit_height_color.jsx +script 2003 25f9524880d8657247afcb429f9052f22be8eaa910f7ecb4533fdc1ea81f49ff pasteSize.jsx +script 3624 bd1c1aa943c1052b0ffdc96be9da7943939bf9b1735c333c277c438108271b6a raise.jsx +script 853 7835e98454235fa4101877e134e5cd88eaf8e232c724888796305415cee01eb0 sortText.jsx +script 474 04dc52a648632a27f429d2ba7868cb5fe347fbeb49c944b4ed2ac54df0587039 tileCrop.jsx +source iconifyit/illustrator-jsx-demos 8e42fdea94cd1b737589cd27bbe2f195c0981779 MIT +license 1068 65c5a756100fecd6e69c7fcb0c392357915b7a12346d41ad51730befd5abbc9b LICENSE +script 5101 6d35ad02d075b192bb823c6592f754438a386a1720966768eb2a61a974dfe743 My Module.jsx +script 3113 447e9f3aacd43f172aff8f3e63d52ffe196103244e29f8b64248a0ad5aee2bf2 Progress Bar Demo.jsx +script 18818 420987f5b8c4cd23ae4e3c55ce504b69c9a2598e57c1fd99fb5f2bcc50606b42 inc/Utils.jsx +source shspage/illustrator-circlepacking 340953573bb8254264e37edfb93950b557289b8e MIT +license 1079 9e68a2f0e729c67282f750dca46c0be009d567058c99f5ab89c7b1cccfe65ce9 LICENSE.txt +script 26602 97d53120ff88a0c0c18af1ccb2d86c51277e758baa1d5a8efe04b5538f0b9955 circlepacking.jsx +script 30087 b5f14819cc06ff3ac00b508b1bed9cab51d215d2ab9332ea4374d23524e9515e variations/circlepacking_in_a_circle.jsx +source Creatide/AI_Group-By-Distance 7b8daba456fcb76836d25c837c550b51528f405b MIT +license 1075 7595a182405f54f904a14e8bbae1ac26c14c7356b79949323b4d4533453b3990 LICENSE +script 13528 a649144ad934e806918364248dfe5669c7b963cc92c50d15c9f13f340a9c2c25 AI_GroupByDistance.jsx +source mike-brady/Adobe-Illustrator-Scripts 9821eba21d90c941f486b9f0cd5c8f848c37db35 MIT +license 1067 53eed8118a589d6b751415643e1eafda291b0d4e47a56f7b01feb8d8fdcba1ae LICENSE +script 8235 dc4a0fa63d5c30f591a089ab01013a1b8916999bb9b655f07c19673c394a4fe0 Auto-Mirror-Bleed/src/AutoMirrorBleed.jsx +script 1604 a33b14c6f4943c808dd0dd95da40bdb0629392ce4b05413521410c4a8e6fb2b7 Save-PDFs/src/SavePDFs.jsx +script 2279 a8bf20eeb36efdf77e7dc5611677c1f11e449d44350e8bf3e6c8a5c141f44c49 Select-Small-Paths/SelectSmallPaths.jsx +source vabushkevich/ai-scripting-utils 49fe6311eb6f984384f61e76aaf5d55dbd46a101 MIT +license 1100 7aa3a31f01a622d02cb715f5729c2170d968c70ede5e7862dc6debb785b24e88 LICENSE +script 80176 6db28d2b9236d421be53f1936e4988fe3900eeb7a2ebfa788a585e3b60c03af7 ai-scripting-utils.jsx +source newsdev/ai2html c73437878fcd6b8f2335ea2edf3b5e21ab757513 Apache-2.0 +license 582 261ee9e17e53a84de8199e783f6c03cbec5225eb6f91c2528c3c05dbc597e90c LICENSE.md +script 132608 de8c2a2b58b16fdffd8cadca802520e690ceef820e81b82a3738bdd0f350d7d8 ai2html-legacy.js +script 163830 ebc61242d739d85b5252dcb471d57e87a0c7a37408714a283a36ece1ce64fe92 ai2html.js +script 2490 18270e820c7251ba55152240a861a054fc87c34b3aae4339ee131fb678cdc2b1 utilities/aifontname.js +source ten-A/Extend_Script_experimentals 93a5f127c3b77ecae887454f0fdfb34dc173c79d MIT +license 1072 6c98c1175f05551f3c22b29e8a2b38cf2e3c8c5352acba3d31ce08cee8f9b561 License.md +script 12289 aeb2e8c940b86d63fcc54356b8e9cdf71897a4833e55488f7f620ab0e0605b45 RegExpSample.jsx +script 5187 b89fe67ebd02fc0e63ca1e7bdab9e99669ddde59abb4bbf5127eb92d8b634ad0 aiRotater.jsx +script 106 a3e03929eea0a08b01adced93f6dc24221671bf6035c42c073726998c6501807 alert_supression.jsx +script 5467 e01f40661d1b6dfad4e32664e07df48a504447610c4d918f427b3f20abd980a8 apollonianGasket.jsx +script 973 f4d2f657e3b3abdd02b296297f3813a7d00e527a5e69aba065777da8b2c65922 circumscribedCircle.jsx +script 490 2de157ae7781a7df872f1a710771c56f4ba0e268dde78af7ac979bb3d29231da getColorValue.jsx +script 801 0d0394a1893b9d3692dc38104f2309079cb5da3004a11854cddaf4821608f4f9 getHSBValue.jsx +script 4229 165f8d3d93fc8525b2d57651f95805a8f692b24d9300d11b14afa36c7de00da8 group_ruby.jsx +script 3189 aff91cc629eeb3e7cf3dec85d56caae9476aa5edfded035a30282ee225956343 halftoneScreenConverter.jsx +script 2329 0dba02500213c66d94cef68325b72716677e3c11c580b88887e3cc9a7f963b4f hilightUserCondition.jsx +script 869 c180ade6f7bff735a857df9f5006b49f256d3e50c2d061cd43cbd7d3ae6eb4b2 layersAutoLock.jsx +script 904 b9c362f4ea06385eb5ed4037c08f350c14b663577ed43b24513db6317fb6e9ae mouseWatcher.jsx +script 1715 02e4cb4151bb61e49920e9ba208ac7e8388ad84cc63d6a073748b926cb6efeb2 pdfPlacer_singlepage.jsx +script 4278 ca5751afeac161d001abde4b3a3c2821b80d768406c47211e4f2a8a57effbe18 photomosaic.jsx +script 1949 5d7e99c4ca0c83f9cbbd8b32d3a729646eca2b9c736f3311d20cf3961f26e629 placedImageMarker.jsx +script 965 82cff0118cfb970ea6e7450ae44a2658373c066de7fcc7f2db6c1157d8262865 rectToLine.jsx +script 3228 c89c953cf991c2e7f3ee90fe3892c632897fbc9d72fe07417049fb551e6a3b9e screenCNV.jsx +script 2925 dcc49f567a88e671b764279fe3a4bfd1f8613726eeeecc01bf6f564ead3ebd1c textTools.jsx +source sebmarkbage/art-illustrator b4fc3d7f04e9f196ab7046e54c6eb7d31a8ad7f0 MIT +license 1117 13059bc9ed47c50634297fac9d000b1700947ddd04a9f0f970b371a8d9f90080 license.txt +include 8554 94c6a716bd3b1b7e1bc9823af2cdde8457aade08628d3ad0be21b8b1781f1094 Source/Illustrator.ART.jsxinc +script 1474 ce37fc74e460384be87539ad0670e61b2be8c2171ad31199720032b3ced14d86 Source/Save As ART Script.jsx +source MPieter/iOS-images-export-script-illustrator ffab26c053d6457e8afdc6b813bb166baecdf5a4 MIT +license 1073 07eed876c2321a2587d5f1b69081c6b26ac6a6f492ccda23a5c27b56a59a126d LICENSE +script 12031 8182a15eb03a214e390253e580abe3ca3fb78f878e1abd67d349ed861e231714 export_assets_for_iOS.jsx diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 3c2a94c14d..ab2e2cc6c9 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -12,6 +12,7 @@ mod ico; mod layers; mod pdf_deps; mod pngsuite; +mod script_corpus; mod sha256; mod shards; mod stats; @@ -43,12 +44,17 @@ commands: ci warm build what every shard builds, without running it (fills the gate's cache) shards list the crates each shard tests; fails when a member is in no shard or in two, or builds with other features in its shard than in the whole workspace - corpus [--download] [--affinity] + corpus [--download | --affinity | --scripts] show where test corpora live; --download fetches PngSuite into corpus/pngsuite, - --affinity the pinned public Affinity documents into corpus/affinity + --affinity the pinned public Affinity documents into corpus/affinity, --scripts + the pinned public scripts of xtask/script-corpus.txt into corpus/scripts bundle build dist/VectorCraft.app (macOS) with assets/app-icon/vectorcraft.icns ico ... pack PNGs into a Windows .ico (used by packaging/icons.sh) + scripts --pass-rate [--report ] + run each script in corpus/scripts headless in a process of its own and report how + many pass, as JSON (default target/script-corpus/report-